mirror of
https://github.com/opelly27/Stockfish.git
synced 2026-05-20 14:27:45 +00:00
Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 48cfdfcc46 | |||
| fa7b244dc9 | |||
| 29ad6a73fc | |||
| ac48b16708 | |||
| 38b1c4b6b8 | |||
| 162dbeaee8 | |||
| 85146ca0a9 | |||
| 02e12a69a7 | |||
| 6e8116e38f | |||
| 29f7fab2a9 | |||
| 2af986bf31 | |||
| b67146b100 | |||
| c1b1a94d81 | |||
| 17212e5fcc | |||
| 46921dff27 | |||
| 941016e7a2 | |||
| 290caf9960 | |||
| 43fa3a4d64 | |||
| 64b4836d12 | |||
| 5df7d62eb9 | |||
| 82179c70dc | |||
| de17652e47 | |||
| 647b79b556 |
@@ -1,44 +0,0 @@
|
|||||||
AccessModifierOffset: -1
|
|
||||||
AlignAfterOpenBracket: Align
|
|
||||||
AlignConsecutiveAssignments: Consecutive
|
|
||||||
AlignConsecutiveDeclarations: Consecutive
|
|
||||||
AlignEscapedNewlines: DontAlign
|
|
||||||
AlignOperands: AlignAfterOperator
|
|
||||||
AlignTrailingComments: true
|
|
||||||
AllowAllParametersOfDeclarationOnNextLine: true
|
|
||||||
AllowShortCaseLabelsOnASingleLine: false
|
|
||||||
AllowShortEnumsOnASingleLine: false
|
|
||||||
AllowShortIfStatementsOnASingleLine: false
|
|
||||||
AlwaysBreakTemplateDeclarations: Yes
|
|
||||||
BasedOnStyle: WebKit
|
|
||||||
BitFieldColonSpacing: After
|
|
||||||
BinPackParameters: false
|
|
||||||
BreakBeforeBinaryOperators: NonAssignment
|
|
||||||
BreakBeforeBraces: Custom
|
|
||||||
BraceWrapping:
|
|
||||||
AfterFunction: false
|
|
||||||
AfterClass: false
|
|
||||||
AfterControlStatement: true
|
|
||||||
BeforeElse: true
|
|
||||||
BreakBeforeTernaryOperators: true
|
|
||||||
BreakConstructorInitializers: AfterColon
|
|
||||||
BreakStringLiterals: false
|
|
||||||
ColumnLimit: 100
|
|
||||||
ContinuationIndentWidth: 2
|
|
||||||
Cpp11BracedListStyle: true
|
|
||||||
IndentGotoLabels: false
|
|
||||||
IndentPPDirectives: BeforeHash
|
|
||||||
IndentWidth: 4
|
|
||||||
MaxEmptyLinesToKeep: 2
|
|
||||||
NamespaceIndentation: None
|
|
||||||
PackConstructorInitializers: Never
|
|
||||||
ReflowComments: false
|
|
||||||
SortIncludes: false
|
|
||||||
SortUsingDeclarations: false
|
|
||||||
SpaceAfterCStyleCast: true
|
|
||||||
SpaceAfterTemplateKeyword: false
|
|
||||||
SpaceBeforeCaseColon: true
|
|
||||||
SpaceBeforeCpp11BracedList: false
|
|
||||||
SpaceBeforeInheritanceColon: false
|
|
||||||
SpaceInEmptyBlock: false
|
|
||||||
SpacesBeforeTrailingComments: 2
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
# .git-blame-ignore-revs
|
|
||||||
# Ignore commit which added clang-format
|
|
||||||
2d0237db3f0e596fb06e3ffbadba84dcc4e018f6
|
|
||||||
|
|
||||||
# Post commit formatting fixes
|
|
||||||
0fca5605fa2e5e7240fde5e1aae50952b2612231
|
|
||||||
08ed4c90db31959521b7ef3186c026edd1e90307
|
|
||||||
@@ -1,65 +0,0 @@
|
|||||||
name: Report issue
|
|
||||||
description: Create a report to help us fix issues with the engine
|
|
||||||
body:
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Describe the issue
|
|
||||||
description: A clear and concise description of what you're experiencing.
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Expected behavior
|
|
||||||
description: A clear and concise description of what you expected to happen.
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Steps to reproduce
|
|
||||||
description: |
|
|
||||||
Steps to reproduce the behavior.
|
|
||||||
You can also use this section to paste the command line output.
|
|
||||||
placeholder: |
|
|
||||||
```
|
|
||||||
position startpos moves g2g4 e7e5 f2f3
|
|
||||||
go mate 1
|
|
||||||
info string NNUE evaluation using nn-6877cd24400e.nnue enabled
|
|
||||||
info depth 1 seldepth 1 multipv 1 score mate 1 nodes 33 nps 11000 tbhits 0 time 3 pv d8h4
|
|
||||||
bestmove d8h4
|
|
||||||
```
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
|
|
||||||
- type: textarea
|
|
||||||
attributes:
|
|
||||||
label: Anything else?
|
|
||||||
description: |
|
|
||||||
Anything that will give us more context about the issue you are encountering.
|
|
||||||
You can also use this section to propose ideas on how to solve the issue.
|
|
||||||
validations:
|
|
||||||
required: false
|
|
||||||
|
|
||||||
- type: dropdown
|
|
||||||
attributes:
|
|
||||||
label: Operating system
|
|
||||||
options:
|
|
||||||
- All
|
|
||||||
- Windows
|
|
||||||
- Linux
|
|
||||||
- MacOS
|
|
||||||
- Android
|
|
||||||
- Other or N/A
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
|
|
||||||
- type: input
|
|
||||||
attributes:
|
|
||||||
label: Stockfish version
|
|
||||||
description: |
|
|
||||||
This can be found by running the engine.
|
|
||||||
You can also use the commit ID.
|
|
||||||
placeholder: Stockfish 15 / e6e324e
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
blank_issues_enabled: false
|
|
||||||
contact_links:
|
|
||||||
- name: Discord server
|
|
||||||
url: https://discord.gg/GWDRS3kU6R
|
|
||||||
about: Feel free to ask for support or have a chat with us on our Discord server!
|
|
||||||
- name: Discussions, Q&A, ideas, show us something...
|
|
||||||
url: https://github.com/official-stockfish/Stockfish/discussions/new
|
|
||||||
about: Do you have an idea for Stockfish? Do you want to show something that you made? Please open a discussion about it!
|
|
||||||
@@ -1,51 +0,0 @@
|
|||||||
{
|
|
||||||
"config": [
|
|
||||||
{
|
|
||||||
"name": "Android NDK aarch64",
|
|
||||||
"os": "ubuntu-22.04",
|
|
||||||
"simple_name": "android",
|
|
||||||
"compiler": "aarch64-linux-android21-clang++",
|
|
||||||
"emu": "qemu-aarch64",
|
|
||||||
"comp": "ndk",
|
|
||||||
"shell": "bash",
|
|
||||||
"archive_ext": "tar"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Android NDK arm",
|
|
||||||
"os": "ubuntu-22.04",
|
|
||||||
"simple_name": "android",
|
|
||||||
"compiler": "armv7a-linux-androideabi21-clang++",
|
|
||||||
"emu": "qemu-arm",
|
|
||||||
"comp": "ndk",
|
|
||||||
"shell": "bash",
|
|
||||||
"archive_ext": "tar"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"binaries": ["armv8-dotprod", "armv8", "armv7", "armv7-neon"],
|
|
||||||
"exclude": [
|
|
||||||
{
|
|
||||||
"binaries": "armv8-dotprod",
|
|
||||||
"config": {
|
|
||||||
"compiler": "armv7a-linux-androideabi21-clang++"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "armv8",
|
|
||||||
"config": {
|
|
||||||
"compiler": "armv7a-linux-androideabi21-clang++"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "armv7",
|
|
||||||
"config": {
|
|
||||||
"compiler": "aarch64-linux-android21-clang++"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "armv7-neon",
|
|
||||||
"config": {
|
|
||||||
"compiler": "aarch64-linux-android21-clang++"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
[
|
|
||||||
# Mappings for libcxx's internal headers
|
|
||||||
{ include: [ "<__fwd/fstream.h>", private, "<iosfwd>", public ] },
|
|
||||||
{ include: [ "<__fwd/ios.h>", private, "<iosfwd>", public ] },
|
|
||||||
{ include: [ "<__fwd/istream.h>", private, "<iosfwd>", public ] },
|
|
||||||
{ include: [ "<__fwd/ostream.h>", private, "<iosfwd>", public ] },
|
|
||||||
{ include: [ "<__fwd/sstream.h>", private, "<iosfwd>", public ] },
|
|
||||||
{ include: [ "<__fwd/streambuf.h>", private, "<iosfwd>", public ] },
|
|
||||||
{ include: [ "<__fwd/string_view.h>", private, "<string_view>", public ] },
|
|
||||||
{ include: [ "<__system_error/errc.h>", private, "<system_error>", public ] },
|
|
||||||
|
|
||||||
# Mappings for includes between public headers
|
|
||||||
{ include: [ "<ios>", public, "<iostream>", public ] },
|
|
||||||
{ include: [ "<streambuf>", public, "<iostream>", public ] },
|
|
||||||
{ include: [ "<istream>", public, "<iostream>", public ] },
|
|
||||||
{ include: [ "<ostream>", public, "<iostream>", public ] },
|
|
||||||
{ include: [ "<iosfwd>", public, "<iostream>", public ] },
|
|
||||||
|
|
||||||
# Missing mappings in include-what-you-use's libcxx.imp
|
|
||||||
{ include: ["@<__condition_variable/.*>", private, "<condition_variable>", public ] },
|
|
||||||
{ include: ["@<__mutex/.*>", private, "<mutex>", public ] },
|
|
||||||
]
|
|
||||||
@@ -1,160 +0,0 @@
|
|||||||
{
|
|
||||||
"config": [
|
|
||||||
{
|
|
||||||
"name": "Ubuntu 20.04 GCC",
|
|
||||||
"os": "ubuntu-20.04",
|
|
||||||
"simple_name": "ubuntu",
|
|
||||||
"compiler": "g++",
|
|
||||||
"comp": "gcc",
|
|
||||||
"shell": "bash",
|
|
||||||
"archive_ext": "tar",
|
|
||||||
"sde": "/home/runner/work/Stockfish/Stockfish/.output/sde-temp-files/sde-external-9.27.0-2023-09-13-lin/sde -future --"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "MacOS 13 Apple Clang",
|
|
||||||
"os": "macos-13",
|
|
||||||
"simple_name": "macos",
|
|
||||||
"compiler": "clang++",
|
|
||||||
"comp": "clang",
|
|
||||||
"shell": "bash",
|
|
||||||
"archive_ext": "tar"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "MacOS 14 Apple Clang M1",
|
|
||||||
"os": "macos-14",
|
|
||||||
"simple_name": "macos-m1",
|
|
||||||
"compiler": "clang++",
|
|
||||||
"comp": "clang",
|
|
||||||
"shell": "bash",
|
|
||||||
"archive_ext": "tar"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"name": "Windows 2022 Mingw-w64 GCC x86_64",
|
|
||||||
"os": "windows-2022",
|
|
||||||
"simple_name": "windows",
|
|
||||||
"compiler": "g++",
|
|
||||||
"comp": "mingw",
|
|
||||||
"msys_sys": "mingw64",
|
|
||||||
"msys_env": "x86_64-gcc",
|
|
||||||
"shell": "msys2 {0}",
|
|
||||||
"ext": ".exe",
|
|
||||||
"sde": "/d/a/Stockfish/Stockfish/.output/sde-temp-files/sde-external-9.27.0-2023-09-13-win/sde.exe -future --",
|
|
||||||
"archive_ext": "zip"
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"binaries": [
|
|
||||||
"x86-64",
|
|
||||||
"x86-64-sse41-popcnt",
|
|
||||||
"x86-64-avx2",
|
|
||||||
"x86-64-bmi2",
|
|
||||||
"x86-64-avxvnni",
|
|
||||||
"x86-64-avx512",
|
|
||||||
"x86-64-vnni256",
|
|
||||||
"x86-64-vnni512",
|
|
||||||
"apple-silicon"
|
|
||||||
],
|
|
||||||
"exclude": [
|
|
||||||
{
|
|
||||||
"binaries": "x86-64",
|
|
||||||
"config": {
|
|
||||||
"os": "macos-14"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "x86-64-sse41-popcnt",
|
|
||||||
"config": {
|
|
||||||
"os": "macos-14"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "x86-64-avx2",
|
|
||||||
"config": {
|
|
||||||
"os": "macos-14"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "x86-64-bmi2",
|
|
||||||
"config": {
|
|
||||||
"os": "macos-14"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "x86-64-avxvnni",
|
|
||||||
"config": {
|
|
||||||
"os": "macos-14"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "x86-64-avxvnni",
|
|
||||||
"config": {
|
|
||||||
"os": "macos-14"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "x86-64-avx512",
|
|
||||||
"config": {
|
|
||||||
"os": "macos-14"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "x86-64-vnni256",
|
|
||||||
"config": {
|
|
||||||
"os": "macos-14"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "x86-64-vnni512",
|
|
||||||
"config": {
|
|
||||||
"os": "macos-14"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "x86-64-avxvnni",
|
|
||||||
"config": {
|
|
||||||
"ubuntu-20.04": null
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "x86-64-avxvnni",
|
|
||||||
"config": {
|
|
||||||
"os": "macos-13"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "x86-64-avx512",
|
|
||||||
"config": {
|
|
||||||
"os": "macos-13"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "x86-64-vnni256",
|
|
||||||
"config": {
|
|
||||||
"os": "macos-13"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "x86-64-vnni512",
|
|
||||||
"config": {
|
|
||||||
"os": "macos-13"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "apple-silicon",
|
|
||||||
"config": {
|
|
||||||
"os": "windows-2022"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "apple-silicon",
|
|
||||||
"config": {
|
|
||||||
"os": "macos-13"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"binaries": "apple-silicon",
|
|
||||||
"config": {
|
|
||||||
"os": "ubuntu-20.04"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
name: Compilation
|
|
||||||
on:
|
|
||||||
workflow_call:
|
|
||||||
inputs:
|
|
||||||
matrix:
|
|
||||||
type: string
|
|
||||||
required: true
|
|
||||||
jobs:
|
|
||||||
Compilation:
|
|
||||||
name: ${{ matrix.config.name }} ${{ matrix.binaries }}
|
|
||||||
runs-on: ${{ matrix.config.os }}
|
|
||||||
env:
|
|
||||||
COMPCXX: ${{ matrix.config.compiler }}
|
|
||||||
COMP: ${{ matrix.config.comp }}
|
|
||||||
EMU: ${{ matrix.config.emu }}
|
|
||||||
EXT: ${{ matrix.config.ext }}
|
|
||||||
BINARY: ${{ matrix.binaries }}
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix: ${{ fromJson(inputs.matrix) }}
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: src
|
|
||||||
shell: ${{ matrix.config.shell }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- name: Download required linux packages
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
run: |
|
|
||||||
sudo apt update
|
|
||||||
sudo apt install qemu-user
|
|
||||||
|
|
||||||
- name: Install NDK
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
run: |
|
|
||||||
if [ $COMP == ndk ]; then
|
|
||||||
NDKV="21.4.7075529"
|
|
||||||
ANDROID_ROOT=/usr/local/lib/android
|
|
||||||
ANDROID_SDK_ROOT=$ANDROID_ROOT/sdk
|
|
||||||
SDKMANAGER=$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager
|
|
||||||
echo "y" | $SDKMANAGER "ndk;$NDKV"
|
|
||||||
ANDROID_NDK_ROOT=$ANDROID_SDK_ROOT/ndk/$NDKV
|
|
||||||
ANDROID_NDK_BIN=$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin
|
|
||||||
echo "ANDROID_NDK_BIN=$ANDROID_NDK_BIN" >> $GITHUB_ENV
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Extract the bench number from the commit history
|
|
||||||
run: |
|
|
||||||
for hash in $(git rev-list -100 HEAD); do
|
|
||||||
benchref=$(git show -s $hash | tac | grep -m 1 -o -x '[[:space:]]*\b[Bb]ench[ :]\+[1-9][0-9]\{5,7\}\b[[:space:]]*' | sed 's/[^0-9]//g') && break || true
|
|
||||||
done
|
|
||||||
[[ -n "$benchref" ]] && echo "benchref=$benchref" >> $GITHUB_ENV && echo "From commit: $hash" && echo "Reference bench: $benchref" || echo "No bench found"
|
|
||||||
|
|
||||||
- name: Download the used network from the fishtest framework
|
|
||||||
run: make net
|
|
||||||
|
|
||||||
- name: Check compiler
|
|
||||||
run: |
|
|
||||||
if [ $COMP == ndk ]; then
|
|
||||||
export PATH=${{ env.ANDROID_NDK_BIN }}:$PATH
|
|
||||||
fi
|
|
||||||
$COMPCXX -v
|
|
||||||
|
|
||||||
- name: Test help target
|
|
||||||
run: make help
|
|
||||||
|
|
||||||
- name: Check git
|
|
||||||
run: git --version
|
|
||||||
|
|
||||||
# Compile profile guided builds
|
|
||||||
|
|
||||||
- name: Compile ${{ matrix.binaries }} build
|
|
||||||
run: |
|
|
||||||
if [ $COMP == ndk ]; then
|
|
||||||
export PATH=${{ env.ANDROID_NDK_BIN }}:$PATH
|
|
||||||
export LDFLAGS="-static -Wno-unused-command-line-argument"
|
|
||||||
fi
|
|
||||||
make clean
|
|
||||||
make -j4 profile-build ARCH=$BINARY COMP=$COMP WINE_PATH=$EMU
|
|
||||||
make strip ARCH=$BINARY COMP=$COMP
|
|
||||||
WINE_PATH=$EMU ../tests/signature.sh $benchref
|
|
||||||
mv ./stockfish$EXT ../stockfish-android-$BINARY$EXT
|
|
||||||
|
|
||||||
- name: Remove non src files
|
|
||||||
run: git clean -fx
|
|
||||||
|
|
||||||
- name: Upload artifact for (pre)-release
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: ${{ matrix.config.simple_name }} ${{ matrix.binaries }}
|
|
||||||
path: |
|
|
||||||
.
|
|
||||||
!.git
|
|
||||||
!.output
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
# This workflow will run clang-format and comment on the PR.
|
|
||||||
# Because of security reasons, it is crucial that this workflow
|
|
||||||
# executes no shell script nor runs make.
|
|
||||||
# Read this before editing: https://securitylab.github.com/research/github-actions-preventing-pwn-requests/
|
|
||||||
|
|
||||||
name: Clang-Format
|
|
||||||
on:
|
|
||||||
pull_request_target:
|
|
||||||
branches:
|
|
||||||
- "master"
|
|
||||||
paths:
|
|
||||||
- "**.cpp"
|
|
||||||
- "**.h"
|
|
||||||
|
|
||||||
permissions:
|
|
||||||
pull-requests: write
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
Clang-Format:
|
|
||||||
name: Clang-Format
|
|
||||||
runs-on: ubuntu-20.04
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
ref: ${{ github.event.pull_request.head.sha }}
|
|
||||||
|
|
||||||
- name: Run clang-format style check
|
|
||||||
uses: jidicula/clang-format-action@f62da5e3d3a2d88ff364771d9d938773a618ab5e # @v4.11.0
|
|
||||||
id: clang-format
|
|
||||||
continue-on-error: true
|
|
||||||
with:
|
|
||||||
clang-format-version: "18"
|
|
||||||
exclude-regex: "incbin"
|
|
||||||
|
|
||||||
- name: Comment on PR
|
|
||||||
if: steps.clang-format.outcome == 'failure'
|
|
||||||
uses: thollander/actions-comment-pull-request@fabd468d3a1a0b97feee5f6b9e499eab0dd903f6 # @v2.5.0
|
|
||||||
with:
|
|
||||||
message: |
|
|
||||||
clang-format 18 needs to be run on this PR.
|
|
||||||
If you do not have clang-format installed, the maintainer will run it when merging.
|
|
||||||
For the exact version please see https://packages.ubuntu.com/noble/clang-format-18.
|
|
||||||
|
|
||||||
_(execution **${{ github.run_id }}** / attempt **${{ github.run_attempt }}**)_
|
|
||||||
comment_tag: execution
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
- name: Comment on PR
|
|
||||||
if: steps.clang-format.outcome != 'failure'
|
|
||||||
uses: thollander/actions-comment-pull-request@fabd468d3a1a0b97feee5f6b9e499eab0dd903f6 # @v2.5.0
|
|
||||||
with:
|
|
||||||
message: |
|
|
||||||
_(execution **${{ github.run_id }}** / attempt **${{ github.run_attempt }}**)_
|
|
||||||
create_if_not_exists: false
|
|
||||||
comment_tag: execution
|
|
||||||
mode: delete
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
name: "CodeQL"
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: ["master"]
|
|
||||||
pull_request:
|
|
||||||
# The branches below must be a subset of the branches above
|
|
||||||
branches: ["master"]
|
|
||||||
schedule:
|
|
||||||
- cron: "17 18 * * 1"
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
analyze:
|
|
||||||
name: Analyze
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
actions: read
|
|
||||||
contents: read
|
|
||||||
security-events: write
|
|
||||||
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
language: ["cpp"]
|
|
||||||
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
|
|
||||||
# Use only 'java' to analyze code written in Java, Kotlin, or both
|
|
||||||
# Use only 'javascript' to analyze code written in JavaScript, TypeScript or both
|
|
||||||
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout repository
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
# Initializes the CodeQL tools for scanning.
|
|
||||||
- name: Initialize CodeQL
|
|
||||||
uses: github/codeql-action/init@v3
|
|
||||||
with:
|
|
||||||
languages: ${{ matrix.language }}
|
|
||||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
|
||||||
# By default, queries listed here will override any specified in a config file.
|
|
||||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
|
||||||
|
|
||||||
# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
|
|
||||||
# queries: security-extended,security-and-quality
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
working-directory: src
|
|
||||||
run: make -j build ARCH=x86-64-modern
|
|
||||||
|
|
||||||
- name: Perform CodeQL Analysis
|
|
||||||
uses: github/codeql-action/analyze@v3
|
|
||||||
with:
|
|
||||||
category: "/language:${{matrix.language}}"
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
name: Compilation
|
|
||||||
on:
|
|
||||||
workflow_call:
|
|
||||||
inputs:
|
|
||||||
matrix:
|
|
||||||
type: string
|
|
||||||
required: true
|
|
||||||
jobs:
|
|
||||||
Compilation:
|
|
||||||
name: ${{ matrix.config.name }} ${{ matrix.binaries }}
|
|
||||||
runs-on: ${{ matrix.config.os }}
|
|
||||||
env:
|
|
||||||
COMPCXX: ${{ matrix.config.compiler }}
|
|
||||||
COMP: ${{ matrix.config.comp }}
|
|
||||||
EXT: ${{ matrix.config.ext }}
|
|
||||||
NAME: ${{ matrix.config.simple_name }}
|
|
||||||
BINARY: ${{ matrix.binaries }}
|
|
||||||
SDE: ${{ matrix.config.sde }}
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix: ${{ fromJson(inputs.matrix) }}
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: src
|
|
||||||
shell: ${{ matrix.config.shell }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- name: Install fixed GCC on Linux
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
uses: egor-tensin/setup-gcc@eaa888eb19115a521fa72b65cd94fe1f25bbcaac # @v1.3
|
|
||||||
with:
|
|
||||||
version: 11
|
|
||||||
|
|
||||||
- name: Setup msys and install required packages
|
|
||||||
if: runner.os == 'Windows'
|
|
||||||
uses: msys2/setup-msys2@v2
|
|
||||||
with:
|
|
||||||
msystem: ${{ matrix.config.msys_sys }}
|
|
||||||
install: mingw-w64-${{ matrix.config.msys_env }} make git zip
|
|
||||||
|
|
||||||
- name: Download SDE package
|
|
||||||
if: runner.os == 'Linux' || runner.os == 'Windows'
|
|
||||||
uses: petarpetrovt/setup-sde@91a1a03434384e064706634125a15f7446d2aafb # @v2.3
|
|
||||||
with:
|
|
||||||
environmentVariableName: SDE_DIR
|
|
||||||
sdeVersion: 9.27.0
|
|
||||||
|
|
||||||
- name: Download the used network from the fishtest framework
|
|
||||||
run: make net
|
|
||||||
|
|
||||||
- name: Check compiler
|
|
||||||
run: $COMPCXX -v
|
|
||||||
|
|
||||||
- name: Test help target
|
|
||||||
run: make help
|
|
||||||
|
|
||||||
- name: Check git
|
|
||||||
run: git --version
|
|
||||||
|
|
||||||
- name: Check compiler
|
|
||||||
run: $COMPCXX -v
|
|
||||||
|
|
||||||
- name: Show g++ cpu info
|
|
||||||
if: runner.os != 'macOS'
|
|
||||||
run: g++ -Q -march=native --help=target
|
|
||||||
|
|
||||||
- name: Show clang++ cpu info
|
|
||||||
if: runner.os == 'macOS'
|
|
||||||
run: clang++ -E - -march=native -###
|
|
||||||
|
|
||||||
# x86-64 with newer extensions tests
|
|
||||||
|
|
||||||
- name: Compile ${{ matrix.config.binaries }} build
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 profile-build ARCH=$BINARY COMP=$COMP WINE_PATH="$SDE"
|
|
||||||
make strip ARCH=$BINARY COMP=$COMP
|
|
||||||
WINE_PATH="$SDE" ../tests/signature.sh $benchref
|
|
||||||
mv ./stockfish$EXT ../stockfish-$NAME-$BINARY$EXT
|
|
||||||
|
|
||||||
- name: Remove non src files
|
|
||||||
run: git clean -fx
|
|
||||||
|
|
||||||
- name: Upload artifact for (pre)-release
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: ${{ matrix.config.simple_name }} ${{ matrix.binaries }}
|
|
||||||
path: |
|
|
||||||
.
|
|
||||||
!.git
|
|
||||||
!.output
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
# This workflow will play games with a debug enabled SF using the PR
|
|
||||||
|
|
||||||
name: Games
|
|
||||||
on:
|
|
||||||
workflow_call:
|
|
||||||
jobs:
|
|
||||||
Matetrack:
|
|
||||||
name: Games
|
|
||||||
runs-on: ubuntu-22.04
|
|
||||||
steps:
|
|
||||||
- name: Checkout SF repo
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
ref: ${{ github.event.pull_request.head.sha }}
|
|
||||||
path: Stockfish
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- name: build debug enabled version of SF
|
|
||||||
working-directory: Stockfish/src
|
|
||||||
run: make -j build debug=yes
|
|
||||||
|
|
||||||
- name: Checkout fast-chess repo
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
repository: Disservin/fast-chess
|
|
||||||
path: fast-chess
|
|
||||||
ref: d54af1910d5479c669dc731f1f54f9108a251951
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- name: fast-chess build
|
|
||||||
working-directory: fast-chess
|
|
||||||
run: make -j
|
|
||||||
|
|
||||||
- name: Run games
|
|
||||||
working-directory: fast-chess
|
|
||||||
run: |
|
|
||||||
./fast-chess -rounds 4 -games 2 -repeat -concurrency 4 -openings file=app/tests/data/openings.epd format=epd order=random -srand $RANDOM\
|
|
||||||
-engine name=sf1 cmd=/home/runner/work/Stockfish/Stockfish/Stockfish/src/stockfish\
|
|
||||||
-engine name=sf2 cmd=/home/runner/work/Stockfish/Stockfish/Stockfish/src/stockfish\
|
|
||||||
-ratinginterval 1 -report penta=true -each proto=uci tc=4+0.04 -log file=fast.log | tee fast.out
|
|
||||||
cat fast.log
|
|
||||||
! grep "Assertion" fast.log > /dev/null
|
|
||||||
! grep "disconnect" fast.out > /dev/null
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
name: IWYU
|
|
||||||
on:
|
|
||||||
workflow_call:
|
|
||||||
jobs:
|
|
||||||
Analyzers:
|
|
||||||
name: Check includes
|
|
||||||
runs-on: ubuntu-22.04
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: Stockfish/src
|
|
||||||
shell: bash
|
|
||||||
steps:
|
|
||||||
- name: Checkout Stockfish
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
path: Stockfish
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- name: Checkout include-what-you-use
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
repository: include-what-you-use/include-what-you-use
|
|
||||||
ref: f25caa280dc3277c4086ec345ad279a2463fea0f
|
|
||||||
path: include-what-you-use
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- name: Download required linux packages
|
|
||||||
run: |
|
|
||||||
sudo add-apt-repository 'deb http://apt.llvm.org/jammy/ llvm-toolchain-jammy-17 main'
|
|
||||||
wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add -
|
|
||||||
sudo apt update
|
|
||||||
sudo apt install -y libclang-17-dev clang-17 libc++-17-dev
|
|
||||||
|
|
||||||
- name: Set up include-what-you-use
|
|
||||||
run: |
|
|
||||||
mkdir build && cd build
|
|
||||||
cmake -G "Unix Makefiles" -DCMAKE_PREFIX_PATH="/usr/lib/llvm-17" ..
|
|
||||||
sudo make install
|
|
||||||
working-directory: include-what-you-use
|
|
||||||
|
|
||||||
- name: Check include-what-you-use
|
|
||||||
run: include-what-you-use --version
|
|
||||||
|
|
||||||
- name: Check includes
|
|
||||||
run: >
|
|
||||||
make analyze
|
|
||||||
COMP=clang
|
|
||||||
CXX=include-what-you-use
|
|
||||||
CXXFLAGS="-stdlib=libc++ -Xiwyu --comment_style=long -Xiwyu --mapping='${{ github.workspace }}/Stockfish/.github/ci/libcxx17.imp' -Xiwyu --error"
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
# This workflow will run matetrack on the PR
|
|
||||||
|
|
||||||
name: Matetrack
|
|
||||||
on:
|
|
||||||
workflow_call:
|
|
||||||
jobs:
|
|
||||||
Matetrack:
|
|
||||||
name: Matetrack
|
|
||||||
runs-on: ubuntu-22.04
|
|
||||||
steps:
|
|
||||||
- name: Checkout SF repo
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
ref: ${{ github.event.pull_request.head.sha }}
|
|
||||||
path: Stockfish
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- name: build SF
|
|
||||||
working-directory: Stockfish/src
|
|
||||||
run: make -j profile-build
|
|
||||||
|
|
||||||
- name: Checkout matetrack repo
|
|
||||||
uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
repository: vondele/matetrack
|
|
||||||
path: matetrack
|
|
||||||
ref: 814160f82e6428ed2f6522dc06c2a6fa539cd413
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- name: matetrack install deps
|
|
||||||
working-directory: matetrack
|
|
||||||
run: pip install -r requirements.txt
|
|
||||||
|
|
||||||
- name: cache syzygy
|
|
||||||
id: cache-syzygy
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
matetrack/3-4-5-wdl/
|
|
||||||
matetrack/3-4-5-dtz/
|
|
||||||
key: key-syzygy
|
|
||||||
|
|
||||||
- name: download syzygy 3-4-5 if needed
|
|
||||||
working-directory: matetrack
|
|
||||||
if: steps.cache-syzygy.outputs.cache-hit != 'true'
|
|
||||||
run: |
|
|
||||||
wget --no-verbose -r -nH --cut-dirs=2 --no-parent --reject="index.html*" -e robots=off https://tablebase.lichess.ovh/tables/standard/3-4-5-wdl/
|
|
||||||
wget --no-verbose -r -nH --cut-dirs=2 --no-parent --reject="index.html*" -e robots=off https://tablebase.lichess.ovh/tables/standard/3-4-5-dtz/
|
|
||||||
|
|
||||||
- name: Run matetrack
|
|
||||||
working-directory: matetrack
|
|
||||||
run: |
|
|
||||||
python matecheck.py --syzygyPath 3-4-5-wdl/:3-4-5-dtz/ --engine /home/runner/work/Stockfish/Stockfish/Stockfish/src/stockfish --epdFile mates2000.epd --nodes 100000 | tee matecheckout.out
|
|
||||||
! grep "issues were detected" matecheckout.out > /dev/null
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
name: Sanitizers
|
|
||||||
on:
|
|
||||||
workflow_call:
|
|
||||||
jobs:
|
|
||||||
Test-under-sanitizers:
|
|
||||||
name: ${{ matrix.sanitizers.name }}
|
|
||||||
runs-on: ${{ matrix.config.os }}
|
|
||||||
env:
|
|
||||||
COMPCXX: ${{ matrix.config.compiler }}
|
|
||||||
COMP: ${{ matrix.config.comp }}
|
|
||||||
CXXFLAGS: "-Werror"
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
config:
|
|
||||||
- name: Ubuntu 22.04 GCC
|
|
||||||
os: ubuntu-22.04
|
|
||||||
compiler: g++
|
|
||||||
comp: gcc
|
|
||||||
shell: bash
|
|
||||||
sanitizers:
|
|
||||||
- name: Run with thread sanitizer
|
|
||||||
make_option: sanitize=thread
|
|
||||||
instrumented_option: sanitizer-thread
|
|
||||||
- name: Run with UB sanitizer
|
|
||||||
make_option: sanitize=undefined
|
|
||||||
instrumented_option: sanitizer-undefined
|
|
||||||
- name: Run under valgrind
|
|
||||||
make_option: ""
|
|
||||||
instrumented_option: valgrind
|
|
||||||
- name: Run under valgrind-thread
|
|
||||||
make_option: ""
|
|
||||||
instrumented_option: valgrind-thread
|
|
||||||
- name: Run non-instrumented
|
|
||||||
make_option: ""
|
|
||||||
instrumented_option: none
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: src
|
|
||||||
shell: ${{ matrix.config.shell }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- name: Download required linux packages
|
|
||||||
run: |
|
|
||||||
sudo apt update
|
|
||||||
sudo apt install expect valgrind g++-multilib
|
|
||||||
|
|
||||||
- name: Download the used network from the fishtest framework
|
|
||||||
run: make net
|
|
||||||
|
|
||||||
- name: Check compiler
|
|
||||||
run: $COMPCXX -v
|
|
||||||
|
|
||||||
- name: Test help target
|
|
||||||
run: make help
|
|
||||||
|
|
||||||
- name: Check git
|
|
||||||
run: git --version
|
|
||||||
|
|
||||||
# Since Linux Kernel 6.5 we are getting false positives from the ci,
|
|
||||||
# lower the ALSR entropy to disable ALSR, which works as a temporary workaround.
|
|
||||||
# https://github.com/google/sanitizers/issues/1716
|
|
||||||
# https://bugs.launchpad.net/ubuntu/+source/linux/+bug/2056762
|
|
||||||
|
|
||||||
- name: Lower ALSR entropy
|
|
||||||
run: sudo sysctl -w vm.mmap_rnd_bits=28
|
|
||||||
|
|
||||||
# Sanitizers
|
|
||||||
|
|
||||||
- name: ${{ matrix.sanitizers.name }}
|
|
||||||
run: |
|
|
||||||
export CXXFLAGS="-O1 -fno-inline"
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=x86-64-sse41-popcnt ${{ matrix.sanitizers.make_option }} debug=yes optimize=no build > /dev/null
|
|
||||||
../tests/instrumented.sh --${{ matrix.sanitizers.instrumented_option }}
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
name: Stockfish
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
tags:
|
|
||||||
- "*"
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
- tools
|
|
||||||
- github_ci
|
|
||||||
pull_request:
|
|
||||||
branches:
|
|
||||||
- master
|
|
||||||
- tools
|
|
||||||
jobs:
|
|
||||||
Prerelease:
|
|
||||||
if: github.repository == 'official-stockfish/Stockfish' && (github.ref == 'refs/heads/master' || (startsWith(github.ref_name, 'sf_') && github.ref_type == 'tag'))
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: write # For deleting/creating a prerelease
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
# returns null if no pre-release exists
|
|
||||||
- name: Get Commit SHA of Latest Pre-release
|
|
||||||
run: |
|
|
||||||
# Install required packages
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y curl jq
|
|
||||||
|
|
||||||
echo "COMMIT_SHA_TAG=$(jq -r 'map(select(.prerelease)) | first | .tag_name' <<< $(curl -s https://api.github.com/repos/${{ github.repository_owner }}/Stockfish/releases))" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
# delete old previous pre-release and tag
|
|
||||||
- run: gh release delete ${{ env.COMMIT_SHA_TAG }} --cleanup-tag
|
|
||||||
if: env.COMMIT_SHA_TAG != 'null'
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
|
|
||||||
# Make sure that an old ci that still runs on master doesn't recreate a prerelease
|
|
||||||
- name: Check Pullable Commits
|
|
||||||
id: check_commits
|
|
||||||
run: |
|
|
||||||
git fetch
|
|
||||||
CHANGES=$(git rev-list HEAD..origin/master --count)
|
|
||||||
echo "CHANGES=$CHANGES" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Get last commit SHA
|
|
||||||
id: last_commit
|
|
||||||
run: echo "COMMIT_SHA=$(git rev-parse HEAD | cut -c 1-8)" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Get commit date
|
|
||||||
id: commit_date
|
|
||||||
run: echo "COMMIT_DATE=$(git show -s --date=format:'%Y%m%d' --format=%cd HEAD)" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
# Create a new pre-release, the other upload_binaries.yml will upload the binaries
|
|
||||||
# to this pre-release.
|
|
||||||
- name: Create Prerelease
|
|
||||||
if: github.ref_name == 'master' && env.CHANGES == '0'
|
|
||||||
uses: softprops/action-gh-release@4634c16e79c963813287e889244c50009e7f0981
|
|
||||||
with:
|
|
||||||
name: Stockfish dev-${{ env.COMMIT_DATE }}-${{ env.COMMIT_SHA }}
|
|
||||||
tag_name: stockfish-dev-${{ env.COMMIT_DATE }}-${{ env.COMMIT_SHA }}
|
|
||||||
prerelease: true
|
|
||||||
|
|
||||||
Matrix:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
outputs:
|
|
||||||
matrix: ${{ steps.set-matrix.outputs.matrix }}
|
|
||||||
arm_matrix: ${{ steps.set-arm-matrix.outputs.arm_matrix }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
- id: set-matrix
|
|
||||||
run: |
|
|
||||||
TASKS=$(echo $(cat .github/ci/matrix.json) )
|
|
||||||
echo "MATRIX=$TASKS" >> $GITHUB_OUTPUT
|
|
||||||
- id: set-arm-matrix
|
|
||||||
run: |
|
|
||||||
TASKS_ARM=$(echo $(cat .github/ci/arm_matrix.json) )
|
|
||||||
echo "ARM_MATRIX=$TASKS_ARM" >> $GITHUB_OUTPUT
|
|
||||||
Compilation:
|
|
||||||
needs: [Matrix]
|
|
||||||
uses: ./.github/workflows/compilation.yml
|
|
||||||
with:
|
|
||||||
matrix: ${{ needs.Matrix.outputs.matrix }}
|
|
||||||
ARMCompilation:
|
|
||||||
needs: [Matrix]
|
|
||||||
uses: ./.github/workflows/arm_compilation.yml
|
|
||||||
with:
|
|
||||||
matrix: ${{ needs.Matrix.outputs.arm_matrix }}
|
|
||||||
IWYU:
|
|
||||||
uses: ./.github/workflows/iwyu.yml
|
|
||||||
Sanitizers:
|
|
||||||
uses: ./.github/workflows/sanitizers.yml
|
|
||||||
Tests:
|
|
||||||
uses: ./.github/workflows/tests.yml
|
|
||||||
Matetrack:
|
|
||||||
uses: ./.github/workflows/matetrack.yml
|
|
||||||
Games:
|
|
||||||
uses: ./.github/workflows/games.yml
|
|
||||||
Binaries:
|
|
||||||
if: github.repository == 'official-stockfish/Stockfish'
|
|
||||||
needs: [Matrix, Prerelease, Compilation]
|
|
||||||
uses: ./.github/workflows/upload_binaries.yml
|
|
||||||
with:
|
|
||||||
matrix: ${{ needs.Matrix.outputs.matrix }}
|
|
||||||
permissions:
|
|
||||||
contents: write # For deleting/creating a (pre)release
|
|
||||||
secrets:
|
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
ARM_Binaries:
|
|
||||||
if: github.repository == 'official-stockfish/Stockfish'
|
|
||||||
needs: [Matrix, Prerelease, ARMCompilation]
|
|
||||||
uses: ./.github/workflows/upload_binaries.yml
|
|
||||||
with:
|
|
||||||
matrix: ${{ needs.Matrix.outputs.arm_matrix }}
|
|
||||||
permissions:
|
|
||||||
contents: write # For deleting/creating a (pre)release
|
|
||||||
secrets:
|
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
@@ -1,366 +0,0 @@
|
|||||||
name: Tests
|
|
||||||
on:
|
|
||||||
workflow_call:
|
|
||||||
jobs:
|
|
||||||
Test-Targets:
|
|
||||||
name: ${{ matrix.config.name }}
|
|
||||||
runs-on: ${{ matrix.config.os }}
|
|
||||||
env:
|
|
||||||
COMPCXX: ${{ matrix.config.compiler }}
|
|
||||||
COMP: ${{ matrix.config.comp }}
|
|
||||||
CXXFLAGS: "-Werror"
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
config:
|
|
||||||
- name: Ubuntu 20.04 GCC
|
|
||||||
os: ubuntu-20.04
|
|
||||||
compiler: g++
|
|
||||||
comp: gcc
|
|
||||||
run_32bit_tests: true
|
|
||||||
run_64bit_tests: true
|
|
||||||
shell: bash
|
|
||||||
- name: Ubuntu 20.04 Clang
|
|
||||||
os: ubuntu-20.04
|
|
||||||
compiler: clang++
|
|
||||||
comp: clang
|
|
||||||
run_32bit_tests: true
|
|
||||||
run_64bit_tests: true
|
|
||||||
shell: bash
|
|
||||||
- name: Android NDK aarch64
|
|
||||||
os: ubuntu-22.04
|
|
||||||
compiler: aarch64-linux-android21-clang++
|
|
||||||
comp: ndk
|
|
||||||
run_armv8_tests: true
|
|
||||||
shell: bash
|
|
||||||
- name: Android NDK arm
|
|
||||||
os: ubuntu-22.04
|
|
||||||
compiler: armv7a-linux-androideabi21-clang++
|
|
||||||
comp: ndk
|
|
||||||
run_armv7_tests: true
|
|
||||||
shell: bash
|
|
||||||
- name: Linux GCC riscv64
|
|
||||||
os: ubuntu-22.04
|
|
||||||
compiler: g++
|
|
||||||
comp: gcc
|
|
||||||
run_riscv64_tests: true
|
|
||||||
base_image: "riscv64/alpine:edge"
|
|
||||||
platform: linux/riscv64
|
|
||||||
shell: bash
|
|
||||||
- name: Linux GCC ppc64
|
|
||||||
os: ubuntu-22.04
|
|
||||||
compiler: g++
|
|
||||||
comp: gcc
|
|
||||||
run_ppc64_tests: true
|
|
||||||
base_image: "ppc64le/alpine:latest"
|
|
||||||
platform: linux/ppc64le
|
|
||||||
shell: bash
|
|
||||||
- name: MacOS 13 Apple Clang
|
|
||||||
os: macos-13
|
|
||||||
compiler: clang++
|
|
||||||
comp: clang
|
|
||||||
run_64bit_tests: true
|
|
||||||
shell: bash
|
|
||||||
- name: MacOS 14 Apple Clang M1
|
|
||||||
os: macos-14
|
|
||||||
compiler: clang++
|
|
||||||
comp: clang
|
|
||||||
run_64bit_tests: false
|
|
||||||
run_m1_tests: true
|
|
||||||
shell: bash
|
|
||||||
- name: MacOS 13 GCC 11
|
|
||||||
os: macos-13
|
|
||||||
compiler: g++-11
|
|
||||||
comp: gcc
|
|
||||||
run_64bit_tests: true
|
|
||||||
shell: bash
|
|
||||||
- name: Windows 2022 Mingw-w64 GCC x86_64
|
|
||||||
os: windows-2022
|
|
||||||
compiler: g++
|
|
||||||
comp: mingw
|
|
||||||
run_64bit_tests: true
|
|
||||||
msys_sys: mingw64
|
|
||||||
msys_env: x86_64-gcc
|
|
||||||
shell: msys2 {0}
|
|
||||||
- name: Windows 2022 Mingw-w64 GCC i686
|
|
||||||
os: windows-2022
|
|
||||||
compiler: g++
|
|
||||||
comp: mingw
|
|
||||||
run_32bit_tests: true
|
|
||||||
msys_sys: mingw32
|
|
||||||
msys_env: i686-gcc
|
|
||||||
shell: msys2 {0}
|
|
||||||
- name: Windows 2022 Mingw-w64 Clang x86_64
|
|
||||||
os: windows-2022
|
|
||||||
compiler: clang++
|
|
||||||
comp: clang
|
|
||||||
run_64bit_tests: true
|
|
||||||
msys_sys: clang64
|
|
||||||
msys_env: clang-x86_64-clang
|
|
||||||
shell: msys2 {0}
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
working-directory: src
|
|
||||||
shell: ${{ matrix.config.shell }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- name: Download required linux packages
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
run: |
|
|
||||||
sudo apt update
|
|
||||||
sudo apt install expect valgrind g++-multilib qemu-user-static
|
|
||||||
|
|
||||||
- name: Install NDK
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
run: |
|
|
||||||
if [ $COMP == ndk ]; then
|
|
||||||
NDKV="21.4.7075529"
|
|
||||||
ANDROID_ROOT=/usr/local/lib/android
|
|
||||||
ANDROID_SDK_ROOT=$ANDROID_ROOT/sdk
|
|
||||||
SDKMANAGER=$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/sdkmanager
|
|
||||||
echo "y" | $SDKMANAGER "ndk;$NDKV"
|
|
||||||
ANDROID_NDK_ROOT=$ANDROID_SDK_ROOT/ndk/$NDKV
|
|
||||||
ANDROID_NDK_BIN=$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/linux-x86_64/bin
|
|
||||||
echo "ANDROID_NDK_BIN=$ANDROID_NDK_BIN" >> $GITHUB_ENV
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Set up QEMU
|
|
||||||
if: matrix.config.base_image
|
|
||||||
uses: docker/setup-qemu-action@v3
|
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
if: matrix.config.base_image
|
|
||||||
uses: docker/setup-buildx-action@v3
|
|
||||||
|
|
||||||
- name: Build Docker container
|
|
||||||
if: matrix.config.base_image
|
|
||||||
run: |
|
|
||||||
docker buildx build --load -t sf_builder - << EOF
|
|
||||||
FROM ${{ matrix.config.base_image }}
|
|
||||||
WORKDIR /app
|
|
||||||
RUN apk update && apk add make g++
|
|
||||||
CMD ["sh", "script.sh"]
|
|
||||||
EOF
|
|
||||||
|
|
||||||
- name: Download required macOS packages
|
|
||||||
if: runner.os == 'macOS'
|
|
||||||
run: brew install coreutils gcc@11
|
|
||||||
|
|
||||||
- name: Setup msys and install required packages
|
|
||||||
if: runner.os == 'Windows'
|
|
||||||
uses: msys2/setup-msys2@v2
|
|
||||||
with:
|
|
||||||
msystem: ${{ matrix.config.msys_sys }}
|
|
||||||
install: mingw-w64-${{ matrix.config.msys_env }} make git expect
|
|
||||||
|
|
||||||
- name: Download the used network from the fishtest framework
|
|
||||||
run: make net
|
|
||||||
|
|
||||||
- name: Extract the bench number from the commit history
|
|
||||||
run: |
|
|
||||||
for hash in $(git rev-list -100 HEAD); do
|
|
||||||
benchref=$(git show -s $hash | tac | grep -m 1 -o -x '[[:space:]]*\b[Bb]ench[ :]\+[1-9][0-9]\{5,7\}\b[[:space:]]*' | sed 's/[^0-9]//g') && break || true
|
|
||||||
done
|
|
||||||
[[ -n "$benchref" ]] && echo "benchref=$benchref" >> $GITHUB_ENV && echo "From commit: $hash" && echo "Reference bench: $benchref" || echo "No bench found"
|
|
||||||
|
|
||||||
- name: Check compiler
|
|
||||||
run: |
|
|
||||||
if [ -z "${{ matrix.config.base_image }}" ]; then
|
|
||||||
if [ $COMP == ndk ]; then
|
|
||||||
export PATH=${{ env.ANDROID_NDK_BIN }}:$PATH
|
|
||||||
fi
|
|
||||||
$COMPCXX -v
|
|
||||||
else
|
|
||||||
echo "$COMPCXX -v" > script.sh
|
|
||||||
docker run --rm --platform ${{ matrix.config.platform }} -v ${{ github.workspace }}/src:/app sf_builder
|
|
||||||
fi
|
|
||||||
|
|
||||||
- name: Test help target
|
|
||||||
run: make help
|
|
||||||
|
|
||||||
- name: Check git
|
|
||||||
run: git --version
|
|
||||||
|
|
||||||
# x86-32 tests
|
|
||||||
|
|
||||||
- name: Test debug x86-32 build
|
|
||||||
if: matrix.config.run_32bit_tests
|
|
||||||
run: |
|
|
||||||
export CXXFLAGS="-Werror -D_GLIBCXX_DEBUG"
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=x86-32 optimize=no debug=yes build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
- name: Test x86-32 build
|
|
||||||
if: matrix.config.run_32bit_tests
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=x86-32 build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
- name: Test x86-32-sse41-popcnt build
|
|
||||||
if: matrix.config.run_32bit_tests
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=x86-32-sse41-popcnt build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
- name: Test x86-32-sse2 build
|
|
||||||
if: matrix.config.run_32bit_tests
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=x86-32-sse2 build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
- name: Test general-32 build
|
|
||||||
if: matrix.config.run_32bit_tests
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=general-32 build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
# x86-64 tests
|
|
||||||
|
|
||||||
- name: Test debug x86-64-avx2 build
|
|
||||||
if: matrix.config.run_64bit_tests
|
|
||||||
run: |
|
|
||||||
export CXXFLAGS="-Werror -D_GLIBCXX_DEBUG"
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=x86-64-avx2 optimize=no debug=yes build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
- name: Test x86-64-bmi2 build
|
|
||||||
if: matrix.config.run_64bit_tests
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=x86-64-bmi2 build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
- name: Test x86-64-avx2 build
|
|
||||||
if: matrix.config.run_64bit_tests
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=x86-64-avx2 build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
# Test a deprecated arch
|
|
||||||
- name: Test x86-64-modern build
|
|
||||||
if: matrix.config.run_64bit_tests
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=x86-64-modern build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
- name: Test x86-64-sse41-popcnt build
|
|
||||||
if: matrix.config.run_64bit_tests
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=x86-64-sse41-popcnt build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
- name: Test x86-64-ssse3 build
|
|
||||||
if: matrix.config.run_64bit_tests
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=x86-64-ssse3 build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
- name: Test x86-64-sse3-popcnt build
|
|
||||||
if: matrix.config.run_64bit_tests
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=x86-64-sse3-popcnt build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
- name: Test x86-64 build
|
|
||||||
if: matrix.config.run_64bit_tests
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=x86-64 build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
- name: Test general-64 build
|
|
||||||
if: matrix.config.run_64bit_tests
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=general-64 build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
- name: Test apple-silicon build
|
|
||||||
if: matrix.config.run_m1_tests
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=apple-silicon build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
# armv8 tests
|
|
||||||
|
|
||||||
- name: Test armv8 build
|
|
||||||
if: matrix.config.run_armv8_tests
|
|
||||||
run: |
|
|
||||||
export PATH=${{ env.ANDROID_NDK_BIN }}:$PATH
|
|
||||||
export LDFLAGS="-static -Wno-unused-command-line-argument"
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=armv8 build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
- name: Test armv8-dotprod build
|
|
||||||
if: matrix.config.run_armv8_tests
|
|
||||||
run: |
|
|
||||||
export PATH=${{ env.ANDROID_NDK_BIN }}:$PATH
|
|
||||||
export LDFLAGS="-static -Wno-unused-command-line-argument"
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=armv8-dotprod build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
# armv7 tests
|
|
||||||
|
|
||||||
- name: Test armv7 build
|
|
||||||
if: matrix.config.run_armv7_tests
|
|
||||||
run: |
|
|
||||||
export PATH=${{ env.ANDROID_NDK_BIN }}:$PATH
|
|
||||||
export LDFLAGS="-static -Wno-unused-command-line-argument"
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=armv7 build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
- name: Test armv7-neon build
|
|
||||||
if: matrix.config.run_armv7_tests
|
|
||||||
run: |
|
|
||||||
export PATH=${{ env.ANDROID_NDK_BIN }}:$PATH
|
|
||||||
export LDFLAGS="-static -Wno-unused-command-line-argument"
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=armv7-neon build
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
# riscv64 tests
|
|
||||||
|
|
||||||
- name: Test riscv64 build
|
|
||||||
if: matrix.config.run_riscv64_tests
|
|
||||||
run: |
|
|
||||||
echo "export LDFLAGS='-static' && make clean && make -j4 ARCH=riscv64 build" > script.sh
|
|
||||||
docker run --rm --platform ${{ matrix.config.platform }} -v ${{ github.workspace }}/src:/app sf_builder
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
# ppc64 tests
|
|
||||||
|
|
||||||
- name: Test ppc64 build
|
|
||||||
if: matrix.config.run_ppc64_tests
|
|
||||||
run: |
|
|
||||||
echo "export LDFLAGS='-static' && make clean && make -j4 ARCH=ppc-64 build" > script.sh
|
|
||||||
docker run --rm --platform ${{ matrix.config.platform }} -v ${{ github.workspace }}/src:/app sf_builder
|
|
||||||
../tests/signature.sh $benchref
|
|
||||||
|
|
||||||
# Other tests
|
|
||||||
|
|
||||||
- name: Check perft and search reproducibility
|
|
||||||
if: matrix.config.run_64bit_tests
|
|
||||||
run: |
|
|
||||||
make clean
|
|
||||||
make -j4 ARCH=x86-64-avx2 build
|
|
||||||
../tests/perft.sh
|
|
||||||
../tests/reprosearch.sh
|
|
||||||
@@ -1,113 +0,0 @@
|
|||||||
name: Upload Binaries
|
|
||||||
on:
|
|
||||||
workflow_call:
|
|
||||||
inputs:
|
|
||||||
matrix:
|
|
||||||
type: string
|
|
||||||
required: true
|
|
||||||
secrets:
|
|
||||||
token:
|
|
||||||
required: true
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
Artifacts:
|
|
||||||
name: ${{ matrix.config.name }} ${{ matrix.binaries }}
|
|
||||||
runs-on: ${{ matrix.config.os }}
|
|
||||||
env:
|
|
||||||
COMPCXX: ${{ matrix.config.compiler }}
|
|
||||||
COMP: ${{ matrix.config.comp }}
|
|
||||||
EXT: ${{ matrix.config.ext }}
|
|
||||||
NAME: ${{ matrix.config.simple_name }}
|
|
||||||
BINARY: ${{ matrix.binaries }}
|
|
||||||
SDE: ${{ matrix.config.sde }}
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix: ${{ fromJson(inputs.matrix) }}
|
|
||||||
defaults:
|
|
||||||
run:
|
|
||||||
shell: ${{ matrix.config.shell }}
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v4
|
|
||||||
with:
|
|
||||||
persist-credentials: false
|
|
||||||
|
|
||||||
- name: Download artifact from compilation
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
name: ${{ matrix.config.simple_name }} ${{ matrix.binaries }}
|
|
||||||
path: ${{ matrix.config.simple_name }} ${{ matrix.binaries }}
|
|
||||||
|
|
||||||
- name: Setup msys and install required packages
|
|
||||||
if: runner.os == 'Windows'
|
|
||||||
uses: msys2/setup-msys2@v2
|
|
||||||
with:
|
|
||||||
msystem: ${{ matrix.config.msys_sys }}
|
|
||||||
install: mingw-w64-${{ matrix.config.msys_env }} make git zip
|
|
||||||
|
|
||||||
- name: Create Package
|
|
||||||
run: |
|
|
||||||
mkdir stockfish
|
|
||||||
|
|
||||||
- name: Download wiki
|
|
||||||
run: |
|
|
||||||
git clone https://github.com/official-stockfish/Stockfish.wiki.git wiki
|
|
||||||
rm -rf wiki/.git
|
|
||||||
mv wiki stockfish/
|
|
||||||
|
|
||||||
- name: Copy files
|
|
||||||
run: |
|
|
||||||
mv "${{ matrix.config.simple_name }} ${{ matrix.binaries }}" stockfish-workflow
|
|
||||||
cd stockfish-workflow
|
|
||||||
cp -r src ../stockfish/
|
|
||||||
cp stockfish-$NAME-$BINARY$EXT ../stockfish/
|
|
||||||
cp "Top CPU Contributors.txt" ../stockfish/
|
|
||||||
cp Copying.txt ../stockfish/
|
|
||||||
cp AUTHORS ../stockfish/
|
|
||||||
cp CITATION.cff ../stockfish/
|
|
||||||
cp README.md ../stockfish/
|
|
||||||
cp CONTRIBUTING.md ../stockfish/
|
|
||||||
|
|
||||||
- name: Create tar
|
|
||||||
if: runner.os != 'Windows'
|
|
||||||
run: |
|
|
||||||
chmod +x ./stockfish/stockfish-$NAME-$BINARY$EXT
|
|
||||||
tar -cvf stockfish-$NAME-$BINARY.tar stockfish
|
|
||||||
|
|
||||||
- name: Create zip
|
|
||||||
if: runner.os == 'Windows'
|
|
||||||
run: |
|
|
||||||
zip -r stockfish-$NAME-$BINARY.zip stockfish
|
|
||||||
|
|
||||||
- name: Release
|
|
||||||
if: startsWith(github.ref_name, 'sf_') && github.ref_type == 'tag'
|
|
||||||
uses: softprops/action-gh-release@4634c16e79c963813287e889244c50009e7f0981
|
|
||||||
with:
|
|
||||||
files: stockfish-${{ matrix.config.simple_name }}-${{ matrix.binaries }}.${{ matrix.config.archive_ext }}
|
|
||||||
token: ${{ secrets.token }}
|
|
||||||
|
|
||||||
- name: Get last commit sha
|
|
||||||
id: last_commit
|
|
||||||
run: echo "COMMIT_SHA=$(git rev-parse HEAD | cut -c 1-8)" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Get commit date
|
|
||||||
id: commit_date
|
|
||||||
run: echo "COMMIT_DATE=$(git show -s --date=format:'%Y%m%d' --format=%cd HEAD)" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
# Make sure that an old ci that still runs on master doesn't recreate a prerelease
|
|
||||||
- name: Check Pullable Commits
|
|
||||||
id: check_commits
|
|
||||||
run: |
|
|
||||||
git fetch
|
|
||||||
CHANGES=$(git rev-list HEAD..origin/master --count)
|
|
||||||
echo "CHANGES=$CHANGES" >> $GITHUB_ENV
|
|
||||||
|
|
||||||
- name: Prerelease
|
|
||||||
if: github.ref_name == 'master' && env.CHANGES == '0'
|
|
||||||
continue-on-error: true
|
|
||||||
uses: softprops/action-gh-release@4634c16e79c963813287e889244c50009e7f0981
|
|
||||||
with:
|
|
||||||
name: Stockfish dev-${{ env.COMMIT_DATE }}-${{ env.COMMIT_SHA }}
|
|
||||||
tag_name: stockfish-dev-${{ env.COMMIT_DATE }}-${{ env.COMMIT_SHA }}
|
|
||||||
prerelease: true
|
|
||||||
files: stockfish-${{ matrix.config.simple_name }}-${{ matrix.binaries }}.${{ matrix.config.archive_ext }}
|
|
||||||
token: ${{ secrets.token }}
|
|
||||||
-12
@@ -1,12 +0,0 @@
|
|||||||
# Files from build
|
|
||||||
**/*.o
|
|
||||||
**/*.s
|
|
||||||
src/.depend
|
|
||||||
|
|
||||||
# Built binary
|
|
||||||
src/stockfish*
|
|
||||||
src/-lstdc++.res
|
|
||||||
|
|
||||||
# Neural network for the NNUE evaluation
|
|
||||||
**/*.nnue
|
|
||||||
|
|
||||||
@@ -1,248 +0,0 @@
|
|||||||
# Founders of the Stockfish project and Fishtest infrastructure
|
|
||||||
Tord Romstad (romstad)
|
|
||||||
Marco Costalba (mcostalba)
|
|
||||||
Joona Kiiski (zamar)
|
|
||||||
Gary Linscott (glinscott)
|
|
||||||
|
|
||||||
# Authors and inventors of NNUE, training, and NNUE port
|
|
||||||
Yu Nasu (ynasu87)
|
|
||||||
Motohiro Isozaki (yaneurao)
|
|
||||||
Hisayori Noda (nodchip)
|
|
||||||
|
|
||||||
# All other authors of Stockfish code (in alphabetical order)
|
|
||||||
Aditya (absimaldata)
|
|
||||||
Adrian Petrescu (apetresc)
|
|
||||||
Ahmed Kerimov (wcdbmv)
|
|
||||||
Ajith Chandy Jose (ajithcj)
|
|
||||||
Alain Savard (Rocky640)
|
|
||||||
Alayan Feh (Alayan-stk-2)
|
|
||||||
Alexander Kure
|
|
||||||
Alexander Pagel (Lolligerhans)
|
|
||||||
Alfredo Menezes (lonfom169)
|
|
||||||
Ali AlZhrani (Cooffe)
|
|
||||||
Andreas Jan van der Meulen (Andyson007)
|
|
||||||
Andreas Matthies (Matthies)
|
|
||||||
Andrei Vetrov (proukornew)
|
|
||||||
Andrew Grant (AndyGrant)
|
|
||||||
Andrey Neporada (nepal)
|
|
||||||
Andy Duplain
|
|
||||||
Antoine Champion (antoinechampion)
|
|
||||||
Aram Tumanian (atumanian)
|
|
||||||
Arjun Temurnikar
|
|
||||||
Artem Solopiy (EntityFX)
|
|
||||||
Auguste Pop
|
|
||||||
Balazs Szilagyi
|
|
||||||
Balint Pfliegel
|
|
||||||
Ben Chaney (Chaneybenjamini)
|
|
||||||
Ben Koshy (BKSpurgeon)
|
|
||||||
Bill Henry (VoyagerOne)
|
|
||||||
Bojun Guo (noobpwnftw, Nooby)
|
|
||||||
borg323
|
|
||||||
Boštjan Mejak (PedanticHacker)
|
|
||||||
braich
|
|
||||||
Brian Sheppard (SapphireBrand, briansheppard-toast)
|
|
||||||
Bruno de Melo Costa (BM123499)
|
|
||||||
Bruno Pellanda (pellanda)
|
|
||||||
Bryan Cross (crossbr)
|
|
||||||
candirufish
|
|
||||||
Chess13234
|
|
||||||
Chris Cain (ceebo)
|
|
||||||
Ciekce
|
|
||||||
clefrks
|
|
||||||
Clemens L. (rn5f107s2)
|
|
||||||
Cody Ho (aesrentai)
|
|
||||||
Dale Weiler (graphitemaster)
|
|
||||||
Daniel Axtens (daxtens)
|
|
||||||
Daniel Dugovic (ddugovic)
|
|
||||||
Daniel Monroe (Ergodice)
|
|
||||||
Dan Schmidt (dfannius)
|
|
||||||
Dariusz Orzechowski (dorzechowski)
|
|
||||||
David (dav1312)
|
|
||||||
David Zar
|
|
||||||
Daylen Yang (daylen)
|
|
||||||
Deshawn Mohan-Smith (GoldenRare)
|
|
||||||
Dieter Dobbelaere (ddobbelaere)
|
|
||||||
DiscanX
|
|
||||||
Dominik Schlösser (domschl)
|
|
||||||
double-beep
|
|
||||||
Douglas Matos Gomes (dsmsgms)
|
|
||||||
Dubslow
|
|
||||||
Eduardo Cáceres (eduherminio)
|
|
||||||
Eelco de Groot (KingDefender)
|
|
||||||
Ehsan Rashid (erashid)
|
|
||||||
Elvin Liu (solarlight2)
|
|
||||||
erbsenzaehler
|
|
||||||
Ernesto Gatti
|
|
||||||
evqsx
|
|
||||||
Fabian Beuke (madnight)
|
|
||||||
Fabian Fichter (ianfab)
|
|
||||||
Fanael Linithien (Fanael)
|
|
||||||
fanon
|
|
||||||
Fauzi Akram Dabat (fauzi2)
|
|
||||||
Felix Wittmann
|
|
||||||
gamander
|
|
||||||
Gabriele Lombardo (gabe)
|
|
||||||
Gahtan Nahdi
|
|
||||||
Gary Heckman (gheckman)
|
|
||||||
George Sobala (gsobala)
|
|
||||||
gguliash
|
|
||||||
Giacomo Lorenzetti (G-Lorenz)
|
|
||||||
Gian-Carlo Pascutto (gcp)
|
|
||||||
Goh CJ (cj5716)
|
|
||||||
Gontran Lemaire (gonlem)
|
|
||||||
Goodkov Vasiliy Aleksandrovich (goodkov)
|
|
||||||
Gregor Cramer
|
|
||||||
GuardianRM
|
|
||||||
Guy Vreuls (gvreuls)
|
|
||||||
Günther Demetz (pb00067, pb00068)
|
|
||||||
Henri Wiechers
|
|
||||||
Hiraoka Takuya (HiraokaTakuya)
|
|
||||||
homoSapiensSapiens
|
|
||||||
Hongzhi Cheng
|
|
||||||
Ivan Ivec (IIvec)
|
|
||||||
Jacques B. (Timshel)
|
|
||||||
Jake Senne (w1wwwwww)
|
|
||||||
Jan Ondruš (hxim)
|
|
||||||
Jared Kish (Kurtbusch, kurt22i)
|
|
||||||
Jarrod Torriero (DU-jdto)
|
|
||||||
Jasper Shovelton (Beanie496)
|
|
||||||
Jean-Francois Romang (jromang)
|
|
||||||
Jean Gauthier (OuaisBla)
|
|
||||||
Jekaa
|
|
||||||
Jerry Donald Watson (jerrydonaldwatson)
|
|
||||||
jjoshua2
|
|
||||||
Jonathan Buladas Dumale (SFisGOD)
|
|
||||||
Jonathan Calovski (Mysseno)
|
|
||||||
Jonathan McDermid (jonathanmcdermid)
|
|
||||||
Joost VandeVondele (vondele)
|
|
||||||
Joseph Ellis (jhellis3)
|
|
||||||
Joseph R. Prostko
|
|
||||||
Jörg Oster (joergoster)
|
|
||||||
Julian Willemer (NightlyKing)
|
|
||||||
jundery
|
|
||||||
Justin Blanchard (UncombedCoconut)
|
|
||||||
Kelly Wilson
|
|
||||||
Ken Takusagawa
|
|
||||||
Kian E (KJE-98)
|
|
||||||
kinderchocolate
|
|
||||||
Kiran Panditrao (Krgp)
|
|
||||||
Kojirion
|
|
||||||
Krystian Kuzniarek (kuzkry)
|
|
||||||
Leonardo Ljubičić (ICCF World Champion)
|
|
||||||
Leonid Pechenik (lp--)
|
|
||||||
Li Ying (yl25946)
|
|
||||||
Liam Keegan (lkeegan)
|
|
||||||
Linmiao Xu (linrock)
|
|
||||||
Linus Arver (listx)
|
|
||||||
loco-loco
|
|
||||||
Lub van den Berg (ElbertoOne)
|
|
||||||
Luca Brivio (lucabrivio)
|
|
||||||
Lucas Braesch (lucasart)
|
|
||||||
Lyudmil Antonov (lantonov)
|
|
||||||
Maciej Żenczykowski (zenczykowski)
|
|
||||||
Malcolm Campbell (xoto10)
|
|
||||||
Mark Tenzer (31m059)
|
|
||||||
marotear
|
|
||||||
Matt Ginsberg (mattginsberg)
|
|
||||||
Matthew Lai (matthewlai)
|
|
||||||
Matthew Sullivan (Matt14916)
|
|
||||||
Max A. (Disservin)
|
|
||||||
Maxim Masiutin (maximmasiutin)
|
|
||||||
Maxim Molchanov (Maxim)
|
|
||||||
Michael An (man)
|
|
||||||
Michael Byrne (MichaelB7)
|
|
||||||
Michael Chaly (Vizvezdenec)
|
|
||||||
Michael Stembera (mstembera)
|
|
||||||
Michael Whiteley (protonspring)
|
|
||||||
Michel Van den Bergh (vdbergh)
|
|
||||||
Miguel Lahoz (miguel-l)
|
|
||||||
Mikael Bäckman (mbootsector)
|
|
||||||
Mike Babigian (Farseer)
|
|
||||||
Mira
|
|
||||||
Miroslav Fontán (Hexik)
|
|
||||||
Moez Jellouli (MJZ1977)
|
|
||||||
Mohammed Li (tthsqe12)
|
|
||||||
Muzhen J (XInTheDark)
|
|
||||||
Nathan Rugg (nmrugg)
|
|
||||||
Nguyen Pham (nguyenpham)
|
|
||||||
Nicklas Persson (NicklasPersson)
|
|
||||||
Nick Pelling (nickpelling)
|
|
||||||
Niklas Fiekas (niklasf)
|
|
||||||
Nikolay Kostov (NikolayIT)
|
|
||||||
Norman Schmidt (FireFather)
|
|
||||||
notruck
|
|
||||||
Nour Berakdar (Nonlinear)
|
|
||||||
Ofek Shochat (OfekShochat, ghostway)
|
|
||||||
Ondrej Mosnáček (WOnder93)
|
|
||||||
Ondřej Mišina (AndrovT)
|
|
||||||
Oskar Werkelin Ahlin
|
|
||||||
Pablo Vazquez
|
|
||||||
Panthee
|
|
||||||
Pascal Romaret
|
|
||||||
Pasquale Pigazzini (ppigazzini)
|
|
||||||
Patrick Jansen (mibere)
|
|
||||||
Peter Schneider (pschneider1968)
|
|
||||||
Peter Zsifkovits (CoffeeOne)
|
|
||||||
PikaCat
|
|
||||||
Praveen Kumar Tummala (praveentml)
|
|
||||||
Prokop Randáček (ProkopRandacek)
|
|
||||||
Rahul Dsilva (silversolver1)
|
|
||||||
Ralph Stößer (Ralph Stoesser)
|
|
||||||
Raminder Singh
|
|
||||||
renouve
|
|
||||||
Reuven Peleg (R-Peleg)
|
|
||||||
Richard Lloyd (Richard-Lloyd)
|
|
||||||
Robert Nürnberg (robertnurnberg)
|
|
||||||
Rodrigo Exterckötter Tjäder
|
|
||||||
Rodrigo Roim (roim)
|
|
||||||
Ronald de Man (syzygy1, syzygy)
|
|
||||||
Ron Britvich (Britvich)
|
|
||||||
rqs
|
|
||||||
Rui Coelho (ruicoelhopedro)
|
|
||||||
Ryan Schmitt
|
|
||||||
Ryan Takker
|
|
||||||
Sami Kiminki (skiminki)
|
|
||||||
Sebastian Buchwald (UniQP)
|
|
||||||
Sergei Antonov (saproj)
|
|
||||||
Sergei Ivanov (svivanov72)
|
|
||||||
Sergio Vieri (sergiovieri)
|
|
||||||
sf-x
|
|
||||||
Shahin M. Shahin (peregrine)
|
|
||||||
Shane Booth (shane31)
|
|
||||||
Shawn Varghese (xXH4CKST3RXx)
|
|
||||||
Shawn Xu (xu-shawn)
|
|
||||||
Siad Daboul (Topologist)
|
|
||||||
Stefan Geschwentner (locutus2)
|
|
||||||
Stefano Cardanobile (Stefano80)
|
|
||||||
Stefano Di Martino (StefanoD)
|
|
||||||
Steinar Gunderson (sesse)
|
|
||||||
Stéphane Nicolet (snicolet)
|
|
||||||
Stephen Touset (stouset)
|
|
||||||
Syine Mineta (MinetaS)
|
|
||||||
Taras Vuk (TarasVuk)
|
|
||||||
Thanar2
|
|
||||||
thaspel
|
|
||||||
theo77186
|
|
||||||
TierynnB
|
|
||||||
Ting-Hsuan Huang (fffelix-huang)
|
|
||||||
Tobias Steinmann
|
|
||||||
Tomasz Sobczyk (Sopel97)
|
|
||||||
Tom Truscott
|
|
||||||
Tom Vijlbrief (tomtor)
|
|
||||||
Torsten Franz (torfranz, tfranzer)
|
|
||||||
Torsten Hellwig (Torom)
|
|
||||||
Tracey Emery (basepr1me)
|
|
||||||
tttak
|
|
||||||
Unai Corzo (unaiic)
|
|
||||||
Uri Blass (uriblass)
|
|
||||||
Vince Negri (cuddlestmonkey)
|
|
||||||
Viren
|
|
||||||
windfishballad
|
|
||||||
xefoci7612
|
|
||||||
Xiang Wang (KatyushaScarlet)
|
|
||||||
zz4032
|
|
||||||
|
|
||||||
# Additionally, we acknowledge the authors and maintainers of fishtest,
|
|
||||||
# an amazing and essential framework for Stockfish development!
|
|
||||||
#
|
|
||||||
# https://github.com/official-stockfish/fishtest/blob/master/AUTHORS
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
# This CITATION.cff file was generated with cffinit.
|
|
||||||
# Visit https://bit.ly/cffinit to generate yours today!
|
|
||||||
|
|
||||||
cff-version: 1.2.0
|
|
||||||
title: Stockfish
|
|
||||||
message: >-
|
|
||||||
Please cite this software using the metadata from this
|
|
||||||
file.
|
|
||||||
type: software
|
|
||||||
authors:
|
|
||||||
- name: The Stockfish developers (see AUTHORS file)
|
|
||||||
repository-code: 'https://github.com/official-stockfish/Stockfish'
|
|
||||||
url: 'https://stockfishchess.org/'
|
|
||||||
repository-artifact: 'https://stockfishchess.org/download/'
|
|
||||||
abstract: Stockfish is a free and strong UCI chess engine.
|
|
||||||
keywords:
|
|
||||||
- chess
|
|
||||||
- artificial intelligence (AI)
|
|
||||||
- tree search
|
|
||||||
- alpha-beta search
|
|
||||||
- neural networks (NN)
|
|
||||||
- efficiently updatable neural networks (NNUE)
|
|
||||||
license: GPL-3.0
|
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
# Contributing to Stockfish
|
|
||||||
|
|
||||||
Welcome to the Stockfish project! We are excited that you are interested in
|
|
||||||
contributing. This document outlines the guidelines and steps to follow when
|
|
||||||
making contributions to Stockfish.
|
|
||||||
|
|
||||||
## Table of Contents
|
|
||||||
|
|
||||||
- [Building Stockfish](#building-stockfish)
|
|
||||||
- [Making Contributions](#making-contributions)
|
|
||||||
- [Reporting Issues](#reporting-issues)
|
|
||||||
- [Submitting Pull Requests](#submitting-pull-requests)
|
|
||||||
- [Code Style](#code-style)
|
|
||||||
- [Community and Communication](#community-and-communication)
|
|
||||||
- [License](#license)
|
|
||||||
|
|
||||||
## Building Stockfish
|
|
||||||
|
|
||||||
In case you do not have a C++ compiler installed, you can follow the
|
|
||||||
instructions from our wiki.
|
|
||||||
|
|
||||||
- [Ubuntu][ubuntu-compiling-link]
|
|
||||||
- [Windows][windows-compiling-link]
|
|
||||||
- [macOS][macos-compiling-link]
|
|
||||||
|
|
||||||
## Making Contributions
|
|
||||||
|
|
||||||
### Reporting Issues
|
|
||||||
|
|
||||||
If you find a bug, please open an issue on the
|
|
||||||
[issue tracker][issue-tracker-link]. Be sure to include relevant information
|
|
||||||
like your operating system, build environment, and a detailed description of the
|
|
||||||
problem.
|
|
||||||
|
|
||||||
_Please note that Stockfish's development is not focused on adding new features.
|
|
||||||
Thus any issue regarding missing features will potentially be closed without
|
|
||||||
further discussion._
|
|
||||||
|
|
||||||
### Submitting Pull Requests
|
|
||||||
|
|
||||||
- Functional changes need to be tested on fishtest. See
|
|
||||||
[Creating my First Test][creating-my-first-test] for more details.
|
|
||||||
The accompanying pull request should include a link to the test results and
|
|
||||||
the new bench.
|
|
||||||
|
|
||||||
- Non-functional changes (e.g. refactoring, code style, documentation) do not
|
|
||||||
need to be tested on fishtest, unless they might impact performance.
|
|
||||||
|
|
||||||
- Provide a clear and concise description of the changes in the pull request
|
|
||||||
description.
|
|
||||||
|
|
||||||
_First time contributors should add their name to [AUTHORS](../AUTHORS)._
|
|
||||||
|
|
||||||
_Stockfish's development is not focused on adding new features. Thus any pull
|
|
||||||
request introducing new features will potentially be closed without further
|
|
||||||
discussion._
|
|
||||||
|
|
||||||
## Code Style
|
|
||||||
|
|
||||||
Changes to Stockfish C++ code should respect our coding style defined by
|
|
||||||
[.clang-format](.clang-format). You can format your changes by running
|
|
||||||
`make format`. This requires clang-format version 18 to be installed on your system.
|
|
||||||
|
|
||||||
## Navigate
|
|
||||||
|
|
||||||
For experienced Git users who frequently use git blame, it is recommended to
|
|
||||||
configure the blame.ignoreRevsFile setting.
|
|
||||||
This setting is useful for excluding noisy formatting commits.
|
|
||||||
|
|
||||||
```bash
|
|
||||||
git config blame.ignoreRevsFile .git-blame-ignore-revs
|
|
||||||
```
|
|
||||||
|
|
||||||
## Community and Communication
|
|
||||||
|
|
||||||
- Join the [Stockfish discord][discord-link] to discuss ideas, issues, and
|
|
||||||
development.
|
|
||||||
- Participate in the [Stockfish GitHub discussions][discussions-link] for
|
|
||||||
broader conversations.
|
|
||||||
|
|
||||||
## License
|
|
||||||
|
|
||||||
By contributing to Stockfish, you agree that your contributions will be licensed
|
|
||||||
under the GNU General Public License v3.0. See [Copying.txt][copying-link] for
|
|
||||||
more details.
|
|
||||||
|
|
||||||
Thank you for contributing to Stockfish and helping us make it even better!
|
|
||||||
|
|
||||||
|
|
||||||
[copying-link]: https://github.com/official-stockfish/Stockfish/blob/master/Copying.txt
|
|
||||||
[discord-link]: https://discord.gg/GWDRS3kU6R
|
|
||||||
[discussions-link]: https://github.com/official-stockfish/Stockfish/discussions/new
|
|
||||||
[creating-my-first-test]: https://github.com/official-stockfish/fishtest/wiki/Creating-my-first-test#create-your-test
|
|
||||||
[issue-tracker-link]: https://github.com/official-stockfish/Stockfish/issues
|
|
||||||
[ubuntu-compiling-link]: https://github.com/official-stockfish/Stockfish/wiki/Developers#user-content-installing-a-compiler-1
|
|
||||||
[windows-compiling-link]: https://github.com/official-stockfish/Stockfish/wiki/Developers#user-content-installing-a-compiler
|
|
||||||
[macos-compiling-link]: https://github.com/official-stockfish/Stockfish/wiki/Developers#user-content-installing-a-compiler-2
|
|
||||||
+674
-674
File diff suppressed because it is too large
Load Diff
@@ -1,154 +0,0 @@
|
|||||||
<div align="center">
|
|
||||||
|
|
||||||
[![Stockfish][stockfish128-logo]][website-link]
|
|
||||||
|
|
||||||
<h3>Stockfish</h3>
|
|
||||||
|
|
||||||
A free and strong UCI chess engine.
|
|
||||||
<br>
|
|
||||||
<strong>[Explore Stockfish docs »][wiki-link]</strong>
|
|
||||||
<br>
|
|
||||||
<br>
|
|
||||||
[Report bug][issue-link]
|
|
||||||
·
|
|
||||||
[Open a discussion][discussions-link]
|
|
||||||
·
|
|
||||||
[Discord][discord-link]
|
|
||||||
·
|
|
||||||
[Blog][website-blog-link]
|
|
||||||
|
|
||||||
[![Build][build-badge]][build-link]
|
|
||||||
[![License][license-badge]][license-link]
|
|
||||||
<br>
|
|
||||||
[![Release][release-badge]][release-link]
|
|
||||||
[![Commits][commits-badge]][commits-link]
|
|
||||||
<br>
|
|
||||||
[![Website][website-badge]][website-link]
|
|
||||||
[![Fishtest][fishtest-badge]][fishtest-link]
|
|
||||||
[![Discord][discord-badge]][discord-link]
|
|
||||||
|
|
||||||
</div>
|
|
||||||
|
|
||||||
## Overview
|
|
||||||
|
|
||||||
[Stockfish][website-link] is a **free and strong UCI chess engine** derived from
|
|
||||||
Glaurung 2.1 that analyzes chess positions and computes the optimal moves.
|
|
||||||
|
|
||||||
Stockfish **does not include a graphical user interface** (GUI) that is required
|
|
||||||
to display a chessboard and to make it easy to input moves. These GUIs are
|
|
||||||
developed independently from Stockfish and are available online. **Read the
|
|
||||||
documentation for your GUI** of choice for information about how to use
|
|
||||||
Stockfish with it.
|
|
||||||
|
|
||||||
See also the Stockfish [documentation][wiki-usage-link] for further usage help.
|
|
||||||
|
|
||||||
## Files
|
|
||||||
|
|
||||||
This distribution of Stockfish consists of the following files:
|
|
||||||
|
|
||||||
* [README.md][readme-link], the file you are currently reading.
|
|
||||||
|
|
||||||
* [Copying.txt][license-link], a text file containing the GNU General Public
|
|
||||||
License version 3.
|
|
||||||
|
|
||||||
* [AUTHORS][authors-link], a text file with the list of authors for the project.
|
|
||||||
|
|
||||||
* [src][src-link], a subdirectory containing the full source code, including a
|
|
||||||
Makefile that can be used to compile Stockfish on Unix-like systems.
|
|
||||||
|
|
||||||
* a file with the .nnue extension, storing the neural network for the NNUE
|
|
||||||
evaluation. Binary distributions will have this file embedded.
|
|
||||||
|
|
||||||
## Contributing
|
|
||||||
|
|
||||||
__See [Contributing Guide](CONTRIBUTING.md).__
|
|
||||||
|
|
||||||
### Donating hardware
|
|
||||||
|
|
||||||
Improving Stockfish requires a massive amount of testing. You can donate your
|
|
||||||
hardware resources by installing the [Fishtest Worker][worker-link] and viewing
|
|
||||||
the current tests on [Fishtest][fishtest-link].
|
|
||||||
|
|
||||||
### Improving the code
|
|
||||||
|
|
||||||
In the [chessprogramming wiki][programming-link], many techniques used in
|
|
||||||
Stockfish are explained with a lot of background information.
|
|
||||||
The [section on Stockfish][programmingsf-link] describes many features
|
|
||||||
and techniques used by Stockfish. However, it is generic rather than
|
|
||||||
focused on Stockfish's precise implementation.
|
|
||||||
|
|
||||||
The engine testing is done on [Fishtest][fishtest-link].
|
|
||||||
If you want to help improve Stockfish, please read this [guideline][guideline-link]
|
|
||||||
first, where the basics of Stockfish development are explained.
|
|
||||||
|
|
||||||
Discussions about Stockfish take place these days mainly in the Stockfish
|
|
||||||
[Discord server][discord-link]. This is also the best place to ask questions
|
|
||||||
about the codebase and how to improve it.
|
|
||||||
|
|
||||||
## Compiling Stockfish
|
|
||||||
|
|
||||||
Stockfish has support for 32 or 64-bit CPUs, certain hardware instructions,
|
|
||||||
big-endian machines such as Power PC, and other platforms.
|
|
||||||
|
|
||||||
On Unix-like systems, it should be easy to compile Stockfish directly from the
|
|
||||||
source code with the included Makefile in the folder `src`. In general, it is
|
|
||||||
recommended to run `make help` to see a list of make targets with corresponding
|
|
||||||
descriptions. An example suitable for most Intel and AMD chips:
|
|
||||||
|
|
||||||
```
|
|
||||||
cd src
|
|
||||||
make -j profile-build ARCH=x86-64-avx2
|
|
||||||
```
|
|
||||||
|
|
||||||
Detailed compilation instructions for all platforms can be found in our
|
|
||||||
[documentation][wiki-compile-link]. Our wiki also has information about
|
|
||||||
the [UCI commands][wiki-uci-link] supported by Stockfish.
|
|
||||||
|
|
||||||
## Terms of use
|
|
||||||
|
|
||||||
Stockfish is free and distributed under the
|
|
||||||
[**GNU General Public License version 3**][license-link] (GPL v3). Essentially,
|
|
||||||
this means 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 website, 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 license and the full source code (or a pointer to
|
|
||||||
where the source code can be found) to generate the exact binary you are
|
|
||||||
distributing. If you make any changes to the source code, these changes must
|
|
||||||
also be made available under GPL v3.
|
|
||||||
|
|
||||||
|
|
||||||
[authors-link]: https://github.com/official-stockfish/Stockfish/blob/master/AUTHORS
|
|
||||||
[build-link]: https://github.com/official-stockfish/Stockfish/actions/workflows/stockfish.yml
|
|
||||||
[commits-link]: https://github.com/official-stockfish/Stockfish/commits/master
|
|
||||||
[discord-link]: https://discord.gg/GWDRS3kU6R
|
|
||||||
[issue-link]: https://github.com/official-stockfish/Stockfish/issues/new?assignees=&labels=&template=BUG-REPORT.yml
|
|
||||||
[discussions-link]: https://github.com/official-stockfish/Stockfish/discussions/new
|
|
||||||
[fishtest-link]: https://tests.stockfishchess.org/tests
|
|
||||||
[guideline-link]: https://github.com/official-stockfish/fishtest/wiki/Creating-my-first-test
|
|
||||||
[license-link]: https://github.com/official-stockfish/Stockfish/blob/master/Copying.txt
|
|
||||||
[programming-link]: https://www.chessprogramming.org/Main_Page
|
|
||||||
[programmingsf-link]: https://www.chessprogramming.org/Stockfish
|
|
||||||
[readme-link]: https://github.com/official-stockfish/Stockfish/blob/master/README.md
|
|
||||||
[release-link]: https://github.com/official-stockfish/Stockfish/releases/latest
|
|
||||||
[src-link]: https://github.com/official-stockfish/Stockfish/tree/master/src
|
|
||||||
[stockfish128-logo]: https://stockfishchess.org/images/logo/icon_128x128.png
|
|
||||||
[uci-link]: https://backscattering.de/chess/uci/
|
|
||||||
[website-link]: https://stockfishchess.org
|
|
||||||
[website-blog-link]: https://stockfishchess.org/blog/
|
|
||||||
[wiki-link]: https://github.com/official-stockfish/Stockfish/wiki
|
|
||||||
[wiki-compile-link]: https://github.com/official-stockfish/Stockfish/wiki/Compiling-from-source
|
|
||||||
[wiki-uci-link]: https://github.com/official-stockfish/Stockfish/wiki/UCI-&-Commands
|
|
||||||
[wiki-usage-link]: https://github.com/official-stockfish/Stockfish/wiki/Download-and-usage
|
|
||||||
[worker-link]: https://github.com/official-stockfish/fishtest/wiki/Running-the-worker
|
|
||||||
|
|
||||||
[build-badge]: https://img.shields.io/github/actions/workflow/status/official-stockfish/Stockfish/stockfish.yml?branch=master&style=for-the-badge&label=stockfish&logo=github
|
|
||||||
[commits-badge]: https://img.shields.io/github/commits-since/official-stockfish/Stockfish/latest?style=for-the-badge
|
|
||||||
[discord-badge]: https://img.shields.io/discord/435943710472011776?style=for-the-badge&label=discord&logo=Discord
|
|
||||||
[fishtest-badge]: https://img.shields.io/website?style=for-the-badge&down_color=red&down_message=Offline&label=Fishtest&up_color=success&up_message=Online&url=https%3A%2F%2Ftests.stockfishchess.org%2Ftests%2Ffinished
|
|
||||||
[license-badge]: https://img.shields.io/github/license/official-stockfish/Stockfish?style=for-the-badge&label=license&color=success
|
|
||||||
[release-badge]: https://img.shields.io/github/v/release/official-stockfish/Stockfish?style=for-the-badge&label=official%20release
|
|
||||||
[website-badge]: https://img.shields.io/website?style=for-the-badge&down_color=red&down_message=Offline&label=website&up_color=success&up_message=Online&url=https%3A%2F%2Fstockfishchess.org
|
|
||||||
+90
@@ -0,0 +1,90 @@
|
|||||||
|
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, Jos�, 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 8 CPUs, but has not been
|
||||||
|
tested thoroughly with more than 2. 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 four threads, it
|
||||||
|
is recommended to raise the value of "Minimum Split Depth" UCI parameter
|
||||||
|
to 6.
|
||||||
|
|
||||||
|
|
||||||
|
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 experimental 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.
|
||||||
|
|
||||||
|
For big-endian machines like Power PC you need to enable the proper
|
||||||
|
flag changing from -DNBIGENDIAN to -DBIGENDIAN in the Makefile.
|
||||||
|
|
||||||
|
Stockfish has POPCNT instruction runtime detection and support. This can
|
||||||
|
give an extra speed on Core i7 or similar systems. To enable this feature
|
||||||
|
compile with 'make icc-profile-popcnt'
|
||||||
|
|
||||||
|
On 64 bit Unix-like systems the 'bsfq' assembly instruction will be used
|
||||||
|
for bit counting. Detection is automatic at compile time, but in case you
|
||||||
|
experience compile problems you can comment out #define USE_BSFQ line in types.h
|
||||||
|
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
|
||||||
|
6. Feedback
|
||||||
|
-----------
|
||||||
|
|
||||||
|
The author's e-mail address is mcostalba@gmail.com
|
||||||
@@ -1,301 +0,0 @@
|
|||||||
Contributors to Fishtest with >10,000 CPU hours, as of 2024-08-31.
|
|
||||||
Thank you!
|
|
||||||
|
|
||||||
Username CPU Hours Games played
|
|
||||||
------------------------------------------------------------------
|
|
||||||
noobpwnftw 40428649 3164740143
|
|
||||||
technologov 23581394 1076895482
|
|
||||||
vdv 19425375 718302718
|
|
||||||
linrock 10034115 643194527
|
|
||||||
mlang 3026000 200065824
|
|
||||||
okrout 2572676 237511408
|
|
||||||
pemo 1836785 62226157
|
|
||||||
dew 1689162 100033738
|
|
||||||
TueRens 1648780 77891164
|
|
||||||
sebastronomy 1468328 60859092
|
|
||||||
grandphish2 1466110 91776075
|
|
||||||
JojoM 1130625 73666098
|
|
||||||
olafm 1067009 74807270
|
|
||||||
tvijlbrief 796125 51897690
|
|
||||||
oz 781847 53910686
|
|
||||||
rpngn 768460 49812975
|
|
||||||
gvreuls 751085 52177668
|
|
||||||
mibere 703840 46867607
|
|
||||||
leszek 566598 42024615
|
|
||||||
cw 519601 34988161
|
|
||||||
fastgm 503862 30260818
|
|
||||||
CSU_Dynasty 468784 31385034
|
|
||||||
maximmasiutin 439192 27893522
|
|
||||||
ctoks 435148 28541909
|
|
||||||
crunchy 427414 27371625
|
|
||||||
bcross 415724 29061187
|
|
||||||
robal 371112 24642270
|
|
||||||
mgrabiak 367963 26464704
|
|
||||||
velislav 342588 22140902
|
|
||||||
ncfish1 329039 20624527
|
|
||||||
Fisherman 327231 21829379
|
|
||||||
Dantist 296386 18031762
|
|
||||||
tolkki963 262050 22049676
|
|
||||||
Sylvain27 255595 8864404
|
|
||||||
nordlandia 249322 16420192
|
|
||||||
Fifis 237657 13065577
|
|
||||||
marrco 234581 17714473
|
|
||||||
Calis007 217537 14450582
|
|
||||||
glinscott 208125 13277240
|
|
||||||
drabel 204167 13930674
|
|
||||||
mhoram 202894 12601997
|
|
||||||
bking_US 198894 11876016
|
|
||||||
Thanar 179852 12365359
|
|
||||||
javran 169679 13481966
|
|
||||||
armo9494 162863 10937118
|
|
||||||
spams 157128 10319326
|
|
||||||
DesolatedDodo 156683 10211206
|
|
||||||
Wencey 152308 8375444
|
|
||||||
sqrt2 147963 9724586
|
|
||||||
vdbergh 140311 9225125
|
|
||||||
jcAEie 140086 10603658
|
|
||||||
CoffeeOne 137100 5024116
|
|
||||||
malala 136182 8002293
|
|
||||||
xoto 133759 9159372
|
|
||||||
Dubslow 129614 8519312
|
|
||||||
davar 129023 8376525
|
|
||||||
DMBK 122960 8980062
|
|
||||||
dsmith 122059 7570238
|
|
||||||
CypressChess 120784 8672620
|
|
||||||
sschnee 120526 7547722
|
|
||||||
maposora 119734 10749710
|
|
||||||
amicic 119661 7938029
|
|
||||||
Wolfgang 115713 8159062
|
|
||||||
Data 113305 8220352
|
|
||||||
BrunoBanani 112960 7436849
|
|
||||||
markkulix 112897 9133168
|
|
||||||
cuistot 109802 7121030
|
|
||||||
skiminki 107583 7218170
|
|
||||||
sterni1971 104431 5938282
|
|
||||||
MaZePallas 102823 6633619
|
|
||||||
sunu 100167 7040199
|
|
||||||
zeryl 99331 6221261
|
|
||||||
thirdlife 99156 2245320
|
|
||||||
ElbertoOne 99028 7023771
|
|
||||||
megaman7de 98456 6675076
|
|
||||||
Goatminola 96765 8257832
|
|
||||||
bigpen0r 94825 6529241
|
|
||||||
brabos 92118 6186135
|
|
||||||
Maxim 90818 3283364
|
|
||||||
psk 89957 5984901
|
|
||||||
racerschmacer 85805 6122790
|
|
||||||
Vizvezdenec 83761 5344740
|
|
||||||
0x3C33 82614 5271253
|
|
||||||
szupaw 82495 7151686
|
|
||||||
BRAVONE 81239 5054681
|
|
||||||
nssy 76497 5259388
|
|
||||||
cody 76126 4492126
|
|
||||||
jromang 76106 5236025
|
|
||||||
MarcusTullius 76103 5061991
|
|
||||||
woutboat 76072 6022922
|
|
||||||
Spprtr 75977 5252287
|
|
||||||
teddybaer 75125 5407666
|
|
||||||
Pking_cda 73776 5293873
|
|
||||||
yurikvelo 73611 5046822
|
|
||||||
Mineta 71130 4711422
|
|
||||||
Bobo1239 70579 4794999
|
|
||||||
solarlight 70517 5028306
|
|
||||||
dv8silencer 70287 3883992
|
|
||||||
manap 66273 4121774
|
|
||||||
tinker 64333 4268790
|
|
||||||
qurashee 61208 3429862
|
|
||||||
AGI 58195 4329580
|
|
||||||
robnjr 57262 4053117
|
|
||||||
Freja 56938 3733019
|
|
||||||
MaxKlaxxMiner 56879 3423958
|
|
||||||
ttruscott 56010 3680085
|
|
||||||
rkl 55132 4164467
|
|
||||||
jmdana 54697 4012593
|
|
||||||
notchris 53936 4184018
|
|
||||||
renouve 53811 3501516
|
|
||||||
finfish 51360 3370515
|
|
||||||
eva42 51272 3599691
|
|
||||||
eastorwest 51117 3454811
|
|
||||||
rap 49985 3219146
|
|
||||||
pb00067 49733 3298934
|
|
||||||
GPUex 48686 3684998
|
|
||||||
OuaisBla 48626 3445134
|
|
||||||
ronaldjerum 47654 3240695
|
|
||||||
biffhero 46564 3111352
|
|
||||||
oryx 45639 3546530
|
|
||||||
VoyagerOne 45476 3452465
|
|
||||||
speedycpu 43842 3003273
|
|
||||||
jbwiebe 43305 2805433
|
|
||||||
Antihistamine 41788 2761312
|
|
||||||
mhunt 41735 2691355
|
|
||||||
jibarbosa 41640 4145702
|
|
||||||
homyur 39893 2850481
|
|
||||||
gri 39871 2515779
|
|
||||||
DeepnessFulled 39020 3323102
|
|
||||||
Garf 37741 2999686
|
|
||||||
SC 37299 2731694
|
|
||||||
Gaster319 37118 3279678
|
|
||||||
naclosagc 36562 1279618
|
|
||||||
csnodgrass 36207 2688994
|
|
||||||
strelock 34716 2074055
|
|
||||||
gopeto 33717 2245606
|
|
||||||
EthanOConnor 33370 2090311
|
|
||||||
slakovv 32915 2021889
|
|
||||||
jojo2357 32890 2826662
|
|
||||||
shawnxu 32019 2802552
|
|
||||||
Gelma 31771 1551204
|
|
||||||
vidar808 31560 1351810
|
|
||||||
kdave 31157 2198362
|
|
||||||
manapbk 30987 1810399
|
|
||||||
ZacHFX 30966 2272416
|
|
||||||
TataneSan 30713 1513402
|
|
||||||
votoanthuan 30691 2460856
|
|
||||||
Prcuvu 30377 2170122
|
|
||||||
anst 30301 2190091
|
|
||||||
jkiiski 30136 1904470
|
|
||||||
spcc 29925 1901692
|
|
||||||
hyperbolic.tom 29840 2017394
|
|
||||||
chuckstablers 29659 2093438
|
|
||||||
Pyafue 29650 1902349
|
|
||||||
belzedar94 28846 1811530
|
|
||||||
mecevdimitar 27610 1721382
|
|
||||||
chriswk 26902 1868317
|
|
||||||
xwziegtm 26897 2124586
|
|
||||||
achambord 26582 1767323
|
|
||||||
somethingintheshadows 26496 2186404
|
|
||||||
Patrick_G 26276 1801617
|
|
||||||
yorkman 26193 1992080
|
|
||||||
srowen 25743 1490684
|
|
||||||
Ulysses 25413 1702830
|
|
||||||
Jopo12321 25227 1652482
|
|
||||||
SFTUser 25182 1675689
|
|
||||||
nabildanial 25068 1531665
|
|
||||||
Sharaf_DG 24765 1786697
|
|
||||||
rodneyc 24376 1416402
|
|
||||||
jsys14 24297 1721230
|
|
||||||
agg177 23890 1395014
|
|
||||||
AndreasKrug 23754 1890115
|
|
||||||
Ente 23752 1678188
|
|
||||||
JanErik 23408 1703875
|
|
||||||
Isidor 23388 1680691
|
|
||||||
Norabor 23371 1603244
|
|
||||||
WoodMan777 23253 2023048
|
|
||||||
Nullvalue 23155 2022752
|
|
||||||
cisco2015 22920 1763301
|
|
||||||
Zirie 22542 1472937
|
|
||||||
team-oh 22272 1636708
|
|
||||||
Roady 22220 1465606
|
|
||||||
MazeOfGalious 21978 1629593
|
|
||||||
sg4032 21950 1643373
|
|
||||||
tsim67 21747 1330880
|
|
||||||
ianh2105 21725 1632562
|
|
||||||
Skiff84 21711 1014212
|
|
||||||
xor12 21628 1680365
|
|
||||||
dex 21612 1467203
|
|
||||||
nesoneg 21494 1463031
|
|
||||||
user213718 21454 1404128
|
|
||||||
Serpensin 21452 1790510
|
|
||||||
sphinx 21211 1384728
|
|
||||||
qoo_charly_cai 21136 1514927
|
|
||||||
IslandLambda 21062 1220838
|
|
||||||
jjoshua2 21001 1423089
|
|
||||||
Zake9298 20938 1565848
|
|
||||||
horst.prack 20878 1465656
|
|
||||||
fishtester 20729 1348888
|
|
||||||
0xB00B1ES 20590 1208666
|
|
||||||
ols 20477 1195945
|
|
||||||
Dinde 20459 1292774
|
|
||||||
j3corre 20405 941444
|
|
||||||
Adrian.Schmidt123 20316 1281436
|
|
||||||
wei 19973 1745989
|
|
||||||
teenychess 19819 1762006
|
|
||||||
rstoesser 19569 1293588
|
|
||||||
eudhan 19274 1283717
|
|
||||||
vulcan 18871 1729392
|
|
||||||
wizardassassin 18795 1376884
|
|
||||||
Karpovbot 18766 1053178
|
|
||||||
jundery 18445 1115855
|
|
||||||
mkstockfishtester 18350 1690676
|
|
||||||
ville 17883 1384026
|
|
||||||
chris 17698 1487385
|
|
||||||
purplefishies 17595 1092533
|
|
||||||
dju 17414 981289
|
|
||||||
iisiraider 17275 1049015
|
|
||||||
DragonLord 17014 1162790
|
|
||||||
Karby 17008 1013160
|
|
||||||
pirt 16965 1271519
|
|
||||||
redstone59 16842 1461780
|
|
||||||
Alb11747 16787 1213990
|
|
||||||
Naven94 16414 951718
|
|
||||||
scuzzi 16115 994341
|
|
||||||
IgorLeMasson 16064 1147232
|
|
||||||
ako027ako 15671 1173203
|
|
||||||
infinigon 15285 965966
|
|
||||||
Nikolay.IT 15154 1068349
|
|
||||||
Andrew Grant 15114 895539
|
|
||||||
OssumOpossum 14857 1007129
|
|
||||||
LunaticBFF57 14525 1190310
|
|
||||||
enedene 14476 905279
|
|
||||||
Hjax 14394 1005013
|
|
||||||
bpfliegel 14233 882523
|
|
||||||
YELNAMRON 14230 1128094
|
|
||||||
mpx86 14019 759568
|
|
||||||
jpulman 13982 870599
|
|
||||||
getraideBFF 13871 1172846
|
|
||||||
Nesa92 13806 1116101
|
|
||||||
crocogoat 13803 1117422
|
|
||||||
joster 13710 946160
|
|
||||||
mbeier 13650 1044928
|
|
||||||
Pablohn26 13552 1088532
|
|
||||||
wxt9861 13550 1312306
|
|
||||||
Dark_wizzie 13422 1007152
|
|
||||||
Rudolphous 13244 883140
|
|
||||||
Machariel 13010 863104
|
|
||||||
nalanzeyu 12996 232590
|
|
||||||
mabichito 12903 749391
|
|
||||||
Jackfish 12895 868928
|
|
||||||
thijsk 12886 722107
|
|
||||||
AdrianSA 12860 804972
|
|
||||||
Flopzee 12698 894821
|
|
||||||
whelanh 12682 266404
|
|
||||||
mschmidt 12644 863193
|
|
||||||
korposzczur 12606 838168
|
|
||||||
fatmurphy 12547 853210
|
|
||||||
Oakwen 12532 855759
|
|
||||||
icewulf 12447 854878
|
|
||||||
SapphireBrand 12416 969604
|
|
||||||
deflectooor 12386 579392
|
|
||||||
modolief 12386 896470
|
|
||||||
Farseer 12249 694108
|
|
||||||
Hongildong 12201 648712
|
|
||||||
pgontarz 12151 848794
|
|
||||||
dbernier 12103 860824
|
|
||||||
szczur90 12035 942376
|
|
||||||
FormazChar 12019 910409
|
|
||||||
rensonthemove 11999 971993
|
|
||||||
stocky 11954 699440
|
|
||||||
MooTheCow 11923 779432
|
|
||||||
3cho 11842 1036786
|
|
||||||
ckaz 11792 732276
|
|
||||||
infinity 11470 727027
|
|
||||||
aga 11412 695127
|
|
||||||
torbjo 11395 729145
|
|
||||||
Thomas A. Anderson 11372 732094
|
|
||||||
savage84 11358 670860
|
|
||||||
Def9Infinity 11345 696552
|
|
||||||
d64 11263 789184
|
|
||||||
ali-al-zhrani 11245 779246
|
|
||||||
ImperiumAeternum 11155 952000
|
|
||||||
snicolet 11106 869170
|
|
||||||
dapper 11032 771402
|
|
||||||
Ethnikoi 10993 945906
|
|
||||||
Snuuka 10938 435504
|
|
||||||
Karmatron 10871 678306
|
|
||||||
basepi 10637 744851
|
|
||||||
Cubox 10621 826448
|
|
||||||
gerbil 10519 971688
|
|
||||||
michaelrpg 10509 739239
|
|
||||||
OIVAS7572 10420 995586
|
|
||||||
Garruk 10365 706465
|
|
||||||
dzjp 10343 732529
|
|
||||||
RickGroszkiewicz 10263 990798
|
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
|
||||||
|
[PolyGlot]
|
||||||
|
|
||||||
|
EngineDir = .
|
||||||
|
EngineCommand = ./stockfish
|
||||||
|
|
||||||
|
Book = false
|
||||||
|
BookFile = book.bin
|
||||||
|
|
||||||
|
Log = true
|
||||||
|
LogFile = stockfish.log
|
||||||
|
|
||||||
|
Resign = true
|
||||||
|
ResignScore = 600
|
||||||
|
|
||||||
|
[Engine]
|
||||||
|
|
||||||
|
Hash = 128
|
||||||
|
Threads = 1
|
||||||
|
OwnBook = false
|
||||||
|
Book File = book.bin
|
||||||
|
Use Search Log = false
|
||||||
|
Mobility (Middle Game) = 100
|
||||||
|
Mobility (Endgame) = 100
|
||||||
|
Pawn Structure (Middle Game) = 100
|
||||||
|
Pawn Structure (Endgame) = 100
|
||||||
|
Passed Pawns (Middle Game) = 100
|
||||||
|
Passed Pawns (Endgame) = 100
|
||||||
|
Aggressiveness = 100
|
||||||
|
Cowardice = 100
|
||||||
|
King Safety Curve = Quadratic
|
||||||
|
Quadratic = Linear
|
||||||
|
King Safety Coefficient = 40
|
||||||
|
King Safety X Intercept = 0
|
||||||
|
King Safety Max Slope = 30
|
||||||
|
King Safety Max Value = 500
|
||||||
|
Queen Contact Check Bonus = 3
|
||||||
|
Queen Check Bonus = 2
|
||||||
|
Rook Check Bonus = 1
|
||||||
|
Bishop Check Bonus = 1
|
||||||
|
Knight Check Bonus = 1
|
||||||
|
Discovered Check Bonus = 3
|
||||||
|
Mate Threat Bonus = 3
|
||||||
|
Check Extension (PV nodes) = 2
|
||||||
|
Check Extension (non-PV nodes) = 1
|
||||||
|
Single Reply Extension (PV nodes) = 2
|
||||||
|
Single Reply Extension (non-PV nodes) = 2
|
||||||
|
Mate Threat Extension (PV nodes) = 0
|
||||||
|
Mate Threat Extension (non-PV nodes) = 0
|
||||||
|
Pawn Push to 7th Extension (PV nodes) = 1
|
||||||
|
Pawn Push to 7th Extension (non-PV nodes) = 1
|
||||||
|
Passed Pawn Extension (PV nodes) = 1
|
||||||
|
Passed Pawn Extension (non-PV nodes) = 0
|
||||||
|
Pawn Endgame Extension (PV nodes) = 2
|
||||||
|
Pawn Endgame Extension (non-PV nodes) = 2
|
||||||
|
Full Depth Moves (PV nodes) = 14
|
||||||
|
Full Depth Moves (non-PV nodes) = 3
|
||||||
|
Threat Depth = 5
|
||||||
|
Futility Pruning (Main Search) = true
|
||||||
|
Futility Pruning (Quiescence Search) = true
|
||||||
|
Randomness = 0
|
||||||
|
Minimum Split Depth = 4
|
||||||
|
Maximum Number of Threads per Split Point = 5
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
|
|
||||||
#
|
|
||||||
# Returns properties of the native system.
|
|
||||||
# best architecture as supported by the CPU
|
|
||||||
# filename of the best binary uploaded as an artifact during CI
|
|
||||||
#
|
|
||||||
|
|
||||||
# Check if all the given flags are present in the CPU flags list
|
|
||||||
check_flags() {
|
|
||||||
for flag; do
|
|
||||||
printf '%s\n' "$flags" | grep -q -w "$flag" || return 1
|
|
||||||
done
|
|
||||||
}
|
|
||||||
|
|
||||||
# Set the CPU flags list
|
|
||||||
# remove underscores and points from flags, e.g. gcc uses avx512vnni, while some cpuinfo can have avx512_vnni, some systems use sse4_1 others sse4.1
|
|
||||||
get_flags() {
|
|
||||||
flags=$(awk '/^flags[ \t]*:|^Features[ \t]*:/{gsub(/^flags[ \t]*:[ \t]*|^Features[ \t]*:[ \t]*|[_.]/, ""); line=$0} END{print line}' /proc/cpuinfo)
|
|
||||||
}
|
|
||||||
|
|
||||||
# Check for gcc march "znver1" or "znver2" https://en.wikichip.org/wiki/amd/cpuid
|
|
||||||
check_znver_1_2() {
|
|
||||||
vendor_id=$(awk '/^vendor_id/{print $3; exit}' /proc/cpuinfo)
|
|
||||||
cpu_family=$(awk '/^cpu family/{print $4; exit}' /proc/cpuinfo)
|
|
||||||
[ "$vendor_id" = "AuthenticAMD" ] && [ "$cpu_family" = "23" ] && znver_1_2=true
|
|
||||||
}
|
|
||||||
|
|
||||||
# Set the file CPU x86_64 architecture
|
|
||||||
set_arch_x86_64() {
|
|
||||||
if check_flags 'avx512vnni' 'avx512dq' 'avx512f' 'avx512bw' 'avx512vl'; then
|
|
||||||
true_arch='x86-64-vnni256'
|
|
||||||
elif check_flags 'avx512f' 'avx512bw'; then
|
|
||||||
true_arch='x86-64-avx512'
|
|
||||||
elif [ -z "${znver_1_2+1}" ] && check_flags 'bmi2'; then
|
|
||||||
true_arch='x86-64-bmi2'
|
|
||||||
elif check_flags 'avx2'; then
|
|
||||||
true_arch='x86-64-avx2'
|
|
||||||
elif check_flags 'sse41' && check_flags 'popcnt'; then
|
|
||||||
true_arch='x86-64-sse41-popcnt'
|
|
||||||
else
|
|
||||||
true_arch='x86-64'
|
|
||||||
fi
|
|
||||||
}
|
|
||||||
|
|
||||||
# Check the system type
|
|
||||||
uname_s=$(uname -s)
|
|
||||||
uname_m=$(uname -m)
|
|
||||||
case $uname_s in
|
|
||||||
'Darwin') # Mac OSX system
|
|
||||||
case $uname_m in
|
|
||||||
'arm64')
|
|
||||||
true_arch='apple-silicon'
|
|
||||||
file_arch='x86-64-sse41-popcnt' # Supported by Rosetta 2
|
|
||||||
;;
|
|
||||||
'x86_64')
|
|
||||||
flags=$(sysctl -n machdep.cpu.features machdep.cpu.leaf7_features | tr '\n' ' ' | tr '[:upper:]' '[:lower:]' | tr -d '_.')
|
|
||||||
set_arch_x86_64
|
|
||||||
if [ "$true_arch" = 'x86-64-vnni256' ] || [ "$true_arch" = 'x86-64-avx512' ]; then
|
|
||||||
file_arch='x86-64-bmi2'
|
|
||||||
fi
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
file_os='macos'
|
|
||||||
file_ext='tar'
|
|
||||||
;;
|
|
||||||
'Linux') # Linux system
|
|
||||||
get_flags
|
|
||||||
case $uname_m in
|
|
||||||
'x86_64')
|
|
||||||
file_os='ubuntu'
|
|
||||||
check_znver_1_2
|
|
||||||
set_arch_x86_64
|
|
||||||
;;
|
|
||||||
'i686')
|
|
||||||
file_os='ubuntu'
|
|
||||||
true_arch='x86-32'
|
|
||||||
;;
|
|
||||||
'aarch64')
|
|
||||||
file_os='android'
|
|
||||||
true_arch='armv8'
|
|
||||||
if check_flags 'asimddp'; then
|
|
||||||
true_arch="$true_arch-dotprod"
|
|
||||||
fi
|
|
||||||
;;
|
|
||||||
'armv7'*)
|
|
||||||
file_os='android'
|
|
||||||
true_arch='armv7'
|
|
||||||
if check_flags 'neon'; then
|
|
||||||
true_arch="$true_arch-neon"
|
|
||||||
fi
|
|
||||||
;;
|
|
||||||
*) # Unsupported machine type, exit with error
|
|
||||||
printf 'Unsupported machine type: %s\n' "$uname_m"
|
|
||||||
exit 1
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
file_ext='tar'
|
|
||||||
;;
|
|
||||||
'CYGWIN'*|'MINGW'*|'MSYS'*) # Windows system with POSIX compatibility layer
|
|
||||||
get_flags
|
|
||||||
check_znver_1_2
|
|
||||||
set_arch_x86_64
|
|
||||||
file_os='windows'
|
|
||||||
file_ext='zip'
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
# Unknown system type, exit with error
|
|
||||||
printf 'Unsupported system type: %s\n' "$uname_s"
|
|
||||||
exit 1
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
if [ -z "$file_arch" ]; then
|
|
||||||
file_arch=$true_arch
|
|
||||||
fi
|
|
||||||
|
|
||||||
file_name="stockfish-$file_os-$file_arch.$file_ext"
|
|
||||||
|
|
||||||
printf '%s %s\n' "$true_arch" "$file_name"
|
|
||||||
+674
@@ -0,0 +1,674 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program 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.
|
||||||
|
|
||||||
|
This program 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/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||||
+277
-1061
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,75 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include "bitboard.h"
|
||||||
|
#include "direction.h"
|
||||||
|
#include "endgame.h"
|
||||||
|
#include "evaluate.h"
|
||||||
|
#include "material.h"
|
||||||
|
#include "mersenne.h"
|
||||||
|
#include "misc.h"
|
||||||
|
#include "movepick.h"
|
||||||
|
#include "position.h"
|
||||||
|
#include "search.h"
|
||||||
|
#include "thread.h"
|
||||||
|
#include "ucioption.h"
|
||||||
|
|
||||||
|
|
||||||
|
/// Application class is in charge of initializing global resources
|
||||||
|
/// at startup and cleanly releases them when program terminates.
|
||||||
|
|
||||||
|
Application::Application() {
|
||||||
|
|
||||||
|
init_mersenne();
|
||||||
|
init_direction_table();
|
||||||
|
init_bitboards();
|
||||||
|
init_uci_options();
|
||||||
|
Position::init_zobrist();
|
||||||
|
Position::init_piece_square_tables();
|
||||||
|
init_eval(1);
|
||||||
|
init_bitbases();
|
||||||
|
init_threads();
|
||||||
|
|
||||||
|
// Make random number generation less deterministic, for book moves
|
||||||
|
for (int i = abs(get_system_time() % 10000); i > 0; i--)
|
||||||
|
genrand_int32();
|
||||||
|
}
|
||||||
|
|
||||||
|
Application::~Application() {
|
||||||
|
|
||||||
|
stop_threads();
|
||||||
|
quit_eval();
|
||||||
|
}
|
||||||
|
|
||||||
|
void Application::initialize() {
|
||||||
|
|
||||||
|
// A static Application object is allocated
|
||||||
|
// once only when this function is called.
|
||||||
|
static Application singleton;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Application::exit_with_failure() {
|
||||||
|
|
||||||
|
exit(EXIT_FAILURE); // d'tor will be called automatically
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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(APPLICATION_H_INCLUDED)
|
||||||
|
#define APPLICATION_H_INCLUDED
|
||||||
|
|
||||||
|
|
||||||
|
/// Singleton class used to housekeep memory and global resources
|
||||||
|
/// so to be sure we always leave in a clean state.
|
||||||
|
|
||||||
|
class Application {
|
||||||
|
|
||||||
|
Application();
|
||||||
|
Application(const Application&);
|
||||||
|
~Application();
|
||||||
|
|
||||||
|
public:
|
||||||
|
static void initialize();
|
||||||
|
static void exit_with_failure();
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif // !defined(APPLICATION_H_INCLUDED)
|
||||||
+132
-114
@@ -1,6 +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-2024 The Stockfish developers (see AUTHORS file)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
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
|
||||||
@@ -16,24 +17,32 @@
|
|||||||
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 "benchmark.h"
|
|
||||||
|
|
||||||
#include <cstdlib>
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <iostream>
|
#include <sstream>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
namespace {
|
#include "benchmark.h"
|
||||||
|
#include "search.h"
|
||||||
|
#include "thread.h"
|
||||||
|
#include "ucioption.h"
|
||||||
|
|
||||||
// clang-format off
|
using namespace std;
|
||||||
const std::vector<std::string> Defaults = {
|
|
||||||
"setoption name UCI_Chess960 value false",
|
////
|
||||||
|
//// Variables
|
||||||
|
////
|
||||||
|
|
||||||
|
const string BenchmarkPositions[] = {
|
||||||
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
|
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
|
||||||
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 10",
|
"r4rk1/1b2qppp/p1n1p3/1p6/1b1PN3/3BRN2/PP3PPP/R2Q2K1 b - - 7 16",
|
||||||
"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 11",
|
"4r1k1/ppq3pp/3b4/2pP4/2Q1p3/4B1P1/PP5P/R5K1 b - - 0 20",
|
||||||
"4rrk1/pp1n3p/3q2pQ/2p1pb2/2PP4/2P3N1/P2B2PP/4RRK1 b - - 7 19",
|
"4rrk1/pp1n3p/3q2pQ/2p1pb2/2PP4/2P3N1/P2B2PP/4RRK1 b - - 7 19",
|
||||||
"rq3rk1/ppp2ppp/1bnpb3/3N2B1/3NP3/7P/PPPQ1PP1/2KR3R w - - 7 14 moves d4e6",
|
"rq3rk1/ppp2ppp/1bnpb3/3N2B1/3NP3/7P/PPPQ1PP1/2KR3R w - - 7 14",
|
||||||
"r1bq1r1k/1pp1n1pp/1p1p4/4p2Q/4Pp2/1BNP4/PPP2PPP/3R1RK1 w - - 2 14 moves g2g4",
|
"r1bq1r1k/1pp1n1pp/1p1p4/4p2Q/4Pp2/1BNP4/PPP2PPP/3R1RK1 w - - 2 14",
|
||||||
"r3r1k1/2p2ppp/p1p1bn2/8/1q2P3/2NPQN2/PPP3PP/R4RK1 b - - 2 15",
|
"r3r1k1/2p2ppp/p1p1bn2/8/1q2P3/2NPQN2/PPP3PP/R4RK1 b - - 2 15",
|
||||||
"r1bbk1nr/pp3p1p/2n5/1N4p1/2Np1B2/8/PPP2PPP/2KR1B1R w kq - 0 13",
|
"r1bbk1nr/pp3p1p/2n5/1N4p1/2Np1B2/8/PPP2PPP/2KR1B1R w kq - 0 13",
|
||||||
"r1bq1rk1/ppp1nppp/4n3/3p3Q/3P4/1BP1B3/PP1N2PP/R4RK1 w - - 1 16",
|
"r1bq1rk1/ppp1nppp/4n3/3p3Q/3P4/1BP1B3/PP1N2PP/R4RK1 w - - 1 16",
|
||||||
@@ -42,122 +51,131 @@ const std::vector<std::string> Defaults = {
|
|||||||
"r1bq1r1k/b1p1npp1/p2p3p/1p6/3PP3/1B2NN2/PP3PPP/R2Q1RK1 w - - 1 16",
|
"r1bq1r1k/b1p1npp1/p2p3p/1p6/3PP3/1B2NN2/PP3PPP/R2Q1RK1 w - - 1 16",
|
||||||
"3r1rk1/p5pp/bpp1pp2/8/q1PP1P2/b3P3/P2NQRPP/1R2B1K1 b - - 6 22",
|
"3r1rk1/p5pp/bpp1pp2/8/q1PP1P2/b3P3/P2NQRPP/1R2B1K1 b - - 6 22",
|
||||||
"r1q2rk1/2p1bppp/2Pp4/p6b/Q1PNp3/4B3/PP1R1PPP/2K4R w - - 2 18",
|
"r1q2rk1/2p1bppp/2Pp4/p6b/Q1PNp3/4B3/PP1R1PPP/2K4R w - - 2 18",
|
||||||
"4k2r/1pb2ppp/1p2p3/1R1p4/3P4/2r1PN2/P4PPP/1R4K1 b - - 3 22",
|
"4k2r/1pb2ppp/1p2p3/1R1p4/3P4/2r1PN2/P4PPP/1R4K1 b - 3 22",
|
||||||
"3q2k1/pb3p1p/4pbp1/2r5/PpN2N2/1P2P2P/5PP1/Q2R2K1 b - - 4 26",
|
"3q2k1/pb3p1p/4pbp1/2r5/PpN2N2/1P2P2P/5PP1/Q2R2K1 b - - 4 26"
|
||||||
"6k1/6p1/6Pp/ppp5/3pn2P/1P3K2/1PP2P2/3N4 b - - 0 1",
|
|
||||||
"3b4/5kp1/1p1p1p1p/pP1PpP1P/P1P1P3/3KN3/8/8 w - - 0 1",
|
|
||||||
"2K5/p7/7P/5pR1/8/5k2/r7/8 w - - 0 1 moves g5g6 f3e3 g6g5 e3f3",
|
|
||||||
"8/6pk/1p6/8/PP3p1p/5P2/4KP1q/3Q4 w - - 0 1",
|
|
||||||
"7k/3p2pp/4q3/8/4Q3/5Kp1/P6b/8 w - - 0 1",
|
|
||||||
"8/2p5/8/2kPKp1p/2p4P/2P5/3P4/8 w - - 0 1",
|
|
||||||
"8/1p3pp1/7p/5P1P/2k3P1/8/2K2P2/8 w - - 0 1",
|
|
||||||
"8/pp2r1k1/2p1p3/3pP2p/1P1P1P1P/P5KR/8/8 w - - 0 1",
|
|
||||||
"8/3p4/p1bk3p/Pp6/1Kp1PpPp/2P2P1P/2P5/5B2 b - - 0 1",
|
|
||||||
"5k2/7R/4P2p/5K2/p1r2P1p/8/8/8 b - - 0 1",
|
|
||||||
"6k1/6p1/P6p/r1N5/5p2/7P/1b3PP1/4R1K1 w - - 0 1",
|
|
||||||
"1r3k2/4q3/2Pp3b/3Bp3/2Q2p2/1p1P2P1/1P2KP2/3N4 w - - 0 1",
|
|
||||||
"6k1/4pp1p/3p2p1/P1pPb3/R7/1r2P1PP/3B1P2/6K1 w - - 0 1",
|
|
||||||
"8/3p3B/5p2/5P2/p7/PP5b/k7/6K1 w - - 0 1",
|
|
||||||
"5rk1/q6p/2p3bR/1pPp1rP1/1P1Pp3/P3B1Q1/1K3P2/R7 w - - 93 90",
|
|
||||||
"4rrk1/1p1nq3/p7/2p1P1pp/3P2bp/3Q1Bn1/PPPB4/1K2R1NR w - - 40 21",
|
|
||||||
"r3k2r/3nnpbp/q2pp1p1/p7/Pp1PPPP1/4BNN1/1P5P/R2Q1RK1 w kq - 0 16",
|
|
||||||
"3Qb1k1/1r2ppb1/pN1n2q1/Pp1Pp1Pr/4P2p/4BP2/4B1R1/1R5K b - - 11 40",
|
|
||||||
"4k3/3q1r2/1N2r1b1/3ppN2/2nPP3/1B1R2n1/2R1Q3/3K4 w - - 5 1",
|
|
||||||
|
|
||||||
// 5-man positions
|
|
||||||
"8/8/8/8/5kp1/P7/8/1K1N4 w - - 0 1", // Kc2 - mate
|
|
||||||
"8/8/8/5N2/8/p7/8/2NK3k w - - 0 1", // Na2 - mate
|
|
||||||
"8/3k4/8/8/8/4B3/4KB2/2B5 w - - 0 1", // draw
|
|
||||||
|
|
||||||
// 6-man positions
|
|
||||||
"8/8/1P6/5pr1/8/4R3/7k/2K5 w - - 0 1", // Re5 - mate
|
|
||||||
"8/2p4P/8/kr6/6R1/8/8/1K6 w - - 0 1", // Ka2 - mate
|
|
||||||
"8/8/3P3k/8/1p6/8/1P6/1K3n2 b - - 0 1", // Nd2 - draw
|
|
||||||
|
|
||||||
// 7-man positions
|
|
||||||
"8/R7/2q5/8/6k1/8/1P5p/K6R w - - 0 124", // Draw
|
|
||||||
|
|
||||||
// Mate and stalemate positions
|
|
||||||
"6k1/3b3r/1p1p4/p1n2p2/1PPNpP1q/P3Q1p1/1R1RB1P1/5K2 b - - 0 1",
|
|
||||||
"r2r1n2/pp2bk2/2p1p2p/3q4/3PN1QP/2P3R1/P4PP1/5RK1 w - - 0 1",
|
|
||||||
"8/8/8/8/8/6k1/6p1/6K1 w - -",
|
|
||||||
"7k/7P/6K1/8/3B4/8/8/8 b - -",
|
|
||||||
|
|
||||||
// Chess 960
|
|
||||||
"setoption name UCI_Chess960 value true",
|
|
||||||
"bbqnnrkr/pppppppp/8/8/8/8/PPPPPPPP/BBQNNRKR w HFhf - 0 1 moves g2g3 d7d5 d2d4 c8h3 c1g5 e8d6 g5e7 f7f6",
|
|
||||||
"nqbnrkrb/pppppppp/8/8/8/8/PPPPPPPP/NQBNRKRB w KQkq - 0 1",
|
|
||||||
"setoption name UCI_Chess960 value false"
|
|
||||||
};
|
};
|
||||||
// clang-format on
|
|
||||||
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
namespace Stockfish::Benchmark {
|
////
|
||||||
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
// Builds a list of UCI commands to be run by bench. There
|
/// benchmark() runs a simple benchmark by letting Stockfish analyze a set
|
||||||
// are five parameters: TT size in MB, number of search threads that
|
/// of positions for a given time each. There are four parameters; the
|
||||||
// should be used, the limit value spent for each position, a file name
|
/// transposition table size, the number of search threads that should
|
||||||
// where to look for positions in FEN format, and the type of the limit:
|
/// be used, the time in seconds spent for each position (optional, default
|
||||||
// depth, perft, nodes and movetime (in milliseconds). Examples:
|
/// is 60) and an optional file name where to look for positions in fen
|
||||||
//
|
/// format (default are the BenchmarkPositions defined above).
|
||||||
// bench : search default positions up to depth 13
|
/// The analysis is written to a file named bench.txt.
|
||||||
// bench 64 1 15 : search default positions up to depth 15 (TT = 64MB)
|
|
||||||
// bench 64 1 100000 default nodes : search default positions for 100K nodes each
|
|
||||||
// bench 64 4 5000 current movetime : search current position with 4 threads for 5 sec
|
|
||||||
// bench 16 1 5 blah perft : run a perft 5 on positions in file "blah"
|
|
||||||
std::vector<std::string> setup_bench(const std::string& currentFen, std::istream& is) {
|
|
||||||
|
|
||||||
std::vector<std::string> fens, list;
|
void benchmark(const string& commandLine) {
|
||||||
std::string go, token;
|
|
||||||
|
|
||||||
// Assign default values to missing arguments
|
istringstream csVal(commandLine);
|
||||||
std::string ttSize = (is >> token) ? token : "16";
|
istringstream csStr(commandLine);
|
||||||
std::string threads = (is >> token) ? token : "1";
|
string ttSize, threads, fileName, limitType, timFile;
|
||||||
std::string limit = (is >> token) ? token : "13";
|
int val, secsPerPos, maxDepth, maxNodes;
|
||||||
std::string fenFile = (is >> token) ? token : "default";
|
|
||||||
std::string limitType = (is >> token) ? token : "depth";
|
|
||||||
|
|
||||||
go = limitType == "eval" ? "eval" : "go " + limitType + " " + limit;
|
csStr >> ttSize;
|
||||||
|
csVal >> val;
|
||||||
|
if (val < 4 || val > 1024)
|
||||||
|
{
|
||||||
|
cerr << "The hash table size must be between 4 and 1024" << endl;
|
||||||
|
Application::exit_with_failure();
|
||||||
|
}
|
||||||
|
csStr >> threads;
|
||||||
|
csVal >> val;
|
||||||
|
if (val < 1 || val > THREAD_MAX)
|
||||||
|
{
|
||||||
|
cerr << "The number of threads must be between 1 and " << THREAD_MAX << endl;
|
||||||
|
Application::exit_with_failure();
|
||||||
|
}
|
||||||
|
set_option_value("Hash", ttSize);
|
||||||
|
set_option_value("Threads", threads);
|
||||||
|
set_option_value("OwnBook", "false");
|
||||||
|
set_option_value("Use Search Log", "true");
|
||||||
|
set_option_value("Search Log Filename", "bench.txt");
|
||||||
|
|
||||||
if (fenFile == "default")
|
csVal >> val;
|
||||||
fens = Defaults;
|
csVal >> fileName;
|
||||||
|
csVal >> limitType;
|
||||||
|
csVal >> timFile;
|
||||||
|
|
||||||
else if (fenFile == "current")
|
secsPerPos = maxDepth = maxNodes = 0;
|
||||||
fens.push_back(currentFen);
|
|
||||||
|
|
||||||
else
|
if (limitType == "time")
|
||||||
{
|
secsPerPos = val * 1000;
|
||||||
std::string fen;
|
else if (limitType == "depth" || limitType == "perft")
|
||||||
std::ifstream file(fenFile);
|
maxDepth = val;
|
||||||
|
else
|
||||||
|
maxNodes = val;
|
||||||
|
|
||||||
if (!file.is_open())
|
vector<string> positions;
|
||||||
{
|
|
||||||
std::cerr << "Unable to open file " << fenFile << std::endl;
|
|
||||||
exit(EXIT_FAILURE);
|
|
||||||
}
|
|
||||||
|
|
||||||
while (getline(file, fen))
|
if (fileName != "default")
|
||||||
if (!fen.empty())
|
{
|
||||||
fens.push_back(fen);
|
ifstream fenFile(fileName.c_str());
|
||||||
|
if (!fenFile.is_open())
|
||||||
|
{
|
||||||
|
cerr << "Unable to open positions file " << fileName << endl;
|
||||||
|
Application::exit_with_failure();
|
||||||
|
}
|
||||||
|
string pos;
|
||||||
|
while (fenFile.good())
|
||||||
|
{
|
||||||
|
getline(fenFile, pos);
|
||||||
|
if (!pos.empty())
|
||||||
|
positions.push_back(pos);
|
||||||
|
}
|
||||||
|
fenFile.close();
|
||||||
|
} else
|
||||||
|
for (int i = 0; i < 16; i++)
|
||||||
|
positions.push_back(string(BenchmarkPositions[i]));
|
||||||
|
|
||||||
file.close();
|
ofstream timingFile;
|
||||||
}
|
if (!timFile.empty())
|
||||||
|
{
|
||||||
|
timingFile.open(timFile.c_str(), ios::out | ios::app);
|
||||||
|
if (!timingFile.is_open())
|
||||||
|
{
|
||||||
|
cerr << "Unable to open timing file " << timFile << endl;
|
||||||
|
Application::exit_with_failure();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
list.emplace_back("setoption name Threads value " + threads);
|
vector<string>::iterator it;
|
||||||
list.emplace_back("setoption name Hash value " + ttSize);
|
int cnt = 1;
|
||||||
list.emplace_back("ucinewgame");
|
int64_t totalNodes = 0;
|
||||||
|
int startTime = get_system_time();
|
||||||
|
|
||||||
for (const std::string& fen : fens)
|
for (it = positions.begin(); it != positions.end(); ++it, ++cnt)
|
||||||
if (fen.find("setoption") != std::string::npos)
|
{
|
||||||
list.emplace_back(fen);
|
Move moves[1] = {MOVE_NONE};
|
||||||
else
|
int dummy[2] = {0, 0};
|
||||||
{
|
Position pos(*it);
|
||||||
list.emplace_back("position fen " + fen);
|
cerr << "\nBench position: " << cnt << '/' << positions.size() << endl << endl;
|
||||||
list.emplace_back(go);
|
if (limitType == "perft")
|
||||||
}
|
totalNodes += perft(pos, maxDepth * OnePly);
|
||||||
|
else if (!think(pos, false, false, 0, dummy, dummy, 0, maxDepth, maxNodes, secsPerPos, moves))
|
||||||
|
break;
|
||||||
|
totalNodes += nodes_searched();
|
||||||
|
}
|
||||||
|
|
||||||
return list;
|
cnt = get_system_time() - startTime;
|
||||||
|
cerr << "==============================="
|
||||||
|
<< "\nTotal time (ms) : " << cnt
|
||||||
|
<< "\nNodes searched : " << totalNodes
|
||||||
|
<< "\nNodes/second : " << (int)(totalNodes/(cnt/1000.0)) << endl << endl;
|
||||||
|
|
||||||
|
if (!timFile.empty())
|
||||||
|
{
|
||||||
|
timingFile << cnt << endl << endl;
|
||||||
|
timingFile.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Under MS Visual C++ debug window always unconditionally closes
|
||||||
|
// when program exits, this is bad because we want to read results before.
|
||||||
|
#if (defined(WINDOWS) || defined(WIN32) || defined(WIN64))
|
||||||
|
cerr << "Press any key to exit" << endl;
|
||||||
|
cin >> fileName;
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace Stockfish
|
|
||||||
+13
-8
@@ -1,6 +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-2024 The Stockfish developers (see AUTHORS file)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
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
|
||||||
@@ -16,17 +17,21 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#ifndef BENCHMARK_H_INCLUDED
|
|
||||||
|
#if !defined(BENCHMARK_H_INCLUDED)
|
||||||
#define BENCHMARK_H_INCLUDED
|
#define BENCHMARK_H_INCLUDED
|
||||||
|
|
||||||
#include <iosfwd>
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
namespace Stockfish::Benchmark {
|
|
||||||
|
|
||||||
std::vector<std::string> setup_bench(const std::string&, std::istream&);
|
////
|
||||||
|
//// Prototypes
|
||||||
|
////
|
||||||
|
|
||||||
} // namespace Stockfish
|
extern void benchmark(const std::string& commandLine);
|
||||||
|
|
||||||
#endif // #ifndef BENCHMARK_H_INCLUDED
|
#endif // !defined(BENCHMARK_H_INCLUDED)
|
||||||
|
|||||||
+350
@@ -0,0 +1,350 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include <cassert>
|
||||||
|
|
||||||
|
#include "bitbase.h"
|
||||||
|
#include "bitboard.h"
|
||||||
|
#include "move.h"
|
||||||
|
#include "square.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Local definitions
|
||||||
|
////
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
enum Result {
|
||||||
|
RESULT_UNKNOWN,
|
||||||
|
RESULT_INVALID,
|
||||||
|
RESULT_WIN,
|
||||||
|
RESULT_LOSS,
|
||||||
|
RESULT_DRAW
|
||||||
|
};
|
||||||
|
|
||||||
|
struct KPKPosition {
|
||||||
|
void from_index(int index);
|
||||||
|
int to_index() const;
|
||||||
|
bool is_legal() const;
|
||||||
|
bool is_immediate_draw() const;
|
||||||
|
bool is_immediate_win() const;
|
||||||
|
Bitboard wk_attacks() const;
|
||||||
|
Bitboard bk_attacks() const;
|
||||||
|
Bitboard pawn_attacks() const;
|
||||||
|
|
||||||
|
Square whiteKingSquare, blackKingSquare, pawnSquare;
|
||||||
|
Color sideToMove;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
Result *Bitbase;
|
||||||
|
const int IndexMax = 2*24*64*64;
|
||||||
|
int UnknownCount = 0;
|
||||||
|
|
||||||
|
void initialize();
|
||||||
|
bool next_iteration();
|
||||||
|
Result classify_wtm(const KPKPosition &p);
|
||||||
|
Result classify_btm(const KPKPosition &p);
|
||||||
|
int compute_index(Square wksq, Square bksq, Square psq, Color stm);
|
||||||
|
int compress_result(Result r);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
|
void generate_kpk_bitbase(uint8_t bitbase[]) {
|
||||||
|
// Allocate array and initialize:
|
||||||
|
Bitbase = new Result[IndexMax];
|
||||||
|
initialize();
|
||||||
|
|
||||||
|
// Iterate until all positions are classified:
|
||||||
|
while(next_iteration());
|
||||||
|
|
||||||
|
// Compress bitbase into the supplied parameter:
|
||||||
|
int i, j, b;
|
||||||
|
for(i = 0; i < 24576; i++) {
|
||||||
|
for(b = 0, j = 0; j < 8; b |= (compress_result(Bitbase[8*i+j]) << j), j++);
|
||||||
|
assert(b == int(uint8_t(b)));
|
||||||
|
bitbase[i] = (uint8_t)b;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Release allocated memory:
|
||||||
|
delete [] Bitbase;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
void KPKPosition::from_index(int index) {
|
||||||
|
int s;
|
||||||
|
sideToMove = Color(index % 2);
|
||||||
|
blackKingSquare = Square((index / 2) % 64);
|
||||||
|
whiteKingSquare = Square((index / 128) % 64);
|
||||||
|
s = (index / 8192) % 24;
|
||||||
|
pawnSquare = make_square(File(s % 4), Rank(s / 4 + 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int KPKPosition::to_index() const {
|
||||||
|
return compute_index(whiteKingSquare, blackKingSquare, pawnSquare,
|
||||||
|
sideToMove);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
bool KPKPosition::is_legal() const {
|
||||||
|
if(whiteKingSquare == pawnSquare || whiteKingSquare == blackKingSquare ||
|
||||||
|
pawnSquare == blackKingSquare)
|
||||||
|
return false;
|
||||||
|
if(sideToMove == WHITE) {
|
||||||
|
if(bit_is_set(this->wk_attacks(), blackKingSquare))
|
||||||
|
return false;
|
||||||
|
if(bit_is_set(this->pawn_attacks(), blackKingSquare))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if(bit_is_set(this->bk_attacks(), whiteKingSquare))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
bool KPKPosition::is_immediate_draw() const {
|
||||||
|
if(sideToMove == BLACK) {
|
||||||
|
Bitboard wka = this->wk_attacks();
|
||||||
|
Bitboard bka = this->bk_attacks();
|
||||||
|
|
||||||
|
// Case 1: Stalemate
|
||||||
|
if((bka & ~(wka | this->pawn_attacks())) == EmptyBoardBB)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
// Case 2: King can capture pawn
|
||||||
|
if(bit_is_set(bka, pawnSquare) && !bit_is_set(wka, pawnSquare))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// Case 1: Stalemate
|
||||||
|
if(whiteKingSquare == SQ_A8 && pawnSquare == SQ_A7 &&
|
||||||
|
(blackKingSquare == SQ_C7 || blackKingSquare == SQ_C8))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
bool KPKPosition::is_immediate_win() const {
|
||||||
|
// The position is an immediate win if it is white to move and the white
|
||||||
|
// pawn can be promoted without getting captured:
|
||||||
|
return
|
||||||
|
sideToMove == WHITE &&
|
||||||
|
square_rank(pawnSquare) == RANK_7 &&
|
||||||
|
(square_distance(blackKingSquare, pawnSquare+DELTA_N) > 1 ||
|
||||||
|
bit_is_set(this->wk_attacks(), pawnSquare+DELTA_N));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Bitboard KPKPosition::wk_attacks() const {
|
||||||
|
return StepAttackBB[WK][whiteKingSquare];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Bitboard KPKPosition::bk_attacks() const {
|
||||||
|
return StepAttackBB[BK][blackKingSquare];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Bitboard KPKPosition::pawn_attacks() const {
|
||||||
|
return StepAttackBB[WP][pawnSquare];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void initialize() {
|
||||||
|
KPKPosition p;
|
||||||
|
for(int i = 0; i < IndexMax; i++) {
|
||||||
|
p.from_index(i);
|
||||||
|
if(!p.is_legal())
|
||||||
|
Bitbase[i] = RESULT_INVALID;
|
||||||
|
else if(p.is_immediate_draw())
|
||||||
|
Bitbase[i] = RESULT_DRAW;
|
||||||
|
else if(p.is_immediate_win())
|
||||||
|
Bitbase[i] = RESULT_WIN;
|
||||||
|
else {
|
||||||
|
Bitbase[i] = RESULT_UNKNOWN;
|
||||||
|
UnknownCount++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
bool next_iteration() {
|
||||||
|
KPKPosition p;
|
||||||
|
int previousUnknownCount = UnknownCount;
|
||||||
|
|
||||||
|
for(int i = 0; i < IndexMax; i++)
|
||||||
|
if(Bitbase[i] == RESULT_UNKNOWN) {
|
||||||
|
p.from_index(i);
|
||||||
|
|
||||||
|
Bitbase[i] = (p.sideToMove == WHITE)? classify_wtm(p) : classify_btm(p);
|
||||||
|
|
||||||
|
if(Bitbase[i] == RESULT_WIN || Bitbase[i] == RESULT_LOSS ||
|
||||||
|
Bitbase[i] == RESULT_DRAW)
|
||||||
|
UnknownCount--;
|
||||||
|
}
|
||||||
|
|
||||||
|
return UnknownCount != previousUnknownCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Result classify_wtm(const KPKPosition &p) {
|
||||||
|
|
||||||
|
// If one move leads to a position classified as RESULT_LOSS, the result
|
||||||
|
// of the current position is RESULT_WIN. If all moves lead to positions
|
||||||
|
// classified as RESULT_DRAW, the current position is classified as
|
||||||
|
// RESULT_DRAW. Otherwise, the current position is classified as
|
||||||
|
// RESULT_UNKNOWN.
|
||||||
|
|
||||||
|
bool unknownFound = false;
|
||||||
|
Bitboard b;
|
||||||
|
Square s;
|
||||||
|
|
||||||
|
// King moves
|
||||||
|
b = p.wk_attacks();
|
||||||
|
while(b) {
|
||||||
|
s = pop_1st_bit(&b);
|
||||||
|
switch(Bitbase[compute_index(s, p.blackKingSquare, p.pawnSquare,
|
||||||
|
BLACK)]) {
|
||||||
|
case RESULT_LOSS:
|
||||||
|
return RESULT_WIN;
|
||||||
|
|
||||||
|
case RESULT_UNKNOWN:
|
||||||
|
unknownFound = true;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case RESULT_DRAW: case RESULT_INVALID:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
assert(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pawn moves
|
||||||
|
if(square_rank(p.pawnSquare) < RANK_7) {
|
||||||
|
s = p.pawnSquare + DELTA_N;
|
||||||
|
switch(Bitbase[compute_index(p.whiteKingSquare, p.blackKingSquare, s,
|
||||||
|
BLACK)]) {
|
||||||
|
case RESULT_LOSS:
|
||||||
|
return RESULT_WIN;
|
||||||
|
|
||||||
|
case RESULT_UNKNOWN:
|
||||||
|
unknownFound = true;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case RESULT_DRAW: case RESULT_INVALID:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
assert(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
if(square_rank(s) == RANK_3 &&
|
||||||
|
s != p.whiteKingSquare && s != p.blackKingSquare) {
|
||||||
|
s += DELTA_N;
|
||||||
|
switch(Bitbase[compute_index(p.whiteKingSquare, p.blackKingSquare, s,
|
||||||
|
BLACK)]) {
|
||||||
|
case RESULT_LOSS:
|
||||||
|
return RESULT_WIN;
|
||||||
|
|
||||||
|
case RESULT_UNKNOWN:
|
||||||
|
unknownFound = true;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case RESULT_DRAW: case RESULT_INVALID:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
assert(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return unknownFound? RESULT_UNKNOWN : RESULT_DRAW;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Result classify_btm(const KPKPosition &p) {
|
||||||
|
|
||||||
|
// If one move leads to a position classified as RESULT_DRAW, the result
|
||||||
|
// of the current position is RESULT_DRAW. If all moves lead to positions
|
||||||
|
// classified as RESULT_WIN, the current position is classified as
|
||||||
|
// RESULT_LOSS. Otherwise, the current position is classified as
|
||||||
|
// RESULT_UNKNOWN.
|
||||||
|
|
||||||
|
bool unknownFound = false;
|
||||||
|
Bitboard b;
|
||||||
|
Square s;
|
||||||
|
|
||||||
|
// King moves
|
||||||
|
b = p.bk_attacks();
|
||||||
|
while(b) {
|
||||||
|
s = pop_1st_bit(&b);
|
||||||
|
switch(Bitbase[compute_index(p.whiteKingSquare, s, p.pawnSquare,
|
||||||
|
WHITE)]) {
|
||||||
|
case RESULT_DRAW:
|
||||||
|
return RESULT_DRAW;
|
||||||
|
|
||||||
|
case RESULT_UNKNOWN:
|
||||||
|
unknownFound = true;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case RESULT_WIN: case RESULT_INVALID:
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
assert(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return unknownFound? RESULT_UNKNOWN : RESULT_LOSS;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int compute_index(Square wksq, Square bksq, Square psq, Color stm) {
|
||||||
|
int p = int(square_file(psq)) + (int(square_rank(psq)) - 1) * 4;
|
||||||
|
int result = int(stm) + 2*int(bksq) + 128*int(wksq) + 8192*p;
|
||||||
|
assert(result >= 0 && result < IndexMax);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
int compress_result(Result r) {
|
||||||
|
return (r == RESULT_WIN || r == RESULT_LOSS)? 1 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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(BITBASE_H_INCLUDED)
|
||||||
|
#define BITBASE_H_INCLUDED
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include "types.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Prototypes
|
||||||
|
////
|
||||||
|
|
||||||
|
extern void generate_kpk_bitbase(uint8_t bitbase[]);
|
||||||
|
|
||||||
|
|
||||||
|
#endif // !defined(BITBASE_H_INCLUDED)
|
||||||
+495
-173
@@ -1,6 +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-2024 The Stockfish developers (see AUTHORS file)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
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
|
||||||
@@ -16,207 +17,528 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
#include "bitboard.h"
|
#include "bitboard.h"
|
||||||
|
#include "bitcount.h"
|
||||||
|
#include "direction.h"
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <bitset>
|
|
||||||
#include <initializer_list>
|
|
||||||
|
|
||||||
#include "misc.h"
|
#if defined(IS_64BIT)
|
||||||
|
|
||||||
namespace Stockfish {
|
const uint64_t BMult[64] = {
|
||||||
|
0x440049104032280ULL, 0x1021023c82008040ULL, 0x404040082000048ULL,
|
||||||
|
0x48c4440084048090ULL, 0x2801104026490000ULL, 0x4100880442040800ULL,
|
||||||
|
0x181011002e06040ULL, 0x9101004104200e00ULL, 0x1240848848310401ULL,
|
||||||
|
0x2000142828050024ULL, 0x1004024d5000ULL, 0x102044400800200ULL,
|
||||||
|
0x8108108820112000ULL, 0xa880818210c00046ULL, 0x4008008801082000ULL,
|
||||||
|
0x60882404049400ULL, 0x104402004240810ULL, 0xa002084250200ULL,
|
||||||
|
0x100b0880801100ULL, 0x4080201220101ULL, 0x44008080a00000ULL,
|
||||||
|
0x202200842000ULL, 0x5006004882d00808ULL, 0x200045080802ULL,
|
||||||
|
0x86100020200601ULL, 0xa802080a20112c02ULL, 0x80411218080900ULL,
|
||||||
|
0x200a0880080a0ULL, 0x9a01010000104000ULL, 0x28008003100080ULL,
|
||||||
|
0x211021004480417ULL, 0x401004188220806ULL, 0x825051400c2006ULL,
|
||||||
|
0x140c0210943000ULL, 0x242800300080ULL, 0xc2208120080200ULL,
|
||||||
|
0x2430008200002200ULL, 0x1010100112008040ULL, 0x8141050100020842ULL,
|
||||||
|
0x822081014405ULL, 0x800c049e40400804ULL, 0x4a0404028a000820ULL,
|
||||||
|
0x22060201041200ULL, 0x360904200840801ULL, 0x881a08208800400ULL,
|
||||||
|
0x60202c00400420ULL, 0x1204440086061400ULL, 0x8184042804040ULL,
|
||||||
|
0x64040315300400ULL, 0xc01008801090a00ULL, 0x808010401140c00ULL,
|
||||||
|
0x4004830c2020040ULL, 0x80005002020054ULL, 0x40000c14481a0490ULL,
|
||||||
|
0x10500101042048ULL, 0x1010100200424000ULL, 0x640901901040ULL,
|
||||||
|
0xa0201014840ULL, 0x840082aa011002ULL, 0x10010840084240aULL,
|
||||||
|
0x420400810420608ULL, 0x8d40230408102100ULL, 0x4a00200612222409ULL,
|
||||||
|
0xa08520292120600ULL
|
||||||
|
};
|
||||||
|
|
||||||
uint8_t PopCnt16[1 << 16];
|
const uint64_t RMult[64] = {
|
||||||
uint8_t SquareDistance[SQUARE_NB][SQUARE_NB];
|
0xa8002c000108020ULL, 0x4440200140003000ULL, 0x8080200010011880ULL,
|
||||||
|
0x380180080141000ULL, 0x1a00060008211044ULL, 0x410001000a0c0008ULL,
|
||||||
|
0x9500060004008100ULL, 0x100024284a20700ULL, 0x802140008000ULL,
|
||||||
|
0x80c01002a00840ULL, 0x402004282011020ULL, 0x9862000820420050ULL,
|
||||||
|
0x1001448011100ULL, 0x6432800200800400ULL, 0x40100010002000cULL,
|
||||||
|
0x2800d0010c080ULL, 0x90c0008000803042ULL, 0x4010004000200041ULL,
|
||||||
|
0x3010010200040ULL, 0xa40828028001000ULL, 0x123010008000430ULL,
|
||||||
|
0x24008004020080ULL, 0x60040001104802ULL, 0x582200028400d1ULL,
|
||||||
|
0x4000802080044000ULL, 0x408208200420308ULL, 0x610038080102000ULL,
|
||||||
|
0x3601000900100020ULL, 0x80080040180ULL, 0xc2020080040080ULL,
|
||||||
|
0x80084400100102ULL, 0x4022408200014401ULL, 0x40052040800082ULL,
|
||||||
|
0xb08200280804000ULL, 0x8a80a008801000ULL, 0x4000480080801000ULL,
|
||||||
|
0x911808800801401ULL, 0x822a003002001894ULL, 0x401068091400108aULL,
|
||||||
|
0x4a10a00004cULL, 0x2000800640008024ULL, 0x1486408102020020ULL,
|
||||||
|
0x100a000d50041ULL, 0x810050020b0020ULL, 0x204000800808004ULL,
|
||||||
|
0x20048100a000cULL, 0x112000831020004ULL, 0x9000040810002ULL,
|
||||||
|
0x440490200208200ULL, 0x8910401000200040ULL, 0x6404200050008480ULL,
|
||||||
|
0x4b824a2010010100ULL, 0x4080801810c0080ULL, 0x400802a0080ULL,
|
||||||
|
0x8224080110026400ULL, 0x40002c4104088200ULL, 0x1002100104a0282ULL,
|
||||||
|
0x1208400811048021ULL, 0x3201014a40d02001ULL, 0x5100019200501ULL,
|
||||||
|
0x101000208001005ULL, 0x2008450080702ULL, 0x1002080301d00cULL,
|
||||||
|
0x410201ce5c030092ULL
|
||||||
|
};
|
||||||
|
|
||||||
Bitboard LineBB[SQUARE_NB][SQUARE_NB];
|
const int BShift[64] = {
|
||||||
Bitboard BetweenBB[SQUARE_NB][SQUARE_NB];
|
58, 59, 59, 59, 59, 59, 59, 58, 59, 59, 59, 59, 59, 59, 59, 59,
|
||||||
Bitboard PseudoAttacks[PIECE_TYPE_NB][SQUARE_NB];
|
59, 59, 57, 57, 57, 57, 59, 59, 59, 59, 57, 55, 55, 57, 59, 59,
|
||||||
Bitboard PawnAttacks[COLOR_NB][SQUARE_NB];
|
59, 59, 57, 55, 55, 57, 59, 59, 59, 59, 57, 57, 57, 57, 59, 59,
|
||||||
|
59, 59, 59, 59, 59, 59, 59, 59, 58, 59, 59, 59, 59, 59, 59, 58
|
||||||
|
};
|
||||||
|
|
||||||
Magic RookMagics[SQUARE_NB];
|
const int RShift[64] = {
|
||||||
Magic BishopMagics[SQUARE_NB];
|
52, 53, 53, 53, 53, 53, 53, 52, 53, 54, 54, 54, 54, 54, 54, 53,
|
||||||
|
53, 54, 54, 54, 54, 54, 54, 53, 53, 54, 54, 54, 54, 54, 54, 53,
|
||||||
|
53, 54, 54, 54, 54, 54, 54, 53, 53, 54, 54, 54, 54, 54, 54, 53,
|
||||||
|
53, 54, 54, 54, 54, 54, 54, 53, 52, 53, 53, 53, 53, 53, 53, 52
|
||||||
|
};
|
||||||
|
|
||||||
|
#else // if !defined(IS_64BIT)
|
||||||
|
|
||||||
|
const uint64_t BMult[64] = {
|
||||||
|
0x54142844c6a22981ULL, 0x710358a6ea25c19eULL, 0x704f746d63a4a8dcULL,
|
||||||
|
0xbfed1a0b80f838c5ULL, 0x90561d5631e62110ULL, 0x2804260376e60944ULL,
|
||||||
|
0x84a656409aa76871ULL, 0xf0267f64c28b6197ULL, 0x70764ebb762f0585ULL,
|
||||||
|
0x92aa09e0cfe161deULL, 0x41ee1f6bb266f60eULL, 0xddcbf04f6039c444ULL,
|
||||||
|
0x5a3fab7bac0d988aULL, 0xd3727877fa4eaa03ULL, 0xd988402d868ddaaeULL,
|
||||||
|
0x812b291afa075c7cULL, 0x94faf987b685a932ULL, 0x3ed867d8470d08dbULL,
|
||||||
|
0x92517660b8901de8ULL, 0x2d97e43e058814b4ULL, 0x880a10c220b25582ULL,
|
||||||
|
0xc7c6520d1f1a0477ULL, 0xdbfc7fbcd7656aa6ULL, 0x78b1b9bfb1a2b84fULL,
|
||||||
|
0x2f20037f112a0bc1ULL, 0x657171ea2269a916ULL, 0xc08302b07142210eULL,
|
||||||
|
0x880a4403064080bULL, 0x3602420842208c00ULL, 0x852800dc7e0b6602ULL,
|
||||||
|
0x595a3fbbaa0f03b2ULL, 0x9f01411558159d5eULL, 0x2b4a4a5f88b394f2ULL,
|
||||||
|
0x4afcbffc292dd03aULL, 0x4a4094a3b3f10522ULL, 0xb06f00b491f30048ULL,
|
||||||
|
0xd5b3820280d77004ULL, 0x8b2e01e7c8e57a75ULL, 0x2d342794e886c2e6ULL,
|
||||||
|
0xc302c410cde21461ULL, 0x111f426f1379c274ULL, 0xe0569220abb31588ULL,
|
||||||
|
0x5026d3064d453324ULL, 0xe2076040c343cd8aULL, 0x93efd1e1738021eeULL,
|
||||||
|
0xb680804bed143132ULL, 0x44e361b21986944cULL, 0x44c60170ef5c598cULL,
|
||||||
|
0xf4da475c195c9c94ULL, 0xa3afbb5f72060b1dULL, 0xbc75f410e41c4ffcULL,
|
||||||
|
0xb51c099390520922ULL, 0x902c011f8f8ec368ULL, 0x950b56b3d6f5490aULL,
|
||||||
|
0x3909e0635bf202d0ULL, 0x5744f90206ec10ccULL, 0xdc59fd76317abbc1ULL,
|
||||||
|
0x881c7c67fcbfc4f6ULL, 0x47ca41e7e440d423ULL, 0xeb0c88112048d004ULL,
|
||||||
|
0x51c60e04359aef1aULL, 0x1aa1fe0e957a5554ULL, 0xdd9448db4f5e3104ULL,
|
||||||
|
0xdc01f6dca4bebbdcULL,
|
||||||
|
};
|
||||||
|
|
||||||
|
const uint64_t RMult[64] = {
|
||||||
|
0xd7445cdec88002c0ULL, 0xd0a505c1f2001722ULL, 0xe065d1c896002182ULL,
|
||||||
|
0x9a8c41e75a000892ULL, 0x8900b10c89002aa8ULL, 0x9b28d1c1d60005a2ULL,
|
||||||
|
0x15d6c88de002d9aULL, 0xb1dbfc802e8016a9ULL, 0x149a1042d9d60029ULL,
|
||||||
|
0xb9c08050599e002fULL, 0x132208c3af300403ULL, 0xc1000ce2e9c50070ULL,
|
||||||
|
0x9d9aa13c99020012ULL, 0xb6b078daf71e0046ULL, 0x9d880182fb6e002eULL,
|
||||||
|
0x52889f467e850037ULL, 0xda6dc008d19a8480ULL, 0x468286034f902420ULL,
|
||||||
|
0x7140ac09dc54c020ULL, 0xd76ffffa39548808ULL, 0xea901c4141500808ULL,
|
||||||
|
0xc91004093f953a02ULL, 0x2882afa8f6bb402ULL, 0xaebe335692442c01ULL,
|
||||||
|
0xe904a22079fb91eULL, 0x13a514851055f606ULL, 0x76c782018c8fe632ULL,
|
||||||
|
0x1dc012a9d116da06ULL, 0x3c9e0037264fffa6ULL, 0x2036002853c6e4a2ULL,
|
||||||
|
0xe3fe08500afb47d4ULL, 0xf38af25c86b025c2ULL, 0xc0800e2182cf9a40ULL,
|
||||||
|
0x72002480d1f60673ULL, 0x2500200bae6e9b53ULL, 0xc60018c1eefca252ULL,
|
||||||
|
0x600590473e3608aULL, 0x46002c4ab3fe51b2ULL, 0xa200011486bcc8d2ULL,
|
||||||
|
0xb680078095784c63ULL, 0x2742002639bf11aeULL, 0xc7d60021a5bdb142ULL,
|
||||||
|
0xc8c04016bb83d820ULL, 0xbd520028123b4842ULL, 0x9d1600344ac2a832ULL,
|
||||||
|
0x6a808005631c8a05ULL, 0x604600a148d5389aULL, 0xe2e40103d40dea65ULL,
|
||||||
|
0x945b5a0087c62a81ULL, 0x12dc200cd82d28eULL, 0x2431c600b5f9ef76ULL,
|
||||||
|
0xfb142a006a9b314aULL, 0x6870e00a1c97d62ULL, 0x2a9db2004a2689a2ULL,
|
||||||
|
0xd3594600caf5d1a2ULL, 0xee0e4900439344a7ULL, 0x89c4d266ca25007aULL,
|
||||||
|
0x3e0013a2743f97e3ULL, 0x180e31a0431378aULL, 0x3a9e465a4d42a512ULL,
|
||||||
|
0x98d0a11a0c0d9cc2ULL, 0x8e711c1aba19b01eULL, 0x8dcdc836dd201142ULL,
|
||||||
|
0x5ac08a4735370479ULL,
|
||||||
|
};
|
||||||
|
|
||||||
|
const int BShift[64] = {
|
||||||
|
26, 27, 27, 27, 27, 27, 27, 26, 27, 27, 27, 27, 27, 27, 27, 27,
|
||||||
|
27, 27, 25, 25, 25, 25, 27, 27, 27, 27, 25, 23, 23, 25, 27, 27,
|
||||||
|
27, 27, 25, 23, 23, 25, 27, 27, 27, 27, 25, 25, 25, 25, 27, 27,
|
||||||
|
27, 27, 27, 27, 27, 27, 27, 27, 26, 27, 27, 27, 27, 27, 27, 26
|
||||||
|
};
|
||||||
|
|
||||||
|
const int RShift[64] = {
|
||||||
|
20, 21, 21, 21, 21, 21, 21, 20, 21, 22, 22, 22, 22, 22, 22, 21,
|
||||||
|
21, 22, 22, 22, 22, 22, 22, 21, 21, 22, 22, 22, 22, 22, 22, 21,
|
||||||
|
21, 22, 22, 22, 22, 22, 22, 21, 21, 22, 22, 22, 22, 22, 22, 21,
|
||||||
|
21, 22, 22, 22, 22, 22, 22, 21, 20, 21, 21, 21, 21, 21, 21, 20
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif // defined(IS_64BIT)
|
||||||
|
|
||||||
|
const Bitboard SquaresByColorBB[2] = { BlackSquaresBB, WhiteSquaresBB };
|
||||||
|
|
||||||
|
const Bitboard FileBB[8] = {
|
||||||
|
FileABB, FileBBB, FileCBB, FileDBB, FileEBB, FileFBB, FileGBB, FileHBB
|
||||||
|
};
|
||||||
|
|
||||||
|
const Bitboard NeighboringFilesBB[8] = {
|
||||||
|
FileBBB, FileABB|FileCBB, FileBBB|FileDBB, FileCBB|FileEBB,
|
||||||
|
FileDBB|FileFBB, FileEBB|FileGBB, FileFBB|FileHBB, FileGBB
|
||||||
|
};
|
||||||
|
|
||||||
|
const Bitboard ThisAndNeighboringFilesBB[8] = {
|
||||||
|
FileABB|FileBBB, FileABB|FileBBB|FileCBB,
|
||||||
|
FileBBB|FileCBB|FileDBB, FileCBB|FileDBB|FileEBB,
|
||||||
|
FileDBB|FileEBB|FileFBB, FileEBB|FileFBB|FileGBB,
|
||||||
|
FileFBB|FileGBB|FileHBB, FileGBB|FileHBB
|
||||||
|
};
|
||||||
|
|
||||||
|
const Bitboard RankBB[8] = {
|
||||||
|
Rank1BB, Rank2BB, Rank3BB, Rank4BB, Rank5BB, Rank6BB, Rank7BB, Rank8BB
|
||||||
|
};
|
||||||
|
|
||||||
|
const Bitboard RelativeRankBB[2][8] = {
|
||||||
|
{ Rank1BB, Rank2BB, Rank3BB, Rank4BB, Rank5BB, Rank6BB, Rank7BB, Rank8BB },
|
||||||
|
{ Rank8BB, Rank7BB, Rank6BB, Rank5BB, Rank4BB, Rank3BB, Rank2BB, Rank1BB }
|
||||||
|
};
|
||||||
|
|
||||||
|
const Bitboard InFrontBB[2][8] = {
|
||||||
|
{ Rank2BB | Rank3BB | Rank4BB | Rank5BB | Rank6BB | Rank7BB | Rank8BB,
|
||||||
|
Rank3BB | Rank4BB | Rank5BB | Rank6BB | Rank7BB | Rank8BB,
|
||||||
|
Rank4BB | Rank5BB | Rank6BB | Rank7BB | Rank8BB,
|
||||||
|
Rank5BB | Rank6BB | Rank7BB | Rank8BB,
|
||||||
|
Rank6BB | Rank7BB | Rank8BB,
|
||||||
|
Rank7BB | Rank8BB,
|
||||||
|
Rank8BB,
|
||||||
|
EmptyBoardBB
|
||||||
|
},
|
||||||
|
{ EmptyBoardBB,
|
||||||
|
Rank1BB,
|
||||||
|
Rank2BB | Rank1BB,
|
||||||
|
Rank3BB | Rank2BB | Rank1BB,
|
||||||
|
Rank4BB | Rank3BB | Rank2BB | Rank1BB,
|
||||||
|
Rank5BB | Rank4BB | Rank3BB | Rank2BB | Rank1BB,
|
||||||
|
Rank6BB | Rank5BB | Rank4BB | Rank3BB | Rank2BB | Rank1BB,
|
||||||
|
Rank7BB | Rank6BB | Rank5BB | Rank4BB | Rank3BB | Rank2BB | Rank1BB
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
Bitboard RMask[64];
|
||||||
|
int RAttackIndex[64];
|
||||||
|
Bitboard RAttacks[0x19000];
|
||||||
|
|
||||||
|
Bitboard BMask[64];
|
||||||
|
int BAttackIndex[64];
|
||||||
|
Bitboard BAttacks[0x1480];
|
||||||
|
|
||||||
|
Bitboard SetMaskBB[65];
|
||||||
|
Bitboard ClearMaskBB[65];
|
||||||
|
|
||||||
|
Bitboard StepAttackBB[16][64];
|
||||||
|
Bitboard RayBB[64][8];
|
||||||
|
Bitboard BetweenBB[64][64];
|
||||||
|
|
||||||
|
Bitboard PassedPawnMask[2][64];
|
||||||
|
Bitboard OutpostMask[2][64];
|
||||||
|
|
||||||
|
Bitboard BishopPseudoAttacks[64];
|
||||||
|
Bitboard RookPseudoAttacks[64];
|
||||||
|
Bitboard QueenPseudoAttacks[64];
|
||||||
|
|
||||||
|
uint8_t BitCount8Bit[256];
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Local definitions
|
||||||
|
////
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
Bitboard RookTable[0x19000]; // To store rook attacks
|
void init_masks();
|
||||||
Bitboard BishopTable[0x1480]; // To store bishop attacks
|
void init_ray_bitboards();
|
||||||
|
void init_attacks();
|
||||||
void init_magics(PieceType pt, Bitboard table[], Magic magics[]);
|
void init_between_bitboards();
|
||||||
|
Bitboard sliding_attacks(int sq, Bitboard block, int dirs, int deltas[][2],
|
||||||
// Returns the bitboard of target square for the given step
|
int fmin, int fmax, int rmin, int rmax);
|
||||||
// from the given square. If the step is off the board, returns empty bitboard.
|
Bitboard index_to_bitboard(int index, Bitboard mask);
|
||||||
Bitboard safe_destination(Square s, int step) {
|
void init_sliding_attacks(Bitboard attacks[],
|
||||||
Square to = Square(s + step);
|
int attackIndex[], Bitboard mask[],
|
||||||
return is_ok(to) && distance(s, to) <= 2 ? square_bb(to) : Bitboard(0);
|
const int shift[2], const Bitboard mult[],
|
||||||
}
|
int deltas[][2]);
|
||||||
}
|
void init_pseudo_attacks();
|
||||||
|
|
||||||
// Returns an ASCII representation of a bitboard suitable
|
|
||||||
// to be printed to standard output. Useful for debugging.
|
|
||||||
std::string Bitboards::pretty(Bitboard b) {
|
|
||||||
|
|
||||||
std::string s = "+---+---+---+---+---+---+---+---+\n";
|
|
||||||
|
|
||||||
for (Rank r = RANK_8; r >= RANK_1; --r)
|
|
||||||
{
|
|
||||||
for (File f = FILE_A; f <= FILE_H; ++f)
|
|
||||||
s += b & make_square(f, r) ? "| X " : "| ";
|
|
||||||
|
|
||||||
s += "| " + std::to_string(1 + r) + "\n+---+---+---+---+---+---+---+---+\n";
|
|
||||||
}
|
|
||||||
s += " a b c d e f g h\n";
|
|
||||||
|
|
||||||
return s;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Initializes various bitboard tables. It is called at
|
////
|
||||||
// startup and relies on global objects to be already zero-initialized.
|
//// Functions
|
||||||
void Bitboards::init() {
|
////
|
||||||
|
|
||||||
for (unsigned i = 0; i < (1 << 16); ++i)
|
/// print_bitboard() prints a bitboard in an easily readable format to the
|
||||||
PopCnt16[i] = uint8_t(std::bitset<16>(i).count());
|
/// standard output. This is sometimes useful for debugging.
|
||||||
|
|
||||||
for (Square s1 = SQ_A1; s1 <= SQ_H8; ++s1)
|
void print_bitboard(Bitboard b) {
|
||||||
for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
|
for(Rank r = RANK_8; r >= RANK_1; r--) {
|
||||||
SquareDistance[s1][s2] = std::max(distance<File>(s1, s2), distance<Rank>(s1, s2));
|
std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
|
||||||
|
for(File f = FILE_A; f <= FILE_H; f++)
|
||||||
|
std::cout << "| " << (bit_is_set(b, make_square(f, r))? 'X' : ' ') << ' ';
|
||||||
|
std::cout << "|" << std::endl;
|
||||||
|
}
|
||||||
|
std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
init_magics(ROOK, RookTable, RookMagics);
|
|
||||||
init_magics(BISHOP, BishopTable, BishopMagics);
|
|
||||||
|
|
||||||
for (Square s1 = SQ_A1; s1 <= SQ_H8; ++s1)
|
/// init_bitboards() initializes various bitboard arrays. It is called during
|
||||||
{
|
/// program initialization.
|
||||||
PawnAttacks[WHITE][s1] = pawn_attacks_bb<WHITE>(square_bb(s1));
|
|
||||||
PawnAttacks[BLACK][s1] = pawn_attacks_bb<BLACK>(square_bb(s1));
|
|
||||||
|
|
||||||
for (int step : {-9, -8, -7, -1, 1, 7, 8, 9})
|
void init_bitboards() {
|
||||||
PseudoAttacks[KING][s1] |= safe_destination(s1, step);
|
int rookDeltas[4][2] = {{0,1},{0,-1},{1,0},{-1,0}};
|
||||||
|
int bishopDeltas[4][2] = {{1,1},{-1,1},{1,-1},{-1,-1}};
|
||||||
|
init_masks();
|
||||||
|
init_ray_bitboards();
|
||||||
|
init_attacks();
|
||||||
|
init_between_bitboards();
|
||||||
|
init_sliding_attacks(RAttacks, RAttackIndex, RMask, RShift, RMult, rookDeltas);
|
||||||
|
init_sliding_attacks(BAttacks, BAttackIndex, BMask, BShift, BMult, bishopDeltas);
|
||||||
|
init_pseudo_attacks();
|
||||||
|
}
|
||||||
|
|
||||||
for (int step : {-17, -15, -10, -6, 6, 10, 15, 17})
|
|
||||||
PseudoAttacks[KNIGHT][s1] |= safe_destination(s1, step);
|
|
||||||
|
|
||||||
PseudoAttacks[QUEEN][s1] = PseudoAttacks[BISHOP][s1] = attacks_bb<BISHOP>(s1, 0);
|
/// first_1() finds the least significant nonzero bit in a nonzero bitboard.
|
||||||
PseudoAttacks[QUEEN][s1] |= PseudoAttacks[ROOK][s1] = attacks_bb<ROOK>(s1, 0);
|
/// pop_1st_bit() finds and clears the least significant nonzero bit in a
|
||||||
|
/// nonzero bitboard.
|
||||||
|
|
||||||
for (PieceType pt : {BISHOP, ROOK})
|
#if defined(IS_64BIT) && !defined(USE_BSFQ)
|
||||||
for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
|
|
||||||
{
|
CACHE_LINE_ALIGNMENT
|
||||||
if (PseudoAttacks[pt][s1] & s2)
|
static const int BitTable[64] = {
|
||||||
{
|
0, 1, 2, 7, 3, 13, 8, 19, 4, 25, 14, 28, 9, 34, 20, 40, 5, 17, 26, 38, 15,
|
||||||
LineBB[s1][s2] = (attacks_bb(pt, s1, 0) & attacks_bb(pt, s2, 0)) | s1 | s2;
|
46, 29, 48, 10, 31, 35, 54, 21, 50, 41, 57, 63, 6, 12, 18, 24, 27, 33, 39,
|
||||||
BetweenBB[s1][s2] =
|
16, 37, 45, 47, 30, 53, 49, 56, 62, 11, 23, 32, 36, 44, 52, 55, 61, 22, 43,
|
||||||
(attacks_bb(pt, s1, square_bb(s2)) & attacks_bb(pt, s2, square_bb(s1)));
|
51, 60, 42, 59, 58
|
||||||
}
|
};
|
||||||
BetweenBB[s1][s2] |= s2;
|
|
||||||
}
|
Square first_1(Bitboard b) {
|
||||||
}
|
return Square(BitTable[((b & -b) * 0x218a392cd3d5dbfULL) >> 58]);
|
||||||
|
}
|
||||||
|
|
||||||
|
Square pop_1st_bit(Bitboard* b) {
|
||||||
|
Bitboard bb = *b;
|
||||||
|
*b &= (*b - 1);
|
||||||
|
return Square(BitTable[((bb & -bb) * 0x218a392cd3d5dbfULL) >> 58]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#elif !defined(USE_BSFQ)
|
||||||
|
|
||||||
|
static CACHE_LINE_ALIGNMENT
|
||||||
|
const int BitTable[64] = {
|
||||||
|
63, 30, 3, 32, 25, 41, 22, 33, 15, 50, 42, 13, 11, 53, 19, 34, 61, 29, 2,
|
||||||
|
51, 21, 43, 45, 10, 18, 47, 1, 54, 9, 57, 0, 35, 62, 31, 40, 4, 49, 5, 52,
|
||||||
|
26, 60, 6, 23, 44, 46, 27, 56, 16, 7, 39, 48, 24, 59, 14, 12, 55, 38, 28,
|
||||||
|
58, 20, 37, 17, 36, 8
|
||||||
|
};
|
||||||
|
|
||||||
|
Square first_1(Bitboard b) {
|
||||||
|
b ^= (b - 1);
|
||||||
|
uint32_t fold = int(b) ^ int(b >> 32);
|
||||||
|
return Square(BitTable[(fold * 0x783a9b23) >> 26]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use type-punning
|
||||||
|
union b_union {
|
||||||
|
|
||||||
|
Bitboard b;
|
||||||
|
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) {
|
||||||
|
|
||||||
|
b_union u;
|
||||||
|
Square ret;
|
||||||
|
|
||||||
|
u.b = *bb;
|
||||||
|
|
||||||
|
if (u.dw.l)
|
||||||
|
{
|
||||||
|
ret = Square(BitTable[((u.dw.l ^ (u.dw.l - 1)) * 0x783a9b23) >> 26]);
|
||||||
|
u.dw.l &= (u.dw.l - 1);
|
||||||
|
*bb = u.b;
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
ret = Square(BitTable[((~(u.dw.h ^ (u.dw.h - 1))) * 0x783a9b23) >> 26]);
|
||||||
|
u.dw.h &= (u.dw.h - 1);
|
||||||
|
*bb = u.b;
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
int bitScanReverse32(uint32_t b)
|
||||||
|
{
|
||||||
|
int result = 0;
|
||||||
|
|
||||||
|
if (b > 0xFFFF) {
|
||||||
|
b >>= 16;
|
||||||
|
result += 16;
|
||||||
|
}
|
||||||
|
if (b > 0xFF) {
|
||||||
|
b >>= 8;
|
||||||
|
result += 8;
|
||||||
|
}
|
||||||
|
if (b > 0xF) {
|
||||||
|
b >>= 4;
|
||||||
|
result += 4;
|
||||||
|
}
|
||||||
|
if (b > 0x3) {
|
||||||
|
b >>= 2;
|
||||||
|
result += 2;
|
||||||
|
}
|
||||||
|
return result + (b > 0) + (b > 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
Bitboard sliding_attack(PieceType pt, Square sq, Bitboard occupied) {
|
// All functions below are used to precompute various bitboards during
|
||||||
|
// program initialization. Some of the functions may be difficult to
|
||||||
|
// understand, but they all seem to work correctly, and it should never
|
||||||
|
// be necessary to touch any of them.
|
||||||
|
|
||||||
Bitboard attacks = 0;
|
void init_masks() {
|
||||||
Direction RookDirections[4] = {NORTH, SOUTH, EAST, WEST};
|
SetMaskBB[SQ_NONE] = 0ULL;
|
||||||
Direction BishopDirections[4] = {NORTH_EAST, SOUTH_EAST, SOUTH_WEST, NORTH_WEST};
|
ClearMaskBB[SQ_NONE] = ~SetMaskBB[SQ_NONE];
|
||||||
|
for(Square s = SQ_A1; s <= SQ_H8; s++) {
|
||||||
for (Direction d : (pt == ROOK ? RookDirections : BishopDirections))
|
SetMaskBB[s] = (1ULL << s);
|
||||||
{
|
ClearMaskBB[s] = ~SetMaskBB[s];
|
||||||
Square s = sq;
|
|
||||||
while (safe_destination(s, d))
|
|
||||||
{
|
|
||||||
attacks |= (s += d);
|
|
||||||
if (occupied & s)
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
for(Color c = WHITE; c <= BLACK; c++)
|
||||||
|
for(Square s = SQ_A1; s <= SQ_H8; s++) {
|
||||||
|
PassedPawnMask[c][s] =
|
||||||
|
in_front_bb(c, s) & this_and_neighboring_files_bb(s);
|
||||||
|
OutpostMask[c][s] = in_front_bb(c, s) & neighboring_files_bb(s);
|
||||||
|
}
|
||||||
|
|
||||||
return attacks;
|
for (Bitboard b = 0ULL; b < 256ULL; b++)
|
||||||
}
|
BitCount8Bit[b] = (uint8_t)count_1s(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
// Computes all rook and bishop attacks at startup. Magic
|
void init_ray_bitboards() {
|
||||||
// bitboards are used to look up attacks of sliding pieces. As a reference see
|
int d[8] = {1, -1, 16, -16, 17, -17, 15, -15};
|
||||||
// www.chessprogramming.org/Magic_Bitboards. In particular, here we use the so
|
for(int i = 0; i < 128; i = (i + 9) & ~8) {
|
||||||
// called "fancy" approach.
|
for(int j = 0; j < 8; j++) {
|
||||||
void init_magics(PieceType pt, Bitboard table[], Magic magics[]) {
|
RayBB[(i&7)|((i>>4)<<3)][j] = EmptyBoardBB;
|
||||||
|
for(int k = i + d[j]; (k & 0x88) == 0; k += d[j])
|
||||||
// Optimal PRNG seeds to pick the correct magics in the shortest time
|
set_bit(&(RayBB[(i&7)|((i>>4)<<3)][j]), Square((k&7)|((k>>4)<<3)));
|
||||||
int seeds[][RANK_NB] = {{8977, 44560, 54343, 38998, 5731, 95205, 104912, 17020},
|
}
|
||||||
{728, 10316, 55013, 32803, 12281, 15100, 16645, 255}};
|
|
||||||
|
|
||||||
Bitboard occupancy[4096], reference[4096], edges, b;
|
|
||||||
int epoch[4096] = {}, cnt = 0, size = 0;
|
|
||||||
|
|
||||||
for (Square s = SQ_A1; s <= SQ_H8; ++s)
|
|
||||||
{
|
|
||||||
// Board edges are not considered in the relevant occupancies
|
|
||||||
edges = ((Rank1BB | Rank8BB) & ~rank_bb(s)) | ((FileABB | FileHBB) & ~file_bb(s));
|
|
||||||
|
|
||||||
// Given a square 's', the mask is the bitboard of sliding attacks from
|
|
||||||
// 's' computed on an empty board. The index must be big enough to contain
|
|
||||||
// all the attacks for each possible subset of the mask and so is 2 power
|
|
||||||
// the number of 1s of the mask. Hence we deduce the size of the shift to
|
|
||||||
// apply to the 64 or 32 bits word to get the index.
|
|
||||||
Magic& m = magics[s];
|
|
||||||
m.mask = sliding_attack(pt, s, 0) & ~edges;
|
|
||||||
m.shift = (Is64Bit ? 64 : 32) - popcount(m.mask);
|
|
||||||
|
|
||||||
// Set the offset for the attacks table of the square. We have individual
|
|
||||||
// table sizes for each square with "Fancy Magic Bitboards".
|
|
||||||
m.attacks = s == SQ_A1 ? table : magics[s - 1].attacks + size;
|
|
||||||
|
|
||||||
// Use Carry-Rippler trick to enumerate all subsets of masks[s] and
|
|
||||||
// store the corresponding sliding attack bitboard in reference[].
|
|
||||||
b = size = 0;
|
|
||||||
do
|
|
||||||
{
|
|
||||||
occupancy[size] = b;
|
|
||||||
reference[size] = sliding_attack(pt, s, b);
|
|
||||||
|
|
||||||
if (HasPext)
|
|
||||||
m.attacks[pext(b, m.mask)] = reference[size];
|
|
||||||
|
|
||||||
size++;
|
|
||||||
b = (b - m.mask) & m.mask;
|
|
||||||
} while (b);
|
|
||||||
|
|
||||||
if (HasPext)
|
|
||||||
continue;
|
|
||||||
|
|
||||||
PRNG rng(seeds[Is64Bit][rank_of(s)]);
|
|
||||||
|
|
||||||
// Find a magic for square 's' picking up an (almost) random number
|
|
||||||
// until we find the one that passes the verification test.
|
|
||||||
for (int i = 0; i < size;)
|
|
||||||
{
|
|
||||||
for (m.magic = 0; popcount((m.magic * m.mask) >> 56) < 6;)
|
|
||||||
m.magic = rng.sparse_rand<Bitboard>();
|
|
||||||
|
|
||||||
// A good magic must map every possible occupancy to an index that
|
|
||||||
// looks up the correct sliding attack in the attacks[s] database.
|
|
||||||
// Note that we build up the database for square 's' as a side
|
|
||||||
// effect of verifying the magic. Keep track of the attempt count
|
|
||||||
// and save it in epoch[], little speed-up trick to avoid resetting
|
|
||||||
// m.attacks[] after every failed attempt.
|
|
||||||
for (++cnt, i = 0; i < size; ++i)
|
|
||||||
{
|
|
||||||
unsigned idx = m.index(occupancy[i]);
|
|
||||||
|
|
||||||
if (epoch[idx] < cnt)
|
|
||||||
{
|
|
||||||
epoch[idx] = cnt;
|
|
||||||
m.attacks[idx] = reference[i];
|
|
||||||
}
|
|
||||||
else if (m.attacks[idx] != reference[i])
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Stockfish
|
|
||||||
|
void init_attacks() {
|
||||||
|
int i, j, k, l;
|
||||||
|
int step[16][8] = {
|
||||||
|
{0},
|
||||||
|
{7,9,0}, {17,15,10,6,-6,-10,-15,-17}, {9,7,-7,-9,0}, {8,1,-1,-8,0},
|
||||||
|
{9,7,-7,-9,8,1,-1,-8}, {9,7,-7,-9,8,1,-1,-8}, {0}, {0},
|
||||||
|
{-7,-9,0}, {17,15,10,6,-6,-10,-15,-17}, {9,7,-7,-9,0}, {8,1,-1,-8,0},
|
||||||
|
{9,7,-7,-9,8,1,-1,-8}, {9,7,-7,-9,8,1,-1,-8}
|
||||||
|
};
|
||||||
|
|
||||||
|
for(i = 0; i < 64; i++) {
|
||||||
|
for(j = 0; j <= int(BK); j++) {
|
||||||
|
StepAttackBB[j][i] = EmptyBoardBB;
|
||||||
|
for(k = 0; k < 8 && step[j][k] != 0; k++) {
|
||||||
|
l = i + step[j][k];
|
||||||
|
if(l >= 0 && l < 64 && abs((i&7) - (l&7)) < 3)
|
||||||
|
StepAttackBB[j][i] |= (1ULL << l);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Bitboard sliding_attacks(int sq, Bitboard block, int dirs, int deltas[][2],
|
||||||
|
int fmin=0, int fmax=7, int rmin=0, int rmax=7) {
|
||||||
|
Bitboard result = 0ULL;
|
||||||
|
int rk = sq / 8, fl = sq % 8, r, f, i;
|
||||||
|
for(i = 0; i < dirs; i++) {
|
||||||
|
int dx = deltas[i][0], dy = deltas[i][1];
|
||||||
|
for(f = fl+dx, r = rk+dy;
|
||||||
|
(dx==0 || (f>=fmin && f<=fmax)) && (dy==0 || (r>=rmin && r<=rmax));
|
||||||
|
f += dx, r += dy) {
|
||||||
|
result |= (1ULL << (f + r*8));
|
||||||
|
if(block & (1ULL << (f + r*8))) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void init_between_bitboards() {
|
||||||
|
SquareDelta step[8] = {
|
||||||
|
DELTA_E, DELTA_W, DELTA_N, DELTA_S, DELTA_NE, DELTA_SW, DELTA_NW, DELTA_SE
|
||||||
|
};
|
||||||
|
SignedDirection d;
|
||||||
|
for(Square s1 = SQ_A1; s1 <= SQ_H8; s1++)
|
||||||
|
for(Square s2 = SQ_A1; s2 <= SQ_H8; s2++) {
|
||||||
|
BetweenBB[s1][s2] = EmptyBoardBB;
|
||||||
|
d = signed_direction_between_squares(s1, s2);
|
||||||
|
if(d != SIGNED_DIR_NONE)
|
||||||
|
for(Square s3 = s1 + step[d]; s3 != s2; s3 += step[d])
|
||||||
|
set_bit(&(BetweenBB[s1][s2]), s3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
Bitboard index_to_bitboard(int index, Bitboard mask) {
|
||||||
|
int i, j, bits = count_1s(mask);
|
||||||
|
Bitboard result = 0ULL;
|
||||||
|
for(i = 0; i < bits; i++) {
|
||||||
|
j = pop_1st_bit(&mask);
|
||||||
|
if(index & (1 << i)) result |= (1ULL << j);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void init_sliding_attacks(Bitboard attacks[],
|
||||||
|
int attackIndex[], Bitboard mask[],
|
||||||
|
const int shift[2], const Bitboard mult[],
|
||||||
|
int deltas[][2]) {
|
||||||
|
int i, j, k, index = 0;
|
||||||
|
Bitboard b;
|
||||||
|
for(i = 0; i < 64; i++) {
|
||||||
|
attackIndex[i] = index;
|
||||||
|
mask[i] = sliding_attacks(i, 0ULL, 4, deltas, 1, 6, 1, 6);
|
||||||
|
|
||||||
|
#if defined(IS_64BIT)
|
||||||
|
j = (1 << (64 - shift[i]));
|
||||||
|
#else
|
||||||
|
j = (1 << (32 - shift[i]));
|
||||||
|
#endif
|
||||||
|
|
||||||
|
for(k = 0; k < j; k++) {
|
||||||
|
|
||||||
|
#if defined(IS_64BIT)
|
||||||
|
b = index_to_bitboard(k, mask[i]);
|
||||||
|
attacks[index + ((b * mult[i]) >> shift[i])] =
|
||||||
|
sliding_attacks(i, b, 4, deltas);
|
||||||
|
#else
|
||||||
|
b = index_to_bitboard(k, mask[i]);
|
||||||
|
attacks[index +
|
||||||
|
(unsigned(int(b) * int(mult[i]) ^
|
||||||
|
int(b >> 32) * int(mult[i] >> 32))
|
||||||
|
>> shift[i])] =
|
||||||
|
sliding_attacks(i, b, 4, deltas);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
index += j;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
void init_pseudo_attacks() {
|
||||||
|
Square s;
|
||||||
|
for(s = SQ_A1; s <= SQ_H8; s++) {
|
||||||
|
BishopPseudoAttacks[s] = bishop_attacks_bb(s, EmptyBoardBB);
|
||||||
|
RookPseudoAttacks[s] = rook_attacks_bb(s, EmptyBoardBB);
|
||||||
|
QueenPseudoAttacks[s] = queen_attacks_bb(s, EmptyBoardBB);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|||||||
+270
-286
@@ -1,12 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
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-2024 The Stockfish developers (see AUTHORS file)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
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
|
||||||
the Free Software Foundation, either version 3 of the License, or
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
(at your option) any later version.
|
(at your option) any later version.
|
||||||
|
|
||||||
|
|
||||||
Stockfish is distributed in the hope that it will be useful,
|
Stockfish is distributed in the hope that it will be useful,
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
@@ -16,356 +18,338 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#ifndef BITBOARD_H_INCLUDED
|
|
||||||
|
#if !defined(BITBOARD_H_INCLUDED)
|
||||||
#define BITBOARD_H_INCLUDED
|
#define BITBOARD_H_INCLUDED
|
||||||
|
|
||||||
#include <algorithm>
|
////
|
||||||
#include <cassert>
|
//// Includes
|
||||||
#include <cmath>
|
////
|
||||||
#include <cstdint>
|
|
||||||
#include <cstdlib>
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
|
#include "direction.h"
|
||||||
|
#include "piece.h"
|
||||||
|
#include "square.h"
|
||||||
#include "types.h"
|
#include "types.h"
|
||||||
|
|
||||||
namespace Stockfish {
|
|
||||||
|
|
||||||
namespace Bitboards {
|
////
|
||||||
|
//// Constants and variables
|
||||||
|
////
|
||||||
|
|
||||||
void init();
|
const Bitboard EmptyBoardBB = 0ULL;
|
||||||
std::string pretty(Bitboard b);
|
|
||||||
|
|
||||||
} // namespace Stockfish::Bitboards
|
const Bitboard WhiteSquaresBB = 0x55AA55AA55AA55AAULL;
|
||||||
|
const Bitboard BlackSquaresBB = 0xAA55AA55AA55AA55ULL;
|
||||||
|
|
||||||
constexpr Bitboard FileABB = 0x0101010101010101ULL;
|
const Bitboard FileABB = 0x0101010101010101ULL;
|
||||||
constexpr Bitboard FileBBB = FileABB << 1;
|
const Bitboard FileBBB = 0x0202020202020202ULL;
|
||||||
constexpr Bitboard FileCBB = FileABB << 2;
|
const Bitboard FileCBB = 0x0404040404040404ULL;
|
||||||
constexpr Bitboard FileDBB = FileABB << 3;
|
const Bitboard FileDBB = 0x0808080808080808ULL;
|
||||||
constexpr Bitboard FileEBB = FileABB << 4;
|
const Bitboard FileEBB = 0x1010101010101010ULL;
|
||||||
constexpr Bitboard FileFBB = FileABB << 5;
|
const Bitboard FileFBB = 0x2020202020202020ULL;
|
||||||
constexpr Bitboard FileGBB = FileABB << 6;
|
const Bitboard FileGBB = 0x4040404040404040ULL;
|
||||||
constexpr Bitboard FileHBB = FileABB << 7;
|
const Bitboard FileHBB = 0x8080808080808080ULL;
|
||||||
|
|
||||||
constexpr Bitboard Rank1BB = 0xFF;
|
const Bitboard Rank1BB = 0xFFULL;
|
||||||
constexpr Bitboard Rank2BB = Rank1BB << (8 * 1);
|
const Bitboard Rank2BB = 0xFF00ULL;
|
||||||
constexpr Bitboard Rank3BB = Rank1BB << (8 * 2);
|
const Bitboard Rank3BB = 0xFF0000ULL;
|
||||||
constexpr Bitboard Rank4BB = Rank1BB << (8 * 3);
|
const Bitboard Rank4BB = 0xFF000000ULL;
|
||||||
constexpr Bitboard Rank5BB = Rank1BB << (8 * 4);
|
const Bitboard Rank5BB = 0xFF00000000ULL;
|
||||||
constexpr Bitboard Rank6BB = Rank1BB << (8 * 5);
|
const Bitboard Rank6BB = 0xFF0000000000ULL;
|
||||||
constexpr Bitboard Rank7BB = Rank1BB << (8 * 6);
|
const Bitboard Rank7BB = 0xFF000000000000ULL;
|
||||||
constexpr Bitboard Rank8BB = Rank1BB << (8 * 7);
|
const Bitboard Rank8BB = 0xFF00000000000000ULL;
|
||||||
|
|
||||||
extern uint8_t PopCnt16[1 << 16];
|
extern const Bitboard SquaresByColorBB[2];
|
||||||
extern uint8_t SquareDistance[SQUARE_NB][SQUARE_NB];
|
extern const Bitboard FileBB[8];
|
||||||
|
extern const Bitboard NeighboringFilesBB[8];
|
||||||
|
extern const Bitboard ThisAndNeighboringFilesBB[8];
|
||||||
|
extern const Bitboard RankBB[8];
|
||||||
|
extern const Bitboard RelativeRankBB[2][8];
|
||||||
|
extern const Bitboard InFrontBB[2][8];
|
||||||
|
|
||||||
extern Bitboard BetweenBB[SQUARE_NB][SQUARE_NB];
|
extern Bitboard SetMaskBB[65];
|
||||||
extern Bitboard LineBB[SQUARE_NB][SQUARE_NB];
|
extern Bitboard ClearMaskBB[65];
|
||||||
extern Bitboard PseudoAttacks[PIECE_TYPE_NB][SQUARE_NB];
|
|
||||||
extern Bitboard PawnAttacks[COLOR_NB][SQUARE_NB];
|
extern Bitboard StepAttackBB[16][64];
|
||||||
|
extern Bitboard RayBB[64][8];
|
||||||
|
extern Bitboard BetweenBB[64][64];
|
||||||
|
|
||||||
|
extern Bitboard PassedPawnMask[2][64];
|
||||||
|
extern Bitboard OutpostMask[2][64];
|
||||||
|
|
||||||
|
extern const uint64_t RMult[64];
|
||||||
|
extern const int RShift[64];
|
||||||
|
extern Bitboard RMask[64];
|
||||||
|
extern int RAttackIndex[64];
|
||||||
|
extern Bitboard RAttacks[0x19000];
|
||||||
|
|
||||||
|
extern const uint64_t BMult[64];
|
||||||
|
extern const int BShift[64];
|
||||||
|
extern Bitboard BMask[64];
|
||||||
|
extern int BAttackIndex[64];
|
||||||
|
extern Bitboard BAttacks[0x1480];
|
||||||
|
|
||||||
|
extern Bitboard BishopPseudoAttacks[64];
|
||||||
|
extern Bitboard RookPseudoAttacks[64];
|
||||||
|
extern Bitboard QueenPseudoAttacks[64];
|
||||||
|
|
||||||
|
extern uint8_t BitCount8Bit[256];
|
||||||
|
|
||||||
|
|
||||||
// Magic holds all magic bitboards relevant data for a single square
|
////
|
||||||
struct Magic {
|
//// Inline functions
|
||||||
Bitboard mask;
|
////
|
||||||
Bitboard magic;
|
|
||||||
Bitboard* attacks;
|
|
||||||
unsigned shift;
|
|
||||||
|
|
||||||
// Compute the attack's index using the 'magic bitboards' approach
|
/// Functions for testing whether a given bit is set in a bitboard, and for
|
||||||
unsigned index(Bitboard occupied) const {
|
/// setting and clearing bits.
|
||||||
|
|
||||||
if (HasPext)
|
inline Bitboard bit_is_set(Bitboard b, Square s) {
|
||||||
return unsigned(pext(occupied, mask));
|
return b & SetMaskBB[s];
|
||||||
|
}
|
||||||
|
|
||||||
if (Is64Bit)
|
inline void set_bit(Bitboard *b, Square s) {
|
||||||
return unsigned(((occupied & mask) * magic) >> shift);
|
*b |= SetMaskBB[s];
|
||||||
|
}
|
||||||
|
|
||||||
unsigned lo = unsigned(occupied) & unsigned(mask);
|
inline void clear_bit(Bitboard *b, Square s) {
|
||||||
unsigned hi = unsigned(occupied >> 32) & unsigned(mask >> 32);
|
*b &= ClearMaskBB[s];
|
||||||
return (lo * unsigned(magic) ^ hi * unsigned(magic >> 32)) >> shift;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
extern Magic RookMagics[SQUARE_NB];
|
|
||||||
extern Magic BishopMagics[SQUARE_NB];
|
|
||||||
|
|
||||||
constexpr Bitboard square_bb(Square s) {
|
|
||||||
assert(is_ok(s));
|
|
||||||
return (1ULL << s);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Overloads of bitwise operators between a Bitboard and a Square for testing
|
/// Functions used to update a bitboard after a move. This is faster
|
||||||
// whether a given bit is set in a bitboard, and for setting and clearing bits.
|
/// then calling a sequence of clear_bit() + set_bit()
|
||||||
|
|
||||||
inline Bitboard operator&(Bitboard b, Square s) { return b & square_bb(s); }
|
inline Bitboard make_move_bb(Square from, Square to) {
|
||||||
inline Bitboard operator|(Bitboard b, Square s) { return b | square_bb(s); }
|
return SetMaskBB[from] | SetMaskBB[to];
|
||||||
inline Bitboard operator^(Bitboard b, Square s) { return b ^ square_bb(s); }
|
}
|
||||||
inline Bitboard& operator|=(Bitboard& b, Square s) { return b |= square_bb(s); }
|
|
||||||
inline Bitboard& operator^=(Bitboard& b, Square s) { return b ^= square_bb(s); }
|
|
||||||
|
|
||||||
inline Bitboard operator&(Square s, Bitboard b) { return b & s; }
|
inline void do_move_bb(Bitboard *b, Bitboard move_bb) {
|
||||||
inline Bitboard operator|(Square s, Bitboard b) { return b | s; }
|
*b ^= move_bb;
|
||||||
inline Bitboard operator^(Square s, Bitboard b) { return b ^ s; }
|
}
|
||||||
|
|
||||||
inline Bitboard operator|(Square s1, Square s2) { return square_bb(s1) | s2; }
|
/// rank_bb() and file_bb() gives a bitboard containing all squares on a given
|
||||||
|
/// file or rank. It is also possible to pass a square as input to these
|
||||||
|
/// functions.
|
||||||
|
|
||||||
constexpr bool more_than_one(Bitboard b) { return b & (b - 1); }
|
inline Bitboard rank_bb(Rank r) {
|
||||||
|
return RankBB[r];
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Bitboard rank_bb(Square s) {
|
||||||
|
return rank_bb(square_rank(s));
|
||||||
|
}
|
||||||
|
|
||||||
// rank_bb() and file_bb() return a bitboard representing all the squares on
|
inline Bitboard file_bb(File f) {
|
||||||
// the given file or rank.
|
return FileBB[f];
|
||||||
|
}
|
||||||
|
|
||||||
constexpr Bitboard rank_bb(Rank r) { return Rank1BB << (8 * r); }
|
inline Bitboard file_bb(Square s) {
|
||||||
|
return file_bb(square_file(s));
|
||||||
constexpr Bitboard rank_bb(Square s) { return rank_bb(rank_of(s)); }
|
|
||||||
|
|
||||||
constexpr Bitboard file_bb(File f) { return FileABB << f; }
|
|
||||||
|
|
||||||
constexpr Bitboard file_bb(Square s) { return file_bb(file_of(s)); }
|
|
||||||
|
|
||||||
|
|
||||||
// Moves a bitboard one or two steps as specified by the direction D
|
|
||||||
template<Direction D>
|
|
||||||
constexpr Bitboard shift(Bitboard b) {
|
|
||||||
return D == NORTH ? b << 8
|
|
||||||
: D == SOUTH ? b >> 8
|
|
||||||
: D == NORTH + NORTH ? b << 16
|
|
||||||
: D == SOUTH + SOUTH ? b >> 16
|
|
||||||
: D == EAST ? (b & ~FileHBB) << 1
|
|
||||||
: D == WEST ? (b & ~FileABB) >> 1
|
|
||||||
: D == NORTH_EAST ? (b & ~FileHBB) << 9
|
|
||||||
: D == NORTH_WEST ? (b & ~FileABB) << 7
|
|
||||||
: D == SOUTH_EAST ? (b & ~FileHBB) >> 7
|
|
||||||
: D == SOUTH_WEST ? (b & ~FileABB) >> 9
|
|
||||||
: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Returns the squares attacked by pawns of the given color
|
/// neighboring_files_bb takes a file or a square as input, and returns a
|
||||||
// from the squares in the given bitboard.
|
/// bitboard representing all squares on the neighboring files.
|
||||||
template<Color C>
|
|
||||||
constexpr Bitboard pawn_attacks_bb(Bitboard b) {
|
inline Bitboard neighboring_files_bb(File f) {
|
||||||
return C == WHITE ? shift<NORTH_WEST>(b) | shift<NORTH_EAST>(b)
|
return NeighboringFilesBB[f];
|
||||||
: shift<SOUTH_WEST>(b) | shift<SOUTH_EAST>(b);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Bitboard pawn_attacks_bb(Color c, Square s) {
|
inline Bitboard neighboring_files_bb(Square s) {
|
||||||
|
return neighboring_files_bb(square_file(s));
|
||||||
assert(is_ok(s));
|
|
||||||
return PawnAttacks[c][s];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns a bitboard representing an entire line (from board edge
|
|
||||||
// to board edge) that intersects the two given squares. If the given squares
|
|
||||||
// are not on a same file/rank/diagonal, the function returns 0. For instance,
|
|
||||||
// line_bb(SQ_C4, SQ_F7) will return a bitboard with the A2-G8 diagonal.
|
|
||||||
inline Bitboard line_bb(Square s1, Square s2) {
|
|
||||||
|
|
||||||
assert(is_ok(s1) && is_ok(s2));
|
|
||||||
return LineBB[s1][s2];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Returns a bitboard representing the squares in the semi-open
|
/// this_and_neighboring_files_bb takes a file or a square as input, and
|
||||||
// segment between the squares s1 and s2 (excluding s1 but including s2). If the
|
/// returns a bitboard representing all squares on the given and neighboring
|
||||||
// given squares are not on a same file/rank/diagonal, it returns s2. For instance,
|
/// files.
|
||||||
// between_bb(SQ_C4, SQ_F7) will return a bitboard with squares D5, E6 and F7, but
|
|
||||||
// between_bb(SQ_E6, SQ_F8) will return a bitboard with the square F8. This trick
|
|
||||||
// allows to generate non-king evasion moves faster: the defending piece must either
|
|
||||||
// interpose itself to cover the check or capture the checking piece.
|
|
||||||
inline Bitboard between_bb(Square s1, Square s2) {
|
|
||||||
|
|
||||||
assert(is_ok(s1) && is_ok(s2));
|
inline Bitboard this_and_neighboring_files_bb(File f) {
|
||||||
return BetweenBB[s1][s2];
|
return ThisAndNeighboringFilesBB[f];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Returns true if the squares s1, s2 and s3 are aligned either on a
|
inline Bitboard this_and_neighboring_files_bb(Square s) {
|
||||||
// straight or on a diagonal line.
|
return this_and_neighboring_files_bb(square_file(s));
|
||||||
inline bool aligned(Square s1, Square s2, Square s3) { return line_bb(s1, s2) & s3; }
|
|
||||||
|
|
||||||
|
|
||||||
// distance() functions return the distance between x and y, defined as the
|
|
||||||
// number of steps for a king in x to reach y.
|
|
||||||
|
|
||||||
template<typename T1 = Square>
|
|
||||||
inline int distance(Square x, Square y);
|
|
||||||
|
|
||||||
template<>
|
|
||||||
inline int distance<File>(Square x, Square y) {
|
|
||||||
return std::abs(file_of(x) - file_of(y));
|
|
||||||
}
|
|
||||||
|
|
||||||
template<>
|
|
||||||
inline int distance<Rank>(Square x, Square y) {
|
|
||||||
return std::abs(rank_of(x) - rank_of(y));
|
|
||||||
}
|
|
||||||
|
|
||||||
template<>
|
|
||||||
inline int distance<Square>(Square x, Square y) {
|
|
||||||
return SquareDistance[x][y];
|
|
||||||
}
|
|
||||||
|
|
||||||
inline int edge_distance(File f) { return std::min(f, File(FILE_H - f)); }
|
|
||||||
|
|
||||||
// Returns the pseudo attacks of the given piece type
|
|
||||||
// assuming an empty board.
|
|
||||||
template<PieceType Pt>
|
|
||||||
inline Bitboard attacks_bb(Square s) {
|
|
||||||
|
|
||||||
assert((Pt != PAWN) && (is_ok(s)));
|
|
||||||
return PseudoAttacks[Pt][s];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Returns the attacks by the given piece
|
/// relative_rank_bb() takes a color and a rank as input, and returns a bitboard
|
||||||
// assuming the board is occupied according to the passed Bitboard.
|
/// representing all squares on the given rank from the given color's point of
|
||||||
// Sliding piece attacks do not continue passed an occupied square.
|
/// view. For instance, relative_rank_bb(WHITE, 7) gives all squares on the
|
||||||
template<PieceType Pt>
|
/// 7th rank, while relative_rank_bb(BLACK, 7) gives all squares on the 2nd
|
||||||
inline Bitboard attacks_bb(Square s, Bitboard occupied) {
|
/// rank.
|
||||||
|
|
||||||
assert((Pt != PAWN) && (is_ok(s)));
|
inline Bitboard relative_rank_bb(Color c, Rank r) {
|
||||||
|
return RelativeRankBB[c][r];
|
||||||
switch (Pt)
|
|
||||||
{
|
|
||||||
case BISHOP :
|
|
||||||
return BishopMagics[s].attacks[BishopMagics[s].index(occupied)];
|
|
||||||
case ROOK :
|
|
||||||
return RookMagics[s].attacks[RookMagics[s].index(occupied)];
|
|
||||||
case QUEEN :
|
|
||||||
return attacks_bb<BISHOP>(s, occupied) | attacks_bb<ROOK>(s, occupied);
|
|
||||||
default :
|
|
||||||
return PseudoAttacks[Pt][s];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the attacks by the given piece
|
|
||||||
// assuming the board is occupied according to the passed Bitboard.
|
|
||||||
// Sliding piece attacks do not continue passed an occupied square.
|
|
||||||
inline Bitboard attacks_bb(PieceType pt, Square s, Bitboard occupied) {
|
|
||||||
|
|
||||||
assert((pt != PAWN) && (is_ok(s)));
|
|
||||||
|
|
||||||
switch (pt)
|
|
||||||
{
|
|
||||||
case BISHOP :
|
|
||||||
return attacks_bb<BISHOP>(s, occupied);
|
|
||||||
case ROOK :
|
|
||||||
return attacks_bb<ROOK>(s, occupied);
|
|
||||||
case QUEEN :
|
|
||||||
return attacks_bb<BISHOP>(s, occupied) | attacks_bb<ROOK>(s, occupied);
|
|
||||||
default :
|
|
||||||
return PseudoAttacks[pt][s];
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Counts the number of non-zero bits in a bitboard.
|
/// in_front_bb() takes a color and a rank or square as input, and returns a
|
||||||
inline int popcount(Bitboard b) {
|
/// bitboard representing all the squares on all ranks in front of the rank
|
||||||
|
/// (or square), from the given color's point of view. For instance,
|
||||||
|
/// in_front_bb(WHITE, RANK_5) will give all squares on ranks 6, 7 and 8, while
|
||||||
|
/// in_front_bb(BLACK, SQ_D3) will give all squares on ranks 1 and 2.
|
||||||
|
|
||||||
#ifndef USE_POPCNT
|
inline Bitboard in_front_bb(Color c, Rank r) {
|
||||||
|
return InFrontBB[c][r];
|
||||||
|
}
|
||||||
|
|
||||||
union {
|
inline Bitboard in_front_bb(Color c, Square s) {
|
||||||
Bitboard bb;
|
return in_front_bb(c, square_rank(s));
|
||||||
uint16_t u[4];
|
}
|
||||||
} v = {b};
|
|
||||||
return PopCnt16[v.u[0]] + PopCnt16[v.u[1]] + PopCnt16[v.u[2]] + PopCnt16[v.u[3]];
|
|
||||||
|
|
||||||
#elif defined(_MSC_VER)
|
|
||||||
|
|
||||||
return int(_mm_popcnt_u64(b));
|
/// behind_bb() takes a color and a rank or square as input, and returns a
|
||||||
|
/// bitboard representing all the squares on all ranks behind of the rank
|
||||||
|
/// (or square), from the given color's point of view.
|
||||||
|
|
||||||
#else // Assumed gcc or compatible compiler
|
inline Bitboard behind_bb(Color c, Rank r) {
|
||||||
|
return InFrontBB[opposite_color(c)][r];
|
||||||
|
}
|
||||||
|
|
||||||
return __builtin_popcountll(b);
|
inline Bitboard behind_bb(Color c, Square s) {
|
||||||
|
return in_front_bb(opposite_color(c), square_rank(s));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// ray_bb() gives a bitboard representing all squares along the ray in a
|
||||||
|
/// given direction from a given square.
|
||||||
|
|
||||||
|
inline Bitboard ray_bb(Square s, SignedDirection d) {
|
||||||
|
return RayBB[s][d];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Functions for computing sliding attack bitboards. rook_attacks_bb(),
|
||||||
|
/// bishop_attacks_bb() and queen_attacks_bb() all take a square and a
|
||||||
|
/// bitboard of occupied squares as input, and return a bitboard representing
|
||||||
|
/// all squares attacked by a rook, bishop or queen on the given square.
|
||||||
|
|
||||||
|
#if defined(IS_64BIT)
|
||||||
|
|
||||||
|
inline Bitboard rook_attacks_bb(Square s, Bitboard blockers) {
|
||||||
|
Bitboard b = blockers & RMask[s];
|
||||||
|
return RAttacks[RAttackIndex[s] + ((b * RMult[s]) >> RShift[s])];
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Bitboard bishop_attacks_bb(Square s, Bitboard blockers) {
|
||||||
|
Bitboard b = blockers & BMask[s];
|
||||||
|
return BAttacks[BAttackIndex[s] + ((b * BMult[s]) >> BShift[s])];
|
||||||
|
}
|
||||||
|
|
||||||
|
#else // if !defined(IS_64BIT)
|
||||||
|
|
||||||
|
inline Bitboard rook_attacks_bb(Square s, Bitboard blockers) {
|
||||||
|
Bitboard b = blockers & RMask[s];
|
||||||
|
return RAttacks[RAttackIndex[s] +
|
||||||
|
(unsigned(int(b) * int(RMult[s]) ^
|
||||||
|
int(b >> 32) * int(RMult[s] >> 32))
|
||||||
|
>> RShift[s])];
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Bitboard bishop_attacks_bb(Square s, Bitboard blockers) {
|
||||||
|
Bitboard b = blockers & BMask[s];
|
||||||
|
return BAttacks[BAttackIndex[s] +
|
||||||
|
(unsigned(int(b) * int(BMult[s]) ^
|
||||||
|
int(b >> 32) * int(BMult[s] >> 32))
|
||||||
|
>> BShift[s])];
|
||||||
|
}
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
inline Bitboard queen_attacks_bb(Square s, Bitboard blockers) {
|
||||||
|
return rook_attacks_bb(s, blockers) | bishop_attacks_bb(s, blockers);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Returns the least significant bit in a non-zero bitboard.
|
|
||||||
inline Square lsb(Bitboard b) {
|
|
||||||
assert(b);
|
|
||||||
|
|
||||||
#if defined(__GNUC__) // GCC, Clang, ICX
|
/// 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.
|
||||||
|
|
||||||
return Square(__builtin_ctzll(b));
|
inline Bitboard squares_between(Square s1, Square s2) {
|
||||||
|
return BetweenBB[s1][s2];
|
||||||
|
}
|
||||||
|
|
||||||
#elif defined(_MSC_VER)
|
|
||||||
#ifdef _WIN64 // MSVC, WIN64
|
|
||||||
|
|
||||||
unsigned long idx;
|
/// squares_in_front_of takes a color and a square as input, and returns a
|
||||||
_BitScanForward64(&idx, b);
|
/// bitboard representing all squares along the line in front of the square,
|
||||||
return Square(idx);
|
/// from the point of view of the given color. For instance,
|
||||||
|
/// squares_in_front_of(BLACK, SQ_E4) returns a bitboard with the squares
|
||||||
|
/// e3, e2 and e1 set.
|
||||||
|
|
||||||
#else // MSVC, WIN32
|
inline Bitboard squares_in_front_of(Color c, Square s) {
|
||||||
unsigned long idx;
|
return in_front_bb(c, s) & file_bb(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// squares_behind is similar to squares_in_front, but returns the squares
|
||||||
|
/// behind the square instead of in front of the square.
|
||||||
|
|
||||||
|
inline Bitboard squares_behind(Color c, Square s) {
|
||||||
|
return in_front_bb(opposite_color(c), s) & file_bb(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// passed_pawn_mask takes a color and a square as input, and returns a
|
||||||
|
/// bitboard mask which can be used to test if a pawn of the given color on
|
||||||
|
/// the given square is a passed pawn.
|
||||||
|
|
||||||
|
inline Bitboard passed_pawn_mask(Color c, Square s) {
|
||||||
|
return PassedPawnMask[c][s];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// outpost_mask takes a color and a square as input, and returns a bitboard
|
||||||
|
/// mask which can be used to test whether a piece on the square can possibly
|
||||||
|
/// be driven away by an enemy pawn.
|
||||||
|
|
||||||
|
inline Bitboard outpost_mask(Color c, Square s) {
|
||||||
|
return OutpostMask[c][s];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// isolated_pawn_mask takes a square as input, and returns a bitboard mask
|
||||||
|
/// which can be used to test whether a pawn on the given square is isolated.
|
||||||
|
|
||||||
|
inline Bitboard isolated_pawn_mask(Square s) {
|
||||||
|
return neighboring_files_bb(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// first_1() finds the least significant nonzero bit in a nonzero bitboard.
|
||||||
|
/// pop_1st_bit() finds and clears the least significant nonzero bit in a
|
||||||
|
/// nonzero bitboard.
|
||||||
|
|
||||||
|
#if defined(USE_BSFQ) // Assembly code by Heinz van Saanen
|
||||||
|
|
||||||
|
inline Square first_1(Bitboard b) {
|
||||||
|
Bitboard dummy;
|
||||||
|
__asm__("bsfq %1, %0": "=r"(dummy): "rm"(b) );
|
||||||
|
return (Square)(dummy);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Square pop_1st_bit(Bitboard* b) {
|
||||||
|
const Square s = first_1(*b);
|
||||||
|
*b &= ~(1ULL<<s);
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
#else // if !defined(USE_BSFQ)
|
||||||
|
|
||||||
|
extern Square first_1(Bitboard b);
|
||||||
|
extern Square pop_1st_bit(Bitboard* b);
|
||||||
|
|
||||||
if (b & 0xffffffff)
|
|
||||||
{
|
|
||||||
_BitScanForward(&idx, int32_t(b));
|
|
||||||
return Square(idx);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_BitScanForward(&idx, int32_t(b >> 32));
|
|
||||||
return Square(idx + 32);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
#else // Compiler is neither GCC nor MSVC compatible
|
|
||||||
#error "Compiler not supported."
|
|
||||||
#endif
|
#endif
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the most significant bit in a non-zero bitboard.
|
|
||||||
inline Square msb(Bitboard b) {
|
|
||||||
assert(b);
|
|
||||||
|
|
||||||
#if defined(__GNUC__) // GCC, Clang, ICX
|
////
|
||||||
|
//// Prototypes
|
||||||
|
////
|
||||||
|
|
||||||
return Square(63 ^ __builtin_clzll(b));
|
extern void print_bitboard(Bitboard b);
|
||||||
|
extern void init_bitboards();
|
||||||
|
extern int bitScanReverse32(uint32_t b);
|
||||||
|
|
||||||
#elif defined(_MSC_VER)
|
|
||||||
#ifdef _WIN64 // MSVC, WIN64
|
|
||||||
|
|
||||||
unsigned long idx;
|
#endif // !defined(BITBOARD_H_INCLUDED)
|
||||||
_BitScanReverse64(&idx, b);
|
|
||||||
return Square(idx);
|
|
||||||
|
|
||||||
#else // MSVC, WIN32
|
|
||||||
|
|
||||||
unsigned long idx;
|
|
||||||
|
|
||||||
if (b >> 32)
|
|
||||||
{
|
|
||||||
_BitScanReverse(&idx, int32_t(b >> 32));
|
|
||||||
return Square(idx + 32);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
_BitScanReverse(&idx, int32_t(b));
|
|
||||||
return Square(idx);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
#else // Compiler is neither GCC nor MSVC compatible
|
|
||||||
#error "Compiler not supported."
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the bitboard of the least significant
|
|
||||||
// square of a non-zero bitboard. It is equivalent to square_bb(lsb(bb)).
|
|
||||||
inline Bitboard least_significant_square_bb(Bitboard b) {
|
|
||||||
assert(b);
|
|
||||||
return b & -b;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Finds and clears the least significant bit in a non-zero bitboard.
|
|
||||||
inline Square pop_lsb(Bitboard& b) {
|
|
||||||
assert(b);
|
|
||||||
const Square s = lsb(b);
|
|
||||||
b &= b - 1;
|
|
||||||
return s;
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Stockfish
|
|
||||||
|
|
||||||
#endif // #ifndef BITBOARD_H_INCLUDED
|
|
||||||
|
|||||||
+167
@@ -0,0 +1,167 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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(BITCOUNT_H_INCLUDED)
|
||||||
|
#define BITCOUNT_H_INCLUDED
|
||||||
|
|
||||||
|
#include "types.h"
|
||||||
|
|
||||||
|
// Select type of intrinsic bit count instruction to use, see
|
||||||
|
// README.txt on how to pgo compile with POPCNT support.
|
||||||
|
|
||||||
|
#if defined(__INTEL_COMPILER) && defined(USE_POPCNT) // Intel compiler
|
||||||
|
|
||||||
|
#include <nmmintrin.h>
|
||||||
|
|
||||||
|
inline bool cpu_has_popcnt() {
|
||||||
|
|
||||||
|
int CPUInfo[4] = {-1};
|
||||||
|
__cpuid(CPUInfo, 0x00000001);
|
||||||
|
return (CPUInfo[2] >> 23) & 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#define POPCNT_INTRINSIC(x) _mm_popcnt_u64(x)
|
||||||
|
|
||||||
|
#elif defined(_MSC_VER) && defined(USE_POPCNT) // Microsoft compiler
|
||||||
|
|
||||||
|
#include <intrin.h>
|
||||||
|
|
||||||
|
inline bool cpu_has_popcnt() {
|
||||||
|
|
||||||
|
int CPUInfo[4] = {-1};
|
||||||
|
__cpuid(CPUInfo, 0x00000001);
|
||||||
|
return (CPUInfo[2] >> 23) & 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#define POPCNT_INTRINSIC(x) __popcnt64(x)
|
||||||
|
|
||||||
|
#elif defined(__GNUC__) && defined(USE_POPCNT) // Gcc compiler
|
||||||
|
|
||||||
|
inline void __cpuid(unsigned int op,
|
||||||
|
unsigned int *eax, unsigned int *ebx,
|
||||||
|
unsigned int *ecx, unsigned int *edx)
|
||||||
|
{
|
||||||
|
*eax = op;
|
||||||
|
*ecx = 0;
|
||||||
|
__asm__("cpuid" : "=a" (*eax), "=b" (*ebx), "=c" (*ecx), "=d" (*edx)
|
||||||
|
: "0" (*eax), "2" (*ecx));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool cpu_has_popcnt() {
|
||||||
|
|
||||||
|
unsigned int eax, ebx, ecx, edx;
|
||||||
|
__cpuid(1, &eax, &ebx, &ecx, &edx);
|
||||||
|
return (ecx >> 23) & 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
#define POPCNT_INTRINSIC(x) ({ \
|
||||||
|
unsigned long __ret; \
|
||||||
|
__asm__("popcnt %1, %0" : "=r" (__ret) : "r" (x)); \
|
||||||
|
__ret; })
|
||||||
|
|
||||||
|
#else // Safe fallback for unsupported compilers or when USE_POPCNT is disabled
|
||||||
|
|
||||||
|
inline bool cpu_has_popcnt() { return false; }
|
||||||
|
|
||||||
|
#define POPCNT_INTRINSIC(x) 0
|
||||||
|
|
||||||
|
#endif // cpu_has_popcnt() and POPCNT_INTRINSIC() definitions
|
||||||
|
|
||||||
|
|
||||||
|
/// Software implementation of bit count functions
|
||||||
|
|
||||||
|
#if defined(IS_64BIT)
|
||||||
|
|
||||||
|
inline int count_1s(Bitboard b) {
|
||||||
|
b -= ((b>>1) & 0x5555555555555555ULL);
|
||||||
|
b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
|
||||||
|
b = ((b>>4) + b) & 0x0F0F0F0F0F0F0F0FULL;
|
||||||
|
b *= 0x0101010101010101ULL;
|
||||||
|
return int(b >> 56);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int count_1s_max_15(Bitboard b) {
|
||||||
|
b -= (b>>1) & 0x5555555555555555ULL;
|
||||||
|
b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
|
||||||
|
b *= 0x1111111111111111ULL;
|
||||||
|
return int(b >> 60);
|
||||||
|
}
|
||||||
|
|
||||||
|
#else // if !defined(IS_64BIT)
|
||||||
|
|
||||||
|
inline int count_1s(Bitboard b) {
|
||||||
|
unsigned w = unsigned(b >> 32), v = unsigned(b);
|
||||||
|
v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits
|
||||||
|
w -= (w >> 1) & 0x55555555;
|
||||||
|
v = ((v >> 2) & 0x33333333) + (v & 0x33333333); // 0-4 in 4 bits
|
||||||
|
w = ((w >> 2) & 0x33333333) + (w & 0x33333333);
|
||||||
|
v = ((v >> 4) + v) & 0x0F0F0F0F; // 0-8 in 8 bits
|
||||||
|
v += (((w >> 4) + w) & 0x0F0F0F0F); // 0-16 in 8 bits
|
||||||
|
v *= 0x01010101; // mul is fast on amd procs
|
||||||
|
return int(v >> 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int count_1s_max_15(Bitboard b) {
|
||||||
|
unsigned w = unsigned(b >> 32), v = unsigned(b);
|
||||||
|
v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits
|
||||||
|
w -= (w >> 1) & 0x55555555;
|
||||||
|
v = ((v >> 2) & 0x33333333) + (v & 0x33333333); // 0-4 in 4 bits
|
||||||
|
w = ((w >> 2) & 0x33333333) + (w & 0x33333333);
|
||||||
|
v += w; // 0-8 in 4 bits
|
||||||
|
v *= 0x11111111;
|
||||||
|
return int(v >> 28);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif // BITCOUNT
|
||||||
|
|
||||||
|
|
||||||
|
/// count_1s() counts the number of nonzero bits in a bitboard.
|
||||||
|
/// If template parameter is true an intrinsic is called, otherwise
|
||||||
|
/// we fallback on a software implementation.
|
||||||
|
|
||||||
|
template<bool UseIntrinsic>
|
||||||
|
inline int count_1s(Bitboard b) {
|
||||||
|
|
||||||
|
return UseIntrinsic ? POPCNT_INTRINSIC(b) : count_1s(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<bool UseIntrinsic>
|
||||||
|
inline int count_1s_max_15(Bitboard b) {
|
||||||
|
|
||||||
|
return UseIntrinsic ? POPCNT_INTRINSIC(b) : count_1s_max_15(b);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Global constant initialized at startup that is set to true if
|
||||||
|
// CPU on which application runs supports POPCNT intrinsic. Unless
|
||||||
|
// USE_POPCNT is not defined.
|
||||||
|
const bool CpuHasPOPCNT = cpu_has_popcnt();
|
||||||
|
|
||||||
|
|
||||||
|
// Global constant used to print info about the use of 64 optimized
|
||||||
|
// functions to verify that a 64 bit compile has been correctly built.
|
||||||
|
#if defined(IS_64BIT)
|
||||||
|
const bool CpuHas64BitPath = true;
|
||||||
|
#else
|
||||||
|
const bool CpuHas64BitPath = false;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif // !defined(BITCOUNT_H_INCLUDED)
|
||||||
+583
@@ -0,0 +1,583 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
The code in this file is based on the opening book code in PolyGlot
|
||||||
|
by Fabien Letouzey. PolyGlot is available under the GNU General
|
||||||
|
Public License, and can be downloaded from http://wbec-ridderkerk.nl
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include <cassert>
|
||||||
|
|
||||||
|
#include "book.h"
|
||||||
|
#include "mersenne.h"
|
||||||
|
#include "movegen.h"
|
||||||
|
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Global variables
|
||||||
|
////
|
||||||
|
|
||||||
|
Book OpeningBook;
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Local definitions
|
||||||
|
////
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
/// Book entry size in bytes
|
||||||
|
const int EntrySize = 16;
|
||||||
|
|
||||||
|
|
||||||
|
/// Random numbers from PolyGlot, used to compute book hash keys
|
||||||
|
|
||||||
|
const uint64_t Random64[781] = {
|
||||||
|
0x9D39247E33776D41ULL, 0x2AF7398005AAA5C7ULL, 0x44DB015024623547ULL,
|
||||||
|
0x9C15F73E62A76AE2ULL, 0x75834465489C0C89ULL, 0x3290AC3A203001BFULL,
|
||||||
|
0x0FBBAD1F61042279ULL, 0xE83A908FF2FB60CAULL, 0x0D7E765D58755C10ULL,
|
||||||
|
0x1A083822CEAFE02DULL, 0x9605D5F0E25EC3B0ULL, 0xD021FF5CD13A2ED5ULL,
|
||||||
|
0x40BDF15D4A672E32ULL, 0x011355146FD56395ULL, 0x5DB4832046F3D9E5ULL,
|
||||||
|
0x239F8B2D7FF719CCULL, 0x05D1A1AE85B49AA1ULL, 0x679F848F6E8FC971ULL,
|
||||||
|
0x7449BBFF801FED0BULL, 0x7D11CDB1C3B7ADF0ULL, 0x82C7709E781EB7CCULL,
|
||||||
|
0xF3218F1C9510786CULL, 0x331478F3AF51BBE6ULL, 0x4BB38DE5E7219443ULL,
|
||||||
|
0xAA649C6EBCFD50FCULL, 0x8DBD98A352AFD40BULL, 0x87D2074B81D79217ULL,
|
||||||
|
0x19F3C751D3E92AE1ULL, 0xB4AB30F062B19ABFULL, 0x7B0500AC42047AC4ULL,
|
||||||
|
0xC9452CA81A09D85DULL, 0x24AA6C514DA27500ULL, 0x4C9F34427501B447ULL,
|
||||||
|
0x14A68FD73C910841ULL, 0xA71B9B83461CBD93ULL, 0x03488B95B0F1850FULL,
|
||||||
|
0x637B2B34FF93C040ULL, 0x09D1BC9A3DD90A94ULL, 0x3575668334A1DD3BULL,
|
||||||
|
0x735E2B97A4C45A23ULL, 0x18727070F1BD400BULL, 0x1FCBACD259BF02E7ULL,
|
||||||
|
0xD310A7C2CE9B6555ULL, 0xBF983FE0FE5D8244ULL, 0x9F74D14F7454A824ULL,
|
||||||
|
0x51EBDC4AB9BA3035ULL, 0x5C82C505DB9AB0FAULL, 0xFCF7FE8A3430B241ULL,
|
||||||
|
0x3253A729B9BA3DDEULL, 0x8C74C368081B3075ULL, 0xB9BC6C87167C33E7ULL,
|
||||||
|
0x7EF48F2B83024E20ULL, 0x11D505D4C351BD7FULL, 0x6568FCA92C76A243ULL,
|
||||||
|
0x4DE0B0F40F32A7B8ULL, 0x96D693460CC37E5DULL, 0x42E240CB63689F2FULL,
|
||||||
|
0x6D2BDCDAE2919661ULL, 0x42880B0236E4D951ULL, 0x5F0F4A5898171BB6ULL,
|
||||||
|
0x39F890F579F92F88ULL, 0x93C5B5F47356388BULL, 0x63DC359D8D231B78ULL,
|
||||||
|
0xEC16CA8AEA98AD76ULL, 0x5355F900C2A82DC7ULL, 0x07FB9F855A997142ULL,
|
||||||
|
0x5093417AA8A7ED5EULL, 0x7BCBC38DA25A7F3CULL, 0x19FC8A768CF4B6D4ULL,
|
||||||
|
0x637A7780DECFC0D9ULL, 0x8249A47AEE0E41F7ULL, 0x79AD695501E7D1E8ULL,
|
||||||
|
0x14ACBAF4777D5776ULL, 0xF145B6BECCDEA195ULL, 0xDABF2AC8201752FCULL,
|
||||||
|
0x24C3C94DF9C8D3F6ULL, 0xBB6E2924F03912EAULL, 0x0CE26C0B95C980D9ULL,
|
||||||
|
0xA49CD132BFBF7CC4ULL, 0xE99D662AF4243939ULL, 0x27E6AD7891165C3FULL,
|
||||||
|
0x8535F040B9744FF1ULL, 0x54B3F4FA5F40D873ULL, 0x72B12C32127FED2BULL,
|
||||||
|
0xEE954D3C7B411F47ULL, 0x9A85AC909A24EAA1ULL, 0x70AC4CD9F04F21F5ULL,
|
||||||
|
0xF9B89D3E99A075C2ULL, 0x87B3E2B2B5C907B1ULL, 0xA366E5B8C54F48B8ULL,
|
||||||
|
0xAE4A9346CC3F7CF2ULL, 0x1920C04D47267BBDULL, 0x87BF02C6B49E2AE9ULL,
|
||||||
|
0x092237AC237F3859ULL, 0xFF07F64EF8ED14D0ULL, 0x8DE8DCA9F03CC54EULL,
|
||||||
|
0x9C1633264DB49C89ULL, 0xB3F22C3D0B0B38EDULL, 0x390E5FB44D01144BULL,
|
||||||
|
0x5BFEA5B4712768E9ULL, 0x1E1032911FA78984ULL, 0x9A74ACB964E78CB3ULL,
|
||||||
|
0x4F80F7A035DAFB04ULL, 0x6304D09A0B3738C4ULL, 0x2171E64683023A08ULL,
|
||||||
|
0x5B9B63EB9CEFF80CULL, 0x506AACF489889342ULL, 0x1881AFC9A3A701D6ULL,
|
||||||
|
0x6503080440750644ULL, 0xDFD395339CDBF4A7ULL, 0xEF927DBCF00C20F2ULL,
|
||||||
|
0x7B32F7D1E03680ECULL, 0xB9FD7620E7316243ULL, 0x05A7E8A57DB91B77ULL,
|
||||||
|
0xB5889C6E15630A75ULL, 0x4A750A09CE9573F7ULL, 0xCF464CEC899A2F8AULL,
|
||||||
|
0xF538639CE705B824ULL, 0x3C79A0FF5580EF7FULL, 0xEDE6C87F8477609DULL,
|
||||||
|
0x799E81F05BC93F31ULL, 0x86536B8CF3428A8CULL, 0x97D7374C60087B73ULL,
|
||||||
|
0xA246637CFF328532ULL, 0x043FCAE60CC0EBA0ULL, 0x920E449535DD359EULL,
|
||||||
|
0x70EB093B15B290CCULL, 0x73A1921916591CBDULL, 0x56436C9FE1A1AA8DULL,
|
||||||
|
0xEFAC4B70633B8F81ULL, 0xBB215798D45DF7AFULL, 0x45F20042F24F1768ULL,
|
||||||
|
0x930F80F4E8EB7462ULL, 0xFF6712FFCFD75EA1ULL, 0xAE623FD67468AA70ULL,
|
||||||
|
0xDD2C5BC84BC8D8FCULL, 0x7EED120D54CF2DD9ULL, 0x22FE545401165F1CULL,
|
||||||
|
0xC91800E98FB99929ULL, 0x808BD68E6AC10365ULL, 0xDEC468145B7605F6ULL,
|
||||||
|
0x1BEDE3A3AEF53302ULL, 0x43539603D6C55602ULL, 0xAA969B5C691CCB7AULL,
|
||||||
|
0xA87832D392EFEE56ULL, 0x65942C7B3C7E11AEULL, 0xDED2D633CAD004F6ULL,
|
||||||
|
0x21F08570F420E565ULL, 0xB415938D7DA94E3CULL, 0x91B859E59ECB6350ULL,
|
||||||
|
0x10CFF333E0ED804AULL, 0x28AED140BE0BB7DDULL, 0xC5CC1D89724FA456ULL,
|
||||||
|
0x5648F680F11A2741ULL, 0x2D255069F0B7DAB3ULL, 0x9BC5A38EF729ABD4ULL,
|
||||||
|
0xEF2F054308F6A2BCULL, 0xAF2042F5CC5C2858ULL, 0x480412BAB7F5BE2AULL,
|
||||||
|
0xAEF3AF4A563DFE43ULL, 0x19AFE59AE451497FULL, 0x52593803DFF1E840ULL,
|
||||||
|
0xF4F076E65F2CE6F0ULL, 0x11379625747D5AF3ULL, 0xBCE5D2248682C115ULL,
|
||||||
|
0x9DA4243DE836994FULL, 0x066F70B33FE09017ULL, 0x4DC4DE189B671A1CULL,
|
||||||
|
0x51039AB7712457C3ULL, 0xC07A3F80C31FB4B4ULL, 0xB46EE9C5E64A6E7CULL,
|
||||||
|
0xB3819A42ABE61C87ULL, 0x21A007933A522A20ULL, 0x2DF16F761598AA4FULL,
|
||||||
|
0x763C4A1371B368FDULL, 0xF793C46702E086A0ULL, 0xD7288E012AEB8D31ULL,
|
||||||
|
0xDE336A2A4BC1C44BULL, 0x0BF692B38D079F23ULL, 0x2C604A7A177326B3ULL,
|
||||||
|
0x4850E73E03EB6064ULL, 0xCFC447F1E53C8E1BULL, 0xB05CA3F564268D99ULL,
|
||||||
|
0x9AE182C8BC9474E8ULL, 0xA4FC4BD4FC5558CAULL, 0xE755178D58FC4E76ULL,
|
||||||
|
0x69B97DB1A4C03DFEULL, 0xF9B5B7C4ACC67C96ULL, 0xFC6A82D64B8655FBULL,
|
||||||
|
0x9C684CB6C4D24417ULL, 0x8EC97D2917456ED0ULL, 0x6703DF9D2924E97EULL,
|
||||||
|
0xC547F57E42A7444EULL, 0x78E37644E7CAD29EULL, 0xFE9A44E9362F05FAULL,
|
||||||
|
0x08BD35CC38336615ULL, 0x9315E5EB3A129ACEULL, 0x94061B871E04DF75ULL,
|
||||||
|
0xDF1D9F9D784BA010ULL, 0x3BBA57B68871B59DULL, 0xD2B7ADEEDED1F73FULL,
|
||||||
|
0xF7A255D83BC373F8ULL, 0xD7F4F2448C0CEB81ULL, 0xD95BE88CD210FFA7ULL,
|
||||||
|
0x336F52F8FF4728E7ULL, 0xA74049DAC312AC71ULL, 0xA2F61BB6E437FDB5ULL,
|
||||||
|
0x4F2A5CB07F6A35B3ULL, 0x87D380BDA5BF7859ULL, 0x16B9F7E06C453A21ULL,
|
||||||
|
0x7BA2484C8A0FD54EULL, 0xF3A678CAD9A2E38CULL, 0x39B0BF7DDE437BA2ULL,
|
||||||
|
0xFCAF55C1BF8A4424ULL, 0x18FCF680573FA594ULL, 0x4C0563B89F495AC3ULL,
|
||||||
|
0x40E087931A00930DULL, 0x8CFFA9412EB642C1ULL, 0x68CA39053261169FULL,
|
||||||
|
0x7A1EE967D27579E2ULL, 0x9D1D60E5076F5B6FULL, 0x3810E399B6F65BA2ULL,
|
||||||
|
0x32095B6D4AB5F9B1ULL, 0x35CAB62109DD038AULL, 0xA90B24499FCFAFB1ULL,
|
||||||
|
0x77A225A07CC2C6BDULL, 0x513E5E634C70E331ULL, 0x4361C0CA3F692F12ULL,
|
||||||
|
0xD941ACA44B20A45BULL, 0x528F7C8602C5807BULL, 0x52AB92BEB9613989ULL,
|
||||||
|
0x9D1DFA2EFC557F73ULL, 0x722FF175F572C348ULL, 0x1D1260A51107FE97ULL,
|
||||||
|
0x7A249A57EC0C9BA2ULL, 0x04208FE9E8F7F2D6ULL, 0x5A110C6058B920A0ULL,
|
||||||
|
0x0CD9A497658A5698ULL, 0x56FD23C8F9715A4CULL, 0x284C847B9D887AAEULL,
|
||||||
|
0x04FEABFBBDB619CBULL, 0x742E1E651C60BA83ULL, 0x9A9632E65904AD3CULL,
|
||||||
|
0x881B82A13B51B9E2ULL, 0x506E6744CD974924ULL, 0xB0183DB56FFC6A79ULL,
|
||||||
|
0x0ED9B915C66ED37EULL, 0x5E11E86D5873D484ULL, 0xF678647E3519AC6EULL,
|
||||||
|
0x1B85D488D0F20CC5ULL, 0xDAB9FE6525D89021ULL, 0x0D151D86ADB73615ULL,
|
||||||
|
0xA865A54EDCC0F019ULL, 0x93C42566AEF98FFBULL, 0x99E7AFEABE000731ULL,
|
||||||
|
0x48CBFF086DDF285AULL, 0x7F9B6AF1EBF78BAFULL, 0x58627E1A149BBA21ULL,
|
||||||
|
0x2CD16E2ABD791E33ULL, 0xD363EFF5F0977996ULL, 0x0CE2A38C344A6EEDULL,
|
||||||
|
0x1A804AADB9CFA741ULL, 0x907F30421D78C5DEULL, 0x501F65EDB3034D07ULL,
|
||||||
|
0x37624AE5A48FA6E9ULL, 0x957BAF61700CFF4EULL, 0x3A6C27934E31188AULL,
|
||||||
|
0xD49503536ABCA345ULL, 0x088E049589C432E0ULL, 0xF943AEE7FEBF21B8ULL,
|
||||||
|
0x6C3B8E3E336139D3ULL, 0x364F6FFA464EE52EULL, 0xD60F6DCEDC314222ULL,
|
||||||
|
0x56963B0DCA418FC0ULL, 0x16F50EDF91E513AFULL, 0xEF1955914B609F93ULL,
|
||||||
|
0x565601C0364E3228ULL, 0xECB53939887E8175ULL, 0xBAC7A9A18531294BULL,
|
||||||
|
0xB344C470397BBA52ULL, 0x65D34954DAF3CEBDULL, 0xB4B81B3FA97511E2ULL,
|
||||||
|
0xB422061193D6F6A7ULL, 0x071582401C38434DULL, 0x7A13F18BBEDC4FF5ULL,
|
||||||
|
0xBC4097B116C524D2ULL, 0x59B97885E2F2EA28ULL, 0x99170A5DC3115544ULL,
|
||||||
|
0x6F423357E7C6A9F9ULL, 0x325928EE6E6F8794ULL, 0xD0E4366228B03343ULL,
|
||||||
|
0x565C31F7DE89EA27ULL, 0x30F5611484119414ULL, 0xD873DB391292ED4FULL,
|
||||||
|
0x7BD94E1D8E17DEBCULL, 0xC7D9F16864A76E94ULL, 0x947AE053EE56E63CULL,
|
||||||
|
0xC8C93882F9475F5FULL, 0x3A9BF55BA91F81CAULL, 0xD9A11FBB3D9808E4ULL,
|
||||||
|
0x0FD22063EDC29FCAULL, 0xB3F256D8ACA0B0B9ULL, 0xB03031A8B4516E84ULL,
|
||||||
|
0x35DD37D5871448AFULL, 0xE9F6082B05542E4EULL, 0xEBFAFA33D7254B59ULL,
|
||||||
|
0x9255ABB50D532280ULL, 0xB9AB4CE57F2D34F3ULL, 0x693501D628297551ULL,
|
||||||
|
0xC62C58F97DD949BFULL, 0xCD454F8F19C5126AULL, 0xBBE83F4ECC2BDECBULL,
|
||||||
|
0xDC842B7E2819E230ULL, 0xBA89142E007503B8ULL, 0xA3BC941D0A5061CBULL,
|
||||||
|
0xE9F6760E32CD8021ULL, 0x09C7E552BC76492FULL, 0x852F54934DA55CC9ULL,
|
||||||
|
0x8107FCCF064FCF56ULL, 0x098954D51FFF6580ULL, 0x23B70EDB1955C4BFULL,
|
||||||
|
0xC330DE426430F69DULL, 0x4715ED43E8A45C0AULL, 0xA8D7E4DAB780A08DULL,
|
||||||
|
0x0572B974F03CE0BBULL, 0xB57D2E985E1419C7ULL, 0xE8D9ECBE2CF3D73FULL,
|
||||||
|
0x2FE4B17170E59750ULL, 0x11317BA87905E790ULL, 0x7FBF21EC8A1F45ECULL,
|
||||||
|
0x1725CABFCB045B00ULL, 0x964E915CD5E2B207ULL, 0x3E2B8BCBF016D66DULL,
|
||||||
|
0xBE7444E39328A0ACULL, 0xF85B2B4FBCDE44B7ULL, 0x49353FEA39BA63B1ULL,
|
||||||
|
0x1DD01AAFCD53486AULL, 0x1FCA8A92FD719F85ULL, 0xFC7C95D827357AFAULL,
|
||||||
|
0x18A6A990C8B35EBDULL, 0xCCCB7005C6B9C28DULL, 0x3BDBB92C43B17F26ULL,
|
||||||
|
0xAA70B5B4F89695A2ULL, 0xE94C39A54A98307FULL, 0xB7A0B174CFF6F36EULL,
|
||||||
|
0xD4DBA84729AF48ADULL, 0x2E18BC1AD9704A68ULL, 0x2DE0966DAF2F8B1CULL,
|
||||||
|
0xB9C11D5B1E43A07EULL, 0x64972D68DEE33360ULL, 0x94628D38D0C20584ULL,
|
||||||
|
0xDBC0D2B6AB90A559ULL, 0xD2733C4335C6A72FULL, 0x7E75D99D94A70F4DULL,
|
||||||
|
0x6CED1983376FA72BULL, 0x97FCAACBF030BC24ULL, 0x7B77497B32503B12ULL,
|
||||||
|
0x8547EDDFB81CCB94ULL, 0x79999CDFF70902CBULL, 0xCFFE1939438E9B24ULL,
|
||||||
|
0x829626E3892D95D7ULL, 0x92FAE24291F2B3F1ULL, 0x63E22C147B9C3403ULL,
|
||||||
|
0xC678B6D860284A1CULL, 0x5873888850659AE7ULL, 0x0981DCD296A8736DULL,
|
||||||
|
0x9F65789A6509A440ULL, 0x9FF38FED72E9052FULL, 0xE479EE5B9930578CULL,
|
||||||
|
0xE7F28ECD2D49EECDULL, 0x56C074A581EA17FEULL, 0x5544F7D774B14AEFULL,
|
||||||
|
0x7B3F0195FC6F290FULL, 0x12153635B2C0CF57ULL, 0x7F5126DBBA5E0CA7ULL,
|
||||||
|
0x7A76956C3EAFB413ULL, 0x3D5774A11D31AB39ULL, 0x8A1B083821F40CB4ULL,
|
||||||
|
0x7B4A38E32537DF62ULL, 0x950113646D1D6E03ULL, 0x4DA8979A0041E8A9ULL,
|
||||||
|
0x3BC36E078F7515D7ULL, 0x5D0A12F27AD310D1ULL, 0x7F9D1A2E1EBE1327ULL,
|
||||||
|
0xDA3A361B1C5157B1ULL, 0xDCDD7D20903D0C25ULL, 0x36833336D068F707ULL,
|
||||||
|
0xCE68341F79893389ULL, 0xAB9090168DD05F34ULL, 0x43954B3252DC25E5ULL,
|
||||||
|
0xB438C2B67F98E5E9ULL, 0x10DCD78E3851A492ULL, 0xDBC27AB5447822BFULL,
|
||||||
|
0x9B3CDB65F82CA382ULL, 0xB67B7896167B4C84ULL, 0xBFCED1B0048EAC50ULL,
|
||||||
|
0xA9119B60369FFEBDULL, 0x1FFF7AC80904BF45ULL, 0xAC12FB171817EEE7ULL,
|
||||||
|
0xAF08DA9177DDA93DULL, 0x1B0CAB936E65C744ULL, 0xB559EB1D04E5E932ULL,
|
||||||
|
0xC37B45B3F8D6F2BAULL, 0xC3A9DC228CAAC9E9ULL, 0xF3B8B6675A6507FFULL,
|
||||||
|
0x9FC477DE4ED681DAULL, 0x67378D8ECCEF96CBULL, 0x6DD856D94D259236ULL,
|
||||||
|
0xA319CE15B0B4DB31ULL, 0x073973751F12DD5EULL, 0x8A8E849EB32781A5ULL,
|
||||||
|
0xE1925C71285279F5ULL, 0x74C04BF1790C0EFEULL, 0x4DDA48153C94938AULL,
|
||||||
|
0x9D266D6A1CC0542CULL, 0x7440FB816508C4FEULL, 0x13328503DF48229FULL,
|
||||||
|
0xD6BF7BAEE43CAC40ULL, 0x4838D65F6EF6748FULL, 0x1E152328F3318DEAULL,
|
||||||
|
0x8F8419A348F296BFULL, 0x72C8834A5957B511ULL, 0xD7A023A73260B45CULL,
|
||||||
|
0x94EBC8ABCFB56DAEULL, 0x9FC10D0F989993E0ULL, 0xDE68A2355B93CAE6ULL,
|
||||||
|
0xA44CFE79AE538BBEULL, 0x9D1D84FCCE371425ULL, 0x51D2B1AB2DDFB636ULL,
|
||||||
|
0x2FD7E4B9E72CD38CULL, 0x65CA5B96B7552210ULL, 0xDD69A0D8AB3B546DULL,
|
||||||
|
0x604D51B25FBF70E2ULL, 0x73AA8A564FB7AC9EULL, 0x1A8C1E992B941148ULL,
|
||||||
|
0xAAC40A2703D9BEA0ULL, 0x764DBEAE7FA4F3A6ULL, 0x1E99B96E70A9BE8BULL,
|
||||||
|
0x2C5E9DEB57EF4743ULL, 0x3A938FEE32D29981ULL, 0x26E6DB8FFDF5ADFEULL,
|
||||||
|
0x469356C504EC9F9DULL, 0xC8763C5B08D1908CULL, 0x3F6C6AF859D80055ULL,
|
||||||
|
0x7F7CC39420A3A545ULL, 0x9BFB227EBDF4C5CEULL, 0x89039D79D6FC5C5CULL,
|
||||||
|
0x8FE88B57305E2AB6ULL, 0xA09E8C8C35AB96DEULL, 0xFA7E393983325753ULL,
|
||||||
|
0xD6B6D0ECC617C699ULL, 0xDFEA21EA9E7557E3ULL, 0xB67C1FA481680AF8ULL,
|
||||||
|
0xCA1E3785A9E724E5ULL, 0x1CFC8BED0D681639ULL, 0xD18D8549D140CAEAULL,
|
||||||
|
0x4ED0FE7E9DC91335ULL, 0xE4DBF0634473F5D2ULL, 0x1761F93A44D5AEFEULL,
|
||||||
|
0x53898E4C3910DA55ULL, 0x734DE8181F6EC39AULL, 0x2680B122BAA28D97ULL,
|
||||||
|
0x298AF231C85BAFABULL, 0x7983EED3740847D5ULL, 0x66C1A2A1A60CD889ULL,
|
||||||
|
0x9E17E49642A3E4C1ULL, 0xEDB454E7BADC0805ULL, 0x50B704CAB602C329ULL,
|
||||||
|
0x4CC317FB9CDDD023ULL, 0x66B4835D9EAFEA22ULL, 0x219B97E26FFC81BDULL,
|
||||||
|
0x261E4E4C0A333A9DULL, 0x1FE2CCA76517DB90ULL, 0xD7504DFA8816EDBBULL,
|
||||||
|
0xB9571FA04DC089C8ULL, 0x1DDC0325259B27DEULL, 0xCF3F4688801EB9AAULL,
|
||||||
|
0xF4F5D05C10CAB243ULL, 0x38B6525C21A42B0EULL, 0x36F60E2BA4FA6800ULL,
|
||||||
|
0xEB3593803173E0CEULL, 0x9C4CD6257C5A3603ULL, 0xAF0C317D32ADAA8AULL,
|
||||||
|
0x258E5A80C7204C4BULL, 0x8B889D624D44885DULL, 0xF4D14597E660F855ULL,
|
||||||
|
0xD4347F66EC8941C3ULL, 0xE699ED85B0DFB40DULL, 0x2472F6207C2D0484ULL,
|
||||||
|
0xC2A1E7B5B459AEB5ULL, 0xAB4F6451CC1D45ECULL, 0x63767572AE3D6174ULL,
|
||||||
|
0xA59E0BD101731A28ULL, 0x116D0016CB948F09ULL, 0x2CF9C8CA052F6E9FULL,
|
||||||
|
0x0B090A7560A968E3ULL, 0xABEEDDB2DDE06FF1ULL, 0x58EFC10B06A2068DULL,
|
||||||
|
0xC6E57A78FBD986E0ULL, 0x2EAB8CA63CE802D7ULL, 0x14A195640116F336ULL,
|
||||||
|
0x7C0828DD624EC390ULL, 0xD74BBE77E6116AC7ULL, 0x804456AF10F5FB53ULL,
|
||||||
|
0xEBE9EA2ADF4321C7ULL, 0x03219A39EE587A30ULL, 0x49787FEF17AF9924ULL,
|
||||||
|
0xA1E9300CD8520548ULL, 0x5B45E522E4B1B4EFULL, 0xB49C3B3995091A36ULL,
|
||||||
|
0xD4490AD526F14431ULL, 0x12A8F216AF9418C2ULL, 0x001F837CC7350524ULL,
|
||||||
|
0x1877B51E57A764D5ULL, 0xA2853B80F17F58EEULL, 0x993E1DE72D36D310ULL,
|
||||||
|
0xB3598080CE64A656ULL, 0x252F59CF0D9F04BBULL, 0xD23C8E176D113600ULL,
|
||||||
|
0x1BDA0492E7E4586EULL, 0x21E0BD5026C619BFULL, 0x3B097ADAF088F94EULL,
|
||||||
|
0x8D14DEDB30BE846EULL, 0xF95CFFA23AF5F6F4ULL, 0x3871700761B3F743ULL,
|
||||||
|
0xCA672B91E9E4FA16ULL, 0x64C8E531BFF53B55ULL, 0x241260ED4AD1E87DULL,
|
||||||
|
0x106C09B972D2E822ULL, 0x7FBA195410E5CA30ULL, 0x7884D9BC6CB569D8ULL,
|
||||||
|
0x0647DFEDCD894A29ULL, 0x63573FF03E224774ULL, 0x4FC8E9560F91B123ULL,
|
||||||
|
0x1DB956E450275779ULL, 0xB8D91274B9E9D4FBULL, 0xA2EBEE47E2FBFCE1ULL,
|
||||||
|
0xD9F1F30CCD97FB09ULL, 0xEFED53D75FD64E6BULL, 0x2E6D02C36017F67FULL,
|
||||||
|
0xA9AA4D20DB084E9BULL, 0xB64BE8D8B25396C1ULL, 0x70CB6AF7C2D5BCF0ULL,
|
||||||
|
0x98F076A4F7A2322EULL, 0xBF84470805E69B5FULL, 0x94C3251F06F90CF3ULL,
|
||||||
|
0x3E003E616A6591E9ULL, 0xB925A6CD0421AFF3ULL, 0x61BDD1307C66E300ULL,
|
||||||
|
0xBF8D5108E27E0D48ULL, 0x240AB57A8B888B20ULL, 0xFC87614BAF287E07ULL,
|
||||||
|
0xEF02CDD06FFDB432ULL, 0xA1082C0466DF6C0AULL, 0x8215E577001332C8ULL,
|
||||||
|
0xD39BB9C3A48DB6CFULL, 0x2738259634305C14ULL, 0x61CF4F94C97DF93DULL,
|
||||||
|
0x1B6BACA2AE4E125BULL, 0x758F450C88572E0BULL, 0x959F587D507A8359ULL,
|
||||||
|
0xB063E962E045F54DULL, 0x60E8ED72C0DFF5D1ULL, 0x7B64978555326F9FULL,
|
||||||
|
0xFD080D236DA814BAULL, 0x8C90FD9B083F4558ULL, 0x106F72FE81E2C590ULL,
|
||||||
|
0x7976033A39F7D952ULL, 0xA4EC0132764CA04BULL, 0x733EA705FAE4FA77ULL,
|
||||||
|
0xB4D8F77BC3E56167ULL, 0x9E21F4F903B33FD9ULL, 0x9D765E419FB69F6DULL,
|
||||||
|
0xD30C088BA61EA5EFULL, 0x5D94337FBFAF7F5BULL, 0x1A4E4822EB4D7A59ULL,
|
||||||
|
0x6FFE73E81B637FB3ULL, 0xDDF957BC36D8B9CAULL, 0x64D0E29EEA8838B3ULL,
|
||||||
|
0x08DD9BDFD96B9F63ULL, 0x087E79E5A57D1D13ULL, 0xE328E230E3E2B3FBULL,
|
||||||
|
0x1C2559E30F0946BEULL, 0x720BF5F26F4D2EAAULL, 0xB0774D261CC609DBULL,
|
||||||
|
0x443F64EC5A371195ULL, 0x4112CF68649A260EULL, 0xD813F2FAB7F5C5CAULL,
|
||||||
|
0x660D3257380841EEULL, 0x59AC2C7873F910A3ULL, 0xE846963877671A17ULL,
|
||||||
|
0x93B633ABFA3469F8ULL, 0xC0C0F5A60EF4CDCFULL, 0xCAF21ECD4377B28CULL,
|
||||||
|
0x57277707199B8175ULL, 0x506C11B9D90E8B1DULL, 0xD83CC2687A19255FULL,
|
||||||
|
0x4A29C6465A314CD1ULL, 0xED2DF21216235097ULL, 0xB5635C95FF7296E2ULL,
|
||||||
|
0x22AF003AB672E811ULL, 0x52E762596BF68235ULL, 0x9AEBA33AC6ECC6B0ULL,
|
||||||
|
0x944F6DE09134DFB6ULL, 0x6C47BEC883A7DE39ULL, 0x6AD047C430A12104ULL,
|
||||||
|
0xA5B1CFDBA0AB4067ULL, 0x7C45D833AFF07862ULL, 0x5092EF950A16DA0BULL,
|
||||||
|
0x9338E69C052B8E7BULL, 0x455A4B4CFE30E3F5ULL, 0x6B02E63195AD0CF8ULL,
|
||||||
|
0x6B17B224BAD6BF27ULL, 0xD1E0CCD25BB9C169ULL, 0xDE0C89A556B9AE70ULL,
|
||||||
|
0x50065E535A213CF6ULL, 0x9C1169FA2777B874ULL, 0x78EDEFD694AF1EEDULL,
|
||||||
|
0x6DC93D9526A50E68ULL, 0xEE97F453F06791EDULL, 0x32AB0EDB696703D3ULL,
|
||||||
|
0x3A6853C7E70757A7ULL, 0x31865CED6120F37DULL, 0x67FEF95D92607890ULL,
|
||||||
|
0x1F2B1D1F15F6DC9CULL, 0xB69E38A8965C6B65ULL, 0xAA9119FF184CCCF4ULL,
|
||||||
|
0xF43C732873F24C13ULL, 0xFB4A3D794A9A80D2ULL, 0x3550C2321FD6109CULL,
|
||||||
|
0x371F77E76BB8417EULL, 0x6BFA9AAE5EC05779ULL, 0xCD04F3FF001A4778ULL,
|
||||||
|
0xE3273522064480CAULL, 0x9F91508BFFCFC14AULL, 0x049A7F41061A9E60ULL,
|
||||||
|
0xFCB6BE43A9F2FE9BULL, 0x08DE8A1C7797DA9BULL, 0x8F9887E6078735A1ULL,
|
||||||
|
0xB5B4071DBFC73A66ULL, 0x230E343DFBA08D33ULL, 0x43ED7F5A0FAE657DULL,
|
||||||
|
0x3A88A0FBBCB05C63ULL, 0x21874B8B4D2DBC4FULL, 0x1BDEA12E35F6A8C9ULL,
|
||||||
|
0x53C065C6C8E63528ULL, 0xE34A1D250E7A8D6BULL, 0xD6B04D3B7651DD7EULL,
|
||||||
|
0x5E90277E7CB39E2DULL, 0x2C046F22062DC67DULL, 0xB10BB459132D0A26ULL,
|
||||||
|
0x3FA9DDFB67E2F199ULL, 0x0E09B88E1914F7AFULL, 0x10E8B35AF3EEAB37ULL,
|
||||||
|
0x9EEDECA8E272B933ULL, 0xD4C718BC4AE8AE5FULL, 0x81536D601170FC20ULL,
|
||||||
|
0x91B534F885818A06ULL, 0xEC8177F83F900978ULL, 0x190E714FADA5156EULL,
|
||||||
|
0xB592BF39B0364963ULL, 0x89C350C893AE7DC1ULL, 0xAC042E70F8B383F2ULL,
|
||||||
|
0xB49B52E587A1EE60ULL, 0xFB152FE3FF26DA89ULL, 0x3E666E6F69AE2C15ULL,
|
||||||
|
0x3B544EBE544C19F9ULL, 0xE805A1E290CF2456ULL, 0x24B33C9D7ED25117ULL,
|
||||||
|
0xE74733427B72F0C1ULL, 0x0A804D18B7097475ULL, 0x57E3306D881EDB4FULL,
|
||||||
|
0x4AE7D6A36EB5DBCBULL, 0x2D8D5432157064C8ULL, 0xD1E649DE1E7F268BULL,
|
||||||
|
0x8A328A1CEDFE552CULL, 0x07A3AEC79624C7DAULL, 0x84547DDC3E203C94ULL,
|
||||||
|
0x990A98FD5071D263ULL, 0x1A4FF12616EEFC89ULL, 0xF6F7FD1431714200ULL,
|
||||||
|
0x30C05B1BA332F41CULL, 0x8D2636B81555A786ULL, 0x46C9FEB55D120902ULL,
|
||||||
|
0xCCEC0A73B49C9921ULL, 0x4E9D2827355FC492ULL, 0x19EBB029435DCB0FULL,
|
||||||
|
0x4659D2B743848A2CULL, 0x963EF2C96B33BE31ULL, 0x74F85198B05A2E7DULL,
|
||||||
|
0x5A0F544DD2B1FB18ULL, 0x03727073C2E134B1ULL, 0xC7F6AA2DE59AEA61ULL,
|
||||||
|
0x352787BAA0D7C22FULL, 0x9853EAB63B5E0B35ULL, 0xABBDCDD7ED5C0860ULL,
|
||||||
|
0xCF05DAF5AC8D77B0ULL, 0x49CAD48CEBF4A71EULL, 0x7A4C10EC2158C4A6ULL,
|
||||||
|
0xD9E92AA246BF719EULL, 0x13AE978D09FE5557ULL, 0x730499AF921549FFULL,
|
||||||
|
0x4E4B705B92903BA4ULL, 0xFF577222C14F0A3AULL, 0x55B6344CF97AAFAEULL,
|
||||||
|
0xB862225B055B6960ULL, 0xCAC09AFBDDD2CDB4ULL, 0xDAF8E9829FE96B5FULL,
|
||||||
|
0xB5FDFC5D3132C498ULL, 0x310CB380DB6F7503ULL, 0xE87FBB46217A360EULL,
|
||||||
|
0x2102AE466EBB1148ULL, 0xF8549E1A3AA5E00DULL, 0x07A69AFDCC42261AULL,
|
||||||
|
0xC4C118BFE78FEAAEULL, 0xF9F4892ED96BD438ULL, 0x1AF3DBE25D8F45DAULL,
|
||||||
|
0xF5B4B0B0D2DEEEB4ULL, 0x962ACEEFA82E1C84ULL, 0x046E3ECAAF453CE9ULL,
|
||||||
|
0xF05D129681949A4CULL, 0x964781CE734B3C84ULL, 0x9C2ED44081CE5FBDULL,
|
||||||
|
0x522E23F3925E319EULL, 0x177E00F9FC32F791ULL, 0x2BC60A63A6F3B3F2ULL,
|
||||||
|
0x222BBFAE61725606ULL, 0x486289DDCC3D6780ULL, 0x7DC7785B8EFDFC80ULL,
|
||||||
|
0x8AF38731C02BA980ULL, 0x1FAB64EA29A2DDF7ULL, 0xE4D9429322CD065AULL,
|
||||||
|
0x9DA058C67844F20CULL, 0x24C0E332B70019B0ULL, 0x233003B5A6CFE6ADULL,
|
||||||
|
0xD586BD01C5C217F6ULL, 0x5E5637885F29BC2BULL, 0x7EBA726D8C94094BULL,
|
||||||
|
0x0A56A5F0BFE39272ULL, 0xD79476A84EE20D06ULL, 0x9E4C1269BAA4BF37ULL,
|
||||||
|
0x17EFEE45B0DEE640ULL, 0x1D95B0A5FCF90BC6ULL, 0x93CBE0B699C2585DULL,
|
||||||
|
0x65FA4F227A2B6D79ULL, 0xD5F9E858292504D5ULL, 0xC2B5A03F71471A6FULL,
|
||||||
|
0x59300222B4561E00ULL, 0xCE2F8642CA0712DCULL, 0x7CA9723FBB2E8988ULL,
|
||||||
|
0x2785338347F2BA08ULL, 0xC61BB3A141E50E8CULL, 0x150F361DAB9DEC26ULL,
|
||||||
|
0x9F6A419D382595F4ULL, 0x64A53DC924FE7AC9ULL, 0x142DE49FFF7A7C3DULL,
|
||||||
|
0x0C335248857FA9E7ULL, 0x0A9C32D5EAE45305ULL, 0xE6C42178C4BBB92EULL,
|
||||||
|
0x71F1CE2490D20B07ULL, 0xF1BCC3D275AFE51AULL, 0xE728E8C83C334074ULL,
|
||||||
|
0x96FBF83A12884624ULL, 0x81A1549FD6573DA5ULL, 0x5FA7867CAF35E149ULL,
|
||||||
|
0x56986E2EF3ED091BULL, 0x917F1DD5F8886C61ULL, 0xD20D8C88C8FFE65FULL,
|
||||||
|
0x31D71DCE64B2C310ULL, 0xF165B587DF898190ULL, 0xA57E6339DD2CF3A0ULL,
|
||||||
|
0x1EF6E6DBB1961EC9ULL, 0x70CC73D90BC26E24ULL, 0xE21A6B35DF0C3AD7ULL,
|
||||||
|
0x003A93D8B2806962ULL, 0x1C99DED33CB890A1ULL, 0xCF3145DE0ADD4289ULL,
|
||||||
|
0xD0E4427A5514FB72ULL, 0x77C621CC9FB3A483ULL, 0x67A34DAC4356550BULL,
|
||||||
|
0xF8D626AAAF278509ULL
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
/// Indices to the Random64[] array
|
||||||
|
|
||||||
|
const int RandomPiece = 0;
|
||||||
|
const int RandomCastle = 768;
|
||||||
|
const int RandomEnPassant = 772;
|
||||||
|
const int RandomTurn = 780;
|
||||||
|
|
||||||
|
|
||||||
|
/// Prototypes
|
||||||
|
|
||||||
|
uint64_t book_key(const Position& pos);
|
||||||
|
uint64_t book_piece_key(Piece p, Square s);
|
||||||
|
uint64_t book_castle_key(const Position& pos);
|
||||||
|
uint64_t book_ep_key(const Position& pos);
|
||||||
|
uint64_t book_color_key(const Position& pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
|
|
||||||
|
/// Destructor. Be sure file is closed before we leave.
|
||||||
|
|
||||||
|
Book::~Book() {
|
||||||
|
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Book::open() opens a book file with a given file name
|
||||||
|
|
||||||
|
void Book::open(const string& fName) {
|
||||||
|
|
||||||
|
// Close old file before opening the new
|
||||||
|
close();
|
||||||
|
|
||||||
|
fileName = fName;
|
||||||
|
ifstream::open(fileName.c_str(), ifstream::in | ifstream::binary);
|
||||||
|
if (!is_open())
|
||||||
|
return;
|
||||||
|
|
||||||
|
// Get the book size in number of entries
|
||||||
|
seekg(0, ios::end);
|
||||||
|
bookSize = tellg() / EntrySize;
|
||||||
|
seekg(0, ios::beg);
|
||||||
|
|
||||||
|
if (!good())
|
||||||
|
{
|
||||||
|
cerr << "Failed to open book file " << fileName << endl;
|
||||||
|
Application::exit_with_failure();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Book::close() closes the file only if it is open, otherwise
|
||||||
|
/// we can end up in a little mess due to how std::ifstream works.
|
||||||
|
|
||||||
|
void Book::close() {
|
||||||
|
|
||||||
|
if (is_open())
|
||||||
|
ifstream::close();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Book::file_name() returns the file name of the currently active book,
|
||||||
|
/// or the empty string if no book is open.
|
||||||
|
|
||||||
|
const string Book::file_name() const {
|
||||||
|
|
||||||
|
return is_open() ? fileName : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Book::get_move() gets a book move for a given position. Returns
|
||||||
|
/// MOVE_NONE if no book move is found.
|
||||||
|
|
||||||
|
Move Book::get_move(const Position& pos) {
|
||||||
|
|
||||||
|
if (!is_open() || bookSize == 0)
|
||||||
|
return MOVE_NONE;
|
||||||
|
|
||||||
|
int bookMove = 0, scoresSum = 0;
|
||||||
|
uint64_t key = book_key(pos);
|
||||||
|
BookEntry entry;
|
||||||
|
|
||||||
|
// Choose a book move among the possible moves for the given position
|
||||||
|
for (int idx = find_key(key); idx < bookSize; idx++)
|
||||||
|
{
|
||||||
|
read_entry(entry, idx);
|
||||||
|
if (entry.key != key)
|
||||||
|
break;
|
||||||
|
|
||||||
|
int score = entry.count;
|
||||||
|
|
||||||
|
assert(score > 0);
|
||||||
|
|
||||||
|
// Choose book move according to its score. If a move has a very
|
||||||
|
// high score it has more probability to be choosen then a one with
|
||||||
|
// lower score. Note that first entry is always chosen.
|
||||||
|
scoresSum += score;
|
||||||
|
if (int(genrand_int32() % scoresSum) < score)
|
||||||
|
bookMove = entry.move;
|
||||||
|
}
|
||||||
|
if (!bookMove)
|
||||||
|
return MOVE_NONE;
|
||||||
|
|
||||||
|
MoveStack mlist[256];
|
||||||
|
MoveStack* last = generate_moves(pos, mlist);
|
||||||
|
for (MoveStack* cur = mlist; cur != last; cur++)
|
||||||
|
if ((int(cur->move) & 07777) == bookMove)
|
||||||
|
return cur->move;
|
||||||
|
|
||||||
|
return MOVE_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Book::find_key() takes a book key as input, and does a binary search
|
||||||
|
/// through the book file for the given key. The index to the first book
|
||||||
|
/// entry with the same key as the input is returned. When the key is not
|
||||||
|
/// found in the book file, bookSize is returned.
|
||||||
|
|
||||||
|
int Book::find_key(uint64_t key) {
|
||||||
|
|
||||||
|
int left, right, mid;
|
||||||
|
BookEntry entry;
|
||||||
|
|
||||||
|
// Binary search (finds the leftmost entry)
|
||||||
|
left = 0;
|
||||||
|
right = bookSize - 1;
|
||||||
|
|
||||||
|
assert(left <= right);
|
||||||
|
|
||||||
|
while (left < right)
|
||||||
|
{
|
||||||
|
mid = (left + right) / 2;
|
||||||
|
|
||||||
|
assert(mid >= left && mid < right);
|
||||||
|
|
||||||
|
read_entry(entry, mid);
|
||||||
|
if (key <= entry.key)
|
||||||
|
right = mid;
|
||||||
|
else
|
||||||
|
left = mid + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert(left == right);
|
||||||
|
|
||||||
|
read_entry(entry, left);
|
||||||
|
return (entry.key == key)? left : bookSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Book::read_entry() takes a BookEntry reference and an integer index as
|
||||||
|
/// input, and looks up the opening book entry at the given index in the book
|
||||||
|
/// file. The book entry is copied to the first input parameter.
|
||||||
|
|
||||||
|
void Book::read_entry(BookEntry& entry, int idx) {
|
||||||
|
|
||||||
|
assert(idx >= 0 && idx < bookSize);
|
||||||
|
assert(is_open());
|
||||||
|
|
||||||
|
seekg(idx * EntrySize, ios_base::beg);
|
||||||
|
*this >> entry;
|
||||||
|
if (!good())
|
||||||
|
{
|
||||||
|
cerr << "Failed to read book entry at index " << idx << endl;
|
||||||
|
Application::exit_with_failure();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Book::read_integer() reads size chars from the file stream
|
||||||
|
/// and converts them in an integer number.
|
||||||
|
|
||||||
|
uint64_t Book::read_integer(int size) {
|
||||||
|
|
||||||
|
char buf[8];
|
||||||
|
read(buf, size);
|
||||||
|
|
||||||
|
// Numbers are stored on disk as a binary byte stream
|
||||||
|
uint64_t n = 0ULL;
|
||||||
|
for (int i = 0; i < size; i++)
|
||||||
|
n = (n << 8) + (unsigned char)buf[i];
|
||||||
|
|
||||||
|
return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Local definitions
|
||||||
|
////
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
uint64_t book_key(const Position& pos) {
|
||||||
|
|
||||||
|
uint64_t result = 0ULL;
|
||||||
|
|
||||||
|
for (Color c = WHITE; c <= BLACK; c++)
|
||||||
|
{
|
||||||
|
Bitboard b = pos.pieces_of_color(c);
|
||||||
|
|
||||||
|
while (b)
|
||||||
|
{
|
||||||
|
Square s = pop_1st_bit(&b);
|
||||||
|
Piece p = pos.piece_on(s);
|
||||||
|
|
||||||
|
assert(piece_is_ok(p));
|
||||||
|
assert(color_of_piece(p) == c);
|
||||||
|
|
||||||
|
result ^= book_piece_key(p, s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
result ^= book_castle_key(pos);
|
||||||
|
result ^= book_ep_key(pos);
|
||||||
|
result ^= book_color_key(pos);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
uint64_t book_piece_key(Piece p, Square s) {
|
||||||
|
|
||||||
|
/// Convert pieces to the range 0..11
|
||||||
|
static const int PieceTo12[] = { 0, 0, 2, 4, 6, 8, 10, 0, 0, 1, 3, 5, 7, 9, 11 };
|
||||||
|
|
||||||
|
return Random64[RandomPiece + (PieceTo12[int(p)]^1) * 64 + int(s)];
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
uint64_t book_castle_key(const Position& pos) {
|
||||||
|
|
||||||
|
uint64_t result = 0ULL;
|
||||||
|
|
||||||
|
if (pos.can_castle_kingside(WHITE))
|
||||||
|
result ^= Random64[RandomCastle+0];
|
||||||
|
|
||||||
|
if (pos.can_castle_queenside(WHITE))
|
||||||
|
result ^= Random64[RandomCastle+1];
|
||||||
|
|
||||||
|
if (pos.can_castle_kingside(BLACK))
|
||||||
|
result ^= Random64[RandomCastle+2];
|
||||||
|
|
||||||
|
if (pos.can_castle_queenside(BLACK))
|
||||||
|
result ^= Random64[RandomCastle+3];
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
uint64_t book_ep_key(const Position& pos) {
|
||||||
|
return (pos.ep_square() == SQ_NONE ? 0ULL : Random64[RandomEnPassant + square_file(pos.ep_square())]);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
uint64_t book_color_key(const Position& pos) {
|
||||||
|
return (pos.side_to_move() == WHITE ? Random64[RandomTurn] : 0ULL);
|
||||||
|
}
|
||||||
|
}
|
||||||
+84
@@ -0,0 +1,84 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
The code in this file is based on the opening book code in PolyGlot
|
||||||
|
by Fabien Letouzey. PolyGlot is available under the GNU General
|
||||||
|
Public License, and can be downloaded from http://wbec-ridderkerk.nl
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#if !defined(BOOK_H_INCLUDED)
|
||||||
|
#define BOOK_H_INCLUDED
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include <fstream>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include "move.h"
|
||||||
|
#include "position.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Types
|
||||||
|
////
|
||||||
|
|
||||||
|
struct BookEntry {
|
||||||
|
uint64_t key;
|
||||||
|
uint16_t move;
|
||||||
|
uint16_t count;
|
||||||
|
uint16_t n;
|
||||||
|
uint16_t sum;
|
||||||
|
};
|
||||||
|
|
||||||
|
class Book : private std::ifstream {
|
||||||
|
public:
|
||||||
|
~Book();
|
||||||
|
void open(const std::string& fName);
|
||||||
|
void close();
|
||||||
|
const std::string file_name() const;
|
||||||
|
Move get_move(const Position& pos);
|
||||||
|
|
||||||
|
private:
|
||||||
|
Book& operator>>(uint64_t& n) { n = read_integer(8); return *this; }
|
||||||
|
Book& operator>>(uint16_t& n) { n = (uint16_t)read_integer(2); return *this; }
|
||||||
|
void operator>>(BookEntry& e) { *this >> e.key >> e.move >> e.count >> e.n >> e.sum; }
|
||||||
|
|
||||||
|
uint64_t read_integer(int size);
|
||||||
|
void read_entry(BookEntry& e, int n);
|
||||||
|
int find_key(uint64_t key);
|
||||||
|
|
||||||
|
std::string fileName;
|
||||||
|
int bookSize;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Global variables
|
||||||
|
////
|
||||||
|
|
||||||
|
extern Book OpeningBook;
|
||||||
|
|
||||||
|
|
||||||
|
#endif // !defined(BOOK_H_INCLUDED)
|
||||||
+50
@@ -0,0 +1,50 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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(COLOR_H_INCLUDED)
|
||||||
|
#define COLOR_H_INCLUDED
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Types
|
||||||
|
////
|
||||||
|
|
||||||
|
enum Color {
|
||||||
|
WHITE,
|
||||||
|
BLACK,
|
||||||
|
COLOR_NONE
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Inline functions
|
||||||
|
////
|
||||||
|
|
||||||
|
inline void operator++ (Color &c, int) { c = Color(int(c) + 1); }
|
||||||
|
|
||||||
|
inline Color opposite_color(Color c) {
|
||||||
|
return Color(int(c) ^ 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool color_is_ok(Color c) {
|
||||||
|
return c == WHITE || c == BLACK;
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif // !defined(COLOR_H_INCLUDED)
|
||||||
+59
@@ -0,0 +1,59 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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(DEPTH_H_INCLUDED)
|
||||||
|
#define DEPTH_H_INCLUDED
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Types
|
||||||
|
////
|
||||||
|
|
||||||
|
enum Depth {
|
||||||
|
DEPTH_ZERO = 0,
|
||||||
|
DEPTH_MAX = 200 // 100 * OnePly;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Constants
|
||||||
|
////
|
||||||
|
|
||||||
|
const Depth OnePly = Depth(2);
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Inline functions
|
||||||
|
////
|
||||||
|
|
||||||
|
inline Depth operator+ (Depth d, int i) { return Depth(int(d) + i); }
|
||||||
|
inline Depth operator+ (Depth d1, Depth d2) { return Depth(int(d1) + int(d2)); }
|
||||||
|
inline void operator+= (Depth &d, int i) { d = Depth(int(d) + i); }
|
||||||
|
inline void operator+= (Depth &d1, Depth d2) { d1 += int(d2); }
|
||||||
|
inline Depth operator- (Depth d, int i) { return Depth(int(d) - i); }
|
||||||
|
inline Depth operator- (Depth d1, Depth d2) { return Depth(int(d1) - int(d2)); }
|
||||||
|
inline void operator-= (Depth & d, int i) { d = Depth(int(d) - i); }
|
||||||
|
inline Depth operator* (Depth d, int i) { return Depth(int(d) * i); }
|
||||||
|
inline Depth operator* (int i, Depth d) { return Depth(int(d) * i); }
|
||||||
|
inline void operator*= (Depth &d, int i) { d = Depth(int(d) * i); }
|
||||||
|
inline Depth operator/ (Depth d, int i) { return Depth(int(d) / i); }
|
||||||
|
inline void operator/= (Depth &d, int i) { d = Depth(int(d) / i); }
|
||||||
|
|
||||||
|
|
||||||
|
#endif // !defined(DEPTH_H_INCLUDED)
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include "direction.h"
|
||||||
|
#include "square.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Local definitions
|
||||||
|
////
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
const SquareDelta directionToDelta[] = {
|
||||||
|
DELTA_E, DELTA_W, DELTA_N, DELTA_S, DELTA_NE, DELTA_SW, DELTA_NW, DELTA_SE
|
||||||
|
};
|
||||||
|
|
||||||
|
bool reachable(Square orig, Square dest, SignedDirection dir) {
|
||||||
|
|
||||||
|
SquareDelta delta = directionToDelta[dir];
|
||||||
|
Square from = orig;
|
||||||
|
Square to = from + delta;
|
||||||
|
while (to != dest && square_distance(to, from) == 1 && square_is_ok(to))
|
||||||
|
{
|
||||||
|
from = to;
|
||||||
|
to += delta;
|
||||||
|
}
|
||||||
|
return (to == dest && square_distance(from, to) == 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Variables
|
||||||
|
////
|
||||||
|
|
||||||
|
uint8_t DirectionTable[64][64];
|
||||||
|
uint8_t SignedDirectionTable[64][64];
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
|
void init_direction_table() {
|
||||||
|
|
||||||
|
for (Square s1 = SQ_A1; s1 <= SQ_H8; s1++)
|
||||||
|
for (Square s2 = SQ_A1; s2 <= SQ_H8; s2++)
|
||||||
|
{
|
||||||
|
DirectionTable[s1][s2] = uint8_t(DIR_NONE);
|
||||||
|
SignedDirectionTable[s1][s2] = uint8_t(SIGNED_DIR_NONE);
|
||||||
|
if (s1 == s2)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
for (SignedDirection d = SIGNED_DIR_E; d != SIGNED_DIR_NONE; d++)
|
||||||
|
{
|
||||||
|
if (reachable(s1, s2, d))
|
||||||
|
{
|
||||||
|
SignedDirectionTable[s1][s2] = uint8_t(d);
|
||||||
|
DirectionTable[s1][s2] = uint8_t(d / 2);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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(DIRECTION_H_INCLUDED)
|
||||||
|
#define DIRECTION_H_INCLUDED
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include "square.h"
|
||||||
|
#include "types.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Types
|
||||||
|
////
|
||||||
|
|
||||||
|
enum Direction {
|
||||||
|
DIR_E = 0, DIR_N = 1, DIR_NE = 2, DIR_NW = 3, DIR_NONE = 4
|
||||||
|
};
|
||||||
|
|
||||||
|
enum SignedDirection {
|
||||||
|
SIGNED_DIR_E = 0, SIGNED_DIR_W = 1,
|
||||||
|
SIGNED_DIR_N = 2, SIGNED_DIR_S = 3,
|
||||||
|
SIGNED_DIR_NE = 4, SIGNED_DIR_SW = 5,
|
||||||
|
SIGNED_DIR_NW = 6, SIGNED_DIR_SE = 7,
|
||||||
|
SIGNED_DIR_NONE = 8
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Variables
|
||||||
|
////
|
||||||
|
|
||||||
|
extern uint8_t DirectionTable[64][64];
|
||||||
|
extern uint8_t SignedDirectionTable[64][64];
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Inline functions
|
||||||
|
////
|
||||||
|
|
||||||
|
inline void operator++ (Direction& d, int) {
|
||||||
|
d = Direction(int(d) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void operator++ (SignedDirection& d, int) {
|
||||||
|
d = SignedDirection(int(d) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Direction direction_between_squares(Square s1, Square s2) {
|
||||||
|
return Direction(DirectionTable[s1][s2]);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline SignedDirection signed_direction_between_squares(Square s1, Square s2) {
|
||||||
|
return SignedDirection(SignedDirectionTable[s1][s2]);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int direction_is_diagonal(Square s1, Square s2) {
|
||||||
|
return DirectionTable[s1][s2] & 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool direction_is_straight(Square s1, Square s2) {
|
||||||
|
return DirectionTable[s1][s2] < 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Prototypes
|
||||||
|
////
|
||||||
|
|
||||||
|
extern void init_direction_table();
|
||||||
|
|
||||||
|
|
||||||
|
#endif // !defined(DIRECTION_H_INCLUDED)
|
||||||
+912
@@ -0,0 +1,912 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include <cassert>
|
||||||
|
|
||||||
|
#include "bitbase.h"
|
||||||
|
#include "bitcount.h"
|
||||||
|
#include "endgame.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Local definitions
|
||||||
|
////
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
// Table used to drive the defending king towards the edge of the board
|
||||||
|
// in KX vs K and KQ vs KR endgames.
|
||||||
|
const uint8_t MateTable[64] = {
|
||||||
|
100, 90, 80, 70, 70, 80, 90, 100,
|
||||||
|
90, 70, 60, 50, 50, 60, 70, 90,
|
||||||
|
80, 60, 40, 30, 30, 40, 60, 80,
|
||||||
|
70, 50, 30, 20, 20, 30, 50, 70,
|
||||||
|
70, 50, 30, 20, 20, 30, 50, 70,
|
||||||
|
80, 60, 40, 30, 30, 40, 60, 80,
|
||||||
|
90, 70, 60, 50, 50, 60, 70, 90,
|
||||||
|
100, 90, 80, 70, 70, 80, 90, 100,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Table used to drive the defending king towards a corner square of the
|
||||||
|
// right color in KBN vs K endgames.
|
||||||
|
const uint8_t KBNKMateTable[64] = {
|
||||||
|
200, 190, 180, 170, 160, 150, 140, 130,
|
||||||
|
190, 180, 170, 160, 150, 140, 130, 140,
|
||||||
|
180, 170, 155, 140, 140, 125, 140, 150,
|
||||||
|
170, 160, 140, 120, 110, 140, 150, 160,
|
||||||
|
160, 150, 140, 110, 120, 140, 160, 170,
|
||||||
|
150, 140, 125, 140, 140, 155, 170, 180,
|
||||||
|
140, 130, 140, 150, 160, 170, 180, 190,
|
||||||
|
130, 140, 150, 160, 170, 180, 190, 200
|
||||||
|
};
|
||||||
|
|
||||||
|
// The attacking side is given a descending bonus based on distance between
|
||||||
|
// the two kings in basic endgames.
|
||||||
|
const int DistanceBonus[8] = { 0, 0, 100, 80, 60, 40, 20, 10 };
|
||||||
|
|
||||||
|
// Bitbase for KP vs K
|
||||||
|
uint8_t KPKBitbase[24576];
|
||||||
|
|
||||||
|
// Penalty for big distance between king and knight for the defending king
|
||||||
|
// and knight in KR vs KN endgames.
|
||||||
|
const int KRKNKingKnightDistancePenalty[8] = { 0, 0, 4, 10, 20, 32, 48, 70 };
|
||||||
|
|
||||||
|
// Various inline functions for accessing the above arrays
|
||||||
|
inline Value mate_table(Square s) {
|
||||||
|
return Value(MateTable[s]);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Value kbnk_mate_table(Square s) {
|
||||||
|
return Value(KBNKMateTable[s]);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Value distance_bonus(int d) {
|
||||||
|
return Value(DistanceBonus[d]);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Value krkn_king_knight_distance_penalty(int d) {
|
||||||
|
return Value(KRKNKingKnightDistancePenalty[d]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Function for probing the KP vs K bitbase
|
||||||
|
int probe_kpk(Square wksq, Square wpsq, Square bksq, Color stm);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
|
/// Mate with KX vs K. This function is used to evaluate positions with
|
||||||
|
/// King and plenty of material vs a lone king. It simply gives the
|
||||||
|
/// attacking side a bonus for driving the defending king towards the edge
|
||||||
|
/// of the board, and for keeping the distance between the two kings small.
|
||||||
|
template<>
|
||||||
|
Value EvaluationFunction<KXK>::apply(const Position& pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == Value(0));
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == Value(0));
|
||||||
|
|
||||||
|
Square winnerKSq = pos.king_square(strongerSide);
|
||||||
|
Square loserKSq = pos.king_square(weakerSide);
|
||||||
|
|
||||||
|
Value result = pos.non_pawn_material(strongerSide)
|
||||||
|
+ pos.piece_count(strongerSide, PAWN) * PawnValueEndgame
|
||||||
|
+ mate_table(loserKSq)
|
||||||
|
+ distance_bonus(square_distance(winnerKSq, loserKSq));
|
||||||
|
|
||||||
|
if ( pos.piece_count(strongerSide, QUEEN) > 0
|
||||||
|
|| pos.piece_count(strongerSide, ROOK) > 0
|
||||||
|
|| pos.piece_count(strongerSide, BISHOP) > 1)
|
||||||
|
// TODO: check for two equal-colored bishops!
|
||||||
|
result += VALUE_KNOWN_WIN;
|
||||||
|
|
||||||
|
return (strongerSide == pos.side_to_move() ? result : -result);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Mate with KBN vs K. This is similar to KX vs K, but we have to drive the
|
||||||
|
/// defending king towards a corner square of the right color.
|
||||||
|
template<>
|
||||||
|
Value EvaluationFunction<KBNK>::apply(const Position& pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == Value(0));
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == Value(0));
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == KnightValueMidgame + BishopValueMidgame);
|
||||||
|
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
||||||
|
assert(pos.piece_count(strongerSide, KNIGHT) == 1);
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
||||||
|
|
||||||
|
Square winnerKSq = pos.king_square(strongerSide);
|
||||||
|
Square loserKSq = pos.king_square(weakerSide);
|
||||||
|
Square bishopSquare = pos.piece_list(strongerSide, BISHOP, 0);
|
||||||
|
|
||||||
|
if (square_color(bishopSquare) == BLACK)
|
||||||
|
{
|
||||||
|
winnerKSq = flop_square(winnerKSq);
|
||||||
|
loserKSq = flop_square(loserKSq);
|
||||||
|
}
|
||||||
|
|
||||||
|
Value result = VALUE_KNOWN_WIN
|
||||||
|
+ distance_bonus(square_distance(winnerKSq, loserKSq))
|
||||||
|
+ kbnk_mate_table(loserKSq);
|
||||||
|
|
||||||
|
return (strongerSide == pos.side_to_move() ? result : -result);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// KP vs K. This endgame is evaluated with the help of a bitbase.
|
||||||
|
template<>
|
||||||
|
Value EvaluationFunction<KPK>::apply(const Position& pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == Value(0));
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == Value(0));
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) == 1);
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
|
Square wksq, bksq, wpsq;
|
||||||
|
Color stm;
|
||||||
|
|
||||||
|
if (strongerSide == WHITE)
|
||||||
|
{
|
||||||
|
wksq = pos.king_square(WHITE);
|
||||||
|
bksq = pos.king_square(BLACK);
|
||||||
|
wpsq = pos.piece_list(WHITE, PAWN, 0);
|
||||||
|
stm = pos.side_to_move();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
wksq = flip_square(pos.king_square(BLACK));
|
||||||
|
bksq = flip_square(pos.king_square(WHITE));
|
||||||
|
wpsq = flip_square(pos.piece_list(BLACK, PAWN, 0));
|
||||||
|
stm = opposite_color(pos.side_to_move());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (square_file(wpsq) >= FILE_E)
|
||||||
|
{
|
||||||
|
wksq = flop_square(wksq);
|
||||||
|
bksq = flop_square(bksq);
|
||||||
|
wpsq = flop_square(wpsq);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!probe_kpk(wksq, wpsq, bksq, stm))
|
||||||
|
return VALUE_DRAW;
|
||||||
|
|
||||||
|
Value result = VALUE_KNOWN_WIN
|
||||||
|
+ PawnValueEndgame
|
||||||
|
+ Value(square_rank(wpsq));
|
||||||
|
|
||||||
|
return (strongerSide == pos.side_to_move() ? result : -result);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// KR vs KP. This is a somewhat tricky endgame to evaluate precisely without
|
||||||
|
/// a bitbase. The function below returns drawish scores when the pawn is
|
||||||
|
/// far advanced with support of the king, while the attacking king is far
|
||||||
|
/// away.
|
||||||
|
template<>
|
||||||
|
Value EvaluationFunction<KRKP>::apply(const Position& pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == 0);
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == 1);
|
||||||
|
|
||||||
|
Square wksq, wrsq, bksq, bpsq;
|
||||||
|
int tempo = (pos.side_to_move() == strongerSide);
|
||||||
|
|
||||||
|
wksq = pos.king_square(strongerSide);
|
||||||
|
wrsq = pos.piece_list(strongerSide, ROOK, 0);
|
||||||
|
bksq = pos.king_square(weakerSide);
|
||||||
|
bpsq = pos.piece_list(weakerSide, PAWN, 0);
|
||||||
|
|
||||||
|
if (strongerSide == BLACK)
|
||||||
|
{
|
||||||
|
wksq = flip_square(wksq);
|
||||||
|
wrsq = flip_square(wrsq);
|
||||||
|
bksq = flip_square(bksq);
|
||||||
|
bpsq = flip_square(bpsq);
|
||||||
|
}
|
||||||
|
|
||||||
|
Square queeningSq = make_square(square_file(bpsq), RANK_1);
|
||||||
|
Value result;
|
||||||
|
|
||||||
|
// If the stronger side's king is in front of the pawn, it's a win
|
||||||
|
if (wksq < bpsq && square_file(wksq) == square_file(bpsq))
|
||||||
|
result = RookValueEndgame - Value(square_distance(wksq, bpsq));
|
||||||
|
|
||||||
|
// If the weaker side's king is too far from the pawn and the rook,
|
||||||
|
// it's a win
|
||||||
|
else if ( square_distance(bksq, bpsq) - (tempo^1) >= 3
|
||||||
|
&& square_distance(bksq, wrsq) >= 3)
|
||||||
|
result = RookValueEndgame - Value(square_distance(wksq, bpsq));
|
||||||
|
|
||||||
|
// If the pawn is far advanced and supported by the defending king,
|
||||||
|
// the position is drawish
|
||||||
|
else if ( square_rank(bksq) <= RANK_3
|
||||||
|
&& square_distance(bksq, bpsq) == 1
|
||||||
|
&& square_rank(wksq) >= RANK_4
|
||||||
|
&& square_distance(wksq, bpsq) - tempo > 2)
|
||||||
|
result = Value(80 - square_distance(wksq, bpsq) * 8);
|
||||||
|
|
||||||
|
else
|
||||||
|
result = Value(200)
|
||||||
|
- Value(square_distance(wksq, bpsq + DELTA_S) * 8)
|
||||||
|
+ Value(square_distance(bksq, bpsq + DELTA_S) * 8)
|
||||||
|
+ Value(square_distance(bpsq, queeningSq) * 8);
|
||||||
|
|
||||||
|
return (strongerSide == pos.side_to_move() ? result : -result);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// KR vs KB. This is very simple, and always returns drawish scores. The
|
||||||
|
/// score is slightly bigger when the defending king is close to the edge.
|
||||||
|
template<>
|
||||||
|
Value EvaluationFunction<KRKB>::apply(const Position& pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
assert(pos.piece_count(weakerSide, BISHOP) == 1);
|
||||||
|
|
||||||
|
Value result = mate_table(pos.king_square(weakerSide));
|
||||||
|
return (pos.side_to_move() == strongerSide ? result : -result);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// KR vs KN. The attacking side has slightly better winning chances than
|
||||||
|
/// in KR vs KB, particularly if the king and the knight are far apart.
|
||||||
|
template<>
|
||||||
|
Value EvaluationFunction<KRKN>::apply(const Position& pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
assert(pos.piece_count(weakerSide, KNIGHT) == 1);
|
||||||
|
|
||||||
|
Square defendingKSq = pos.king_square(weakerSide);
|
||||||
|
Square nSq = pos.piece_list(weakerSide, KNIGHT, 0);
|
||||||
|
|
||||||
|
Value result = Value(10) + mate_table(defendingKSq) +
|
||||||
|
krkn_king_knight_distance_penalty(square_distance(defendingKSq, nSq));
|
||||||
|
|
||||||
|
return (strongerSide == pos.side_to_move())? result : -result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
/// defending king towards the edge. If we also take care to avoid null move
|
||||||
|
/// for the defending side in the search, this is usually sufficient to be
|
||||||
|
/// able to win KQ vs KR.
|
||||||
|
template<>
|
||||||
|
Value EvaluationFunction<KQKR>::apply(const Position& pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == QueenValueMidgame);
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
|
Square winnerKSq = pos.king_square(strongerSide);
|
||||||
|
Square loserKSq = pos.king_square(weakerSide);
|
||||||
|
|
||||||
|
Value result = QueenValueEndgame
|
||||||
|
- RookValueEndgame
|
||||||
|
+ mate_table(loserKSq)
|
||||||
|
+ distance_bonus(square_distance(winnerKSq, loserKSq));
|
||||||
|
|
||||||
|
return (strongerSide == pos.side_to_move())? result : -result;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<>
|
||||||
|
Value EvaluationFunction<KBBKN>::apply(const Position& pos) {
|
||||||
|
|
||||||
|
assert(pos.piece_count(strongerSide, BISHOP) == 2);
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == 2*BishopValueMidgame);
|
||||||
|
assert(pos.piece_count(weakerSide, KNIGHT) == 1);
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
|
||||||
|
assert(pos.pieces(PAWN) == EmptyBoardBB);
|
||||||
|
|
||||||
|
Value result = BishopValueEndgame;
|
||||||
|
Square wksq = pos.king_square(strongerSide);
|
||||||
|
Square bksq = pos.king_square(weakerSide);
|
||||||
|
Square nsq = pos.piece_list(weakerSide, KNIGHT, 0);
|
||||||
|
|
||||||
|
// Bonus for attacking king close to defending king
|
||||||
|
result += distance_bonus(square_distance(wksq, bksq));
|
||||||
|
|
||||||
|
// Bonus for driving the defending king and knight apart
|
||||||
|
result += Value(square_distance(bksq, nsq) * 32);
|
||||||
|
|
||||||
|
// Bonus for restricting the knight's mobility
|
||||||
|
result += Value((8 - count_1s_max_15(pos.attacks_from<KNIGHT>(nsq))) * 8);
|
||||||
|
|
||||||
|
return (strongerSide == pos.side_to_move() ? result : -result);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// K and two minors vs K and one or two minors or K and two knights against
|
||||||
|
/// king alone are always draw.
|
||||||
|
template<>
|
||||||
|
Value EvaluationFunction<KmmKm>::apply(const Position&) {
|
||||||
|
return Value(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<>
|
||||||
|
Value EvaluationFunction<KNNK>::apply(const Position&) {
|
||||||
|
return Value(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// KBPKScalingFunction scales endgames where the stronger side has king,
|
||||||
|
/// bishop and one or more pawns. It checks for draws with rook pawns and a
|
||||||
|
/// bishop of the wrong color. If such a draw is detected, ScaleFactor(0) is
|
||||||
|
/// returned. If not, the return value is SCALE_FACTOR_NONE, i.e. no scaling
|
||||||
|
/// will be used.
|
||||||
|
template<>
|
||||||
|
ScaleFactor ScalingFunction<KBPsK>::apply(const Position& pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
|
||||||
|
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) >= 1);
|
||||||
|
|
||||||
|
// No assertions about the material of weakerSide, because we want draws to
|
||||||
|
// be detected even when the weaker side has some pawns.
|
||||||
|
|
||||||
|
Bitboard pawns = pos.pieces(PAWN, strongerSide);
|
||||||
|
File pawnFile = square_file(pos.piece_list(strongerSide, PAWN, 0));
|
||||||
|
|
||||||
|
// All pawns are on a single rook file ?
|
||||||
|
if ( (pawnFile == FILE_A || pawnFile == FILE_H)
|
||||||
|
&& (pawns & ~file_bb(pawnFile)) == EmptyBoardBB)
|
||||||
|
{
|
||||||
|
Square bishopSq = pos.piece_list(strongerSide, BISHOP, 0);
|
||||||
|
Square queeningSq = relative_square(strongerSide, make_square(pawnFile, RANK_8));
|
||||||
|
Square kingSq = pos.king_square(weakerSide);
|
||||||
|
|
||||||
|
if ( square_color(queeningSq) != square_color(bishopSq)
|
||||||
|
&& file_distance(square_file(kingSq), pawnFile) <= 1)
|
||||||
|
{
|
||||||
|
// 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
|
||||||
|
// frontmost pawn.
|
||||||
|
Rank rank;
|
||||||
|
if (strongerSide == WHITE)
|
||||||
|
{
|
||||||
|
for (rank = RANK_7; (rank_bb(rank) & pawns) == EmptyBoardBB; rank--) {}
|
||||||
|
assert(rank >= RANK_2 && rank <= RANK_7);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
for(rank = RANK_2; (rank_bb(rank) & pawns) == EmptyBoardBB; rank++) {}
|
||||||
|
rank = Rank(rank^7); // HACK to get the relative rank
|
||||||
|
assert(rank >= RANK_2 && rank <= RANK_7);
|
||||||
|
}
|
||||||
|
// If the defending king has distance 1 to the promotion square or
|
||||||
|
// is placed somewhere in front of the pawn, it's a draw.
|
||||||
|
if ( square_distance(kingSq, queeningSq) <= 1
|
||||||
|
|| relative_rank(strongerSide, kingSq) >= rank)
|
||||||
|
return ScaleFactor(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// KQKRPScalingFunction scales endgames where the stronger side has only
|
||||||
|
/// king and queen, while the weaker side has at least a rook and a pawn.
|
||||||
|
/// It tests for fortress draws with a rook on the third rank defended by
|
||||||
|
/// a pawn.
|
||||||
|
template<>
|
||||||
|
ScaleFactor ScalingFunction<KQKRPs>::apply(const Position& pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == QueenValueMidgame);
|
||||||
|
assert(pos.piece_count(strongerSide, QUEEN) == 1);
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) == 0);
|
||||||
|
assert(pos.piece_count(weakerSide, ROOK) == 1);
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) >= 1);
|
||||||
|
|
||||||
|
Square kingSq = pos.king_square(weakerSide);
|
||||||
|
if ( relative_rank(weakerSide, kingSq) <= RANK_2
|
||||||
|
&& relative_rank(weakerSide, pos.king_square(strongerSide)) >= RANK_4
|
||||||
|
&& (pos.pieces(ROOK, weakerSide) & relative_rank_bb(weakerSide, RANK_3))
|
||||||
|
&& (pos.pieces(PAWN, weakerSide) & relative_rank_bb(weakerSide, RANK_2))
|
||||||
|
&& (pos.attacks_from<KING>(kingSq) & pos.pieces(PAWN, weakerSide)))
|
||||||
|
{
|
||||||
|
Square rsq = pos.piece_list(weakerSide, ROOK, 0);
|
||||||
|
if (pos.attacks_from<PAWN>(rsq, strongerSide) & pos.pieces(PAWN, weakerSide))
|
||||||
|
return ScaleFactor(0);
|
||||||
|
}
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// KRPKRScalingFunction scales KRP vs KR endgames. This function knows a
|
||||||
|
/// handful of the most important classes of drawn positions, but is far
|
||||||
|
/// from perfect. It would probably be a good idea to add more knowledge
|
||||||
|
/// in the future.
|
||||||
|
///
|
||||||
|
/// It would also be nice to rewrite the actual code for this function,
|
||||||
|
/// which is mostly copied from Glaurung 1.x, and not very pretty.
|
||||||
|
template<>
|
||||||
|
ScaleFactor ScalingFunction<KRPKR>::apply(const Position &pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) == 1);
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
|
Square wksq = pos.king_square(strongerSide);
|
||||||
|
Square wrsq = pos.piece_list(strongerSide, ROOK, 0);
|
||||||
|
Square wpsq = pos.piece_list(strongerSide, PAWN, 0);
|
||||||
|
Square bksq = pos.king_square(weakerSide);
|
||||||
|
Square brsq = pos.piece_list(weakerSide, ROOK, 0);
|
||||||
|
|
||||||
|
// Orient the board in such a way that the stronger side is white, and the
|
||||||
|
// pawn is on the left half of the board.
|
||||||
|
if (strongerSide == BLACK)
|
||||||
|
{
|
||||||
|
wksq = flip_square(wksq);
|
||||||
|
wrsq = flip_square(wrsq);
|
||||||
|
wpsq = flip_square(wpsq);
|
||||||
|
bksq = flip_square(bksq);
|
||||||
|
brsq = flip_square(brsq);
|
||||||
|
}
|
||||||
|
if (square_file(wpsq) > FILE_D)
|
||||||
|
{
|
||||||
|
wksq = flop_square(wksq);
|
||||||
|
wrsq = flop_square(wrsq);
|
||||||
|
wpsq = flop_square(wpsq);
|
||||||
|
bksq = flop_square(bksq);
|
||||||
|
brsq = flop_square(brsq);
|
||||||
|
}
|
||||||
|
|
||||||
|
File f = square_file(wpsq);
|
||||||
|
Rank r = square_rank(wpsq);
|
||||||
|
Square queeningSq = make_square(f, RANK_8);
|
||||||
|
int tempo = (pos.side_to_move() == strongerSide);
|
||||||
|
|
||||||
|
// If the pawn is not too far advanced and the defending king defends the
|
||||||
|
// queening square, use the third-rank defence.
|
||||||
|
if ( r <= RANK_5
|
||||||
|
&& square_distance(bksq, queeningSq) <= 1
|
||||||
|
&& wksq <= SQ_H5
|
||||||
|
&& (square_rank(brsq) == RANK_6 || (r <= RANK_3 && square_rank(wrsq) != RANK_6)))
|
||||||
|
return ScaleFactor(0);
|
||||||
|
|
||||||
|
// The defending side saves a draw by checking from behind in case the pawn
|
||||||
|
// has advanced to the 6th rank with the king behind.
|
||||||
|
if ( r == RANK_6
|
||||||
|
&& square_distance(bksq, queeningSq) <= 1
|
||||||
|
&& square_rank(wksq) + tempo <= RANK_6
|
||||||
|
&& (square_rank(brsq) == RANK_1 || (!tempo && abs(square_file(brsq) - f) >= 3)))
|
||||||
|
return ScaleFactor(0);
|
||||||
|
|
||||||
|
if ( r >= RANK_6
|
||||||
|
&& bksq == queeningSq
|
||||||
|
&& square_rank(brsq) == RANK_1
|
||||||
|
&& (!tempo || square_distance(wksq, wpsq) >= 2))
|
||||||
|
return ScaleFactor(0);
|
||||||
|
|
||||||
|
// White pawn on a7 and rook on a8 is a draw if black's king is on g7 or h7
|
||||||
|
// and the black rook is behind the pawn.
|
||||||
|
if ( wpsq == SQ_A7
|
||||||
|
&& wrsq == SQ_A8
|
||||||
|
&& (bksq == SQ_H7 || bksq == SQ_G7)
|
||||||
|
&& square_file(brsq) == FILE_A
|
||||||
|
&& (square_rank(brsq) <= RANK_3 || square_file(wksq) >= FILE_D || square_rank(wksq) <= RANK_5))
|
||||||
|
return ScaleFactor(0);
|
||||||
|
|
||||||
|
// If the defending king blocks the pawn and the attacking king is too far
|
||||||
|
// away, it's a draw.
|
||||||
|
if ( r <= RANK_5
|
||||||
|
&& bksq == wpsq + DELTA_N
|
||||||
|
&& square_distance(wksq, wpsq) - tempo >= 2
|
||||||
|
&& square_distance(wksq, brsq) - tempo >= 2)
|
||||||
|
return ScaleFactor(0);
|
||||||
|
|
||||||
|
// Pawn on the 7th rank supported by the rook from behind usually wins if the
|
||||||
|
// attacking king is closer to the queening square than the defending king,
|
||||||
|
// and the defending king cannot gain tempi by threatening the attacking rook.
|
||||||
|
if ( r == RANK_7
|
||||||
|
&& f != FILE_A
|
||||||
|
&& square_file(wrsq) == f
|
||||||
|
&& wrsq != queeningSq
|
||||||
|
&& (square_distance(wksq, queeningSq) < square_distance(bksq, queeningSq) - 2 + tempo)
|
||||||
|
&& (square_distance(wksq, queeningSq) < square_distance(bksq, wrsq) + tempo))
|
||||||
|
return ScaleFactor(SCALE_FACTOR_MAX - 2 * square_distance(wksq, queeningSq));
|
||||||
|
|
||||||
|
// Similar to the above, but with the pawn further back
|
||||||
|
if ( f != FILE_A
|
||||||
|
&& square_file(wrsq) == f
|
||||||
|
&& wrsq < wpsq
|
||||||
|
&& (square_distance(wksq, queeningSq) < square_distance(bksq, queeningSq) - 2 + tempo)
|
||||||
|
&& (square_distance(wksq, wpsq + DELTA_N) < square_distance(bksq, wpsq + DELTA_N) - 2 + tempo)
|
||||||
|
&& ( square_distance(bksq, wrsq) + tempo >= 3
|
||||||
|
|| ( square_distance(wksq, queeningSq) < square_distance(bksq, wrsq) + tempo
|
||||||
|
&& (square_distance(wksq, wpsq + DELTA_N) < square_distance(bksq, wrsq) + tempo))))
|
||||||
|
return ScaleFactor( SCALE_FACTOR_MAX
|
||||||
|
- (8 * square_distance(wpsq, queeningSq)
|
||||||
|
+ 2 * square_distance(wksq, queeningSq)));
|
||||||
|
|
||||||
|
// If the pawn is not far advanced, and the defending king is somewhere in
|
||||||
|
// the pawn's path, it's probably a draw.
|
||||||
|
if (r <= RANK_4 && bksq > wpsq)
|
||||||
|
{
|
||||||
|
if (square_file(bksq) == square_file(wpsq))
|
||||||
|
return ScaleFactor(10);
|
||||||
|
if ( abs(square_file(bksq) - square_file(wpsq)) == 1
|
||||||
|
&& square_distance(wksq, bksq) > 2)
|
||||||
|
return ScaleFactor(24 - 2 * square_distance(wksq, bksq));
|
||||||
|
}
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// KRPPKRPScalingFunction scales KRPP vs KRP endgames. There is only a
|
||||||
|
/// single pattern: If the stronger side has no pawns and the defending king
|
||||||
|
/// is actively placed, the position is drawish.
|
||||||
|
template<>
|
||||||
|
ScaleFactor ScalingFunction<KRPPKRP>::apply(const Position &pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == RookValueMidgame);
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) == 2);
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == RookValueMidgame);
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == 1);
|
||||||
|
|
||||||
|
Square wpsq1 = pos.piece_list(strongerSide, PAWN, 0);
|
||||||
|
Square wpsq2 = pos.piece_list(strongerSide, PAWN, 1);
|
||||||
|
Square bksq = pos.king_square(weakerSide);
|
||||||
|
|
||||||
|
// Does the stronger side have a passed pawn?
|
||||||
|
if ( pos.pawn_is_passed(strongerSide, wpsq1)
|
||||||
|
|| pos.pawn_is_passed(strongerSide, wpsq2))
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
|
||||||
|
Rank r = Max(relative_rank(strongerSide, wpsq1), relative_rank(strongerSide, wpsq2));
|
||||||
|
|
||||||
|
if ( file_distance(bksq, wpsq1) <= 1
|
||||||
|
&& file_distance(bksq, wpsq2) <= 1
|
||||||
|
&& relative_rank(strongerSide, bksq) > r)
|
||||||
|
{
|
||||||
|
switch (r) {
|
||||||
|
case RANK_2: return ScaleFactor(10);
|
||||||
|
case RANK_3: return ScaleFactor(10);
|
||||||
|
case RANK_4: return ScaleFactor(15);
|
||||||
|
case RANK_5: return ScaleFactor(20);
|
||||||
|
case RANK_6: return ScaleFactor(40);
|
||||||
|
default: assert(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// KPsKScalingFunction scales endgames with king and two or more pawns
|
||||||
|
/// against king. There is just a single rule here: If all pawns are on
|
||||||
|
/// the same rook file and are blocked by the defending king, it's a draw.
|
||||||
|
template<>
|
||||||
|
ScaleFactor ScalingFunction<KPsK>::apply(const Position &pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == Value(0));
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) >= 2);
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == Value(0));
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
|
Bitboard pawns = pos.pieces(PAWN, strongerSide);
|
||||||
|
|
||||||
|
// Are all pawns on the 'a' file?
|
||||||
|
if ((pawns & ~FileABB) == EmptyBoardBB)
|
||||||
|
{
|
||||||
|
// Does the defending king block the pawns?
|
||||||
|
Square ksq = pos.king_square(weakerSide);
|
||||||
|
if (square_distance(ksq, relative_square(strongerSide, SQ_A8)) <= 1)
|
||||||
|
return ScaleFactor(0);
|
||||||
|
else if( square_file(ksq) == FILE_A
|
||||||
|
&& (in_front_bb(strongerSide, ksq) & pawns) == EmptyBoardBB)
|
||||||
|
return ScaleFactor(0);
|
||||||
|
else
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
}
|
||||||
|
// Are all pawns on the 'h' file?
|
||||||
|
else if ((pawns & ~FileHBB) == EmptyBoardBB)
|
||||||
|
{
|
||||||
|
// Does the defending king block the pawns?
|
||||||
|
Square ksq = pos.king_square(weakerSide);
|
||||||
|
if (square_distance(ksq, relative_square(strongerSide, SQ_H8)) <= 1)
|
||||||
|
return ScaleFactor(0);
|
||||||
|
else if ( square_file(ksq) == FILE_H
|
||||||
|
&& (in_front_bb(strongerSide, ksq) & pawns) == EmptyBoardBB)
|
||||||
|
return ScaleFactor(0);
|
||||||
|
else
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// KBPKBScalingFunction scales KBP vs KB endgames. There are two rules:
|
||||||
|
/// If the defending king is somewhere along the path of the pawn, and the
|
||||||
|
/// square of the king is not of the same color as the stronger side's bishop,
|
||||||
|
/// it's a draw. If the two bishops have opposite color, it's almost always
|
||||||
|
/// a draw.
|
||||||
|
template<>
|
||||||
|
ScaleFactor ScalingFunction<KBPKB>::apply(const Position &pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
|
||||||
|
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) == 1);
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
|
||||||
|
assert(pos.piece_count(weakerSide, BISHOP) == 1);
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
|
Square pawnSq = pos.piece_list(strongerSide, PAWN, 0);
|
||||||
|
Square strongerBishopSq = pos.piece_list(strongerSide, BISHOP, 0);
|
||||||
|
Square weakerBishopSq = pos.piece_list(weakerSide, BISHOP, 0);
|
||||||
|
Square weakerKingSq = pos.king_square(weakerSide);
|
||||||
|
|
||||||
|
// Case 1: Defending king blocks the pawn, and cannot be driven away
|
||||||
|
if ( square_file(weakerKingSq) == square_file(pawnSq)
|
||||||
|
&& relative_rank(strongerSide, pawnSq) < relative_rank(strongerSide, weakerKingSq)
|
||||||
|
&& ( square_color(weakerKingSq) != square_color(strongerBishopSq)
|
||||||
|
|| relative_rank(strongerSide, weakerKingSq) <= RANK_6))
|
||||||
|
return ScaleFactor(0);
|
||||||
|
|
||||||
|
// Case 2: Opposite colored bishops
|
||||||
|
if (square_color(strongerBishopSq) != square_color(weakerBishopSq))
|
||||||
|
{
|
||||||
|
// We assume that the position is drawn in the following three situations:
|
||||||
|
//
|
||||||
|
// a. The pawn is on rank 5 or further back.
|
||||||
|
// b. The defending king is somewhere in the pawn's path.
|
||||||
|
// c. The defending bishop attacks some square along the pawn's path,
|
||||||
|
// and is at least three squares away from the pawn.
|
||||||
|
//
|
||||||
|
// These rules are probably not perfect, but in practice they work
|
||||||
|
// reasonably well.
|
||||||
|
|
||||||
|
if (relative_rank(strongerSide, pawnSq) <= RANK_5)
|
||||||
|
return ScaleFactor(0);
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Bitboard ray = ray_bb(pawnSq, (strongerSide == WHITE)? SIGNED_DIR_N : SIGNED_DIR_S);
|
||||||
|
if (ray & pos.pieces(KING, weakerSide))
|
||||||
|
return ScaleFactor(0);
|
||||||
|
if( (pos.attacks_from<BISHOP>(weakerBishopSq) & ray)
|
||||||
|
&& square_distance(weakerBishopSq, pawnSq) >= 3)
|
||||||
|
return ScaleFactor(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// KBPPKBScalingFunction scales KBPP vs KB endgames. It detects a few basic
|
||||||
|
/// draws with opposite-colored bishops.
|
||||||
|
template<>
|
||||||
|
ScaleFactor ScalingFunction<KBPPKB>::apply(const Position& pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
|
||||||
|
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) == 2);
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == BishopValueMidgame);
|
||||||
|
assert(pos.piece_count(weakerSide, BISHOP) == 1);
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
|
Square wbsq = pos.piece_list(strongerSide, BISHOP, 0);
|
||||||
|
Square bbsq = pos.piece_list(weakerSide, BISHOP, 0);
|
||||||
|
|
||||||
|
if (square_color(wbsq) == square_color(bbsq))
|
||||||
|
// Not opposite-colored bishops, no scaling
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
|
||||||
|
Square ksq = pos.king_square(weakerSide);
|
||||||
|
Square psq1 = pos.piece_list(strongerSide, PAWN, 0);
|
||||||
|
Square psq2 = pos.piece_list(strongerSide, PAWN, 1);
|
||||||
|
Rank r1 = square_rank(psq1);
|
||||||
|
Rank r2 = square_rank(psq2);
|
||||||
|
Square blockSq1, blockSq2;
|
||||||
|
|
||||||
|
if (relative_rank(strongerSide, psq1) > relative_rank(strongerSide, psq2))
|
||||||
|
{
|
||||||
|
blockSq1 = psq1 + pawn_push(strongerSide);
|
||||||
|
blockSq2 = make_square(square_file(psq2), square_rank(psq1));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
blockSq1 = psq2 + pawn_push(strongerSide);
|
||||||
|
blockSq2 = make_square(square_file(psq1), square_rank(psq2));
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (file_distance(psq1, psq2))
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
// Both pawns are on the same file. Easy draw if defender firmly controls
|
||||||
|
// some square in the frontmost pawn's path.
|
||||||
|
if ( square_file(ksq) == square_file(blockSq1)
|
||||||
|
&& relative_rank(strongerSide, ksq) >= relative_rank(strongerSide, blockSq1)
|
||||||
|
&& square_color(ksq) != square_color(wbsq))
|
||||||
|
return ScaleFactor(0);
|
||||||
|
else
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
|
||||||
|
case 1:
|
||||||
|
// Pawns on neighboring files. Draw if defender firmly controls the square
|
||||||
|
// in front of the frontmost pawn's path, and the square diagonally behind
|
||||||
|
// this square on the file of the other pawn.
|
||||||
|
if ( ksq == blockSq1
|
||||||
|
&& square_color(ksq) != square_color(wbsq)
|
||||||
|
&& ( bbsq == blockSq2
|
||||||
|
|| (pos.attacks_from<BISHOP>(blockSq2) & pos.pieces(BISHOP, weakerSide))
|
||||||
|
|| rank_distance(r1, r2) >= 2))
|
||||||
|
return ScaleFactor(0);
|
||||||
|
else if ( ksq == blockSq2
|
||||||
|
&& square_color(ksq) != square_color(wbsq)
|
||||||
|
&& ( bbsq == blockSq1
|
||||||
|
|| (pos.attacks_from<BISHOP>(blockSq1) & pos.pieces(BISHOP, weakerSide))))
|
||||||
|
return ScaleFactor(0);
|
||||||
|
else
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
|
||||||
|
default:
|
||||||
|
// The pawns are not on the same file or adjacent files. No scaling.
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// KBPKNScalingFunction scales KBP vs KN endgames. There is a single rule:
|
||||||
|
/// If the defending king is somewhere along the path of the pawn, and the
|
||||||
|
/// square of the king is not of the same color as the stronger side's bishop,
|
||||||
|
/// it's a draw.
|
||||||
|
template<>
|
||||||
|
ScaleFactor ScalingFunction<KBPKN>::apply(const Position &pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == BishopValueMidgame);
|
||||||
|
assert(pos.piece_count(strongerSide, BISHOP) == 1);
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) == 1);
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == KnightValueMidgame);
|
||||||
|
assert(pos.piece_count(weakerSide, KNIGHT) == 1);
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
|
Square pawnSq = pos.piece_list(strongerSide, PAWN, 0);
|
||||||
|
Square strongerBishopSq = pos.piece_list(strongerSide, BISHOP, 0);
|
||||||
|
Square weakerKingSq = pos.king_square(weakerSide);
|
||||||
|
|
||||||
|
if ( square_file(weakerKingSq) == square_file(pawnSq)
|
||||||
|
&& relative_rank(strongerSide, pawnSq) < relative_rank(strongerSide, weakerKingSq)
|
||||||
|
&& ( square_color(weakerKingSq) != square_color(strongerBishopSq)
|
||||||
|
|| relative_rank(strongerSide, weakerKingSq) <= RANK_6))
|
||||||
|
return ScaleFactor(0);
|
||||||
|
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// KNPKScalingFunction scales KNP vs K endgames. There is a single rule:
|
||||||
|
/// If the pawn is a rook pawn on the 7th rank and the defending king prevents
|
||||||
|
/// the pawn from advancing, the position is drawn.
|
||||||
|
template<>
|
||||||
|
ScaleFactor ScalingFunction<KNPK>::apply(const Position &pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == KnightValueMidgame);
|
||||||
|
assert(pos.piece_count(strongerSide, KNIGHT) == 1);
|
||||||
|
assert(pos.piece_count(strongerSide, PAWN) == 1);
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == Value(0));
|
||||||
|
assert(pos.piece_count(weakerSide, PAWN) == 0);
|
||||||
|
|
||||||
|
Square pawnSq = pos.piece_list(strongerSide, PAWN, 0);
|
||||||
|
Square weakerKingSq = pos.king_square(weakerSide);
|
||||||
|
|
||||||
|
if ( pawnSq == relative_square(strongerSide, SQ_A7)
|
||||||
|
&& square_distance(weakerKingSq, relative_square(strongerSide, SQ_A8)) <= 1)
|
||||||
|
return ScaleFactor(0);
|
||||||
|
|
||||||
|
if ( pawnSq == relative_square(strongerSide, SQ_H7)
|
||||||
|
&& square_distance(weakerKingSq, relative_square(strongerSide, SQ_H8)) <= 1)
|
||||||
|
return ScaleFactor(0);
|
||||||
|
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// KPKPScalingFunction scales KP vs KP endgames. 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 the pawn, she probably has at least a draw with
|
||||||
|
/// the pawn as well. The exception is when the stronger side's pawn is far
|
||||||
|
/// advanced and not on a rook file; in this case it is often possible to win
|
||||||
|
/// (e.g. 8/4k3/3p4/3P4/6K1/8/8/8 w - - 0 1).
|
||||||
|
template<>
|
||||||
|
ScaleFactor ScalingFunction<KPKP>::apply(const Position &pos) {
|
||||||
|
|
||||||
|
assert(pos.non_pawn_material(strongerSide) == Value(0));
|
||||||
|
assert(pos.non_pawn_material(weakerSide) == Value(0));
|
||||||
|
assert(pos.piece_count(WHITE, PAWN) == 1);
|
||||||
|
assert(pos.piece_count(BLACK, PAWN) == 1);
|
||||||
|
|
||||||
|
Square wksq, bksq, wpsq;
|
||||||
|
Color stm;
|
||||||
|
|
||||||
|
if (strongerSide == WHITE)
|
||||||
|
{
|
||||||
|
wksq = pos.king_square(WHITE);
|
||||||
|
bksq = pos.king_square(BLACK);
|
||||||
|
wpsq = pos.piece_list(WHITE, PAWN, 0);
|
||||||
|
stm = pos.side_to_move();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
wksq = flip_square(pos.king_square(BLACK));
|
||||||
|
bksq = flip_square(pos.king_square(WHITE));
|
||||||
|
wpsq = flip_square(pos.piece_list(BLACK, PAWN, 0));
|
||||||
|
stm = opposite_color(pos.side_to_move());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (square_file(wpsq) >= FILE_E)
|
||||||
|
{
|
||||||
|
wksq = flop_square(wksq);
|
||||||
|
bksq = flop_square(bksq);
|
||||||
|
wpsq = flop_square(wpsq);
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the pawn has advanced to the fifth rank or further, and is not a
|
||||||
|
// rook pawn, it's too dangerous to assume that it's at least a draw.
|
||||||
|
if ( square_rank(wpsq) >= RANK_5
|
||||||
|
&& square_file(wpsq) != FILE_A)
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
|
||||||
|
// 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.
|
||||||
|
if (probe_kpk(wksq, wpsq, bksq, stm))
|
||||||
|
return SCALE_FACTOR_NONE;
|
||||||
|
else
|
||||||
|
return ScaleFactor(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// init_bitbases() is called during program initialization, and simply loads
|
||||||
|
/// bitbases from disk into memory. At the moment, there is only the bitbase
|
||||||
|
/// for KP vs K, but we may decide to add other bitbases later.
|
||||||
|
|
||||||
|
void init_bitbases() {
|
||||||
|
generate_kpk_bitbase(KPKBitbase);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
// Probe the KP vs K bitbase:
|
||||||
|
|
||||||
|
int probe_kpk(Square wksq, Square wpsq, Square bksq, Color stm) {
|
||||||
|
|
||||||
|
int wp = int(square_file(wpsq)) + (int(square_rank(wpsq)) - 1) * 4;
|
||||||
|
int index = int(stm) + 2*int(bksq) + 128*int(wksq) + 8192*wp;
|
||||||
|
|
||||||
|
assert(index >= 0 && index < 24576*8);
|
||||||
|
return KPKBitbase[index/8] & (1 << (index&7));
|
||||||
|
}
|
||||||
|
}
|
||||||
+106
@@ -0,0 +1,106 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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(ENDGAME_H_INCLUDED)
|
||||||
|
#define ENDGAME_H_INCLUDED
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include "position.h"
|
||||||
|
#include "scale.h"
|
||||||
|
#include "value.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Types
|
||||||
|
////
|
||||||
|
|
||||||
|
enum EndgameType {
|
||||||
|
|
||||||
|
// Evaluation functions
|
||||||
|
KXK, // Generic "mate lone king" eval
|
||||||
|
KBNK, // KBN vs K
|
||||||
|
KPK, // KP vs K
|
||||||
|
KRKP, // KR vs KP
|
||||||
|
KRKB, // KR vs KB
|
||||||
|
KRKN, // KR vs KN
|
||||||
|
KQKR, // KQ vs KR
|
||||||
|
KBBKN, // KBB vs KN
|
||||||
|
KNNK, // KNN vs K
|
||||||
|
KmmKm, // K and two minors vs K and one or two minors
|
||||||
|
|
||||||
|
// Scaling functions
|
||||||
|
KBPsK, // KB+pawns vs K
|
||||||
|
KQKRPs, // KQ vs KR+pawns
|
||||||
|
KRPKR, // KRP vs KR
|
||||||
|
KRPPKRP, // KRPP vs KRP
|
||||||
|
KPsK, // King and pawns vs king
|
||||||
|
KBPKB, // KBP vs KB
|
||||||
|
KBPPKB, // KBPP vs KB
|
||||||
|
KBPKN, // KBP vs KN
|
||||||
|
KNPK, // KNP vs K
|
||||||
|
KPKP // KP vs KP
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Template abstract base class for all special endgame functions
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
class EndgameFunctionBase {
|
||||||
|
public:
|
||||||
|
EndgameFunctionBase(Color c) : strongerSide(c), weakerSide(opposite_color(c)) {}
|
||||||
|
virtual ~EndgameFunctionBase() {}
|
||||||
|
virtual T apply(const Position&) = 0;
|
||||||
|
Color color() const { return strongerSide; }
|
||||||
|
|
||||||
|
protected:
|
||||||
|
Color strongerSide, weakerSide;
|
||||||
|
};
|
||||||
|
|
||||||
|
typedef EndgameFunctionBase<Value> EndgameEvaluationFunctionBase;
|
||||||
|
typedef EndgameFunctionBase<ScaleFactor> EndgameScalingFunctionBase;
|
||||||
|
|
||||||
|
|
||||||
|
/// Templates subclass for various concrete endgames
|
||||||
|
|
||||||
|
template<EndgameType>
|
||||||
|
struct EvaluationFunction : public EndgameEvaluationFunctionBase {
|
||||||
|
typedef EndgameEvaluationFunctionBase Base;
|
||||||
|
explicit EvaluationFunction(Color c): EndgameEvaluationFunctionBase(c) {}
|
||||||
|
Value apply(const Position&);
|
||||||
|
};
|
||||||
|
|
||||||
|
template<EndgameType>
|
||||||
|
struct ScalingFunction : public EndgameScalingFunctionBase {
|
||||||
|
typedef EndgameScalingFunctionBase Base;
|
||||||
|
explicit ScalingFunction(Color c) : EndgameScalingFunctionBase(c) {}
|
||||||
|
ScaleFactor apply(const Position&);
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Prototypes
|
||||||
|
////
|
||||||
|
|
||||||
|
extern void init_bitbases();
|
||||||
|
|
||||||
|
|
||||||
|
#endif // !defined(ENDGAME_H_INCLUDED)
|
||||||
-335
@@ -1,335 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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 "engine.h"
|
|
||||||
|
|
||||||
#include <cassert>
|
|
||||||
#include <deque>
|
|
||||||
#include <iosfwd>
|
|
||||||
#include <memory>
|
|
||||||
#include <ostream>
|
|
||||||
#include <sstream>
|
|
||||||
#include <string_view>
|
|
||||||
#include <utility>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#include "evaluate.h"
|
|
||||||
#include "misc.h"
|
|
||||||
#include "nnue/network.h"
|
|
||||||
#include "nnue/nnue_common.h"
|
|
||||||
#include "perft.h"
|
|
||||||
#include "position.h"
|
|
||||||
#include "search.h"
|
|
||||||
#include "syzygy/tbprobe.h"
|
|
||||||
#include "types.h"
|
|
||||||
#include "uci.h"
|
|
||||||
#include "ucioption.h"
|
|
||||||
|
|
||||||
namespace Stockfish {
|
|
||||||
|
|
||||||
namespace NN = Eval::NNUE;
|
|
||||||
|
|
||||||
constexpr auto StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
|
|
||||||
constexpr int MaxHashMB = Is64Bit ? 33554432 : 2048;
|
|
||||||
|
|
||||||
Engine::Engine(std::string path) :
|
|
||||||
binaryDirectory(CommandLine::get_binary_directory(path)),
|
|
||||||
numaContext(NumaConfig::from_system()),
|
|
||||||
states(new std::deque<StateInfo>(1)),
|
|
||||||
threads(),
|
|
||||||
networks(
|
|
||||||
numaContext,
|
|
||||||
NN::Networks(
|
|
||||||
NN::NetworkBig({EvalFileDefaultNameBig, "None", ""}, NN::EmbeddedNNUEType::BIG),
|
|
||||||
NN::NetworkSmall({EvalFileDefaultNameSmall, "None", ""}, NN::EmbeddedNNUEType::SMALL))) {
|
|
||||||
pos.set(StartFEN, false, &states->back());
|
|
||||||
capSq = SQ_NONE;
|
|
||||||
|
|
||||||
options["Debug Log File"] << Option("", [](const Option& o) {
|
|
||||||
start_logger(o);
|
|
||||||
return std::nullopt;
|
|
||||||
});
|
|
||||||
|
|
||||||
options["NumaPolicy"] << Option("auto", [this](const Option& o) {
|
|
||||||
set_numa_config_from_option(o);
|
|
||||||
return numa_config_information_as_string() + "\n" + thread_binding_information_as_string();
|
|
||||||
});
|
|
||||||
|
|
||||||
options["Threads"] << Option(1, 1, 1024, [this](const Option&) {
|
|
||||||
resize_threads();
|
|
||||||
return thread_binding_information_as_string();
|
|
||||||
});
|
|
||||||
|
|
||||||
options["Hash"] << Option(16, 1, MaxHashMB, [this](const Option& o) {
|
|
||||||
set_tt_size(o);
|
|
||||||
return std::nullopt;
|
|
||||||
});
|
|
||||||
|
|
||||||
options["Clear Hash"] << Option([this](const Option&) {
|
|
||||||
search_clear();
|
|
||||||
return std::nullopt;
|
|
||||||
});
|
|
||||||
options["Ponder"] << Option(false);
|
|
||||||
options["MultiPV"] << Option(1, 1, MAX_MOVES);
|
|
||||||
options["Skill Level"] << Option(20, 0, 20);
|
|
||||||
options["Move Overhead"] << Option(10, 0, 5000);
|
|
||||||
options["nodestime"] << Option(0, 0, 10000);
|
|
||||||
options["UCI_Chess960"] << Option(false);
|
|
||||||
options["UCI_LimitStrength"] << Option(false);
|
|
||||||
options["UCI_Elo"] << Option(Stockfish::Search::Skill::LowestElo,
|
|
||||||
Stockfish::Search::Skill::LowestElo,
|
|
||||||
Stockfish::Search::Skill::HighestElo);
|
|
||||||
options["UCI_ShowWDL"] << Option(false);
|
|
||||||
options["SyzygyPath"] << Option("", [](const Option& o) {
|
|
||||||
Tablebases::init(o);
|
|
||||||
return std::nullopt;
|
|
||||||
});
|
|
||||||
options["SyzygyProbeDepth"] << Option(1, 1, 100);
|
|
||||||
options["Syzygy50MoveRule"] << Option(true);
|
|
||||||
options["SyzygyProbeLimit"] << Option(7, 0, 7);
|
|
||||||
options["EvalFile"] << Option(EvalFileDefaultNameBig, [this](const Option& o) {
|
|
||||||
load_big_network(o);
|
|
||||||
return std::nullopt;
|
|
||||||
});
|
|
||||||
options["EvalFileSmall"] << Option(EvalFileDefaultNameSmall, [this](const Option& o) {
|
|
||||||
load_small_network(o);
|
|
||||||
return std::nullopt;
|
|
||||||
});
|
|
||||||
|
|
||||||
load_networks();
|
|
||||||
resize_threads();
|
|
||||||
}
|
|
||||||
|
|
||||||
std::uint64_t Engine::perft(const std::string& fen, Depth depth, bool isChess960) {
|
|
||||||
verify_networks();
|
|
||||||
|
|
||||||
return Benchmark::perft(fen, depth, isChess960);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Engine::go(Search::LimitsType& limits) {
|
|
||||||
assert(limits.perft == 0);
|
|
||||||
verify_networks();
|
|
||||||
limits.capSq = capSq;
|
|
||||||
|
|
||||||
threads.start_thinking(options, pos, states, limits);
|
|
||||||
}
|
|
||||||
void Engine::stop() { threads.stop = true; }
|
|
||||||
|
|
||||||
void Engine::search_clear() {
|
|
||||||
wait_for_search_finished();
|
|
||||||
|
|
||||||
tt.clear(threads);
|
|
||||||
threads.clear();
|
|
||||||
|
|
||||||
// @TODO wont work with multiple instances
|
|
||||||
Tablebases::init(options["SyzygyPath"]); // Free mapped files
|
|
||||||
}
|
|
||||||
|
|
||||||
void Engine::set_on_update_no_moves(std::function<void(const Engine::InfoShort&)>&& f) {
|
|
||||||
updateContext.onUpdateNoMoves = std::move(f);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Engine::set_on_update_full(std::function<void(const Engine::InfoFull&)>&& f) {
|
|
||||||
updateContext.onUpdateFull = std::move(f);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Engine::set_on_iter(std::function<void(const Engine::InfoIter&)>&& f) {
|
|
||||||
updateContext.onIter = std::move(f);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Engine::set_on_bestmove(std::function<void(std::string_view, std::string_view)>&& f) {
|
|
||||||
updateContext.onBestmove = std::move(f);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Engine::wait_for_search_finished() { threads.main_thread()->wait_for_search_finished(); }
|
|
||||||
|
|
||||||
void Engine::set_position(const std::string& fen, const std::vector<std::string>& moves) {
|
|
||||||
// Drop the old state and create a new one
|
|
||||||
states = StateListPtr(new std::deque<StateInfo>(1));
|
|
||||||
pos.set(fen, options["UCI_Chess960"], &states->back());
|
|
||||||
|
|
||||||
capSq = SQ_NONE;
|
|
||||||
for (const auto& move : moves)
|
|
||||||
{
|
|
||||||
auto m = UCIEngine::to_move(pos, move);
|
|
||||||
|
|
||||||
if (m == Move::none())
|
|
||||||
break;
|
|
||||||
|
|
||||||
states->emplace_back();
|
|
||||||
pos.do_move(m, states->back());
|
|
||||||
|
|
||||||
capSq = SQ_NONE;
|
|
||||||
DirtyPiece& dp = states->back().dirtyPiece;
|
|
||||||
if (dp.dirty_num > 1 && dp.to[1] == SQ_NONE)
|
|
||||||
capSq = m.to_sq();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// modifiers
|
|
||||||
|
|
||||||
void Engine::set_numa_config_from_option(const std::string& o) {
|
|
||||||
if (o == "auto" || o == "system")
|
|
||||||
{
|
|
||||||
numaContext.set_numa_config(NumaConfig::from_system());
|
|
||||||
}
|
|
||||||
else if (o == "hardware")
|
|
||||||
{
|
|
||||||
// Don't respect affinity set in the system.
|
|
||||||
numaContext.set_numa_config(NumaConfig::from_system(false));
|
|
||||||
}
|
|
||||||
else if (o == "none")
|
|
||||||
{
|
|
||||||
numaContext.set_numa_config(NumaConfig{});
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
numaContext.set_numa_config(NumaConfig::from_string(o));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Force reallocation of threads in case affinities need to change.
|
|
||||||
resize_threads();
|
|
||||||
threads.ensure_network_replicated();
|
|
||||||
}
|
|
||||||
|
|
||||||
void Engine::resize_threads() {
|
|
||||||
threads.wait_for_search_finished();
|
|
||||||
threads.set(numaContext.get_numa_config(), {options, threads, tt, networks}, updateContext);
|
|
||||||
|
|
||||||
// Reallocate the hash with the new threadpool size
|
|
||||||
set_tt_size(options["Hash"]);
|
|
||||||
threads.ensure_network_replicated();
|
|
||||||
}
|
|
||||||
|
|
||||||
void Engine::set_tt_size(size_t mb) {
|
|
||||||
wait_for_search_finished();
|
|
||||||
tt.resize(mb, threads);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Engine::set_ponderhit(bool b) { threads.main_manager()->ponder = b; }
|
|
||||||
|
|
||||||
// network related
|
|
||||||
|
|
||||||
void Engine::verify_networks() const {
|
|
||||||
networks->big.verify(options["EvalFile"]);
|
|
||||||
networks->small.verify(options["EvalFileSmall"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
void Engine::load_networks() {
|
|
||||||
networks.modify_and_replicate([this](NN::Networks& networks_) {
|
|
||||||
networks_.big.load(binaryDirectory, options["EvalFile"]);
|
|
||||||
networks_.small.load(binaryDirectory, options["EvalFileSmall"]);
|
|
||||||
});
|
|
||||||
threads.clear();
|
|
||||||
threads.ensure_network_replicated();
|
|
||||||
}
|
|
||||||
|
|
||||||
void Engine::load_big_network(const std::string& file) {
|
|
||||||
networks.modify_and_replicate(
|
|
||||||
[this, &file](NN::Networks& networks_) { networks_.big.load(binaryDirectory, file); });
|
|
||||||
threads.clear();
|
|
||||||
threads.ensure_network_replicated();
|
|
||||||
}
|
|
||||||
|
|
||||||
void Engine::load_small_network(const std::string& file) {
|
|
||||||
networks.modify_and_replicate(
|
|
||||||
[this, &file](NN::Networks& networks_) { networks_.small.load(binaryDirectory, file); });
|
|
||||||
threads.clear();
|
|
||||||
threads.ensure_network_replicated();
|
|
||||||
}
|
|
||||||
|
|
||||||
void Engine::save_network(const std::pair<std::optional<std::string>, std::string> files[2]) {
|
|
||||||
networks.modify_and_replicate([&files](NN::Networks& networks_) {
|
|
||||||
networks_.big.save(files[0].first);
|
|
||||||
networks_.small.save(files[1].first);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// utility functions
|
|
||||||
|
|
||||||
void Engine::trace_eval() const {
|
|
||||||
StateListPtr trace_states(new std::deque<StateInfo>(1));
|
|
||||||
Position p;
|
|
||||||
p.set(pos.fen(), options["UCI_Chess960"], &trace_states->back());
|
|
||||||
|
|
||||||
verify_networks();
|
|
||||||
|
|
||||||
sync_cout << "\n" << Eval::trace(p, *networks) << sync_endl;
|
|
||||||
}
|
|
||||||
|
|
||||||
const OptionsMap& Engine::get_options() const { return options; }
|
|
||||||
OptionsMap& Engine::get_options() { return options; }
|
|
||||||
|
|
||||||
std::string Engine::fen() const { return pos.fen(); }
|
|
||||||
|
|
||||||
void Engine::flip() { pos.flip(); }
|
|
||||||
|
|
||||||
std::string Engine::visualize() const {
|
|
||||||
std::stringstream ss;
|
|
||||||
ss << pos;
|
|
||||||
return ss.str();
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<std::pair<size_t, size_t>> Engine::get_bound_thread_count_by_numa_node() const {
|
|
||||||
auto counts = threads.get_bound_thread_count_by_numa_node();
|
|
||||||
const NumaConfig& cfg = numaContext.get_numa_config();
|
|
||||||
std::vector<std::pair<size_t, size_t>> ratios;
|
|
||||||
NumaIndex n = 0;
|
|
||||||
for (; n < counts.size(); ++n)
|
|
||||||
ratios.emplace_back(counts[n], cfg.num_cpus_in_numa_node(n));
|
|
||||||
if (!counts.empty())
|
|
||||||
for (; n < cfg.num_numa_nodes(); ++n)
|
|
||||||
ratios.emplace_back(0, cfg.num_cpus_in_numa_node(n));
|
|
||||||
return ratios;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string Engine::get_numa_config_as_string() const {
|
|
||||||
return numaContext.get_numa_config().to_string();
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string Engine::numa_config_information_as_string() const {
|
|
||||||
auto cfgStr = get_numa_config_as_string();
|
|
||||||
return "Available processors: " + cfgStr;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string Engine::thread_binding_information_as_string() const {
|
|
||||||
auto boundThreadsByNode = get_bound_thread_count_by_numa_node();
|
|
||||||
std::stringstream ss;
|
|
||||||
|
|
||||||
size_t threadsSize = threads.size();
|
|
||||||
ss << "Using " << threadsSize << (threadsSize > 1 ? " threads" : " thread");
|
|
||||||
|
|
||||||
if (boundThreadsByNode.empty())
|
|
||||||
return ss.str();
|
|
||||||
|
|
||||||
ss << " with NUMA node thread binding: ";
|
|
||||||
|
|
||||||
bool isFirst = true;
|
|
||||||
|
|
||||||
for (auto&& [current, total] : boundThreadsByNode)
|
|
||||||
{
|
|
||||||
if (!isFirst)
|
|
||||||
ss << ":";
|
|
||||||
ss << current << "/" << total;
|
|
||||||
isFirst = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return ss.str();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
-128
@@ -1,128 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef ENGINE_H_INCLUDED
|
|
||||||
#define ENGINE_H_INCLUDED
|
|
||||||
|
|
||||||
#include <cstddef>
|
|
||||||
#include <cstdint>
|
|
||||||
#include <functional>
|
|
||||||
#include <optional>
|
|
||||||
#include <string>
|
|
||||||
#include <string_view>
|
|
||||||
#include <utility>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#include "nnue/network.h"
|
|
||||||
#include "numa.h"
|
|
||||||
#include "position.h"
|
|
||||||
#include "search.h"
|
|
||||||
#include "syzygy/tbprobe.h" // for Stockfish::Depth
|
|
||||||
#include "thread.h"
|
|
||||||
#include "tt.h"
|
|
||||||
#include "ucioption.h"
|
|
||||||
|
|
||||||
namespace Stockfish {
|
|
||||||
|
|
||||||
enum Square : int;
|
|
||||||
|
|
||||||
class Engine {
|
|
||||||
public:
|
|
||||||
using InfoShort = Search::InfoShort;
|
|
||||||
using InfoFull = Search::InfoFull;
|
|
||||||
using InfoIter = Search::InfoIteration;
|
|
||||||
|
|
||||||
Engine(std::string path = "");
|
|
||||||
|
|
||||||
// Cannot be movable due to components holding backreferences to fields
|
|
||||||
Engine(const Engine&) = delete;
|
|
||||||
Engine(Engine&&) = delete;
|
|
||||||
Engine& operator=(const Engine&) = delete;
|
|
||||||
Engine& operator=(Engine&&) = delete;
|
|
||||||
|
|
||||||
~Engine() { wait_for_search_finished(); }
|
|
||||||
|
|
||||||
std::uint64_t perft(const std::string& fen, Depth depth, bool isChess960);
|
|
||||||
|
|
||||||
// non blocking call to start searching
|
|
||||||
void go(Search::LimitsType&);
|
|
||||||
// non blocking call to stop searching
|
|
||||||
void stop();
|
|
||||||
|
|
||||||
// blocking call to wait for search to finish
|
|
||||||
void wait_for_search_finished();
|
|
||||||
// set a new position, moves are in UCI format
|
|
||||||
void set_position(const std::string& fen, const std::vector<std::string>& moves);
|
|
||||||
|
|
||||||
// modifiers
|
|
||||||
|
|
||||||
void set_numa_config_from_option(const std::string& o);
|
|
||||||
void resize_threads();
|
|
||||||
void set_tt_size(size_t mb);
|
|
||||||
void set_ponderhit(bool);
|
|
||||||
void search_clear();
|
|
||||||
|
|
||||||
void set_on_update_no_moves(std::function<void(const InfoShort&)>&&);
|
|
||||||
void set_on_update_full(std::function<void(const InfoFull&)>&&);
|
|
||||||
void set_on_iter(std::function<void(const InfoIter&)>&&);
|
|
||||||
void set_on_bestmove(std::function<void(std::string_view, std::string_view)>&&);
|
|
||||||
|
|
||||||
// network related
|
|
||||||
|
|
||||||
void verify_networks() const;
|
|
||||||
void load_networks();
|
|
||||||
void load_big_network(const std::string& file);
|
|
||||||
void load_small_network(const std::string& file);
|
|
||||||
void save_network(const std::pair<std::optional<std::string>, std::string> files[2]);
|
|
||||||
|
|
||||||
// utility functions
|
|
||||||
|
|
||||||
void trace_eval() const;
|
|
||||||
|
|
||||||
const OptionsMap& get_options() const;
|
|
||||||
OptionsMap& get_options();
|
|
||||||
|
|
||||||
std::string fen() const;
|
|
||||||
void flip();
|
|
||||||
std::string visualize() const;
|
|
||||||
std::vector<std::pair<size_t, size_t>> get_bound_thread_count_by_numa_node() const;
|
|
||||||
std::string get_numa_config_as_string() const;
|
|
||||||
std::string numa_config_information_as_string() const;
|
|
||||||
std::string thread_binding_information_as_string() const;
|
|
||||||
|
|
||||||
private:
|
|
||||||
const std::string binaryDirectory;
|
|
||||||
|
|
||||||
NumaReplicationContext numaContext;
|
|
||||||
|
|
||||||
Position pos;
|
|
||||||
StateListPtr states;
|
|
||||||
Square capSq;
|
|
||||||
|
|
||||||
OptionsMap options;
|
|
||||||
ThreadPool threads;
|
|
||||||
TranspositionTable tt;
|
|
||||||
LazyNumaReplicated<Eval::NNUE::Networks> networks;
|
|
||||||
|
|
||||||
Search::SearchManager::UpdateContext updateContext;
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Stockfish
|
|
||||||
|
|
||||||
|
|
||||||
#endif // #ifndef ENGINE_H_INCLUDED
|
|
||||||
+1216
-89
File diff suppressed because it is too large
Load Diff
+83
-26
@@ -1,6 +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-2024 The Stockfish developers (see AUTHORS file)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
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
|
||||||
@@ -16,41 +17,97 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#ifndef EVALUATE_H_INCLUDED
|
|
||||||
|
#if !defined(EVALUATE_H_INCLUDED)
|
||||||
#define EVALUATE_H_INCLUDED
|
#define EVALUATE_H_INCLUDED
|
||||||
|
|
||||||
#include <string>
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
#include "types.h"
|
#include <iostream>
|
||||||
|
|
||||||
namespace Stockfish {
|
#include "material.h"
|
||||||
|
#include "pawns.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Types
|
||||||
|
////
|
||||||
|
|
||||||
|
|
||||||
|
/// The EvalInfo struct contains various information computed and collected
|
||||||
|
/// by the evaluation function. An EvalInfo object is passed as one of the
|
||||||
|
/// arguments to the evaluation function, and the search can make use of its
|
||||||
|
/// contents to make intelligent search decisions.
|
||||||
|
///
|
||||||
|
/// At the moment, this is not utilized very much: The only part of the
|
||||||
|
/// EvalInfo object which is used by the search is futilityMargin.
|
||||||
class Position;
|
class Position;
|
||||||
|
|
||||||
namespace Eval {
|
struct EvalInfo {
|
||||||
|
|
||||||
// The default net name MUST follow the format nn-[SHA256 first 12 digits].nnue
|
// Middle game and endgame evaluations
|
||||||
// for the build process (profile-build and fishtest) to work. Do not change the
|
Score value;
|
||||||
// name of the macro or the location where this macro is defined, as it is used
|
|
||||||
// in the Makefile/Fishtest.
|
|
||||||
#define EvalFileDefaultNameBig "nn-1111cefa1111.nnue"
|
|
||||||
#define EvalFileDefaultNameSmall "nn-37f18f62d772.nnue"
|
|
||||||
|
|
||||||
namespace NNUE {
|
// Pointers to material and pawn hash table entries
|
||||||
struct Networks;
|
MaterialInfo* mi;
|
||||||
struct AccumulatorCaches;
|
PawnInfo* pi;
|
||||||
}
|
|
||||||
|
|
||||||
std::string trace(Position& pos, const Eval::NNUE::Networks& networks);
|
// attackedBy[color][piece type] is a bitboard representing all squares
|
||||||
|
// attacked by a given color and piece type, attackedBy[color][0] contains
|
||||||
|
// all squares attacked by the given color.
|
||||||
|
Bitboard attackedBy[2][8];
|
||||||
|
Bitboard attacked_by(Color c) const { return attackedBy[c][0]; }
|
||||||
|
Bitboard attacked_by(Color c, PieceType pt) const { return attackedBy[c][pt]; }
|
||||||
|
|
||||||
int simple_eval(const Position& pos, Color c);
|
// kingZone[color] is the zone around the enemy king which is considered
|
||||||
bool use_smallnet(const Position& pos);
|
// by the king safety evaluation. This consists of the squares directly
|
||||||
Value evaluate(const NNUE::Networks& networks,
|
// adjacent to the king, and the three (or two, for a king on an edge file)
|
||||||
const Position& pos,
|
// squares two ranks in front of the king. For instance, if black's king
|
||||||
Eval::NNUE::AccumulatorCaches& caches,
|
// is on g8, kingZone[WHITE] is a bitboard containing the squares f8, h8,
|
||||||
int optimism);
|
// f7, g7, h7, f6, g6 and h6.
|
||||||
} // namespace Eval
|
Bitboard kingZone[2];
|
||||||
|
|
||||||
} // namespace Stockfish
|
// kingAttackersCount[color] is the number of pieces of the given color
|
||||||
|
// which attack a square in the kingZone of the enemy king.
|
||||||
|
int kingAttackersCount[2];
|
||||||
|
|
||||||
#endif // #ifndef EVALUATE_H_INCLUDED
|
// kingAttackersWeight[color] is the sum of the "weight" of the pieces of the
|
||||||
|
// given color which attack a square in the kingZone of the enemy king. The
|
||||||
|
// weights of the individual piece types are given by the variables
|
||||||
|
// QueenAttackWeight, RookAttackWeight, BishopAttackWeight and
|
||||||
|
// KnightAttackWeight in evaluate.cpp
|
||||||
|
int kingAttackersWeight[2];
|
||||||
|
|
||||||
|
// kingAdjacentZoneAttacksCount[color] is the number of attacks to squares
|
||||||
|
// 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
|
||||||
|
// king is on g8 and there's a white knight on g5, this knight adds
|
||||||
|
// 2 to kingAdjacentZoneAttacksCount[BLACK].
|
||||||
|
int kingAdjacentZoneAttacksCount[2];
|
||||||
|
|
||||||
|
// mateThreat[color] is a move for the given side which gives a direct mate.
|
||||||
|
Move mateThreat[2];
|
||||||
|
|
||||||
|
// Middle game and endgame mobility scores.
|
||||||
|
Score mobility;
|
||||||
|
|
||||||
|
// Extra futility margin. This is added to the standard futility margin
|
||||||
|
// in the quiescence search.
|
||||||
|
Value futilityMargin;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Prototypes
|
||||||
|
////
|
||||||
|
|
||||||
|
extern Value evaluate(const Position& pos, EvalInfo& ei, int threadID);
|
||||||
|
extern Value quick_evaluate(const Position& pos);
|
||||||
|
extern void init_eval(int threads);
|
||||||
|
extern void quit_eval();
|
||||||
|
extern void read_weights(Color sideToMove);
|
||||||
|
|
||||||
|
|
||||||
|
#endif // !defined(EVALUATE_H_INCLUDED)
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include <cassert>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "history.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
|
|
||||||
|
/// Constructor
|
||||||
|
|
||||||
|
History::History() { clear(); }
|
||||||
|
|
||||||
|
|
||||||
|
/// History::clear() clears the history tables
|
||||||
|
|
||||||
|
void History::clear() {
|
||||||
|
memset(history, 0, 2 * 8 * 64 * sizeof(int));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// History::success() registers a move as being successful. This is done
|
||||||
|
/// whenever a non-capturing move causes a beta cutoff in the main search.
|
||||||
|
/// The three parameters are the moving piece, the destination square, and
|
||||||
|
/// the search depth.
|
||||||
|
|
||||||
|
void History::success(Piece p, Square to, Depth d) {
|
||||||
|
|
||||||
|
assert(piece_is_ok(p));
|
||||||
|
assert(square_is_ok(to));
|
||||||
|
|
||||||
|
history[p][to] += int(d) * int(d);
|
||||||
|
|
||||||
|
// Prevent history overflow
|
||||||
|
if (history[p][to] >= HistoryMax)
|
||||||
|
for (int i = 0; i < 16; i++)
|
||||||
|
for (int j = 0; j < 64; j++)
|
||||||
|
history[i][j] /= 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// History::failure() registers a move as being unsuccessful. The function is
|
||||||
|
/// called for each non-capturing move which failed to produce a beta cutoff
|
||||||
|
/// at a node where a beta cutoff was finally found.
|
||||||
|
|
||||||
|
void History::failure(Piece p, Square to, Depth d) {
|
||||||
|
|
||||||
|
assert(piece_is_ok(p));
|
||||||
|
assert(square_is_ok(to));
|
||||||
|
|
||||||
|
history[p][to] -= int(d) * int(d);
|
||||||
|
if (history[p][to] < 0)
|
||||||
|
history[p][to] = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// History::move_ordering_score() returns an integer value used to order the
|
||||||
|
/// non-capturing moves in the MovePicker class.
|
||||||
|
|
||||||
|
int History::move_ordering_score(Piece p, Square to) const {
|
||||||
|
|
||||||
|
assert(piece_is_ok(p));
|
||||||
|
assert(square_is_ok(to));
|
||||||
|
|
||||||
|
return history[p][to];
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include "depth.h"
|
||||||
|
#include "move.h"
|
||||||
|
#include "piece.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Types
|
||||||
|
////
|
||||||
|
|
||||||
|
/// 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:
|
||||||
|
History();
|
||||||
|
void clear();
|
||||||
|
void success(Piece p, Square to, Depth d);
|
||||||
|
void failure(Piece p, Square to, Depth d);
|
||||||
|
int move_ordering_score(Piece p, Square to) const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
int history[16][64]; // [piece][square]
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Constants and variables
|
||||||
|
////
|
||||||
|
|
||||||
|
/// HistoryMax controls how often the history counters will be scaled down:
|
||||||
|
/// When the history score for a move gets bigger than HistoryMax, all
|
||||||
|
/// entries in the table are divided by 4. It is difficult to guess what
|
||||||
|
/// the ideal value of this constant is. Scaling down the scores often has
|
||||||
|
/// the effect that parts of the search tree which have been searched
|
||||||
|
/// recently have a bigger importance for move ordering than the moves which
|
||||||
|
/// have been searched a long time ago.
|
||||||
|
|
||||||
|
const int HistoryMax = 25000 * OnePly;
|
||||||
|
|
||||||
|
|
||||||
|
#endif // !defined(HISTORY_H_INCLUDED)
|
||||||
@@ -1,26 +0,0 @@
|
|||||||
The file "incbin.h" is free and unencumbered software released into
|
|
||||||
the public domain by Dale Weiler, see:
|
|
||||||
<https://github.com/graphitemaster/incbin>
|
|
||||||
|
|
||||||
Anyone is free to copy, modify, publish, use, compile, sell, or
|
|
||||||
distribute this software, either in source code form or as a compiled
|
|
||||||
binary, for any purpose, commercial or non-commercial, and by any
|
|
||||||
means.
|
|
||||||
|
|
||||||
In jurisdictions that recognize copyright laws, the author or authors
|
|
||||||
of this software dedicate any and all copyright interest in the
|
|
||||||
software to the public domain. We make this dedication for the benefit
|
|
||||||
of the public at large and to the detriment of our heirs and
|
|
||||||
successors. We intend this dedication to be an overt act of
|
|
||||||
relinquishment in perpetuity of all present and future rights to this
|
|
||||||
software under copyright law.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
|
||||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
||||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
||||||
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
|
||||||
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
|
||||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
||||||
OTHER DEALINGS IN THE SOFTWARE.
|
|
||||||
|
|
||||||
For more information, please refer to <http://unlicense.org/>
|
|
||||||
@@ -1,368 +0,0 @@
|
|||||||
/**
|
|
||||||
* @file incbin.h
|
|
||||||
* @author Dale Weiler
|
|
||||||
* @brief Utility for including binary files
|
|
||||||
*
|
|
||||||
* Facilities for including binary files into the current translation unit
|
|
||||||
* and making use of them externally in other translation units.
|
|
||||||
*/
|
|
||||||
#ifndef INCBIN_HDR
|
|
||||||
#define INCBIN_HDR
|
|
||||||
#include <limits.h>
|
|
||||||
#if defined(__AVX512BW__) || \
|
|
||||||
defined(__AVX512CD__) || \
|
|
||||||
defined(__AVX512DQ__) || \
|
|
||||||
defined(__AVX512ER__) || \
|
|
||||||
defined(__AVX512PF__) || \
|
|
||||||
defined(__AVX512VL__) || \
|
|
||||||
defined(__AVX512F__)
|
|
||||||
# define INCBIN_ALIGNMENT_INDEX 6
|
|
||||||
#elif defined(__AVX__) || \
|
|
||||||
defined(__AVX2__)
|
|
||||||
# define INCBIN_ALIGNMENT_INDEX 5
|
|
||||||
#elif defined(__SSE__) || \
|
|
||||||
defined(__SSE2__) || \
|
|
||||||
defined(__SSE3__) || \
|
|
||||||
defined(__SSSE3__) || \
|
|
||||||
defined(__SSE4_1__) || \
|
|
||||||
defined(__SSE4_2__) || \
|
|
||||||
defined(__neon__)
|
|
||||||
# define INCBIN_ALIGNMENT_INDEX 4
|
|
||||||
#elif ULONG_MAX != 0xffffffffu
|
|
||||||
# define INCBIN_ALIGNMENT_INDEX 3
|
|
||||||
# else
|
|
||||||
# define INCBIN_ALIGNMENT_INDEX 2
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* Lookup table of (1 << n) where `n' is `INCBIN_ALIGNMENT_INDEX' */
|
|
||||||
#define INCBIN_ALIGN_SHIFT_0 1
|
|
||||||
#define INCBIN_ALIGN_SHIFT_1 2
|
|
||||||
#define INCBIN_ALIGN_SHIFT_2 4
|
|
||||||
#define INCBIN_ALIGN_SHIFT_3 8
|
|
||||||
#define INCBIN_ALIGN_SHIFT_4 16
|
|
||||||
#define INCBIN_ALIGN_SHIFT_5 32
|
|
||||||
#define INCBIN_ALIGN_SHIFT_6 64
|
|
||||||
|
|
||||||
/* Actual alignment value */
|
|
||||||
#define INCBIN_ALIGNMENT \
|
|
||||||
INCBIN_CONCATENATE( \
|
|
||||||
INCBIN_CONCATENATE(INCBIN_ALIGN_SHIFT, _), \
|
|
||||||
INCBIN_ALIGNMENT_INDEX)
|
|
||||||
|
|
||||||
/* Stringize */
|
|
||||||
#define INCBIN_STR(X) \
|
|
||||||
#X
|
|
||||||
#define INCBIN_STRINGIZE(X) \
|
|
||||||
INCBIN_STR(X)
|
|
||||||
/* Concatenate */
|
|
||||||
#define INCBIN_CAT(X, Y) \
|
|
||||||
X ## Y
|
|
||||||
#define INCBIN_CONCATENATE(X, Y) \
|
|
||||||
INCBIN_CAT(X, Y)
|
|
||||||
/* Deferred macro expansion */
|
|
||||||
#define INCBIN_EVAL(X) \
|
|
||||||
X
|
|
||||||
#define INCBIN_INVOKE(N, ...) \
|
|
||||||
INCBIN_EVAL(N(__VA_ARGS__))
|
|
||||||
|
|
||||||
/* Green Hills uses a different directive for including binary data */
|
|
||||||
#if defined(__ghs__)
|
|
||||||
# if (__ghs_asm == 2)
|
|
||||||
# define INCBIN_MACRO ".file"
|
|
||||||
/* Or consider the ".myrawdata" entry in the ld file */
|
|
||||||
# else
|
|
||||||
# define INCBIN_MACRO "\tINCBIN"
|
|
||||||
# endif
|
|
||||||
#else
|
|
||||||
# define INCBIN_MACRO ".incbin"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef _MSC_VER
|
|
||||||
# define INCBIN_ALIGN \
|
|
||||||
__attribute__((aligned(INCBIN_ALIGNMENT)))
|
|
||||||
#else
|
|
||||||
# define INCBIN_ALIGN __declspec(align(INCBIN_ALIGNMENT))
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if defined(__arm__) || /* GNU C and RealView */ \
|
|
||||||
defined(__arm) || /* Diab */ \
|
|
||||||
defined(_ARM) /* ImageCraft */
|
|
||||||
# define INCBIN_ARM
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifdef __GNUC__
|
|
||||||
/* Utilize .balign where supported */
|
|
||||||
# define INCBIN_ALIGN_HOST ".balign " INCBIN_STRINGIZE(INCBIN_ALIGNMENT) "\n"
|
|
||||||
# define INCBIN_ALIGN_BYTE ".balign 1\n"
|
|
||||||
#elif defined(INCBIN_ARM)
|
|
||||||
/*
|
|
||||||
* On arm assemblers, the alignment value is calculated as (1 << n) where `n' is
|
|
||||||
* the shift count. This is the value passed to `.align'
|
|
||||||
*/
|
|
||||||
# define INCBIN_ALIGN_HOST ".align " INCBIN_STRINGIZE(INCBIN_ALIGNMENT_INDEX) "\n"
|
|
||||||
# define INCBIN_ALIGN_BYTE ".align 0\n"
|
|
||||||
#else
|
|
||||||
/* We assume other inline assembler's treat `.align' as `.balign' */
|
|
||||||
# define INCBIN_ALIGN_HOST ".align " INCBIN_STRINGIZE(INCBIN_ALIGNMENT) "\n"
|
|
||||||
# define INCBIN_ALIGN_BYTE ".align 1\n"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* INCBIN_CONST is used by incbin.c generated files */
|
|
||||||
#if defined(__cplusplus)
|
|
||||||
# define INCBIN_EXTERNAL extern "C"
|
|
||||||
# define INCBIN_CONST extern const
|
|
||||||
#else
|
|
||||||
# define INCBIN_EXTERNAL extern
|
|
||||||
# define INCBIN_CONST const
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Optionally override the linker section into which data is emitted.
|
|
||||||
*
|
|
||||||
* @warning If you use this facility, you'll have to deal with platform-specific linker output
|
|
||||||
* section naming on your own
|
|
||||||
*
|
|
||||||
* Overriding the default linker output section, e.g for esp8266/Arduino:
|
|
||||||
* @code
|
|
||||||
* #define INCBIN_OUTPUT_SECTION ".irom.text"
|
|
||||||
* #include "incbin.h"
|
|
||||||
* INCBIN(Foo, "foo.txt");
|
|
||||||
* // Data is emitted into program memory that never gets copied to RAM
|
|
||||||
* @endcode
|
|
||||||
*/
|
|
||||||
#if !defined(INCBIN_OUTPUT_SECTION)
|
|
||||||
# if defined(__APPLE__)
|
|
||||||
# define INCBIN_OUTPUT_SECTION ".const_data"
|
|
||||||
# else
|
|
||||||
# define INCBIN_OUTPUT_SECTION ".rodata"
|
|
||||||
# endif
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if defined(__APPLE__)
|
|
||||||
/* The directives are different for Apple-branded compilers */
|
|
||||||
# define INCBIN_SECTION INCBIN_OUTPUT_SECTION "\n"
|
|
||||||
# define INCBIN_GLOBAL(NAME) ".globl " INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME "\n"
|
|
||||||
# define INCBIN_INT ".long "
|
|
||||||
# define INCBIN_MANGLE "_"
|
|
||||||
# define INCBIN_BYTE ".byte "
|
|
||||||
# define INCBIN_TYPE(...)
|
|
||||||
#else
|
|
||||||
# define INCBIN_SECTION ".section " INCBIN_OUTPUT_SECTION "\n"
|
|
||||||
# define INCBIN_GLOBAL(NAME) ".global " INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME "\n"
|
|
||||||
# if defined(__ghs__)
|
|
||||||
# define INCBIN_INT ".word "
|
|
||||||
# else
|
|
||||||
# define INCBIN_INT ".int "
|
|
||||||
# endif
|
|
||||||
# if defined(__USER_LABEL_PREFIX__)
|
|
||||||
# define INCBIN_MANGLE INCBIN_STRINGIZE(__USER_LABEL_PREFIX__)
|
|
||||||
# else
|
|
||||||
# define INCBIN_MANGLE ""
|
|
||||||
# endif
|
|
||||||
# if defined(INCBIN_ARM)
|
|
||||||
/* On arm assemblers, `@' is used as a line comment token */
|
|
||||||
# define INCBIN_TYPE(NAME) ".type " INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME ", %object\n"
|
|
||||||
# elif defined(__MINGW32__) || defined(__MINGW64__)
|
|
||||||
/* Mingw doesn't support this directive either */
|
|
||||||
# define INCBIN_TYPE(NAME)
|
|
||||||
# else
|
|
||||||
/* It's safe to use `@' on other architectures */
|
|
||||||
# define INCBIN_TYPE(NAME) ".type " INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME ", @object\n"
|
|
||||||
# endif
|
|
||||||
# define INCBIN_BYTE ".byte "
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* List of style types used for symbol names */
|
|
||||||
#define INCBIN_STYLE_CAMEL 0
|
|
||||||
#define INCBIN_STYLE_SNAKE 1
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Specify the prefix to use for symbol names.
|
|
||||||
*
|
|
||||||
* By default this is `g', producing symbols of the form:
|
|
||||||
* @code
|
|
||||||
* #include "incbin.h"
|
|
||||||
* INCBIN(Foo, "foo.txt");
|
|
||||||
*
|
|
||||||
* // Now you have the following symbols:
|
|
||||||
* // const unsigned char gFooData[];
|
|
||||||
* // const unsigned char *const gFooEnd;
|
|
||||||
* // const unsigned int gFooSize;
|
|
||||||
* @endcode
|
|
||||||
*
|
|
||||||
* If however you specify a prefix before including: e.g:
|
|
||||||
* @code
|
|
||||||
* #define INCBIN_PREFIX incbin
|
|
||||||
* #include "incbin.h"
|
|
||||||
* INCBIN(Foo, "foo.txt");
|
|
||||||
*
|
|
||||||
* // Now you have the following symbols instead:
|
|
||||||
* // const unsigned char incbinFooData[];
|
|
||||||
* // const unsigned char *const incbinFooEnd;
|
|
||||||
* // const unsigned int incbinFooSize;
|
|
||||||
* @endcode
|
|
||||||
*/
|
|
||||||
#if !defined(INCBIN_PREFIX)
|
|
||||||
# define INCBIN_PREFIX g
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Specify the style used for symbol names.
|
|
||||||
*
|
|
||||||
* Possible options are
|
|
||||||
* - INCBIN_STYLE_CAMEL "CamelCase"
|
|
||||||
* - INCBIN_STYLE_SNAKE "snake_case"
|
|
||||||
*
|
|
||||||
* Default option is *INCBIN_STYLE_CAMEL* producing symbols of the form:
|
|
||||||
* @code
|
|
||||||
* #include "incbin.h"
|
|
||||||
* INCBIN(Foo, "foo.txt");
|
|
||||||
*
|
|
||||||
* // Now you have the following symbols:
|
|
||||||
* // const unsigned char <prefix>FooData[];
|
|
||||||
* // const unsigned char *const <prefix>FooEnd;
|
|
||||||
* // const unsigned int <prefix>FooSize;
|
|
||||||
* @endcode
|
|
||||||
*
|
|
||||||
* If however you specify a style before including: e.g:
|
|
||||||
* @code
|
|
||||||
* #define INCBIN_STYLE INCBIN_STYLE_SNAKE
|
|
||||||
* #include "incbin.h"
|
|
||||||
* INCBIN(foo, "foo.txt");
|
|
||||||
*
|
|
||||||
* // Now you have the following symbols:
|
|
||||||
* // const unsigned char <prefix>foo_data[];
|
|
||||||
* // const unsigned char *const <prefix>foo_end;
|
|
||||||
* // const unsigned int <prefix>foo_size;
|
|
||||||
* @endcode
|
|
||||||
*/
|
|
||||||
#if !defined(INCBIN_STYLE)
|
|
||||||
# define INCBIN_STYLE INCBIN_STYLE_CAMEL
|
|
||||||
#endif
|
|
||||||
|
|
||||||
/* Style lookup tables */
|
|
||||||
#define INCBIN_STYLE_0_DATA Data
|
|
||||||
#define INCBIN_STYLE_0_END End
|
|
||||||
#define INCBIN_STYLE_0_SIZE Size
|
|
||||||
#define INCBIN_STYLE_1_DATA _data
|
|
||||||
#define INCBIN_STYLE_1_END _end
|
|
||||||
#define INCBIN_STYLE_1_SIZE _size
|
|
||||||
|
|
||||||
/* Style lookup: returning identifier */
|
|
||||||
#define INCBIN_STYLE_IDENT(TYPE) \
|
|
||||||
INCBIN_CONCATENATE( \
|
|
||||||
INCBIN_STYLE_, \
|
|
||||||
INCBIN_CONCATENATE( \
|
|
||||||
INCBIN_EVAL(INCBIN_STYLE), \
|
|
||||||
INCBIN_CONCATENATE(_, TYPE)))
|
|
||||||
|
|
||||||
/* Style lookup: returning string literal */
|
|
||||||
#define INCBIN_STYLE_STRING(TYPE) \
|
|
||||||
INCBIN_STRINGIZE( \
|
|
||||||
INCBIN_STYLE_IDENT(TYPE)) \
|
|
||||||
|
|
||||||
/* Generate the global labels by indirectly invoking the macro
|
|
||||||
* with our style type and concatenate the name against them. */
|
|
||||||
#define INCBIN_GLOBAL_LABELS(NAME, TYPE) \
|
|
||||||
INCBIN_INVOKE( \
|
|
||||||
INCBIN_GLOBAL, \
|
|
||||||
INCBIN_CONCATENATE( \
|
|
||||||
NAME, \
|
|
||||||
INCBIN_INVOKE( \
|
|
||||||
INCBIN_STYLE_IDENT, \
|
|
||||||
TYPE))) \
|
|
||||||
INCBIN_INVOKE( \
|
|
||||||
INCBIN_TYPE, \
|
|
||||||
INCBIN_CONCATENATE( \
|
|
||||||
NAME, \
|
|
||||||
INCBIN_INVOKE( \
|
|
||||||
INCBIN_STYLE_IDENT, \
|
|
||||||
TYPE)))
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Externally reference binary data included in another translation unit.
|
|
||||||
*
|
|
||||||
* Produces three external symbols that reference the binary data included in
|
|
||||||
* another translation unit.
|
|
||||||
*
|
|
||||||
* The symbol names are a concatenation of `INCBIN_PREFIX' before *NAME*; with
|
|
||||||
* "Data", as well as "End" and "Size" after. An example is provided below.
|
|
||||||
*
|
|
||||||
* @param NAME The name given for the binary data
|
|
||||||
*
|
|
||||||
* @code
|
|
||||||
* INCBIN_EXTERN(Foo);
|
|
||||||
*
|
|
||||||
* // Now you have the following symbols:
|
|
||||||
* // extern const unsigned char <prefix>FooData[];
|
|
||||||
* // extern const unsigned char *const <prefix>FooEnd;
|
|
||||||
* // extern const unsigned int <prefix>FooSize;
|
|
||||||
* @endcode
|
|
||||||
*/
|
|
||||||
#define INCBIN_EXTERN(NAME) \
|
|
||||||
INCBIN_EXTERNAL const INCBIN_ALIGN unsigned char \
|
|
||||||
INCBIN_CONCATENATE( \
|
|
||||||
INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
|
|
||||||
INCBIN_STYLE_IDENT(DATA))[]; \
|
|
||||||
INCBIN_EXTERNAL const INCBIN_ALIGN unsigned char *const \
|
|
||||||
INCBIN_CONCATENATE( \
|
|
||||||
INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
|
|
||||||
INCBIN_STYLE_IDENT(END)); \
|
|
||||||
INCBIN_EXTERNAL const unsigned int \
|
|
||||||
INCBIN_CONCATENATE( \
|
|
||||||
INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
|
|
||||||
INCBIN_STYLE_IDENT(SIZE))
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @brief Include a binary file into the current translation unit.
|
|
||||||
*
|
|
||||||
* Includes a binary file into the current translation unit, producing three symbols
|
|
||||||
* for objects that encode the data and size respectively.
|
|
||||||
*
|
|
||||||
* The symbol names are a concatenation of `INCBIN_PREFIX' before *NAME*; with
|
|
||||||
* "Data", as well as "End" and "Size" after. An example is provided below.
|
|
||||||
*
|
|
||||||
* @param NAME The name to associate with this binary data (as an identifier.)
|
|
||||||
* @param FILENAME The file to include (as a string literal.)
|
|
||||||
*
|
|
||||||
* @code
|
|
||||||
* INCBIN(Icon, "icon.png");
|
|
||||||
*
|
|
||||||
* // Now you have the following symbols:
|
|
||||||
* // const unsigned char <prefix>IconData[];
|
|
||||||
* // const unsigned char *const <prefix>IconEnd;
|
|
||||||
* // const unsigned int <prefix>IconSize;
|
|
||||||
* @endcode
|
|
||||||
*
|
|
||||||
* @warning This must be used in global scope
|
|
||||||
* @warning The identifiers may be different if INCBIN_STYLE is not default
|
|
||||||
*
|
|
||||||
* To externally reference the data included by this in another translation unit
|
|
||||||
* please @see INCBIN_EXTERN.
|
|
||||||
*/
|
|
||||||
#ifdef _MSC_VER
|
|
||||||
#define INCBIN(NAME, FILENAME) \
|
|
||||||
INCBIN_EXTERN(NAME)
|
|
||||||
#else
|
|
||||||
#define INCBIN(NAME, FILENAME) \
|
|
||||||
__asm__(INCBIN_SECTION \
|
|
||||||
INCBIN_GLOBAL_LABELS(NAME, DATA) \
|
|
||||||
INCBIN_ALIGN_HOST \
|
|
||||||
INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(DATA) ":\n" \
|
|
||||||
INCBIN_MACRO " \"" FILENAME "\"\n" \
|
|
||||||
INCBIN_GLOBAL_LABELS(NAME, END) \
|
|
||||||
INCBIN_ALIGN_BYTE \
|
|
||||||
INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(END) ":\n" \
|
|
||||||
INCBIN_BYTE "1\n" \
|
|
||||||
INCBIN_GLOBAL_LABELS(NAME, SIZE) \
|
|
||||||
INCBIN_ALIGN_HOST \
|
|
||||||
INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(SIZE) ":\n" \
|
|
||||||
INCBIN_INT INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(END) " - " \
|
|
||||||
INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(DATA) "\n" \
|
|
||||||
INCBIN_ALIGN_HOST \
|
|
||||||
".text\n" \
|
|
||||||
); \
|
|
||||||
INCBIN_EXTERN(NAME)
|
|
||||||
|
|
||||||
#endif
|
|
||||||
#endif
|
|
||||||
+103
@@ -0,0 +1,103 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
// x86 assembly language locks or OS spin locks may perform faster than
|
||||||
|
// mutex locks on some platforms. On my machine, mutexes seem to be the
|
||||||
|
// best.
|
||||||
|
|
||||||
|
//#define ASM_LOCK
|
||||||
|
//#define OS_SPIN_LOCK
|
||||||
|
|
||||||
|
|
||||||
|
#if defined(ASM_LOCK)
|
||||||
|
|
||||||
|
|
||||||
|
typedef volatile int Lock;
|
||||||
|
|
||||||
|
static inline void LockX86(Lock *lock) {
|
||||||
|
int dummy;
|
||||||
|
asm __volatile__("1: movl $1, %0" "\n\t"
|
||||||
|
" xchgl (%1), %0" "\n\t" " testl %0, %0" "\n\t"
|
||||||
|
" jz 3f" "\n\t" "2: pause" "\n\t"
|
||||||
|
" movl (%1), %0" "\n\t" " testl %0, %0" "\n\t"
|
||||||
|
" jnz 2b" "\n\t" " jmp 1b" "\n\t" "3:"
|
||||||
|
"\n\t":"=&q"(dummy)
|
||||||
|
:"q"(lock)
|
||||||
|
:"cc");
|
||||||
|
}
|
||||||
|
|
||||||
|
static inline void UnlockX86(Lock *lock) {
|
||||||
|
int dummy;
|
||||||
|
asm __volatile__("movl $0, (%1)":"=&q"(dummy)
|
||||||
|
:"q"(lock));
|
||||||
|
}
|
||||||
|
|
||||||
|
# define lock_init(x, y) (*(x) = 0)
|
||||||
|
# define lock_grab(x) LockX86(x)
|
||||||
|
# define lock_release(x) UnlockX86(x)
|
||||||
|
# define lock_destroy(x)
|
||||||
|
|
||||||
|
|
||||||
|
#elif defined(OS_SPIN_LOCK)
|
||||||
|
|
||||||
|
|
||||||
|
# include <libkern/OSAtomic.h>
|
||||||
|
|
||||||
|
typedef OSSpinLock Lock;
|
||||||
|
|
||||||
|
# define lock_init(x, y) (*(x) = 0)
|
||||||
|
# define lock_grab(x) OSSpinLockLock(x)
|
||||||
|
# define lock_release(x) OSSpinLockUnlock(x)
|
||||||
|
# define lock_destroy(x)
|
||||||
|
|
||||||
|
|
||||||
|
#elif !defined(_MSC_VER)
|
||||||
|
|
||||||
|
# include <pthread.h>
|
||||||
|
|
||||||
|
typedef pthread_mutex_t Lock;
|
||||||
|
|
||||||
|
# define lock_init(x, y) pthread_mutex_init(x, y)
|
||||||
|
# define lock_grab(x) pthread_mutex_lock(x)
|
||||||
|
# define lock_release(x) pthread_mutex_unlock(x)
|
||||||
|
# define lock_destroy(x) pthread_mutex_destroy(x)
|
||||||
|
|
||||||
|
|
||||||
|
#else
|
||||||
|
|
||||||
|
#define WIN32_LEAN_AND_MEAN
|
||||||
|
#include <windows.h>
|
||||||
|
#undef WIN32_LEAN_AND_MEAN
|
||||||
|
|
||||||
|
typedef CRITICAL_SECTION Lock;
|
||||||
|
# define lock_init(x, y) InitializeCriticalSection(x)
|
||||||
|
# define lock_grab(x) EnterCriticalSection(x)
|
||||||
|
# define lock_release(x) LeaveCriticalSection(x)
|
||||||
|
# define lock_destroy(x) DeleteCriticalSection(x)
|
||||||
|
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
#endif // !defined(LOCK_H_INCLUDED)
|
||||||
+59
-14
@@ -1,6 +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-2024 The Stockfish developers (see AUTHORS file)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
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
|
||||||
@@ -16,29 +17,73 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
// To profile with callgrind uncomment following line
|
||||||
|
//#define USE_CALLGRIND
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
#include "bitboard.h"
|
#include "benchmark.h"
|
||||||
|
#include "bitcount.h"
|
||||||
#include "misc.h"
|
#include "misc.h"
|
||||||
#include "position.h"
|
|
||||||
#include "types.h"
|
|
||||||
#include "uci.h"
|
#include "uci.h"
|
||||||
#include "tune.h"
|
|
||||||
|
|
||||||
using namespace Stockfish;
|
#ifdef USE_CALLGRIND
|
||||||
|
#include <valgrind/callgrind.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
int main(int argc, char* argv[]) {
|
using namespace std;
|
||||||
|
|
||||||
std::cout << engine_info() << std::endl;
|
|
||||||
|
|
||||||
Bitboards::init();
|
////
|
||||||
Position::init();
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
UCIEngine uci(argc, argv);
|
int main(int argc, char *argv[]) {
|
||||||
|
|
||||||
Tune::init(uci.engine_options());
|
// Disable IO buffering
|
||||||
|
cout.rdbuf()->pubsetbuf(NULL, 0);
|
||||||
|
cin.rdbuf()->pubsetbuf(NULL, 0);
|
||||||
|
|
||||||
uci.loop();
|
// Initialization through global resources manager
|
||||||
|
Application::initialize();
|
||||||
|
|
||||||
return 0;
|
#ifdef USE_CALLGRIND
|
||||||
|
CALLGRIND_START_INSTRUMENTATION;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Process command line arguments if any
|
||||||
|
if (argc > 1)
|
||||||
|
{
|
||||||
|
if (string(argv[1]) != "bench" || argc < 4 || argc > 8)
|
||||||
|
cout << "Usage: stockfish bench <hash size> <threads> "
|
||||||
|
<< "[time = 60s] [fen positions file = default] "
|
||||||
|
<< "[time, depth, perft or node limited = time] "
|
||||||
|
<< "[timing file name = none]" << endl;
|
||||||
|
else
|
||||||
|
{
|
||||||
|
string time = argc > 4 ? argv[4] : "60";
|
||||||
|
string fen = argc > 5 ? argv[5] : "default";
|
||||||
|
string lim = argc > 6 ? argv[6] : "time";
|
||||||
|
string tim = argc > 7 ? argv[7] : "";
|
||||||
|
benchmark(string(argv[2]) + " " + string(argv[3]) + " " + time + " " + fen + " " + lim + " " + tim);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Print copyright notice
|
||||||
|
cout << engine_name()
|
||||||
|
<< ". By Tord Romstad, Marco Costalba, Joona Kiiski." << endl;
|
||||||
|
|
||||||
|
if (CpuHasPOPCNT)
|
||||||
|
cout << "Good! CPU has hardware POPCNT. We will use it." << endl;
|
||||||
|
|
||||||
|
// Enter UCI mode
|
||||||
|
uci_main_loop();
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,430 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include <cassert>
|
||||||
|
#include <sstream>
|
||||||
|
#include <map>
|
||||||
|
|
||||||
|
#include "material.h"
|
||||||
|
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Local definitions
|
||||||
|
////
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
// Values modified by Joona Kiiski
|
||||||
|
const Value MidgameLimit = Value(15581);
|
||||||
|
const Value EndgameLimit = Value(3998);
|
||||||
|
|
||||||
|
// Polynomial material balance parameters
|
||||||
|
const Value RedundantQueenPenalty = Value(320);
|
||||||
|
const Value RedundantRookPenalty = Value(554);
|
||||||
|
|
||||||
|
const int LinearCoefficients[6] = { 1617, -162, -1172, -190, 105, 26 };
|
||||||
|
|
||||||
|
const int QuadraticCoefficientsSameColor[][6] = {
|
||||||
|
{ 7, 7, 7, 7, 7, 7 }, { 39, 2, 7, 7, 7, 7 }, { 35, 271, -4, 7, 7, 7 },
|
||||||
|
{ 7, 25, 4, 7, 7, 7 }, { -27, -2, 46, 100, 56, 7 }, { 58, 29, 83, 148, -3, -25 } };
|
||||||
|
|
||||||
|
const int QuadraticCoefficientsOppositeColor[][6] = {
|
||||||
|
{ 41, 41, 41, 41, 41, 41 }, { 37, 41, 41, 41, 41, 41 }, { 10, 62, 41, 41, 41, 41 },
|
||||||
|
{ 57, 64, 39, 41, 41, 41 }, { 50, 40, 23, -22, 41, 41 }, { 106, 101, 3, 151, 171, 41 } };
|
||||||
|
|
||||||
|
// Named endgame evaluation and scaling functions, these
|
||||||
|
// are accessed direcly and not through the function maps.
|
||||||
|
EvaluationFunction<KmmKm> EvaluateKmmKm(WHITE);
|
||||||
|
EvaluationFunction<KXK> EvaluateKXK(WHITE), EvaluateKKX(BLACK);
|
||||||
|
ScalingFunction<KBPsK> ScaleKBPsK(WHITE), ScaleKKBPs(BLACK);
|
||||||
|
ScalingFunction<KQKRPs> ScaleKQKRPs(WHITE), ScaleKRPsKQ(BLACK);
|
||||||
|
ScalingFunction<KPsK> ScaleKPsK(WHITE), ScaleKKPs(BLACK);
|
||||||
|
ScalingFunction<KPKP> ScaleKPKPw(WHITE), ScaleKPKPb(BLACK);
|
||||||
|
|
||||||
|
typedef EndgameEvaluationFunctionBase EF;
|
||||||
|
typedef EndgameScalingFunctionBase SF;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Classes
|
||||||
|
////
|
||||||
|
|
||||||
|
/// EndgameFunctions class stores endgame evaluation and scaling functions
|
||||||
|
/// in two std::map. Because STL library is not guaranteed to be thread
|
||||||
|
/// safe even for read access, the maps, although with identical content,
|
||||||
|
/// are replicated for each thread. This is faster then using locks.
|
||||||
|
|
||||||
|
class EndgameFunctions {
|
||||||
|
public:
|
||||||
|
EndgameFunctions();
|
||||||
|
~EndgameFunctions();
|
||||||
|
template<class T> T* get(Key key) const;
|
||||||
|
|
||||||
|
private:
|
||||||
|
template<class T> void add(const string& keyCode);
|
||||||
|
|
||||||
|
static Key buildKey(const string& keyCode);
|
||||||
|
static const string swapColors(const string& keyCode);
|
||||||
|
|
||||||
|
// Here we store two maps, for evaluate and scaling functions
|
||||||
|
pair<map<Key, EF*>, map<Key, SF*> > maps;
|
||||||
|
|
||||||
|
// Maps accessing functions returning const and non-const references
|
||||||
|
template<typename T> const map<Key, T*>& get() const { return maps.first; }
|
||||||
|
template<typename T> map<Key, T*>& get() { return maps.first; }
|
||||||
|
};
|
||||||
|
|
||||||
|
// Explicit specializations of a member function shall be declared in
|
||||||
|
// the namespace of which the class template is a member.
|
||||||
|
template<> const map<Key, SF*>&
|
||||||
|
EndgameFunctions::get<SF>() const { return maps.second; }
|
||||||
|
|
||||||
|
template<> map<Key, SF*>&
|
||||||
|
EndgameFunctions::get<SF>() { return maps.second; }
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
|
/// MaterialInfoTable c'tor and d'tor, called once by each thread
|
||||||
|
|
||||||
|
MaterialInfoTable::MaterialInfoTable(unsigned int numOfEntries) {
|
||||||
|
|
||||||
|
size = numOfEntries;
|
||||||
|
entries = new MaterialInfo[size];
|
||||||
|
funcs = new EndgameFunctions();
|
||||||
|
|
||||||
|
if (!entries || !funcs)
|
||||||
|
{
|
||||||
|
cerr << "Failed to allocate " << numOfEntries * sizeof(MaterialInfo)
|
||||||
|
<< " bytes for material hash table." << endl;
|
||||||
|
Application::exit_with_failure();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
MaterialInfoTable::~MaterialInfoTable() {
|
||||||
|
|
||||||
|
delete funcs;
|
||||||
|
delete [] entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// MaterialInfoTable::game_phase() calculates the phase given the current
|
||||||
|
/// position. Because the phase is strictly a function of the material, it
|
||||||
|
/// is stored in MaterialInfo.
|
||||||
|
|
||||||
|
Phase MaterialInfoTable::game_phase(const Position& pos) {
|
||||||
|
|
||||||
|
Value npm = pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK);
|
||||||
|
|
||||||
|
if (npm >= MidgameLimit)
|
||||||
|
return PHASE_MIDGAME;
|
||||||
|
else if (npm <= EndgameLimit)
|
||||||
|
return PHASE_ENDGAME;
|
||||||
|
|
||||||
|
return Phase(((npm - EndgameLimit) * 128) / (MidgameLimit - EndgameLimit));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// MaterialInfoTable::get_material_info() takes a position object as input,
|
||||||
|
/// computes or looks up a MaterialInfo object, and returns a pointer to it.
|
||||||
|
/// If the material configuration is not already present in the table, it
|
||||||
|
/// is stored there, so we don't have to recompute everything when the
|
||||||
|
/// same material configuration occurs again.
|
||||||
|
|
||||||
|
MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
|
||||||
|
|
||||||
|
Key key = pos.get_material_key();
|
||||||
|
int index = key & (size - 1);
|
||||||
|
MaterialInfo* mi = entries + index;
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
|
||||||
|
// Clear the MaterialInfo object, and set its key
|
||||||
|
mi->clear();
|
||||||
|
mi->key = key;
|
||||||
|
|
||||||
|
// 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<EF>(key)) != NULL)
|
||||||
|
return mi;
|
||||||
|
|
||||||
|
else if ( pos.non_pawn_material(BLACK) == Value(0)
|
||||||
|
&& pos.piece_count(BLACK, PAWN) == 0
|
||||||
|
&& pos.non_pawn_material(WHITE) >= RookValueMidgame)
|
||||||
|
{
|
||||||
|
mi->evaluationFunction = &EvaluateKXK;
|
||||||
|
return mi;
|
||||||
|
}
|
||||||
|
else if ( pos.non_pawn_material(WHITE) == Value(0)
|
||||||
|
&& pos.piece_count(WHITE, PAWN) == 0
|
||||||
|
&& pos.non_pawn_material(BLACK) >= RookValueMidgame)
|
||||||
|
{
|
||||||
|
mi->evaluationFunction = &EvaluateKKX;
|
||||||
|
return mi;
|
||||||
|
}
|
||||||
|
else if ( pos.pieces(PAWN) == EmptyBoardBB
|
||||||
|
&& pos.pieces(ROOK) == EmptyBoardBB
|
||||||
|
&& pos.pieces(QUEEN) == EmptyBoardBB)
|
||||||
|
{
|
||||||
|
// 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;
|
||||||
|
return mi;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// OK, we didn't find any special evaluation function for the current
|
||||||
|
// material configuration. Is there a suitable scaling function?
|
||||||
|
//
|
||||||
|
// The code below is rather messy, and it could easily get worse later,
|
||||||
|
// if we decide to add more special cases. We face problems when there
|
||||||
|
// are several conflicting applicable scaling functions and we need to
|
||||||
|
// decide which one to use.
|
||||||
|
SF* sf;
|
||||||
|
|
||||||
|
if ((sf = funcs->get<SF>(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 ( pos.non_pawn_material(WHITE) == BishopValueMidgame
|
||||||
|
&& pos.piece_count(WHITE, BISHOP) == 1
|
||||||
|
&& pos.piece_count(WHITE, PAWN) >= 1)
|
||||||
|
mi->scalingFunction[WHITE] = &ScaleKBPsK;
|
||||||
|
|
||||||
|
if ( pos.non_pawn_material(BLACK) == BishopValueMidgame
|
||||||
|
&& pos.piece_count(BLACK, BISHOP) == 1
|
||||||
|
&& pos.piece_count(BLACK, PAWN) >= 1)
|
||||||
|
mi->scalingFunction[BLACK] = &ScaleKKBPs;
|
||||||
|
|
||||||
|
if ( pos.piece_count(WHITE, PAWN) == 0
|
||||||
|
&& pos.non_pawn_material(WHITE) == QueenValueMidgame
|
||||||
|
&& pos.piece_count(WHITE, QUEEN) == 1
|
||||||
|
&& pos.piece_count(BLACK, ROOK) == 1
|
||||||
|
&& pos.piece_count(BLACK, PAWN) >= 1)
|
||||||
|
mi->scalingFunction[WHITE] = &ScaleKQKRPs;
|
||||||
|
|
||||||
|
else if ( pos.piece_count(BLACK, PAWN) == 0
|
||||||
|
&& pos.non_pawn_material(BLACK) == QueenValueMidgame
|
||||||
|
&& pos.piece_count(BLACK, QUEEN) == 1
|
||||||
|
&& pos.piece_count(WHITE, ROOK) == 1
|
||||||
|
&& pos.piece_count(WHITE, PAWN) >= 1)
|
||||||
|
mi->scalingFunction[BLACK] = &ScaleKRPsKQ;
|
||||||
|
|
||||||
|
if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) == Value(0))
|
||||||
|
{
|
||||||
|
if (pos.piece_count(BLACK, PAWN) == 0)
|
||||||
|
{
|
||||||
|
assert(pos.piece_count(WHITE, PAWN) >= 2);
|
||||||
|
mi->scalingFunction[WHITE] = &ScaleKPsK;
|
||||||
|
}
|
||||||
|
else if (pos.piece_count(WHITE, PAWN) == 0)
|
||||||
|
{
|
||||||
|
assert(pos.piece_count(BLACK, PAWN) >= 2);
|
||||||
|
mi->scalingFunction[BLACK] = &ScaleKKPs;
|
||||||
|
}
|
||||||
|
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] = &ScaleKPKPw;
|
||||||
|
mi->scalingFunction[BLACK] = &ScaleKPKPb;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Compute the space weight
|
||||||
|
if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) >=
|
||||||
|
2*QueenValueMidgame + 4*RookValueMidgame + 2*KnightValueMidgame)
|
||||||
|
{
|
||||||
|
int minorPieceCount = pos.piece_count(WHITE, KNIGHT)
|
||||||
|
+ pos.piece_count(BLACK, KNIGHT)
|
||||||
|
+ pos.piece_count(WHITE, BISHOP)
|
||||||
|
+ pos.piece_count(BLACK, BISHOP);
|
||||||
|
|
||||||
|
mi->spaceWeight = minorPieceCount * minorPieceCount;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Evaluate the material balance
|
||||||
|
const int pieceCount[2][6] = { { 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) } };
|
||||||
|
Color c, them;
|
||||||
|
int sign, pt1, pt2, pc;
|
||||||
|
int v, vv, matValue = 0;
|
||||||
|
|
||||||
|
for (c = WHITE, sign = 1; c <= BLACK; c++, sign = -sign)
|
||||||
|
{
|
||||||
|
// No pawns makes it difficult to win, even with a material advantage
|
||||||
|
if ( pos.piece_count(c, PAWN) == 0
|
||||||
|
&& pos.non_pawn_material(c) - pos.non_pawn_material(opposite_color(c)) <= BishopValueMidgame)
|
||||||
|
{
|
||||||
|
if ( pos.non_pawn_material(c) == pos.non_pawn_material(opposite_color(c))
|
||||||
|
|| pos.non_pawn_material(c) < RookValueMidgame)
|
||||||
|
mi->factor[c] = 0;
|
||||||
|
else
|
||||||
|
{
|
||||||
|
switch (pos.piece_count(c, BISHOP)) {
|
||||||
|
case 2:
|
||||||
|
mi->factor[c] = 32;
|
||||||
|
break;
|
||||||
|
case 1:
|
||||||
|
mi->factor[c] = 12;
|
||||||
|
break;
|
||||||
|
case 0:
|
||||||
|
mi->factor[c] = 6;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Redundancy of major pieces, formula based on Kaufman's paper
|
||||||
|
// "The Evaluation of Material Imbalances in Chess"
|
||||||
|
// http://mywebpages.comcast.net/danheisman/Articles/evaluation_of_material_imbalance.htm
|
||||||
|
if (pieceCount[c][ROOK] >= 1)
|
||||||
|
matValue -= sign * ((pieceCount[c][ROOK] - 1) * RedundantRookPenalty + pieceCount[c][QUEEN] * RedundantQueenPenalty);
|
||||||
|
|
||||||
|
them = opposite_color(c);
|
||||||
|
v = 0;
|
||||||
|
|
||||||
|
// Second-degree polynomial material imbalance by Tord Romstad
|
||||||
|
//
|
||||||
|
// We use NO_PIECE_TYPE as a place holder for the bishop pair "extended piece",
|
||||||
|
// this allow us to be more flexible in defining bishop pair bonuses.
|
||||||
|
for (pt1 = NO_PIECE_TYPE; pt1 <= QUEEN; pt1++)
|
||||||
|
{
|
||||||
|
pc = pieceCount[c][pt1];
|
||||||
|
if (!pc)
|
||||||
|
continue;
|
||||||
|
|
||||||
|
vv = LinearCoefficients[pt1];
|
||||||
|
|
||||||
|
for (pt2 = NO_PIECE_TYPE; pt2 <= pt1; pt2++)
|
||||||
|
vv += pieceCount[c][pt2] * QuadraticCoefficientsSameColor[pt1][pt2]
|
||||||
|
+ pieceCount[them][pt2] * QuadraticCoefficientsOppositeColor[pt1][pt2];
|
||||||
|
|
||||||
|
v += pc * vv;
|
||||||
|
}
|
||||||
|
matValue += sign * v;
|
||||||
|
}
|
||||||
|
mi->value = int16_t(matValue / 16);
|
||||||
|
return mi;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// EndgameFunctions member definitions.
|
||||||
|
|
||||||
|
EndgameFunctions::EndgameFunctions() {
|
||||||
|
|
||||||
|
add<EvaluationFunction<KNNK> >("KNNK");
|
||||||
|
add<EvaluationFunction<KPK> >("KPK");
|
||||||
|
add<EvaluationFunction<KBNK> >("KBNK");
|
||||||
|
add<EvaluationFunction<KRKP> >("KRKP");
|
||||||
|
add<EvaluationFunction<KRKB> >("KRKB");
|
||||||
|
add<EvaluationFunction<KRKN> >("KRKN");
|
||||||
|
add<EvaluationFunction<KQKR> >("KQKR");
|
||||||
|
add<EvaluationFunction<KBBKN> >("KBBKN");
|
||||||
|
|
||||||
|
add<ScalingFunction<KNPK> >("KNPK");
|
||||||
|
add<ScalingFunction<KRPKR> >("KRPKR");
|
||||||
|
add<ScalingFunction<KBPKB> >("KBPKB");
|
||||||
|
add<ScalingFunction<KBPPKB> >("KBPPKB");
|
||||||
|
add<ScalingFunction<KBPKN> >("KBPKN");
|
||||||
|
add<ScalingFunction<KRPPKRP> >("KRPPKRP");
|
||||||
|
}
|
||||||
|
|
||||||
|
EndgameFunctions::~EndgameFunctions() {
|
||||||
|
|
||||||
|
for (map<Key, EF*>::iterator it = maps.first.begin(); it != maps.first.end(); ++it)
|
||||||
|
delete (*it).second;
|
||||||
|
|
||||||
|
for (map<Key, SF*>::iterator it = maps.second.begin(); it != maps.second.end(); ++it)
|
||||||
|
delete (*it).second;
|
||||||
|
}
|
||||||
|
|
||||||
|
Key EndgameFunctions::buildKey(const string& keyCode) {
|
||||||
|
|
||||||
|
assert(keyCode.length() > 0 && keyCode[0] == 'K');
|
||||||
|
assert(keyCode.length() < 8);
|
||||||
|
|
||||||
|
stringstream s;
|
||||||
|
bool upcase = false;
|
||||||
|
|
||||||
|
// Build up a fen string with the given pieces, note that
|
||||||
|
// the fen string could be of an illegal position.
|
||||||
|
for (size_t i = 0; i < keyCode.length(); i++)
|
||||||
|
{
|
||||||
|
if (keyCode[i] == 'K')
|
||||||
|
upcase = !upcase;
|
||||||
|
|
||||||
|
s << char(upcase? toupper(keyCode[i]) : tolower(keyCode[i]));
|
||||||
|
}
|
||||||
|
s << 8 - keyCode.length() << "/8/8/8/8/8/8/8 w -";
|
||||||
|
return Position(s.str()).get_material_key();
|
||||||
|
}
|
||||||
|
|
||||||
|
const string EndgameFunctions::swapColors(const string& keyCode) {
|
||||||
|
|
||||||
|
// Build corresponding key for the opposite color: "KBPKN" -> "KNKBP"
|
||||||
|
size_t idx = keyCode.find("K", 1);
|
||||||
|
return keyCode.substr(idx) + keyCode.substr(0, idx);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class T>
|
||||||
|
void EndgameFunctions::add(const string& keyCode) {
|
||||||
|
|
||||||
|
typedef typename T::Base F;
|
||||||
|
|
||||||
|
get<F>().insert(pair<Key, F*>(buildKey(keyCode), new T(WHITE)));
|
||||||
|
get<F>().insert(pair<Key, F*>(buildKey(swapColors(keyCode)), new T(BLACK)));
|
||||||
|
}
|
||||||
|
|
||||||
|
template<class T>
|
||||||
|
T* EndgameFunctions::get(Key key) const {
|
||||||
|
|
||||||
|
typename map<Key, T*>::const_iterator it(get<T>().find(key));
|
||||||
|
return (it != get<T>().end() ? it->second : NULL);
|
||||||
|
}
|
||||||
+177
@@ -0,0 +1,177 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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(MATERIAL_H_INCLUDED)
|
||||||
|
#define MATERIAL_H_INCLUDED
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include "endgame.h"
|
||||||
|
#include "position.h"
|
||||||
|
#include "scale.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Types
|
||||||
|
////
|
||||||
|
|
||||||
|
/// 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.
|
||||||
|
/// For instance, in KRB vs KR endgames, the score is scaled down by a factor
|
||||||
|
/// of 4, which will result in scores of absolute value less than one pawn.
|
||||||
|
|
||||||
|
class MaterialInfo {
|
||||||
|
|
||||||
|
friend class MaterialInfoTable;
|
||||||
|
|
||||||
|
public:
|
||||||
|
MaterialInfo() : key(0) { clear(); }
|
||||||
|
|
||||||
|
Score material_value() 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:
|
||||||
|
inline void clear();
|
||||||
|
|
||||||
|
Key key;
|
||||||
|
int16_t value;
|
||||||
|
uint8_t factor[2];
|
||||||
|
EndgameEvaluationFunctionBase* evaluationFunction;
|
||||||
|
EndgameScalingFunctionBase* scalingFunction[2];
|
||||||
|
int spaceWeight;
|
||||||
|
Phase gamePhase;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The MaterialInfoTable class represents a pawn hash table. It is basically
|
||||||
|
/// just an array of MaterialInfo objects and a few methods for accessing these
|
||||||
|
/// objects. The most important method is get_material_info, which looks up a
|
||||||
|
/// position in the table and returns a pointer to a MaterialInfo object.
|
||||||
|
class EndgameFunctions;
|
||||||
|
|
||||||
|
class MaterialInfoTable {
|
||||||
|
|
||||||
|
public:
|
||||||
|
MaterialInfoTable(unsigned numOfEntries);
|
||||||
|
~MaterialInfoTable();
|
||||||
|
MaterialInfo* get_material_info(const Position& pos);
|
||||||
|
|
||||||
|
static Phase game_phase(const Position& pos);
|
||||||
|
|
||||||
|
private:
|
||||||
|
unsigned size;
|
||||||
|
MaterialInfo* entries;
|
||||||
|
EndgameFunctions* funcs;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Inline functions
|
||||||
|
////
|
||||||
|
|
||||||
|
|
||||||
|
/// MaterialInfo::material_value simply returns the material balance
|
||||||
|
/// evaluation that is independent from game phase.
|
||||||
|
|
||||||
|
inline Score MaterialInfo::material_value() const {
|
||||||
|
|
||||||
|
return make_score(value, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// MaterialInfo::clear() resets a MaterialInfo object to an empty state,
|
||||||
|
/// with all slots at their default values but the key.
|
||||||
|
|
||||||
|
inline void MaterialInfo::clear() {
|
||||||
|
|
||||||
|
value = 0;
|
||||||
|
factor[WHITE] = factor[BLACK] = uint8_t(SCALE_FACTOR_NORMAL);
|
||||||
|
evaluationFunction = NULL;
|
||||||
|
scalingFunction[WHITE] = scalingFunction[BLACK] = NULL;
|
||||||
|
spaceWeight = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// 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
|
||||||
|
/// position in addition to the color, because the scale factor need not
|
||||||
|
/// to be a constant: It can also be a function which should be applied to
|
||||||
|
/// the position. For instance, in KBP vs K endgames, a scaling function
|
||||||
|
/// which checks for draws with rook pawns and wrong-colored bishops.
|
||||||
|
|
||||||
|
inline ScaleFactor MaterialInfo::scale_factor(const Position& pos, Color c) const {
|
||||||
|
|
||||||
|
if (scalingFunction[c] != NULL)
|
||||||
|
{
|
||||||
|
ScaleFactor sf = scalingFunction[c]->apply(pos);
|
||||||
|
if (sf != SCALE_FACTOR_NONE)
|
||||||
|
return sf;
|
||||||
|
}
|
||||||
|
return ScaleFactor(factor[c]);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// MaterialInfo::space_weight() simply returns the weight for the space
|
||||||
|
/// evaluation for this material configuration.
|
||||||
|
|
||||||
|
inline int MaterialInfo::space_weight() const {
|
||||||
|
|
||||||
|
return spaceWeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// MaterialInfo::game_phase() returns the game phase according
|
||||||
|
/// to this material configuration.
|
||||||
|
|
||||||
|
inline Phase MaterialInfo::game_phase() const {
|
||||||
|
|
||||||
|
return gamePhase;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// MaterialInfo::specialized_eval_exists decides whether there is a
|
||||||
|
/// specialized evaluation function for the current material configuration,
|
||||||
|
/// or if the normal evaluation function should be used.
|
||||||
|
|
||||||
|
inline bool MaterialInfo::specialized_eval_exists() const {
|
||||||
|
|
||||||
|
return evaluationFunction != NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// MaterialInfo::evaluate applies a specialized evaluation function
|
||||||
|
/// to a given position object. It should only be called when
|
||||||
|
/// specialized_eval_exists() returns 'true'.
|
||||||
|
|
||||||
|
inline Value MaterialInfo::evaluate(const Position& pos) const {
|
||||||
|
|
||||||
|
return evaluationFunction->apply(pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif // !defined(MATERIAL_H_INCLUDED)
|
||||||
-237
@@ -1,237 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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 "memory.h"
|
|
||||||
|
|
||||||
#include <cstdlib>
|
|
||||||
|
|
||||||
#if __has_include("features.h")
|
|
||||||
#include <features.h>
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if defined(__linux__) && !defined(__ANDROID__)
|
|
||||||
#include <sys/mman.h>
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if defined(__APPLE__) || defined(__ANDROID__) || defined(__OpenBSD__) \
|
|
||||||
|| (defined(__GLIBCXX__) && !defined(_GLIBCXX_HAVE_ALIGNED_ALLOC) && !defined(_WIN32)) \
|
|
||||||
|| defined(__e2k__)
|
|
||||||
#define POSIXALIGNEDALLOC
|
|
||||||
#include <stdlib.h>
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifdef _WIN32
|
|
||||||
#if _WIN32_WINNT < 0x0601
|
|
||||||
#undef _WIN32_WINNT
|
|
||||||
#define _WIN32_WINNT 0x0601 // Force to include needed API prototypes
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef NOMINMAX
|
|
||||||
#define NOMINMAX
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#include <ios> // std::hex, std::dec
|
|
||||||
#include <iostream> // std::cerr
|
|
||||||
#include <ostream> // std::endl
|
|
||||||
#include <windows.h>
|
|
||||||
|
|
||||||
// The needed Windows API for processor groups could be missed from old Windows
|
|
||||||
// versions, so instead of calling them directly (forcing the linker to resolve
|
|
||||||
// the calls at compile time), try to load them at runtime. To do this we need
|
|
||||||
// first to define the corresponding function pointers.
|
|
||||||
|
|
||||||
extern "C" {
|
|
||||||
using OpenProcessToken_t = bool (*)(HANDLE, DWORD, PHANDLE);
|
|
||||||
using LookupPrivilegeValueA_t = bool (*)(LPCSTR, LPCSTR, PLUID);
|
|
||||||
using AdjustTokenPrivileges_t =
|
|
||||||
bool (*)(HANDLE, BOOL, PTOKEN_PRIVILEGES, DWORD, PTOKEN_PRIVILEGES, PDWORD);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
namespace Stockfish {
|
|
||||||
|
|
||||||
// Wrappers for systems where the c++17 implementation does not guarantee the
|
|
||||||
// availability of aligned_alloc(). Memory allocated with std_aligned_alloc()
|
|
||||||
// must be freed with std_aligned_free().
|
|
||||||
|
|
||||||
void* std_aligned_alloc(size_t alignment, size_t size) {
|
|
||||||
#if defined(_ISOC11_SOURCE)
|
|
||||||
return aligned_alloc(alignment, size);
|
|
||||||
#elif defined(POSIXALIGNEDALLOC)
|
|
||||||
void* mem = nullptr;
|
|
||||||
posix_memalign(&mem, alignment, size);
|
|
||||||
return mem;
|
|
||||||
#elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
|
|
||||||
return _mm_malloc(size, alignment);
|
|
||||||
#elif defined(_WIN32)
|
|
||||||
return _aligned_malloc(size, alignment);
|
|
||||||
#else
|
|
||||||
return std::aligned_alloc(alignment, size);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
void std_aligned_free(void* ptr) {
|
|
||||||
|
|
||||||
#if defined(POSIXALIGNEDALLOC)
|
|
||||||
free(ptr);
|
|
||||||
#elif defined(_WIN32) && !defined(_M_ARM) && !defined(_M_ARM64)
|
|
||||||
_mm_free(ptr);
|
|
||||||
#elif defined(_WIN32)
|
|
||||||
_aligned_free(ptr);
|
|
||||||
#else
|
|
||||||
free(ptr);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
// aligned_large_pages_alloc() will return suitably aligned memory,
|
|
||||||
// if possible using large pages.
|
|
||||||
|
|
||||||
#if defined(_WIN32)
|
|
||||||
|
|
||||||
static void* aligned_large_pages_alloc_windows([[maybe_unused]] size_t allocSize) {
|
|
||||||
|
|
||||||
#if !defined(_WIN64)
|
|
||||||
return nullptr;
|
|
||||||
#else
|
|
||||||
|
|
||||||
HANDLE hProcessToken{};
|
|
||||||
LUID luid{};
|
|
||||||
void* mem = nullptr;
|
|
||||||
|
|
||||||
const size_t largePageSize = GetLargePageMinimum();
|
|
||||||
if (!largePageSize)
|
|
||||||
return nullptr;
|
|
||||||
|
|
||||||
// Dynamically link OpenProcessToken, LookupPrivilegeValue and AdjustTokenPrivileges
|
|
||||||
|
|
||||||
HMODULE hAdvapi32 = GetModuleHandle(TEXT("advapi32.dll"));
|
|
||||||
|
|
||||||
if (!hAdvapi32)
|
|
||||||
hAdvapi32 = LoadLibrary(TEXT("advapi32.dll"));
|
|
||||||
|
|
||||||
auto OpenProcessToken_f =
|
|
||||||
OpenProcessToken_t((void (*)()) GetProcAddress(hAdvapi32, "OpenProcessToken"));
|
|
||||||
if (!OpenProcessToken_f)
|
|
||||||
return nullptr;
|
|
||||||
auto LookupPrivilegeValueA_f =
|
|
||||||
LookupPrivilegeValueA_t((void (*)()) GetProcAddress(hAdvapi32, "LookupPrivilegeValueA"));
|
|
||||||
if (!LookupPrivilegeValueA_f)
|
|
||||||
return nullptr;
|
|
||||||
auto AdjustTokenPrivileges_f =
|
|
||||||
AdjustTokenPrivileges_t((void (*)()) GetProcAddress(hAdvapi32, "AdjustTokenPrivileges"));
|
|
||||||
if (!AdjustTokenPrivileges_f)
|
|
||||||
return nullptr;
|
|
||||||
|
|
||||||
// We need SeLockMemoryPrivilege, so try to enable it for the process
|
|
||||||
|
|
||||||
if (!OpenProcessToken_f( // OpenProcessToken()
|
|
||||||
GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hProcessToken))
|
|
||||||
return nullptr;
|
|
||||||
|
|
||||||
if (LookupPrivilegeValueA_f(nullptr, "SeLockMemoryPrivilege", &luid))
|
|
||||||
{
|
|
||||||
TOKEN_PRIVILEGES tp{};
|
|
||||||
TOKEN_PRIVILEGES prevTp{};
|
|
||||||
DWORD prevTpLen = 0;
|
|
||||||
|
|
||||||
tp.PrivilegeCount = 1;
|
|
||||||
tp.Privileges[0].Luid = luid;
|
|
||||||
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
|
|
||||||
|
|
||||||
// Try to enable SeLockMemoryPrivilege. Note that even if AdjustTokenPrivileges()
|
|
||||||
// succeeds, we still need to query GetLastError() to ensure that the privileges
|
|
||||||
// were actually obtained.
|
|
||||||
|
|
||||||
if (AdjustTokenPrivileges_f(hProcessToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), &prevTp,
|
|
||||||
&prevTpLen)
|
|
||||||
&& GetLastError() == ERROR_SUCCESS)
|
|
||||||
{
|
|
||||||
// Round up size to full pages and allocate
|
|
||||||
allocSize = (allocSize + largePageSize - 1) & ~size_t(largePageSize - 1);
|
|
||||||
mem = VirtualAlloc(nullptr, allocSize, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES,
|
|
||||||
PAGE_READWRITE);
|
|
||||||
|
|
||||||
// Privilege no longer needed, restore previous state
|
|
||||||
AdjustTokenPrivileges_f(hProcessToken, FALSE, &prevTp, 0, nullptr, nullptr);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
CloseHandle(hProcessToken);
|
|
||||||
|
|
||||||
return mem;
|
|
||||||
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
void* aligned_large_pages_alloc(size_t allocSize) {
|
|
||||||
|
|
||||||
// Try to allocate large pages
|
|
||||||
void* mem = aligned_large_pages_alloc_windows(allocSize);
|
|
||||||
|
|
||||||
// Fall back to regular, page-aligned, allocation if necessary
|
|
||||||
if (!mem)
|
|
||||||
mem = VirtualAlloc(nullptr, allocSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
|
|
||||||
|
|
||||||
return mem;
|
|
||||||
}
|
|
||||||
|
|
||||||
#else
|
|
||||||
|
|
||||||
void* aligned_large_pages_alloc(size_t allocSize) {
|
|
||||||
|
|
||||||
#if defined(__linux__)
|
|
||||||
constexpr size_t alignment = 2 * 1024 * 1024; // 2MB page size assumed
|
|
||||||
#else
|
|
||||||
constexpr size_t alignment = 4096; // small page size assumed
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Round up to multiples of alignment
|
|
||||||
size_t size = ((allocSize + alignment - 1) / alignment) * alignment;
|
|
||||||
void* mem = std_aligned_alloc(alignment, size);
|
|
||||||
#if defined(MADV_HUGEPAGE)
|
|
||||||
madvise(mem, size, MADV_HUGEPAGE);
|
|
||||||
#endif
|
|
||||||
return mem;
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
// aligned_large_pages_free() will free the previously memory allocated
|
|
||||||
// by aligned_large_pages_alloc(). The effect is a nop if mem == nullptr.
|
|
||||||
|
|
||||||
#if defined(_WIN32)
|
|
||||||
|
|
||||||
void aligned_large_pages_free(void* mem) {
|
|
||||||
|
|
||||||
if (mem && !VirtualFree(mem, 0, MEM_RELEASE))
|
|
||||||
{
|
|
||||||
DWORD err = GetLastError();
|
|
||||||
std::cerr << "Failed to free large page memory. Error code: 0x" << std::hex << err
|
|
||||||
<< std::dec << std::endl;
|
|
||||||
exit(EXIT_FAILURE);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#else
|
|
||||||
|
|
||||||
void aligned_large_pages_free(void* mem) { std_aligned_free(mem); }
|
|
||||||
|
|
||||||
#endif
|
|
||||||
} // namespace Stockfish
|
|
||||||
-216
@@ -1,216 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef MEMORY_H_INCLUDED
|
|
||||||
#define MEMORY_H_INCLUDED
|
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <cstddef>
|
|
||||||
#include <cstdint>
|
|
||||||
#include <memory>
|
|
||||||
#include <new>
|
|
||||||
#include <type_traits>
|
|
||||||
#include <utility>
|
|
||||||
|
|
||||||
#include "types.h"
|
|
||||||
|
|
||||||
namespace Stockfish {
|
|
||||||
|
|
||||||
void* std_aligned_alloc(size_t alignment, size_t size);
|
|
||||||
void std_aligned_free(void* ptr);
|
|
||||||
|
|
||||||
// Memory aligned by page size, min alignment: 4096 bytes
|
|
||||||
void* aligned_large_pages_alloc(size_t size);
|
|
||||||
void aligned_large_pages_free(void* mem);
|
|
||||||
|
|
||||||
// Frees memory which was placed there with placement new.
|
|
||||||
// Works for both single objects and arrays of unknown bound.
|
|
||||||
template<typename T, typename FREE_FUNC>
|
|
||||||
void memory_deleter(T* ptr, FREE_FUNC free_func) {
|
|
||||||
if (!ptr)
|
|
||||||
return;
|
|
||||||
|
|
||||||
// Explicitly needed to call the destructor
|
|
||||||
if constexpr (!std::is_trivially_destructible_v<T>)
|
|
||||||
ptr->~T();
|
|
||||||
|
|
||||||
free_func(ptr);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Frees memory which was placed there with placement new.
|
|
||||||
// Works for both single objects and arrays of unknown bound.
|
|
||||||
template<typename T, typename FREE_FUNC>
|
|
||||||
void memory_deleter_array(T* ptr, FREE_FUNC free_func) {
|
|
||||||
if (!ptr)
|
|
||||||
return;
|
|
||||||
|
|
||||||
|
|
||||||
// Move back on the pointer to where the size is allocated
|
|
||||||
const size_t array_offset = std::max(sizeof(size_t), alignof(T));
|
|
||||||
char* raw_memory = reinterpret_cast<char*>(ptr) - array_offset;
|
|
||||||
|
|
||||||
if constexpr (!std::is_trivially_destructible_v<T>)
|
|
||||||
{
|
|
||||||
const size_t size = *reinterpret_cast<size_t*>(raw_memory);
|
|
||||||
|
|
||||||
// Explicitly call the destructor for each element in reverse order
|
|
||||||
for (size_t i = size; i-- > 0;)
|
|
||||||
ptr[i].~T();
|
|
||||||
}
|
|
||||||
|
|
||||||
free_func(raw_memory);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Allocates memory for a single object and places it there with placement new
|
|
||||||
template<typename T, typename ALLOC_FUNC, typename... Args>
|
|
||||||
inline std::enable_if_t<!std::is_array_v<T>, T*> memory_allocator(ALLOC_FUNC alloc_func,
|
|
||||||
Args&&... args) {
|
|
||||||
void* raw_memory = alloc_func(sizeof(T));
|
|
||||||
ASSERT_ALIGNED(raw_memory, alignof(T));
|
|
||||||
return new (raw_memory) T(std::forward<Args>(args)...);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Allocates memory for an array of unknown bound and places it there with placement new
|
|
||||||
template<typename T, typename ALLOC_FUNC>
|
|
||||||
inline std::enable_if_t<std::is_array_v<T>, std::remove_extent_t<T>*>
|
|
||||||
memory_allocator(ALLOC_FUNC alloc_func, size_t num) {
|
|
||||||
using ElementType = std::remove_extent_t<T>;
|
|
||||||
|
|
||||||
const size_t array_offset = std::max(sizeof(size_t), alignof(ElementType));
|
|
||||||
|
|
||||||
// Save the array size in the memory location
|
|
||||||
char* raw_memory =
|
|
||||||
reinterpret_cast<char*>(alloc_func(array_offset + num * sizeof(ElementType)));
|
|
||||||
ASSERT_ALIGNED(raw_memory, alignof(T));
|
|
||||||
|
|
||||||
new (raw_memory) size_t(num);
|
|
||||||
|
|
||||||
for (size_t i = 0; i < num; ++i)
|
|
||||||
new (raw_memory + array_offset + i * sizeof(ElementType)) ElementType();
|
|
||||||
|
|
||||||
// Need to return the pointer at the start of the array so that
|
|
||||||
// the indexing in unique_ptr<T[]> works.
|
|
||||||
return reinterpret_cast<ElementType*>(raw_memory + array_offset);
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
//
|
|
||||||
// aligned large page unique ptr
|
|
||||||
//
|
|
||||||
//
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
struct LargePageDeleter {
|
|
||||||
void operator()(T* ptr) const { return memory_deleter<T>(ptr, aligned_large_pages_free); }
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
struct LargePageArrayDeleter {
|
|
||||||
void operator()(T* ptr) const { return memory_deleter_array<T>(ptr, aligned_large_pages_free); }
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
using LargePagePtr =
|
|
||||||
std::conditional_t<std::is_array_v<T>,
|
|
||||||
std::unique_ptr<T, LargePageArrayDeleter<std::remove_extent_t<T>>>,
|
|
||||||
std::unique_ptr<T, LargePageDeleter<T>>>;
|
|
||||||
|
|
||||||
// make_unique_large_page for single objects
|
|
||||||
template<typename T, typename... Args>
|
|
||||||
std::enable_if_t<!std::is_array_v<T>, LargePagePtr<T>> make_unique_large_page(Args&&... args) {
|
|
||||||
static_assert(alignof(T) <= 4096,
|
|
||||||
"aligned_large_pages_alloc() may fail for such a big alignment requirement of T");
|
|
||||||
|
|
||||||
T* obj = memory_allocator<T>(aligned_large_pages_alloc, std::forward<Args>(args)...);
|
|
||||||
|
|
||||||
return LargePagePtr<T>(obj);
|
|
||||||
}
|
|
||||||
|
|
||||||
// make_unique_large_page for arrays of unknown bound
|
|
||||||
template<typename T>
|
|
||||||
std::enable_if_t<std::is_array_v<T>, LargePagePtr<T>> make_unique_large_page(size_t num) {
|
|
||||||
using ElementType = std::remove_extent_t<T>;
|
|
||||||
|
|
||||||
static_assert(alignof(ElementType) <= 4096,
|
|
||||||
"aligned_large_pages_alloc() may fail for such a big alignment requirement of T");
|
|
||||||
|
|
||||||
ElementType* memory = memory_allocator<T>(aligned_large_pages_alloc, num);
|
|
||||||
|
|
||||||
return LargePagePtr<T>(memory);
|
|
||||||
}
|
|
||||||
|
|
||||||
//
|
|
||||||
//
|
|
||||||
// aligned unique ptr
|
|
||||||
//
|
|
||||||
//
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
struct AlignedDeleter {
|
|
||||||
void operator()(T* ptr) const { return memory_deleter<T>(ptr, std_aligned_free); }
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
struct AlignedArrayDeleter {
|
|
||||||
void operator()(T* ptr) const { return memory_deleter_array<T>(ptr, std_aligned_free); }
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
using AlignedPtr =
|
|
||||||
std::conditional_t<std::is_array_v<T>,
|
|
||||||
std::unique_ptr<T, AlignedArrayDeleter<std::remove_extent_t<T>>>,
|
|
||||||
std::unique_ptr<T, AlignedDeleter<T>>>;
|
|
||||||
|
|
||||||
// make_unique_aligned for single objects
|
|
||||||
template<typename T, typename... Args>
|
|
||||||
std::enable_if_t<!std::is_array_v<T>, AlignedPtr<T>> make_unique_aligned(Args&&... args) {
|
|
||||||
const auto func = [](size_t size) { return std_aligned_alloc(alignof(T), size); };
|
|
||||||
T* obj = memory_allocator<T>(func, std::forward<Args>(args)...);
|
|
||||||
|
|
||||||
return AlignedPtr<T>(obj);
|
|
||||||
}
|
|
||||||
|
|
||||||
// make_unique_aligned for arrays of unknown bound
|
|
||||||
template<typename T>
|
|
||||||
std::enable_if_t<std::is_array_v<T>, AlignedPtr<T>> make_unique_aligned(size_t num) {
|
|
||||||
using ElementType = std::remove_extent_t<T>;
|
|
||||||
|
|
||||||
const auto func = [](size_t size) { return std_aligned_alloc(alignof(ElementType), size); };
|
|
||||||
ElementType* memory = memory_allocator<T>(func, num);
|
|
||||||
|
|
||||||
return AlignedPtr<T>(memory);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Get the first aligned element of an array.
|
|
||||||
// ptr must point to an array of size at least `sizeof(T) * N + alignment` bytes,
|
|
||||||
// where N is the number of elements in the array.
|
|
||||||
template<uintptr_t Alignment, typename T>
|
|
||||||
T* align_ptr_up(T* ptr) {
|
|
||||||
static_assert(alignof(T) < Alignment);
|
|
||||||
|
|
||||||
const uintptr_t ptrint = reinterpret_cast<uintptr_t>(reinterpret_cast<char*>(ptr));
|
|
||||||
return reinterpret_cast<T*>(
|
|
||||||
reinterpret_cast<char*>((ptrint + (Alignment - 1)) / Alignment * Alignment));
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
} // namespace Stockfish
|
|
||||||
|
|
||||||
#endif // #ifndef MEMORY_H_INCLUDED
|
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
/*
|
||||||
|
A C-program for MT19937, with initialization improved 2002/1/26.
|
||||||
|
Coded by Takuji Nishimura and Makoto Matsumoto.
|
||||||
|
|
||||||
|
Before using, initialize the state by using init_genrand(seed)
|
||||||
|
or init_by_array(init_key, key_length).
|
||||||
|
|
||||||
|
Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
|
||||||
|
All rights reserved.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions
|
||||||
|
are met:
|
||||||
|
|
||||||
|
1. Redistributions of source code must retain the above copyright
|
||||||
|
notice, this list of conditions and the following disclaimer.
|
||||||
|
|
||||||
|
2. Redistributions in binary form must reproduce the above copyright
|
||||||
|
notice, this list of conditions and the following disclaimer in the
|
||||||
|
documentation and/or other materials provided with the distribution.
|
||||||
|
|
||||||
|
3. The names of its contributors may not be used to endorse or promote
|
||||||
|
products derived from this software without specific prior written
|
||||||
|
permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||||
|
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||||
|
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||||
|
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
|
||||||
|
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
|
||||||
|
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
||||||
|
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
||||||
|
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
||||||
|
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
||||||
|
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
|
|
||||||
|
|
||||||
|
Any feedback is very welcome.
|
||||||
|
http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
|
||||||
|
email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "types.h"
|
||||||
|
#include "mersenne.h"
|
||||||
|
|
||||||
|
/* Period parameters */
|
||||||
|
#define N 624
|
||||||
|
#define M 397
|
||||||
|
#define MATRIX_A 0x9908b0dfUL /* constant vector a */
|
||||||
|
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
|
||||||
|
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */
|
||||||
|
|
||||||
|
static unsigned long mt[N]; /* the array for the state vector */
|
||||||
|
static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
|
||||||
|
|
||||||
|
/* initializes mt[N] with a seed */
|
||||||
|
static void init_genrand(unsigned long s)
|
||||||
|
{
|
||||||
|
mt[0]= s & 0xffffffffUL;
|
||||||
|
for (mti=1; mti<N; mti++) {
|
||||||
|
mt[mti] =
|
||||||
|
(1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti);
|
||||||
|
/* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
|
||||||
|
/* In the previous versions, MSBs of the seed affect */
|
||||||
|
/* only MSBs of the array mt[]. */
|
||||||
|
/* 2002/01/09 modified by Makoto Matsumoto */
|
||||||
|
mt[mti] &= 0xffffffffUL;
|
||||||
|
/* for >32 bit machines */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* initialize by an array with array-length */
|
||||||
|
/* init_key is the array for initializing keys */
|
||||||
|
/* key_length is its length */
|
||||||
|
/* slight change for C++, 2004/2/26 */
|
||||||
|
static void init_by_array(unsigned long init_key[], int key_length)
|
||||||
|
{
|
||||||
|
int i, j, k;
|
||||||
|
init_genrand(19650218UL);
|
||||||
|
i=1; j=0;
|
||||||
|
k = (N>key_length ? N : key_length);
|
||||||
|
for (; k; k--) {
|
||||||
|
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
|
||||||
|
+ init_key[j] + j; /* non linear */
|
||||||
|
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
|
||||||
|
i++; j++;
|
||||||
|
if (i>=N) { mt[0] = mt[N-1]; i=1; }
|
||||||
|
if (j>=key_length) j=0;
|
||||||
|
}
|
||||||
|
for (k=N-1; k; k--) {
|
||||||
|
mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
|
||||||
|
- i; /* non linear */
|
||||||
|
mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
|
||||||
|
i++;
|
||||||
|
if (i>=N) { mt[0] = mt[N-1]; i=1; }
|
||||||
|
}
|
||||||
|
|
||||||
|
mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* generates a random number on [0,0xffffffff]-interval */
|
||||||
|
uint32_t genrand_int32(void) {
|
||||||
|
unsigned long y;
|
||||||
|
static unsigned long mag01[2]={0x0UL, MATRIX_A};
|
||||||
|
/* mag01[x] = x * MATRIX_A for x=0,1 */
|
||||||
|
|
||||||
|
if (mti >= N) { /* generate N words at one time */
|
||||||
|
int kk;
|
||||||
|
|
||||||
|
if (mti == N+1) /* if init_genrand() has not been called, */
|
||||||
|
init_genrand(5489UL); /* a default initial seed is used */
|
||||||
|
|
||||||
|
for (kk=0;kk<N-M;kk++) {
|
||||||
|
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
|
||||||
|
mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
|
||||||
|
}
|
||||||
|
for (;kk<N-1;kk++) {
|
||||||
|
y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
|
||||||
|
mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
|
||||||
|
}
|
||||||
|
y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
|
||||||
|
mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];
|
||||||
|
|
||||||
|
mti = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
y = mt[mti++];
|
||||||
|
|
||||||
|
/* Tempering */
|
||||||
|
y ^= (y >> 11);
|
||||||
|
y ^= (y << 7) & 0x9d2c5680UL;
|
||||||
|
y ^= (y << 15) & 0xefc60000UL;
|
||||||
|
y ^= (y >> 18);
|
||||||
|
|
||||||
|
return y;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint64_t genrand_int64(void) {
|
||||||
|
uint64_t x, y;
|
||||||
|
|
||||||
|
x = genrand_int32(); y = genrand_int32();
|
||||||
|
return (x<<32)|y;
|
||||||
|
}
|
||||||
|
|
||||||
|
void init_mersenne(void) {
|
||||||
|
unsigned long init[4]={0x123, 0x234, 0x345, 0x456}, length=4;
|
||||||
|
init_by_array(init, length);
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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(MERSENNE_H_INCLUDED)
|
||||||
|
#define MERSENNE_H_INCLUDED
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include "types.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Prototypes
|
||||||
|
////
|
||||||
|
|
||||||
|
extern uint32_t genrand_int32(void);
|
||||||
|
extern uint64_t genrand_int64(void);
|
||||||
|
extern void init_mersenne(void);
|
||||||
|
|
||||||
|
|
||||||
|
#endif // !defined(MERSENNE_H_INCLUDED)
|
||||||
+227
-452
@@ -1,6 +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-2024 The Stockfish developers (see AUTHORS file)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
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
|
||||||
@@ -16,488 +17,262 @@
|
|||||||
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 "misc.h"
|
|
||||||
|
|
||||||
#include <atomic>
|
////
|
||||||
#include <cctype>
|
//// Includes
|
||||||
#include <cmath>
|
////
|
||||||
#include <cstdlib>
|
|
||||||
#include <fstream>
|
#if !defined(_MSC_VER)
|
||||||
|
|
||||||
|
# include <sys/time.h>
|
||||||
|
# include <sys/types.h>
|
||||||
|
# include <unistd.h>
|
||||||
|
|
||||||
|
#else
|
||||||
|
|
||||||
|
#define _CRT_SECURE_NO_DEPRECATE
|
||||||
|
#include <windows.h>
|
||||||
|
#include <sys/timeb.h>
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include <cassert>
|
||||||
|
#include <cstdio>
|
||||||
#include <iomanip>
|
#include <iomanip>
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <iterator>
|
|
||||||
#include <limits>
|
|
||||||
#include <mutex>
|
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <string_view>
|
|
||||||
|
|
||||||
#include "types.h"
|
#include "bitcount.h"
|
||||||
|
#include "misc.h"
|
||||||
|
|
||||||
namespace Stockfish {
|
using namespace std;
|
||||||
|
|
||||||
namespace {
|
/// Version number. If this is left empty, the current date (in the format
|
||||||
|
/// YYMMDD) is used as a version number.
|
||||||
|
|
||||||
// Version number or dev.
|
static const string EngineVersion = "1.6.3";
|
||||||
constexpr std::string_view version = "17";
|
static const string AppName = "Stockfish";
|
||||||
|
static const string AppTag = "";
|
||||||
|
|
||||||
// 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 whilst preserving
|
|
||||||
// usual I/O functionality, all without changing a single line of code!
|
|
||||||
// Idea from http://groups.google.com/group/comp.lang.c++/msg/1d941c0f26ea0d81
|
|
||||||
|
|
||||||
struct Tie: public std::streambuf { // MSVC requires split streambuf for cin and cout
|
////
|
||||||
|
//// Variables
|
||||||
|
////
|
||||||
|
|
||||||
Tie(std::streambuf* b, std::streambuf* l) :
|
bool Chess960;
|
||||||
buf(b),
|
|
||||||
logBuf(l) {}
|
|
||||||
|
|
||||||
int sync() override { return logBuf->pubsync(), buf->pubsync(); }
|
uint64_t dbg_cnt0 = 0;
|
||||||
int overflow(int c) override { return log(buf->sputc(char(c)), "<< "); }
|
uint64_t dbg_cnt1 = 0;
|
||||||
int underflow() override { return buf->sgetc(); }
|
|
||||||
int uflow() override { return log(buf->sbumpc(), ">> "); }
|
|
||||||
|
|
||||||
std::streambuf *buf, *logBuf;
|
bool dbg_show_mean = false;
|
||||||
|
bool dbg_show_hit_rate = false;
|
||||||
|
|
||||||
int log(int c, const char* prefix) {
|
|
||||||
|
|
||||||
static int last = '\n'; // Single log file
|
////
|
||||||
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
if (last == '\n')
|
void dbg_hit_on(bool b) {
|
||||||
logBuf->sputn(prefix, 3);
|
|
||||||
|
|
||||||
return last = logBuf->sputc(char(c));
|
assert(!dbg_show_mean);
|
||||||
}
|
dbg_show_hit_rate = true;
|
||||||
};
|
dbg_cnt0++;
|
||||||
|
if (b)
|
||||||
|
dbg_cnt1++;
|
||||||
|
}
|
||||||
|
|
||||||
class Logger {
|
void dbg_hit_on_c(bool c, bool b) {
|
||||||
|
|
||||||
Logger() :
|
if (c)
|
||||||
in(std::cin.rdbuf(), file.rdbuf()),
|
dbg_hit_on(b);
|
||||||
out(std::cout.rdbuf(), file.rdbuf()) {}
|
}
|
||||||
~Logger() { start(""); }
|
|
||||||
|
|
||||||
std::ofstream file;
|
void dbg_before() {
|
||||||
Tie in, out;
|
|
||||||
|
|
||||||
public:
|
assert(!dbg_show_mean);
|
||||||
static void start(const std::string& fname) {
|
dbg_show_hit_rate = true;
|
||||||
|
dbg_cnt0++;
|
||||||
|
}
|
||||||
|
|
||||||
static Logger l;
|
void dbg_after() {
|
||||||
|
|
||||||
if (l.file.is_open())
|
assert(!dbg_show_mean);
|
||||||
{
|
dbg_show_hit_rate = true;
|
||||||
std::cout.rdbuf(l.out.buf);
|
dbg_cnt1++;
|
||||||
std::cin.rdbuf(l.in.buf);
|
}
|
||||||
l.file.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!fname.empty())
|
void dbg_mean_of(int v) {
|
||||||
{
|
|
||||||
l.file.open(fname, std::ifstream::out);
|
|
||||||
|
|
||||||
if (!l.file.is_open())
|
assert(!dbg_show_hit_rate);
|
||||||
{
|
dbg_show_mean = true;
|
||||||
std::cerr << "Unable to open debug log file " << fname << std::endl;
|
dbg_cnt0++;
|
||||||
exit(EXIT_FAILURE);
|
dbg_cnt1 += v;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::cin.rdbuf(&l.in);
|
void dbg_print_hit_rate() {
|
||||||
std::cout.rdbuf(&l.out);
|
|
||||||
|
cout << "Total " << dbg_cnt0 << " Hit " << dbg_cnt1
|
||||||
|
<< " hit rate (%) " << (dbg_cnt1*100)/(dbg_cnt0 ? dbg_cnt0 : 1) << endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
void dbg_print_mean() {
|
||||||
|
|
||||||
|
cout << "Total " << dbg_cnt0 << " Mean "
|
||||||
|
<< (float)dbg_cnt1 / (dbg_cnt0 ? dbg_cnt0 : 1) << endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
void dbg_print_hit_rate(ofstream& logFile) {
|
||||||
|
|
||||||
|
logFile << "Total " << dbg_cnt0 << " Hit " << dbg_cnt1
|
||||||
|
<< " hit rate (%) " << (dbg_cnt1*100)/(dbg_cnt0 ? dbg_cnt0 : 1) << endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
void dbg_print_mean(ofstream& logFile) {
|
||||||
|
|
||||||
|
logFile << "Total " << dbg_cnt0 << " Mean "
|
||||||
|
<< (float)dbg_cnt1 / (dbg_cnt0 ? dbg_cnt0 : 1) << endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// engine_name() returns the full name of the current Stockfish version.
|
||||||
|
/// This will be either "Stockfish YYMMDD" (where YYMMDD is the date when the
|
||||||
|
/// program was compiled) or "Stockfish <version number>", depending on whether
|
||||||
|
/// the constant EngineVersion (defined in misc.h) is empty.
|
||||||
|
|
||||||
|
const string engine_name() {
|
||||||
|
|
||||||
|
const string cpu64(CpuHas64BitPath ? " 64bit" : "");
|
||||||
|
|
||||||
|
if (!EngineVersion.empty())
|
||||||
|
return AppName+ " " + EngineVersion + cpu64;
|
||||||
|
|
||||||
|
string date(__DATE__); // From compiler, format is "Sep 21 2008"
|
||||||
|
string months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
|
||||||
|
|
||||||
|
size_t mon = 1 + months.find(date.substr(0, 3)) / 4;
|
||||||
|
|
||||||
|
stringstream s;
|
||||||
|
string day = (date[4] == ' ' ? date.substr(5, 1) : date.substr(4, 2));
|
||||||
|
|
||||||
|
string name = AppName + " " + AppTag + " ";
|
||||||
|
|
||||||
|
s << name << date.substr(date.length() - 2) << setfill('0')
|
||||||
|
<< setw(2) << mon << setw(2) << day << cpu64;
|
||||||
|
|
||||||
|
return s.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// get_system_time() returns the current system time, measured in
|
||||||
|
/// milliseconds.
|
||||||
|
|
||||||
|
int get_system_time() {
|
||||||
|
|
||||||
|
#if defined(_MSC_VER)
|
||||||
|
struct _timeb t;
|
||||||
|
_ftime(&t);
|
||||||
|
return int(t.time*1000 + t.millitm);
|
||||||
|
#else
|
||||||
|
struct timeval t;
|
||||||
|
gettimeofday(&t, NULL);
|
||||||
|
return t.tv_sec*1000 + t.tv_usec/1000;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// cpu_count() tries to detect the number of CPU cores.
|
||||||
|
|
||||||
|
#if !defined(_MSC_VER)
|
||||||
|
|
||||||
|
# if defined(_SC_NPROCESSORS_ONLN)
|
||||||
|
int cpu_count() {
|
||||||
|
return Min(sysconf(_SC_NPROCESSORS_ONLN), 8);
|
||||||
|
}
|
||||||
|
# else
|
||||||
|
int cpu_count() {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
# endif
|
||||||
|
|
||||||
|
#else
|
||||||
|
|
||||||
|
int cpu_count() {
|
||||||
|
SYSTEM_INFO s;
|
||||||
|
GetSystemInfo(&s);
|
||||||
|
return Min(s.dwNumberOfProcessors, 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
From Beowulf, from Olithink
|
||||||
|
*/
|
||||||
|
#ifndef _WIN32
|
||||||
|
/* Non-windows version */
|
||||||
|
int Bioskey()
|
||||||
|
{
|
||||||
|
fd_set readfds;
|
||||||
|
struct timeval timeout;
|
||||||
|
|
||||||
|
FD_ZERO(&readfds);
|
||||||
|
FD_SET(fileno(stdin), &readfds);
|
||||||
|
/* Set to timeout immediately */
|
||||||
|
timeout.tv_sec = 0;
|
||||||
|
timeout.tv_usec = 0;
|
||||||
|
select(16, &readfds, 0, 0, &timeout);
|
||||||
|
|
||||||
|
return (FD_ISSET(fileno(stdin), &readfds));
|
||||||
|
}
|
||||||
|
|
||||||
|
#else
|
||||||
|
/* Windows-version */
|
||||||
|
#include <windows.h>
|
||||||
|
#include <conio.h>
|
||||||
|
int Bioskey()
|
||||||
|
{
|
||||||
|
static int init = 0,
|
||||||
|
pipe;
|
||||||
|
static HANDLE inh;
|
||||||
|
DWORD dw;
|
||||||
|
/* If we're running under XBoard then we can't use _kbhit() as the input
|
||||||
|
* commands are sent to us directly over the internal pipe */
|
||||||
|
|
||||||
|
#if defined(FILE_CNT)
|
||||||
|
if (stdin->_cnt > 0)
|
||||||
|
return stdin->_cnt;
|
||||||
|
#endif
|
||||||
|
if (!init) {
|
||||||
|
init = 1;
|
||||||
|
inh = GetStdHandle(STD_INPUT_HANDLE);
|
||||||
|
pipe = !GetConsoleMode(inh, &dw);
|
||||||
|
if (!pipe) {
|
||||||
|
SetConsoleMode(inh, dw & ~(ENABLE_MOUSE_INPUT | ENABLE_WINDOW_INPUT));
|
||||||
|
FlushConsoleInputBuffer(inh);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
if (pipe) {
|
||||||
|
if (!PeekNamedPipe(inh, NULL, 0, NULL, &dw, NULL))
|
||||||
|
return 1;
|
||||||
|
return dw;
|
||||||
|
} else {
|
||||||
|
// Count the number of unread input records, including keyboard,
|
||||||
|
// mouse, and window-resizing input records.
|
||||||
|
GetNumberOfConsoleInputEvents(inh, &dw);
|
||||||
|
if (dw <= 0)
|
||||||
|
return 0;
|
||||||
|
|
||||||
} // namespace
|
// Read data from console without removing it from the buffer
|
||||||
|
INPUT_RECORD rec[256];
|
||||||
|
DWORD recCnt;
|
||||||
|
if (!PeekConsoleInput(inh, rec, Min(dw, 256), &recCnt))
|
||||||
|
return 0;
|
||||||
|
|
||||||
|
// Search for at least one keyboard event
|
||||||
|
for (DWORD i = 0; i < recCnt; i++)
|
||||||
|
if (rec[i].EventType == KEY_EVENT)
|
||||||
|
return 1;
|
||||||
|
|
||||||
// Returns the full name of the current Stockfish version.
|
return 0;
|
||||||
//
|
|
||||||
// For local dev compiles we try to append the commit SHA and
|
|
||||||
// commit date from git. If that fails only the local compilation
|
|
||||||
// date is set and "nogit" is specified:
|
|
||||||
// Stockfish dev-YYYYMMDD-SHA
|
|
||||||
// or
|
|
||||||
// Stockfish dev-YYYYMMDD-nogit
|
|
||||||
//
|
|
||||||
// For releases (non-dev builds) we only include the version number:
|
|
||||||
// Stockfish version
|
|
||||||
std::string engine_info(bool to_uci) {
|
|
||||||
std::stringstream ss;
|
|
||||||
ss << "Stockfish " << version << std::setfill('0');
|
|
||||||
|
|
||||||
if constexpr (version == "dev")
|
|
||||||
{
|
|
||||||
ss << "-";
|
|
||||||
#ifdef GIT_DATE
|
|
||||||
ss << stringify(GIT_DATE);
|
|
||||||
#else
|
|
||||||
constexpr std::string_view months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
|
|
||||||
|
|
||||||
std::string month, day, year;
|
|
||||||
std::stringstream date(__DATE__); // From compiler, format is "Sep 21 2008"
|
|
||||||
|
|
||||||
date >> month >> day >> year;
|
|
||||||
ss << year << std::setw(2) << std::setfill('0') << (1 + months.find(month) / 4)
|
|
||||||
<< std::setw(2) << std::setfill('0') << day;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
ss << "-";
|
|
||||||
|
|
||||||
#ifdef GIT_SHA
|
|
||||||
ss << stringify(GIT_SHA);
|
|
||||||
#else
|
|
||||||
ss << "nogit";
|
|
||||||
#endif
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ss << (to_uci ? "\nid author " : " by ") << "the Stockfish developers (see AUTHORS file)";
|
|
||||||
|
|
||||||
return ss.str();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Returns a string trying to describe the compiler we use
|
|
||||||
std::string compiler_info() {
|
|
||||||
|
|
||||||
#define make_version_string(major, minor, patch) \
|
|
||||||
stringify(major) "." stringify(minor) "." stringify(patch)
|
|
||||||
|
|
||||||
// Predefined macros hell:
|
|
||||||
//
|
|
||||||
// __GNUC__ Compiler is GCC, Clang or ICX
|
|
||||||
// __clang__ Compiler is Clang or ICX
|
|
||||||
// __INTEL_LLVM_COMPILER Compiler is ICX
|
|
||||||
// _MSC_VER Compiler is MSVC
|
|
||||||
// _WIN32 Building on Windows (any)
|
|
||||||
// _WIN64 Building on Windows 64 bit
|
|
||||||
|
|
||||||
std::string compiler = "\nCompiled by : ";
|
|
||||||
|
|
||||||
#if defined(__INTEL_LLVM_COMPILER)
|
|
||||||
compiler += "ICX ";
|
|
||||||
compiler += stringify(__INTEL_LLVM_COMPILER);
|
|
||||||
#elif defined(__clang__)
|
|
||||||
compiler += "clang++ ";
|
|
||||||
compiler += make_version_string(__clang_major__, __clang_minor__, __clang_patchlevel__);
|
|
||||||
#elif _MSC_VER
|
|
||||||
compiler += "MSVC ";
|
|
||||||
compiler += "(version ";
|
|
||||||
compiler += stringify(_MSC_FULL_VER) "." stringify(_MSC_BUILD);
|
|
||||||
compiler += ")";
|
|
||||||
#elif defined(__e2k__) && defined(__LCC__)
|
|
||||||
#define dot_ver2(n) \
|
|
||||||
compiler += char('.'); \
|
|
||||||
compiler += char('0' + (n) / 10); \
|
|
||||||
compiler += char('0' + (n) % 10);
|
|
||||||
|
|
||||||
compiler += "MCST LCC ";
|
|
||||||
compiler += "(version ";
|
|
||||||
compiler += std::to_string(__LCC__ / 100);
|
|
||||||
dot_ver2(__LCC__ % 100) dot_ver2(__LCC_MINOR__) compiler += ")";
|
|
||||||
#elif __GNUC__
|
|
||||||
compiler += "g++ (GNUC) ";
|
|
||||||
compiler += make_version_string(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
|
|
||||||
#else
|
|
||||||
compiler += "Unknown compiler ";
|
|
||||||
compiler += "(unknown version)";
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#if defined(__APPLE__)
|
|
||||||
compiler += " on Apple";
|
|
||||||
#elif defined(__CYGWIN__)
|
|
||||||
compiler += " on Cygwin";
|
|
||||||
#elif defined(__MINGW64__)
|
|
||||||
compiler += " on MinGW64";
|
|
||||||
#elif defined(__MINGW32__)
|
|
||||||
compiler += " on MinGW32";
|
|
||||||
#elif defined(__ANDROID__)
|
|
||||||
compiler += " on Android";
|
|
||||||
#elif defined(__linux__)
|
|
||||||
compiler += " on Linux";
|
|
||||||
#elif defined(_WIN64)
|
|
||||||
compiler += " on Microsoft Windows 64-bit";
|
|
||||||
#elif defined(_WIN32)
|
|
||||||
compiler += " on Microsoft Windows 32-bit";
|
|
||||||
#else
|
|
||||||
compiler += " on unknown system";
|
|
||||||
#endif
|
|
||||||
|
|
||||||
compiler += "\nCompilation architecture : ";
|
|
||||||
#if defined(ARCH)
|
|
||||||
compiler += stringify(ARCH);
|
|
||||||
#else
|
|
||||||
compiler += "(undefined architecture)";
|
|
||||||
#endif
|
|
||||||
|
|
||||||
compiler += "\nCompilation settings : ";
|
|
||||||
compiler += (Is64Bit ? "64bit" : "32bit");
|
|
||||||
#if defined(USE_VNNI)
|
|
||||||
compiler += " VNNI";
|
|
||||||
#endif
|
|
||||||
#if defined(USE_AVX512)
|
|
||||||
compiler += " AVX512";
|
|
||||||
#endif
|
|
||||||
compiler += (HasPext ? " BMI2" : "");
|
|
||||||
#if defined(USE_AVX2)
|
|
||||||
compiler += " AVX2";
|
|
||||||
#endif
|
|
||||||
#if defined(USE_SSE41)
|
|
||||||
compiler += " SSE41";
|
|
||||||
#endif
|
|
||||||
#if defined(USE_SSSE3)
|
|
||||||
compiler += " SSSE3";
|
|
||||||
#endif
|
|
||||||
#if defined(USE_SSE2)
|
|
||||||
compiler += " SSE2";
|
|
||||||
#endif
|
|
||||||
compiler += (HasPopCnt ? " POPCNT" : "");
|
|
||||||
#if defined(USE_NEON_DOTPROD)
|
|
||||||
compiler += " NEON_DOTPROD";
|
|
||||||
#elif defined(USE_NEON)
|
|
||||||
compiler += " NEON";
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if !defined(NDEBUG)
|
|
||||||
compiler += " DEBUG";
|
|
||||||
#endif
|
|
||||||
|
|
||||||
compiler += "\nCompiler __VERSION__ macro : ";
|
|
||||||
#ifdef __VERSION__
|
|
||||||
compiler += __VERSION__;
|
|
||||||
#else
|
|
||||||
compiler += "(undefined macro)";
|
|
||||||
#endif
|
|
||||||
|
|
||||||
compiler += "\n";
|
|
||||||
|
|
||||||
return compiler;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Debug functions used mainly to collect run-time statistics
|
|
||||||
constexpr int MaxDebugSlots = 32;
|
|
||||||
|
|
||||||
namespace {
|
|
||||||
|
|
||||||
template<size_t N>
|
|
||||||
struct DebugInfo {
|
|
||||||
std::atomic<int64_t> data[N] = {0};
|
|
||||||
|
|
||||||
constexpr std::atomic<int64_t>& operator[](int index) { return data[index]; }
|
|
||||||
};
|
|
||||||
|
|
||||||
struct DebugExtremes: public DebugInfo<3> {
|
|
||||||
DebugExtremes() {
|
|
||||||
data[1] = std::numeric_limits<int64_t>::min();
|
|
||||||
data[2] = std::numeric_limits<int64_t>::max();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
DebugInfo<2> hit[MaxDebugSlots];
|
|
||||||
DebugInfo<2> mean[MaxDebugSlots];
|
|
||||||
DebugInfo<3> stdev[MaxDebugSlots];
|
|
||||||
DebugInfo<6> correl[MaxDebugSlots];
|
|
||||||
DebugExtremes extremes[MaxDebugSlots];
|
|
||||||
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
void dbg_hit_on(bool cond, int slot) {
|
|
||||||
|
|
||||||
++hit[slot][0];
|
|
||||||
if (cond)
|
|
||||||
++hit[slot][1];
|
|
||||||
}
|
|
||||||
|
|
||||||
void dbg_mean_of(int64_t value, int slot) {
|
|
||||||
|
|
||||||
++mean[slot][0];
|
|
||||||
mean[slot][1] += value;
|
|
||||||
}
|
|
||||||
|
|
||||||
void dbg_stdev_of(int64_t value, int slot) {
|
|
||||||
|
|
||||||
++stdev[slot][0];
|
|
||||||
stdev[slot][1] += value;
|
|
||||||
stdev[slot][2] += value * value;
|
|
||||||
}
|
|
||||||
|
|
||||||
void dbg_extremes_of(int64_t value, int slot) {
|
|
||||||
++extremes[slot][0];
|
|
||||||
|
|
||||||
int64_t current_max = extremes[slot][1].load();
|
|
||||||
while (current_max < value && !extremes[slot][1].compare_exchange_weak(current_max, value))
|
|
||||||
{}
|
|
||||||
|
|
||||||
int64_t current_min = extremes[slot][2].load();
|
|
||||||
while (current_min > value && !extremes[slot][2].compare_exchange_weak(current_min, value))
|
|
||||||
{}
|
|
||||||
}
|
|
||||||
|
|
||||||
void dbg_correl_of(int64_t value1, int64_t value2, int slot) {
|
|
||||||
|
|
||||||
++correl[slot][0];
|
|
||||||
correl[slot][1] += value1;
|
|
||||||
correl[slot][2] += value1 * value1;
|
|
||||||
correl[slot][3] += value2;
|
|
||||||
correl[slot][4] += value2 * value2;
|
|
||||||
correl[slot][5] += value1 * value2;
|
|
||||||
}
|
|
||||||
|
|
||||||
void dbg_print() {
|
|
||||||
|
|
||||||
int64_t n;
|
|
||||||
auto E = [&n](int64_t x) { return double(x) / n; };
|
|
||||||
auto sqr = [](double x) { return x * x; };
|
|
||||||
|
|
||||||
for (int i = 0; i < MaxDebugSlots; ++i)
|
|
||||||
if ((n = hit[i][0]))
|
|
||||||
std::cerr << "Hit #" << i << ": Total " << n << " Hits " << hit[i][1]
|
|
||||||
<< " Hit Rate (%) " << 100.0 * E(hit[i][1]) << std::endl;
|
|
||||||
|
|
||||||
for (int i = 0; i < MaxDebugSlots; ++i)
|
|
||||||
if ((n = mean[i][0]))
|
|
||||||
{
|
|
||||||
std::cerr << "Mean #" << i << ": Total " << n << " Mean " << E(mean[i][1]) << std::endl;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = 0; i < MaxDebugSlots; ++i)
|
|
||||||
if ((n = stdev[i][0]))
|
|
||||||
{
|
|
||||||
double r = sqrt(E(stdev[i][2]) - sqr(E(stdev[i][1])));
|
|
||||||
std::cerr << "Stdev #" << i << ": Total " << n << " Stdev " << r << std::endl;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = 0; i < MaxDebugSlots; ++i)
|
|
||||||
if ((n = extremes[i][0]))
|
|
||||||
{
|
|
||||||
std::cerr << "Extremity #" << i << ": Total " << n << " Min " << extremes[i][2]
|
|
||||||
<< " Max " << extremes[i][1] << std::endl;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = 0; i < MaxDebugSlots; ++i)
|
|
||||||
if ((n = correl[i][0]))
|
|
||||||
{
|
|
||||||
double r = (E(correl[i][5]) - E(correl[i][1]) * E(correl[i][3]))
|
|
||||||
/ (sqrt(E(correl[i][2]) - sqr(E(correl[i][1])))
|
|
||||||
* sqrt(E(correl[i][4]) - sqr(E(correl[i][3]))));
|
|
||||||
std::cerr << "Correl. #" << i << ": Total " << n << " Coefficient " << r << std::endl;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Used to serialize access to std::cout
|
|
||||||
// to avoid multiple threads writing at the same time.
|
|
||||||
std::ostream& operator<<(std::ostream& os, SyncCout sc) {
|
|
||||||
|
|
||||||
static std::mutex m;
|
|
||||||
|
|
||||||
if (sc == IO_LOCK)
|
|
||||||
m.lock();
|
|
||||||
|
|
||||||
if (sc == IO_UNLOCK)
|
|
||||||
m.unlock();
|
|
||||||
|
|
||||||
return os;
|
|
||||||
}
|
|
||||||
|
|
||||||
void sync_cout_start() { std::cout << IO_LOCK; }
|
|
||||||
void sync_cout_end() { std::cout << IO_UNLOCK; }
|
|
||||||
|
|
||||||
// Trampoline helper to avoid moving Logger to misc.h
|
|
||||||
void start_logger(const std::string& fname) { Logger::start(fname); }
|
|
||||||
|
|
||||||
|
|
||||||
#ifdef NO_PREFETCH
|
|
||||||
|
|
||||||
void prefetch(const void*) {}
|
|
||||||
|
|
||||||
#else
|
|
||||||
|
|
||||||
void prefetch(const void* addr) {
|
|
||||||
|
|
||||||
#if defined(_MSC_VER)
|
|
||||||
_mm_prefetch((char const*) addr, _MM_HINT_T0);
|
|
||||||
#else
|
|
||||||
__builtin_prefetch(addr);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifdef _WIN32
|
|
||||||
#include <direct.h>
|
|
||||||
#define GETCWD _getcwd
|
|
||||||
#else
|
|
||||||
#include <unistd.h>
|
|
||||||
#define GETCWD getcwd
|
|
||||||
#endif
|
|
||||||
|
|
||||||
size_t str_to_size_t(const std::string& s) {
|
|
||||||
unsigned long long value = std::stoull(s);
|
|
||||||
if (value > std::numeric_limits<size_t>::max())
|
|
||||||
std::exit(EXIT_FAILURE);
|
|
||||||
return static_cast<size_t>(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::optional<std::string> read_file_to_string(const std::string& path) {
|
|
||||||
std::ifstream f(path, std::ios_base::binary);
|
|
||||||
if (!f)
|
|
||||||
return std::nullopt;
|
|
||||||
return std::string(std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>());
|
|
||||||
}
|
|
||||||
|
|
||||||
void remove_whitespace(std::string& s) {
|
|
||||||
s.erase(std::remove_if(s.begin(), s.end(), [](char c) { return std::isspace(c); }), s.end());
|
|
||||||
}
|
|
||||||
|
|
||||||
bool is_whitespace(const std::string& s) {
|
|
||||||
return std::all_of(s.begin(), s.end(), [](char c) { return std::isspace(c); });
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string CommandLine::get_binary_directory(std::string argv0) {
|
|
||||||
std::string pathSeparator;
|
|
||||||
|
|
||||||
#ifdef _WIN32
|
|
||||||
pathSeparator = "\\";
|
|
||||||
#ifdef _MSC_VER
|
|
||||||
// Under windows argv[0] may not have the extension. Also _get_pgmptr() had
|
|
||||||
// issues in some Windows 10 versions, so check returned values carefully.
|
|
||||||
char* pgmptr = nullptr;
|
|
||||||
if (!_get_pgmptr(&pgmptr) && pgmptr != nullptr && *pgmptr)
|
|
||||||
argv0 = pgmptr;
|
|
||||||
#endif
|
|
||||||
#else
|
|
||||||
pathSeparator = "/";
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Extract the working directory
|
|
||||||
auto workingDirectory = CommandLine::get_working_directory();
|
|
||||||
|
|
||||||
// Extract the binary directory path from argv0
|
|
||||||
auto binaryDirectory = argv0;
|
|
||||||
size_t pos = binaryDirectory.find_last_of("\\/");
|
|
||||||
if (pos == std::string::npos)
|
|
||||||
binaryDirectory = "." + pathSeparator;
|
|
||||||
else
|
|
||||||
binaryDirectory.resize(pos + 1);
|
|
||||||
|
|
||||||
// Pattern replacement: "./" at the start of path is replaced by the working directory
|
|
||||||
if (binaryDirectory.find("." + pathSeparator) == 0)
|
|
||||||
binaryDirectory.replace(0, 1, workingDirectory);
|
|
||||||
|
|
||||||
return binaryDirectory;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string CommandLine::get_working_directory() {
|
|
||||||
std::string workingDirectory = "";
|
|
||||||
char buff[40000];
|
|
||||||
char* cwd = GETCWD(buff, 40000);
|
|
||||||
if (cwd)
|
|
||||||
workingDirectory = cwd;
|
|
||||||
|
|
||||||
return workingDirectory;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
} // namespace Stockfish
|
|
||||||
|
|||||||
+45
-195
@@ -1,6 +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-2024 The Stockfish developers (see AUTHORS file)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
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
|
||||||
@@ -16,215 +17,64 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#ifndef MISC_H_INCLUDED
|
|
||||||
|
#if !defined(MISC_H_INCLUDED)
|
||||||
#define MISC_H_INCLUDED
|
#define MISC_H_INCLUDED
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <cassert>
|
////
|
||||||
#include <chrono>
|
//// Includes
|
||||||
#include <cstddef>
|
////
|
||||||
#include <cstdint>
|
|
||||||
#include <cstdio>
|
#include <fstream>
|
||||||
#include <iosfwd>
|
|
||||||
#include <optional>
|
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#define stringify2(x) #x
|
#include "application.h"
|
||||||
#define stringify(x) stringify2(x)
|
#include "types.h"
|
||||||
|
|
||||||
namespace Stockfish {
|
////
|
||||||
|
//// Macros
|
||||||
|
////
|
||||||
|
|
||||||
std::string engine_info(bool to_uci = false);
|
#define Min(x, y) (((x) < (y))? (x) : (y))
|
||||||
std::string compiler_info();
|
#define Max(x, y) (((x) < (y))? (y) : (x))
|
||||||
|
|
||||||
// Preloads the given address in L1/L2 cache. This is a non-blocking
|
|
||||||
// function that doesn't stall the CPU waiting for data to be loaded from memory,
|
|
||||||
// which can be quite slow.
|
|
||||||
void prefetch(const void* addr);
|
|
||||||
|
|
||||||
void start_logger(const std::string& fname);
|
|
||||||
|
|
||||||
size_t str_to_size_t(const std::string& s);
|
|
||||||
|
|
||||||
#if defined(__linux__)
|
|
||||||
|
|
||||||
struct PipeDeleter {
|
|
||||||
void operator()(FILE* file) const {
|
|
||||||
if (file != nullptr)
|
|
||||||
{
|
|
||||||
pclose(file);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Reads the file as bytes.
|
|
||||||
// Returns std::nullopt if the file does not exist.
|
|
||||||
std::optional<std::string> read_file_to_string(const std::string& path);
|
|
||||||
|
|
||||||
void dbg_hit_on(bool cond, int slot = 0);
|
|
||||||
void dbg_mean_of(int64_t value, int slot = 0);
|
|
||||||
void dbg_stdev_of(int64_t value, int slot = 0);
|
|
||||||
void dbg_extremes_of(int64_t value, int slot = 0);
|
|
||||||
void dbg_correl_of(int64_t value1, int64_t value2, int slot = 0);
|
|
||||||
void dbg_print();
|
|
||||||
|
|
||||||
using TimePoint = std::chrono::milliseconds::rep; // A value in milliseconds
|
|
||||||
static_assert(sizeof(TimePoint) == sizeof(int64_t), "TimePoint should be 64 bits");
|
|
||||||
inline TimePoint now() {
|
|
||||||
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
||||||
std::chrono::steady_clock::now().time_since_epoch())
|
|
||||||
.count();
|
|
||||||
}
|
|
||||||
|
|
||||||
inline std::vector<std::string> split(const std::string& s, const std::string& delimiter) {
|
|
||||||
std::vector<std::string> res;
|
|
||||||
|
|
||||||
if (s.empty())
|
|
||||||
return res;
|
|
||||||
|
|
||||||
size_t begin = 0;
|
|
||||||
for (;;)
|
|
||||||
{
|
|
||||||
const size_t end = s.find(delimiter, begin);
|
|
||||||
if (end == std::string::npos)
|
|
||||||
break;
|
|
||||||
|
|
||||||
res.emplace_back(s.substr(begin, end - begin));
|
|
||||||
begin = end + delimiter.size();
|
|
||||||
}
|
|
||||||
|
|
||||||
res.emplace_back(s.substr(begin));
|
|
||||||
|
|
||||||
return res;
|
|
||||||
}
|
|
||||||
|
|
||||||
void remove_whitespace(std::string& s);
|
|
||||||
bool is_whitespace(const std::string& s);
|
|
||||||
|
|
||||||
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
|
|
||||||
|
|
||||||
void sync_cout_start();
|
|
||||||
void sync_cout_end();
|
|
||||||
|
|
||||||
// True if and only if the binary is compiled on a little-endian machine
|
|
||||||
static inline const union {
|
|
||||||
uint32_t i;
|
|
||||||
char c[4];
|
|
||||||
} Le = {0x01020304};
|
|
||||||
static inline const bool IsLittleEndian = (Le.c[0] == 4);
|
|
||||||
|
|
||||||
|
|
||||||
template<typename T, std::size_t MaxSize>
|
////
|
||||||
class ValueList {
|
//// Variables
|
||||||
|
////
|
||||||
|
|
||||||
public:
|
extern bool Chess960;
|
||||||
std::size_t size() const { return size_; }
|
|
||||||
void push_back(const T& value) { values_[size_++] = value; }
|
|
||||||
const T* begin() const { return values_; }
|
|
||||||
const T* end() const { return values_ + size_; }
|
|
||||||
const T& operator[](int index) const { return values_[index]; }
|
|
||||||
|
|
||||||
private:
|
|
||||||
T values_[MaxSize];
|
|
||||||
std::size_t size_ = 0;
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
// xorshift64star Pseudo-Random Number Generator
|
////
|
||||||
// This class is based on original code written and dedicated
|
//// Prototypes
|
||||||
// to the public domain by Sebastiano Vigna (2014).
|
////
|
||||||
// It has the following characteristics:
|
|
||||||
//
|
|
||||||
// - Outputs 64-bit numbers
|
|
||||||
// - Passes Dieharder and SmallCrush test batteries
|
|
||||||
// - Does not require warm-up, no zeroland to escape
|
|
||||||
// - Internal state is a single 64-bit integer
|
|
||||||
// - Period is 2^64 - 1
|
|
||||||
// - Speed: 1.60 ns/call (Core i7 @3.40GHz)
|
|
||||||
//
|
|
||||||
// For further analysis see
|
|
||||||
// <http://vigna.di.unimi.it/ftp/papers/xorshift.pdf>
|
|
||||||
|
|
||||||
class PRNG {
|
extern const std::string engine_name();
|
||||||
|
extern int get_system_time();
|
||||||
uint64_t s;
|
extern int cpu_count();
|
||||||
|
extern int Bioskey();
|
||||||
uint64_t rand64() {
|
|
||||||
|
|
||||||
s ^= s >> 12, s ^= s << 25, s ^= s >> 27;
|
|
||||||
return s * 2685821657736338717LL;
|
|
||||||
}
|
|
||||||
|
|
||||||
public:
|
|
||||||
PRNG(uint64_t seed) :
|
|
||||||
s(seed) {
|
|
||||||
assert(seed);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
T rand() {
|
|
||||||
return T(rand64());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Special generator used to fast init magic numbers.
|
|
||||||
// Output values only have 1/8th of their bits set on average.
|
|
||||||
template<typename T>
|
|
||||||
T sparse_rand() {
|
|
||||||
return T(rand64() & rand64() & rand64());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
inline uint64_t mul_hi64(uint64_t a, uint64_t b) {
|
|
||||||
#if defined(__GNUC__) && defined(IS_64BIT)
|
|
||||||
__extension__ using uint128 = unsigned __int128;
|
|
||||||
return (uint128(a) * uint128(b)) >> 64;
|
|
||||||
#else
|
|
||||||
uint64_t aL = uint32_t(a), aH = a >> 32;
|
|
||||||
uint64_t bL = uint32_t(b), bH = b >> 32;
|
|
||||||
uint64_t c1 = (aL * bL) >> 32;
|
|
||||||
uint64_t c2 = aH * bL + c1;
|
|
||||||
uint64_t c3 = aL * bH + uint32_t(c2);
|
|
||||||
return aH * bH + (c2 >> 32) + (c3 >> 32);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
struct CommandLine {
|
////
|
||||||
public:
|
//// Debug
|
||||||
CommandLine(int _argc, char** _argv) :
|
////
|
||||||
argc(_argc),
|
|
||||||
argv(_argv) {}
|
|
||||||
|
|
||||||
static std::string get_binary_directory(std::string argv0);
|
extern bool dbg_show_mean;
|
||||||
static std::string get_working_directory();
|
extern bool dbg_show_hit_rate;
|
||||||
|
|
||||||
int argc;
|
extern uint64_t dbg_cnt0;
|
||||||
char** argv;
|
extern uint64_t dbg_cnt1;
|
||||||
};
|
|
||||||
|
|
||||||
namespace Utility {
|
extern void dbg_hit_on(bool b);
|
||||||
|
extern void dbg_hit_on_c(bool c, bool b);
|
||||||
|
extern void dbg_before();
|
||||||
|
extern void dbg_after();
|
||||||
|
extern void dbg_mean_of(int v);
|
||||||
|
extern void dbg_print_hit_rate();
|
||||||
|
extern void dbg_print_mean();
|
||||||
|
extern void dbg_print_hit_rate(std::ofstream& logFile);
|
||||||
|
extern void dbg_print_mean(std::ofstream& logFile);
|
||||||
|
|
||||||
template<typename T, typename Predicate>
|
#endif // !defined(MISC_H_INCLUDED)
|
||||||
void move_to_front(std::vector<T>& vec, Predicate pred) {
|
|
||||||
auto it = std::find_if(vec.begin(), vec.end(), pred);
|
|
||||||
|
|
||||||
if (it != vec.end())
|
|
||||||
{
|
|
||||||
std::rotate(vec.begin(), it, it + 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Stockfish
|
|
||||||
|
|
||||||
#endif // #ifndef MISC_H_INCLUDED
|
|
||||||
|
|||||||
+152
@@ -0,0 +1,152 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include <cassert>
|
||||||
|
|
||||||
|
#include "move.h"
|
||||||
|
#include "piece.h"
|
||||||
|
#include "position.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
|
/// move_from_string() takes a position and a string as input, and attempts to
|
||||||
|
/// convert the string to a move, using simple coordinate notation (g1f3,
|
||||||
|
/// a7a8q, etc.). In order to correctly parse en passant captures and castling
|
||||||
|
/// moves, we need the position. This function is not robust, and expects that
|
||||||
|
/// the input move is legal and correctly formatted.
|
||||||
|
|
||||||
|
Move move_from_string(const Position& pos, const std::string& str) {
|
||||||
|
|
||||||
|
Square from, to;
|
||||||
|
Piece piece;
|
||||||
|
Color us = pos.side_to_move();
|
||||||
|
|
||||||
|
if (str.length() < 4)
|
||||||
|
return MOVE_NONE;
|
||||||
|
|
||||||
|
// Read the from and to squares
|
||||||
|
from = square_from_string(str.substr(0, 2));
|
||||||
|
to = square_from_string(str.substr(2, 4));
|
||||||
|
|
||||||
|
// Find the moving piece
|
||||||
|
piece = pos.piece_on(from);
|
||||||
|
|
||||||
|
// If the string has more than 4 characters, try to interpret the 5th
|
||||||
|
// character as a promotion
|
||||||
|
if (type_of_piece(piece) == PAWN && str.length() > 4)
|
||||||
|
{
|
||||||
|
switch (tolower(str[4])) {
|
||||||
|
case 'n':
|
||||||
|
return make_promotion_move(from, to, KNIGHT);
|
||||||
|
case 'b':
|
||||||
|
return make_promotion_move(from, to, BISHOP);
|
||||||
|
case 'r':
|
||||||
|
return make_promotion_move(from, to, ROOK);
|
||||||
|
case 'q':
|
||||||
|
return make_promotion_move(from, to, QUEEN);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (piece == piece_of_color_and_type(us, KING))
|
||||||
|
{
|
||||||
|
// Is this a castling move? A king move is assumed to be a castling
|
||||||
|
// move if the destination square is occupied by a friendly rook, or
|
||||||
|
// if the distance between the source and destination squares is more
|
||||||
|
// than 1.
|
||||||
|
if (pos.piece_on(to) == piece_of_color_and_type(us, ROOK))
|
||||||
|
return make_castle_move(from, to);
|
||||||
|
|
||||||
|
else if (square_distance(from, to) > 1)
|
||||||
|
{
|
||||||
|
// This is a castling move, but we have to translate it to the
|
||||||
|
// internal "king captures rook" representation.
|
||||||
|
SquareDelta delta = (to > from ? DELTA_E : DELTA_W);
|
||||||
|
Square s = from + delta;
|
||||||
|
while (relative_rank(us, s) == RANK_1 && pos.piece_on(s) != piece_of_color_and_type(us, ROOK))
|
||||||
|
s += delta;
|
||||||
|
|
||||||
|
return (relative_rank(us, s) == RANK_1 ? make_castle_move(from, s) : MOVE_NONE);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (piece == piece_of_color_and_type(us, PAWN))
|
||||||
|
{
|
||||||
|
// En passant move? We assume that a pawn move is an en passant move
|
||||||
|
// without further testing if the destination square is epSquare.
|
||||||
|
if (to == pos.ep_square())
|
||||||
|
return make_ep_move(from, to);
|
||||||
|
}
|
||||||
|
return make_move(from, to);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// move_to_string() converts a move to a string in coordinate notation
|
||||||
|
/// (g1f3, a7a8q, etc.). The only special case is castling moves, where we
|
||||||
|
/// print in the e1g1 notation in normal chess mode, and in e1h1 notation in
|
||||||
|
/// Chess960 mode.
|
||||||
|
|
||||||
|
const std::string move_to_string(Move move) {
|
||||||
|
|
||||||
|
std::string str;
|
||||||
|
Square from = move_from(move);
|
||||||
|
Square to = move_to(move);
|
||||||
|
|
||||||
|
if (move == MOVE_NONE)
|
||||||
|
str = "(none)";
|
||||||
|
else if (move == MOVE_NULL)
|
||||||
|
str = "0000";
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (!Chess960)
|
||||||
|
{
|
||||||
|
if (move_is_short_castle(move))
|
||||||
|
return (from == SQ_E1 ? "e1g1" : "e8g8");
|
||||||
|
|
||||||
|
if (move_is_long_castle(move))
|
||||||
|
return (from == SQ_E1 ? "e1c1" : "e8c8");
|
||||||
|
}
|
||||||
|
str = square_to_string(from) + square_to_string(to);
|
||||||
|
if (move_is_promotion(move))
|
||||||
|
str += piece_type_to_char(move_promotion_piece(move), false);
|
||||||
|
}
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Overload the << operator, to make it easier to print moves.
|
||||||
|
|
||||||
|
std::ostream &operator << (std::ostream& os, Move m) {
|
||||||
|
|
||||||
|
return os << move_to_string(m);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// move_is_ok(), for debugging.
|
||||||
|
|
||||||
|
bool move_is_ok(Move m) {
|
||||||
|
|
||||||
|
return square_is_ok(move_from(m)) && square_is_ok(move_to(m));
|
||||||
|
}
|
||||||
+230
@@ -0,0 +1,230 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
Stockfish is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
Stockfish is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
#if !defined(MOVE_H_INCLUDED)
|
||||||
|
#define MOVE_H_INCLUDED
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
|
#include "misc.h"
|
||||||
|
#include "piece.h"
|
||||||
|
#include "square.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Types
|
||||||
|
////
|
||||||
|
|
||||||
|
class Position;
|
||||||
|
|
||||||
|
/// A move needs 17 bits to be stored
|
||||||
|
///
|
||||||
|
/// bit 0- 5: destination square (from 0 to 63)
|
||||||
|
/// bit 6-11: origin square (from 0 to 63)
|
||||||
|
/// bit 12-14: promotion piece type
|
||||||
|
/// bit 15: en passant flag
|
||||||
|
/// bit 16: castle flag
|
||||||
|
///
|
||||||
|
/// Special cases are MOVE_NONE and MOVE_NULL. We can sneak these in
|
||||||
|
/// because in any normal move destination square is always different
|
||||||
|
/// from origin square while MOVE_NONE and MOVE_NULL have the same
|
||||||
|
/// origin and destination square, 0 and 1 respectively.
|
||||||
|
|
||||||
|
enum Move {
|
||||||
|
MOVE_NONE = 0,
|
||||||
|
MOVE_NULL = 65
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
struct MoveStack {
|
||||||
|
Move move;
|
||||||
|
int score;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Note that operator< is set up such that sorting will be in descending order
|
||||||
|
inline bool operator<(const MoveStack& f, const MoveStack& s) { return s.score < f.score; }
|
||||||
|
|
||||||
|
// An helper insertion sort implementation
|
||||||
|
template<typename T>
|
||||||
|
inline void insertion_sort(T* firstMove, T* lastMove)
|
||||||
|
{
|
||||||
|
T value;
|
||||||
|
T *cur, *p, *d;
|
||||||
|
|
||||||
|
if (firstMove != lastMove)
|
||||||
|
for (cur = firstMove + 1; cur != lastMove; cur++)
|
||||||
|
{
|
||||||
|
p = d = cur;
|
||||||
|
value = *p--;
|
||||||
|
if (value < *p)
|
||||||
|
{
|
||||||
|
do *d = *p;
|
||||||
|
while (--d != firstMove && value < *--p);
|
||||||
|
*d = value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Our dedicated sort in range [firstMove, lastMove), it is well
|
||||||
|
// tuned for non-captures where we have a lot of zero scored moves.
|
||||||
|
template<typename T>
|
||||||
|
inline void sort_moves(T* firstMove, T* lastMove)
|
||||||
|
{
|
||||||
|
T tmp;
|
||||||
|
T *p, *d;
|
||||||
|
|
||||||
|
d = lastMove;
|
||||||
|
p = firstMove - 1;
|
||||||
|
|
||||||
|
d->score = -1; // right guard
|
||||||
|
|
||||||
|
// Split positives vs non-positives
|
||||||
|
do {
|
||||||
|
while ((++p)->score > 0);
|
||||||
|
|
||||||
|
if (p != d)
|
||||||
|
{
|
||||||
|
while (--d != p && d->score <= 0);
|
||||||
|
|
||||||
|
tmp = *p;
|
||||||
|
*p = *d;
|
||||||
|
*d = tmp;
|
||||||
|
}
|
||||||
|
|
||||||
|
} while (p != d);
|
||||||
|
|
||||||
|
// Sort positives
|
||||||
|
insertion_sort<T>(firstMove, p);
|
||||||
|
|
||||||
|
d = lastMove;
|
||||||
|
p--;
|
||||||
|
|
||||||
|
// Split zero vs negatives
|
||||||
|
do {
|
||||||
|
while ((++p)->score == 0);
|
||||||
|
|
||||||
|
if (p != d)
|
||||||
|
{
|
||||||
|
while (--d != p && d->score < 0);
|
||||||
|
|
||||||
|
tmp = *p;
|
||||||
|
*p = *d;
|
||||||
|
*d = tmp;
|
||||||
|
}
|
||||||
|
|
||||||
|
} while (p != d);
|
||||||
|
|
||||||
|
// Sort negatives
|
||||||
|
insertion_sort<T>(p, lastMove);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Picks up the best move in range [curMove, lastMove), one per cycle.
|
||||||
|
// It is faster then sorting all the moves in advance when moves are few,
|
||||||
|
// as normally are the possible captures. Note that is not a stable alghoritm.
|
||||||
|
template<typename T>
|
||||||
|
inline T pick_best(T* curMove, T* lastMove)
|
||||||
|
{
|
||||||
|
T bestMove, tmp;
|
||||||
|
|
||||||
|
bestMove = *curMove;
|
||||||
|
while (++curMove != lastMove)
|
||||||
|
{
|
||||||
|
if (*curMove < bestMove)
|
||||||
|
{
|
||||||
|
tmp = *curMove;
|
||||||
|
*curMove = bestMove;
|
||||||
|
bestMove = tmp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bestMove;
|
||||||
|
}
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Inline functions
|
||||||
|
////
|
||||||
|
|
||||||
|
inline Square move_from(Move m) {
|
||||||
|
return Square((int(m) >> 6) & 0x3F);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Square move_to(Move m) {
|
||||||
|
return Square(m & 0x3F);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline PieceType move_promotion_piece(Move m) {
|
||||||
|
return PieceType((int(m) >> 12) & 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int move_is_special(Move m) {
|
||||||
|
return m & (0x1F << 12);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int move_is_promotion(Move m) {
|
||||||
|
return m & (7 << 12);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int move_is_ep(Move m) {
|
||||||
|
return m & (1 << 15);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int move_is_castle(Move m) {
|
||||||
|
return m & (1 << 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool move_is_short_castle(Move m) {
|
||||||
|
return move_is_castle(m) && (move_to(m) > move_from(m));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool move_is_long_castle(Move m) {
|
||||||
|
return move_is_castle(m) && (move_to(m) < move_from(m));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Move make_promotion_move(Square from, Square to, PieceType promotion) {
|
||||||
|
return Move(int(to) | (int(from) << 6) | (int(promotion) << 12));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Move make_move(Square from, Square to) {
|
||||||
|
return Move(int(to) | (int(from) << 6));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Move make_castle_move(Square from, Square to) {
|
||||||
|
return Move(int(to) | (int(from) << 6) | (1 << 16));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Move make_ep_move(Square from, Square to) {
|
||||||
|
return Move(int(to) | (int(from) << 6) | (1 << 15));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Prototypes
|
||||||
|
////
|
||||||
|
|
||||||
|
extern std::ostream& operator<<(std::ostream &os, Move m);
|
||||||
|
extern Move move_from_string(const Position &pos, const std::string &str);
|
||||||
|
extern const std::string move_to_string(Move m);
|
||||||
|
extern bool move_is_ok(Move m);
|
||||||
|
|
||||||
|
|
||||||
|
#endif // !defined(MOVE_H_INCLUDED)
|
||||||
+633
-196
@@ -1,6 +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-2024 The Stockfish developers (see AUTHORS file)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
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
|
||||||
@@ -16,241 +17,677 @@
|
|||||||
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 "movegen.h"
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
#include <initializer_list>
|
|
||||||
|
|
||||||
#include "bitboard.h"
|
#include "bitcount.h"
|
||||||
#include "position.h"
|
#include "movegen.h"
|
||||||
|
|
||||||
namespace Stockfish {
|
// Simple macro to wrap a very common while loop, no facny, no flexibility,
|
||||||
|
// hardcoded list name 'mlist' and from square 'from'.
|
||||||
|
#define SERIALIZE_MOVES(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
|
||||||
|
|
||||||
|
// Version used for pawns, where the 'from' square is given as a delta from the 'to' square
|
||||||
|
#define SERIALIZE_MOVES_D(b, d) while (b) { to = pop_1st_bit(&b); (*mlist++).move = make_move(to + (d), to); }
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Local definitions
|
||||||
|
////
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
template<GenType Type, Direction D, bool Enemy>
|
enum CastlingSide {
|
||||||
ExtMove* make_promotions(ExtMove* moveList, [[maybe_unused]] Square to) {
|
KING_SIDE,
|
||||||
|
QUEEN_SIDE
|
||||||
|
};
|
||||||
|
|
||||||
constexpr bool all = Type == EVASIONS || Type == NON_EVASIONS;
|
enum MoveType {
|
||||||
|
CAPTURE,
|
||||||
|
NON_CAPTURE,
|
||||||
|
CHECK,
|
||||||
|
EVASION
|
||||||
|
};
|
||||||
|
|
||||||
if constexpr (Type == CAPTURES || all)
|
// Helper templates
|
||||||
*moveList++ = Move::make<PROMOTION>(to - D, to, QUEEN);
|
template<CastlingSide Side>
|
||||||
|
MoveStack* generate_castle_moves(const Position&, MoveStack*);
|
||||||
|
|
||||||
if constexpr ((Type == CAPTURES && Enemy) || (Type == QUIETS && !Enemy) || all)
|
template<Color Us, MoveType Type>
|
||||||
{
|
MoveStack* generate_pawn_moves(const Position&, MoveStack*, Bitboard, Square);
|
||||||
*moveList++ = Move::make<PROMOTION>(to - D, to, ROOK);
|
|
||||||
*moveList++ = Move::make<PROMOTION>(to - D, to, BISHOP);
|
|
||||||
*moveList++ = Move::make<PROMOTION>(to - D, to, KNIGHT);
|
|
||||||
}
|
|
||||||
|
|
||||||
return moveList;
|
// Template generate_piece_moves (captures and non-captures) with specializations and overloads
|
||||||
|
template<PieceType>
|
||||||
|
MoveStack* generate_piece_moves(const Position&, MoveStack*, Color, Bitboard);
|
||||||
|
|
||||||
|
template<>
|
||||||
|
MoveStack* generate_piece_moves<KING>(const Position&, MoveStack*, Color, Bitboard);
|
||||||
|
|
||||||
|
template<PieceType Piece, MoveType Type>
|
||||||
|
inline MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us, Bitboard t) {
|
||||||
|
|
||||||
|
assert(Piece == PAWN);
|
||||||
|
assert(Type == CAPTURE || Type == NON_CAPTURE || Type == EVASION);
|
||||||
|
|
||||||
|
return (us == WHITE ? generate_pawn_moves<WHITE, Type>(p, m, t, SQ_NONE)
|
||||||
|
: generate_pawn_moves<BLACK, Type>(p, m, t, SQ_NONE));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Templates for non-capture checks generation
|
||||||
|
|
||||||
|
template<PieceType Piece>
|
||||||
|
MoveStack* generate_discovered_checks(const Position&, MoveStack*, Square);
|
||||||
|
|
||||||
|
template<PieceType>
|
||||||
|
MoveStack* generate_direct_checks(const Position&, MoveStack*, Color, Bitboard, Square);
|
||||||
|
|
||||||
|
template<>
|
||||||
|
inline MoveStack* generate_direct_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
|
||||||
|
|
||||||
|
return (us == WHITE ? generate_pawn_moves<WHITE, CHECK>(p, m, dc, ksq)
|
||||||
|
: generate_pawn_moves<BLACK, CHECK>(p, m, dc, ksq));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
template<Color Us, GenType Type>
|
////
|
||||||
ExtMove* generate_pawn_moves(const Position& pos, ExtMove* moveList, Bitboard target) {
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
constexpr Color Them = ~Us;
|
|
||||||
constexpr Bitboard TRank7BB = (Us == WHITE ? Rank7BB : Rank2BB);
|
|
||||||
constexpr Bitboard TRank3BB = (Us == WHITE ? Rank3BB : Rank6BB);
|
|
||||||
constexpr Direction Up = pawn_push(Us);
|
|
||||||
constexpr Direction UpRight = (Us == WHITE ? NORTH_EAST : SOUTH_WEST);
|
|
||||||
constexpr Direction UpLeft = (Us == WHITE ? NORTH_WEST : SOUTH_EAST);
|
|
||||||
|
|
||||||
const Bitboard emptySquares = ~pos.pieces();
|
/// generate_captures() generates all pseudo-legal captures and queen
|
||||||
const Bitboard enemies = Type == EVASIONS ? pos.checkers() : pos.pieces(Them);
|
/// promotions. Returns a pointer to the end of the move list.
|
||||||
|
|
||||||
Bitboard pawnsOn7 = pos.pieces(Us, PAWN) & TRank7BB;
|
MoveStack* generate_captures(const Position& pos, MoveStack* mlist) {
|
||||||
Bitboard pawnsNotOn7 = pos.pieces(Us, PAWN) & ~TRank7BB;
|
|
||||||
|
|
||||||
// Single and double pawn pushes, no promotions
|
assert(pos.is_ok());
|
||||||
if constexpr (Type != CAPTURES)
|
assert(!pos.is_check());
|
||||||
|
|
||||||
|
Color us = pos.side_to_move();
|
||||||
|
Bitboard target = pos.pieces_of_color(opposite_color(us));
|
||||||
|
|
||||||
|
mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
|
||||||
|
mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
|
||||||
|
mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
|
||||||
|
mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
|
||||||
|
mlist = generate_piece_moves<PAWN, CAPTURE>(pos, mlist, us, target);
|
||||||
|
return generate_piece_moves<KING>(pos, mlist, us, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// generate_noncaptures() generates all pseudo-legal non-captures and
|
||||||
|
/// underpromotions. Returns a pointer to the end of the move list.
|
||||||
|
|
||||||
|
MoveStack* generate_noncaptures(const Position& pos, MoveStack* mlist) {
|
||||||
|
|
||||||
|
assert(pos.is_ok());
|
||||||
|
assert(!pos.is_check());
|
||||||
|
|
||||||
|
Color us = pos.side_to_move();
|
||||||
|
Bitboard target = pos.empty_squares();
|
||||||
|
|
||||||
|
mlist = generate_piece_moves<PAWN, NON_CAPTURE>(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);
|
||||||
|
mlist = generate_castle_moves<KING_SIDE>(pos, mlist);
|
||||||
|
return generate_castle_moves<QUEEN_SIDE>(pos, mlist);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// generate_non_capture_checks() generates all pseudo-legal non-captures and knight
|
||||||
|
/// underpromotions that give check. Returns a pointer to the end of the move list.
|
||||||
|
|
||||||
|
MoveStack* generate_non_capture_checks(const Position& pos, MoveStack* mlist) {
|
||||||
|
|
||||||
|
assert(pos.is_ok());
|
||||||
|
assert(!pos.is_check());
|
||||||
|
|
||||||
|
Bitboard b, dc;
|
||||||
|
Square from;
|
||||||
|
Color us = pos.side_to_move();
|
||||||
|
Square ksq = pos.king_square(opposite_color(us));
|
||||||
|
|
||||||
|
assert(pos.piece_on(ksq) == piece_of_color_and_type(opposite_color(us), KING));
|
||||||
|
|
||||||
|
// Discovered non-capture checks
|
||||||
|
b = dc = pos.discovered_check_candidates(us);
|
||||||
|
|
||||||
|
while (b)
|
||||||
|
{
|
||||||
|
from = pop_1st_bit(&b);
|
||||||
|
switch (pos.type_of_piece_on(from))
|
||||||
|
{
|
||||||
|
case PAWN: /* Will be generated togheter with pawns direct checks */ break;
|
||||||
|
case KNIGHT: mlist = generate_discovered_checks<KNIGHT>(pos, mlist, from); break;
|
||||||
|
case BISHOP: mlist = generate_discovered_checks<BISHOP>(pos, mlist, from); break;
|
||||||
|
case ROOK: mlist = generate_discovered_checks<ROOK>(pos, mlist, from); break;
|
||||||
|
case KING: mlist = generate_discovered_checks<KING>(pos, mlist, from); break;
|
||||||
|
default: assert(false); break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Direct non-capture checks
|
||||||
|
mlist = generate_direct_checks<PAWN>(pos, mlist, us, dc, ksq);
|
||||||
|
mlist = generate_direct_checks<KNIGHT>(pos, mlist, us, dc, ksq);
|
||||||
|
mlist = generate_direct_checks<BISHOP>(pos, mlist, us, dc, ksq);
|
||||||
|
mlist = generate_direct_checks<ROOK>(pos, mlist, us, dc, ksq);
|
||||||
|
return generate_direct_checks<QUEEN>(pos, mlist, us, dc, ksq);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// 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.
|
||||||
|
|
||||||
|
MoveStack* generate_evasions(const Position& pos, MoveStack* mlist) {
|
||||||
|
|
||||||
|
assert(pos.is_ok());
|
||||||
|
assert(pos.is_check());
|
||||||
|
|
||||||
|
Bitboard b, target;
|
||||||
|
Square from, checksq;
|
||||||
|
int checkersCnt = 0;
|
||||||
|
Color us = pos.side_to_move();
|
||||||
|
Square ksq = pos.king_square(us);
|
||||||
|
Bitboard checkers = pos.checkers();
|
||||||
|
Bitboard sliderAttacks = EmptyBoardBB;
|
||||||
|
|
||||||
|
assert(pos.piece_on(ksq) == piece_of_color_and_type(us, KING));
|
||||||
|
assert(checkers);
|
||||||
|
|
||||||
|
// Find squares attacked by slider checkers, we will remove
|
||||||
|
// them from the king evasions set so to early skip known
|
||||||
|
// illegal moves and avoid an useless legality check later.
|
||||||
|
b = checkers;
|
||||||
|
do
|
||||||
|
{
|
||||||
|
checkersCnt++;
|
||||||
|
checksq = pop_1st_bit(&b);
|
||||||
|
|
||||||
|
assert(pos.color_of_piece_on(checksq) == opposite_color(us));
|
||||||
|
|
||||||
|
switch (pos.type_of_piece_on(checksq))
|
||||||
|
{
|
||||||
|
case BISHOP: sliderAttacks |= BishopPseudoAttacks[checksq]; break;
|
||||||
|
case ROOK: sliderAttacks |= RookPseudoAttacks[checksq]; break;
|
||||||
|
case QUEEN:
|
||||||
|
// In case of a queen remove also squares attacked in the other direction to
|
||||||
|
// avoid possible illegal moves when queen and king are on adjacent squares.
|
||||||
|
if (direction_is_straight(checksq, ksq))
|
||||||
|
sliderAttacks |= RookPseudoAttacks[checksq] | pos.attacks_from<BISHOP>(checksq);
|
||||||
|
else
|
||||||
|
sliderAttacks |= BishopPseudoAttacks[checksq] | pos.attacks_from<ROOK>(checksq);
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} while (b);
|
||||||
|
|
||||||
|
// Generate evasions for king, capture and non capture moves
|
||||||
|
b = pos.attacks_from<KING>(ksq) & ~pos.pieces_of_color(us) & ~sliderAttacks;
|
||||||
|
from = ksq;
|
||||||
|
SERIALIZE_MOVES(b);
|
||||||
|
|
||||||
|
// Generate evasions for other pieces only if not double check
|
||||||
|
if (checkersCnt > 1)
|
||||||
|
return mlist;
|
||||||
|
|
||||||
|
// Find squares where a blocking evasion or a capture of the
|
||||||
|
// checker piece is possible.
|
||||||
|
target = squares_between(checksq, ksq) | checkers;
|
||||||
|
|
||||||
|
mlist = generate_piece_moves<PAWN, EVASION>(pos, mlist, us, target);
|
||||||
|
mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
|
||||||
|
mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
|
||||||
|
mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
|
||||||
|
return generate_piece_moves<QUEEN>(pos, mlist, us, target);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// generate_moves() computes a complete list of legal or pseudo-legal moves in
|
||||||
|
/// the current position. This function is not very fast, and should be used
|
||||||
|
/// only in non time-critical paths.
|
||||||
|
|
||||||
|
MoveStack* generate_moves(const Position& pos, MoveStack* mlist, bool pseudoLegal) {
|
||||||
|
|
||||||
|
assert(pos.is_ok());
|
||||||
|
|
||||||
|
MoveStack *last, *cur = mlist;
|
||||||
|
Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
|
||||||
|
|
||||||
|
// Generate pseudo-legal moves
|
||||||
|
if (pos.is_check())
|
||||||
|
last = generate_evasions(pos, mlist);
|
||||||
|
else
|
||||||
|
last = generate_noncaptures(pos, generate_captures(pos, mlist));
|
||||||
|
|
||||||
|
if (pseudoLegal)
|
||||||
|
return last;
|
||||||
|
|
||||||
|
// Remove illegal moves from the list
|
||||||
|
while (cur != last)
|
||||||
|
if (pos.pl_move_is_legal(cur->move, pinned))
|
||||||
|
cur++;
|
||||||
|
else
|
||||||
|
cur->move = (--last)->move;
|
||||||
|
|
||||||
|
return last;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// move_is_legal() takes a position and a (not necessarily pseudo-legal)
|
||||||
|
/// move and tests whether the move is legal. This version is not very fast
|
||||||
|
/// and should be used only in non time-critical paths.
|
||||||
|
|
||||||
|
bool move_is_legal(const Position& pos, const Move m) {
|
||||||
|
|
||||||
|
MoveStack mlist[256];
|
||||||
|
MoveStack *cur, *last = generate_moves(pos, mlist, true);
|
||||||
|
|
||||||
|
for (cur = mlist; cur != last; cur++)
|
||||||
|
if (cur->move == m)
|
||||||
|
return pos.pl_move_is_legal(m, pos.pinned_pieces(pos.side_to_move()));
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Fast version of move_is_legal() that takes a position a move and a
|
||||||
|
/// bitboard of pinned pieces as input, and tests whether the move is legal.
|
||||||
|
|
||||||
|
bool move_is_legal(const Position& pos, const Move m, Bitboard pinned) {
|
||||||
|
|
||||||
|
assert(pos.is_ok());
|
||||||
|
assert(move_is_ok(m));
|
||||||
|
assert(pinned == pos.pinned_pieces(pos.side_to_move()));
|
||||||
|
|
||||||
|
Color us = pos.side_to_move();
|
||||||
|
Color them = opposite_color(us);
|
||||||
|
Square from = move_from(m);
|
||||||
|
Square to = move_to(m);
|
||||||
|
Piece pc = pos.piece_on(from);
|
||||||
|
|
||||||
|
// Use a slower but simpler function for uncommon cases
|
||||||
|
if (move_is_ep(m) || move_is_castle(m))
|
||||||
|
return move_is_legal(pos, m);
|
||||||
|
|
||||||
|
// If the from square is not occupied by a piece belonging to the side to
|
||||||
|
// move, the move is obviously not legal.
|
||||||
|
if (color_of_piece(pc) != us)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
// The destination square cannot be occupied by a friendly piece
|
||||||
|
if (pos.color_of_piece_on(to) == us)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
// Handle the special case of a pawn move
|
||||||
|
if (type_of_piece(pc) == PAWN)
|
||||||
|
{
|
||||||
|
// Move direction must be compatible with pawn color
|
||||||
|
int direction = to - from;
|
||||||
|
if ((us == WHITE) != (direction > 0))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
// A pawn move is a promotion iff the destination square is
|
||||||
|
// on the 8/1th rank.
|
||||||
|
if (( (square_rank(to) == RANK_8 && us == WHITE)
|
||||||
|
||(square_rank(to) == RANK_1 && us != WHITE)) != bool(move_is_promotion(m)))
|
||||||
|
return false;
|
||||||
|
|
||||||
|
// Proceed according to the square delta between the origin and
|
||||||
|
// destination squares.
|
||||||
|
switch (direction)
|
||||||
|
{
|
||||||
|
case DELTA_NW:
|
||||||
|
case DELTA_NE:
|
||||||
|
case DELTA_SW:
|
||||||
|
case DELTA_SE:
|
||||||
|
// Capture. The destination square must be occupied by an enemy
|
||||||
|
// piece (en passant captures was handled earlier).
|
||||||
|
if (pos.color_of_piece_on(to) != them)
|
||||||
|
return false;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case DELTA_N:
|
||||||
|
case DELTA_S:
|
||||||
|
// Pawn push. The destination square must be empty.
|
||||||
|
if (!pos.square_is_empty(to))
|
||||||
|
return false;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case DELTA_NN:
|
||||||
|
// Double white pawn push. The destination square must be on the fourth
|
||||||
|
// rank, and both the destination square and the square between the
|
||||||
|
// source and destination squares must be empty.
|
||||||
|
if ( square_rank(to) != RANK_4
|
||||||
|
|| !pos.square_is_empty(to)
|
||||||
|
|| !pos.square_is_empty(from + DELTA_N))
|
||||||
|
return false;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case DELTA_SS:
|
||||||
|
// Double black pawn push. The destination square must be on the fifth
|
||||||
|
// rank, and both the destination square and the square between the
|
||||||
|
// source and destination squares must be empty.
|
||||||
|
if ( square_rank(to) != RANK_5
|
||||||
|
|| !pos.square_is_empty(to)
|
||||||
|
|| !pos.square_is_empty(from + DELTA_S))
|
||||||
|
return false;
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// The move is pseudo-legal, check if it is also legal
|
||||||
|
return pos.is_check() ? pos.pl_move_is_evasion(m, pinned) : pos.pl_move_is_legal(m, pinned);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Luckly we can handle all the other pieces in one go
|
||||||
|
return bit_is_set(pos.attacks_from(pc, from), to)
|
||||||
|
&& (pos.is_check() ? pos.pl_move_is_evasion(m, pinned) : pos.pl_move_is_legal(m, pinned))
|
||||||
|
&& !move_is_promotion(m);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
template<PieceType Piece>
|
||||||
|
MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
|
||||||
|
|
||||||
|
Bitboard b;
|
||||||
|
Square from;
|
||||||
|
const Square* ptr = pos.piece_list_begin(us, Piece);
|
||||||
|
|
||||||
|
while ((from = *ptr++) != SQ_NONE)
|
||||||
{
|
{
|
||||||
Bitboard b1 = shift<Up>(pawnsNotOn7) & emptySquares;
|
b = pos.attacks_from<Piece>(from) & target;
|
||||||
Bitboard b2 = shift<Up>(b1 & TRank3BB) & emptySquares;
|
SERIALIZE_MOVES(b);
|
||||||
|
}
|
||||||
|
return mlist;
|
||||||
|
}
|
||||||
|
|
||||||
if constexpr (Type == EVASIONS) // Consider only blocking squares
|
template<>
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<Color Us, SquareDelta Direction>
|
||||||
|
inline Bitboard move_pawns(Bitboard p) {
|
||||||
|
|
||||||
|
if (Direction == DELTA_N)
|
||||||
|
return Us == WHITE ? p << 8 : p >> 8;
|
||||||
|
else if (Direction == DELTA_NE)
|
||||||
|
return Us == WHITE ? p << 9 : p >> 7;
|
||||||
|
else if (Direction == DELTA_NW)
|
||||||
|
return Us == WHITE ? p << 7 : p >> 9;
|
||||||
|
else
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
template<Color Us, MoveType Type, SquareDelta Diagonal>
|
||||||
|
inline MoveStack* generate_pawn_captures(MoveStack* mlist, Bitboard pawns, Bitboard enemyPieces) {
|
||||||
|
|
||||||
|
// Calculate our parametrized parameters at compile time
|
||||||
|
const Bitboard TRank8BB = (Us == WHITE ? Rank8BB : Rank1BB);
|
||||||
|
const Bitboard TFileABB = (Diagonal == DELTA_NE ? FileABB : FileHBB);
|
||||||
|
const SquareDelta TDELTA_NE = (Us == WHITE ? DELTA_NE : DELTA_SE);
|
||||||
|
const SquareDelta TDELTA_NW = (Us == WHITE ? DELTA_NW : DELTA_SW);
|
||||||
|
const SquareDelta TTDELTA_NE = (Diagonal == DELTA_NE ? TDELTA_NE : TDELTA_NW);
|
||||||
|
|
||||||
|
Bitboard b1, b2;
|
||||||
|
Square to;
|
||||||
|
|
||||||
|
// Captures in the a1-h8 (a8-h1 for black) diagonal or in the h1-a8 (h8-a1 for black)
|
||||||
|
b1 = move_pawns<Us, Diagonal>(pawns) & ~TFileABB & enemyPieces;
|
||||||
|
|
||||||
|
// Capturing promotions and under-promotions
|
||||||
|
if (b1 & TRank8BB)
|
||||||
|
{
|
||||||
|
b2 = b1 & TRank8BB;
|
||||||
|
b1 &= ~TRank8BB;
|
||||||
|
while (b2)
|
||||||
|
{
|
||||||
|
to = pop_1st_bit(&b2);
|
||||||
|
|
||||||
|
if (Type == CAPTURE || Type == EVASION)
|
||||||
|
(*mlist++).move = make_promotion_move(to - TTDELTA_NE, to, QUEEN);
|
||||||
|
|
||||||
|
if (Type == NON_CAPTURE || Type == EVASION)
|
||||||
|
{
|
||||||
|
(*mlist++).move = make_promotion_move(to - TTDELTA_NE, to, ROOK);
|
||||||
|
(*mlist++).move = make_promotion_move(to - TTDELTA_NE, to, BISHOP);
|
||||||
|
(*mlist++).move = make_promotion_move(to - TTDELTA_NE, to, KNIGHT);
|
||||||
|
}
|
||||||
|
|
||||||
|
// This is the only possible under promotion that can give a check
|
||||||
|
// not already included in the queen-promotion. It is not sure that
|
||||||
|
// the promoted knight will give check, but it doesn't worth to verify.
|
||||||
|
if (Type == CHECK)
|
||||||
|
(*mlist++).move = make_promotion_move(to - TTDELTA_NE, to, KNIGHT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Serialize standard captures
|
||||||
|
if (Type == CAPTURE || Type == EVASION)
|
||||||
|
SERIALIZE_MOVES_D(b1, -TTDELTA_NE);
|
||||||
|
|
||||||
|
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
|
||||||
|
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 SquareDelta TDELTA_N = (Us == WHITE ? DELTA_N : DELTA_S);
|
||||||
|
|
||||||
|
Square to;
|
||||||
|
Bitboard b1, b2, enemyPieces, emptySquares;
|
||||||
|
Bitboard pawns = pos.pieces(PAWN, Us);
|
||||||
|
|
||||||
|
// Standard captures and capturing promotions and underpromotions
|
||||||
|
if (Type == CAPTURE || Type == EVASION || (pawns & TRank7BB))
|
||||||
|
{
|
||||||
|
enemyPieces = (Type == CAPTURE ? target : pos.pieces_of_color(opposite_color(Us)));
|
||||||
|
|
||||||
|
if (Type == EVASION)
|
||||||
|
enemyPieces &= target; // Capture only the checker piece
|
||||||
|
|
||||||
|
mlist = generate_pawn_captures<Us, Type, DELTA_NE>(mlist, pawns, enemyPieces);
|
||||||
|
mlist = generate_pawn_captures<Us, Type, DELTA_NW>(mlist, pawns, enemyPieces);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Non-capturing promotions and underpromotions
|
||||||
|
if (pawns & TRank7BB)
|
||||||
|
{
|
||||||
|
b1 = move_pawns<Us, DELTA_N>(pawns) & TRank8BB & pos.empty_squares();
|
||||||
|
|
||||||
|
if (Type == EVASION)
|
||||||
|
b1 &= target; // Only blocking promotion pushes
|
||||||
|
|
||||||
|
while (b1)
|
||||||
|
{
|
||||||
|
to = pop_1st_bit(&b1);
|
||||||
|
|
||||||
|
if (Type == CAPTURE || Type == EVASION)
|
||||||
|
(*mlist++).move = make_promotion_move(to - TDELTA_N, to, QUEEN);
|
||||||
|
|
||||||
|
if (Type == NON_CAPTURE || Type == EVASION)
|
||||||
|
{
|
||||||
|
(*mlist++).move = make_promotion_move(to - TDELTA_N, to, ROOK);
|
||||||
|
(*mlist++).move = make_promotion_move(to - TDELTA_N, to, BISHOP);
|
||||||
|
(*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
|
||||||
|
}
|
||||||
|
|
||||||
|
// This is the only possible under promotion that can give a check
|
||||||
|
// not already included in the queen-promotion.
|
||||||
|
if (Type == CHECK && bit_is_set(pos.attacks_from<KNIGHT>(to), pos.king_square(Them)))
|
||||||
|
(*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Standard pawn pushes and double pushes
|
||||||
|
if (Type != CAPTURE)
|
||||||
|
{
|
||||||
|
emptySquares = (Type == NON_CAPTURE ? target : pos.empty_squares());
|
||||||
|
|
||||||
|
// Single and double pawn pushes
|
||||||
|
b1 = move_pawns<Us, DELTA_N>(pawns) & emptySquares & ~TRank8BB;
|
||||||
|
b2 = move_pawns<Us, DELTA_N>(b1 & TRank3BB) & emptySquares;
|
||||||
|
|
||||||
|
// Filter out unwanted pushes according to the move type
|
||||||
|
if (Type == EVASION)
|
||||||
{
|
{
|
||||||
b1 &= target;
|
b1 &= target;
|
||||||
b2 &= target;
|
b2 &= target;
|
||||||
}
|
}
|
||||||
|
else if (Type == CHECK)
|
||||||
|
{
|
||||||
|
// Pawn moves which give direct cheks
|
||||||
|
b1 &= pos.attacks_from<PAWN>(ksq, Them);
|
||||||
|
b2 &= pos.attacks_from<PAWN>(ksq, Them);
|
||||||
|
|
||||||
|
// 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
|
||||||
|
{
|
||||||
|
Bitboard dc1 = move_pawns<Us, DELTA_N>(pawns & target & ~file_bb(ksq)) & emptySquares & ~TRank8BB;
|
||||||
|
Bitboard dc2 = move_pawns<Us, DELTA_N>(dc1 & TRank3BB) & emptySquares;
|
||||||
|
|
||||||
|
b1 |= dc1;
|
||||||
|
b2 |= dc2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SERIALIZE_MOVES_D(b1, -TDELTA_N);
|
||||||
|
SERIALIZE_MOVES_D(b2, -TDELTA_N -TDELTA_N);
|
||||||
|
}
|
||||||
|
|
||||||
|
// En passant captures
|
||||||
|
if ((Type == CAPTURE || Type == EVASION) && pos.ep_square() != SQ_NONE)
|
||||||
|
{
|
||||||
|
assert(Us != WHITE || square_rank(pos.ep_square()) == RANK_6);
|
||||||
|
assert(Us != BLACK || square_rank(pos.ep_square()) == RANK_3);
|
||||||
|
|
||||||
|
// An en passant capture can be an evasion only if the checking piece
|
||||||
|
// is the double pushed pawn and so is in the target. Otherwise this
|
||||||
|
// is a discovery check and we are forced to do otherwise.
|
||||||
|
if (Type == EVASION && !bit_is_set(target, pos.ep_square() - TDELTA_N))
|
||||||
|
return mlist;
|
||||||
|
|
||||||
|
b1 = pawns & pos.attacks_from<PAWN>(pos.ep_square(), Them);
|
||||||
|
|
||||||
|
assert(b1 != EmptyBoardBB);
|
||||||
|
|
||||||
while (b1)
|
while (b1)
|
||||||
{
|
{
|
||||||
Square to = pop_lsb(b1);
|
to = pop_1st_bit(&b1);
|
||||||
*moveList++ = Move(to - Up, to);
|
(*mlist++).move = make_ep_move(to, pos.ep_square());
|
||||||
}
|
|
||||||
|
|
||||||
while (b2)
|
|
||||||
{
|
|
||||||
Square to = pop_lsb(b2);
|
|
||||||
*moveList++ = Move(to - Up - Up, to);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return mlist;
|
||||||
|
}
|
||||||
|
|
||||||
// Promotions and underpromotions
|
template<PieceType Piece>
|
||||||
if (pawnsOn7)
|
MoveStack* generate_discovered_checks(const Position& pos, MoveStack* mlist, Square from) {
|
||||||
|
|
||||||
|
assert(Piece != QUEEN);
|
||||||
|
|
||||||
|
Bitboard b = pos.attacks_from<Piece>(from) & pos.empty_squares();
|
||||||
|
if (Piece == KING)
|
||||||
{
|
{
|
||||||
Bitboard b1 = shift<UpRight>(pawnsOn7) & enemies;
|
Square ksq = pos.king_square(opposite_color(pos.side_to_move()));
|
||||||
Bitboard b2 = shift<UpLeft>(pawnsOn7) & enemies;
|
b &= ~QueenPseudoAttacks[ksq];
|
||||||
Bitboard b3 = shift<Up>(pawnsOn7) & emptySquares;
|
|
||||||
|
|
||||||
if constexpr (Type == EVASIONS)
|
|
||||||
b3 &= target;
|
|
||||||
|
|
||||||
while (b1)
|
|
||||||
moveList = make_promotions<Type, UpRight, true>(moveList, pop_lsb(b1));
|
|
||||||
|
|
||||||
while (b2)
|
|
||||||
moveList = make_promotions<Type, UpLeft, true>(moveList, pop_lsb(b2));
|
|
||||||
|
|
||||||
while (b3)
|
|
||||||
moveList = make_promotions<Type, Up, false>(moveList, pop_lsb(b3));
|
|
||||||
}
|
}
|
||||||
|
SERIALIZE_MOVES(b);
|
||||||
|
return mlist;
|
||||||
|
}
|
||||||
|
|
||||||
// Standard and en passant captures
|
template<PieceType Piece>
|
||||||
if constexpr (Type == CAPTURES || Type == EVASIONS || Type == NON_EVASIONS)
|
MoveStack* generate_direct_checks(const Position& pos, MoveStack* mlist, Color us,
|
||||||
|
Bitboard dc, Square ksq) {
|
||||||
|
assert(Piece != KING);
|
||||||
|
|
||||||
|
Bitboard checkSqs, b;
|
||||||
|
Square from;
|
||||||
|
const Square* ptr = pos.piece_list_begin(us, Piece);
|
||||||
|
|
||||||
|
if ((from = *ptr++) == SQ_NONE)
|
||||||
|
return mlist;
|
||||||
|
|
||||||
|
checkSqs = pos.attacks_from<Piece>(ksq) & pos.empty_squares();
|
||||||
|
|
||||||
|
do
|
||||||
{
|
{
|
||||||
Bitboard b1 = shift<UpRight>(pawnsNotOn7) & enemies;
|
if ( (Piece == QUEEN && !(QueenPseudoAttacks[from] & checkSqs))
|
||||||
Bitboard b2 = shift<UpLeft>(pawnsNotOn7) & enemies;
|
|| (Piece == ROOK && !(RookPseudoAttacks[from] & checkSqs))
|
||||||
|
|| (Piece == BISHOP && !(BishopPseudoAttacks[from] & checkSqs)))
|
||||||
|
continue;
|
||||||
|
|
||||||
while (b1)
|
if (dc && bit_is_set(dc, from))
|
||||||
{
|
continue;
|
||||||
Square to = pop_lsb(b1);
|
|
||||||
*moveList++ = Move(to - UpRight, to);
|
|
||||||
}
|
|
||||||
|
|
||||||
while (b2)
|
b = pos.attacks_from<Piece>(from) & checkSqs;
|
||||||
{
|
SERIALIZE_MOVES(b);
|
||||||
Square to = pop_lsb(b2);
|
|
||||||
*moveList++ = Move(to - UpLeft, to);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (pos.ep_square() != SQ_NONE)
|
} while ((from = *ptr++) != SQ_NONE);
|
||||||
{
|
|
||||||
assert(rank_of(pos.ep_square()) == relative_rank(Us, RANK_6));
|
|
||||||
|
|
||||||
// An en passant capture cannot resolve a discovered check
|
return mlist;
|
||||||
if (Type == EVASIONS && (target & (pos.ep_square() + Up)))
|
}
|
||||||
return moveList;
|
|
||||||
|
|
||||||
b1 = pawnsNotOn7 & pawn_attacks_bb(Them, pos.ep_square());
|
template<CastlingSide Side>
|
||||||
|
MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist) {
|
||||||
assert(b1);
|
|
||||||
|
|
||||||
while (b1)
|
|
||||||
*moveList++ = Move::make<EN_PASSANT>(pop_lsb(b1), pos.ep_square());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return moveList;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
template<Color Us, PieceType Pt>
|
|
||||||
ExtMove* generate_moves(const Position& pos, ExtMove* moveList, Bitboard target) {
|
|
||||||
|
|
||||||
static_assert(Pt != KING && Pt != PAWN, "Unsupported piece type in generate_moves()");
|
|
||||||
|
|
||||||
Bitboard bb = pos.pieces(Us, Pt);
|
|
||||||
|
|
||||||
while (bb)
|
|
||||||
{
|
|
||||||
Square from = pop_lsb(bb);
|
|
||||||
Bitboard b = attacks_bb<Pt>(from, pos.pieces()) & target;
|
|
||||||
|
|
||||||
while (b)
|
|
||||||
*moveList++ = Move(from, pop_lsb(b));
|
|
||||||
}
|
|
||||||
|
|
||||||
return moveList;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
template<Color Us, GenType Type>
|
|
||||||
ExtMove* generate_all(const Position& pos, ExtMove* moveList) {
|
|
||||||
|
|
||||||
static_assert(Type != LEGAL, "Unsupported type in generate_all()");
|
|
||||||
|
|
||||||
const Square ksq = pos.square<KING>(Us);
|
|
||||||
Bitboard target;
|
|
||||||
|
|
||||||
// Skip generating non-king moves when in double check
|
|
||||||
if (Type != EVASIONS || !more_than_one(pos.checkers()))
|
|
||||||
{
|
|
||||||
target = Type == EVASIONS ? between_bb(ksq, lsb(pos.checkers()))
|
|
||||||
: Type == NON_EVASIONS ? ~pos.pieces(Us)
|
|
||||||
: Type == CAPTURES ? pos.pieces(~Us)
|
|
||||||
: ~pos.pieces(); // QUIETS
|
|
||||||
|
|
||||||
moveList = generate_pawn_moves<Us, Type>(pos, moveList, target);
|
|
||||||
moveList = generate_moves<Us, KNIGHT>(pos, moveList, target);
|
|
||||||
moveList = generate_moves<Us, BISHOP>(pos, moveList, target);
|
|
||||||
moveList = generate_moves<Us, ROOK>(pos, moveList, target);
|
|
||||||
moveList = generate_moves<Us, QUEEN>(pos, moveList, target);
|
|
||||||
}
|
|
||||||
|
|
||||||
Bitboard b = attacks_bb<KING>(ksq) & (Type == EVASIONS ? ~pos.pieces(Us) : target);
|
|
||||||
|
|
||||||
while (b)
|
|
||||||
*moveList++ = Move(ksq, pop_lsb(b));
|
|
||||||
|
|
||||||
if ((Type == QUIETS || Type == NON_EVASIONS) && pos.can_castle(Us & ANY_CASTLING))
|
|
||||||
for (CastlingRights cr : {Us & KING_SIDE, Us & QUEEN_SIDE})
|
|
||||||
if (!pos.castling_impeded(cr) && pos.can_castle(cr))
|
|
||||||
*moveList++ = Move::make<CASTLING>(ksq, pos.castling_rook_square(cr));
|
|
||||||
|
|
||||||
return moveList;
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace
|
|
||||||
|
|
||||||
|
|
||||||
// <CAPTURES> Generates all pseudo-legal captures plus queen promotions
|
|
||||||
// <QUIETS> Generates all pseudo-legal non-captures and underpromotions
|
|
||||||
// <EVASIONS> Generates all pseudo-legal check evasions
|
|
||||||
// <NON_EVASIONS> Generates all pseudo-legal captures and non-captures
|
|
||||||
//
|
|
||||||
// Returns a pointer to the end of the move list.
|
|
||||||
template<GenType Type>
|
|
||||||
ExtMove* generate(const Position& pos, ExtMove* moveList) {
|
|
||||||
|
|
||||||
static_assert(Type != LEGAL, "Unsupported type in generate()");
|
|
||||||
assert((Type == EVASIONS) == bool(pos.checkers()));
|
|
||||||
|
|
||||||
Color us = pos.side_to_move();
|
Color us = pos.side_to_move();
|
||||||
|
|
||||||
return us == WHITE ? generate_all<WHITE, Type>(pos, moveList)
|
if ( (Side == KING_SIDE && pos.can_castle_kingside(us))
|
||||||
: generate_all<BLACK, Type>(pos, moveList);
|
||(Side == QUEEN_SIDE && pos.can_castle_queenside(us)))
|
||||||
|
{
|
||||||
|
Color them = opposite_color(us);
|
||||||
|
Square ksq = pos.king_square(us);
|
||||||
|
|
||||||
|
assert(pos.piece_on(ksq) == piece_of_color_and_type(us, KING));
|
||||||
|
|
||||||
|
Square rsq = (Side == KING_SIDE ? pos.initial_kr_square(us) : pos.initial_qr_square(us));
|
||||||
|
Square s1 = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
|
||||||
|
Square s2 = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
|
||||||
|
Square s;
|
||||||
|
bool illegal = false;
|
||||||
|
|
||||||
|
assert(pos.piece_on(rsq) == piece_of_color_and_type(us, ROOK));
|
||||||
|
|
||||||
|
// It is a bit complicated to correctly handle Chess960
|
||||||
|
for (s = Min(ksq, s1); s <= Max(ksq, s1); s++)
|
||||||
|
if ( (s != ksq && s != rsq && pos.square_is_occupied(s))
|
||||||
|
||(pos.attackers_to(s) & pos.pieces_of_color(them)))
|
||||||
|
illegal = true;
|
||||||
|
|
||||||
|
for (s = Min(rsq, s2); s <= Max(rsq, s2); s++)
|
||||||
|
if (s != ksq && s != rsq && pos.square_is_occupied(s))
|
||||||
|
illegal = true;
|
||||||
|
|
||||||
|
if ( Side == QUEEN_SIDE
|
||||||
|
&& square_file(rsq) == FILE_B
|
||||||
|
&& ( pos.piece_on(relative_square(us, SQ_A1)) == piece_of_color_and_type(them, ROOK)
|
||||||
|
|| pos.piece_on(relative_square(us, SQ_A1)) == piece_of_color_and_type(them, QUEEN)))
|
||||||
|
illegal = true;
|
||||||
|
|
||||||
|
if (!illegal)
|
||||||
|
(*mlist++).move = make_castle_move(ksq, rsq);
|
||||||
|
}
|
||||||
|
return mlist;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Explicit template instantiations
|
|
||||||
template ExtMove* generate<CAPTURES>(const Position&, ExtMove*);
|
|
||||||
template ExtMove* generate<QUIETS>(const Position&, ExtMove*);
|
|
||||||
template ExtMove* generate<EVASIONS>(const Position&, ExtMove*);
|
|
||||||
template ExtMove* generate<NON_EVASIONS>(const Position&, ExtMove*);
|
|
||||||
|
|
||||||
|
|
||||||
// generate<LEGAL> generates all the legal moves in the given position
|
|
||||||
|
|
||||||
template<>
|
|
||||||
ExtMove* generate<LEGAL>(const Position& pos, ExtMove* moveList) {
|
|
||||||
|
|
||||||
Color us = pos.side_to_move();
|
|
||||||
Bitboard pinned = pos.blockers_for_king(us) & pos.pieces(us);
|
|
||||||
Square ksq = pos.square<KING>(us);
|
|
||||||
ExtMove* cur = moveList;
|
|
||||||
|
|
||||||
moveList =
|
|
||||||
pos.checkers() ? generate<EVASIONS>(pos, moveList) : generate<NON_EVASIONS>(pos, moveList);
|
|
||||||
while (cur != moveList)
|
|
||||||
if (((pinned & cur->from_sq()) || cur->from_sq() == ksq || cur->type_of() == EN_PASSANT)
|
|
||||||
&& !pos.legal(*cur))
|
|
||||||
*cur = *(--moveList);
|
|
||||||
else
|
|
||||||
++cur;
|
|
||||||
|
|
||||||
return moveList;
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Stockfish
|
|
||||||
|
|||||||
+19
-48
@@ -1,6 +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-2024 The Stockfish developers (see AUTHORS file)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
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
|
||||||
@@ -16,58 +17,28 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#ifndef MOVEGEN_H_INCLUDED
|
|
||||||
|
#if !defined(MOVEGEN_H_INCLUDED)
|
||||||
#define MOVEGEN_H_INCLUDED
|
#define MOVEGEN_H_INCLUDED
|
||||||
|
|
||||||
#include <algorithm> // IWYU pragma: keep
|
////
|
||||||
#include <cstddef>
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
#include "types.h"
|
#include "position.h"
|
||||||
|
|
||||||
namespace Stockfish {
|
|
||||||
|
|
||||||
class Position;
|
////
|
||||||
|
//// Prototypes
|
||||||
|
////
|
||||||
|
|
||||||
enum GenType {
|
extern MoveStack* generate_captures(const Position& pos, MoveStack* mlist);
|
||||||
CAPTURES,
|
extern MoveStack* generate_noncaptures(const Position& pos, MoveStack* mlist);
|
||||||
QUIETS,
|
extern MoveStack* generate_non_capture_checks(const Position& pos, MoveStack* mlist);
|
||||||
EVASIONS,
|
extern MoveStack* generate_evasions(const Position& pos, MoveStack* mlist);
|
||||||
NON_EVASIONS,
|
extern MoveStack* generate_moves(const Position& pos, MoveStack* mlist, bool pseudoLegal = false);
|
||||||
LEGAL
|
extern bool move_is_legal(const Position& pos, const Move m, Bitboard pinned);
|
||||||
};
|
extern bool move_is_legal(const Position& pos, const Move m);
|
||||||
|
|
||||||
struct ExtMove: public Move {
|
|
||||||
int value;
|
|
||||||
|
|
||||||
void operator=(Move m) { data = m.raw(); }
|
#endif // !defined(MOVEGEN_H_INCLUDED)
|
||||||
|
|
||||||
// Inhibit unwanted implicit conversions to Move
|
|
||||||
// with an ambiguity that yields to a compile error.
|
|
||||||
operator float() const = delete;
|
|
||||||
};
|
|
||||||
|
|
||||||
inline bool operator<(const ExtMove& f, const ExtMove& s) { return f.value < s.value; }
|
|
||||||
|
|
||||||
template<GenType>
|
|
||||||
ExtMove* generate(const Position& pos, ExtMove* moveList);
|
|
||||||
|
|
||||||
// The MoveList struct wraps the generate() function and returns a convenient
|
|
||||||
// list of moves. Using MoveList is sometimes preferable to directly calling
|
|
||||||
// the lower level generate() function.
|
|
||||||
template<GenType T>
|
|
||||||
struct MoveList {
|
|
||||||
|
|
||||||
explicit MoveList(const Position& pos) :
|
|
||||||
last(generate<T>(pos, moveList)) {}
|
|
||||||
const ExtMove* begin() const { return moveList; }
|
|
||||||
const ExtMove* end() const { return last; }
|
|
||||||
size_t size() const { return last - moveList; }
|
|
||||||
bool contains(Move move) const { return std::find(begin(), end(), move) != end(); }
|
|
||||||
|
|
||||||
private:
|
|
||||||
ExtMove moveList[MAX_MOVES], *last;
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Stockfish
|
|
||||||
|
|
||||||
#endif // #ifndef MOVEGEN_H_INCLUDED
|
|
||||||
|
|||||||
+310
-268
@@ -1,12 +1,14 @@
|
|||||||
/*
|
/*
|
||||||
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-2024 The Stockfish developers (see AUTHORS file)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
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
|
||||||
the Free Software Foundation, either version 3 of the License, or
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
(at your option) any later version.
|
(at your option) any later version.
|
||||||
|
|
||||||
|
|
||||||
Stockfish is distributed in the hope that it will be useful,
|
Stockfish is distributed in the hope that it will be useful,
|
||||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
@@ -16,303 +18,343 @@
|
|||||||
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 "movepick.h"
|
|
||||||
|
|
||||||
#include <algorithm>
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
#include <cassert>
|
#include <cassert>
|
||||||
#include <utility>
|
|
||||||
|
|
||||||
#include "bitboard.h"
|
#include "history.h"
|
||||||
#include "position.h"
|
#include "movegen.h"
|
||||||
|
#include "movepick.h"
|
||||||
|
#include "search.h"
|
||||||
|
#include "value.h"
|
||||||
|
|
||||||
namespace Stockfish {
|
|
||||||
|
////
|
||||||
|
//// Local definitions
|
||||||
|
////
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
enum Stages {
|
enum MovegenPhase {
|
||||||
// generate main search moves
|
PH_TT_MOVES, // Transposition table move and mate killer
|
||||||
MAIN_TT,
|
PH_GOOD_CAPTURES, // Queen promotions and captures with SEE values >= 0
|
||||||
CAPTURE_INIT,
|
PH_KILLERS, // Killer moves from the current ply
|
||||||
GOOD_CAPTURE,
|
PH_NONCAPTURES, // Non-captures and underpromotions
|
||||||
QUIET_INIT,
|
PH_BAD_CAPTURES, // Queen promotions and captures with SEE values < 0
|
||||||
GOOD_QUIET,
|
PH_EVASIONS, // Check evasions
|
||||||
BAD_CAPTURE,
|
PH_QCAPTURES, // Captures in quiescence search
|
||||||
BAD_QUIET,
|
PH_QCHECKS, // Non-capture checks in quiescence search
|
||||||
|
PH_STOP
|
||||||
|
};
|
||||||
|
|
||||||
// generate evasion moves
|
CACHE_LINE_ALIGNMENT
|
||||||
EVASION_TT,
|
const uint8_t MainSearchPhaseTable[] = { PH_TT_MOVES, PH_GOOD_CAPTURES, PH_KILLERS, PH_NONCAPTURES, PH_BAD_CAPTURES, PH_STOP};
|
||||||
EVASION_INIT,
|
const uint8_t EvasionsPhaseTable[] = { PH_TT_MOVES, PH_EVASIONS, PH_STOP};
|
||||||
EVASION,
|
const uint8_t QsearchWithChecksPhaseTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_QCHECKS, PH_STOP};
|
||||||
|
const uint8_t QsearchWithoutChecksPhaseTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_STOP};
|
||||||
// generate probcut moves
|
|
||||||
PROBCUT_TT,
|
|
||||||
PROBCUT_INIT,
|
|
||||||
PROBCUT,
|
|
||||||
|
|
||||||
// generate qsearch moves
|
|
||||||
QSEARCH_TT,
|
|
||||||
QCAPTURE_INIT,
|
|
||||||
QCAPTURE
|
|
||||||
};
|
|
||||||
|
|
||||||
// Sort moves in descending order up to and including a given limit.
|
|
||||||
// The order of moves smaller than the limit is left unspecified.
|
|
||||||
void partial_insertion_sort(ExtMove* begin, ExtMove* end, int limit) {
|
|
||||||
|
|
||||||
for (ExtMove *sortedEnd = begin, *p = begin + 1; p < end; ++p)
|
|
||||||
if (p->value >= limit)
|
|
||||||
{
|
|
||||||
ExtMove tmp = *p, *q;
|
|
||||||
*p = *++sortedEnd;
|
|
||||||
for (q = sortedEnd; q != begin && *(q - 1) < tmp; --q)
|
|
||||||
*q = *(q - 1);
|
|
||||||
*q = tmp;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace
|
|
||||||
|
////
|
||||||
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
|
|
||||||
// Constructors of the MovePicker class. As arguments, we pass information
|
/// Constructor for the MovePicker class. Apart from the position for which
|
||||||
// to decide which class of moves to emit, to help sorting the (presumably)
|
/// it is asked to pick legal moves, MovePicker also wants some information
|
||||||
// good moves first, and how important move ordering is at the current node.
|
/// to help it to return the presumably good moves first, to decide which
|
||||||
|
/// moves to return (in the quiescence search, for instance, we only want to
|
||||||
|
/// search captures, promotions and some checks) and about how important good
|
||||||
|
/// move ordering is at the current node.
|
||||||
|
|
||||||
// MovePicker constructor for the main search and for the quiescence search
|
MovePicker::MovePicker(const Position& p, Move ttm, Depth d,
|
||||||
MovePicker::MovePicker(const Position& p,
|
const History& h, SearchStack* ss) : pos(p), H(h) {
|
||||||
Move ttm,
|
int searchTT = ttm;
|
||||||
Depth d,
|
ttMoves[0].move = ttm;
|
||||||
const ButterflyHistory* mh,
|
finished = false;
|
||||||
const CapturePieceToHistory* cph,
|
lastBadCapture = badCaptures;
|
||||||
const PieceToHistory** ch,
|
|
||||||
const PawnHistory* ph) :
|
|
||||||
pos(p),
|
|
||||||
mainHistory(mh),
|
|
||||||
captureHistory(cph),
|
|
||||||
continuationHistory(ch),
|
|
||||||
pawnHistory(ph),
|
|
||||||
ttMove(ttm),
|
|
||||||
depth(d) {
|
|
||||||
|
|
||||||
if (pos.checkers())
|
pinned = p.pinned_pieces(pos.side_to_move());
|
||||||
stage = EVASION_TT + !(ttm && pos.pseudo_legal(ttm));
|
|
||||||
|
|
||||||
else
|
if (ss && !p.is_check())
|
||||||
stage = (depth > 0 ? MAIN_TT : QSEARCH_TT) + !(ttm && pos.pseudo_legal(ttm));
|
{
|
||||||
|
ttMoves[1].move = (ss->mateKiller == ttm)? MOVE_NONE : ss->mateKiller;
|
||||||
|
searchTT |= ttMoves[1].move;
|
||||||
|
killers[0].move = ss->killers[0];
|
||||||
|
killers[1].move = ss->killers[1];
|
||||||
|
} else
|
||||||
|
ttMoves[1].move = killers[0].move = killers[1].move = MOVE_NONE;
|
||||||
|
|
||||||
|
if (p.is_check())
|
||||||
|
phasePtr = EvasionsPhaseTable;
|
||||||
|
else if (d > Depth(0))
|
||||||
|
phasePtr = MainSearchPhaseTable;
|
||||||
|
else if (d == Depth(0))
|
||||||
|
phasePtr = QsearchWithChecksPhaseTable;
|
||||||
|
else
|
||||||
|
phasePtr = QsearchWithoutChecksPhaseTable;
|
||||||
|
|
||||||
|
phasePtr += !searchTT - 1;
|
||||||
|
go_next_phase();
|
||||||
}
|
}
|
||||||
|
|
||||||
// MovePicker constructor for ProbCut: we generate captures with Static Exchange
|
|
||||||
// Evaluation (SEE) greater than or equal to the given threshold.
|
|
||||||
MovePicker::MovePicker(const Position& p, Move ttm, int th, const CapturePieceToHistory* cph) :
|
|
||||||
pos(p),
|
|
||||||
captureHistory(cph),
|
|
||||||
ttMove(ttm),
|
|
||||||
threshold(th) {
|
|
||||||
assert(!pos.checkers());
|
|
||||||
|
|
||||||
stage = PROBCUT_TT
|
/// MovePicker::go_next_phase() generates, scores and sorts the next bunch
|
||||||
+ !(ttm && pos.capture_stage(ttm) && pos.pseudo_legal(ttm) && pos.see_ge(ttm, threshold));
|
/// of moves when there are no more moves to try for the current phase.
|
||||||
|
|
||||||
|
void MovePicker::go_next_phase() {
|
||||||
|
|
||||||
|
curMove = moves;
|
||||||
|
phase = *(++phasePtr);
|
||||||
|
switch (phase) {
|
||||||
|
|
||||||
|
case PH_TT_MOVES:
|
||||||
|
curMove = ttMoves;
|
||||||
|
lastMove = curMove + 2;
|
||||||
|
return;
|
||||||
|
|
||||||
|
case PH_GOOD_CAPTURES:
|
||||||
|
lastMove = generate_captures(pos, moves);
|
||||||
|
score_captures();
|
||||||
|
return;
|
||||||
|
|
||||||
|
case PH_KILLERS:
|
||||||
|
curMove = killers;
|
||||||
|
lastMove = curMove + 2;
|
||||||
|
return;
|
||||||
|
|
||||||
|
case PH_NONCAPTURES:
|
||||||
|
lastMove = generate_noncaptures(pos, moves);
|
||||||
|
score_noncaptures();
|
||||||
|
sort_moves(moves, lastMove);
|
||||||
|
return;
|
||||||
|
|
||||||
|
case PH_BAD_CAPTURES:
|
||||||
|
// Bad captures SEE value is already calculated so just sort them
|
||||||
|
// to get SEE move ordering.
|
||||||
|
curMove = badCaptures;
|
||||||
|
lastMove = lastBadCapture;
|
||||||
|
return;
|
||||||
|
|
||||||
|
case PH_EVASIONS:
|
||||||
|
assert(pos.is_check());
|
||||||
|
lastMove = generate_evasions(pos, moves);
|
||||||
|
score_evasions();
|
||||||
|
return;
|
||||||
|
|
||||||
|
case PH_QCAPTURES:
|
||||||
|
lastMove = generate_captures(pos, moves);
|
||||||
|
score_captures();
|
||||||
|
return;
|
||||||
|
|
||||||
|
case PH_QCHECKS:
|
||||||
|
// Perhaps we should order moves move here? FIXME
|
||||||
|
lastMove = generate_non_capture_checks(pos, moves);
|
||||||
|
return;
|
||||||
|
|
||||||
|
case PH_STOP:
|
||||||
|
lastMove = curMove + 1; // hack to be friendly for get_next_move()
|
||||||
|
return;
|
||||||
|
|
||||||
|
default:
|
||||||
|
assert(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Assigns a numerical value to each move in a list, used for sorting.
|
|
||||||
// Captures are ordered by Most Valuable Victim (MVV), preferring captures
|
|
||||||
// with a good history. Quiets moves are ordered using the history tables.
|
|
||||||
template<GenType Type>
|
|
||||||
void MovePicker::score() {
|
|
||||||
|
|
||||||
static_assert(Type == CAPTURES || Type == QUIETS || Type == EVASIONS, "Wrong type");
|
/// MovePicker::score_captures(), MovePicker::score_noncaptures() and
|
||||||
|
/// MovePicker::score_evasions() assign a numerical move ordering score
|
||||||
|
/// to each move in a move list. The moves with highest scores will be
|
||||||
|
/// picked first by get_next_move().
|
||||||
|
|
||||||
[[maybe_unused]] Bitboard threatenedByPawn, threatenedByMinor, threatenedByRook,
|
void MovePicker::score_captures() {
|
||||||
threatenedPieces;
|
// Winning and equal captures in the main search are ordered by MVV/LVA.
|
||||||
if constexpr (Type == QUIETS)
|
// Suprisingly, this appears to perform slightly better than SEE based
|
||||||
{
|
// move ordering. The reason is probably that in a position with a winning
|
||||||
Color us = pos.side_to_move();
|
// capture, capturing a more valuable (but sufficiently defended) piece
|
||||||
|
// first usually doesn't hurt. The opponent will have to recapture, and
|
||||||
|
// the hanging piece will still be hanging (except in the unusual cases
|
||||||
|
// where it is possible to recapture with the hanging piece). Exchanging
|
||||||
|
// big pieces before capturing a hanging piece probably helps to reduce
|
||||||
|
// the subtree size.
|
||||||
|
// In main search we want to push captures with negative SEE values to
|
||||||
|
// badCaptures[] array, but instead of doing it now we delay till when
|
||||||
|
// the move has been picked up in pick_move_from_list(), this way we save
|
||||||
|
// some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
|
||||||
|
Move m;
|
||||||
|
|
||||||
threatenedByPawn = pos.attacks_by<PAWN>(~us);
|
// Use MVV/LVA ordering
|
||||||
threatenedByMinor =
|
for (MoveStack* cur = moves; cur != lastMove; cur++)
|
||||||
pos.attacks_by<KNIGHT>(~us) | pos.attacks_by<BISHOP>(~us) | threatenedByPawn;
|
{
|
||||||
threatenedByRook = pos.attacks_by<ROOK>(~us) | threatenedByMinor;
|
m = cur->move;
|
||||||
|
if (move_is_promotion(m))
|
||||||
// Pieces threatened by pieces of lesser material value
|
cur->score = QueenValueMidgame;
|
||||||
threatenedPieces = (pos.pieces(us, QUEEN) & threatenedByRook)
|
else
|
||||||
| (pos.pieces(us, ROOK) & threatenedByMinor)
|
cur->score = pos.midgame_value_of_piece_on(move_to(m))
|
||||||
| (pos.pieces(us, KNIGHT, BISHOP) & threatenedByPawn);
|
- pos.type_of_piece_on(move_from(m));
|
||||||
}
|
}
|
||||||
|
|
||||||
for (auto& m : *this)
|
|
||||||
if constexpr (Type == CAPTURES)
|
|
||||||
m.value =
|
|
||||||
7 * int(PieceValue[pos.piece_on(m.to_sq())])
|
|
||||||
+ (*captureHistory)[pos.moved_piece(m)][m.to_sq()][type_of(pos.piece_on(m.to_sq()))];
|
|
||||||
|
|
||||||
else if constexpr (Type == QUIETS)
|
|
||||||
{
|
|
||||||
Piece pc = pos.moved_piece(m);
|
|
||||||
PieceType pt = type_of(pc);
|
|
||||||
Square from = m.from_sq();
|
|
||||||
Square to = m.to_sq();
|
|
||||||
|
|
||||||
// histories
|
|
||||||
m.value = (*mainHistory)[pos.side_to_move()][m.from_to()];
|
|
||||||
m.value += 2 * (*pawnHistory)[pawn_structure_index(pos)][pc][to];
|
|
||||||
m.value += 2 * (*continuationHistory[0])[pc][to];
|
|
||||||
m.value += (*continuationHistory[1])[pc][to];
|
|
||||||
m.value += (*continuationHistory[2])[pc][to] / 3;
|
|
||||||
m.value += (*continuationHistory[3])[pc][to];
|
|
||||||
m.value += (*continuationHistory[5])[pc][to];
|
|
||||||
|
|
||||||
// bonus for checks
|
|
||||||
m.value += bool(pos.check_squares(pt) & to) * 16384;
|
|
||||||
|
|
||||||
// bonus for escaping from capture
|
|
||||||
m.value += threatenedPieces & from ? (pt == QUEEN && !(to & threatenedByRook) ? 51700
|
|
||||||
: pt == ROOK && !(to & threatenedByMinor) ? 25600
|
|
||||||
: !(to & threatenedByPawn) ? 14450
|
|
||||||
: 0)
|
|
||||||
: 0;
|
|
||||||
|
|
||||||
// malus for putting piece en prise
|
|
||||||
m.value -= (pt == QUEEN ? bool(to & threatenedByRook) * 49000
|
|
||||||
: pt == ROOK ? bool(to & threatenedByMinor) * 24335
|
|
||||||
: bool(to & threatenedByPawn) * 14900);
|
|
||||||
}
|
|
||||||
|
|
||||||
else // Type == EVASIONS
|
|
||||||
{
|
|
||||||
if (pos.capture_stage(m))
|
|
||||||
m.value =
|
|
||||||
PieceValue[pos.piece_on(m.to_sq())] - type_of(pos.moved_piece(m)) + (1 << 28);
|
|
||||||
else
|
|
||||||
m.value = (*mainHistory)[pos.side_to_move()][m.from_to()]
|
|
||||||
+ (*continuationHistory[0])[pos.moved_piece(m)][m.to_sq()]
|
|
||||||
+ (*pawnHistory)[pawn_structure_index(pos)][pos.moved_piece(m)][m.to_sq()];
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Returns the next move satisfying a predicate function.
|
void MovePicker::score_noncaptures() {
|
||||||
// This never returns the TT move, as it was emitted before.
|
// First score by history, when no history is available then use
|
||||||
template<MovePicker::PickType T, typename Pred>
|
// piece/square tables values. This seems to be better then a
|
||||||
Move MovePicker::select(Pred filter) {
|
// random choice when we don't have an history for any move.
|
||||||
|
Move m;
|
||||||
|
Piece piece;
|
||||||
|
Square from, to;
|
||||||
|
int hs;
|
||||||
|
|
||||||
while (cur < endMoves)
|
for (MoveStack* cur = moves; cur != lastMove; cur++)
|
||||||
{
|
{
|
||||||
if constexpr (T == Best)
|
m = cur->move;
|
||||||
std::swap(*cur, *std::max_element(cur, endMoves));
|
from = move_from(m);
|
||||||
|
to = move_to(m);
|
||||||
|
piece = pos.piece_on(from);
|
||||||
|
hs = H.move_ordering_score(piece, to);
|
||||||
|
|
||||||
if (*cur != ttMove && filter())
|
// Ensure history is always preferred to pst
|
||||||
return *cur++;
|
if (hs > 0)
|
||||||
|
hs += 1000;
|
||||||
|
|
||||||
cur++;
|
// pst based scoring
|
||||||
}
|
cur->score = hs + mg_value(pos.pst_delta(piece, from, to));
|
||||||
return Move::none();
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// This is the most important method of the MovePicker class. We emit one
|
void MovePicker::score_evasions() {
|
||||||
// new pseudo-legal move on every call until there are no more moves left,
|
// Try good captures ordered by MVV/LVA, then non-captures if
|
||||||
// picking the move with the highest score from a list of generated moves.
|
// destination square is not under attack, ordered by history
|
||||||
Move MovePicker::next_move(bool skipQuiets) {
|
// value, and at the end bad-captures and non-captures with a
|
||||||
|
// negative SEE. This last group is ordered by the SEE score.
|
||||||
|
Move m;
|
||||||
|
int seeScore;
|
||||||
|
|
||||||
auto quiet_threshold = [](Depth d) { return -3560 * d; };
|
for (MoveStack* cur = moves; cur != lastMove; cur++)
|
||||||
|
{
|
||||||
top:
|
m = cur->move;
|
||||||
switch (stage)
|
if ((seeScore = pos.see_sign(m)) < 0)
|
||||||
{
|
cur->score = seeScore;
|
||||||
|
else if (pos.move_is_capture(m))
|
||||||
case MAIN_TT :
|
cur->score = pos.midgame_value_of_piece_on(move_to(m))
|
||||||
case EVASION_TT :
|
- pos.type_of_piece_on(move_from(m)) + HistoryMax;
|
||||||
case QSEARCH_TT :
|
else
|
||||||
case PROBCUT_TT :
|
cur->score = H.move_ordering_score(pos.piece_on(move_from(m)), move_to(m));
|
||||||
++stage;
|
}
|
||||||
return ttMove;
|
|
||||||
|
|
||||||
case CAPTURE_INIT :
|
|
||||||
case PROBCUT_INIT :
|
|
||||||
case QCAPTURE_INIT :
|
|
||||||
cur = endBadCaptures = moves;
|
|
||||||
endMoves = generate<CAPTURES>(pos, cur);
|
|
||||||
|
|
||||||
score<CAPTURES>();
|
|
||||||
partial_insertion_sort(cur, endMoves, std::numeric_limits<int>::min());
|
|
||||||
++stage;
|
|
||||||
goto top;
|
|
||||||
|
|
||||||
case GOOD_CAPTURE :
|
|
||||||
if (select<Next>([&]() {
|
|
||||||
// Move losing capture to endBadCaptures to be tried later
|
|
||||||
return pos.see_ge(*cur, -cur->value / 18) ? true
|
|
||||||
: (*endBadCaptures++ = *cur, false);
|
|
||||||
}))
|
|
||||||
return *(cur - 1);
|
|
||||||
|
|
||||||
++stage;
|
|
||||||
[[fallthrough]];
|
|
||||||
|
|
||||||
case QUIET_INIT :
|
|
||||||
if (!skipQuiets)
|
|
||||||
{
|
|
||||||
cur = endBadCaptures;
|
|
||||||
endMoves = beginBadQuiets = endBadQuiets = generate<QUIETS>(pos, cur);
|
|
||||||
|
|
||||||
score<QUIETS>();
|
|
||||||
partial_insertion_sort(cur, endMoves, quiet_threshold(depth));
|
|
||||||
}
|
|
||||||
|
|
||||||
++stage;
|
|
||||||
[[fallthrough]];
|
|
||||||
|
|
||||||
case GOOD_QUIET :
|
|
||||||
if (!skipQuiets && select<Next>([]() { return true; }))
|
|
||||||
{
|
|
||||||
if ((cur - 1)->value > -7998 || (cur - 1)->value <= quiet_threshold(depth))
|
|
||||||
return *(cur - 1);
|
|
||||||
|
|
||||||
// Remaining quiets are bad
|
|
||||||
beginBadQuiets = cur - 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Prepare the pointers to loop over the bad captures
|
|
||||||
cur = moves;
|
|
||||||
endMoves = endBadCaptures;
|
|
||||||
|
|
||||||
++stage;
|
|
||||||
[[fallthrough]];
|
|
||||||
|
|
||||||
case BAD_CAPTURE :
|
|
||||||
if (select<Next>([]() { return true; }))
|
|
||||||
return *(cur - 1);
|
|
||||||
|
|
||||||
// Prepare the pointers to loop over the bad quiets
|
|
||||||
cur = beginBadQuiets;
|
|
||||||
endMoves = endBadQuiets;
|
|
||||||
|
|
||||||
++stage;
|
|
||||||
[[fallthrough]];
|
|
||||||
|
|
||||||
case BAD_QUIET :
|
|
||||||
if (!skipQuiets)
|
|
||||||
return select<Next>([]() { return true; });
|
|
||||||
|
|
||||||
return Move::none();
|
|
||||||
|
|
||||||
case EVASION_INIT :
|
|
||||||
cur = moves;
|
|
||||||
endMoves = generate<EVASIONS>(pos, cur);
|
|
||||||
|
|
||||||
score<EVASIONS>();
|
|
||||||
++stage;
|
|
||||||
[[fallthrough]];
|
|
||||||
|
|
||||||
case EVASION :
|
|
||||||
return select<Best>([]() { return true; });
|
|
||||||
|
|
||||||
case PROBCUT :
|
|
||||||
return select<Next>([&]() { return pos.see_ge(*cur, threshold); });
|
|
||||||
|
|
||||||
case QCAPTURE :
|
|
||||||
return select<Next>([]() { return true; });
|
|
||||||
}
|
|
||||||
|
|
||||||
assert(false);
|
|
||||||
return Move::none(); // Silence warning
|
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace Stockfish
|
/// MovePicker::get_next_move() is the most important method of the MovePicker
|
||||||
|
/// class. It returns a new legal move every time it is called, until there
|
||||||
|
/// 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.
|
||||||
|
|
||||||
|
Move MovePicker::get_next_move() {
|
||||||
|
|
||||||
|
Move move;
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
while (curMove != lastMove)
|
||||||
|
{
|
||||||
|
switch (phase) {
|
||||||
|
|
||||||
|
case PH_TT_MOVES:
|
||||||
|
move = (curMove++)->move;
|
||||||
|
if ( move != MOVE_NONE
|
||||||
|
&& move_is_legal(pos, move, pinned))
|
||||||
|
return move;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PH_GOOD_CAPTURES:
|
||||||
|
move = pick_best(curMove++, lastMove).move;
|
||||||
|
if ( move != ttMoves[0].move
|
||||||
|
&& move != ttMoves[1].move
|
||||||
|
&& pos.pl_move_is_legal(move, pinned))
|
||||||
|
{
|
||||||
|
// Check for a non negative SEE now
|
||||||
|
int seeValue = pos.see_sign(move);
|
||||||
|
if (seeValue >= 0)
|
||||||
|
return move;
|
||||||
|
|
||||||
|
// Losing capture, move it to the badCaptures[] array, note
|
||||||
|
// that move has now been already checked for legality.
|
||||||
|
assert(int(lastBadCapture - badCaptures) < 63);
|
||||||
|
lastBadCapture->move = move;
|
||||||
|
lastBadCapture->score = seeValue;
|
||||||
|
lastBadCapture++;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PH_KILLERS:
|
||||||
|
move = (curMove++)->move;
|
||||||
|
if ( move != MOVE_NONE
|
||||||
|
&& move != ttMoves[0].move
|
||||||
|
&& move != ttMoves[1].move
|
||||||
|
&& move_is_legal(pos, move, pinned)
|
||||||
|
&& !pos.move_is_capture(move))
|
||||||
|
return move;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PH_NONCAPTURES:
|
||||||
|
move = (curMove++)->move;
|
||||||
|
if ( move != ttMoves[0].move
|
||||||
|
&& move != ttMoves[1].move
|
||||||
|
&& move != killers[0].move
|
||||||
|
&& move != killers[1].move
|
||||||
|
&& pos.pl_move_is_legal(move, pinned))
|
||||||
|
return move;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PH_BAD_CAPTURES:
|
||||||
|
move = pick_best(curMove++, lastMove).move;
|
||||||
|
return move;
|
||||||
|
|
||||||
|
case PH_EVASIONS:
|
||||||
|
case PH_QCAPTURES:
|
||||||
|
move = pick_best(curMove++, lastMove).move;
|
||||||
|
if ( move != ttMoves[0].move
|
||||||
|
&& pos.pl_move_is_legal(move, pinned))
|
||||||
|
return move;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PH_QCHECKS:
|
||||||
|
move = (curMove++)->move;
|
||||||
|
if ( move != ttMoves[0].move
|
||||||
|
&& pos.pl_move_is_legal(move, pinned))
|
||||||
|
return move;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PH_STOP:
|
||||||
|
return MOVE_NONE;
|
||||||
|
|
||||||
|
default:
|
||||||
|
assert(false);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
go_next_phase();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A variant of get_next_move() which takes a lock as a parameter, used to
|
||||||
|
/// prevent multiple threads from picking the same move at a split point.
|
||||||
|
|
||||||
|
Move MovePicker::get_next_move(Lock &lock) {
|
||||||
|
|
||||||
|
lock_grab(&lock);
|
||||||
|
if (finished)
|
||||||
|
{
|
||||||
|
lock_release(&lock);
|
||||||
|
return MOVE_NONE;
|
||||||
|
}
|
||||||
|
Move m = get_next_move();
|
||||||
|
if (m == MOVE_NONE)
|
||||||
|
finished = true;
|
||||||
|
|
||||||
|
lock_release(&lock);
|
||||||
|
return m;
|
||||||
|
}
|
||||||
|
|||||||
+56
-155
@@ -1,6 +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-2024 The Stockfish developers (see AUTHORS file)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
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
|
||||||
@@ -16,174 +17,74 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#ifndef MOVEPICK_H_INCLUDED
|
|
||||||
|
#if !defined MOVEPICK_H_INCLUDED
|
||||||
#define MOVEPICK_H_INCLUDED
|
#define MOVEPICK_H_INCLUDED
|
||||||
|
|
||||||
#include <algorithm>
|
////
|
||||||
#include <array>
|
//// Includes
|
||||||
#include <cassert>
|
////
|
||||||
#include <cmath>
|
|
||||||
#include <cstdint>
|
|
||||||
#include <cstdlib>
|
|
||||||
#include <limits>
|
|
||||||
#include <type_traits> // IWYU pragma: keep
|
|
||||||
|
|
||||||
#include "movegen.h"
|
#include "depth.h"
|
||||||
|
#include "history.h"
|
||||||
|
#include "lock.h"
|
||||||
#include "position.h"
|
#include "position.h"
|
||||||
#include "types.h"
|
|
||||||
|
|
||||||
namespace Stockfish {
|
|
||||||
|
|
||||||
constexpr int PAWN_HISTORY_SIZE = 512; // has to be a power of 2
|
////
|
||||||
constexpr int CORRECTION_HISTORY_SIZE = 16384; // has to be a power of 2
|
//// Types
|
||||||
constexpr int CORRECTION_HISTORY_LIMIT = 1024;
|
////
|
||||||
|
|
||||||
static_assert((PAWN_HISTORY_SIZE & (PAWN_HISTORY_SIZE - 1)) == 0,
|
struct SearchStack;
|
||||||
"PAWN_HISTORY_SIZE has to be a power of 2");
|
|
||||||
|
|
||||||
static_assert((CORRECTION_HISTORY_SIZE & (CORRECTION_HISTORY_SIZE - 1)) == 0,
|
/// MovePicker is a class which is used to pick one legal move at a time from
|
||||||
"CORRECTION_HISTORY_SIZE has to be a power of 2");
|
/// the current position. It is initialized with a Position object and a few
|
||||||
|
/// moves we have reason to believe are good. The most important method is
|
||||||
|
/// MovePicker::pick_next_move(), which returns a new legal move each time it
|
||||||
|
/// is called, until there are no legal moves left, when MOVE_NONE is returned.
|
||||||
|
/// In order to improve the efficiency of the alpha beta algorithm, MovePicker
|
||||||
|
/// attempts to return the moves which are most likely to be strongest first.
|
||||||
|
|
||||||
enum PawnHistoryType {
|
|
||||||
Normal,
|
|
||||||
Correction
|
|
||||||
};
|
|
||||||
|
|
||||||
template<PawnHistoryType T = Normal>
|
|
||||||
inline int pawn_structure_index(const Position& pos) {
|
|
||||||
return pos.pawn_key() & ((T == Normal ? PAWN_HISTORY_SIZE : CORRECTION_HISTORY_SIZE) - 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// StatsEntry stores the stat table value. It is usually a number but could
|
|
||||||
// be a move or even a nested history. We use a class instead of a naked value
|
|
||||||
// to directly call history update operator<<() on the entry so to use stats
|
|
||||||
// tables at caller sites as simple multi-dim arrays.
|
|
||||||
template<typename T, int D>
|
|
||||||
class StatsEntry {
|
|
||||||
|
|
||||||
T entry;
|
|
||||||
|
|
||||||
public:
|
|
||||||
void operator=(const T& v) { entry = v; }
|
|
||||||
T* operator&() { return &entry; }
|
|
||||||
T* operator->() { return &entry; }
|
|
||||||
operator const T&() const { return entry; }
|
|
||||||
|
|
||||||
void operator<<(int bonus) {
|
|
||||||
static_assert(D <= std::numeric_limits<T>::max(), "D overflows T");
|
|
||||||
|
|
||||||
// Make sure that bonus is in range [-D, D]
|
|
||||||
int clampedBonus = std::clamp(bonus, -D, D);
|
|
||||||
entry += clampedBonus - entry * std::abs(clampedBonus) / D;
|
|
||||||
|
|
||||||
assert(std::abs(entry) <= D);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Stats is a generic N-dimensional array used to store various statistics.
|
|
||||||
// The first template parameter T is the base type of the array, and the second
|
|
||||||
// template parameter D limits the range of updates in [-D, D] when we update
|
|
||||||
// values with the << operator, while the last parameters (Size and Sizes)
|
|
||||||
// encode the dimensions of the array.
|
|
||||||
template<typename T, int D, int Size, int... Sizes>
|
|
||||||
struct Stats: public std::array<Stats<T, D, Sizes...>, Size> {
|
|
||||||
using stats = Stats<T, D, Size, Sizes...>;
|
|
||||||
|
|
||||||
void fill(const T& v) {
|
|
||||||
|
|
||||||
// For standard-layout 'this' points to the first struct member
|
|
||||||
assert(std::is_standard_layout_v<stats>);
|
|
||||||
|
|
||||||
using entry = StatsEntry<T, D>;
|
|
||||||
entry* p = reinterpret_cast<entry*>(this);
|
|
||||||
std::fill(p, p + sizeof(*this) / sizeof(entry), v);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename T, int D, int Size>
|
|
||||||
struct Stats<T, D, Size>: public std::array<StatsEntry<T, D>, Size> {};
|
|
||||||
|
|
||||||
// In stats table, D=0 means that the template parameter is not used
|
|
||||||
enum StatsParams {
|
|
||||||
NOT_USED = 0
|
|
||||||
};
|
|
||||||
enum StatsType {
|
|
||||||
NoCaptures,
|
|
||||||
Captures
|
|
||||||
};
|
|
||||||
|
|
||||||
// ButterflyHistory records how often quiet moves have been successful or unsuccessful
|
|
||||||
// during the current search, and is used for reduction and move ordering decisions.
|
|
||||||
// It uses 2 tables (one for each color) indexed by the move's from and to squares,
|
|
||||||
// see www.chessprogramming.org/Butterfly_Boards (~11 elo)
|
|
||||||
using ButterflyHistory = Stats<int16_t, 7183, COLOR_NB, int(SQUARE_NB) * int(SQUARE_NB)>;
|
|
||||||
|
|
||||||
// CapturePieceToHistory is addressed by a move's [piece][to][captured piece type]
|
|
||||||
using CapturePieceToHistory = Stats<int16_t, 10692, PIECE_NB, SQUARE_NB, PIECE_TYPE_NB>;
|
|
||||||
|
|
||||||
// PieceToHistory is like ButterflyHistory but is addressed by a move's [piece][to]
|
|
||||||
using PieceToHistory = Stats<int16_t, 29952, PIECE_NB, SQUARE_NB>;
|
|
||||||
|
|
||||||
// ContinuationHistory is the combined history of a given pair of moves, usually
|
|
||||||
// the current one given a previous one. The nested history table is based on
|
|
||||||
// PieceToHistory instead of ButterflyBoards.
|
|
||||||
// (~63 elo)
|
|
||||||
using ContinuationHistory = Stats<PieceToHistory, NOT_USED, PIECE_NB, SQUARE_NB>;
|
|
||||||
|
|
||||||
// PawnHistory is addressed by the pawn structure and a move's [piece][to]
|
|
||||||
using PawnHistory = Stats<int16_t, 8192, PAWN_HISTORY_SIZE, PIECE_NB, SQUARE_NB>;
|
|
||||||
|
|
||||||
// CorrectionHistory is addressed by color and pawn structure
|
|
||||||
using CorrectionHistory =
|
|
||||||
Stats<int16_t, CORRECTION_HISTORY_LIMIT, COLOR_NB, CORRECTION_HISTORY_SIZE>;
|
|
||||||
|
|
||||||
// The 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 emits one
|
|
||||||
// new pseudo-legal move on every call, 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 {
|
||||||
|
|
||||||
enum PickType {
|
MovePicker& operator=(const MovePicker&); // silence a warning under MSVC
|
||||||
Next,
|
|
||||||
Best
|
|
||||||
};
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
MovePicker(const MovePicker&) = delete;
|
MovePicker(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss = NULL);
|
||||||
MovePicker& operator=(const MovePicker&) = delete;
|
Move get_next_move();
|
||||||
MovePicker(const Position&,
|
Move get_next_move(Lock& lock);
|
||||||
Move,
|
int number_of_evasions() const;
|
||||||
Depth,
|
|
||||||
const ButterflyHistory*,
|
|
||||||
const CapturePieceToHistory*,
|
|
||||||
const PieceToHistory**,
|
|
||||||
const PawnHistory*);
|
|
||||||
MovePicker(const Position&, Move, int, const CapturePieceToHistory*);
|
|
||||||
Move next_move(bool skipQuiets = false);
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
template<PickType T, typename Pred>
|
void score_captures();
|
||||||
Move select(Pred);
|
void score_noncaptures();
|
||||||
template<GenType>
|
void score_evasions();
|
||||||
void score();
|
void go_next_phase();
|
||||||
ExtMove* begin() { return cur; }
|
|
||||||
ExtMove* end() { return endMoves; }
|
|
||||||
|
|
||||||
const Position& pos;
|
const Position& pos;
|
||||||
const ButterflyHistory* mainHistory;
|
const History& H;
|
||||||
const CapturePieceToHistory* captureHistory;
|
MoveStack ttMoves[2], killers[2];
|
||||||
const PieceToHistory** continuationHistory;
|
bool finished;
|
||||||
const PawnHistory* pawnHistory;
|
int phase;
|
||||||
Move ttMove;
|
const uint8_t* phasePtr;
|
||||||
ExtMove * cur, *endMoves, *endBadCaptures, *beginBadQuiets, *endBadQuiets;
|
MoveStack *curMove, *lastMove, *lastBadCapture;
|
||||||
int stage;
|
Bitboard pinned;
|
||||||
int threshold;
|
MoveStack moves[256], badCaptures[64];
|
||||||
Depth depth;
|
|
||||||
ExtMove moves[MAX_MOVES];
|
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace Stockfish
|
|
||||||
|
|
||||||
#endif // #ifndef MOVEPICK_H_INCLUDED
|
////
|
||||||
|
//// Inline functions
|
||||||
|
////
|
||||||
|
|
||||||
|
/// MovePicker::number_of_evasions() simply returns the number of moves in
|
||||||
|
/// evasions phase. It is intended to be used in positions where the side to
|
||||||
|
/// move is in check, for detecting checkmates or situations where there is
|
||||||
|
/// only a single reply to check.
|
||||||
|
/// WARNING: It works as long as PH_EVASIONS is the _only_ phase for evasions.
|
||||||
|
|
||||||
|
inline int MovePicker::number_of_evasions() const {
|
||||||
|
return int(lastMove - moves);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif // !defined(MOVEPICK_H_INCLUDED)
|
||||||
|
|||||||
@@ -1,88 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
//Definition of input features HalfKAv2_hm of NNUE evaluation function
|
|
||||||
|
|
||||||
#include "half_ka_v2_hm.h"
|
|
||||||
|
|
||||||
#include "../../bitboard.h"
|
|
||||||
#include "../../position.h"
|
|
||||||
#include "../../types.h"
|
|
||||||
#include "../nnue_accumulator.h"
|
|
||||||
|
|
||||||
namespace Stockfish::Eval::NNUE::Features {
|
|
||||||
|
|
||||||
// Index of a feature for a given king position and another piece on some square
|
|
||||||
template<Color Perspective>
|
|
||||||
inline IndexType HalfKAv2_hm::make_index(Square s, Piece pc, Square ksq) {
|
|
||||||
return IndexType((int(s) ^ OrientTBL[Perspective][ksq]) + PieceSquareIndex[Perspective][pc]
|
|
||||||
+ KingBuckets[Perspective][ksq]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get a list of indices for active features
|
|
||||||
template<Color Perspective>
|
|
||||||
void HalfKAv2_hm::append_active_indices(const Position& pos, IndexList& active) {
|
|
||||||
Square ksq = pos.square<KING>(Perspective);
|
|
||||||
Bitboard bb = pos.pieces();
|
|
||||||
while (bb)
|
|
||||||
{
|
|
||||||
Square s = pop_lsb(bb);
|
|
||||||
active.push_back(make_index<Perspective>(s, pos.piece_on(s), ksq));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Explicit template instantiations
|
|
||||||
template void HalfKAv2_hm::append_active_indices<WHITE>(const Position& pos, IndexList& active);
|
|
||||||
template void HalfKAv2_hm::append_active_indices<BLACK>(const Position& pos, IndexList& active);
|
|
||||||
template IndexType HalfKAv2_hm::make_index<WHITE>(Square s, Piece pc, Square ksq);
|
|
||||||
template IndexType HalfKAv2_hm::make_index<BLACK>(Square s, Piece pc, Square ksq);
|
|
||||||
|
|
||||||
// Get a list of indices for recently changed features
|
|
||||||
template<Color Perspective>
|
|
||||||
void HalfKAv2_hm::append_changed_indices(Square ksq,
|
|
||||||
const DirtyPiece& dp,
|
|
||||||
IndexList& removed,
|
|
||||||
IndexList& added) {
|
|
||||||
for (int i = 0; i < dp.dirty_num; ++i)
|
|
||||||
{
|
|
||||||
if (dp.from[i] != SQ_NONE)
|
|
||||||
removed.push_back(make_index<Perspective>(dp.from[i], dp.piece[i], ksq));
|
|
||||||
if (dp.to[i] != SQ_NONE)
|
|
||||||
added.push_back(make_index<Perspective>(dp.to[i], dp.piece[i], ksq));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Explicit template instantiations
|
|
||||||
template void HalfKAv2_hm::append_changed_indices<WHITE>(Square ksq,
|
|
||||||
const DirtyPiece& dp,
|
|
||||||
IndexList& removed,
|
|
||||||
IndexList& added);
|
|
||||||
template void HalfKAv2_hm::append_changed_indices<BLACK>(Square ksq,
|
|
||||||
const DirtyPiece& dp,
|
|
||||||
IndexList& removed,
|
|
||||||
IndexList& added);
|
|
||||||
|
|
||||||
int HalfKAv2_hm::update_cost(const StateInfo* st) { return st->dirtyPiece.dirty_num; }
|
|
||||||
|
|
||||||
int HalfKAv2_hm::refresh_cost(const Position& pos) { return pos.count<ALL_PIECES>(); }
|
|
||||||
|
|
||||||
bool HalfKAv2_hm::requires_refresh(const StateInfo* st, Color perspective) {
|
|
||||||
return st->dirtyPiece.piece[0] == make_piece(perspective, KING);
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Stockfish::Eval::NNUE::Features
|
|
||||||
@@ -1,150 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
//Definition of input features HalfKP of NNUE evaluation function
|
|
||||||
|
|
||||||
#ifndef NNUE_FEATURES_HALF_KA_V2_HM_H_INCLUDED
|
|
||||||
#define NNUE_FEATURES_HALF_KA_V2_HM_H_INCLUDED
|
|
||||||
|
|
||||||
#include <cstdint>
|
|
||||||
|
|
||||||
#include "../../misc.h"
|
|
||||||
#include "../../types.h"
|
|
||||||
#include "../nnue_common.h"
|
|
||||||
|
|
||||||
namespace Stockfish {
|
|
||||||
struct StateInfo;
|
|
||||||
class Position;
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace Stockfish::Eval::NNUE::Features {
|
|
||||||
|
|
||||||
// Feature HalfKAv2_hm: Combination of the position of own king and the
|
|
||||||
// position of pieces. Position mirrored such that king is always on e..h files.
|
|
||||||
class HalfKAv2_hm {
|
|
||||||
|
|
||||||
// Unique number for each piece type on each square
|
|
||||||
enum {
|
|
||||||
PS_NONE = 0,
|
|
||||||
PS_W_PAWN = 0,
|
|
||||||
PS_B_PAWN = 1 * SQUARE_NB,
|
|
||||||
PS_W_KNIGHT = 2 * SQUARE_NB,
|
|
||||||
PS_B_KNIGHT = 3 * SQUARE_NB,
|
|
||||||
PS_W_BISHOP = 4 * SQUARE_NB,
|
|
||||||
PS_B_BISHOP = 5 * SQUARE_NB,
|
|
||||||
PS_W_ROOK = 6 * SQUARE_NB,
|
|
||||||
PS_B_ROOK = 7 * SQUARE_NB,
|
|
||||||
PS_W_QUEEN = 8 * SQUARE_NB,
|
|
||||||
PS_B_QUEEN = 9 * SQUARE_NB,
|
|
||||||
PS_KING = 10 * SQUARE_NB,
|
|
||||||
PS_NB = 11 * SQUARE_NB
|
|
||||||
};
|
|
||||||
|
|
||||||
static constexpr IndexType PieceSquareIndex[COLOR_NB][PIECE_NB] = {
|
|
||||||
// Convention: W - us, B - them
|
|
||||||
// Viewed from other side, W and B are reversed
|
|
||||||
{PS_NONE, PS_W_PAWN, PS_W_KNIGHT, PS_W_BISHOP, PS_W_ROOK, PS_W_QUEEN, PS_KING, PS_NONE,
|
|
||||||
PS_NONE, PS_B_PAWN, PS_B_KNIGHT, PS_B_BISHOP, PS_B_ROOK, PS_B_QUEEN, PS_KING, PS_NONE},
|
|
||||||
{PS_NONE, PS_B_PAWN, PS_B_KNIGHT, PS_B_BISHOP, PS_B_ROOK, PS_B_QUEEN, PS_KING, PS_NONE,
|
|
||||||
PS_NONE, PS_W_PAWN, PS_W_KNIGHT, PS_W_BISHOP, PS_W_ROOK, PS_W_QUEEN, PS_KING, PS_NONE}};
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Feature name
|
|
||||||
static constexpr const char* Name = "HalfKAv2_hm(Friend)";
|
|
||||||
|
|
||||||
// Hash value embedded in the evaluation file
|
|
||||||
static constexpr std::uint32_t HashValue = 0x7f234cb8u;
|
|
||||||
|
|
||||||
// Number of feature dimensions
|
|
||||||
static constexpr IndexType Dimensions =
|
|
||||||
static_cast<IndexType>(SQUARE_NB) * static_cast<IndexType>(PS_NB) / 2;
|
|
||||||
|
|
||||||
#define B(v) (v * PS_NB)
|
|
||||||
// clang-format off
|
|
||||||
static constexpr int KingBuckets[COLOR_NB][SQUARE_NB] = {
|
|
||||||
{ B(28), B(29), B(30), B(31), B(31), B(30), B(29), B(28),
|
|
||||||
B(24), B(25), B(26), B(27), B(27), B(26), B(25), B(24),
|
|
||||||
B(20), B(21), B(22), B(23), B(23), B(22), B(21), B(20),
|
|
||||||
B(16), B(17), B(18), B(19), B(19), B(18), B(17), B(16),
|
|
||||||
B(12), B(13), B(14), B(15), B(15), B(14), B(13), B(12),
|
|
||||||
B( 8), B( 9), B(10), B(11), B(11), B(10), B( 9), B( 8),
|
|
||||||
B( 4), B( 5), B( 6), B( 7), B( 7), B( 6), B( 5), B( 4),
|
|
||||||
B( 0), B( 1), B( 2), B( 3), B( 3), B( 2), B( 1), B( 0) },
|
|
||||||
{ B( 0), B( 1), B( 2), B( 3), B( 3), B( 2), B( 1), B( 0),
|
|
||||||
B( 4), B( 5), B( 6), B( 7), B( 7), B( 6), B( 5), B( 4),
|
|
||||||
B( 8), B( 9), B(10), B(11), B(11), B(10), B( 9), B( 8),
|
|
||||||
B(12), B(13), B(14), B(15), B(15), B(14), B(13), B(12),
|
|
||||||
B(16), B(17), B(18), B(19), B(19), B(18), B(17), B(16),
|
|
||||||
B(20), B(21), B(22), B(23), B(23), B(22), B(21), B(20),
|
|
||||||
B(24), B(25), B(26), B(27), B(27), B(26), B(25), B(24),
|
|
||||||
B(28), B(29), B(30), B(31), B(31), B(30), B(29), B(28) }
|
|
||||||
};
|
|
||||||
// clang-format on
|
|
||||||
#undef B
|
|
||||||
// clang-format off
|
|
||||||
// Orient a square according to perspective (rotates by 180 for black)
|
|
||||||
static constexpr int OrientTBL[COLOR_NB][SQUARE_NB] = {
|
|
||||||
{ SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1,
|
|
||||||
SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1,
|
|
||||||
SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1,
|
|
||||||
SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1,
|
|
||||||
SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1,
|
|
||||||
SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1,
|
|
||||||
SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1,
|
|
||||||
SQ_H1, SQ_H1, SQ_H1, SQ_H1, SQ_A1, SQ_A1, SQ_A1, SQ_A1 },
|
|
||||||
{ SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8,
|
|
||||||
SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8,
|
|
||||||
SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8,
|
|
||||||
SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8,
|
|
||||||
SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8,
|
|
||||||
SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8,
|
|
||||||
SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8,
|
|
||||||
SQ_H8, SQ_H8, SQ_H8, SQ_H8, SQ_A8, SQ_A8, SQ_A8, SQ_A8 }
|
|
||||||
};
|
|
||||||
// clang-format on
|
|
||||||
|
|
||||||
// Maximum number of simultaneously active features.
|
|
||||||
static constexpr IndexType MaxActiveDimensions = 32;
|
|
||||||
using IndexList = ValueList<IndexType, MaxActiveDimensions>;
|
|
||||||
|
|
||||||
// Index of a feature for a given king position and another piece on some square
|
|
||||||
template<Color Perspective>
|
|
||||||
static IndexType make_index(Square s, Piece pc, Square ksq);
|
|
||||||
|
|
||||||
// Get a list of indices for active features
|
|
||||||
template<Color Perspective>
|
|
||||||
static void append_active_indices(const Position& pos, IndexList& active);
|
|
||||||
|
|
||||||
// Get a list of indices for recently changed features
|
|
||||||
template<Color Perspective>
|
|
||||||
static void
|
|
||||||
append_changed_indices(Square ksq, const DirtyPiece& dp, IndexList& removed, IndexList& added);
|
|
||||||
|
|
||||||
// Returns the cost of updating one perspective, the most costly one.
|
|
||||||
// Assumes no refresh needed.
|
|
||||||
static int update_cost(const StateInfo* st);
|
|
||||||
static int refresh_cost(const Position& pos);
|
|
||||||
|
|
||||||
// Returns whether the change stored in this StateInfo means
|
|
||||||
// that a full accumulator refresh is required.
|
|
||||||
static bool requires_refresh(const StateInfo* st, Color perspective);
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Stockfish::Eval::NNUE::Features
|
|
||||||
|
|
||||||
#endif // #ifndef NNUE_FEATURES_HALF_KA_V2_HM_H_INCLUDED
|
|
||||||
@@ -1,306 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Definition of layer AffineTransform of NNUE evaluation function
|
|
||||||
|
|
||||||
#ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED
|
|
||||||
#define NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED
|
|
||||||
|
|
||||||
#include <cstdint>
|
|
||||||
#include <iostream>
|
|
||||||
|
|
||||||
#include "../nnue_common.h"
|
|
||||||
#include "simd.h"
|
|
||||||
|
|
||||||
/*
|
|
||||||
This file contains the definition for a fully connected layer (aka affine transform).
|
|
||||||
|
|
||||||
- expected use-case is for when PaddedInputDimensions == 32 and InputDimensions <= 32.
|
|
||||||
- that's why AVX512 is hard to implement
|
|
||||||
- expected use-case is small layers
|
|
||||||
- inputs are processed in chunks of 4, weights are respectively transposed
|
|
||||||
- accumulation happens directly to int32s
|
|
||||||
*/
|
|
||||||
|
|
||||||
namespace Stockfish::Eval::NNUE::Layers {
|
|
||||||
|
|
||||||
#if defined(USE_SSSE3) || defined(USE_NEON_DOTPROD)
|
|
||||||
#define ENABLE_SEQ_OPT
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Fallback implementation for older/other architectures.
|
|
||||||
// Requires the input to be padded to at least 16 values.
|
|
||||||
#ifndef ENABLE_SEQ_OPT
|
|
||||||
|
|
||||||
template<IndexType InputDimensions, IndexType PaddedInputDimensions, IndexType OutputDimensions>
|
|
||||||
static void affine_transform_non_ssse3(std::int32_t* output,
|
|
||||||
const std::int8_t* weights,
|
|
||||||
const std::int32_t* biases,
|
|
||||||
const std::uint8_t* input) {
|
|
||||||
#if defined(USE_SSE2) || defined(USE_NEON)
|
|
||||||
#if defined(USE_SSE2)
|
|
||||||
// At least a multiple of 16, with SSE2.
|
|
||||||
constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
|
|
||||||
const __m128i Zeros = _mm_setzero_si128();
|
|
||||||
const auto inputVector = reinterpret_cast<const __m128i*>(input);
|
|
||||||
|
|
||||||
#elif defined(USE_NEON)
|
|
||||||
constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 16) / 16;
|
|
||||||
const auto inputVector = reinterpret_cast<const int8x8_t*>(input);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
for (IndexType i = 0; i < OutputDimensions; ++i)
|
|
||||||
{
|
|
||||||
const IndexType offset = i * PaddedInputDimensions;
|
|
||||||
|
|
||||||
#if defined(USE_SSE2)
|
|
||||||
__m128i sumLo = _mm_cvtsi32_si128(biases[i]);
|
|
||||||
__m128i sumHi = Zeros;
|
|
||||||
const auto row = reinterpret_cast<const __m128i*>(&weights[offset]);
|
|
||||||
for (IndexType j = 0; j < NumChunks; ++j)
|
|
||||||
{
|
|
||||||
__m128i row_j = _mm_load_si128(&row[j]);
|
|
||||||
__m128i input_j = _mm_load_si128(&inputVector[j]);
|
|
||||||
__m128i extendedRowLo = _mm_srai_epi16(_mm_unpacklo_epi8(row_j, row_j), 8);
|
|
||||||
__m128i extendedRowHi = _mm_srai_epi16(_mm_unpackhi_epi8(row_j, row_j), 8);
|
|
||||||
__m128i extendedInputLo = _mm_unpacklo_epi8(input_j, Zeros);
|
|
||||||
__m128i extendedInputHi = _mm_unpackhi_epi8(input_j, Zeros);
|
|
||||||
__m128i productLo = _mm_madd_epi16(extendedRowLo, extendedInputLo);
|
|
||||||
__m128i productHi = _mm_madd_epi16(extendedRowHi, extendedInputHi);
|
|
||||||
sumLo = _mm_add_epi32(sumLo, productLo);
|
|
||||||
sumHi = _mm_add_epi32(sumHi, productHi);
|
|
||||||
}
|
|
||||||
__m128i sum = _mm_add_epi32(sumLo, sumHi);
|
|
||||||
__m128i sumHigh_64 = _mm_shuffle_epi32(sum, _MM_SHUFFLE(1, 0, 3, 2));
|
|
||||||
sum = _mm_add_epi32(sum, sumHigh_64);
|
|
||||||
__m128i sum_second_32 = _mm_shufflelo_epi16(sum, _MM_SHUFFLE(1, 0, 3, 2));
|
|
||||||
sum = _mm_add_epi32(sum, sum_second_32);
|
|
||||||
output[i] = _mm_cvtsi128_si32(sum);
|
|
||||||
|
|
||||||
#elif defined(USE_NEON)
|
|
||||||
|
|
||||||
int32x4_t sum = {biases[i]};
|
|
||||||
const auto row = reinterpret_cast<const int8x8_t*>(&weights[offset]);
|
|
||||||
for (IndexType j = 0; j < NumChunks; ++j)
|
|
||||||
{
|
|
||||||
int16x8_t product = vmull_s8(inputVector[j * 2], row[j * 2]);
|
|
||||||
product = vmlal_s8(product, inputVector[j * 2 + 1], row[j * 2 + 1]);
|
|
||||||
sum = vpadalq_s16(sum, product);
|
|
||||||
}
|
|
||||||
output[i] = sum[0] + sum[1] + sum[2] + sum[3];
|
|
||||||
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
std::memcpy(output, biases, sizeof(std::int32_t) * OutputDimensions);
|
|
||||||
|
|
||||||
// Traverse weights in transpose order to take advantage of input sparsity
|
|
||||||
for (IndexType i = 0; i < InputDimensions; ++i)
|
|
||||||
if (input[i])
|
|
||||||
{
|
|
||||||
const std::int8_t* w = &weights[i];
|
|
||||||
const int in = input[i];
|
|
||||||
for (IndexType j = 0; j < OutputDimensions; ++j)
|
|
||||||
output[j] += w[j * PaddedInputDimensions] * in;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif // !ENABLE_SEQ_OPT
|
|
||||||
|
|
||||||
template<IndexType InDims, IndexType OutDims>
|
|
||||||
class AffineTransform {
|
|
||||||
public:
|
|
||||||
// Input/output type
|
|
||||||
using InputType = std::uint8_t;
|
|
||||||
using OutputType = std::int32_t;
|
|
||||||
|
|
||||||
// Number of input/output dimensions
|
|
||||||
static constexpr IndexType InputDimensions = InDims;
|
|
||||||
static constexpr IndexType OutputDimensions = OutDims;
|
|
||||||
|
|
||||||
static constexpr IndexType PaddedInputDimensions =
|
|
||||||
ceil_to_multiple<IndexType>(InputDimensions, MaxSimdWidth);
|
|
||||||
static constexpr IndexType PaddedOutputDimensions =
|
|
||||||
ceil_to_multiple<IndexType>(OutputDimensions, MaxSimdWidth);
|
|
||||||
|
|
||||||
using OutputBuffer = OutputType[PaddedOutputDimensions];
|
|
||||||
|
|
||||||
// Hash value embedded in the evaluation file
|
|
||||||
static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
|
|
||||||
std::uint32_t hashValue = 0xCC03DAE4u;
|
|
||||||
hashValue += OutputDimensions;
|
|
||||||
hashValue ^= prevHash >> 1;
|
|
||||||
hashValue ^= prevHash << 31;
|
|
||||||
return hashValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
static constexpr IndexType get_weight_index_scrambled(IndexType i) {
|
|
||||||
return (i / 4) % (PaddedInputDimensions / 4) * OutputDimensions * 4
|
|
||||||
+ i / PaddedInputDimensions * 4 + i % 4;
|
|
||||||
}
|
|
||||||
|
|
||||||
static constexpr IndexType get_weight_index(IndexType i) {
|
|
||||||
#ifdef ENABLE_SEQ_OPT
|
|
||||||
return get_weight_index_scrambled(i);
|
|
||||||
#else
|
|
||||||
return i;
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read network parameters
|
|
||||||
bool read_parameters(std::istream& stream) {
|
|
||||||
read_little_endian<BiasType>(stream, biases, OutputDimensions);
|
|
||||||
for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
|
|
||||||
weights[get_weight_index(i)] = read_little_endian<WeightType>(stream);
|
|
||||||
|
|
||||||
return !stream.fail();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write network parameters
|
|
||||||
bool write_parameters(std::ostream& stream) const {
|
|
||||||
write_little_endian<BiasType>(stream, biases, OutputDimensions);
|
|
||||||
|
|
||||||
for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
|
|
||||||
write_little_endian<WeightType>(stream, weights[get_weight_index(i)]);
|
|
||||||
|
|
||||||
return !stream.fail();
|
|
||||||
}
|
|
||||||
// Forward propagation
|
|
||||||
void propagate(const InputType* input, OutputType* output) const {
|
|
||||||
|
|
||||||
#ifdef ENABLE_SEQ_OPT
|
|
||||||
|
|
||||||
if constexpr (OutputDimensions > 1)
|
|
||||||
{
|
|
||||||
#if defined(USE_AVX512)
|
|
||||||
using vec_t = __m512i;
|
|
||||||
#define vec_set_32 _mm512_set1_epi32
|
|
||||||
#define vec_add_dpbusd_32 Simd::m512_add_dpbusd_epi32
|
|
||||||
#elif defined(USE_AVX2)
|
|
||||||
using vec_t = __m256i;
|
|
||||||
#define vec_set_32 _mm256_set1_epi32
|
|
||||||
#define vec_add_dpbusd_32 Simd::m256_add_dpbusd_epi32
|
|
||||||
#elif defined(USE_SSSE3)
|
|
||||||
using vec_t = __m128i;
|
|
||||||
#define vec_set_32 _mm_set1_epi32
|
|
||||||
#define vec_add_dpbusd_32 Simd::m128_add_dpbusd_epi32
|
|
||||||
#elif defined(USE_NEON_DOTPROD)
|
|
||||||
using vec_t = int32x4_t;
|
|
||||||
#define vec_set_32 vdupq_n_s32
|
|
||||||
#define vec_add_dpbusd_32(acc, a, b) \
|
|
||||||
Simd::dotprod_m128_add_dpbusd_epi32(acc, vreinterpretq_s8_s32(a), \
|
|
||||||
vreinterpretq_s8_s32(b))
|
|
||||||
#endif
|
|
||||||
|
|
||||||
static constexpr IndexType OutputSimdWidth = sizeof(vec_t) / sizeof(OutputType);
|
|
||||||
|
|
||||||
static_assert(OutputDimensions % OutputSimdWidth == 0);
|
|
||||||
|
|
||||||
constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 8) / 4;
|
|
||||||
constexpr IndexType NumRegs = OutputDimensions / OutputSimdWidth;
|
|
||||||
|
|
||||||
const auto input32 = reinterpret_cast<const std::int32_t*>(input);
|
|
||||||
const vec_t* biasvec = reinterpret_cast<const vec_t*>(biases);
|
|
||||||
vec_t acc[NumRegs];
|
|
||||||
for (IndexType k = 0; k < NumRegs; ++k)
|
|
||||||
acc[k] = biasvec[k];
|
|
||||||
|
|
||||||
for (IndexType i = 0; i < NumChunks; ++i)
|
|
||||||
{
|
|
||||||
const vec_t in0 = vec_set_32(input32[i]);
|
|
||||||
const auto col0 =
|
|
||||||
reinterpret_cast<const vec_t*>(&weights[i * OutputDimensions * 4]);
|
|
||||||
|
|
||||||
for (IndexType k = 0; k < NumRegs; ++k)
|
|
||||||
vec_add_dpbusd_32(acc[k], in0, col0[k]);
|
|
||||||
}
|
|
||||||
|
|
||||||
vec_t* outptr = reinterpret_cast<vec_t*>(output);
|
|
||||||
for (IndexType k = 0; k < NumRegs; ++k)
|
|
||||||
outptr[k] = acc[k];
|
|
||||||
|
|
||||||
#undef vec_set_32
|
|
||||||
#undef vec_add_dpbusd_32
|
|
||||||
}
|
|
||||||
else if constexpr (OutputDimensions == 1)
|
|
||||||
{
|
|
||||||
// We cannot use AVX512 for the last layer because there are only 32 inputs
|
|
||||||
// and the buffer is not padded to 64 elements.
|
|
||||||
#if defined(USE_AVX2)
|
|
||||||
using vec_t = __m256i;
|
|
||||||
#define vec_setzero() _mm256_setzero_si256()
|
|
||||||
#define vec_set_32 _mm256_set1_epi32
|
|
||||||
#define vec_add_dpbusd_32 Simd::m256_add_dpbusd_epi32
|
|
||||||
#define vec_hadd Simd::m256_hadd
|
|
||||||
#elif defined(USE_SSSE3)
|
|
||||||
using vec_t = __m128i;
|
|
||||||
#define vec_setzero() _mm_setzero_si128()
|
|
||||||
#define vec_set_32 _mm_set1_epi32
|
|
||||||
#define vec_add_dpbusd_32 Simd::m128_add_dpbusd_epi32
|
|
||||||
#define vec_hadd Simd::m128_hadd
|
|
||||||
#elif defined(USE_NEON_DOTPROD)
|
|
||||||
using vec_t = int32x4_t;
|
|
||||||
#define vec_setzero() vdupq_n_s32(0)
|
|
||||||
#define vec_set_32 vdupq_n_s32
|
|
||||||
#define vec_add_dpbusd_32(acc, a, b) \
|
|
||||||
Simd::dotprod_m128_add_dpbusd_epi32(acc, vreinterpretq_s8_s32(a), \
|
|
||||||
vreinterpretq_s8_s32(b))
|
|
||||||
#define vec_hadd Simd::neon_m128_hadd
|
|
||||||
#endif
|
|
||||||
|
|
||||||
const auto inputVector = reinterpret_cast<const vec_t*>(input);
|
|
||||||
|
|
||||||
static constexpr IndexType InputSimdWidth = sizeof(vec_t) / sizeof(InputType);
|
|
||||||
|
|
||||||
static_assert(PaddedInputDimensions % InputSimdWidth == 0);
|
|
||||||
|
|
||||||
constexpr IndexType NumChunks = PaddedInputDimensions / InputSimdWidth;
|
|
||||||
vec_t sum0 = vec_setzero();
|
|
||||||
const auto row0 = reinterpret_cast<const vec_t*>(&weights[0]);
|
|
||||||
|
|
||||||
for (int j = 0; j < int(NumChunks); ++j)
|
|
||||||
{
|
|
||||||
const vec_t in = inputVector[j];
|
|
||||||
vec_add_dpbusd_32(sum0, in, row0[j]);
|
|
||||||
}
|
|
||||||
output[0] = vec_hadd(sum0, biases[0]);
|
|
||||||
|
|
||||||
#undef vec_setzero
|
|
||||||
#undef vec_set_32
|
|
||||||
#undef vec_add_dpbusd_32
|
|
||||||
#undef vec_hadd
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
// Use old implementation for the other architectures.
|
|
||||||
affine_transform_non_ssse3<InputDimensions, PaddedInputDimensions, OutputDimensions>(
|
|
||||||
output, weights, biases, input);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
using BiasType = OutputType;
|
|
||||||
using WeightType = std::int8_t;
|
|
||||||
|
|
||||||
alignas(CacheLineSize) BiasType biases[OutputDimensions];
|
|
||||||
alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Stockfish::Eval::NNUE::Layers
|
|
||||||
|
|
||||||
#endif // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_H_INCLUDED
|
|
||||||
@@ -1,278 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Definition of layer AffineTransformSparseInput of NNUE evaluation function
|
|
||||||
|
|
||||||
#ifndef NNUE_LAYERS_AFFINE_TRANSFORM_SPARSE_INPUT_H_INCLUDED
|
|
||||||
#define NNUE_LAYERS_AFFINE_TRANSFORM_SPARSE_INPUT_H_INCLUDED
|
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <array>
|
|
||||||
#include <cstdint>
|
|
||||||
#include <iostream>
|
|
||||||
|
|
||||||
#include "../../bitboard.h"
|
|
||||||
#include "../nnue_common.h"
|
|
||||||
#include "affine_transform.h"
|
|
||||||
#include "simd.h"
|
|
||||||
|
|
||||||
/*
|
|
||||||
This file contains the definition for a fully connected layer (aka affine transform) with block sparse input.
|
|
||||||
*/
|
|
||||||
|
|
||||||
namespace Stockfish::Eval::NNUE::Layers {
|
|
||||||
|
|
||||||
#if (USE_SSSE3 | (USE_NEON >= 8))
|
|
||||||
alignas(CacheLineSize) static inline const
|
|
||||||
std::array<std::array<std::uint16_t, 8>, 256> lookup_indices = []() {
|
|
||||||
std::array<std::array<std::uint16_t, 8>, 256> v{};
|
|
||||||
for (unsigned i = 0; i < 256; ++i)
|
|
||||||
{
|
|
||||||
std::uint64_t j = i, k = 0;
|
|
||||||
while (j)
|
|
||||||
v[i][k++] = pop_lsb(j);
|
|
||||||
}
|
|
||||||
return v;
|
|
||||||
}();
|
|
||||||
|
|
||||||
// Find indices of nonzero numbers in an int32_t array
|
|
||||||
template<const IndexType InputDimensions>
|
|
||||||
void find_nnz(const std::int32_t* input, std::uint16_t* out, IndexType& count_out) {
|
|
||||||
#if defined(USE_SSSE3)
|
|
||||||
#if defined(USE_AVX512)
|
|
||||||
using vec_t = __m512i;
|
|
||||||
#define vec_nnz(a) _mm512_cmpgt_epi32_mask(a, _mm512_setzero_si512())
|
|
||||||
#elif defined(USE_AVX2)
|
|
||||||
using vec_t = __m256i;
|
|
||||||
#if defined(USE_VNNI) && !defined(USE_AVXVNNI)
|
|
||||||
#define vec_nnz(a) _mm256_cmpgt_epi32_mask(a, _mm256_setzero_si256())
|
|
||||||
#else
|
|
||||||
#define vec_nnz(a) \
|
|
||||||
_mm256_movemask_ps( \
|
|
||||||
_mm256_castsi256_ps(_mm256_cmpgt_epi32(a, _mm256_setzero_si256())))
|
|
||||||
#endif
|
|
||||||
#elif defined(USE_SSSE3)
|
|
||||||
using vec_t = __m128i;
|
|
||||||
#define vec_nnz(a) \
|
|
||||||
_mm_movemask_ps(_mm_castsi128_ps(_mm_cmpgt_epi32(a, _mm_setzero_si128())))
|
|
||||||
#endif
|
|
||||||
using vec128_t = __m128i;
|
|
||||||
#define vec128_zero _mm_setzero_si128()
|
|
||||||
#define vec128_set_16(a) _mm_set1_epi16(a)
|
|
||||||
#define vec128_load(a) _mm_load_si128(a)
|
|
||||||
#define vec128_storeu(a, b) _mm_storeu_si128(a, b)
|
|
||||||
#define vec128_add(a, b) _mm_add_epi16(a, b)
|
|
||||||
#elif defined(USE_NEON)
|
|
||||||
using vec_t = uint32x4_t;
|
|
||||||
static const std::uint32_t Mask[4] = {1, 2, 4, 8};
|
|
||||||
#define vec_nnz(a) vaddvq_u32(vandq_u32(vtstq_u32(a, a), vld1q_u32(Mask)))
|
|
||||||
using vec128_t = uint16x8_t;
|
|
||||||
#define vec128_zero vdupq_n_u16(0)
|
|
||||||
#define vec128_set_16(a) vdupq_n_u16(a)
|
|
||||||
#define vec128_load(a) vld1q_u16(reinterpret_cast<const std::uint16_t*>(a))
|
|
||||||
#define vec128_storeu(a, b) vst1q_u16(reinterpret_cast<std::uint16_t*>(a), b)
|
|
||||||
#define vec128_add(a, b) vaddq_u16(a, b)
|
|
||||||
#endif
|
|
||||||
constexpr IndexType InputSimdWidth = sizeof(vec_t) / sizeof(std::int32_t);
|
|
||||||
// Inputs are processed InputSimdWidth at a time and outputs are processed 8 at a time so we process in chunks of max(InputSimdWidth, 8)
|
|
||||||
constexpr IndexType ChunkSize = std::max<IndexType>(InputSimdWidth, 8);
|
|
||||||
constexpr IndexType NumChunks = InputDimensions / ChunkSize;
|
|
||||||
constexpr IndexType InputsPerChunk = ChunkSize / InputSimdWidth;
|
|
||||||
constexpr IndexType OutputsPerChunk = ChunkSize / 8;
|
|
||||||
|
|
||||||
const auto inputVector = reinterpret_cast<const vec_t*>(input);
|
|
||||||
IndexType count = 0;
|
|
||||||
vec128_t base = vec128_zero;
|
|
||||||
const vec128_t increment = vec128_set_16(8);
|
|
||||||
for (IndexType i = 0; i < NumChunks; ++i)
|
|
||||||
{
|
|
||||||
// bitmask of nonzero values in this chunk
|
|
||||||
unsigned nnz = 0;
|
|
||||||
for (IndexType j = 0; j < InputsPerChunk; ++j)
|
|
||||||
{
|
|
||||||
const vec_t inputChunk = inputVector[i * InputsPerChunk + j];
|
|
||||||
nnz |= unsigned(vec_nnz(inputChunk)) << (j * InputSimdWidth);
|
|
||||||
}
|
|
||||||
for (IndexType j = 0; j < OutputsPerChunk; ++j)
|
|
||||||
{
|
|
||||||
const auto lookup = (nnz >> (j * 8)) & 0xFF;
|
|
||||||
const auto offsets =
|
|
||||||
vec128_load(reinterpret_cast<const vec128_t*>(&lookup_indices[lookup]));
|
|
||||||
vec128_storeu(reinterpret_cast<vec128_t*>(out + count), vec128_add(base, offsets));
|
|
||||||
count += popcount(lookup);
|
|
||||||
base = vec128_add(base, increment);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
count_out = count;
|
|
||||||
}
|
|
||||||
#undef vec_nnz
|
|
||||||
#undef vec128_zero
|
|
||||||
#undef vec128_set_16
|
|
||||||
#undef vec128_load
|
|
||||||
#undef vec128_storeu
|
|
||||||
#undef vec128_add
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Sparse input implementation
|
|
||||||
template<IndexType InDims, IndexType OutDims>
|
|
||||||
class AffineTransformSparseInput {
|
|
||||||
public:
|
|
||||||
// Input/output type
|
|
||||||
using InputType = std::uint8_t;
|
|
||||||
using OutputType = std::int32_t;
|
|
||||||
|
|
||||||
// Number of input/output dimensions
|
|
||||||
static constexpr IndexType InputDimensions = InDims;
|
|
||||||
static constexpr IndexType OutputDimensions = OutDims;
|
|
||||||
|
|
||||||
static_assert(OutputDimensions % 16 == 0,
|
|
||||||
"Only implemented for OutputDimensions divisible by 16.");
|
|
||||||
|
|
||||||
static constexpr IndexType PaddedInputDimensions =
|
|
||||||
ceil_to_multiple<IndexType>(InputDimensions, MaxSimdWidth);
|
|
||||||
static constexpr IndexType PaddedOutputDimensions =
|
|
||||||
ceil_to_multiple<IndexType>(OutputDimensions, MaxSimdWidth);
|
|
||||||
|
|
||||||
#if (USE_SSSE3 | (USE_NEON >= 8))
|
|
||||||
static constexpr IndexType ChunkSize = 4;
|
|
||||||
#else
|
|
||||||
static constexpr IndexType ChunkSize = 1;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
using OutputBuffer = OutputType[PaddedOutputDimensions];
|
|
||||||
|
|
||||||
// Hash value embedded in the evaluation file
|
|
||||||
static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
|
|
||||||
std::uint32_t hashValue = 0xCC03DAE4u;
|
|
||||||
hashValue += OutputDimensions;
|
|
||||||
hashValue ^= prevHash >> 1;
|
|
||||||
hashValue ^= prevHash << 31;
|
|
||||||
return hashValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
static constexpr IndexType get_weight_index_scrambled(IndexType i) {
|
|
||||||
return (i / ChunkSize) % (PaddedInputDimensions / ChunkSize) * OutputDimensions * ChunkSize
|
|
||||||
+ i / PaddedInputDimensions * ChunkSize + i % ChunkSize;
|
|
||||||
}
|
|
||||||
|
|
||||||
static constexpr IndexType get_weight_index(IndexType i) {
|
|
||||||
#if (USE_SSSE3 | (USE_NEON >= 8))
|
|
||||||
return get_weight_index_scrambled(i);
|
|
||||||
#else
|
|
||||||
return i;
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read network parameters
|
|
||||||
bool read_parameters(std::istream& stream) {
|
|
||||||
read_little_endian<BiasType>(stream, biases, OutputDimensions);
|
|
||||||
for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
|
|
||||||
weights[get_weight_index(i)] = read_little_endian<WeightType>(stream);
|
|
||||||
|
|
||||||
return !stream.fail();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write network parameters
|
|
||||||
bool write_parameters(std::ostream& stream) const {
|
|
||||||
write_little_endian<BiasType>(stream, biases, OutputDimensions);
|
|
||||||
|
|
||||||
for (IndexType i = 0; i < OutputDimensions * PaddedInputDimensions; ++i)
|
|
||||||
write_little_endian<WeightType>(stream, weights[get_weight_index(i)]);
|
|
||||||
|
|
||||||
return !stream.fail();
|
|
||||||
}
|
|
||||||
// Forward propagation
|
|
||||||
void propagate(const InputType* input, OutputType* output) const {
|
|
||||||
|
|
||||||
#if (USE_SSSE3 | (USE_NEON >= 8))
|
|
||||||
#if defined(USE_AVX512)
|
|
||||||
using invec_t = __m512i;
|
|
||||||
using outvec_t = __m512i;
|
|
||||||
#define vec_set_32 _mm512_set1_epi32
|
|
||||||
#define vec_add_dpbusd_32 Simd::m512_add_dpbusd_epi32
|
|
||||||
#elif defined(USE_AVX2)
|
|
||||||
using invec_t = __m256i;
|
|
||||||
using outvec_t = __m256i;
|
|
||||||
#define vec_set_32 _mm256_set1_epi32
|
|
||||||
#define vec_add_dpbusd_32 Simd::m256_add_dpbusd_epi32
|
|
||||||
#elif defined(USE_SSSE3)
|
|
||||||
using invec_t = __m128i;
|
|
||||||
using outvec_t = __m128i;
|
|
||||||
#define vec_set_32 _mm_set1_epi32
|
|
||||||
#define vec_add_dpbusd_32 Simd::m128_add_dpbusd_epi32
|
|
||||||
#elif defined(USE_NEON_DOTPROD)
|
|
||||||
using invec_t = int8x16_t;
|
|
||||||
using outvec_t = int32x4_t;
|
|
||||||
#define vec_set_32(a) vreinterpretq_s8_u32(vdupq_n_u32(a))
|
|
||||||
#define vec_add_dpbusd_32 Simd::dotprod_m128_add_dpbusd_epi32
|
|
||||||
#elif defined(USE_NEON)
|
|
||||||
using invec_t = int8x16_t;
|
|
||||||
using outvec_t = int32x4_t;
|
|
||||||
#define vec_set_32(a) vreinterpretq_s8_u32(vdupq_n_u32(a))
|
|
||||||
#define vec_add_dpbusd_32 Simd::neon_m128_add_dpbusd_epi32
|
|
||||||
#endif
|
|
||||||
static constexpr IndexType OutputSimdWidth = sizeof(outvec_t) / sizeof(OutputType);
|
|
||||||
|
|
||||||
constexpr IndexType NumChunks = ceil_to_multiple<IndexType>(InputDimensions, 8) / ChunkSize;
|
|
||||||
constexpr IndexType NumRegs = OutputDimensions / OutputSimdWidth;
|
|
||||||
std::uint16_t nnz[NumChunks];
|
|
||||||
IndexType count;
|
|
||||||
|
|
||||||
const auto input32 = reinterpret_cast<const std::int32_t*>(input);
|
|
||||||
|
|
||||||
// Find indices of nonzero 32-bit blocks
|
|
||||||
find_nnz<NumChunks>(input32, nnz, count);
|
|
||||||
|
|
||||||
const outvec_t* biasvec = reinterpret_cast<const outvec_t*>(biases);
|
|
||||||
outvec_t acc[NumRegs];
|
|
||||||
for (IndexType k = 0; k < NumRegs; ++k)
|
|
||||||
acc[k] = biasvec[k];
|
|
||||||
|
|
||||||
for (IndexType j = 0; j < count; ++j)
|
|
||||||
{
|
|
||||||
const auto i = nnz[j];
|
|
||||||
const invec_t in = vec_set_32(input32[i]);
|
|
||||||
const auto col =
|
|
||||||
reinterpret_cast<const invec_t*>(&weights[i * OutputDimensions * ChunkSize]);
|
|
||||||
for (IndexType k = 0; k < NumRegs; ++k)
|
|
||||||
vec_add_dpbusd_32(acc[k], in, col[k]);
|
|
||||||
}
|
|
||||||
|
|
||||||
outvec_t* outptr = reinterpret_cast<outvec_t*>(output);
|
|
||||||
for (IndexType k = 0; k < NumRegs; ++k)
|
|
||||||
outptr[k] = acc[k];
|
|
||||||
#undef vec_set_32
|
|
||||||
#undef vec_add_dpbusd_32
|
|
||||||
#else
|
|
||||||
// Use dense implementation for the other architectures.
|
|
||||||
affine_transform_non_ssse3<InputDimensions, PaddedInputDimensions, OutputDimensions>(
|
|
||||||
output, weights, biases, input);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
using BiasType = OutputType;
|
|
||||||
using WeightType = std::int8_t;
|
|
||||||
|
|
||||||
alignas(CacheLineSize) BiasType biases[OutputDimensions];
|
|
||||||
alignas(CacheLineSize) WeightType weights[OutputDimensions * PaddedInputDimensions];
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Stockfish::Eval::NNUE::Layers
|
|
||||||
|
|
||||||
#endif // #ifndef NNUE_LAYERS_AFFINE_TRANSFORM_SPARSE_INPUT_H_INCLUDED
|
|
||||||
@@ -1,164 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Definition of layer ClippedReLU of NNUE evaluation function
|
|
||||||
|
|
||||||
#ifndef NNUE_LAYERS_CLIPPED_RELU_H_INCLUDED
|
|
||||||
#define NNUE_LAYERS_CLIPPED_RELU_H_INCLUDED
|
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <cstdint>
|
|
||||||
#include <iosfwd>
|
|
||||||
|
|
||||||
#include "../nnue_common.h"
|
|
||||||
|
|
||||||
namespace Stockfish::Eval::NNUE::Layers {
|
|
||||||
|
|
||||||
// Clipped ReLU
|
|
||||||
template<IndexType InDims>
|
|
||||||
class ClippedReLU {
|
|
||||||
public:
|
|
||||||
// Input/output type
|
|
||||||
using InputType = std::int32_t;
|
|
||||||
using OutputType = std::uint8_t;
|
|
||||||
|
|
||||||
// Number of input/output dimensions
|
|
||||||
static constexpr IndexType InputDimensions = InDims;
|
|
||||||
static constexpr IndexType OutputDimensions = InputDimensions;
|
|
||||||
static constexpr IndexType PaddedOutputDimensions =
|
|
||||||
ceil_to_multiple<IndexType>(OutputDimensions, 32);
|
|
||||||
|
|
||||||
using OutputBuffer = OutputType[PaddedOutputDimensions];
|
|
||||||
|
|
||||||
// Hash value embedded in the evaluation file
|
|
||||||
static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
|
|
||||||
std::uint32_t hashValue = 0x538D24C7u;
|
|
||||||
hashValue += prevHash;
|
|
||||||
return hashValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read network parameters
|
|
||||||
bool read_parameters(std::istream&) { return true; }
|
|
||||||
|
|
||||||
// Write network parameters
|
|
||||||
bool write_parameters(std::ostream&) const { return true; }
|
|
||||||
|
|
||||||
// Forward propagation
|
|
||||||
void propagate(const InputType* input, OutputType* output) const {
|
|
||||||
|
|
||||||
#if defined(USE_AVX2)
|
|
||||||
if constexpr (InputDimensions % SimdWidth == 0)
|
|
||||||
{
|
|
||||||
constexpr IndexType NumChunks = InputDimensions / SimdWidth;
|
|
||||||
const __m256i Offsets = _mm256_set_epi32(7, 3, 6, 2, 5, 1, 4, 0);
|
|
||||||
const auto in = reinterpret_cast<const __m256i*>(input);
|
|
||||||
const auto out = reinterpret_cast<__m256i*>(output);
|
|
||||||
for (IndexType i = 0; i < NumChunks; ++i)
|
|
||||||
{
|
|
||||||
const __m256i words0 =
|
|
||||||
_mm256_srli_epi16(_mm256_packus_epi32(_mm256_load_si256(&in[i * 4 + 0]),
|
|
||||||
_mm256_load_si256(&in[i * 4 + 1])),
|
|
||||||
WeightScaleBits);
|
|
||||||
const __m256i words1 =
|
|
||||||
_mm256_srli_epi16(_mm256_packus_epi32(_mm256_load_si256(&in[i * 4 + 2]),
|
|
||||||
_mm256_load_si256(&in[i * 4 + 3])),
|
|
||||||
WeightScaleBits);
|
|
||||||
_mm256_store_si256(&out[i], _mm256_permutevar8x32_epi32(
|
|
||||||
_mm256_packs_epi16(words0, words1), Offsets));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
constexpr IndexType NumChunks = InputDimensions / (SimdWidth / 2);
|
|
||||||
const auto in = reinterpret_cast<const __m128i*>(input);
|
|
||||||
const auto out = reinterpret_cast<__m128i*>(output);
|
|
||||||
for (IndexType i = 0; i < NumChunks; ++i)
|
|
||||||
{
|
|
||||||
const __m128i words0 = _mm_srli_epi16(
|
|
||||||
_mm_packus_epi32(_mm_load_si128(&in[i * 4 + 0]), _mm_load_si128(&in[i * 4 + 1])),
|
|
||||||
WeightScaleBits);
|
|
||||||
const __m128i words1 = _mm_srli_epi16(
|
|
||||||
_mm_packus_epi32(_mm_load_si128(&in[i * 4 + 2]), _mm_load_si128(&in[i * 4 + 3])),
|
|
||||||
WeightScaleBits);
|
|
||||||
_mm_store_si128(&out[i], _mm_packs_epi16(words0, words1));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
constexpr IndexType Start = InputDimensions % SimdWidth == 0
|
|
||||||
? InputDimensions / SimdWidth * SimdWidth
|
|
||||||
: InputDimensions / (SimdWidth / 2) * (SimdWidth / 2);
|
|
||||||
|
|
||||||
#elif defined(USE_SSE2)
|
|
||||||
constexpr IndexType NumChunks = InputDimensions / SimdWidth;
|
|
||||||
|
|
||||||
#ifndef USE_SSE41
|
|
||||||
const __m128i k0x80s = _mm_set1_epi8(-128);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
const auto in = reinterpret_cast<const __m128i*>(input);
|
|
||||||
const auto out = reinterpret_cast<__m128i*>(output);
|
|
||||||
for (IndexType i = 0; i < NumChunks; ++i)
|
|
||||||
{
|
|
||||||
#if defined(USE_SSE41)
|
|
||||||
const __m128i words0 = _mm_srli_epi16(
|
|
||||||
_mm_packus_epi32(_mm_load_si128(&in[i * 4 + 0]), _mm_load_si128(&in[i * 4 + 1])),
|
|
||||||
WeightScaleBits);
|
|
||||||
const __m128i words1 = _mm_srli_epi16(
|
|
||||||
_mm_packus_epi32(_mm_load_si128(&in[i * 4 + 2]), _mm_load_si128(&in[i * 4 + 3])),
|
|
||||||
WeightScaleBits);
|
|
||||||
_mm_store_si128(&out[i], _mm_packs_epi16(words0, words1));
|
|
||||||
#else
|
|
||||||
const __m128i words0 = _mm_srai_epi16(
|
|
||||||
_mm_packs_epi32(_mm_load_si128(&in[i * 4 + 0]), _mm_load_si128(&in[i * 4 + 1])),
|
|
||||||
WeightScaleBits);
|
|
||||||
const __m128i words1 = _mm_srai_epi16(
|
|
||||||
_mm_packs_epi32(_mm_load_si128(&in[i * 4 + 2]), _mm_load_si128(&in[i * 4 + 3])),
|
|
||||||
WeightScaleBits);
|
|
||||||
const __m128i packedbytes = _mm_packs_epi16(words0, words1);
|
|
||||||
_mm_store_si128(&out[i], _mm_subs_epi8(_mm_adds_epi8(packedbytes, k0x80s), k0x80s));
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
constexpr IndexType Start = NumChunks * SimdWidth;
|
|
||||||
|
|
||||||
#elif defined(USE_NEON)
|
|
||||||
constexpr IndexType NumChunks = InputDimensions / (SimdWidth / 2);
|
|
||||||
const int8x8_t Zero = {0};
|
|
||||||
const auto in = reinterpret_cast<const int32x4_t*>(input);
|
|
||||||
const auto out = reinterpret_cast<int8x8_t*>(output);
|
|
||||||
for (IndexType i = 0; i < NumChunks; ++i)
|
|
||||||
{
|
|
||||||
int16x8_t shifted;
|
|
||||||
const auto pack = reinterpret_cast<int16x4_t*>(&shifted);
|
|
||||||
pack[0] = vqshrn_n_s32(in[i * 2 + 0], WeightScaleBits);
|
|
||||||
pack[1] = vqshrn_n_s32(in[i * 2 + 1], WeightScaleBits);
|
|
||||||
out[i] = vmax_s8(vqmovn_s16(shifted), Zero);
|
|
||||||
}
|
|
||||||
constexpr IndexType Start = NumChunks * (SimdWidth / 2);
|
|
||||||
#else
|
|
||||||
constexpr IndexType Start = 0;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
for (IndexType i = Start; i < InputDimensions; ++i)
|
|
||||||
{
|
|
||||||
output[i] = static_cast<OutputType>(std::clamp(input[i] >> WeightScaleBits, 0, 127));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Stockfish::Eval::NNUE::Layers
|
|
||||||
|
|
||||||
#endif // NNUE_LAYERS_CLIPPED_RELU_H_INCLUDED
|
|
||||||
@@ -1,134 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef STOCKFISH_SIMD_H_INCLUDED
|
|
||||||
#define STOCKFISH_SIMD_H_INCLUDED
|
|
||||||
|
|
||||||
#if defined(USE_AVX2)
|
|
||||||
#include <immintrin.h>
|
|
||||||
|
|
||||||
#elif defined(USE_SSE41)
|
|
||||||
#include <smmintrin.h>
|
|
||||||
|
|
||||||
#elif defined(USE_SSSE3)
|
|
||||||
#include <tmmintrin.h>
|
|
||||||
|
|
||||||
#elif defined(USE_SSE2)
|
|
||||||
#include <emmintrin.h>
|
|
||||||
|
|
||||||
#elif defined(USE_NEON)
|
|
||||||
#include <arm_neon.h>
|
|
||||||
#endif
|
|
||||||
|
|
||||||
namespace Stockfish::Simd {
|
|
||||||
|
|
||||||
#if defined(USE_AVX512)
|
|
||||||
|
|
||||||
[[maybe_unused]] static int m512_hadd(__m512i sum, int bias) {
|
|
||||||
return _mm512_reduce_add_epi32(sum) + bias;
|
|
||||||
}
|
|
||||||
|
|
||||||
[[maybe_unused]] static void m512_add_dpbusd_epi32(__m512i& acc, __m512i a, __m512i b) {
|
|
||||||
|
|
||||||
#if defined(USE_VNNI)
|
|
||||||
acc = _mm512_dpbusd_epi32(acc, a, b);
|
|
||||||
#else
|
|
||||||
__m512i product0 = _mm512_maddubs_epi16(a, b);
|
|
||||||
product0 = _mm512_madd_epi16(product0, _mm512_set1_epi16(1));
|
|
||||||
acc = _mm512_add_epi32(acc, product0);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if defined(USE_AVX2)
|
|
||||||
|
|
||||||
[[maybe_unused]] static int m256_hadd(__m256i sum, int bias) {
|
|
||||||
__m128i sum128 = _mm_add_epi32(_mm256_castsi256_si128(sum), _mm256_extracti128_si256(sum, 1));
|
|
||||||
sum128 = _mm_add_epi32(sum128, _mm_shuffle_epi32(sum128, _MM_PERM_BADC));
|
|
||||||
sum128 = _mm_add_epi32(sum128, _mm_shuffle_epi32(sum128, _MM_PERM_CDAB));
|
|
||||||
return _mm_cvtsi128_si32(sum128) + bias;
|
|
||||||
}
|
|
||||||
|
|
||||||
[[maybe_unused]] static void m256_add_dpbusd_epi32(__m256i& acc, __m256i a, __m256i b) {
|
|
||||||
|
|
||||||
#if defined(USE_VNNI)
|
|
||||||
acc = _mm256_dpbusd_epi32(acc, a, b);
|
|
||||||
#else
|
|
||||||
__m256i product0 = _mm256_maddubs_epi16(a, b);
|
|
||||||
product0 = _mm256_madd_epi16(product0, _mm256_set1_epi16(1));
|
|
||||||
acc = _mm256_add_epi32(acc, product0);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if defined(USE_SSSE3)
|
|
||||||
|
|
||||||
[[maybe_unused]] static int m128_hadd(__m128i sum, int bias) {
|
|
||||||
sum = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, 0x4E)); //_MM_PERM_BADC
|
|
||||||
sum = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, 0xB1)); //_MM_PERM_CDAB
|
|
||||||
return _mm_cvtsi128_si32(sum) + bias;
|
|
||||||
}
|
|
||||||
|
|
||||||
[[maybe_unused]] static void m128_add_dpbusd_epi32(__m128i& acc, __m128i a, __m128i b) {
|
|
||||||
|
|
||||||
__m128i product0 = _mm_maddubs_epi16(a, b);
|
|
||||||
product0 = _mm_madd_epi16(product0, _mm_set1_epi16(1));
|
|
||||||
acc = _mm_add_epi32(acc, product0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if defined(USE_NEON_DOTPROD)
|
|
||||||
|
|
||||||
[[maybe_unused]] static void
|
|
||||||
dotprod_m128_add_dpbusd_epi32(int32x4_t& acc, int8x16_t a, int8x16_t b) {
|
|
||||||
|
|
||||||
acc = vdotq_s32(acc, a, b);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if defined(USE_NEON)
|
|
||||||
|
|
||||||
[[maybe_unused]] static int neon_m128_reduce_add_epi32(int32x4_t s) {
|
|
||||||
#if USE_NEON >= 8
|
|
||||||
return vaddvq_s32(s);
|
|
||||||
#else
|
|
||||||
return s[0] + s[1] + s[2] + s[3];
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
[[maybe_unused]] static int neon_m128_hadd(int32x4_t sum, int bias) {
|
|
||||||
return neon_m128_reduce_add_epi32(sum) + bias;
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if USE_NEON >= 8
|
|
||||||
[[maybe_unused]] static void neon_m128_add_dpbusd_epi32(int32x4_t& acc, int8x16_t a, int8x16_t b) {
|
|
||||||
|
|
||||||
int16x8_t product0 = vmull_s8(vget_low_s8(a), vget_low_s8(b));
|
|
||||||
int16x8_t product1 = vmull_high_s8(a, b);
|
|
||||||
int16x8_t sum = vpaddq_s16(product0, product1);
|
|
||||||
acc = vpadalq_s16(acc, sum);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif // STOCKFISH_SIMD_H_INCLUDED
|
|
||||||
@@ -1,103 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Definition of layer ClippedReLU of NNUE evaluation function
|
|
||||||
|
|
||||||
#ifndef NNUE_LAYERS_SQR_CLIPPED_RELU_H_INCLUDED
|
|
||||||
#define NNUE_LAYERS_SQR_CLIPPED_RELU_H_INCLUDED
|
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <cstdint>
|
|
||||||
#include <iosfwd>
|
|
||||||
|
|
||||||
#include "../nnue_common.h"
|
|
||||||
|
|
||||||
namespace Stockfish::Eval::NNUE::Layers {
|
|
||||||
|
|
||||||
// Clipped ReLU
|
|
||||||
template<IndexType InDims>
|
|
||||||
class SqrClippedReLU {
|
|
||||||
public:
|
|
||||||
// Input/output type
|
|
||||||
using InputType = std::int32_t;
|
|
||||||
using OutputType = std::uint8_t;
|
|
||||||
|
|
||||||
// Number of input/output dimensions
|
|
||||||
static constexpr IndexType InputDimensions = InDims;
|
|
||||||
static constexpr IndexType OutputDimensions = InputDimensions;
|
|
||||||
static constexpr IndexType PaddedOutputDimensions =
|
|
||||||
ceil_to_multiple<IndexType>(OutputDimensions, 32);
|
|
||||||
|
|
||||||
using OutputBuffer = OutputType[PaddedOutputDimensions];
|
|
||||||
|
|
||||||
// Hash value embedded in the evaluation file
|
|
||||||
static constexpr std::uint32_t get_hash_value(std::uint32_t prevHash) {
|
|
||||||
std::uint32_t hashValue = 0x538D24C7u;
|
|
||||||
hashValue += prevHash;
|
|
||||||
return hashValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read network parameters
|
|
||||||
bool read_parameters(std::istream&) { return true; }
|
|
||||||
|
|
||||||
// Write network parameters
|
|
||||||
bool write_parameters(std::ostream&) const { return true; }
|
|
||||||
|
|
||||||
// Forward propagation
|
|
||||||
void propagate(const InputType* input, OutputType* output) const {
|
|
||||||
|
|
||||||
#if defined(USE_SSE2)
|
|
||||||
constexpr IndexType NumChunks = InputDimensions / 16;
|
|
||||||
|
|
||||||
static_assert(WeightScaleBits == 6);
|
|
||||||
const auto in = reinterpret_cast<const __m128i*>(input);
|
|
||||||
const auto out = reinterpret_cast<__m128i*>(output);
|
|
||||||
for (IndexType i = 0; i < NumChunks; ++i)
|
|
||||||
{
|
|
||||||
__m128i words0 =
|
|
||||||
_mm_packs_epi32(_mm_load_si128(&in[i * 4 + 0]), _mm_load_si128(&in[i * 4 + 1]));
|
|
||||||
__m128i words1 =
|
|
||||||
_mm_packs_epi32(_mm_load_si128(&in[i * 4 + 2]), _mm_load_si128(&in[i * 4 + 3]));
|
|
||||||
|
|
||||||
// We shift by WeightScaleBits * 2 = 12 and divide by 128
|
|
||||||
// which is an additional shift-right of 7, meaning 19 in total.
|
|
||||||
// MulHi strips the lower 16 bits so we need to shift out 3 more to match.
|
|
||||||
words0 = _mm_srli_epi16(_mm_mulhi_epi16(words0, words0), 3);
|
|
||||||
words1 = _mm_srli_epi16(_mm_mulhi_epi16(words1, words1), 3);
|
|
||||||
|
|
||||||
_mm_store_si128(&out[i], _mm_packs_epi16(words0, words1));
|
|
||||||
}
|
|
||||||
constexpr IndexType Start = NumChunks * 16;
|
|
||||||
|
|
||||||
#else
|
|
||||||
constexpr IndexType Start = 0;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
for (IndexType i = Start; i < InputDimensions; ++i)
|
|
||||||
{
|
|
||||||
output[i] = static_cast<OutputType>(
|
|
||||||
// Really should be /127 but we need to make it fast so we right-shift
|
|
||||||
// by an extra 7 bits instead. Needs to be accounted for in the trainer.
|
|
||||||
std::min(127ll, ((long long) (input[i]) * input[i]) >> (2 * WeightScaleBits + 7)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Stockfish::Eval::NNUE::Layers
|
|
||||||
|
|
||||||
#endif // NNUE_LAYERS_SQR_CLIPPED_RELU_H_INCLUDED
|
|
||||||
@@ -1,455 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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 "network.h"
|
|
||||||
|
|
||||||
#include <cstdlib>
|
|
||||||
#include <fstream>
|
|
||||||
#include <iostream>
|
|
||||||
#include <memory>
|
|
||||||
#include <optional>
|
|
||||||
#include <type_traits>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#include "../evaluate.h"
|
|
||||||
#include "../incbin/incbin.h"
|
|
||||||
#include "../memory.h"
|
|
||||||
#include "../misc.h"
|
|
||||||
#include "../position.h"
|
|
||||||
#include "../types.h"
|
|
||||||
#include "nnue_architecture.h"
|
|
||||||
#include "nnue_common.h"
|
|
||||||
#include "nnue_misc.h"
|
|
||||||
|
|
||||||
namespace {
|
|
||||||
// Macro to embed the default efficiently updatable neural network (NNUE) file
|
|
||||||
// data in the engine binary (using incbin.h, by Dale Weiler).
|
|
||||||
// This macro invocation will declare the following three variables
|
|
||||||
// const unsigned char gEmbeddedNNUEData[]; // a pointer to the embedded data
|
|
||||||
// const unsigned char *const gEmbeddedNNUEEnd; // a marker to the end
|
|
||||||
// const unsigned int gEmbeddedNNUESize; // the size of the embedded file
|
|
||||||
// Note that this does not work in Microsoft Visual Studio.
|
|
||||||
#if !defined(_MSC_VER) && !defined(NNUE_EMBEDDING_OFF)
|
|
||||||
INCBIN(EmbeddedNNUEBig, EvalFileDefaultNameBig);
|
|
||||||
INCBIN(EmbeddedNNUESmall, EvalFileDefaultNameSmall);
|
|
||||||
#else
|
|
||||||
const unsigned char gEmbeddedNNUEBigData[1] = {0x0};
|
|
||||||
const unsigned char* const gEmbeddedNNUEBigEnd = &gEmbeddedNNUEBigData[1];
|
|
||||||
const unsigned int gEmbeddedNNUEBigSize = 1;
|
|
||||||
const unsigned char gEmbeddedNNUESmallData[1] = {0x0};
|
|
||||||
const unsigned char* const gEmbeddedNNUESmallEnd = &gEmbeddedNNUESmallData[1];
|
|
||||||
const unsigned int gEmbeddedNNUESmallSize = 1;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
struct EmbeddedNNUE {
|
|
||||||
EmbeddedNNUE(const unsigned char* embeddedData,
|
|
||||||
const unsigned char* embeddedEnd,
|
|
||||||
const unsigned int embeddedSize) :
|
|
||||||
data(embeddedData),
|
|
||||||
end(embeddedEnd),
|
|
||||||
size(embeddedSize) {}
|
|
||||||
const unsigned char* data;
|
|
||||||
const unsigned char* end;
|
|
||||||
const unsigned int size;
|
|
||||||
};
|
|
||||||
|
|
||||||
using namespace Stockfish::Eval::NNUE;
|
|
||||||
|
|
||||||
EmbeddedNNUE get_embedded(EmbeddedNNUEType type) {
|
|
||||||
if (type == EmbeddedNNUEType::BIG)
|
|
||||||
return EmbeddedNNUE(gEmbeddedNNUEBigData, gEmbeddedNNUEBigEnd, gEmbeddedNNUEBigSize);
|
|
||||||
else
|
|
||||||
return EmbeddedNNUE(gEmbeddedNNUESmallData, gEmbeddedNNUESmallEnd, gEmbeddedNNUESmallSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
namespace Stockfish::Eval::NNUE {
|
|
||||||
|
|
||||||
|
|
||||||
namespace Detail {
|
|
||||||
|
|
||||||
// Read evaluation function parameters
|
|
||||||
template<typename T>
|
|
||||||
bool read_parameters(std::istream& stream, T& reference) {
|
|
||||||
|
|
||||||
std::uint32_t header;
|
|
||||||
header = read_little_endian<std::uint32_t>(stream);
|
|
||||||
if (!stream || header != T::get_hash_value())
|
|
||||||
return false;
|
|
||||||
return reference.read_parameters(stream);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write evaluation function parameters
|
|
||||||
template<typename T>
|
|
||||||
bool write_parameters(std::ostream& stream, const T& reference) {
|
|
||||||
|
|
||||||
write_little_endian<std::uint32_t>(stream, T::get_hash_value());
|
|
||||||
return reference.write_parameters(stream);
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Detail
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
Network<Arch, Transformer>::Network(const Network<Arch, Transformer>& other) :
|
|
||||||
evalFile(other.evalFile),
|
|
||||||
embeddedType(other.embeddedType) {
|
|
||||||
|
|
||||||
if (other.featureTransformer)
|
|
||||||
featureTransformer = make_unique_large_page<Transformer>(*other.featureTransformer);
|
|
||||||
|
|
||||||
network = make_unique_aligned<Arch[]>(LayerStacks);
|
|
||||||
|
|
||||||
if (!other.network)
|
|
||||||
return;
|
|
||||||
|
|
||||||
for (std::size_t i = 0; i < LayerStacks; ++i)
|
|
||||||
network[i] = other.network[i];
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
Network<Arch, Transformer>&
|
|
||||||
Network<Arch, Transformer>::operator=(const Network<Arch, Transformer>& other) {
|
|
||||||
evalFile = other.evalFile;
|
|
||||||
embeddedType = other.embeddedType;
|
|
||||||
|
|
||||||
if (other.featureTransformer)
|
|
||||||
featureTransformer = make_unique_large_page<Transformer>(*other.featureTransformer);
|
|
||||||
|
|
||||||
network = make_unique_aligned<Arch[]>(LayerStacks);
|
|
||||||
|
|
||||||
if (!other.network)
|
|
||||||
return *this;
|
|
||||||
|
|
||||||
for (std::size_t i = 0; i < LayerStacks; ++i)
|
|
||||||
network[i] = other.network[i];
|
|
||||||
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
void Network<Arch, Transformer>::load(const std::string& rootDirectory, std::string evalfilePath) {
|
|
||||||
#if defined(DEFAULT_NNUE_DIRECTORY)
|
|
||||||
std::vector<std::string> dirs = {"<internal>", "", rootDirectory,
|
|
||||||
stringify(DEFAULT_NNUE_DIRECTORY)};
|
|
||||||
#else
|
|
||||||
std::vector<std::string> dirs = {"<internal>", "", rootDirectory};
|
|
||||||
#endif
|
|
||||||
|
|
||||||
if (evalfilePath.empty())
|
|
||||||
evalfilePath = evalFile.defaultName;
|
|
||||||
|
|
||||||
for (const auto& directory : dirs)
|
|
||||||
{
|
|
||||||
if (evalFile.current != evalfilePath)
|
|
||||||
{
|
|
||||||
if (directory != "<internal>")
|
|
||||||
{
|
|
||||||
load_user_net(directory, evalfilePath);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (directory == "<internal>" && evalfilePath == evalFile.defaultName)
|
|
||||||
{
|
|
||||||
load_internal();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
bool Network<Arch, Transformer>::save(const std::optional<std::string>& filename) const {
|
|
||||||
std::string actualFilename;
|
|
||||||
std::string msg;
|
|
||||||
|
|
||||||
if (filename.has_value())
|
|
||||||
actualFilename = filename.value();
|
|
||||||
else
|
|
||||||
{
|
|
||||||
if (evalFile.current != evalFile.defaultName)
|
|
||||||
{
|
|
||||||
msg = "Failed to export a net. "
|
|
||||||
"A non-embedded net can only be saved if the filename is specified";
|
|
||||||
|
|
||||||
sync_cout << msg << sync_endl;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
actualFilename = evalFile.defaultName;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::ofstream stream(actualFilename, std::ios_base::binary);
|
|
||||||
bool saved = save(stream, evalFile.current, evalFile.netDescription);
|
|
||||||
|
|
||||||
msg = saved ? "Network saved successfully to " + actualFilename : "Failed to export a net";
|
|
||||||
|
|
||||||
sync_cout << msg << sync_endl;
|
|
||||||
return saved;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
NetworkOutput
|
|
||||||
Network<Arch, Transformer>::evaluate(const Position& pos,
|
|
||||||
AccumulatorCaches::Cache<FTDimensions>* cache) const {
|
|
||||||
// We manually align the arrays on the stack because with gcc < 9.3
|
|
||||||
// overaligning stack variables with alignas() doesn't work correctly.
|
|
||||||
|
|
||||||
constexpr uint64_t alignment = CacheLineSize;
|
|
||||||
|
|
||||||
#if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
|
|
||||||
TransformedFeatureType
|
|
||||||
transformedFeaturesUnaligned[FeatureTransformer<FTDimensions, nullptr>::BufferSize
|
|
||||||
+ alignment / sizeof(TransformedFeatureType)];
|
|
||||||
|
|
||||||
auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
|
|
||||||
#else
|
|
||||||
alignas(alignment) TransformedFeatureType
|
|
||||||
transformedFeatures[FeatureTransformer<FTDimensions, nullptr>::BufferSize];
|
|
||||||
#endif
|
|
||||||
|
|
||||||
ASSERT_ALIGNED(transformedFeatures, alignment);
|
|
||||||
|
|
||||||
const int bucket = (pos.count<ALL_PIECES>() - 1) / 4;
|
|
||||||
const auto psqt = featureTransformer->transform(pos, cache, transformedFeatures, bucket);
|
|
||||||
const auto positional = network[bucket].propagate(transformedFeatures);
|
|
||||||
return {static_cast<Value>(psqt / OutputScale), static_cast<Value>(positional / OutputScale)};
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
void Network<Arch, Transformer>::verify(std::string evalfilePath) const {
|
|
||||||
if (evalfilePath.empty())
|
|
||||||
evalfilePath = evalFile.defaultName;
|
|
||||||
|
|
||||||
if (evalFile.current != evalfilePath)
|
|
||||||
{
|
|
||||||
std::string msg1 =
|
|
||||||
"Network evaluation parameters compatible with the engine must be available.";
|
|
||||||
std::string msg2 = "The network file " + evalfilePath + " was not loaded successfully.";
|
|
||||||
std::string msg3 = "The UCI option EvalFile might need to specify the full path, "
|
|
||||||
"including the directory name, to the network file.";
|
|
||||||
std::string msg4 = "The default net can be downloaded from: "
|
|
||||||
"https://tests.stockfishchess.org/api/nn/"
|
|
||||||
+ evalFile.defaultName;
|
|
||||||
std::string msg5 = "The engine will be terminated now.";
|
|
||||||
|
|
||||||
sync_cout << "info string ERROR: " << msg1 << sync_endl;
|
|
||||||
sync_cout << "info string ERROR: " << msg2 << sync_endl;
|
|
||||||
sync_cout << "info string ERROR: " << msg3 << sync_endl;
|
|
||||||
sync_cout << "info string ERROR: " << msg4 << sync_endl;
|
|
||||||
sync_cout << "info string ERROR: " << msg5 << sync_endl;
|
|
||||||
exit(EXIT_FAILURE);
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t size = sizeof(*featureTransformer) + sizeof(Arch) * LayerStacks;
|
|
||||||
sync_cout << "info string NNUE evaluation using " << evalfilePath << " ("
|
|
||||||
<< size / (1024 * 1024) << "MiB, (" << featureTransformer->InputDimensions << ", "
|
|
||||||
<< network[0].TransformedFeatureDimensions << ", " << network[0].FC_0_OUTPUTS << ", "
|
|
||||||
<< network[0].FC_1_OUTPUTS << ", 1))" << sync_endl;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
void Network<Arch, Transformer>::hint_common_access(
|
|
||||||
const Position& pos, AccumulatorCaches::Cache<FTDimensions>* cache) const {
|
|
||||||
featureTransformer->hint_common_access(pos, cache);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
NnueEvalTrace
|
|
||||||
Network<Arch, Transformer>::trace_evaluate(const Position& pos,
|
|
||||||
AccumulatorCaches::Cache<FTDimensions>* cache) const {
|
|
||||||
// We manually align the arrays on the stack because with gcc < 9.3
|
|
||||||
// overaligning stack variables with alignas() doesn't work correctly.
|
|
||||||
constexpr uint64_t alignment = CacheLineSize;
|
|
||||||
|
|
||||||
#if defined(ALIGNAS_ON_STACK_VARIABLES_BROKEN)
|
|
||||||
TransformedFeatureType
|
|
||||||
transformedFeaturesUnaligned[FeatureTransformer<FTDimensions, nullptr>::BufferSize
|
|
||||||
+ alignment / sizeof(TransformedFeatureType)];
|
|
||||||
|
|
||||||
auto* transformedFeatures = align_ptr_up<alignment>(&transformedFeaturesUnaligned[0]);
|
|
||||||
#else
|
|
||||||
alignas(alignment) TransformedFeatureType
|
|
||||||
transformedFeatures[FeatureTransformer<FTDimensions, nullptr>::BufferSize];
|
|
||||||
#endif
|
|
||||||
|
|
||||||
ASSERT_ALIGNED(transformedFeatures, alignment);
|
|
||||||
|
|
||||||
NnueEvalTrace t{};
|
|
||||||
t.correctBucket = (pos.count<ALL_PIECES>() - 1) / 4;
|
|
||||||
for (IndexType bucket = 0; bucket < LayerStacks; ++bucket)
|
|
||||||
{
|
|
||||||
const auto materialist =
|
|
||||||
featureTransformer->transform(pos, cache, transformedFeatures, bucket);
|
|
||||||
const auto positional = network[bucket].propagate(transformedFeatures);
|
|
||||||
|
|
||||||
t.psqt[bucket] = static_cast<Value>(materialist / OutputScale);
|
|
||||||
t.positional[bucket] = static_cast<Value>(positional / OutputScale);
|
|
||||||
}
|
|
||||||
|
|
||||||
return t;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
void Network<Arch, Transformer>::load_user_net(const std::string& dir,
|
|
||||||
const std::string& evalfilePath) {
|
|
||||||
std::ifstream stream(dir + evalfilePath, std::ios::binary);
|
|
||||||
auto description = load(stream);
|
|
||||||
|
|
||||||
if (description.has_value())
|
|
||||||
{
|
|
||||||
evalFile.current = evalfilePath;
|
|
||||||
evalFile.netDescription = description.value();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
void Network<Arch, Transformer>::load_internal() {
|
|
||||||
// C++ way to prepare a buffer for a memory stream
|
|
||||||
class MemoryBuffer: public std::basic_streambuf<char> {
|
|
||||||
public:
|
|
||||||
MemoryBuffer(char* p, size_t n) {
|
|
||||||
setg(p, p, p + n);
|
|
||||||
setp(p, p + n);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const auto embedded = get_embedded(embeddedType);
|
|
||||||
|
|
||||||
MemoryBuffer buffer(const_cast<char*>(reinterpret_cast<const char*>(embedded.data)),
|
|
||||||
size_t(embedded.size));
|
|
||||||
|
|
||||||
std::istream stream(&buffer);
|
|
||||||
auto description = load(stream);
|
|
||||||
|
|
||||||
if (description.has_value())
|
|
||||||
{
|
|
||||||
evalFile.current = evalFile.defaultName;
|
|
||||||
evalFile.netDescription = description.value();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
void Network<Arch, Transformer>::initialize() {
|
|
||||||
featureTransformer = make_unique_large_page<Transformer>();
|
|
||||||
network = make_unique_aligned<Arch[]>(LayerStacks);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
bool Network<Arch, Transformer>::save(std::ostream& stream,
|
|
||||||
const std::string& name,
|
|
||||||
const std::string& netDescription) const {
|
|
||||||
if (name.empty() || name == "None")
|
|
||||||
return false;
|
|
||||||
|
|
||||||
return write_parameters(stream, netDescription);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
std::optional<std::string> Network<Arch, Transformer>::load(std::istream& stream) {
|
|
||||||
initialize();
|
|
||||||
std::string description;
|
|
||||||
|
|
||||||
return read_parameters(stream, description) ? std::make_optional(description) : std::nullopt;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Read network header
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
bool Network<Arch, Transformer>::read_header(std::istream& stream,
|
|
||||||
std::uint32_t* hashValue,
|
|
||||||
std::string* desc) const {
|
|
||||||
std::uint32_t version, size;
|
|
||||||
|
|
||||||
version = read_little_endian<std::uint32_t>(stream);
|
|
||||||
*hashValue = read_little_endian<std::uint32_t>(stream);
|
|
||||||
size = read_little_endian<std::uint32_t>(stream);
|
|
||||||
if (!stream || version != Version)
|
|
||||||
return false;
|
|
||||||
desc->resize(size);
|
|
||||||
stream.read(&(*desc)[0], size);
|
|
||||||
return !stream.fail();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Write network header
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
bool Network<Arch, Transformer>::write_header(std::ostream& stream,
|
|
||||||
std::uint32_t hashValue,
|
|
||||||
const std::string& desc) const {
|
|
||||||
write_little_endian<std::uint32_t>(stream, Version);
|
|
||||||
write_little_endian<std::uint32_t>(stream, hashValue);
|
|
||||||
write_little_endian<std::uint32_t>(stream, std::uint32_t(desc.size()));
|
|
||||||
stream.write(&desc[0], desc.size());
|
|
||||||
return !stream.fail();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
bool Network<Arch, Transformer>::read_parameters(std::istream& stream,
|
|
||||||
std::string& netDescription) const {
|
|
||||||
std::uint32_t hashValue;
|
|
||||||
if (!read_header(stream, &hashValue, &netDescription))
|
|
||||||
return false;
|
|
||||||
if (hashValue != Network::hash)
|
|
||||||
return false;
|
|
||||||
if (!Detail::read_parameters(stream, *featureTransformer))
|
|
||||||
return false;
|
|
||||||
for (std::size_t i = 0; i < LayerStacks; ++i)
|
|
||||||
{
|
|
||||||
if (!Detail::read_parameters(stream, network[i]))
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return stream && stream.peek() == std::ios::traits_type::eof();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
bool Network<Arch, Transformer>::write_parameters(std::ostream& stream,
|
|
||||||
const std::string& netDescription) const {
|
|
||||||
if (!write_header(stream, Network::hash, netDescription))
|
|
||||||
return false;
|
|
||||||
if (!Detail::write_parameters(stream, *featureTransformer))
|
|
||||||
return false;
|
|
||||||
for (std::size_t i = 0; i < LayerStacks; ++i)
|
|
||||||
{
|
|
||||||
if (!Detail::write_parameters(stream, network[i]))
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return bool(stream);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Explicit template instantiation
|
|
||||||
|
|
||||||
template class Network<
|
|
||||||
NetworkArchitecture<TransformedFeatureDimensionsBig, L2Big, L3Big>,
|
|
||||||
FeatureTransformer<TransformedFeatureDimensionsBig, &StateInfo::accumulatorBig>>;
|
|
||||||
|
|
||||||
template class Network<
|
|
||||||
NetworkArchitecture<TransformedFeatureDimensionsSmall, L2Small, L3Small>,
|
|
||||||
FeatureTransformer<TransformedFeatureDimensionsSmall, &StateInfo::accumulatorSmall>>;
|
|
||||||
|
|
||||||
} // namespace Stockfish::Eval::NNUE
|
|
||||||
@@ -1,132 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef NETWORK_H_INCLUDED
|
|
||||||
#define NETWORK_H_INCLUDED
|
|
||||||
|
|
||||||
#include <cstdint>
|
|
||||||
#include <iostream>
|
|
||||||
#include <optional>
|
|
||||||
#include <string>
|
|
||||||
#include <tuple>
|
|
||||||
#include <utility>
|
|
||||||
|
|
||||||
#include "../memory.h"
|
|
||||||
#include "../position.h"
|
|
||||||
#include "../types.h"
|
|
||||||
#include "nnue_accumulator.h"
|
|
||||||
#include "nnue_architecture.h"
|
|
||||||
#include "nnue_feature_transformer.h"
|
|
||||||
#include "nnue_misc.h"
|
|
||||||
|
|
||||||
namespace Stockfish::Eval::NNUE {
|
|
||||||
|
|
||||||
enum class EmbeddedNNUEType {
|
|
||||||
BIG,
|
|
||||||
SMALL,
|
|
||||||
};
|
|
||||||
|
|
||||||
using NetworkOutput = std::tuple<Value, Value>;
|
|
||||||
|
|
||||||
template<typename Arch, typename Transformer>
|
|
||||||
class Network {
|
|
||||||
static constexpr IndexType FTDimensions = Arch::TransformedFeatureDimensions;
|
|
||||||
|
|
||||||
public:
|
|
||||||
Network(EvalFile file, EmbeddedNNUEType type) :
|
|
||||||
evalFile(file),
|
|
||||||
embeddedType(type) {}
|
|
||||||
|
|
||||||
Network(const Network& other);
|
|
||||||
Network(Network&& other) = default;
|
|
||||||
|
|
||||||
Network& operator=(const Network& other);
|
|
||||||
Network& operator=(Network&& other) = default;
|
|
||||||
|
|
||||||
void load(const std::string& rootDirectory, std::string evalfilePath);
|
|
||||||
bool save(const std::optional<std::string>& filename) const;
|
|
||||||
|
|
||||||
NetworkOutput evaluate(const Position& pos,
|
|
||||||
AccumulatorCaches::Cache<FTDimensions>* cache) const;
|
|
||||||
|
|
||||||
|
|
||||||
void hint_common_access(const Position& pos,
|
|
||||||
AccumulatorCaches::Cache<FTDimensions>* cache) const;
|
|
||||||
|
|
||||||
void verify(std::string evalfilePath) const;
|
|
||||||
NnueEvalTrace trace_evaluate(const Position& pos,
|
|
||||||
AccumulatorCaches::Cache<FTDimensions>* cache) const;
|
|
||||||
|
|
||||||
private:
|
|
||||||
void load_user_net(const std::string&, const std::string&);
|
|
||||||
void load_internal();
|
|
||||||
|
|
||||||
void initialize();
|
|
||||||
|
|
||||||
bool save(std::ostream&, const std::string&, const std::string&) const;
|
|
||||||
std::optional<std::string> load(std::istream&);
|
|
||||||
|
|
||||||
bool read_header(std::istream&, std::uint32_t*, std::string*) const;
|
|
||||||
bool write_header(std::ostream&, std::uint32_t, const std::string&) const;
|
|
||||||
|
|
||||||
bool read_parameters(std::istream&, std::string&) const;
|
|
||||||
bool write_parameters(std::ostream&, const std::string&) const;
|
|
||||||
|
|
||||||
// Input feature converter
|
|
||||||
LargePagePtr<Transformer> featureTransformer;
|
|
||||||
|
|
||||||
// Evaluation function
|
|
||||||
AlignedPtr<Arch[]> network;
|
|
||||||
|
|
||||||
EvalFile evalFile;
|
|
||||||
EmbeddedNNUEType embeddedType;
|
|
||||||
|
|
||||||
// Hash value of evaluation function structure
|
|
||||||
static constexpr std::uint32_t hash = Transformer::get_hash_value() ^ Arch::get_hash_value();
|
|
||||||
|
|
||||||
template<IndexType Size>
|
|
||||||
friend struct AccumulatorCaches::Cache;
|
|
||||||
};
|
|
||||||
|
|
||||||
// Definitions of the network types
|
|
||||||
using SmallFeatureTransformer =
|
|
||||||
FeatureTransformer<TransformedFeatureDimensionsSmall, &StateInfo::accumulatorSmall>;
|
|
||||||
using SmallNetworkArchitecture =
|
|
||||||
NetworkArchitecture<TransformedFeatureDimensionsSmall, L2Small, L3Small>;
|
|
||||||
|
|
||||||
using BigFeatureTransformer =
|
|
||||||
FeatureTransformer<TransformedFeatureDimensionsBig, &StateInfo::accumulatorBig>;
|
|
||||||
using BigNetworkArchitecture = NetworkArchitecture<TransformedFeatureDimensionsBig, L2Big, L3Big>;
|
|
||||||
|
|
||||||
using NetworkBig = Network<BigNetworkArchitecture, BigFeatureTransformer>;
|
|
||||||
using NetworkSmall = Network<SmallNetworkArchitecture, SmallFeatureTransformer>;
|
|
||||||
|
|
||||||
|
|
||||||
struct Networks {
|
|
||||||
Networks(NetworkBig&& nB, NetworkSmall&& nS) :
|
|
||||||
big(std::move(nB)),
|
|
||||||
small(std::move(nS)) {}
|
|
||||||
|
|
||||||
NetworkBig big;
|
|
||||||
NetworkSmall small;
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
} // namespace Stockfish
|
|
||||||
|
|
||||||
#endif
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Class for difference calculation of NNUE evaluation function
|
|
||||||
|
|
||||||
#ifndef NNUE_ACCUMULATOR_H_INCLUDED
|
|
||||||
#define NNUE_ACCUMULATOR_H_INCLUDED
|
|
||||||
|
|
||||||
#include <cstdint>
|
|
||||||
|
|
||||||
#include "nnue_architecture.h"
|
|
||||||
#include "nnue_common.h"
|
|
||||||
|
|
||||||
namespace Stockfish::Eval::NNUE {
|
|
||||||
|
|
||||||
using BiasType = std::int16_t;
|
|
||||||
using PSQTWeightType = std::int32_t;
|
|
||||||
using IndexType = std::uint32_t;
|
|
||||||
|
|
||||||
// Class that holds the result of affine transformation of input features
|
|
||||||
template<IndexType Size>
|
|
||||||
struct alignas(CacheLineSize) Accumulator {
|
|
||||||
std::int16_t accumulation[COLOR_NB][Size];
|
|
||||||
std::int32_t psqtAccumulation[COLOR_NB][PSQTBuckets];
|
|
||||||
bool computed[COLOR_NB];
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
// AccumulatorCaches struct provides per-thread accumulator caches, where each
|
|
||||||
// cache contains multiple entries for each of the possible king squares.
|
|
||||||
// When the accumulator needs to be refreshed, the cached entry is used to more
|
|
||||||
// efficiently update the accumulator, instead of rebuilding it from scratch.
|
|
||||||
// This idea, was first described by Luecx (author of Koivisto) and
|
|
||||||
// is commonly referred to as "Finny Tables".
|
|
||||||
struct AccumulatorCaches {
|
|
||||||
|
|
||||||
template<typename Networks>
|
|
||||||
AccumulatorCaches(const Networks& networks) {
|
|
||||||
clear(networks);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<IndexType Size>
|
|
||||||
struct alignas(CacheLineSize) Cache {
|
|
||||||
|
|
||||||
struct alignas(CacheLineSize) Entry {
|
|
||||||
BiasType accumulation[Size];
|
|
||||||
PSQTWeightType psqtAccumulation[PSQTBuckets];
|
|
||||||
Bitboard byColorBB[COLOR_NB];
|
|
||||||
Bitboard byTypeBB[PIECE_TYPE_NB];
|
|
||||||
|
|
||||||
// To initialize a refresh entry, we set all its bitboards empty,
|
|
||||||
// so we put the biases in the accumulation, without any weights on top
|
|
||||||
void clear(const BiasType* biases) {
|
|
||||||
|
|
||||||
std::memcpy(accumulation, biases, sizeof(accumulation));
|
|
||||||
std::memset((uint8_t*) this + offsetof(Entry, psqtAccumulation), 0,
|
|
||||||
sizeof(Entry) - offsetof(Entry, psqtAccumulation));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename Network>
|
|
||||||
void clear(const Network& network) {
|
|
||||||
for (auto& entries1D : entries)
|
|
||||||
for (auto& entry : entries1D)
|
|
||||||
entry.clear(network.featureTransformer->biases);
|
|
||||||
}
|
|
||||||
|
|
||||||
void clear(const BiasType* biases) {
|
|
||||||
for (auto& entry : entries)
|
|
||||||
entry.clear(biases);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::array<Entry, COLOR_NB>& operator[](Square sq) { return entries[sq]; }
|
|
||||||
|
|
||||||
std::array<std::array<Entry, COLOR_NB>, SQUARE_NB> entries;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<typename Networks>
|
|
||||||
void clear(const Networks& networks) {
|
|
||||||
big.clear(networks.big);
|
|
||||||
small.clear(networks.small);
|
|
||||||
}
|
|
||||||
|
|
||||||
Cache<TransformedFeatureDimensionsBig> big;
|
|
||||||
Cache<TransformedFeatureDimensionsSmall> small;
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Stockfish::Eval::NNUE
|
|
||||||
|
|
||||||
#endif // NNUE_ACCUMULATOR_H_INCLUDED
|
|
||||||
@@ -1,137 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Input features and network structure used in NNUE evaluation function
|
|
||||||
|
|
||||||
#ifndef NNUE_ARCHITECTURE_H_INCLUDED
|
|
||||||
#define NNUE_ARCHITECTURE_H_INCLUDED
|
|
||||||
|
|
||||||
#include <cstdint>
|
|
||||||
#include <cstring>
|
|
||||||
#include <iosfwd>
|
|
||||||
|
|
||||||
#include "features/half_ka_v2_hm.h"
|
|
||||||
#include "layers/affine_transform.h"
|
|
||||||
#include "layers/affine_transform_sparse_input.h"
|
|
||||||
#include "layers/clipped_relu.h"
|
|
||||||
#include "layers/sqr_clipped_relu.h"
|
|
||||||
#include "nnue_common.h"
|
|
||||||
|
|
||||||
namespace Stockfish::Eval::NNUE {
|
|
||||||
|
|
||||||
// Input features used in evaluation function
|
|
||||||
using FeatureSet = Features::HalfKAv2_hm;
|
|
||||||
|
|
||||||
// Number of input feature dimensions after conversion
|
|
||||||
constexpr IndexType TransformedFeatureDimensionsBig = 3072;
|
|
||||||
constexpr int L2Big = 15;
|
|
||||||
constexpr int L3Big = 32;
|
|
||||||
|
|
||||||
constexpr IndexType TransformedFeatureDimensionsSmall = 128;
|
|
||||||
constexpr int L2Small = 15;
|
|
||||||
constexpr int L3Small = 32;
|
|
||||||
|
|
||||||
constexpr IndexType PSQTBuckets = 8;
|
|
||||||
constexpr IndexType LayerStacks = 8;
|
|
||||||
|
|
||||||
template<IndexType L1, int L2, int L3>
|
|
||||||
struct NetworkArchitecture {
|
|
||||||
static constexpr IndexType TransformedFeatureDimensions = L1;
|
|
||||||
static constexpr int FC_0_OUTPUTS = L2;
|
|
||||||
static constexpr int FC_1_OUTPUTS = L3;
|
|
||||||
|
|
||||||
Layers::AffineTransformSparseInput<TransformedFeatureDimensions, FC_0_OUTPUTS + 1> fc_0;
|
|
||||||
Layers::SqrClippedReLU<FC_0_OUTPUTS + 1> ac_sqr_0;
|
|
||||||
Layers::ClippedReLU<FC_0_OUTPUTS + 1> ac_0;
|
|
||||||
Layers::AffineTransform<FC_0_OUTPUTS * 2, FC_1_OUTPUTS> fc_1;
|
|
||||||
Layers::ClippedReLU<FC_1_OUTPUTS> ac_1;
|
|
||||||
Layers::AffineTransform<FC_1_OUTPUTS, 1> fc_2;
|
|
||||||
|
|
||||||
// Hash value embedded in the evaluation file
|
|
||||||
static constexpr std::uint32_t get_hash_value() {
|
|
||||||
// input slice hash
|
|
||||||
std::uint32_t hashValue = 0xEC42E90Du;
|
|
||||||
hashValue ^= TransformedFeatureDimensions * 2;
|
|
||||||
|
|
||||||
hashValue = decltype(fc_0)::get_hash_value(hashValue);
|
|
||||||
hashValue = decltype(ac_0)::get_hash_value(hashValue);
|
|
||||||
hashValue = decltype(fc_1)::get_hash_value(hashValue);
|
|
||||||
hashValue = decltype(ac_1)::get_hash_value(hashValue);
|
|
||||||
hashValue = decltype(fc_2)::get_hash_value(hashValue);
|
|
||||||
|
|
||||||
return hashValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read network parameters
|
|
||||||
bool read_parameters(std::istream& stream) {
|
|
||||||
return fc_0.read_parameters(stream) && ac_0.read_parameters(stream)
|
|
||||||
&& fc_1.read_parameters(stream) && ac_1.read_parameters(stream)
|
|
||||||
&& fc_2.read_parameters(stream);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write network parameters
|
|
||||||
bool write_parameters(std::ostream& stream) const {
|
|
||||||
return fc_0.write_parameters(stream) && ac_0.write_parameters(stream)
|
|
||||||
&& fc_1.write_parameters(stream) && ac_1.write_parameters(stream)
|
|
||||||
&& fc_2.write_parameters(stream);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::int32_t propagate(const TransformedFeatureType* transformedFeatures) {
|
|
||||||
struct alignas(CacheLineSize) Buffer {
|
|
||||||
alignas(CacheLineSize) typename decltype(fc_0)::OutputBuffer fc_0_out;
|
|
||||||
alignas(CacheLineSize) typename decltype(ac_sqr_0)::OutputType
|
|
||||||
ac_sqr_0_out[ceil_to_multiple<IndexType>(FC_0_OUTPUTS * 2, 32)];
|
|
||||||
alignas(CacheLineSize) typename decltype(ac_0)::OutputBuffer ac_0_out;
|
|
||||||
alignas(CacheLineSize) typename decltype(fc_1)::OutputBuffer fc_1_out;
|
|
||||||
alignas(CacheLineSize) typename decltype(ac_1)::OutputBuffer ac_1_out;
|
|
||||||
alignas(CacheLineSize) typename decltype(fc_2)::OutputBuffer fc_2_out;
|
|
||||||
|
|
||||||
Buffer() { std::memset(this, 0, sizeof(*this)); }
|
|
||||||
};
|
|
||||||
|
|
||||||
#if defined(__clang__) && (__APPLE__)
|
|
||||||
// workaround for a bug reported with xcode 12
|
|
||||||
static thread_local auto tlsBuffer = std::make_unique<Buffer>();
|
|
||||||
// Access TLS only once, cache result.
|
|
||||||
Buffer& buffer = *tlsBuffer;
|
|
||||||
#else
|
|
||||||
alignas(CacheLineSize) static thread_local Buffer buffer;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
fc_0.propagate(transformedFeatures, buffer.fc_0_out);
|
|
||||||
ac_sqr_0.propagate(buffer.fc_0_out, buffer.ac_sqr_0_out);
|
|
||||||
ac_0.propagate(buffer.fc_0_out, buffer.ac_0_out);
|
|
||||||
std::memcpy(buffer.ac_sqr_0_out + FC_0_OUTPUTS, buffer.ac_0_out,
|
|
||||||
FC_0_OUTPUTS * sizeof(typename decltype(ac_0)::OutputType));
|
|
||||||
fc_1.propagate(buffer.ac_sqr_0_out, buffer.fc_1_out);
|
|
||||||
ac_1.propagate(buffer.fc_1_out, buffer.ac_1_out);
|
|
||||||
fc_2.propagate(buffer.ac_1_out, buffer.fc_2_out);
|
|
||||||
|
|
||||||
// buffer.fc_0_out[FC_0_OUTPUTS] is such that 1.0 is equal to 127*(1<<WeightScaleBits) in
|
|
||||||
// quantized form, but we want 1.0 to be equal to 600*OutputScale
|
|
||||||
std::int32_t fwdOut =
|
|
||||||
(buffer.fc_0_out[FC_0_OUTPUTS]) * (600 * OutputScale) / (127 * (1 << WeightScaleBits));
|
|
||||||
std::int32_t outputValue = buffer.fc_2_out[0] + fwdOut;
|
|
||||||
|
|
||||||
return outputValue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Stockfish::Eval::NNUE
|
|
||||||
|
|
||||||
#endif // #ifndef NNUE_ARCHITECTURE_H_INCLUDED
|
|
||||||
@@ -1,284 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Constants used in NNUE evaluation function
|
|
||||||
|
|
||||||
#ifndef NNUE_COMMON_H_INCLUDED
|
|
||||||
#define NNUE_COMMON_H_INCLUDED
|
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <cassert>
|
|
||||||
#include <cstdint>
|
|
||||||
#include <cstring>
|
|
||||||
#include <iostream>
|
|
||||||
#include <type_traits>
|
|
||||||
|
|
||||||
#include "../misc.h"
|
|
||||||
|
|
||||||
#if defined(USE_AVX2)
|
|
||||||
#include <immintrin.h>
|
|
||||||
|
|
||||||
#elif defined(USE_SSE41)
|
|
||||||
#include <smmintrin.h>
|
|
||||||
|
|
||||||
#elif defined(USE_SSSE3)
|
|
||||||
#include <tmmintrin.h>
|
|
||||||
|
|
||||||
#elif defined(USE_SSE2)
|
|
||||||
#include <emmintrin.h>
|
|
||||||
|
|
||||||
#elif defined(USE_NEON)
|
|
||||||
#include <arm_neon.h>
|
|
||||||
#endif
|
|
||||||
|
|
||||||
namespace Stockfish::Eval::NNUE {
|
|
||||||
|
|
||||||
// Version of the evaluation file
|
|
||||||
constexpr std::uint32_t Version = 0x7AF32F20u;
|
|
||||||
|
|
||||||
// Constant used in evaluation value calculation
|
|
||||||
constexpr int OutputScale = 16;
|
|
||||||
constexpr int WeightScaleBits = 6;
|
|
||||||
|
|
||||||
// Size of cache line (in bytes)
|
|
||||||
constexpr std::size_t CacheLineSize = 64;
|
|
||||||
|
|
||||||
constexpr const char Leb128MagicString[] = "COMPRESSED_LEB128";
|
|
||||||
constexpr const std::size_t Leb128MagicStringSize = sizeof(Leb128MagicString) - 1;
|
|
||||||
|
|
||||||
// SIMD width (in bytes)
|
|
||||||
#if defined(USE_AVX2)
|
|
||||||
constexpr std::size_t SimdWidth = 32;
|
|
||||||
|
|
||||||
#elif defined(USE_SSE2)
|
|
||||||
constexpr std::size_t SimdWidth = 16;
|
|
||||||
|
|
||||||
#elif defined(USE_NEON)
|
|
||||||
constexpr std::size_t SimdWidth = 16;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
constexpr std::size_t MaxSimdWidth = 32;
|
|
||||||
|
|
||||||
// Type of input feature after conversion
|
|
||||||
using TransformedFeatureType = std::uint8_t;
|
|
||||||
using IndexType = std::uint32_t;
|
|
||||||
|
|
||||||
// Round n up to be a multiple of base
|
|
||||||
template<typename IntType>
|
|
||||||
constexpr IntType ceil_to_multiple(IntType n, IntType base) {
|
|
||||||
return (n + base - 1) / base * base;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Utility to read an integer (signed or unsigned, any size)
|
|
||||||
// from a stream in little-endian order. We swap the byte order after the read if
|
|
||||||
// necessary to return a result with the byte ordering of the compiling machine.
|
|
||||||
template<typename IntType>
|
|
||||||
inline IntType read_little_endian(std::istream& stream) {
|
|
||||||
IntType result;
|
|
||||||
|
|
||||||
if (IsLittleEndian)
|
|
||||||
stream.read(reinterpret_cast<char*>(&result), sizeof(IntType));
|
|
||||||
else
|
|
||||||
{
|
|
||||||
std::uint8_t u[sizeof(IntType)];
|
|
||||||
std::make_unsigned_t<IntType> v = 0;
|
|
||||||
|
|
||||||
stream.read(reinterpret_cast<char*>(u), sizeof(IntType));
|
|
||||||
for (std::size_t i = 0; i < sizeof(IntType); ++i)
|
|
||||||
v = (v << 8) | u[sizeof(IntType) - i - 1];
|
|
||||||
|
|
||||||
std::memcpy(&result, &v, sizeof(IntType));
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Utility to write an integer (signed or unsigned, any size)
|
|
||||||
// to a stream in little-endian order. We swap the byte order before the write if
|
|
||||||
// necessary to always write in little-endian order, independently of the byte
|
|
||||||
// ordering of the compiling machine.
|
|
||||||
template<typename IntType>
|
|
||||||
inline void write_little_endian(std::ostream& stream, IntType value) {
|
|
||||||
|
|
||||||
if (IsLittleEndian)
|
|
||||||
stream.write(reinterpret_cast<const char*>(&value), sizeof(IntType));
|
|
||||||
else
|
|
||||||
{
|
|
||||||
std::uint8_t u[sizeof(IntType)];
|
|
||||||
std::make_unsigned_t<IntType> v = value;
|
|
||||||
|
|
||||||
std::size_t i = 0;
|
|
||||||
// if constexpr to silence the warning about shift by 8
|
|
||||||
if constexpr (sizeof(IntType) > 1)
|
|
||||||
{
|
|
||||||
for (; i + 1 < sizeof(IntType); ++i)
|
|
||||||
{
|
|
||||||
u[i] = std::uint8_t(v);
|
|
||||||
v >>= 8;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
u[i] = std::uint8_t(v);
|
|
||||||
|
|
||||||
stream.write(reinterpret_cast<char*>(u), sizeof(IntType));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Read integers in bulk from a little-endian stream.
|
|
||||||
// This reads N integers from stream s and puts them in array out.
|
|
||||||
template<typename IntType>
|
|
||||||
inline void read_little_endian(std::istream& stream, IntType* out, std::size_t count) {
|
|
||||||
if (IsLittleEndian)
|
|
||||||
stream.read(reinterpret_cast<char*>(out), sizeof(IntType) * count);
|
|
||||||
else
|
|
||||||
for (std::size_t i = 0; i < count; ++i)
|
|
||||||
out[i] = read_little_endian<IntType>(stream);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Write integers in bulk to a little-endian stream.
|
|
||||||
// This takes N integers from array values and writes them on stream s.
|
|
||||||
template<typename IntType>
|
|
||||||
inline void write_little_endian(std::ostream& stream, const IntType* values, std::size_t count) {
|
|
||||||
if (IsLittleEndian)
|
|
||||||
stream.write(reinterpret_cast<const char*>(values), sizeof(IntType) * count);
|
|
||||||
else
|
|
||||||
for (std::size_t i = 0; i < count; ++i)
|
|
||||||
write_little_endian<IntType>(stream, values[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Read N signed integers from the stream s, putting them in the array out.
|
|
||||||
// The stream is assumed to be compressed using the signed LEB128 format.
|
|
||||||
// See https://en.wikipedia.org/wiki/LEB128 for a description of the compression scheme.
|
|
||||||
template<typename IntType>
|
|
||||||
inline void read_leb_128(std::istream& stream, IntType* out, std::size_t count) {
|
|
||||||
|
|
||||||
// Check the presence of our LEB128 magic string
|
|
||||||
char leb128MagicString[Leb128MagicStringSize];
|
|
||||||
stream.read(leb128MagicString, Leb128MagicStringSize);
|
|
||||||
assert(strncmp(Leb128MagicString, leb128MagicString, Leb128MagicStringSize) == 0);
|
|
||||||
|
|
||||||
static_assert(std::is_signed_v<IntType>, "Not implemented for unsigned types");
|
|
||||||
|
|
||||||
const std::uint32_t BUF_SIZE = 4096;
|
|
||||||
std::uint8_t buf[BUF_SIZE];
|
|
||||||
|
|
||||||
auto bytes_left = read_little_endian<std::uint32_t>(stream);
|
|
||||||
|
|
||||||
std::uint32_t buf_pos = BUF_SIZE;
|
|
||||||
for (std::size_t i = 0; i < count; ++i)
|
|
||||||
{
|
|
||||||
IntType result = 0;
|
|
||||||
size_t shift = 0;
|
|
||||||
do
|
|
||||||
{
|
|
||||||
if (buf_pos == BUF_SIZE)
|
|
||||||
{
|
|
||||||
stream.read(reinterpret_cast<char*>(buf), std::min(bytes_left, BUF_SIZE));
|
|
||||||
buf_pos = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::uint8_t byte = buf[buf_pos++];
|
|
||||||
--bytes_left;
|
|
||||||
result |= (byte & 0x7f) << shift;
|
|
||||||
shift += 7;
|
|
||||||
|
|
||||||
if ((byte & 0x80) == 0)
|
|
||||||
{
|
|
||||||
out[i] = (sizeof(IntType) * 8 <= shift || (byte & 0x40) == 0)
|
|
||||||
? result
|
|
||||||
: result | ~((1 << shift) - 1);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} while (shift < sizeof(IntType) * 8);
|
|
||||||
}
|
|
||||||
|
|
||||||
assert(bytes_left == 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Write signed integers to a stream with LEB128 compression.
|
|
||||||
// This takes N integers from array values, compresses them with
|
|
||||||
// the LEB128 algorithm and writes the result on the stream s.
|
|
||||||
// See https://en.wikipedia.org/wiki/LEB128 for a description of the compression scheme.
|
|
||||||
template<typename IntType>
|
|
||||||
inline void write_leb_128(std::ostream& stream, const IntType* values, std::size_t count) {
|
|
||||||
|
|
||||||
// Write our LEB128 magic string
|
|
||||||
stream.write(Leb128MagicString, Leb128MagicStringSize);
|
|
||||||
|
|
||||||
static_assert(std::is_signed_v<IntType>, "Not implemented for unsigned types");
|
|
||||||
|
|
||||||
std::uint32_t byte_count = 0;
|
|
||||||
for (std::size_t i = 0; i < count; ++i)
|
|
||||||
{
|
|
||||||
IntType value = values[i];
|
|
||||||
std::uint8_t byte;
|
|
||||||
do
|
|
||||||
{
|
|
||||||
byte = value & 0x7f;
|
|
||||||
value >>= 7;
|
|
||||||
++byte_count;
|
|
||||||
} while ((byte & 0x40) == 0 ? value != 0 : value != -1);
|
|
||||||
}
|
|
||||||
|
|
||||||
write_little_endian(stream, byte_count);
|
|
||||||
|
|
||||||
const std::uint32_t BUF_SIZE = 4096;
|
|
||||||
std::uint8_t buf[BUF_SIZE];
|
|
||||||
std::uint32_t buf_pos = 0;
|
|
||||||
|
|
||||||
auto flush = [&]() {
|
|
||||||
if (buf_pos > 0)
|
|
||||||
{
|
|
||||||
stream.write(reinterpret_cast<char*>(buf), buf_pos);
|
|
||||||
buf_pos = 0;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
auto write = [&](std::uint8_t byte) {
|
|
||||||
buf[buf_pos++] = byte;
|
|
||||||
if (buf_pos == BUF_SIZE)
|
|
||||||
flush();
|
|
||||||
};
|
|
||||||
|
|
||||||
for (std::size_t i = 0; i < count; ++i)
|
|
||||||
{
|
|
||||||
IntType value = values[i];
|
|
||||||
while (true)
|
|
||||||
{
|
|
||||||
std::uint8_t byte = value & 0x7f;
|
|
||||||
value >>= 7;
|
|
||||||
if ((byte & 0x40) == 0 ? value == 0 : value == -1)
|
|
||||||
{
|
|
||||||
write(byte);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
write(byte | 0x80);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
flush();
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace Stockfish::Eval::NNUE
|
|
||||||
|
|
||||||
#endif // #ifndef NNUE_COMMON_H_INCLUDED
|
|
||||||
@@ -1,929 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// A class that converts the input features of the NNUE evaluation function
|
|
||||||
|
|
||||||
#ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED
|
|
||||||
#define NNUE_FEATURE_TRANSFORMER_H_INCLUDED
|
|
||||||
|
|
||||||
#include <algorithm>
|
|
||||||
#include <cassert>
|
|
||||||
#include <cstdint>
|
|
||||||
#include <cstring>
|
|
||||||
#include <iosfwd>
|
|
||||||
#include <utility>
|
|
||||||
|
|
||||||
#include "../position.h"
|
|
||||||
#include "../types.h"
|
|
||||||
#include "nnue_accumulator.h"
|
|
||||||
#include "nnue_architecture.h"
|
|
||||||
#include "nnue_common.h"
|
|
||||||
|
|
||||||
namespace Stockfish::Eval::NNUE {
|
|
||||||
|
|
||||||
using BiasType = std::int16_t;
|
|
||||||
using WeightType = std::int16_t;
|
|
||||||
using PSQTWeightType = std::int32_t;
|
|
||||||
|
|
||||||
// If vector instructions are enabled, we update and refresh the
|
|
||||||
// accumulator tile by tile such that each tile fits in the CPU's
|
|
||||||
// vector registers.
|
|
||||||
#define VECTOR
|
|
||||||
|
|
||||||
static_assert(PSQTBuckets % 8 == 0,
|
|
||||||
"Per feature PSQT values cannot be processed at granularity lower than 8 at a time.");
|
|
||||||
|
|
||||||
#ifdef USE_AVX512
|
|
||||||
using vec_t = __m512i;
|
|
||||||
using psqt_vec_t = __m256i;
|
|
||||||
#define vec_load(a) _mm512_load_si512(a)
|
|
||||||
#define vec_store(a, b) _mm512_store_si512(a, b)
|
|
||||||
#define vec_add_16(a, b) _mm512_add_epi16(a, b)
|
|
||||||
#define vec_sub_16(a, b) _mm512_sub_epi16(a, b)
|
|
||||||
#define vec_mulhi_16(a, b) _mm512_mulhi_epi16(a, b)
|
|
||||||
#define vec_zero() _mm512_setzero_epi32()
|
|
||||||
#define vec_set_16(a) _mm512_set1_epi16(a)
|
|
||||||
#define vec_max_16(a, b) _mm512_max_epi16(a, b)
|
|
||||||
#define vec_min_16(a, b) _mm512_min_epi16(a, b)
|
|
||||||
#define vec_slli_16(a, b) _mm512_slli_epi16(a, b)
|
|
||||||
// Inverse permuted at load time
|
|
||||||
#define vec_packus_16(a, b) _mm512_packus_epi16(a, b)
|
|
||||||
#define vec_load_psqt(a) _mm256_load_si256(a)
|
|
||||||
#define vec_store_psqt(a, b) _mm256_store_si256(a, b)
|
|
||||||
#define vec_add_psqt_32(a, b) _mm256_add_epi32(a, b)
|
|
||||||
#define vec_sub_psqt_32(a, b) _mm256_sub_epi32(a, b)
|
|
||||||
#define vec_zero_psqt() _mm256_setzero_si256()
|
|
||||||
#define NumRegistersSIMD 16
|
|
||||||
#define MaxChunkSize 64
|
|
||||||
|
|
||||||
#elif USE_AVX2
|
|
||||||
using vec_t = __m256i;
|
|
||||||
using psqt_vec_t = __m256i;
|
|
||||||
#define vec_load(a) _mm256_load_si256(a)
|
|
||||||
#define vec_store(a, b) _mm256_store_si256(a, b)
|
|
||||||
#define vec_add_16(a, b) _mm256_add_epi16(a, b)
|
|
||||||
#define vec_sub_16(a, b) _mm256_sub_epi16(a, b)
|
|
||||||
#define vec_mulhi_16(a, b) _mm256_mulhi_epi16(a, b)
|
|
||||||
#define vec_zero() _mm256_setzero_si256()
|
|
||||||
#define vec_set_16(a) _mm256_set1_epi16(a)
|
|
||||||
#define vec_max_16(a, b) _mm256_max_epi16(a, b)
|
|
||||||
#define vec_min_16(a, b) _mm256_min_epi16(a, b)
|
|
||||||
#define vec_slli_16(a, b) _mm256_slli_epi16(a, b)
|
|
||||||
// Inverse permuted at load time
|
|
||||||
#define vec_packus_16(a, b) _mm256_packus_epi16(a, b)
|
|
||||||
#define vec_load_psqt(a) _mm256_load_si256(a)
|
|
||||||
#define vec_store_psqt(a, b) _mm256_store_si256(a, b)
|
|
||||||
#define vec_add_psqt_32(a, b) _mm256_add_epi32(a, b)
|
|
||||||
#define vec_sub_psqt_32(a, b) _mm256_sub_epi32(a, b)
|
|
||||||
#define vec_zero_psqt() _mm256_setzero_si256()
|
|
||||||
#define NumRegistersSIMD 16
|
|
||||||
#define MaxChunkSize 32
|
|
||||||
|
|
||||||
#elif USE_SSE2
|
|
||||||
using vec_t = __m128i;
|
|
||||||
using psqt_vec_t = __m128i;
|
|
||||||
#define vec_load(a) (*(a))
|
|
||||||
#define vec_store(a, b) *(a) = (b)
|
|
||||||
#define vec_add_16(a, b) _mm_add_epi16(a, b)
|
|
||||||
#define vec_sub_16(a, b) _mm_sub_epi16(a, b)
|
|
||||||
#define vec_mulhi_16(a, b) _mm_mulhi_epi16(a, b)
|
|
||||||
#define vec_zero() _mm_setzero_si128()
|
|
||||||
#define vec_set_16(a) _mm_set1_epi16(a)
|
|
||||||
#define vec_max_16(a, b) _mm_max_epi16(a, b)
|
|
||||||
#define vec_min_16(a, b) _mm_min_epi16(a, b)
|
|
||||||
#define vec_slli_16(a, b) _mm_slli_epi16(a, b)
|
|
||||||
#define vec_packus_16(a, b) _mm_packus_epi16(a, b)
|
|
||||||
#define vec_load_psqt(a) (*(a))
|
|
||||||
#define vec_store_psqt(a, b) *(a) = (b)
|
|
||||||
#define vec_add_psqt_32(a, b) _mm_add_epi32(a, b)
|
|
||||||
#define vec_sub_psqt_32(a, b) _mm_sub_epi32(a, b)
|
|
||||||
#define vec_zero_psqt() _mm_setzero_si128()
|
|
||||||
#define NumRegistersSIMD (Is64Bit ? 16 : 8)
|
|
||||||
#define MaxChunkSize 16
|
|
||||||
|
|
||||||
#elif USE_NEON
|
|
||||||
using vec_t = int16x8_t;
|
|
||||||
using psqt_vec_t = int32x4_t;
|
|
||||||
#define vec_load(a) (*(a))
|
|
||||||
#define vec_store(a, b) *(a) = (b)
|
|
||||||
#define vec_add_16(a, b) vaddq_s16(a, b)
|
|
||||||
#define vec_sub_16(a, b) vsubq_s16(a, b)
|
|
||||||
#define vec_mulhi_16(a, b) vqdmulhq_s16(a, b)
|
|
||||||
#define vec_zero() \
|
|
||||||
vec_t { 0 }
|
|
||||||
#define vec_set_16(a) vdupq_n_s16(a)
|
|
||||||
#define vec_max_16(a, b) vmaxq_s16(a, b)
|
|
||||||
#define vec_min_16(a, b) vminq_s16(a, b)
|
|
||||||
#define vec_slli_16(a, b) vshlq_s16(a, vec_set_16(b))
|
|
||||||
#define vec_packus_16(a, b) reinterpret_cast<vec_t>(vcombine_u8(vqmovun_s16(a), vqmovun_s16(b)))
|
|
||||||
#define vec_load_psqt(a) (*(a))
|
|
||||||
#define vec_store_psqt(a, b) *(a) = (b)
|
|
||||||
#define vec_add_psqt_32(a, b) vaddq_s32(a, b)
|
|
||||||
#define vec_sub_psqt_32(a, b) vsubq_s32(a, b)
|
|
||||||
#define vec_zero_psqt() \
|
|
||||||
psqt_vec_t { 0 }
|
|
||||||
#define NumRegistersSIMD 16
|
|
||||||
#define MaxChunkSize 16
|
|
||||||
|
|
||||||
#else
|
|
||||||
#undef VECTOR
|
|
||||||
|
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
#ifdef VECTOR
|
|
||||||
|
|
||||||
// Compute optimal SIMD register count for feature transformer accumulation.
|
|
||||||
|
|
||||||
// We use __m* types as template arguments, which causes GCC to emit warnings
|
|
||||||
// about losing some attribute information. This is irrelevant to us as we
|
|
||||||
// only take their size, so the following pragma are harmless.
|
|
||||||
#if defined(__GNUC__)
|
|
||||||
#pragma GCC diagnostic push
|
|
||||||
#pragma GCC diagnostic ignored "-Wignored-attributes"
|
|
||||||
#endif
|
|
||||||
|
|
||||||
template<typename SIMDRegisterType, typename LaneType, int NumLanes, int MaxRegisters>
|
|
||||||
static constexpr int BestRegisterCount() {
|
|
||||||
#define RegisterSize sizeof(SIMDRegisterType)
|
|
||||||
#define LaneSize sizeof(LaneType)
|
|
||||||
|
|
||||||
static_assert(RegisterSize >= LaneSize);
|
|
||||||
static_assert(MaxRegisters <= NumRegistersSIMD);
|
|
||||||
static_assert(MaxRegisters > 0);
|
|
||||||
static_assert(NumRegistersSIMD > 0);
|
|
||||||
static_assert(RegisterSize % LaneSize == 0);
|
|
||||||
static_assert((NumLanes * LaneSize) % RegisterSize == 0);
|
|
||||||
|
|
||||||
const int ideal = (NumLanes * LaneSize) / RegisterSize;
|
|
||||||
if (ideal <= MaxRegisters)
|
|
||||||
return ideal;
|
|
||||||
|
|
||||||
// Look for the largest divisor of the ideal register count that is smaller than MaxRegisters
|
|
||||||
for (int divisor = MaxRegisters; divisor > 1; --divisor)
|
|
||||||
if (ideal % divisor == 0)
|
|
||||||
return divisor;
|
|
||||||
|
|
||||||
return 1;
|
|
||||||
}
|
|
||||||
#if defined(__GNUC__)
|
|
||||||
#pragma GCC diagnostic pop
|
|
||||||
#endif
|
|
||||||
#endif
|
|
||||||
|
|
||||||
|
|
||||||
// Input feature converter
|
|
||||||
template<IndexType TransformedFeatureDimensions,
|
|
||||||
Accumulator<TransformedFeatureDimensions> StateInfo::*accPtr>
|
|
||||||
class FeatureTransformer {
|
|
||||||
|
|
||||||
// Number of output dimensions for one side
|
|
||||||
static constexpr IndexType HalfDimensions = TransformedFeatureDimensions;
|
|
||||||
|
|
||||||
private:
|
|
||||||
#ifdef VECTOR
|
|
||||||
static constexpr int NumRegs =
|
|
||||||
BestRegisterCount<vec_t, WeightType, TransformedFeatureDimensions, NumRegistersSIMD>();
|
|
||||||
static constexpr int NumPsqtRegs =
|
|
||||||
BestRegisterCount<psqt_vec_t, PSQTWeightType, PSQTBuckets, NumRegistersSIMD>();
|
|
||||||
|
|
||||||
static constexpr IndexType TileHeight = NumRegs * sizeof(vec_t) / 2;
|
|
||||||
static constexpr IndexType PsqtTileHeight = NumPsqtRegs * sizeof(psqt_vec_t) / 4;
|
|
||||||
static_assert(HalfDimensions % TileHeight == 0, "TileHeight must divide HalfDimensions");
|
|
||||||
static_assert(PSQTBuckets % PsqtTileHeight == 0, "PsqtTileHeight must divide PSQTBuckets");
|
|
||||||
#endif
|
|
||||||
|
|
||||||
public:
|
|
||||||
// Output type
|
|
||||||
using OutputType = TransformedFeatureType;
|
|
||||||
|
|
||||||
// Number of input/output dimensions
|
|
||||||
static constexpr IndexType InputDimensions = FeatureSet::Dimensions;
|
|
||||||
static constexpr IndexType OutputDimensions = HalfDimensions;
|
|
||||||
|
|
||||||
// Size of forward propagation buffer
|
|
||||||
static constexpr std::size_t BufferSize = OutputDimensions * sizeof(OutputType);
|
|
||||||
|
|
||||||
// Hash value embedded in the evaluation file
|
|
||||||
static constexpr std::uint32_t get_hash_value() {
|
|
||||||
return FeatureSet::HashValue ^ (OutputDimensions * 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
static constexpr void order_packs([[maybe_unused]] uint64_t* v) {
|
|
||||||
#if defined(USE_AVX512) // _mm512_packs_epi16 ordering
|
|
||||||
uint64_t tmp0 = v[2], tmp1 = v[3];
|
|
||||||
v[2] = v[8], v[3] = v[9];
|
|
||||||
v[8] = v[4], v[9] = v[5];
|
|
||||||
v[4] = tmp0, v[5] = tmp1;
|
|
||||||
tmp0 = v[6], tmp1 = v[7];
|
|
||||||
v[6] = v[10], v[7] = v[11];
|
|
||||||
v[10] = v[12], v[11] = v[13];
|
|
||||||
v[12] = tmp0, v[13] = tmp1;
|
|
||||||
#elif defined(USE_AVX2) // _mm256_packs_epi16 ordering
|
|
||||||
std::swap(v[2], v[4]);
|
|
||||||
std::swap(v[3], v[5]);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
static constexpr void inverse_order_packs([[maybe_unused]] uint64_t* v) {
|
|
||||||
#if defined(USE_AVX512) // Inverse _mm512_packs_epi16 ordering
|
|
||||||
uint64_t tmp0 = v[2], tmp1 = v[3];
|
|
||||||
v[2] = v[4], v[3] = v[5];
|
|
||||||
v[4] = v[8], v[5] = v[9];
|
|
||||||
v[8] = tmp0, v[9] = tmp1;
|
|
||||||
tmp0 = v[6], tmp1 = v[7];
|
|
||||||
v[6] = v[12], v[7] = v[13];
|
|
||||||
v[12] = v[10], v[13] = v[11];
|
|
||||||
v[10] = tmp0, v[11] = tmp1;
|
|
||||||
#elif defined(USE_AVX2) // Inverse _mm256_packs_epi16 ordering
|
|
||||||
std::swap(v[2], v[4]);
|
|
||||||
std::swap(v[3], v[5]);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
void permute_weights([[maybe_unused]] void (*order_fn)(uint64_t*)) const {
|
|
||||||
#if defined(USE_AVX2)
|
|
||||||
#if defined(USE_AVX512)
|
|
||||||
constexpr IndexType di = 16;
|
|
||||||
#else
|
|
||||||
constexpr IndexType di = 8;
|
|
||||||
#endif
|
|
||||||
uint64_t* b = reinterpret_cast<uint64_t*>(const_cast<BiasType*>(&biases[0]));
|
|
||||||
for (IndexType i = 0; i < HalfDimensions * sizeof(BiasType) / sizeof(uint64_t); i += di)
|
|
||||||
order_fn(&b[i]);
|
|
||||||
|
|
||||||
for (IndexType j = 0; j < InputDimensions; ++j)
|
|
||||||
{
|
|
||||||
uint64_t* w =
|
|
||||||
reinterpret_cast<uint64_t*>(const_cast<WeightType*>(&weights[j * HalfDimensions]));
|
|
||||||
for (IndexType i = 0; i < HalfDimensions * sizeof(WeightType) / sizeof(uint64_t);
|
|
||||||
i += di)
|
|
||||||
order_fn(&w[i]);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void scale_weights(bool read) const {
|
|
||||||
for (IndexType j = 0; j < InputDimensions; ++j)
|
|
||||||
{
|
|
||||||
WeightType* w = const_cast<WeightType*>(&weights[j * HalfDimensions]);
|
|
||||||
for (IndexType i = 0; i < HalfDimensions; ++i)
|
|
||||||
w[i] = read ? w[i] * 2 : w[i] / 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
BiasType* b = const_cast<BiasType*>(biases);
|
|
||||||
for (IndexType i = 0; i < HalfDimensions; ++i)
|
|
||||||
b[i] = read ? b[i] * 2 : b[i] / 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read network parameters
|
|
||||||
bool read_parameters(std::istream& stream) {
|
|
||||||
|
|
||||||
read_leb_128<BiasType>(stream, biases, HalfDimensions);
|
|
||||||
read_leb_128<WeightType>(stream, weights, HalfDimensions * InputDimensions);
|
|
||||||
read_leb_128<PSQTWeightType>(stream, psqtWeights, PSQTBuckets * InputDimensions);
|
|
||||||
|
|
||||||
permute_weights(inverse_order_packs);
|
|
||||||
scale_weights(true);
|
|
||||||
return !stream.fail();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write network parameters
|
|
||||||
bool write_parameters(std::ostream& stream) const {
|
|
||||||
|
|
||||||
permute_weights(order_packs);
|
|
||||||
scale_weights(false);
|
|
||||||
|
|
||||||
write_leb_128<BiasType>(stream, biases, HalfDimensions);
|
|
||||||
write_leb_128<WeightType>(stream, weights, HalfDimensions * InputDimensions);
|
|
||||||
write_leb_128<PSQTWeightType>(stream, psqtWeights, PSQTBuckets * InputDimensions);
|
|
||||||
|
|
||||||
permute_weights(inverse_order_packs);
|
|
||||||
scale_weights(true);
|
|
||||||
return !stream.fail();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert input features
|
|
||||||
std::int32_t transform(const Position& pos,
|
|
||||||
AccumulatorCaches::Cache<HalfDimensions>* cache,
|
|
||||||
OutputType* output,
|
|
||||||
int bucket) const {
|
|
||||||
update_accumulator<WHITE>(pos, cache);
|
|
||||||
update_accumulator<BLACK>(pos, cache);
|
|
||||||
|
|
||||||
const Color perspectives[2] = {pos.side_to_move(), ~pos.side_to_move()};
|
|
||||||
const auto& psqtAccumulation = (pos.state()->*accPtr).psqtAccumulation;
|
|
||||||
const auto psqt =
|
|
||||||
(psqtAccumulation[perspectives[0]][bucket] - psqtAccumulation[perspectives[1]][bucket])
|
|
||||||
/ 2;
|
|
||||||
|
|
||||||
const auto& accumulation = (pos.state()->*accPtr).accumulation;
|
|
||||||
|
|
||||||
for (IndexType p = 0; p < 2; ++p)
|
|
||||||
{
|
|
||||||
const IndexType offset = (HalfDimensions / 2) * p;
|
|
||||||
|
|
||||||
#if defined(VECTOR)
|
|
||||||
|
|
||||||
constexpr IndexType OutputChunkSize = MaxChunkSize;
|
|
||||||
static_assert((HalfDimensions / 2) % OutputChunkSize == 0);
|
|
||||||
constexpr IndexType NumOutputChunks = HalfDimensions / 2 / OutputChunkSize;
|
|
||||||
|
|
||||||
const vec_t Zero = vec_zero();
|
|
||||||
const vec_t One = vec_set_16(127 * 2);
|
|
||||||
|
|
||||||
const vec_t* in0 = reinterpret_cast<const vec_t*>(&(accumulation[perspectives[p]][0]));
|
|
||||||
const vec_t* in1 =
|
|
||||||
reinterpret_cast<const vec_t*>(&(accumulation[perspectives[p]][HalfDimensions / 2]));
|
|
||||||
vec_t* out = reinterpret_cast<vec_t*>(output + offset);
|
|
||||||
|
|
||||||
// Per the NNUE architecture, here we want to multiply pairs of
|
|
||||||
// clipped elements and divide the product by 128. To do this,
|
|
||||||
// we can naively perform min/max operation to clip each of the
|
|
||||||
// four int16 vectors, mullo pairs together, then pack them into
|
|
||||||
// one int8 vector. However, there exists a faster way.
|
|
||||||
|
|
||||||
// The idea here is to use the implicit clipping from packus to
|
|
||||||
// save us two vec_max_16 instructions. This clipping works due
|
|
||||||
// to the fact that any int16 integer below zero will be zeroed
|
|
||||||
// on packus.
|
|
||||||
|
|
||||||
// Consider the case where the second element is negative.
|
|
||||||
// If we do standard clipping, that element will be zero, which
|
|
||||||
// means our pairwise product is zero. If we perform packus and
|
|
||||||
// remove the lower-side clip for the second element, then our
|
|
||||||
// product before packus will be negative, and is zeroed on pack.
|
|
||||||
// The two operation produce equivalent results, but the second
|
|
||||||
// one (using packus) saves one max operation per pair.
|
|
||||||
|
|
||||||
// But here we run into a problem: mullo does not preserve the
|
|
||||||
// sign of the multiplication. We can get around this by doing
|
|
||||||
// mulhi, which keeps the sign. But that requires an additional
|
|
||||||
// tweak.
|
|
||||||
|
|
||||||
// mulhi cuts off the last 16 bits of the resulting product,
|
|
||||||
// which is the same as performing a rightward shift of 16 bits.
|
|
||||||
// We can use this to our advantage. Recall that we want to
|
|
||||||
// divide the final product by 128, which is equivalent to a
|
|
||||||
// 7-bit right shift. Intuitively, if we shift the clipped
|
|
||||||
// value left by 9, and perform mulhi, which shifts the product
|
|
||||||
// right by 16 bits, then we will net a right shift of 7 bits.
|
|
||||||
// However, this won't work as intended. Since we clip the
|
|
||||||
// values to have a maximum value of 127, shifting it by 9 bits
|
|
||||||
// might occupy the signed bit, resulting in some positive
|
|
||||||
// values being interpreted as negative after the shift.
|
|
||||||
|
|
||||||
// There is a way, however, to get around this limitation. When
|
|
||||||
// loading the network, scale accumulator weights and biases by
|
|
||||||
// 2. To get the same pairwise multiplication result as before,
|
|
||||||
// we need to divide the product by 128 * 2 * 2 = 512, which
|
|
||||||
// amounts to a right shift of 9 bits. So now we only have to
|
|
||||||
// shift left by 7 bits, perform mulhi (shifts right by 16 bits)
|
|
||||||
// and net a 9 bit right shift. Since we scaled everything by
|
|
||||||
// two, the values are clipped at 127 * 2 = 254, which occupies
|
|
||||||
// 8 bits. Shifting it by 7 bits left will no longer occupy the
|
|
||||||
// signed bit, so we are safe.
|
|
||||||
|
|
||||||
// Note that on NEON processors, we shift left by 6 instead
|
|
||||||
// because the instruction "vqdmulhq_s16" also doubles the
|
|
||||||
// return value after the multiplication, adding an extra shift
|
|
||||||
// to the left by 1, so we compensate by shifting less before
|
|
||||||
// the multiplication.
|
|
||||||
|
|
||||||
constexpr int shift =
|
|
||||||
#if defined(USE_SSE2)
|
|
||||||
7;
|
|
||||||
#else
|
|
||||||
6;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
for (IndexType j = 0; j < NumOutputChunks; ++j)
|
|
||||||
{
|
|
||||||
const vec_t sum0a =
|
|
||||||
vec_slli_16(vec_max_16(vec_min_16(in0[j * 2 + 0], One), Zero), shift);
|
|
||||||
const vec_t sum0b =
|
|
||||||
vec_slli_16(vec_max_16(vec_min_16(in0[j * 2 + 1], One), Zero), shift);
|
|
||||||
const vec_t sum1a = vec_min_16(in1[j * 2 + 0], One);
|
|
||||||
const vec_t sum1b = vec_min_16(in1[j * 2 + 1], One);
|
|
||||||
|
|
||||||
const vec_t pa = vec_mulhi_16(sum0a, sum1a);
|
|
||||||
const vec_t pb = vec_mulhi_16(sum0b, sum1b);
|
|
||||||
|
|
||||||
out[j] = vec_packus_16(pa, pb);
|
|
||||||
}
|
|
||||||
|
|
||||||
#else
|
|
||||||
|
|
||||||
for (IndexType j = 0; j < HalfDimensions / 2; ++j)
|
|
||||||
{
|
|
||||||
BiasType sum0 = accumulation[static_cast<int>(perspectives[p])][j + 0];
|
|
||||||
BiasType sum1 =
|
|
||||||
accumulation[static_cast<int>(perspectives[p])][j + HalfDimensions / 2];
|
|
||||||
sum0 = std::clamp<BiasType>(sum0, 0, 127 * 2);
|
|
||||||
sum1 = std::clamp<BiasType>(sum1, 0, 127 * 2);
|
|
||||||
output[offset + j] = static_cast<OutputType>(unsigned(sum0 * sum1) / 512);
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
return psqt;
|
|
||||||
} // end of function transform()
|
|
||||||
|
|
||||||
void hint_common_access(const Position& pos,
|
|
||||||
AccumulatorCaches::Cache<HalfDimensions>* cache) const {
|
|
||||||
hint_common_access_for_perspective<WHITE>(pos, cache);
|
|
||||||
hint_common_access_for_perspective<BLACK>(pos, cache);
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
template<Color Perspective>
|
|
||||||
[[nodiscard]] std::pair<StateInfo*, StateInfo*>
|
|
||||||
try_find_computed_accumulator(const Position& pos) const {
|
|
||||||
// Look for a usable accumulator of an earlier position. We keep track
|
|
||||||
// of the estimated gain in terms of features to be added/subtracted.
|
|
||||||
StateInfo *st = pos.state(), *next = nullptr;
|
|
||||||
int gain = FeatureSet::refresh_cost(pos);
|
|
||||||
while (st->previous && !(st->*accPtr).computed[Perspective])
|
|
||||||
{
|
|
||||||
// This governs when a full feature refresh is needed and how many
|
|
||||||
// updates are better than just one full refresh.
|
|
||||||
if (FeatureSet::requires_refresh(st, Perspective)
|
|
||||||
|| (gain -= FeatureSet::update_cost(st) + 1) < 0)
|
|
||||||
break;
|
|
||||||
next = st;
|
|
||||||
st = st->previous;
|
|
||||||
}
|
|
||||||
return {st, next};
|
|
||||||
}
|
|
||||||
|
|
||||||
// NOTE: The parameter states_to_update is an array of position states.
|
|
||||||
// All states must be sequential, that is states_to_update[i] must
|
|
||||||
// either be reachable by repeatedly applying ->previous from
|
|
||||||
// states_to_update[i+1], and computed_st must be reachable by
|
|
||||||
// repeatedly applying ->previous on states_to_update[0].
|
|
||||||
template<Color Perspective, size_t N>
|
|
||||||
void update_accumulator_incremental(const Position& pos,
|
|
||||||
StateInfo* computed_st,
|
|
||||||
StateInfo* states_to_update[N]) const {
|
|
||||||
static_assert(N > 0);
|
|
||||||
assert([&]() {
|
|
||||||
for (size_t i = 0; i < N; ++i)
|
|
||||||
{
|
|
||||||
if (states_to_update[i] == nullptr)
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}());
|
|
||||||
|
|
||||||
#ifdef VECTOR
|
|
||||||
// Gcc-10.2 unnecessarily spills AVX2 registers if this array
|
|
||||||
// is defined in the VECTOR code below, once in each branch.
|
|
||||||
vec_t acc[NumRegs];
|
|
||||||
psqt_vec_t psqt[NumPsqtRegs];
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Update incrementally going back through states_to_update.
|
|
||||||
// Gather all features to be updated.
|
|
||||||
const Square ksq = pos.square<KING>(Perspective);
|
|
||||||
|
|
||||||
// The size must be enough to contain the largest possible update.
|
|
||||||
// That might depend on the feature set and generally relies on the
|
|
||||||
// feature set's update cost calculation to be correct and never allow
|
|
||||||
// updates with more added/removed features than MaxActiveDimensions.
|
|
||||||
FeatureSet::IndexList removed[N], added[N];
|
|
||||||
|
|
||||||
for (int i = N - 1; i >= 0; --i)
|
|
||||||
{
|
|
||||||
(states_to_update[i]->*accPtr).computed[Perspective] = true;
|
|
||||||
|
|
||||||
const StateInfo* end_state = i == 0 ? computed_st : states_to_update[i - 1];
|
|
||||||
|
|
||||||
for (StateInfo* st2 = states_to_update[i]; st2 != end_state; st2 = st2->previous)
|
|
||||||
FeatureSet::append_changed_indices<Perspective>(ksq, st2->dirtyPiece, removed[i],
|
|
||||||
added[i]);
|
|
||||||
}
|
|
||||||
|
|
||||||
StateInfo* st = computed_st;
|
|
||||||
|
|
||||||
// Now update the accumulators listed in states_to_update[],
|
|
||||||
// where the last element is a sentinel.
|
|
||||||
#ifdef VECTOR
|
|
||||||
|
|
||||||
if (N == 1 && (removed[0].size() == 1 || removed[0].size() == 2) && added[0].size() == 1)
|
|
||||||
{
|
|
||||||
assert(states_to_update[0]);
|
|
||||||
|
|
||||||
auto accIn =
|
|
||||||
reinterpret_cast<const vec_t*>(&(st->*accPtr).accumulation[Perspective][0]);
|
|
||||||
auto accOut = reinterpret_cast<vec_t*>(
|
|
||||||
&(states_to_update[0]->*accPtr).accumulation[Perspective][0]);
|
|
||||||
|
|
||||||
const IndexType offsetR0 = HalfDimensions * removed[0][0];
|
|
||||||
auto columnR0 = reinterpret_cast<const vec_t*>(&weights[offsetR0]);
|
|
||||||
const IndexType offsetA = HalfDimensions * added[0][0];
|
|
||||||
auto columnA = reinterpret_cast<const vec_t*>(&weights[offsetA]);
|
|
||||||
|
|
||||||
if (removed[0].size() == 1)
|
|
||||||
{
|
|
||||||
for (IndexType k = 0; k < HalfDimensions * sizeof(std::int16_t) / sizeof(vec_t);
|
|
||||||
++k)
|
|
||||||
accOut[k] = vec_add_16(vec_sub_16(accIn[k], columnR0[k]), columnA[k]);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
const IndexType offsetR1 = HalfDimensions * removed[0][1];
|
|
||||||
auto columnR1 = reinterpret_cast<const vec_t*>(&weights[offsetR1]);
|
|
||||||
|
|
||||||
for (IndexType k = 0; k < HalfDimensions * sizeof(std::int16_t) / sizeof(vec_t);
|
|
||||||
++k)
|
|
||||||
accOut[k] = vec_sub_16(vec_add_16(accIn[k], columnA[k]),
|
|
||||||
vec_add_16(columnR0[k], columnR1[k]));
|
|
||||||
}
|
|
||||||
|
|
||||||
auto accPsqtIn =
|
|
||||||
reinterpret_cast<const psqt_vec_t*>(&(st->*accPtr).psqtAccumulation[Perspective][0]);
|
|
||||||
auto accPsqtOut = reinterpret_cast<psqt_vec_t*>(
|
|
||||||
&(states_to_update[0]->*accPtr).psqtAccumulation[Perspective][0]);
|
|
||||||
|
|
||||||
const IndexType offsetPsqtR0 = PSQTBuckets * removed[0][0];
|
|
||||||
auto columnPsqtR0 = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offsetPsqtR0]);
|
|
||||||
const IndexType offsetPsqtA = PSQTBuckets * added[0][0];
|
|
||||||
auto columnPsqtA = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offsetPsqtA]);
|
|
||||||
|
|
||||||
if (removed[0].size() == 1)
|
|
||||||
{
|
|
||||||
for (std::size_t k = 0; k < PSQTBuckets * sizeof(std::int32_t) / sizeof(psqt_vec_t);
|
|
||||||
++k)
|
|
||||||
accPsqtOut[k] = vec_add_psqt_32(vec_sub_psqt_32(accPsqtIn[k], columnPsqtR0[k]),
|
|
||||||
columnPsqtA[k]);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
const IndexType offsetPsqtR1 = PSQTBuckets * removed[0][1];
|
|
||||||
auto columnPsqtR1 = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offsetPsqtR1]);
|
|
||||||
|
|
||||||
for (std::size_t k = 0; k < PSQTBuckets * sizeof(std::int32_t) / sizeof(psqt_vec_t);
|
|
||||||
++k)
|
|
||||||
accPsqtOut[k] =
|
|
||||||
vec_sub_psqt_32(vec_add_psqt_32(accPsqtIn[k], columnPsqtA[k]),
|
|
||||||
vec_add_psqt_32(columnPsqtR0[k], columnPsqtR1[k]));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
|
|
||||||
{
|
|
||||||
// Load accumulator
|
|
||||||
auto accTileIn = reinterpret_cast<const vec_t*>(
|
|
||||||
&(st->*accPtr).accumulation[Perspective][j * TileHeight]);
|
|
||||||
for (IndexType k = 0; k < NumRegs; ++k)
|
|
||||||
acc[k] = vec_load(&accTileIn[k]);
|
|
||||||
|
|
||||||
for (IndexType i = 0; i < N; ++i)
|
|
||||||
{
|
|
||||||
// Difference calculation for the deactivated features
|
|
||||||
for (const auto index : removed[i])
|
|
||||||
{
|
|
||||||
const IndexType offset = HalfDimensions * index + j * TileHeight;
|
|
||||||
auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
|
|
||||||
for (IndexType k = 0; k < NumRegs; ++k)
|
|
||||||
acc[k] = vec_sub_16(acc[k], column[k]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Difference calculation for the activated features
|
|
||||||
for (const auto index : added[i])
|
|
||||||
{
|
|
||||||
const IndexType offset = HalfDimensions * index + j * TileHeight;
|
|
||||||
auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
|
|
||||||
for (IndexType k = 0; k < NumRegs; ++k)
|
|
||||||
acc[k] = vec_add_16(acc[k], column[k]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store accumulator
|
|
||||||
auto accTileOut = reinterpret_cast<vec_t*>(
|
|
||||||
&(states_to_update[i]->*accPtr).accumulation[Perspective][j * TileHeight]);
|
|
||||||
for (IndexType k = 0; k < NumRegs; ++k)
|
|
||||||
vec_store(&accTileOut[k], acc[k]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
|
|
||||||
{
|
|
||||||
// Load accumulator
|
|
||||||
auto accTilePsqtIn = reinterpret_cast<const psqt_vec_t*>(
|
|
||||||
&(st->*accPtr).psqtAccumulation[Perspective][j * PsqtTileHeight]);
|
|
||||||
for (std::size_t k = 0; k < NumPsqtRegs; ++k)
|
|
||||||
psqt[k] = vec_load_psqt(&accTilePsqtIn[k]);
|
|
||||||
|
|
||||||
for (IndexType i = 0; i < N; ++i)
|
|
||||||
{
|
|
||||||
// Difference calculation for the deactivated features
|
|
||||||
for (const auto index : removed[i])
|
|
||||||
{
|
|
||||||
const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
|
|
||||||
auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
|
|
||||||
for (std::size_t k = 0; k < NumPsqtRegs; ++k)
|
|
||||||
psqt[k] = vec_sub_psqt_32(psqt[k], columnPsqt[k]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Difference calculation for the activated features
|
|
||||||
for (const auto index : added[i])
|
|
||||||
{
|
|
||||||
const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
|
|
||||||
auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
|
|
||||||
for (std::size_t k = 0; k < NumPsqtRegs; ++k)
|
|
||||||
psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store accumulator
|
|
||||||
auto accTilePsqtOut = reinterpret_cast<psqt_vec_t*>(
|
|
||||||
&(states_to_update[i]->*accPtr)
|
|
||||||
.psqtAccumulation[Perspective][j * PsqtTileHeight]);
|
|
||||||
for (std::size_t k = 0; k < NumPsqtRegs; ++k)
|
|
||||||
vec_store_psqt(&accTilePsqtOut[k], psqt[k]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
for (IndexType i = 0; i < N; ++i)
|
|
||||||
{
|
|
||||||
std::memcpy((states_to_update[i]->*accPtr).accumulation[Perspective],
|
|
||||||
(st->*accPtr).accumulation[Perspective], HalfDimensions * sizeof(BiasType));
|
|
||||||
|
|
||||||
for (std::size_t k = 0; k < PSQTBuckets; ++k)
|
|
||||||
(states_to_update[i]->*accPtr).psqtAccumulation[Perspective][k] =
|
|
||||||
(st->*accPtr).psqtAccumulation[Perspective][k];
|
|
||||||
|
|
||||||
st = states_to_update[i];
|
|
||||||
|
|
||||||
// Difference calculation for the deactivated features
|
|
||||||
for (const auto index : removed[i])
|
|
||||||
{
|
|
||||||
const IndexType offset = HalfDimensions * index;
|
|
||||||
for (IndexType j = 0; j < HalfDimensions; ++j)
|
|
||||||
(st->*accPtr).accumulation[Perspective][j] -= weights[offset + j];
|
|
||||||
|
|
||||||
for (std::size_t k = 0; k < PSQTBuckets; ++k)
|
|
||||||
(st->*accPtr).psqtAccumulation[Perspective][k] -=
|
|
||||||
psqtWeights[index * PSQTBuckets + k];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Difference calculation for the activated features
|
|
||||||
for (const auto index : added[i])
|
|
||||||
{
|
|
||||||
const IndexType offset = HalfDimensions * index;
|
|
||||||
for (IndexType j = 0; j < HalfDimensions; ++j)
|
|
||||||
(st->*accPtr).accumulation[Perspective][j] += weights[offset + j];
|
|
||||||
|
|
||||||
for (std::size_t k = 0; k < PSQTBuckets; ++k)
|
|
||||||
(st->*accPtr).psqtAccumulation[Perspective][k] +=
|
|
||||||
psqtWeights[index * PSQTBuckets + k];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
template<Color Perspective>
|
|
||||||
void update_accumulator_refresh_cache(const Position& pos,
|
|
||||||
AccumulatorCaches::Cache<HalfDimensions>* cache) const {
|
|
||||||
assert(cache != nullptr);
|
|
||||||
|
|
||||||
Square ksq = pos.square<KING>(Perspective);
|
|
||||||
auto& entry = (*cache)[ksq][Perspective];
|
|
||||||
FeatureSet::IndexList removed, added;
|
|
||||||
|
|
||||||
for (Color c : {WHITE, BLACK})
|
|
||||||
{
|
|
||||||
for (PieceType pt = PAWN; pt <= KING; ++pt)
|
|
||||||
{
|
|
||||||
const Piece piece = make_piece(c, pt);
|
|
||||||
const Bitboard oldBB = entry.byColorBB[c] & entry.byTypeBB[pt];
|
|
||||||
const Bitboard newBB = pos.pieces(c, pt);
|
|
||||||
Bitboard toRemove = oldBB & ~newBB;
|
|
||||||
Bitboard toAdd = newBB & ~oldBB;
|
|
||||||
|
|
||||||
while (toRemove)
|
|
||||||
{
|
|
||||||
Square sq = pop_lsb(toRemove);
|
|
||||||
removed.push_back(FeatureSet::make_index<Perspective>(sq, piece, ksq));
|
|
||||||
}
|
|
||||||
while (toAdd)
|
|
||||||
{
|
|
||||||
Square sq = pop_lsb(toAdd);
|
|
||||||
added.push_back(FeatureSet::make_index<Perspective>(sq, piece, ksq));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
auto& accumulator = pos.state()->*accPtr;
|
|
||||||
accumulator.computed[Perspective] = true;
|
|
||||||
|
|
||||||
#ifdef VECTOR
|
|
||||||
vec_t acc[NumRegs];
|
|
||||||
psqt_vec_t psqt[NumPsqtRegs];
|
|
||||||
|
|
||||||
for (IndexType j = 0; j < HalfDimensions / TileHeight; ++j)
|
|
||||||
{
|
|
||||||
auto accTile =
|
|
||||||
reinterpret_cast<vec_t*>(&accumulator.accumulation[Perspective][j * TileHeight]);
|
|
||||||
auto entryTile = reinterpret_cast<vec_t*>(&entry.accumulation[j * TileHeight]);
|
|
||||||
|
|
||||||
for (IndexType k = 0; k < NumRegs; ++k)
|
|
||||||
acc[k] = entryTile[k];
|
|
||||||
|
|
||||||
int i = 0;
|
|
||||||
for (; i < int(std::min(removed.size(), added.size())); ++i)
|
|
||||||
{
|
|
||||||
IndexType indexR = removed[i];
|
|
||||||
const IndexType offsetR = HalfDimensions * indexR + j * TileHeight;
|
|
||||||
auto columnR = reinterpret_cast<const vec_t*>(&weights[offsetR]);
|
|
||||||
IndexType indexA = added[i];
|
|
||||||
const IndexType offsetA = HalfDimensions * indexA + j * TileHeight;
|
|
||||||
auto columnA = reinterpret_cast<const vec_t*>(&weights[offsetA]);
|
|
||||||
|
|
||||||
for (unsigned k = 0; k < NumRegs; ++k)
|
|
||||||
acc[k] = vec_add_16(acc[k], vec_sub_16(columnA[k], columnR[k]));
|
|
||||||
}
|
|
||||||
for (; i < int(removed.size()); ++i)
|
|
||||||
{
|
|
||||||
IndexType index = removed[i];
|
|
||||||
const IndexType offset = HalfDimensions * index + j * TileHeight;
|
|
||||||
auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
|
|
||||||
|
|
||||||
for (unsigned k = 0; k < NumRegs; ++k)
|
|
||||||
acc[k] = vec_sub_16(acc[k], column[k]);
|
|
||||||
}
|
|
||||||
for (; i < int(added.size()); ++i)
|
|
||||||
{
|
|
||||||
IndexType index = added[i];
|
|
||||||
const IndexType offset = HalfDimensions * index + j * TileHeight;
|
|
||||||
auto column = reinterpret_cast<const vec_t*>(&weights[offset]);
|
|
||||||
|
|
||||||
for (unsigned k = 0; k < NumRegs; ++k)
|
|
||||||
acc[k] = vec_add_16(acc[k], column[k]);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (IndexType k = 0; k < NumRegs; k++)
|
|
||||||
vec_store(&entryTile[k], acc[k]);
|
|
||||||
for (IndexType k = 0; k < NumRegs; k++)
|
|
||||||
vec_store(&accTile[k], acc[k]);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (IndexType j = 0; j < PSQTBuckets / PsqtTileHeight; ++j)
|
|
||||||
{
|
|
||||||
auto accTilePsqt = reinterpret_cast<psqt_vec_t*>(
|
|
||||||
&accumulator.psqtAccumulation[Perspective][j * PsqtTileHeight]);
|
|
||||||
auto entryTilePsqt =
|
|
||||||
reinterpret_cast<psqt_vec_t*>(&entry.psqtAccumulation[j * PsqtTileHeight]);
|
|
||||||
|
|
||||||
for (std::size_t k = 0; k < NumPsqtRegs; ++k)
|
|
||||||
psqt[k] = entryTilePsqt[k];
|
|
||||||
|
|
||||||
for (int i = 0; i < int(removed.size()); ++i)
|
|
||||||
{
|
|
||||||
IndexType index = removed[i];
|
|
||||||
const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
|
|
||||||
auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
|
|
||||||
|
|
||||||
for (std::size_t k = 0; k < NumPsqtRegs; ++k)
|
|
||||||
psqt[k] = vec_sub_psqt_32(psqt[k], columnPsqt[k]);
|
|
||||||
}
|
|
||||||
for (int i = 0; i < int(added.size()); ++i)
|
|
||||||
{
|
|
||||||
IndexType index = added[i];
|
|
||||||
const IndexType offset = PSQTBuckets * index + j * PsqtTileHeight;
|
|
||||||
auto columnPsqt = reinterpret_cast<const psqt_vec_t*>(&psqtWeights[offset]);
|
|
||||||
|
|
||||||
for (std::size_t k = 0; k < NumPsqtRegs; ++k)
|
|
||||||
psqt[k] = vec_add_psqt_32(psqt[k], columnPsqt[k]);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (std::size_t k = 0; k < NumPsqtRegs; ++k)
|
|
||||||
vec_store_psqt(&entryTilePsqt[k], psqt[k]);
|
|
||||||
for (std::size_t k = 0; k < NumPsqtRegs; ++k)
|
|
||||||
vec_store_psqt(&accTilePsqt[k], psqt[k]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#else
|
|
||||||
|
|
||||||
for (const auto index : removed)
|
|
||||||
{
|
|
||||||
const IndexType offset = HalfDimensions * index;
|
|
||||||
for (IndexType j = 0; j < HalfDimensions; ++j)
|
|
||||||
entry.accumulation[j] -= weights[offset + j];
|
|
||||||
|
|
||||||
for (std::size_t k = 0; k < PSQTBuckets; ++k)
|
|
||||||
entry.psqtAccumulation[k] -= psqtWeights[index * PSQTBuckets + k];
|
|
||||||
}
|
|
||||||
for (const auto index : added)
|
|
||||||
{
|
|
||||||
const IndexType offset = HalfDimensions * index;
|
|
||||||
for (IndexType j = 0; j < HalfDimensions; ++j)
|
|
||||||
entry.accumulation[j] += weights[offset + j];
|
|
||||||
|
|
||||||
for (std::size_t k = 0; k < PSQTBuckets; ++k)
|
|
||||||
entry.psqtAccumulation[k] += psqtWeights[index * PSQTBuckets + k];
|
|
||||||
}
|
|
||||||
|
|
||||||
// The accumulator of the refresh entry has been updated.
|
|
||||||
// Now copy its content to the actual accumulator we were refreshing.
|
|
||||||
|
|
||||||
std::memcpy(accumulator.accumulation[Perspective], entry.accumulation,
|
|
||||||
sizeof(BiasType) * HalfDimensions);
|
|
||||||
|
|
||||||
std::memcpy(accumulator.psqtAccumulation[Perspective], entry.psqtAccumulation,
|
|
||||||
sizeof(int32_t) * PSQTBuckets);
|
|
||||||
#endif
|
|
||||||
|
|
||||||
for (Color c : {WHITE, BLACK})
|
|
||||||
entry.byColorBB[c] = pos.pieces(c);
|
|
||||||
|
|
||||||
for (PieceType pt = PAWN; pt <= KING; ++pt)
|
|
||||||
entry.byTypeBB[pt] = pos.pieces(pt);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<Color Perspective>
|
|
||||||
void hint_common_access_for_perspective(const Position& pos,
|
|
||||||
AccumulatorCaches::Cache<HalfDimensions>* cache) const {
|
|
||||||
|
|
||||||
// Works like update_accumulator, but performs less work.
|
|
||||||
// Updates ONLY the accumulator for pos.
|
|
||||||
|
|
||||||
// Look for a usable accumulator of an earlier position. We keep track
|
|
||||||
// of the estimated gain in terms of features to be added/subtracted.
|
|
||||||
// Fast early exit.
|
|
||||||
if ((pos.state()->*accPtr).computed[Perspective])
|
|
||||||
return;
|
|
||||||
|
|
||||||
auto [oldest_st, _] = try_find_computed_accumulator<Perspective>(pos);
|
|
||||||
|
|
||||||
if ((oldest_st->*accPtr).computed[Perspective])
|
|
||||||
{
|
|
||||||
// Only update current position accumulator to minimize work
|
|
||||||
StateInfo* states_to_update[1] = {pos.state()};
|
|
||||||
update_accumulator_incremental<Perspective, 1>(pos, oldest_st, states_to_update);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
update_accumulator_refresh_cache<Perspective>(pos, cache);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<Color Perspective>
|
|
||||||
void update_accumulator(const Position& pos,
|
|
||||||
AccumulatorCaches::Cache<HalfDimensions>* cache) const {
|
|
||||||
|
|
||||||
auto [oldest_st, next] = try_find_computed_accumulator<Perspective>(pos);
|
|
||||||
|
|
||||||
if ((oldest_st->*accPtr).computed[Perspective])
|
|
||||||
{
|
|
||||||
if (next == nullptr)
|
|
||||||
return;
|
|
||||||
|
|
||||||
// Now update the accumulators listed in states_to_update[], where
|
|
||||||
// the last element is a sentinel. Currently we update two accumulators:
|
|
||||||
// 1. for the current position
|
|
||||||
// 2. the next accumulator after the computed one
|
|
||||||
// The heuristic may change in the future.
|
|
||||||
if (next == pos.state())
|
|
||||||
{
|
|
||||||
StateInfo* states_to_update[1] = {next};
|
|
||||||
|
|
||||||
update_accumulator_incremental<Perspective, 1>(pos, oldest_st, states_to_update);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
StateInfo* states_to_update[2] = {next, pos.state()};
|
|
||||||
|
|
||||||
update_accumulator_incremental<Perspective, 2>(pos, oldest_st, states_to_update);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else
|
|
||||||
update_accumulator_refresh_cache<Perspective>(pos, cache);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<IndexType Size>
|
|
||||||
friend struct AccumulatorCaches::Cache;
|
|
||||||
|
|
||||||
alignas(CacheLineSize) BiasType biases[HalfDimensions];
|
|
||||||
alignas(CacheLineSize) WeightType weights[HalfDimensions * InputDimensions];
|
|
||||||
alignas(CacheLineSize) PSQTWeightType psqtWeights[InputDimensions * PSQTBuckets];
|
|
||||||
};
|
|
||||||
|
|
||||||
} // namespace Stockfish::Eval::NNUE
|
|
||||||
|
|
||||||
#endif // #ifndef NNUE_FEATURE_TRANSFORMER_H_INCLUDED
|
|
||||||
@@ -1,203 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
// Code for calculating NNUE evaluation function
|
|
||||||
|
|
||||||
#include "nnue_misc.h"
|
|
||||||
|
|
||||||
#include <cmath>
|
|
||||||
#include <cstdlib>
|
|
||||||
#include <cstring>
|
|
||||||
#include <iomanip>
|
|
||||||
#include <iosfwd>
|
|
||||||
#include <iostream>
|
|
||||||
#include <sstream>
|
|
||||||
#include <string_view>
|
|
||||||
#include <tuple>
|
|
||||||
|
|
||||||
#include "../evaluate.h"
|
|
||||||
#include "../position.h"
|
|
||||||
#include "../types.h"
|
|
||||||
#include "../uci.h"
|
|
||||||
#include "network.h"
|
|
||||||
#include "nnue_accumulator.h"
|
|
||||||
|
|
||||||
namespace Stockfish::Eval::NNUE {
|
|
||||||
|
|
||||||
|
|
||||||
constexpr std::string_view PieceToChar(" PNBRQK pnbrqk");
|
|
||||||
|
|
||||||
|
|
||||||
void hint_common_parent_position(const Position& pos,
|
|
||||||
const Networks& networks,
|
|
||||||
AccumulatorCaches& caches) {
|
|
||||||
if (Eval::use_smallnet(pos))
|
|
||||||
networks.small.hint_common_access(pos, &caches.small);
|
|
||||||
else
|
|
||||||
networks.big.hint_common_access(pos, &caches.big);
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace {
|
|
||||||
// Converts a Value into (centi)pawns and writes it in a buffer.
|
|
||||||
// The buffer must have capacity for at least 5 chars.
|
|
||||||
void format_cp_compact(Value v, char* buffer, const Position& pos) {
|
|
||||||
|
|
||||||
buffer[0] = (v < 0 ? '-' : v > 0 ? '+' : ' ');
|
|
||||||
|
|
||||||
int cp = std::abs(UCIEngine::to_cp(v, pos));
|
|
||||||
if (cp >= 10000)
|
|
||||||
{
|
|
||||||
buffer[1] = '0' + cp / 10000;
|
|
||||||
cp %= 10000;
|
|
||||||
buffer[2] = '0' + cp / 1000;
|
|
||||||
cp %= 1000;
|
|
||||||
buffer[3] = '0' + cp / 100;
|
|
||||||
buffer[4] = ' ';
|
|
||||||
}
|
|
||||||
else if (cp >= 1000)
|
|
||||||
{
|
|
||||||
buffer[1] = '0' + cp / 1000;
|
|
||||||
cp %= 1000;
|
|
||||||
buffer[2] = '0' + cp / 100;
|
|
||||||
cp %= 100;
|
|
||||||
buffer[3] = '.';
|
|
||||||
buffer[4] = '0' + cp / 10;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
buffer[1] = '0' + cp / 100;
|
|
||||||
cp %= 100;
|
|
||||||
buffer[2] = '.';
|
|
||||||
buffer[3] = '0' + cp / 10;
|
|
||||||
cp %= 10;
|
|
||||||
buffer[4] = '0' + cp / 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Converts a Value into pawns, always keeping two decimals
|
|
||||||
void format_cp_aligned_dot(Value v, std::stringstream& stream, const Position& pos) {
|
|
||||||
|
|
||||||
const double pawns = std::abs(0.01 * UCIEngine::to_cp(v, pos));
|
|
||||||
|
|
||||||
stream << (v < 0 ? '-'
|
|
||||||
: v > 0 ? '+'
|
|
||||||
: ' ')
|
|
||||||
<< std::setiosflags(std::ios::fixed) << std::setw(6) << std::setprecision(2) << pawns;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
// Returns a string with the value of each piece on a board,
|
|
||||||
// and a table for (PSQT, Layers) values bucket by bucket.
|
|
||||||
std::string
|
|
||||||
trace(Position& pos, const Eval::NNUE::Networks& networks, Eval::NNUE::AccumulatorCaches& caches) {
|
|
||||||
|
|
||||||
std::stringstream ss;
|
|
||||||
|
|
||||||
char board[3 * 8 + 1][8 * 8 + 2];
|
|
||||||
std::memset(board, ' ', sizeof(board));
|
|
||||||
for (int row = 0; row < 3 * 8 + 1; ++row)
|
|
||||||
board[row][8 * 8 + 1] = '\0';
|
|
||||||
|
|
||||||
// A lambda to output one box of the board
|
|
||||||
auto writeSquare = [&board, &pos](File file, Rank rank, Piece pc, Value value) {
|
|
||||||
const int x = int(file) * 8;
|
|
||||||
const int y = (7 - int(rank)) * 3;
|
|
||||||
for (int i = 1; i < 8; ++i)
|
|
||||||
board[y][x + i] = board[y + 3][x + i] = '-';
|
|
||||||
for (int i = 1; i < 3; ++i)
|
|
||||||
board[y + i][x] = board[y + i][x + 8] = '|';
|
|
||||||
board[y][x] = board[y][x + 8] = board[y + 3][x + 8] = board[y + 3][x] = '+';
|
|
||||||
if (pc != NO_PIECE)
|
|
||||||
board[y + 1][x + 4] = PieceToChar[pc];
|
|
||||||
if (value != VALUE_NONE)
|
|
||||||
format_cp_compact(value, &board[y + 2][x + 2], pos);
|
|
||||||
};
|
|
||||||
|
|
||||||
// We estimate the value of each piece by doing a differential evaluation from
|
|
||||||
// the current base eval, simulating the removal of the piece from its square.
|
|
||||||
auto [psqt, positional] = networks.big.evaluate(pos, &caches.big);
|
|
||||||
Value base = psqt + positional;
|
|
||||||
base = pos.side_to_move() == WHITE ? base : -base;
|
|
||||||
|
|
||||||
for (File f = FILE_A; f <= FILE_H; ++f)
|
|
||||||
for (Rank r = RANK_1; r <= RANK_8; ++r)
|
|
||||||
{
|
|
||||||
Square sq = make_square(f, r);
|
|
||||||
Piece pc = pos.piece_on(sq);
|
|
||||||
Value v = VALUE_NONE;
|
|
||||||
|
|
||||||
if (pc != NO_PIECE && type_of(pc) != KING)
|
|
||||||
{
|
|
||||||
auto st = pos.state();
|
|
||||||
|
|
||||||
pos.remove_piece(sq);
|
|
||||||
st->accumulatorBig.computed[WHITE] = st->accumulatorBig.computed[BLACK] = false;
|
|
||||||
|
|
||||||
std::tie(psqt, positional) = networks.big.evaluate(pos, &caches.big);
|
|
||||||
Value eval = psqt + positional;
|
|
||||||
eval = pos.side_to_move() == WHITE ? eval : -eval;
|
|
||||||
v = base - eval;
|
|
||||||
|
|
||||||
pos.put_piece(pc, sq);
|
|
||||||
st->accumulatorBig.computed[WHITE] = st->accumulatorBig.computed[BLACK] = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
writeSquare(f, r, pc, v);
|
|
||||||
}
|
|
||||||
|
|
||||||
ss << " NNUE derived piece values:\n";
|
|
||||||
for (int row = 0; row < 3 * 8 + 1; ++row)
|
|
||||||
ss << board[row] << '\n';
|
|
||||||
ss << '\n';
|
|
||||||
|
|
||||||
auto t = networks.big.trace_evaluate(pos, &caches.big);
|
|
||||||
|
|
||||||
ss << " NNUE network contributions "
|
|
||||||
<< (pos.side_to_move() == WHITE ? "(White to move)" : "(Black to move)") << std::endl
|
|
||||||
<< "+------------+------------+------------+------------+\n"
|
|
||||||
<< "| Bucket | Material | Positional | Total |\n"
|
|
||||||
<< "| | (PSQT) | (Layers) | |\n"
|
|
||||||
<< "+------------+------------+------------+------------+\n";
|
|
||||||
|
|
||||||
for (std::size_t bucket = 0; bucket < LayerStacks; ++bucket)
|
|
||||||
{
|
|
||||||
ss << "| " << bucket << " " //
|
|
||||||
<< " | ";
|
|
||||||
format_cp_aligned_dot(t.psqt[bucket], ss, pos);
|
|
||||||
ss << " " //
|
|
||||||
<< " | ";
|
|
||||||
format_cp_aligned_dot(t.positional[bucket], ss, pos);
|
|
||||||
ss << " " //
|
|
||||||
<< " | ";
|
|
||||||
format_cp_aligned_dot(t.psqt[bucket] + t.positional[bucket], ss, pos);
|
|
||||||
ss << " " //
|
|
||||||
<< " |";
|
|
||||||
if (bucket == t.correctBucket)
|
|
||||||
ss << " <-- this bucket is used";
|
|
||||||
ss << '\n';
|
|
||||||
}
|
|
||||||
|
|
||||||
ss << "+------------+------------+------------+------------+\n";
|
|
||||||
|
|
||||||
return ss.str();
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
} // namespace Stockfish::Eval::NNUE
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef NNUE_MISC_H_INCLUDED
|
|
||||||
#define NNUE_MISC_H_INCLUDED
|
|
||||||
|
|
||||||
#include <cstddef>
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
#include "../types.h"
|
|
||||||
#include "nnue_architecture.h"
|
|
||||||
|
|
||||||
namespace Stockfish {
|
|
||||||
|
|
||||||
class Position;
|
|
||||||
|
|
||||||
namespace Eval::NNUE {
|
|
||||||
|
|
||||||
struct EvalFile {
|
|
||||||
// Default net name, will use one of the EvalFileDefaultName* macros defined
|
|
||||||
// in evaluate.h
|
|
||||||
std::string defaultName;
|
|
||||||
// Selected net name, either via uci option or default
|
|
||||||
std::string current;
|
|
||||||
// Net description extracted from the net file
|
|
||||||
std::string netDescription;
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
struct NnueEvalTrace {
|
|
||||||
static_assert(LayerStacks == PSQTBuckets);
|
|
||||||
|
|
||||||
Value psqt[LayerStacks];
|
|
||||||
Value positional[LayerStacks];
|
|
||||||
std::size_t correctBucket;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct Networks;
|
|
||||||
struct AccumulatorCaches;
|
|
||||||
|
|
||||||
std::string trace(Position& pos, const Networks& networks, AccumulatorCaches& caches);
|
|
||||||
void hint_common_parent_position(const Position& pos,
|
|
||||||
const Networks& networks,
|
|
||||||
AccumulatorCaches& caches);
|
|
||||||
|
|
||||||
} // namespace Stockfish::Eval::NNUE
|
|
||||||
} // namespace Stockfish
|
|
||||||
|
|
||||||
#endif // #ifndef NNUE_MISC_H_INCLUDED
|
|
||||||
-1345
File diff suppressed because it is too large
Load Diff
+368
@@ -0,0 +1,368 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include <cassert>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "bitcount.h"
|
||||||
|
#include "pawns.h"
|
||||||
|
#include "position.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Local definitions
|
||||||
|
////
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
/// Constants and variables
|
||||||
|
|
||||||
|
#define S(mg, eg) make_score(mg, eg)
|
||||||
|
|
||||||
|
// Doubled pawn penalty by file
|
||||||
|
const Score DoubledPawnPenalty[8] = {
|
||||||
|
S(13, 43), S(20, 48), S(23, 48), S(23, 48),
|
||||||
|
S(23, 48), S(23, 48), S(20, 48), S(13, 43)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Isolated pawn penalty by file
|
||||||
|
const Score IsolatedPawnPenalty[8] = {
|
||||||
|
S(25, 30), S(36, 35), S(40, 35), S(40, 35),
|
||||||
|
S(40, 35), S(40, 35), S(36, 35), S(25, 30)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Backward pawn penalty by file
|
||||||
|
const Score BackwardPawnPenalty[8] = {
|
||||||
|
S(20, 28), S(29, 31), S(33, 31), S(33, 31),
|
||||||
|
S(33, 31), S(33, 31), S(29, 31), S(20, 28)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Pawn chain membership bonus by file
|
||||||
|
const Score ChainBonus[8] = {
|
||||||
|
S(11,-1), S(13,-1), S(13,-1), S(14,-1),
|
||||||
|
S(14,-1), S(13,-1), S(13,-1), S(11,-1)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Candidate passed pawn bonus by rank
|
||||||
|
const Score CandidateBonus[8] = {
|
||||||
|
S( 0, 0), S( 6, 13), S(6,13), S(14,29),
|
||||||
|
S(34,68), S(83,166), S(0, 0), S( 0, 0)
|
||||||
|
};
|
||||||
|
|
||||||
|
// Pawn storm tables for positions with opposite castling
|
||||||
|
const int QStormTable[64] = {
|
||||||
|
0, 0, 0, 0, 0, 0, 0, 0,
|
||||||
|
-22,-22,-22,-14,-6, 0, 0, 0,
|
||||||
|
-6,-10,-10,-10,-6, 0, 0, 0,
|
||||||
|
4, 12, 16, 12, 4, 0, 0, 0,
|
||||||
|
16, 23, 23, 16, 0, 0, 0, 0,
|
||||||
|
23, 31, 31, 23, 0, 0, 0, 0,
|
||||||
|
23, 31, 31, 23, 0, 0, 0, 0,
|
||||||
|
0, 0, 0, 0, 0, 0, 0, 0
|
||||||
|
};
|
||||||
|
|
||||||
|
const int KStormTable[64] = {
|
||||||
|
0, 0, 0, 0, 0, 0, 0, 0,
|
||||||
|
0, 0, 0,-10,-19,-28,-33,-33,
|
||||||
|
0, 0, 0,-10,-15,-19,-24,-24,
|
||||||
|
0, 0, 0, 0, 1, 1, 1, 1,
|
||||||
|
0, 0, 0, 0, 1, 10, 19, 19,
|
||||||
|
0, 0, 0, 0, 1, 19, 31, 27,
|
||||||
|
0, 0, 0, 0, 0, 22, 31, 22,
|
||||||
|
0, 0, 0, 0, 0, 0, 0, 0
|
||||||
|
};
|
||||||
|
|
||||||
|
// Pawn storm open file bonuses by file
|
||||||
|
const int16_t KStormOpenFileBonus[8] = { 31, 31, 18, 0, 0, 0, 0, 0 };
|
||||||
|
const int16_t QStormOpenFileBonus[8] = { 0, 0, 0, 0, 0, 26, 42, 26 };
|
||||||
|
|
||||||
|
// Pawn storm lever bonuses by file
|
||||||
|
const int StormLeverBonus[8] = { -8, -8, -13, 0, 0, -13, -8, -8 };
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
|
/// Constructor
|
||||||
|
|
||||||
|
PawnInfoTable::PawnInfoTable(unsigned numOfEntries) {
|
||||||
|
|
||||||
|
size = numOfEntries;
|
||||||
|
entries = new PawnInfo[size];
|
||||||
|
if (!entries)
|
||||||
|
{
|
||||||
|
std::cerr << "Failed to allocate " << (numOfEntries * sizeof(PawnInfo))
|
||||||
|
<< " bytes for pawn hash table." << std::endl;
|
||||||
|
Application::exit_with_failure();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Destructor
|
||||||
|
|
||||||
|
PawnInfoTable::~PawnInfoTable() {
|
||||||
|
delete [] entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// PawnInfo::clear() resets to zero the PawnInfo entry. Note that
|
||||||
|
/// kingSquares[] is initialized to SQ_NONE instead.
|
||||||
|
|
||||||
|
void PawnInfo::clear() {
|
||||||
|
|
||||||
|
memset(this, 0, sizeof(PawnInfo));
|
||||||
|
kingSquares[WHITE] = kingSquares[BLACK] = SQ_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// PawnInfoTable::get_pawn_info() takes a position object as input, computes
|
||||||
|
/// a PawnInfo object, and returns a pointer to it. The result is also
|
||||||
|
/// stored in a hash table, so we don't have to recompute everything when
|
||||||
|
/// the same pawn structure occurs again.
|
||||||
|
|
||||||
|
PawnInfo* PawnInfoTable::get_pawn_info(const Position& pos) {
|
||||||
|
|
||||||
|
assert(pos.is_ok());
|
||||||
|
|
||||||
|
Key key = pos.get_pawn_key();
|
||||||
|
int index = int(key & (size - 1));
|
||||||
|
PawnInfo* pi = entries + index;
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
|
||||||
|
// Clear the PawnInfo object, and set the key
|
||||||
|
pi->clear();
|
||||||
|
pi->key = key;
|
||||||
|
|
||||||
|
// Calculate pawn attacks
|
||||||
|
Bitboard whitePawns = pos.pieces(PAWN, WHITE);
|
||||||
|
Bitboard blackPawns = pos.pieces(PAWN, BLACK);
|
||||||
|
pi->pawnAttacks[WHITE] = ((whitePawns << 9) & ~FileABB) | ((whitePawns << 7) & ~FileHBB);
|
||||||
|
pi->pawnAttacks[BLACK] = ((blackPawns >> 7) & ~FileABB) | ((blackPawns >> 9) & ~FileHBB);
|
||||||
|
|
||||||
|
// Evaluate pawns for both colors
|
||||||
|
pi->value = evaluate_pawns<WHITE>(pos, whitePawns, blackPawns, pi)
|
||||||
|
- evaluate_pawns<BLACK>(pos, blackPawns, whitePawns, pi);
|
||||||
|
return pi;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// PawnInfoTable::evaluate_pawns() evaluates each pawn of the given color
|
||||||
|
|
||||||
|
template<Color Us>
|
||||||
|
Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
|
||||||
|
Bitboard theirPawns, PawnInfo* pi) {
|
||||||
|
Square s;
|
||||||
|
File f;
|
||||||
|
Rank r;
|
||||||
|
bool passed, isolated, doubled, chain, backward, candidate;
|
||||||
|
int bonus;
|
||||||
|
Score value = make_score(0, 0);
|
||||||
|
const Square* ptr = pos.piece_list_begin(Us, PAWN);
|
||||||
|
|
||||||
|
// Initialize pawn storm scores by giving bonuses for open files
|
||||||
|
for (f = FILE_A; f <= FILE_H; f++)
|
||||||
|
if (!(ourPawns & file_bb(f)))
|
||||||
|
{
|
||||||
|
pi->ksStormValue[Us] += KStormOpenFileBonus[f];
|
||||||
|
pi->qsStormValue[Us] += QStormOpenFileBonus[f];
|
||||||
|
pi->halfOpenFiles[Us] |= (1 << f);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Loop through all pawns of the current color and score each pawn
|
||||||
|
while ((s = *ptr++) != SQ_NONE)
|
||||||
|
{
|
||||||
|
f = square_file(s);
|
||||||
|
r = square_rank(s);
|
||||||
|
|
||||||
|
assert(pos.piece_on(s) == piece_of_color_and_type(Us, PAWN));
|
||||||
|
|
||||||
|
// Passed, isolated or doubled pawn?
|
||||||
|
passed = Position::pawn_is_passed(theirPawns, Us, s);
|
||||||
|
isolated = Position::pawn_is_isolated(ourPawns, s);
|
||||||
|
doubled = Position::pawn_is_doubled(ourPawns, Us, s);
|
||||||
|
|
||||||
|
// We calculate kingside and queenside pawn storm
|
||||||
|
// scores for both colors. These are used when evaluating
|
||||||
|
// middle game positions with opposite side castling.
|
||||||
|
//
|
||||||
|
// Each pawn is given a base score given by a piece square table
|
||||||
|
// (KStormTable[] or QStormTable[]). Pawns which seem to have good
|
||||||
|
// chances of creating an open file by exchanging itself against an
|
||||||
|
// enemy pawn on an adjacent file gets an additional bonus.
|
||||||
|
|
||||||
|
// Kingside pawn storms
|
||||||
|
bonus = KStormTable[relative_square(Us, s)];
|
||||||
|
if (f >= FILE_F)
|
||||||
|
{
|
||||||
|
Bitboard b = outpost_mask(Us, s) & theirPawns & (FileFBB | FileGBB | FileHBB);
|
||||||
|
while (b)
|
||||||
|
{
|
||||||
|
Square s2 = pop_1st_bit(&b);
|
||||||
|
if (!(theirPawns & neighboring_files_bb(s2) & rank_bb(s2)))
|
||||||
|
{
|
||||||
|
// The enemy pawn has no pawn beside itself, which makes it
|
||||||
|
// particularly vulnerable. Big bonus, especially against a
|
||||||
|
// weakness on the rook file.
|
||||||
|
if (square_file(s2) == FILE_H)
|
||||||
|
bonus += 4*StormLeverBonus[f] - 8*square_distance(s, s2);
|
||||||
|
else
|
||||||
|
bonus += 2*StormLeverBonus[f] - 4*square_distance(s, s2);
|
||||||
|
} else
|
||||||
|
// There is at least one enemy pawn beside the enemy pawn we look
|
||||||
|
// at, which means that the pawn has somewhat better chances of
|
||||||
|
// defending itself by advancing. Smaller bonus.
|
||||||
|
bonus += StormLeverBonus[f] - 2*square_distance(s, s2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pi->ksStormValue[Us] += bonus;
|
||||||
|
|
||||||
|
// Queenside pawn storms
|
||||||
|
bonus = QStormTable[relative_square(Us, s)];
|
||||||
|
if (f <= FILE_C)
|
||||||
|
{
|
||||||
|
Bitboard b = outpost_mask(Us, s) & theirPawns & (FileABB | FileBBB | FileCBB);
|
||||||
|
while (b)
|
||||||
|
{
|
||||||
|
Square s2 = pop_1st_bit(&b);
|
||||||
|
if (!(theirPawns & neighboring_files_bb(s2) & rank_bb(s2)))
|
||||||
|
{
|
||||||
|
// The enemy pawn has no pawn beside itself, which makes it
|
||||||
|
// particularly vulnerable. Big bonus, especially against a
|
||||||
|
// weakness on the rook file.
|
||||||
|
if (square_file(s2) == FILE_A)
|
||||||
|
bonus += 4*StormLeverBonus[f] - 16*square_distance(s, s2);
|
||||||
|
else
|
||||||
|
bonus += 2*StormLeverBonus[f] - 8*square_distance(s, s2);
|
||||||
|
} else
|
||||||
|
// There is at least one enemy pawn beside the enemy pawn we look
|
||||||
|
// at, which means that the pawn has somewhat better chances of
|
||||||
|
// defending itself by advancing. Smaller bonus.
|
||||||
|
bonus += StormLeverBonus[f] - 4*square_distance(s, s2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pi->qsStormValue[Us] += bonus;
|
||||||
|
|
||||||
|
// Member of a pawn chain (but not the backward one)? We could speed up
|
||||||
|
// the test a little by introducing an array of masks indexed by color
|
||||||
|
// and square for doing the test, but because everything is hashed,
|
||||||
|
// it probably won't make any noticable difference.
|
||||||
|
chain = ourPawns
|
||||||
|
& neighboring_files_bb(f)
|
||||||
|
& (rank_bb(r) | rank_bb(r - (Us == WHITE ? 1 : -1)));
|
||||||
|
|
||||||
|
// Test for backward pawn
|
||||||
|
//
|
||||||
|
// If the pawn is passed, isolated, or member of a pawn chain
|
||||||
|
// it cannot be backward. If can capture an enemy pawn or if
|
||||||
|
// there are friendly pawns behind on neighboring files it cannot
|
||||||
|
// be backward either.
|
||||||
|
if ( (passed | isolated | chain)
|
||||||
|
|| (ourPawns & behind_bb(Us, r) & neighboring_files_bb(f))
|
||||||
|
|| (pos.attacks_from<PAWN>(s, Us) & theirPawns))
|
||||||
|
backward = false;
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// We now know that there are no friendly pawns beside or behind this
|
||||||
|
// pawn on neighboring files. We now check whether the pawn is
|
||||||
|
// backward by looking in the forward direction on the neighboring
|
||||||
|
// files, and seeing whether we meet a friendly or an enemy pawn first.
|
||||||
|
Bitboard b = pos.attacks_from<PAWN>(s, Us);
|
||||||
|
|
||||||
|
// Note that we are sure to find something because pawn is not passed
|
||||||
|
// nor isolated, so loop is potentially infinite, but it isn't.
|
||||||
|
while (!(b & (ourPawns | theirPawns)))
|
||||||
|
Us == WHITE ? b <<= 8 : b >>= 8;
|
||||||
|
|
||||||
|
// The friendly pawn needs to be at least two ranks closer than the enemy
|
||||||
|
// pawn in order to help the potentially backward pawn advance.
|
||||||
|
backward = (b | (Us == WHITE ? b << 8 : b >> 8)) & theirPawns;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test for candidate passed pawn
|
||||||
|
candidate = !passed
|
||||||
|
&& !(theirPawns & file_bb(f))
|
||||||
|
&& ( count_1s_max_15(neighboring_files_bb(f) & (behind_bb(Us, r) | rank_bb(r)) & ourPawns)
|
||||||
|
- count_1s_max_15(neighboring_files_bb(f) & in_front_bb(Us, r) & theirPawns)
|
||||||
|
>= 0);
|
||||||
|
|
||||||
|
// In order to prevent doubled passed pawns from receiving a too big
|
||||||
|
// bonus, only the frontmost passed pawn on each file is considered as
|
||||||
|
// a true passed pawn.
|
||||||
|
if (passed && (ourPawns & squares_in_front_of(Us, s)))
|
||||||
|
passed = false;
|
||||||
|
|
||||||
|
// Score this pawn
|
||||||
|
if (passed)
|
||||||
|
set_bit(&(pi->passedPawns), s);
|
||||||
|
|
||||||
|
if (isolated)
|
||||||
|
{
|
||||||
|
value -= IsolatedPawnPenalty[f];
|
||||||
|
if (!(theirPawns & file_bb(f)))
|
||||||
|
value -= IsolatedPawnPenalty[f] / 2;
|
||||||
|
}
|
||||||
|
if (doubled)
|
||||||
|
value -= DoubledPawnPenalty[f];
|
||||||
|
|
||||||
|
if (backward)
|
||||||
|
{
|
||||||
|
value -= BackwardPawnPenalty[f];
|
||||||
|
if (!(theirPawns & file_bb(f)))
|
||||||
|
value -= BackwardPawnPenalty[f] / 2;
|
||||||
|
}
|
||||||
|
if (chain)
|
||||||
|
value += ChainBonus[f];
|
||||||
|
|
||||||
|
if (candidate)
|
||||||
|
value += CandidateBonus[relative_rank(Us, s)];
|
||||||
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// PawnInfo::updateShelter calculates and caches king shelter. It is called
|
||||||
|
/// only when king square changes, about 20% of total get_king_shelter() calls.
|
||||||
|
int PawnInfo::updateShelter(const Position& pos, Color c, Square ksq) {
|
||||||
|
|
||||||
|
unsigned shelter = 0;
|
||||||
|
Bitboard pawns = pos.pieces(PAWN, c) & this_and_neighboring_files_bb(ksq);
|
||||||
|
unsigned r = ksq & (7 << 3);
|
||||||
|
for (int i = 1, k = (c ? -8 : 8); i < 4; i++)
|
||||||
|
{
|
||||||
|
r += k;
|
||||||
|
shelter += BitCount8Bit[(pawns >> r) & 0xFF] * (128 >> i);
|
||||||
|
}
|
||||||
|
kingSquares[c] = ksq;
|
||||||
|
kingShelters[c] = shelter;
|
||||||
|
return shelter;
|
||||||
|
}
|
||||||
+135
@@ -0,0 +1,135 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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(PAWNS_H_INCLUDED)
|
||||||
|
#define PAWNS_H_INCLUDED
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include "bitboard.h"
|
||||||
|
#include "value.h"
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Types
|
||||||
|
////
|
||||||
|
|
||||||
|
/// PawnInfo is a class which contains various information about a pawn
|
||||||
|
/// structure. Currently, it only includes a middle game and an end game
|
||||||
|
/// pawn structure evaluation, and a bitboard of passed pawns. We may want
|
||||||
|
/// to add further information in the future. A lookup to the pawn hash table
|
||||||
|
/// (performed by calling the get_pawn_info method in a PawnInfoTable object)
|
||||||
|
/// returns a pointer to a PawnInfo object.
|
||||||
|
class Position;
|
||||||
|
|
||||||
|
class PawnInfo {
|
||||||
|
|
||||||
|
friend class PawnInfoTable;
|
||||||
|
|
||||||
|
public:
|
||||||
|
PawnInfo() { clear(); }
|
||||||
|
|
||||||
|
Score pawns_value() const;
|
||||||
|
Value kingside_storm_value(Color c) const;
|
||||||
|
Value queenside_storm_value(Color c) const;
|
||||||
|
Bitboard pawn_attacks(Color c) const;
|
||||||
|
Bitboard passed_pawns() const;
|
||||||
|
int file_is_half_open(Color c, File f) const;
|
||||||
|
int has_open_file_to_left(Color c, File f) const;
|
||||||
|
int has_open_file_to_right(Color c, File f) const;
|
||||||
|
int get_king_shelter(const Position& pos, Color c, Square ksq);
|
||||||
|
|
||||||
|
private:
|
||||||
|
void clear();
|
||||||
|
int updateShelter(const Position& pos, Color c, Square ksq);
|
||||||
|
|
||||||
|
Key key;
|
||||||
|
Bitboard passedPawns;
|
||||||
|
Bitboard pawnAttacks[2];
|
||||||
|
Score value;
|
||||||
|
int16_t ksStormValue[2], qsStormValue[2];
|
||||||
|
uint8_t halfOpenFiles[2];
|
||||||
|
Square kingSquares[2];
|
||||||
|
uint8_t kingShelters[2];
|
||||||
|
};
|
||||||
|
|
||||||
|
/// The PawnInfoTable class represents a pawn hash table. It is basically
|
||||||
|
/// just an array of PawnInfo objects and a few methods for accessing these
|
||||||
|
/// objects. The most important method is get_pawn_info, which looks up a
|
||||||
|
/// position in the table and returns a pointer to a PawnInfo object.
|
||||||
|
|
||||||
|
class PawnInfoTable {
|
||||||
|
|
||||||
|
public:
|
||||||
|
PawnInfoTable(unsigned numOfEntries);
|
||||||
|
~PawnInfoTable();
|
||||||
|
PawnInfo* get_pawn_info(const Position& pos);
|
||||||
|
|
||||||
|
private:
|
||||||
|
template<Color Us>
|
||||||
|
Score evaluate_pawns(const Position& pos, Bitboard ourPawns, Bitboard theirPawns, PawnInfo* pi);
|
||||||
|
|
||||||
|
unsigned size;
|
||||||
|
PawnInfo* entries;
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Inline functions
|
||||||
|
////
|
||||||
|
|
||||||
|
inline Score PawnInfo::pawns_value() const {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Bitboard PawnInfo::passed_pawns() const {
|
||||||
|
return passedPawns;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Bitboard PawnInfo::pawn_attacks(Color c) const {
|
||||||
|
return pawnAttacks[c];
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Value PawnInfo::kingside_storm_value(Color c) const {
|
||||||
|
return Value(ksStormValue[c]);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Value PawnInfo::queenside_storm_value(Color c) const {
|
||||||
|
return Value(qsStormValue[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);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int PawnInfo::get_king_shelter(const Position& pos, Color c, Square ksq) {
|
||||||
|
return (kingSquares[c] == ksq ? kingShelters[c] : updateShelter(pos, c, ksq));
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif // !defined(PAWNS_H_INCLUDED)
|
||||||
-68
@@ -1,68 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef PERFT_H_INCLUDED
|
|
||||||
#define PERFT_H_INCLUDED
|
|
||||||
|
|
||||||
#include <cstdint>
|
|
||||||
|
|
||||||
#include "movegen.h"
|
|
||||||
#include "position.h"
|
|
||||||
#include "types.h"
|
|
||||||
#include "uci.h"
|
|
||||||
|
|
||||||
namespace Stockfish::Benchmark {
|
|
||||||
|
|
||||||
// Utility to verify move generation. All the leaf nodes up
|
|
||||||
// to the given depth are generated and counted, and the sum is returned.
|
|
||||||
template<bool Root>
|
|
||||||
uint64_t perft(Position& pos, Depth depth) {
|
|
||||||
|
|
||||||
StateInfo st;
|
|
||||||
ASSERT_ALIGNED(&st, Eval::NNUE::CacheLineSize);
|
|
||||||
|
|
||||||
uint64_t cnt, nodes = 0;
|
|
||||||
const bool leaf = (depth == 2);
|
|
||||||
|
|
||||||
for (const auto& m : MoveList<LEGAL>(pos))
|
|
||||||
{
|
|
||||||
if (Root && depth <= 1)
|
|
||||||
cnt = 1, nodes++;
|
|
||||||
else
|
|
||||||
{
|
|
||||||
pos.do_move(m, st);
|
|
||||||
cnt = leaf ? MoveList<LEGAL>(pos).size() : perft<false>(pos, depth - 1);
|
|
||||||
nodes += cnt;
|
|
||||||
pos.undo_move(m);
|
|
||||||
}
|
|
||||||
if (Root)
|
|
||||||
sync_cout << UCIEngine::move(m, pos.is_chess960()) << ": " << cnt << sync_endl;
|
|
||||||
}
|
|
||||||
return nodes;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline uint64_t perft(const std::string& fen, Depth depth, bool isChess960) {
|
|
||||||
StateListPtr states(new std::deque<StateInfo>(1));
|
|
||||||
Position p;
|
|
||||||
p.set(fen, isChess960, &states->back());
|
|
||||||
|
|
||||||
return perft<true>(p, depth);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif // PERFT_H_INCLUDED
|
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include "piece.h"
|
||||||
|
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
|
/// Translating piece types to/from English piece letters
|
||||||
|
|
||||||
|
static const string PieceChars(" pnbrqk PNBRQK");
|
||||||
|
|
||||||
|
char piece_type_to_char(PieceType pt, bool upcase) {
|
||||||
|
|
||||||
|
return PieceChars[pt + upcase * 7];
|
||||||
|
}
|
||||||
|
|
||||||
|
PieceType piece_type_from_char(char c) {
|
||||||
|
|
||||||
|
size_t idx = PieceChars.find(c);
|
||||||
|
|
||||||
|
return idx != string::npos ? PieceType(idx % 7) : NO_PIECE_TYPE;
|
||||||
|
}
|
||||||
+107
@@ -0,0 +1,107 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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(PIECE_H_INCLUDED)
|
||||||
|
#define PIECE_H_INCLUDED
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include "color.h"
|
||||||
|
#include "square.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Types
|
||||||
|
////
|
||||||
|
|
||||||
|
enum PieceType {
|
||||||
|
NO_PIECE_TYPE = 0,
|
||||||
|
PAWN = 1, KNIGHT = 2, BISHOP = 3, ROOK = 4, QUEEN = 5, KING = 6
|
||||||
|
};
|
||||||
|
|
||||||
|
enum Piece {
|
||||||
|
NO_PIECE = 0, WP = 1, WN = 2, WB = 3, WR = 4, WQ = 5, WK = 6,
|
||||||
|
BP = 9, BN = 10, BB = 11, BR = 12, BQ = 13, BK = 14,
|
||||||
|
EMPTY = 16, OUTSIDE = 17
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Constants
|
||||||
|
////
|
||||||
|
|
||||||
|
const int SlidingArray[18] = {
|
||||||
|
0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Inline functions
|
||||||
|
////
|
||||||
|
|
||||||
|
inline Piece operator+ (Piece p, int i) { return Piece(int(p) + i); }
|
||||||
|
inline void operator++ (Piece &p, int) { p = Piece(int(p) + 1); }
|
||||||
|
inline Piece operator- (Piece p, int i) { return Piece(int(p) - i); }
|
||||||
|
inline void operator-- (Piece &p, int) { p = Piece(int(p) - 1); }
|
||||||
|
inline PieceType operator+ (PieceType p, int i) {return PieceType(int(p) + i);}
|
||||||
|
inline void operator++ (PieceType &p, int) { p = PieceType(int(p) + 1); }
|
||||||
|
inline PieceType operator- (PieceType p, int i) {return PieceType(int(p) - i);}
|
||||||
|
inline void operator-- (PieceType &p, int) { p = PieceType(int(p) - 1); }
|
||||||
|
|
||||||
|
inline PieceType type_of_piece(Piece p) {
|
||||||
|
return PieceType(int(p) & 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Color color_of_piece(Piece p) {
|
||||||
|
return Color(int(p) >> 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Piece piece_of_color_and_type(Color c, PieceType pt) {
|
||||||
|
return Piece((int(c) << 3) | int(pt));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int piece_is_slider(Piece p) {
|
||||||
|
return SlidingArray[int(p)];
|
||||||
|
}
|
||||||
|
|
||||||
|
inline SquareDelta pawn_push(Color c) {
|
||||||
|
return (c == WHITE ? DELTA_N : DELTA_S);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool piece_type_is_ok(PieceType pc) {
|
||||||
|
return pc >= PAWN && pc <= KING;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool piece_is_ok(Piece pc) {
|
||||||
|
return piece_type_is_ok(type_of_piece(pc)) && color_is_ok(color_of_piece(pc));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Prototypes
|
||||||
|
////
|
||||||
|
|
||||||
|
extern char piece_type_to_char(PieceType pt, bool upcase = false);
|
||||||
|
extern PieceType piece_type_from_char(char c);
|
||||||
|
|
||||||
|
|
||||||
|
#endif // !defined(PIECE_H_INCLUDED)
|
||||||
+1798
-1067
File diff suppressed because it is too large
Load Diff
+479
-273
@@ -1,6 +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-2024 The Stockfish developers (see AUTHORS file)
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
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
|
||||||
@@ -16,349 +17,554 @@
|
|||||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#ifndef POSITION_H_INCLUDED
|
|
||||||
|
#if !defined(POSITION_H_INCLUDED)
|
||||||
#define POSITION_H_INCLUDED
|
#define POSITION_H_INCLUDED
|
||||||
|
|
||||||
#include <cassert>
|
// Disable some silly and noisy warning from MSVC compiler
|
||||||
#include <deque>
|
#if defined(_MSC_VER)
|
||||||
#include <iosfwd>
|
|
||||||
#include <memory>
|
// Forcing value to bool 'true' or 'false' (performance warning)
|
||||||
#include <string>
|
#pragma warning(disable: 4800)
|
||||||
|
|
||||||
|
// Conditional expression is constant
|
||||||
|
#pragma warning(disable: 4127)
|
||||||
|
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
#include "bitboard.h"
|
#include "bitboard.h"
|
||||||
#include "nnue/nnue_accumulator.h"
|
#include "color.h"
|
||||||
#include "nnue/nnue_architecture.h"
|
#include "direction.h"
|
||||||
#include "types.h"
|
#include "move.h"
|
||||||
|
#include "piece.h"
|
||||||
|
#include "square.h"
|
||||||
|
#include "value.h"
|
||||||
|
|
||||||
namespace Stockfish {
|
|
||||||
|
|
||||||
class TranspositionTable;
|
////
|
||||||
|
//// Constants
|
||||||
|
////
|
||||||
|
|
||||||
// StateInfo struct stores information needed to restore a Position object to
|
/// FEN string for the initial position
|
||||||
// its previous state when we retract a move. Whenever a move is made on the
|
const std::string StartPosition = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
|
||||||
// board (by calling Position::do_move), a StateInfo object must be passed.
|
|
||||||
|
/// Maximum number of plies per game (220 should be enough, because the
|
||||||
|
/// maximum search depth is 100, and during position setup we reset the
|
||||||
|
/// move counter for every non-reversible move).
|
||||||
|
const int MaxGameLength = 220;
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Types
|
||||||
|
////
|
||||||
|
|
||||||
|
/// struct checkInfo is initialized at c'tor time and keeps
|
||||||
|
/// info used to detect if a move gives check.
|
||||||
|
|
||||||
|
struct CheckInfo {
|
||||||
|
|
||||||
|
CheckInfo(const Position&);
|
||||||
|
|
||||||
|
Square ksq;
|
||||||
|
Bitboard dcCandidates;
|
||||||
|
Bitboard checkSq[8];
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Castle rights, encoded as bit fields
|
||||||
|
|
||||||
|
enum CastleRights {
|
||||||
|
NO_CASTLES = 0,
|
||||||
|
WHITE_OO = 1,
|
||||||
|
BLACK_OO = 2,
|
||||||
|
WHITE_OOO = 4,
|
||||||
|
BLACK_OOO = 8,
|
||||||
|
ALL_CASTLES = 15
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Game phase
|
||||||
|
enum Phase {
|
||||||
|
PHASE_ENDGAME = 0,
|
||||||
|
PHASE_MIDGAME = 128
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
/// The StateInfo struct stores information we need to restore a Position
|
||||||
|
/// 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
|
||||||
|
/// must be passed as a parameter.
|
||||||
|
|
||||||
struct StateInfo {
|
struct StateInfo {
|
||||||
|
Key pawnKey, materialKey;
|
||||||
|
int castleRights, rule50, pliesFromNull;
|
||||||
|
Square epSquare;
|
||||||
|
Score value;
|
||||||
|
Value npMaterial[2];
|
||||||
|
|
||||||
// Copied when making a move
|
Key key;
|
||||||
Key materialKey;
|
PieceType capture;
|
||||||
Key pawnKey;
|
Bitboard checkersBB;
|
||||||
Value nonPawnMaterial[COLOR_NB];
|
StateInfo* previous;
|
||||||
int castlingRights;
|
|
||||||
int rule50;
|
|
||||||
int pliesFromNull;
|
|
||||||
Square epSquare;
|
|
||||||
|
|
||||||
// Not copied when making a move (will be recomputed anyhow)
|
|
||||||
Key key;
|
|
||||||
Bitboard checkersBB;
|
|
||||||
StateInfo* previous;
|
|
||||||
Bitboard blockersForKing[COLOR_NB];
|
|
||||||
Bitboard pinners[COLOR_NB];
|
|
||||||
Bitboard checkSquares[PIECE_TYPE_NB];
|
|
||||||
Piece capturedPiece;
|
|
||||||
int repetition;
|
|
||||||
|
|
||||||
// Used by NNUE
|
|
||||||
Eval::NNUE::Accumulator<Eval::NNUE::TransformedFeatureDimensionsBig> accumulatorBig;
|
|
||||||
Eval::NNUE::Accumulator<Eval::NNUE::TransformedFeatureDimensionsSmall> accumulatorSmall;
|
|
||||||
DirtyPiece dirtyPiece;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
// A list to keep track of the position states along the setup moves (from the
|
/// The position data structure. A position consists of the following data:
|
||||||
// start position to the position just before the search starts). Needed by
|
///
|
||||||
// 'draw by repetition' detection. Use a std::deque because pointers to
|
/// * For each piece type, a bitboard representing the squares occupied
|
||||||
// elements are not invalidated upon list resizing.
|
/// by pieces of that type.
|
||||||
using StateListPtr = std::unique_ptr<std::deque<StateInfo>>;
|
/// * For each color, a bitboard representing the squares occupied by
|
||||||
|
/// pieces of that color.
|
||||||
|
/// * A bitboard of all occupied squares.
|
||||||
|
/// * A bitboard of all checking pieces.
|
||||||
|
/// * A 64-entry array of pieces, indexed by the squares of the board.
|
||||||
|
/// * The current side to move.
|
||||||
|
/// * Information about the castling rights for both sides.
|
||||||
|
/// * The initial files of the kings and both pairs of rooks. This is
|
||||||
|
/// used to implement the Chess960 castling rules.
|
||||||
|
/// * The en passant square (which is SQ_NONE if no en passant capture is
|
||||||
|
/// possible).
|
||||||
|
/// * The squares of the kings for both sides.
|
||||||
|
/// * Hash keys for the position itself, the current pawn structure, and
|
||||||
|
/// the current material situation.
|
||||||
|
/// * Hash keys for all previous positions in the game for detecting
|
||||||
|
/// repetition draws.
|
||||||
|
/// * A counter for detecting 50 move rule draws.
|
||||||
|
|
||||||
|
|
||||||
// Position class stores information regarding the board representation as
|
|
||||||
// pieces, side to move, hash keys, castling info, etc. Important methods are
|
|
||||||
// do_move() and undo_move(), used by the search to update node info when
|
|
||||||
// traversing the search tree.
|
|
||||||
class Position {
|
class Position {
|
||||||
public:
|
|
||||||
static void init();
|
|
||||||
|
|
||||||
Position() = default;
|
friend class MaterialInfo;
|
||||||
Position(const Position&) = delete;
|
friend class EndgameFunctions;
|
||||||
Position& operator=(const Position&) = delete;
|
|
||||||
|
|
||||||
// FEN string input/output
|
public:
|
||||||
Position& set(const std::string& fenStr, bool isChess960, StateInfo* si);
|
enum GamePhase {
|
||||||
Position& set(const std::string& code, Color c, StateInfo* si);
|
MidGame,
|
||||||
std::string fen() const;
|
EndGame
|
||||||
|
};
|
||||||
|
|
||||||
// Position representation
|
// Constructors
|
||||||
Bitboard pieces(PieceType pt = ALL_PIECES) const;
|
Position() {}
|
||||||
template<typename... PieceTypes>
|
Position(const Position& pos);
|
||||||
Bitboard pieces(PieceType pt, PieceTypes... pts) const;
|
Position(const std::string& fen);
|
||||||
Bitboard pieces(Color c) const;
|
|
||||||
template<typename... PieceTypes>
|
|
||||||
Bitboard pieces(Color c, PieceTypes... pts) const;
|
|
||||||
Piece piece_on(Square s) const;
|
|
||||||
Square ep_square() const;
|
|
||||||
bool empty(Square s) const;
|
|
||||||
template<PieceType Pt>
|
|
||||||
int count(Color c) const;
|
|
||||||
template<PieceType Pt>
|
|
||||||
int count() const;
|
|
||||||
template<PieceType Pt>
|
|
||||||
Square square(Color c) const;
|
|
||||||
|
|
||||||
// Castling
|
// Text input/output
|
||||||
CastlingRights castling_rights(Color c) const;
|
void from_fen(const std::string& fen);
|
||||||
bool can_castle(CastlingRights cr) const;
|
const std::string to_fen() const;
|
||||||
bool castling_impeded(CastlingRights cr) const;
|
void print(Move m = MOVE_NONE) const;
|
||||||
Square castling_rook_square(CastlingRights cr) const;
|
|
||||||
|
|
||||||
// Checking
|
// Copying
|
||||||
Bitboard checkers() const;
|
void copy(const Position& pos);
|
||||||
Bitboard blockers_for_king(Color c) const;
|
void flipped_copy(const Position& pos);
|
||||||
Bitboard check_squares(PieceType pt) const;
|
|
||||||
Bitboard pinners(Color c) const;
|
|
||||||
|
|
||||||
// Attacks to/from a given square
|
// The piece on a given square
|
||||||
Bitboard attackers_to(Square s) const;
|
Piece piece_on(Square s) const;
|
||||||
Bitboard attackers_to(Square s, Bitboard occupied) const;
|
PieceType type_of_piece_on(Square s) const;
|
||||||
void update_slider_blockers(Color c) const;
|
Color color_of_piece_on(Square s) const;
|
||||||
template<PieceType Pt>
|
bool square_is_empty(Square s) const;
|
||||||
Bitboard attacks_by(Color c) const;
|
bool square_is_occupied(Square s) const;
|
||||||
|
Value midgame_value_of_piece_on(Square s) const;
|
||||||
|
Value endgame_value_of_piece_on(Square s) const;
|
||||||
|
|
||||||
// Properties of moves
|
// Side to move
|
||||||
bool legal(Move m) const;
|
Color side_to_move() const;
|
||||||
bool pseudo_legal(const Move m) const;
|
|
||||||
bool capture(Move m) const;
|
|
||||||
bool capture_stage(Move m) const;
|
|
||||||
bool gives_check(Move m) const;
|
|
||||||
Piece moved_piece(Move m) const;
|
|
||||||
Piece captured_piece() const;
|
|
||||||
|
|
||||||
// Doing and undoing moves
|
// Bitboard representation of the position
|
||||||
void do_move(Move m, StateInfo& newSt);
|
Bitboard empty_squares() const;
|
||||||
void do_move(Move m, StateInfo& newSt, bool givesCheck);
|
Bitboard occupied_squares() const;
|
||||||
void undo_move(Move m);
|
Bitboard pieces_of_color(Color c) const;
|
||||||
void do_null_move(StateInfo& newSt, TranspositionTable& tt);
|
Bitboard pieces(PieceType pt) const;
|
||||||
void undo_null_move();
|
Bitboard pieces(PieceType pt, Color c) const;
|
||||||
|
Bitboard pieces(PieceType pt1, PieceType pt2) const;
|
||||||
|
Bitboard pieces(PieceType pt1, PieceType pt2, Color c) const;
|
||||||
|
|
||||||
// Static Exchange Evaluation
|
// Number of pieces of each color and type
|
||||||
bool see_ge(Move m, int threshold = 0) const;
|
int piece_count(Color c, PieceType pt) const;
|
||||||
|
|
||||||
// Accessing hash keys
|
// The en passant square
|
||||||
Key key() const;
|
Square ep_square() const;
|
||||||
Key key_after(Move m) const;
|
|
||||||
Key material_key() const;
|
|
||||||
Key pawn_key() const;
|
|
||||||
|
|
||||||
// Other properties of the position
|
// Current king position for each color
|
||||||
Color side_to_move() const;
|
Square king_square(Color c) const;
|
||||||
int game_ply() const;
|
|
||||||
bool is_chess960() const;
|
|
||||||
bool is_draw(int ply) const;
|
|
||||||
bool upcoming_repetition(int ply) const;
|
|
||||||
bool has_repeated() const;
|
|
||||||
int rule50_count() const;
|
|
||||||
Value non_pawn_material(Color c) const;
|
|
||||||
Value non_pawn_material() const;
|
|
||||||
|
|
||||||
// Position consistency check, for debugging
|
// Castling rights
|
||||||
bool pos_is_ok() const;
|
bool can_castle_kingside(Color c) const;
|
||||||
void flip();
|
bool can_castle_queenside(Color c) const;
|
||||||
|
bool can_castle(Color c) const;
|
||||||
|
Square initial_kr_square(Color c) const;
|
||||||
|
Square initial_qr_square(Color c) const;
|
||||||
|
|
||||||
// Used by NNUE
|
// Bitboards for pinned pieces and discovered check candidates
|
||||||
StateInfo* state() const;
|
Bitboard discovered_check_candidates(Color c) const;
|
||||||
|
Bitboard pinned_pieces(Color c) const;
|
||||||
|
|
||||||
void put_piece(Piece pc, Square s);
|
// Checking pieces and under check information
|
||||||
void remove_piece(Square s);
|
Bitboard checkers() const;
|
||||||
|
bool is_check() const;
|
||||||
|
|
||||||
private:
|
// Piece lists
|
||||||
// Initialization helpers (used while setting up a position)
|
Square piece_list(Color c, PieceType pt, int index) const;
|
||||||
void set_castling_right(Color c, Square rfrom);
|
const Square* piece_list_begin(Color c, PieceType pt) const;
|
||||||
void set_state() const;
|
|
||||||
void set_check_info() const;
|
|
||||||
|
|
||||||
// Other helpers
|
// Information about attacks to or from a given square
|
||||||
void move_piece(Square from, Square to);
|
Bitboard attackers_to(Square s) const;
|
||||||
template<bool Do>
|
Bitboard attacks_from(Piece p, Square s) const;
|
||||||
void do_castling(Color us, Square from, Square& to, Square& rfrom, Square& rto);
|
template<PieceType> Bitboard attacks_from(Square s) const;
|
||||||
template<bool AfterMove>
|
template<PieceType> Bitboard attacks_from(Square s, Color c) const;
|
||||||
Key adjust_key50(Key k) const;
|
|
||||||
|
|
||||||
// Data members
|
// Properties of moves
|
||||||
Piece board[SQUARE_NB];
|
bool pl_move_is_legal(Move m, Bitboard pinned) const;
|
||||||
Bitboard byTypeBB[PIECE_TYPE_NB];
|
bool pl_move_is_evasion(Move m, Bitboard pinned) const;
|
||||||
Bitboard byColorBB[COLOR_NB];
|
bool move_is_check(Move m) const;
|
||||||
int pieceCount[PIECE_NB];
|
bool move_is_check(Move m, const CheckInfo& ci) const;
|
||||||
int castlingRightsMask[SQUARE_NB];
|
bool move_is_capture(Move m) const;
|
||||||
Square castlingRookSquare[CASTLING_RIGHT_NB];
|
bool move_is_capture_or_promotion(Move m) const;
|
||||||
Bitboard castlingPath[CASTLING_RIGHT_NB];
|
bool move_is_passed_pawn_push(Move m) const;
|
||||||
StateInfo* st;
|
bool move_attacks_square(Move m, Square s) const;
|
||||||
int gamePly;
|
|
||||||
Color sideToMove;
|
// Information about pawns
|
||||||
bool chess960;
|
bool pawn_is_passed(Color c, Square s) const;
|
||||||
|
static bool pawn_is_passed(Bitboard theirPawns, Color c, Square s);
|
||||||
|
static bool pawn_is_isolated(Bitboard ourPawns, Square s);
|
||||||
|
static bool pawn_is_doubled(Bitboard ourPawns, Color c, Square s);
|
||||||
|
|
||||||
|
// Weak squares
|
||||||
|
bool square_is_weak(Square s, Color c) const;
|
||||||
|
|
||||||
|
// Doing and undoing moves
|
||||||
|
void saveState();
|
||||||
|
void do_move(Move m, StateInfo& st);
|
||||||
|
void do_move(Move m, StateInfo& st, const CheckInfo& ci, bool moveIsCheck);
|
||||||
|
void undo_move(Move m);
|
||||||
|
void do_null_move(StateInfo& st);
|
||||||
|
void undo_null_move();
|
||||||
|
|
||||||
|
// Static exchange evaluation
|
||||||
|
int see(Square from, Square to) const;
|
||||||
|
int see(Move m) const;
|
||||||
|
int see(Square to) const;
|
||||||
|
int see_sign(Move m) const;
|
||||||
|
|
||||||
|
// Accessing hash keys
|
||||||
|
Key get_key() const;
|
||||||
|
Key get_exclusion_key() const;
|
||||||
|
Key get_pawn_key() const;
|
||||||
|
Key get_material_key() const;
|
||||||
|
|
||||||
|
// Incremental evaluation
|
||||||
|
Score value() 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;
|
||||||
|
bool is_draw() const;
|
||||||
|
|
||||||
|
// Check if one side threatens a mate in one
|
||||||
|
bool has_mate_threat(Color c);
|
||||||
|
|
||||||
|
// Number of plies since the last non-reversible move
|
||||||
|
int rule_50_counter() const;
|
||||||
|
|
||||||
|
// Other properties of the position
|
||||||
|
bool opposite_colored_bishops() const;
|
||||||
|
bool has_pawn_on_7th(Color c) const;
|
||||||
|
|
||||||
|
// Reset the gamePly variable to 0
|
||||||
|
void reset_game_ply();
|
||||||
|
|
||||||
|
// Position consistency check, for debugging
|
||||||
|
bool is_ok(int* failedStep = NULL) const;
|
||||||
|
|
||||||
|
// Static member functions
|
||||||
|
static void init_zobrist();
|
||||||
|
static void init_piece_square_tables();
|
||||||
|
|
||||||
|
private:
|
||||||
|
|
||||||
|
// Initialization helper functions (used while setting up a position)
|
||||||
|
void clear();
|
||||||
|
void put_piece(Piece p, Square s);
|
||||||
|
void allow_oo(Color c);
|
||||||
|
void allow_ooo(Color c);
|
||||||
|
|
||||||
|
// Helper functions for doing and undoing moves
|
||||||
|
void do_capture_move(Bitboard& key, PieceType capture, Color them, Square to, bool ep);
|
||||||
|
void do_castle_move(Move m);
|
||||||
|
void undo_castle_move(Move m);
|
||||||
|
void find_checkers();
|
||||||
|
|
||||||
|
template<bool FindPinned>
|
||||||
|
Bitboard hidden_checkers(Color c) const;
|
||||||
|
|
||||||
|
// Computing hash keys from scratch (for initialization and debugging)
|
||||||
|
Key compute_key() const;
|
||||||
|
Key compute_pawn_key() const;
|
||||||
|
Key compute_material_key() const;
|
||||||
|
|
||||||
|
// Computing incremental evaluation scores and material counts
|
||||||
|
Score pst(Color c, PieceType pt, Square s) const;
|
||||||
|
Score compute_value() const;
|
||||||
|
Value compute_non_pawn_material(Color c) const;
|
||||||
|
|
||||||
|
// Board
|
||||||
|
Piece board[64];
|
||||||
|
|
||||||
|
// Bitboards
|
||||||
|
Bitboard byTypeBB[8], byColorBB[2];
|
||||||
|
|
||||||
|
// Piece counts
|
||||||
|
int pieceCount[2][8]; // [color][pieceType]
|
||||||
|
|
||||||
|
// Piece lists
|
||||||
|
Square pieceList[2][8][16]; // [color][pieceType][index]
|
||||||
|
int index[64]; // [square]
|
||||||
|
|
||||||
|
// Other info
|
||||||
|
Color sideToMove;
|
||||||
|
int gamePly;
|
||||||
|
Key history[MaxGameLength];
|
||||||
|
File initialKFile, initialKRFile, initialQRFile;
|
||||||
|
StateInfo startState;
|
||||||
|
StateInfo* st;
|
||||||
|
|
||||||
|
// Static variables
|
||||||
|
static int castleRightsMask[64];
|
||||||
|
static Key zobrist[2][8][64];
|
||||||
|
static Key zobEp[64];
|
||||||
|
static Key zobCastle[16];
|
||||||
|
static Key zobMaterial[2][8][16];
|
||||||
|
static Key zobSideToMove;
|
||||||
|
static Score PieceSquareTable[16][64];
|
||||||
|
static Key zobExclusion;
|
||||||
};
|
};
|
||||||
|
|
||||||
std::ostream& operator<<(std::ostream& os, const Position& pos);
|
|
||||||
|
|
||||||
inline Color Position::side_to_move() const { return sideToMove; }
|
////
|
||||||
|
//// Inline functions
|
||||||
|
////
|
||||||
|
|
||||||
inline Piece Position::piece_on(Square s) const {
|
inline Piece Position::piece_on(Square s) const {
|
||||||
assert(is_ok(s));
|
return board[s];
|
||||||
return board[s];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool Position::empty(Square s) const { return piece_on(s) == NO_PIECE; }
|
inline Color Position::color_of_piece_on(Square s) const {
|
||||||
|
return color_of_piece(piece_on(s));
|
||||||
inline Piece Position::moved_piece(Move m) const { return piece_on(m.from_sq()); }
|
|
||||||
|
|
||||||
inline Bitboard Position::pieces(PieceType pt) const { return byTypeBB[pt]; }
|
|
||||||
|
|
||||||
template<typename... PieceTypes>
|
|
||||||
inline Bitboard Position::pieces(PieceType pt, PieceTypes... pts) const {
|
|
||||||
return pieces(pt) | pieces(pts...);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Bitboard Position::pieces(Color c) const { return byColorBB[c]; }
|
inline PieceType Position::type_of_piece_on(Square s) const {
|
||||||
|
return type_of_piece(piece_on(s));
|
||||||
template<typename... PieceTypes>
|
|
||||||
inline Bitboard Position::pieces(Color c, PieceTypes... pts) const {
|
|
||||||
return pieces(c) & pieces(pts...);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
template<PieceType Pt>
|
inline bool Position::square_is_empty(Square s) const {
|
||||||
inline int Position::count(Color c) const {
|
return piece_on(s) == EMPTY;
|
||||||
return pieceCount[make_piece(c, Pt)];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
template<PieceType Pt>
|
inline bool Position::square_is_occupied(Square s) const {
|
||||||
inline int Position::count() const {
|
return !square_is_empty(s);
|
||||||
return count<Pt>(WHITE) + count<Pt>(BLACK);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
template<PieceType Pt>
|
inline Value Position::midgame_value_of_piece_on(Square s) const {
|
||||||
inline Square Position::square(Color c) const {
|
return piece_value_midgame(piece_on(s));
|
||||||
assert(count<Pt>(c) == 1);
|
|
||||||
return lsb(pieces(c, Pt));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Square Position::ep_square() const { return st->epSquare; }
|
inline Value Position::endgame_value_of_piece_on(Square s) const {
|
||||||
|
return piece_value_endgame(piece_on(s));
|
||||||
inline bool Position::can_castle(CastlingRights cr) const { return st->castlingRights & cr; }
|
|
||||||
|
|
||||||
inline CastlingRights Position::castling_rights(Color c) const {
|
|
||||||
return c & CastlingRights(st->castlingRights);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline bool Position::castling_impeded(CastlingRights cr) const {
|
inline Color Position::side_to_move() const {
|
||||||
assert(cr == WHITE_OO || cr == WHITE_OOO || cr == BLACK_OO || cr == BLACK_OOO);
|
return sideToMove;
|
||||||
return pieces() & castlingPath[cr];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Square Position::castling_rook_square(CastlingRights cr) const {
|
inline Bitboard Position::occupied_squares() const {
|
||||||
assert(cr == WHITE_OO || cr == WHITE_OOO || cr == BLACK_OO || cr == BLACK_OOO);
|
return byTypeBB[0];
|
||||||
return castlingRookSquare[cr];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Bitboard Position::attackers_to(Square s) const { return attackers_to(s, pieces()); }
|
inline Bitboard Position::empty_squares() const {
|
||||||
|
return ~(occupied_squares());
|
||||||
template<PieceType Pt>
|
|
||||||
inline Bitboard Position::attacks_by(Color c) const {
|
|
||||||
|
|
||||||
if constexpr (Pt == PAWN)
|
|
||||||
return c == WHITE ? pawn_attacks_bb<WHITE>(pieces(WHITE, PAWN))
|
|
||||||
: pawn_attacks_bb<BLACK>(pieces(BLACK, PAWN));
|
|
||||||
else
|
|
||||||
{
|
|
||||||
Bitboard threats = 0;
|
|
||||||
Bitboard attackers = pieces(c, Pt);
|
|
||||||
while (attackers)
|
|
||||||
threats |= attacks_bb<Pt>(pop_lsb(attackers), pieces());
|
|
||||||
return threats;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Bitboard Position::checkers() const { return st->checkersBB; }
|
inline Bitboard Position::pieces_of_color(Color c) const {
|
||||||
|
return byColorBB[c];
|
||||||
inline Bitboard Position::blockers_for_king(Color c) const { return st->blockersForKing[c]; }
|
|
||||||
|
|
||||||
inline Bitboard Position::pinners(Color c) const { return st->pinners[c]; }
|
|
||||||
|
|
||||||
inline Bitboard Position::check_squares(PieceType pt) const { return st->checkSquares[pt]; }
|
|
||||||
|
|
||||||
inline Key Position::key() const { return adjust_key50<false>(st->key); }
|
|
||||||
|
|
||||||
template<bool AfterMove>
|
|
||||||
inline Key Position::adjust_key50(Key k) const {
|
|
||||||
return st->rule50 < 14 - AfterMove ? k : k ^ make_key((st->rule50 - (14 - AfterMove)) / 8);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Key Position::pawn_key() const { return st->pawnKey; }
|
inline Bitboard Position::pieces(PieceType pt) const {
|
||||||
|
return byTypeBB[pt];
|
||||||
inline Key Position::material_key() const { return st->materialKey; }
|
|
||||||
|
|
||||||
inline Value Position::non_pawn_material(Color c) const { return st->nonPawnMaterial[c]; }
|
|
||||||
|
|
||||||
inline Value Position::non_pawn_material() const {
|
|
||||||
return non_pawn_material(WHITE) + non_pawn_material(BLACK);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline int Position::game_ply() const { return gamePly; }
|
inline Bitboard Position::pieces(PieceType pt, Color c) const {
|
||||||
|
return byTypeBB[pt] & byColorBB[c];
|
||||||
inline int Position::rule50_count() const { return st->rule50; }
|
|
||||||
|
|
||||||
inline bool Position::is_chess960() const { return chess960; }
|
|
||||||
|
|
||||||
inline bool Position::capture(Move m) const {
|
|
||||||
assert(m.is_ok());
|
|
||||||
return (!empty(m.to_sq()) && m.type_of() != CASTLING) || m.type_of() == EN_PASSANT;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Returns true if a move is generated from the capture stage, having also
|
inline Bitboard Position::pieces(PieceType pt1, PieceType pt2) const {
|
||||||
// queen promotions covered, i.e. consistency with the capture stage move
|
return byTypeBB[pt1] | byTypeBB[pt2];
|
||||||
// generation is needed to avoid the generation of duplicate moves.
|
|
||||||
inline bool Position::capture_stage(Move m) const {
|
|
||||||
assert(m.is_ok());
|
|
||||||
return capture(m) || m.promotion_type() == QUEEN;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline Piece Position::captured_piece() const { return st->capturedPiece; }
|
inline Bitboard Position::pieces(PieceType pt1, PieceType pt2, Color c) const {
|
||||||
|
return (byTypeBB[pt1] | byTypeBB[pt2]) & byColorBB[c];
|
||||||
inline void Position::put_piece(Piece pc, Square s) {
|
|
||||||
|
|
||||||
board[s] = pc;
|
|
||||||
byTypeBB[ALL_PIECES] |= byTypeBB[type_of(pc)] |= s;
|
|
||||||
byColorBB[color_of(pc)] |= s;
|
|
||||||
pieceCount[pc]++;
|
|
||||||
pieceCount[make_piece(color_of(pc), ALL_PIECES)]++;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void Position::remove_piece(Square s) {
|
inline int Position::piece_count(Color c, PieceType pt) const {
|
||||||
|
return pieceCount[c][pt];
|
||||||
Piece pc = board[s];
|
|
||||||
byTypeBB[ALL_PIECES] ^= s;
|
|
||||||
byTypeBB[type_of(pc)] ^= s;
|
|
||||||
byColorBB[color_of(pc)] ^= s;
|
|
||||||
board[s] = NO_PIECE;
|
|
||||||
pieceCount[pc]--;
|
|
||||||
pieceCount[make_piece(color_of(pc), ALL_PIECES)]--;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void Position::move_piece(Square from, Square to) {
|
inline Square Position::piece_list(Color c, PieceType pt, int index) const {
|
||||||
|
return pieceList[c][pt][index];
|
||||||
Piece pc = board[from];
|
|
||||||
Bitboard fromTo = from | to;
|
|
||||||
byTypeBB[ALL_PIECES] ^= fromTo;
|
|
||||||
byTypeBB[type_of(pc)] ^= fromTo;
|
|
||||||
byColorBB[color_of(pc)] ^= fromTo;
|
|
||||||
board[from] = NO_PIECE;
|
|
||||||
board[to] = pc;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void Position::do_move(Move m, StateInfo& newSt) { do_move(m, newSt, gives_check(m)); }
|
inline const Square* Position::piece_list_begin(Color c, PieceType pt) const {
|
||||||
|
return pieceList[c][pt];
|
||||||
|
}
|
||||||
|
|
||||||
inline StateInfo* Position::state() const { return st; }
|
inline Square Position::ep_square() const {
|
||||||
|
return st->epSquare;
|
||||||
|
}
|
||||||
|
|
||||||
} // namespace Stockfish
|
inline Square Position::king_square(Color c) const {
|
||||||
|
return pieceList[c][KING][0];
|
||||||
|
}
|
||||||
|
|
||||||
#endif // #ifndef POSITION_H_INCLUDED
|
inline bool Position::can_castle_kingside(Color side) const {
|
||||||
|
return st->castleRights & (1+int(side));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool Position::can_castle_queenside(Color side) const {
|
||||||
|
return st->castleRights & (4+4*int(side));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool Position::can_castle(Color side) const {
|
||||||
|
return can_castle_kingside(side) || can_castle_queenside(side);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Square Position::initial_kr_square(Color c) const {
|
||||||
|
return relative_square(c, make_square(initialKRFile, RANK_1));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Square Position::initial_qr_square(Color c) const {
|
||||||
|
return relative_square(c, make_square(initialQRFile, RANK_1));
|
||||||
|
}
|
||||||
|
|
||||||
|
template<>
|
||||||
|
inline Bitboard Position::attacks_from<PAWN>(Square s, Color c) const {
|
||||||
|
return StepAttackBB[piece_of_color_and_type(c, PAWN)][s];
|
||||||
|
}
|
||||||
|
|
||||||
|
template<PieceType Piece> // Knight and King and white pawns
|
||||||
|
inline Bitboard Position::attacks_from(Square s) const {
|
||||||
|
return StepAttackBB[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::checkers() const {
|
||||||
|
return st->checkersBB;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool Position::is_check() const {
|
||||||
|
return st->checkersBB != EmptyBoardBB;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool Position::pawn_is_passed(Color c, Square s) const {
|
||||||
|
return !(pieces(PAWN, opposite_color(c)) & passed_pawn_mask(c, s));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool Position::pawn_is_passed(Bitboard theirPawns, Color c, Square s) {
|
||||||
|
return !(theirPawns & passed_pawn_mask(c, s));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool Position::pawn_is_isolated(Bitboard ourPawns, Square s) {
|
||||||
|
return !(ourPawns & neighboring_files_bb(s));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool Position::pawn_is_doubled(Bitboard ourPawns, Color c, Square s) {
|
||||||
|
return ourPawns & squares_behind(c, s);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool Position::square_is_weak(Square s, Color c) const {
|
||||||
|
return !(pieces(PAWN, c) & outpost_mask(opposite_color(c), s));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Key Position::get_key() const {
|
||||||
|
return st->key;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Key Position::get_exclusion_key() const {
|
||||||
|
return st->key ^ zobExclusion;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Key Position::get_pawn_key() const {
|
||||||
|
return st->pawnKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Key Position::get_material_key() const {
|
||||||
|
return st->materialKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Score Position::pst(Color c, PieceType pt, Square s) const {
|
||||||
|
return PieceSquareTable[piece_of_color_and_type(c, pt)][s];
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Score Position::pst_delta(Piece piece, Square from, Square to) const {
|
||||||
|
return PieceSquareTable[piece][to] - PieceSquareTable[piece][from];
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Score Position::value() const {
|
||||||
|
return st->value;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline Value Position::non_pawn_material(Color c) const {
|
||||||
|
return st->npMaterial[c];
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool Position::move_is_passed_pawn_push(Move m) const {
|
||||||
|
|
||||||
|
Color c = side_to_move();
|
||||||
|
return piece_on(move_from(m)) == piece_of_color_and_type(c, PAWN)
|
||||||
|
&& pawn_is_passed(c, move_to(m));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int Position::rule_50_counter() const {
|
||||||
|
|
||||||
|
return st->rule50;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool Position::opposite_colored_bishops() const {
|
||||||
|
|
||||||
|
return piece_count(WHITE, BISHOP) == 1
|
||||||
|
&& piece_count(BLACK, BISHOP) == 1
|
||||||
|
&& square_color(piece_list(WHITE, BISHOP, 0)) != square_color(piece_list(BLACK, BISHOP, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool Position::has_pawn_on_7th(Color c) const {
|
||||||
|
|
||||||
|
return pieces(PAWN, c) & relative_rank_bb(c, RANK_7);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool Position::move_is_capture(Move m) const {
|
||||||
|
|
||||||
|
// Move must not be MOVE_NONE !
|
||||||
|
return (m & (3 << 15)) ? !move_is_castle(m) : !square_is_empty(move_to(m));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool Position::move_is_capture_or_promotion(Move m) const {
|
||||||
|
|
||||||
|
// Move must not be MOVE_NONE !
|
||||||
|
return (m & (0x1F << 12)) ? !move_is_castle(m) : !square_is_empty(move_to(m));
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif // !defined(POSITION_H_INCLUDED)
|
||||||
|
|||||||
+188
@@ -0,0 +1,188 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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(PSQTAB_H_INCLUDED)
|
||||||
|
#define PSQTAB_H_INCLUDED
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include "value.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Constants modified by Joona Kiiski
|
||||||
|
////
|
||||||
|
|
||||||
|
static const Value MP = PawnValueMidgame;
|
||||||
|
static const Value MK = KnightValueMidgame;
|
||||||
|
static const Value MB = BishopValueMidgame;
|
||||||
|
static const Value MR = RookValueMidgame;
|
||||||
|
static const Value MQ = QueenValueMidgame;
|
||||||
|
|
||||||
|
static const int MgPST[][64] = {
|
||||||
|
{ },
|
||||||
|
{// Pawn
|
||||||
|
// A B C D E F G H
|
||||||
|
0, 0, 0, 0, 0, 0, 0, 0,
|
||||||
|
MP-28, MP-6, MP+ 4, MP+14, MP+14, MP+ 4, MP-6, MP-28,
|
||||||
|
MP-28, MP-6, MP+ 9, MP+36, MP+36, MP+ 9, MP-6, MP-28,
|
||||||
|
MP-28, MP-6, MP+17, MP+58, MP+58, MP+17, MP-6, MP-28,
|
||||||
|
MP-28, MP-6, MP+17, MP+36, MP+36, MP+17, MP-6, MP-28,
|
||||||
|
MP-28, MP-6, MP+ 9, MP+14, MP+14, MP+ 9, MP-6, MP-28,
|
||||||
|
MP-28, MP-6, MP+ 4, MP+14, MP+14, MP+ 4, MP-6, MP-28,
|
||||||
|
0, 0, 0, 0, 0, 0, 0, 0
|
||||||
|
},
|
||||||
|
{// Knight
|
||||||
|
// A B C D E F G H
|
||||||
|
MK-135, MK-107, MK-80, MK-67, MK-67, MK-80, MK-107, MK-135,
|
||||||
|
MK- 93, MK- 67, MK-39, MK-25, MK-25, MK-39, MK- 67, MK- 93,
|
||||||
|
MK- 53, MK- 25, MK+ 1, MK+13, MK+13, MK+ 1, MK- 25, MK- 53,
|
||||||
|
MK- 25, MK+ 1, MK+27, MK+41, MK+41, MK+27, MK+ 1, MK- 25,
|
||||||
|
MK- 11, MK+ 13, MK+41, MK+55, MK+55, MK+41, MK+ 13, MK- 11,
|
||||||
|
MK- 11, MK+ 13, MK+41, MK+55, MK+55, MK+41, MK+ 13, MK- 11,
|
||||||
|
MK- 53, MK- 25, MK+ 1, MK+13, MK+13, MK+ 1, MK- 25, MK- 53,
|
||||||
|
MK-193, MK- 67, MK-39, MK-25, MK-25, MK-39, MK- 67, MK-193
|
||||||
|
},
|
||||||
|
{// Bishop
|
||||||
|
// A B C D E F G H
|
||||||
|
MB-40, MB-40, MB-35, MB-30, MB-30, MB-35, MB-40, MB-40,
|
||||||
|
MB-17, MB+ 0, MB- 4, MB+ 0, MB+ 0, MB- 4, MB+ 0, MB-17,
|
||||||
|
MB-13, MB- 4, MB+ 8, MB+ 4, MB+ 4, MB+ 8, MB- 4, MB-13,
|
||||||
|
MB- 8, MB+ 0, MB+ 4, MB+17, MB+17, MB+ 4, MB+ 0, MB- 8,
|
||||||
|
MB- 8, MB+ 0, MB+ 4, MB+17, MB+17, MB+ 4, MB+ 0, MB- 8,
|
||||||
|
MB-13, MB- 4, MB+ 8, MB+ 4, MB+ 4, MB+ 8, MB- 4, MB-13,
|
||||||
|
MB-17, MB+ 0, MB- 4, MB+ 0, MB+ 0, MB- 4, MB+ 0, MB-17,
|
||||||
|
MB-17, MB-17, MB-13, MB- 8, MB- 8, MB-13, MB-17, MB-17
|
||||||
|
},
|
||||||
|
{// Rook
|
||||||
|
// A B C D E F G H
|
||||||
|
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
|
||||||
|
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
|
||||||
|
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
|
||||||
|
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
|
||||||
|
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
|
||||||
|
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
|
||||||
|
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
|
||||||
|
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12
|
||||||
|
},
|
||||||
|
{// Queen
|
||||||
|
// A B C D E F G H
|
||||||
|
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
|
||||||
|
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
|
||||||
|
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
|
||||||
|
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
|
||||||
|
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
|
||||||
|
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
|
||||||
|
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
|
||||||
|
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8
|
||||||
|
},
|
||||||
|
{// King
|
||||||
|
//A B C D E F G H
|
||||||
|
287, 311, 262, 214, 214, 262, 311, 287,
|
||||||
|
262, 287, 238, 190, 190, 238, 287, 262,
|
||||||
|
214, 238, 190, 142, 142, 190, 238, 214,
|
||||||
|
190, 214, 167, 119, 119, 167, 214, 190,
|
||||||
|
167, 190, 142, 94, 94, 142, 190, 167,
|
||||||
|
142, 167, 119, 69, 69, 119, 167, 142,
|
||||||
|
119, 142, 94, 46, 46, 94, 142, 119,
|
||||||
|
94, 119, 69, 21, 21, 69, 119, 94
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
static const Value EP = PawnValueEndgame;
|
||||||
|
static const Value EK = KnightValueEndgame;
|
||||||
|
static const Value EB = BishopValueEndgame;
|
||||||
|
static const Value ER = RookValueEndgame;
|
||||||
|
static const Value EQ = QueenValueEndgame;
|
||||||
|
|
||||||
|
static const int EgPST[][64] = {
|
||||||
|
{ },
|
||||||
|
{// Pawn
|
||||||
|
// A B C D E F G H
|
||||||
|
0, 0, 0, 0, 0, 0, 0, 0,
|
||||||
|
EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
|
||||||
|
EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
|
||||||
|
EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
|
||||||
|
EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
|
||||||
|
EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
|
||||||
|
EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
|
||||||
|
0, 0, 0, 0, 0, 0, 0, 0
|
||||||
|
},
|
||||||
|
{// Knight
|
||||||
|
// A B C D E F G H
|
||||||
|
EK-104, EK-79, EK-55, EK-42, EK-42, EK-55, EK-79, EK-104,
|
||||||
|
EK- 79, EK-55, EK-30, EK-17, EK-17, EK-30, EK-55, EK- 79,
|
||||||
|
EK- 55, EK-30, EK- 6, EK+ 5, EK+ 5, EK- 6, EK-30, EK- 55,
|
||||||
|
EK- 42, EK-17, EK+ 5, EK+18, EK+18, EK+ 5, EK-17, EK- 42,
|
||||||
|
EK- 42, EK-17, EK+ 5, EK+18, EK+18, EK+ 5, EK-17, EK- 42,
|
||||||
|
EK- 55, EK-30, EK- 6, EK+ 5, EK+ 5, EK- 6, EK-30, EK- 55,
|
||||||
|
EK- 79, EK-55, EK-30, EK-17, EK-17, EK-30, EK-55, EK- 79,
|
||||||
|
EK-104, EK-79, EK-55, EK-42, EK-42, EK-55, EK-79, EK-104
|
||||||
|
},
|
||||||
|
{// Bishop
|
||||||
|
// A B C D E F G H
|
||||||
|
EB-59, EB-42, EB-35, EB-26, EB-26, EB-35, EB-42, EB-59,
|
||||||
|
EB-42, EB-26, EB-18, EB-11, EB-11, EB-18, EB-26, EB-42,
|
||||||
|
EB-35, EB-18, EB-11, EB- 4, EB- 4, EB-11, EB-18, EB-35,
|
||||||
|
EB-26, EB-11, EB- 4, EB+ 4, EB+ 4, EB- 4, EB-11, EB-26,
|
||||||
|
EB-26, EB-11, EB- 4, EB+ 4, EB+ 4, EB- 4, EB-11, EB-26,
|
||||||
|
EB-35, EB-18, EB-11, EB- 4, EB- 4, EB-11, EB-18, EB-35,
|
||||||
|
EB-42, EB-26, EB-18, EB-11, EB-11, EB-18, EB-26, EB-42,
|
||||||
|
EB-59, EB-42, EB-35, EB-26, EB-26, EB-35, EB-42, EB-59
|
||||||
|
},
|
||||||
|
{// Rook
|
||||||
|
// A B C D E F G H
|
||||||
|
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
|
||||||
|
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
|
||||||
|
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
|
||||||
|
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
|
||||||
|
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
|
||||||
|
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
|
||||||
|
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
|
||||||
|
ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3
|
||||||
|
},
|
||||||
|
{// Queen
|
||||||
|
// A B C D E F G H
|
||||||
|
EQ-80, EQ-54, EQ-42, EQ-30, EQ-30, EQ-42, EQ-54, EQ-80,
|
||||||
|
EQ-54, EQ-30, EQ-18, EQ- 6, EQ- 6, EQ-18, EQ-30, EQ-54,
|
||||||
|
EQ-42, EQ-18, EQ- 6, EQ+ 6, EQ+ 6, EQ- 6, EQ-18, EQ-42,
|
||||||
|
EQ-30, EQ- 6, EQ+ 6, EQ+18, EQ+18, EQ+ 6, EQ- 6, EQ-30,
|
||||||
|
EQ-30, EQ- 6, EQ+ 6, EQ+18, EQ+18, EQ+ 6, EQ- 6, EQ-30,
|
||||||
|
EQ-42, EQ-18, EQ- 6, EQ+ 6, EQ+ 6, EQ- 6, EQ-18, EQ-42,
|
||||||
|
EQ-54, EQ-30, EQ-18, EQ- 6, EQ- 6, EQ-18, EQ-30, EQ-54,
|
||||||
|
EQ-80, EQ-54, EQ-42, EQ-30, EQ-30, EQ-42, EQ-54, EQ-80
|
||||||
|
},
|
||||||
|
{// King
|
||||||
|
//A B C D E F G H
|
||||||
|
18, 77, 105, 135, 135, 105, 77, 18,
|
||||||
|
77, 135, 165, 193, 193, 165, 135, 77,
|
||||||
|
105, 165, 193, 222, 222, 193, 165, 105,
|
||||||
|
135, 193, 222, 251, 251, 222, 193, 135,
|
||||||
|
135, 193, 222, 251, 251, 222, 193, 135,
|
||||||
|
105, 165, 193, 222, 222, 193, 165, 105,
|
||||||
|
77, 135, 165, 193, 193, 165, 135, 77,
|
||||||
|
18, 77, 105, 135, 135, 105, 77, 18
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
#endif // !defined(PSQTAB_H_INCLUDED)
|
||||||
+436
@@ -0,0 +1,436 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include <cassert>
|
||||||
|
#include <cstring>
|
||||||
|
#include <iomanip>
|
||||||
|
#include <string>
|
||||||
|
#include <sstream>
|
||||||
|
|
||||||
|
#include "history.h"
|
||||||
|
#include "movepick.h"
|
||||||
|
#include "san.h"
|
||||||
|
|
||||||
|
using std::string;
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Local definitions
|
||||||
|
////
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
enum Ambiguity {
|
||||||
|
AMBIGUITY_NONE,
|
||||||
|
AMBIGUITY_FILE,
|
||||||
|
AMBIGUITY_RANK,
|
||||||
|
AMBIGUITY_BOTH
|
||||||
|
};
|
||||||
|
|
||||||
|
const History H; // used as dummy argument for MovePicker c'tor
|
||||||
|
|
||||||
|
Ambiguity move_ambiguity(const Position& pos, Move m);
|
||||||
|
const string time_string(int milliseconds);
|
||||||
|
const string score_string(Value v);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Functions
|
||||||
|
////
|
||||||
|
|
||||||
|
/// move_to_san() takes a position and a move as input, where it is assumed
|
||||||
|
/// that the move is a legal move from the position. The return value is
|
||||||
|
/// a string containing the move in short algebraic notation.
|
||||||
|
|
||||||
|
const string move_to_san(const Position& pos, Move m) {
|
||||||
|
|
||||||
|
assert(pos.is_ok());
|
||||||
|
assert(move_is_ok(m));
|
||||||
|
|
||||||
|
Square from, to;
|
||||||
|
PieceType pt;
|
||||||
|
|
||||||
|
from = move_from(m);
|
||||||
|
to = move_to(m);
|
||||||
|
pt = type_of_piece(pos.piece_on(move_from(m)));
|
||||||
|
|
||||||
|
string san = "";
|
||||||
|
|
||||||
|
if (m == MOVE_NONE)
|
||||||
|
return "(none)";
|
||||||
|
else if (m == MOVE_NULL)
|
||||||
|
return "(null)";
|
||||||
|
else if (move_is_long_castle(m) || (int(to - from) == -2 && pt == KING))
|
||||||
|
san = "O-O-O";
|
||||||
|
else if (move_is_short_castle(m) || (int(to - from) == 2 && pt == KING))
|
||||||
|
san = "O-O";
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (pt != PAWN)
|
||||||
|
{
|
||||||
|
san += piece_type_to_char(pt, true);
|
||||||
|
switch (move_ambiguity(pos, m)) {
|
||||||
|
case AMBIGUITY_NONE:
|
||||||
|
break;
|
||||||
|
case AMBIGUITY_FILE:
|
||||||
|
san += file_to_char(square_file(from));
|
||||||
|
break;
|
||||||
|
case AMBIGUITY_RANK:
|
||||||
|
san += rank_to_char(square_rank(from));
|
||||||
|
break;
|
||||||
|
case AMBIGUITY_BOTH:
|
||||||
|
san += square_to_string(from);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
assert(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (pos.move_is_capture(m))
|
||||||
|
{
|
||||||
|
if (pt == PAWN)
|
||||||
|
san += file_to_char(square_file(move_from(m)));
|
||||||
|
san += "x";
|
||||||
|
}
|
||||||
|
san += square_to_string(move_to(m));
|
||||||
|
if (move_is_promotion(m))
|
||||||
|
{
|
||||||
|
san += '=';
|
||||||
|
san += piece_type_to_char(move_promotion_piece(m), true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Is the move check? We don't use pos.move_is_check(m) here, because
|
||||||
|
// Position::move_is_check doesn't detect all checks (not castling moves,
|
||||||
|
// promotions and en passant captures).
|
||||||
|
StateInfo st;
|
||||||
|
Position p(pos);
|
||||||
|
p.do_move(m, st);
|
||||||
|
if (p.is_check())
|
||||||
|
san += p.is_mate()? "#" : "+";
|
||||||
|
|
||||||
|
return san;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// move_from_san() takes a position and a string as input, and tries to
|
||||||
|
/// interpret the string as a move in short algebraic notation. On success,
|
||||||
|
/// the move is returned. On failure (i.e. if the string is unparsable, or
|
||||||
|
/// if the move is illegal or ambiguous), MOVE_NONE is returned.
|
||||||
|
|
||||||
|
Move move_from_san(const Position& pos, const string& movestr) {
|
||||||
|
|
||||||
|
assert(pos.is_ok());
|
||||||
|
|
||||||
|
MovePicker mp = MovePicker(pos, MOVE_NONE, OnePly, H);
|
||||||
|
Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
|
||||||
|
|
||||||
|
// Castling moves
|
||||||
|
if (movestr == "O-O-O" || movestr == "O-O-O+")
|
||||||
|
{
|
||||||
|
Move m;
|
||||||
|
while ((m = mp.get_next_move()) != MOVE_NONE)
|
||||||
|
if (move_is_long_castle(m) && pos.pl_move_is_legal(m, pinned))
|
||||||
|
return m;
|
||||||
|
|
||||||
|
return MOVE_NONE;
|
||||||
|
}
|
||||||
|
else if (movestr == "O-O" || movestr == "O-O+")
|
||||||
|
{
|
||||||
|
Move m;
|
||||||
|
while ((m = mp.get_next_move()) != MOVE_NONE)
|
||||||
|
if (move_is_short_castle(m) && pos.pl_move_is_legal(m, pinned))
|
||||||
|
return m;
|
||||||
|
|
||||||
|
return MOVE_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normal moves. We use a simple FSM to parse the san string.
|
||||||
|
enum { START, TO_FILE, TO_RANK, PROMOTION_OR_CHECK, PROMOTION, CHECK, END };
|
||||||
|
static const string pieceLetters = "KQRBN";
|
||||||
|
PieceType pt = NO_PIECE_TYPE, promotion = NO_PIECE_TYPE;
|
||||||
|
File fromFile = FILE_NONE, toFile = FILE_NONE;
|
||||||
|
Rank fromRank = RANK_NONE, toRank = RANK_NONE;
|
||||||
|
Square to;
|
||||||
|
int state = START;
|
||||||
|
|
||||||
|
for (size_t i = 0; i < movestr.length(); i++)
|
||||||
|
{
|
||||||
|
char type, c = movestr[i];
|
||||||
|
if (pieceLetters.find(c) != string::npos)
|
||||||
|
type = 'P';
|
||||||
|
else if (c >= 'a' && c <= 'h')
|
||||||
|
type = 'F';
|
||||||
|
else if (c >= '1' && c <= '8')
|
||||||
|
type = 'R';
|
||||||
|
else
|
||||||
|
type = c;
|
||||||
|
|
||||||
|
switch (type) {
|
||||||
|
case 'P':
|
||||||
|
if (state == START)
|
||||||
|
{
|
||||||
|
pt = piece_type_from_char(c);
|
||||||
|
state = TO_FILE;
|
||||||
|
}
|
||||||
|
else if (state == PROMOTION)
|
||||||
|
{
|
||||||
|
promotion = piece_type_from_char(c);
|
||||||
|
state = (i < movestr.length() - 1) ? CHECK : END;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
return MOVE_NONE;
|
||||||
|
break;
|
||||||
|
case 'F':
|
||||||
|
if (state == START)
|
||||||
|
{
|
||||||
|
pt = PAWN;
|
||||||
|
fromFile = toFile = file_from_char(c);
|
||||||
|
state = TO_RANK;
|
||||||
|
}
|
||||||
|
else if (state == TO_FILE)
|
||||||
|
{
|
||||||
|
toFile = file_from_char(c);
|
||||||
|
state = TO_RANK;
|
||||||
|
}
|
||||||
|
else if (state == TO_RANK && toFile != FILE_NONE)
|
||||||
|
{
|
||||||
|
// Previous file was for disambiguation
|
||||||
|
fromFile = toFile;
|
||||||
|
toFile = file_from_char(c);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
return MOVE_NONE;
|
||||||
|
break;
|
||||||
|
case 'R':
|
||||||
|
if (state == TO_RANK)
|
||||||
|
{
|
||||||
|
toRank = rank_from_char(c);
|
||||||
|
state = (i < movestr.length() - 1) ? PROMOTION_OR_CHECK : END;
|
||||||
|
}
|
||||||
|
else if (state == TO_FILE && fromRank == RANK_NONE)
|
||||||
|
{
|
||||||
|
// It's a disambiguation rank instead of a file
|
||||||
|
fromRank = rank_from_char(c);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
return MOVE_NONE;
|
||||||
|
break;
|
||||||
|
case 'x': case 'X':
|
||||||
|
if (state == TO_RANK)
|
||||||
|
{
|
||||||
|
// Previous file was for disambiguation, or it's a pawn capture
|
||||||
|
fromFile = toFile;
|
||||||
|
state = TO_FILE;
|
||||||
|
}
|
||||||
|
else if (state != TO_FILE)
|
||||||
|
return MOVE_NONE;
|
||||||
|
break;
|
||||||
|
case '=':
|
||||||
|
if (state == PROMOTION_OR_CHECK)
|
||||||
|
state = PROMOTION;
|
||||||
|
else
|
||||||
|
return MOVE_NONE;
|
||||||
|
break;
|
||||||
|
case '+': case '#':
|
||||||
|
if (state == PROMOTION_OR_CHECK || state == CHECK)
|
||||||
|
state = END;
|
||||||
|
else
|
||||||
|
return MOVE_NONE;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
return MOVE_NONE;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state != END)
|
||||||
|
return MOVE_NONE;
|
||||||
|
|
||||||
|
// Look for a matching move
|
||||||
|
Move m, move = MOVE_NONE;
|
||||||
|
to = make_square(toFile, toRank);
|
||||||
|
int matches = 0;
|
||||||
|
|
||||||
|
while ((m = mp.get_next_move()) != MOVE_NONE)
|
||||||
|
if ( pos.type_of_piece_on(move_from(m)) == pt
|
||||||
|
&& move_to(m) == to
|
||||||
|
&& move_promotion_piece(m) == promotion
|
||||||
|
&& (fromFile == FILE_NONE || fromFile == square_file(move_from(m)))
|
||||||
|
&& (fromRank == RANK_NONE || fromRank == square_rank(move_from(m))))
|
||||||
|
{
|
||||||
|
move = m;
|
||||||
|
matches++;
|
||||||
|
}
|
||||||
|
return (matches == 1 ? move : MOVE_NONE);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// line_to_san() takes a position and a line (an array of moves representing
|
||||||
|
/// a sequence of legal moves from the position) as input, and returns a
|
||||||
|
/// string containing the line in short algebraic notation. If the boolean
|
||||||
|
/// parameter 'breakLines' is true, line breaks are inserted, with a line
|
||||||
|
/// length of 80 characters. After a line break, 'startColumn' spaces are
|
||||||
|
/// inserted at the beginning of the new line.
|
||||||
|
|
||||||
|
const string line_to_san(const Position& pos, Move line[], int startColumn, bool breakLines) {
|
||||||
|
|
||||||
|
StateInfo st;
|
||||||
|
std::stringstream s;
|
||||||
|
string moveStr;
|
||||||
|
size_t length = 0;
|
||||||
|
size_t maxLength = 80 - startColumn;
|
||||||
|
Position p(pos);
|
||||||
|
|
||||||
|
for (int i = 0; line[i] != MOVE_NONE; i++)
|
||||||
|
{
|
||||||
|
moveStr = move_to_san(p, line[i]);
|
||||||
|
length += moveStr.length() + 1;
|
||||||
|
if (breakLines && length > maxLength)
|
||||||
|
{
|
||||||
|
s << '\n' << std::setw(startColumn) << ' ';
|
||||||
|
length = moveStr.length() + 1;
|
||||||
|
}
|
||||||
|
s << moveStr << ' ';
|
||||||
|
|
||||||
|
if (line[i] == MOVE_NULL)
|
||||||
|
p.do_null_move(st);
|
||||||
|
else
|
||||||
|
p.do_move(line[i], st);
|
||||||
|
}
|
||||||
|
return s.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// pretty_pv() creates a human-readable string from a position and a PV.
|
||||||
|
/// It is used to write search information to the log file (which is created
|
||||||
|
/// when the UCI parameter "Use Search Log" is "true").
|
||||||
|
|
||||||
|
const string pretty_pv(const Position& pos, int time, int depth,
|
||||||
|
uint64_t nodes, Value score, ValueType type, Move pv[]) {
|
||||||
|
std::stringstream s;
|
||||||
|
|
||||||
|
// Depth
|
||||||
|
s << std::setw(2) << depth << " ";
|
||||||
|
|
||||||
|
// Score
|
||||||
|
s << ((type == VALUE_TYPE_LOWER)? ">" : ((type == VALUE_TYPE_UPPER)? "<" : " "));
|
||||||
|
s << std::setw(7) << score_string(score);
|
||||||
|
|
||||||
|
// Time
|
||||||
|
s << std::setw(8) << time_string(time) << " ";
|
||||||
|
|
||||||
|
// Nodes
|
||||||
|
if (nodes < 1000000ULL)
|
||||||
|
s << std::setw(8) << nodes << " ";
|
||||||
|
else if (nodes < 1000000000ULL)
|
||||||
|
s << std::setw(7) << nodes/1000ULL << 'k' << " ";
|
||||||
|
else
|
||||||
|
s << std::setw(7) << nodes/1000000ULL << 'M' << " ";
|
||||||
|
|
||||||
|
// PV
|
||||||
|
s << line_to_san(pos, pv, 30, true);
|
||||||
|
|
||||||
|
return s.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
Ambiguity move_ambiguity(const Position& pos, Move m) {
|
||||||
|
|
||||||
|
Square from = move_from(m);
|
||||||
|
Square to = move_to(m);
|
||||||
|
Piece pc = pos.piece_on(from);
|
||||||
|
|
||||||
|
// King moves are never ambiguous, because there is never two kings of
|
||||||
|
// the same color.
|
||||||
|
if (type_of_piece(pc) == KING)
|
||||||
|
return AMBIGUITY_NONE;
|
||||||
|
|
||||||
|
MovePicker mp = MovePicker(pos, MOVE_NONE, OnePly, H);
|
||||||
|
Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
|
||||||
|
Move mv, moveList[8];
|
||||||
|
|
||||||
|
int n = 0;
|
||||||
|
while ((mv = mp.get_next_move()) != MOVE_NONE)
|
||||||
|
if (move_to(mv) == to && pos.piece_on(move_from(mv)) == pc && pos.pl_move_is_legal(mv, pinned))
|
||||||
|
moveList[n++] = mv;
|
||||||
|
|
||||||
|
if (n == 1)
|
||||||
|
return AMBIGUITY_NONE;
|
||||||
|
|
||||||
|
int f = 0, r = 0;
|
||||||
|
for (int i = 0; i < n; i++)
|
||||||
|
{
|
||||||
|
if (square_file(move_from(moveList[i])) == square_file(from))
|
||||||
|
f++;
|
||||||
|
|
||||||
|
if (square_rank(move_from(moveList[i])) == square_rank(from))
|
||||||
|
r++;
|
||||||
|
}
|
||||||
|
if (f == 1)
|
||||||
|
return AMBIGUITY_FILE;
|
||||||
|
|
||||||
|
if (r == 1)
|
||||||
|
return AMBIGUITY_RANK;
|
||||||
|
|
||||||
|
return AMBIGUITY_BOTH;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const string time_string(int milliseconds) {
|
||||||
|
|
||||||
|
std::stringstream s;
|
||||||
|
s << std::setfill('0');
|
||||||
|
|
||||||
|
int hours = milliseconds / (1000*60*60);
|
||||||
|
int minutes = (milliseconds - hours*1000*60*60) / (1000*60);
|
||||||
|
int seconds = (milliseconds - hours*1000*60*60 - minutes*1000*60) / 1000;
|
||||||
|
|
||||||
|
if (hours)
|
||||||
|
s << hours << ':';
|
||||||
|
|
||||||
|
s << std::setw(2) << minutes << ':' << std::setw(2) << seconds;
|
||||||
|
return s.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
const string score_string(Value v) {
|
||||||
|
|
||||||
|
std::stringstream s;
|
||||||
|
|
||||||
|
if (v >= VALUE_MATE - 200)
|
||||||
|
s << "#" << (VALUE_MATE - v + 1) / 2;
|
||||||
|
else if(v <= -VALUE_MATE + 200)
|
||||||
|
s << "-#" << (VALUE_MATE + v) / 2;
|
||||||
|
else
|
||||||
|
{
|
||||||
|
float floatScore = float(v) / float(PawnValueMidgame);
|
||||||
|
if (v >= 0)
|
||||||
|
s << '+';
|
||||||
|
|
||||||
|
s << std::setprecision(2) << std::fixed << floatScore;
|
||||||
|
}
|
||||||
|
return s.str();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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(SAN_H_INCLUDED)
|
||||||
|
#define SAN_H_INCLUDED
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include "move.h"
|
||||||
|
#include "position.h"
|
||||||
|
#include "value.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Prototypes
|
||||||
|
////
|
||||||
|
|
||||||
|
extern const std::string move_to_san(const Position& pos, Move m);
|
||||||
|
extern Move move_from_san(const Position& pos, const std::string& str);
|
||||||
|
extern const std::string line_to_san(const Position& pos, Move line[], int startColumn, bool breakLines);
|
||||||
|
extern const std::string pretty_pv(const Position& pos, int time, int depth, uint64_t nodes, Value score, ValueType type, Move pv[]);
|
||||||
|
|
||||||
|
#endif // !defined(SAN_H_INCLUDED)
|
||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
/*
|
||||||
|
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
||||||
|
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
|
||||||
|
Copyright (C) 2008-2009 Marco Costalba
|
||||||
|
|
||||||
|
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(SCALE_H_INCLUDED)
|
||||||
|
#define SCALE_H_INCLUDED
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Includes
|
||||||
|
////
|
||||||
|
|
||||||
|
#include "value.h"
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Types
|
||||||
|
////
|
||||||
|
|
||||||
|
enum ScaleFactor {
|
||||||
|
SCALE_FACTOR_ZERO = 0,
|
||||||
|
SCALE_FACTOR_NORMAL = 64,
|
||||||
|
SCALE_FACTOR_MAX = 128,
|
||||||
|
SCALE_FACTOR_NONE = 255
|
||||||
|
};
|
||||||
|
|
||||||
|
|
||||||
|
////
|
||||||
|
//// Inline functions
|
||||||
|
////
|
||||||
|
|
||||||
|
inline Value apply_scale_factor(Value v, ScaleFactor f) {
|
||||||
|
return Value((v * f) / int(SCALE_FACTOR_NORMAL));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#endif // !defined(SCALE_H_INCLUDED)
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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 "score.h"
|
|
||||||
|
|
||||||
#include <cassert>
|
|
||||||
#include <cmath>
|
|
||||||
#include <cstdlib>
|
|
||||||
|
|
||||||
#include "uci.h"
|
|
||||||
|
|
||||||
namespace Stockfish {
|
|
||||||
|
|
||||||
Score::Score(Value v, const Position& pos) {
|
|
||||||
assert(-VALUE_INFINITE < v && v < VALUE_INFINITE);
|
|
||||||
|
|
||||||
if (std::abs(v) < VALUE_TB_WIN_IN_MAX_PLY)
|
|
||||||
{
|
|
||||||
score = InternalUnits{UCIEngine::to_cp(v, pos)};
|
|
||||||
}
|
|
||||||
else if (std::abs(v) <= VALUE_TB)
|
|
||||||
{
|
|
||||||
auto distance = VALUE_TB - std::abs(v);
|
|
||||||
score = (v > 0) ? Tablebase{distance, true} : Tablebase{-distance, false};
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
auto distance = VALUE_MATE - std::abs(v);
|
|
||||||
score = (v > 0) ? Mate{distance} : Mate{-distance};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
-70
@@ -1,70 +0,0 @@
|
|||||||
/*
|
|
||||||
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
|
|
||||||
Copyright (C) 2004-2024 The Stockfish developers (see AUTHORS file)
|
|
||||||
|
|
||||||
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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef SCORE_H_INCLUDED
|
|
||||||
#define SCORE_H_INCLUDED
|
|
||||||
|
|
||||||
#include <variant>
|
|
||||||
#include <utility>
|
|
||||||
|
|
||||||
#include "types.h"
|
|
||||||
|
|
||||||
namespace Stockfish {
|
|
||||||
|
|
||||||
class Position;
|
|
||||||
|
|
||||||
class Score {
|
|
||||||
public:
|
|
||||||
struct Mate {
|
|
||||||
int plies;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct Tablebase {
|
|
||||||
int plies;
|
|
||||||
bool win;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct InternalUnits {
|
|
||||||
int value;
|
|
||||||
};
|
|
||||||
|
|
||||||
Score() = default;
|
|
||||||
Score(Value v, const Position& pos);
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
bool is() const {
|
|
||||||
return std::holds_alternative<T>(score);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
T get() const {
|
|
||||||
return std::get<T>(score);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename F>
|
|
||||||
decltype(auto) visit(F&& f) const {
|
|
||||||
return std::visit(std::forward<F>(f), score);
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
std::variant<Mate, Tablebase, InternalUnits> score;
|
|
||||||
};
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
#endif // #ifndef SCORE_H_INCLUDED
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user