Compare commits

..

830 Commits

Author SHA1 Message Date
Marco Costalba
78e6b361c5 Stockfish 2.2.1
Hopefully fixed the "lose on time" issue.

stockfish bench signature is: 5457475

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2012-01-06 17:01:40 +01:00
Marco Costalba
aa392c366e Extra time management safety
Further increase safety against time losses. After this
change (tested on LittleBlitzer and cutechess) I had no
more time losses at 2" and 1"+0.02 TC both on Windows
and Linux on more than 10000 games.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2012-01-06 13:24:37 +01:00
Marco Costalba
f80c50bcdd Try hard not to lose on time
We try hard not to lose on time even under extreme
time pressure. We achieve this through 3 different but
coordinated steps:

    1) Increase max frequency of timer events

    2) Quickly return after a stop signal

    3) Take in account timer resolution

With these SF played under LittleBlitzer at 1"+0.02 and 3"+0
without losing on time even one game.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2012-01-06 01:41:45 +01:00
Marco Costalba
d282cf6964 Avoid a race at thread creation
Before creating main thread we set its do_sleep flag to true,
then thread is created and it will go to sleep in main_loop()
after resetting do_sleep.

But if after the setting of do_sleep and before its resetting
the UI thread calls start_thinking() it will not wait on:

  if (!asyncMode)
      while (!main.do_sleep)
          cond_wait(&sleepCond, &main.sleepLock);

as it should but will immediately return before the main thread has
started the search. This very rare race show itself during bench,
when the first position is erroneusly skipped so that bench node count
results of 5309038 instead of the correct 5457475.

The patch is somewhat tricky, but is simple and it works!

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2012-01-03 21:31:50 +01:00
Marco Costalba
b1fcfe4c5d Streamline generation of MV_NON_EVASION
Small speed-up of 3% in perft.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2012-01-03 19:18:38 +01:00
Marco Costalba
30418a3cfc Fix a warning under gcc
Locals left and right shadow two same named
variables in the std::ifstream base class.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2012-01-03 19:01:47 +01:00
Marco Costalba
cb1709ef5e Revert cond_signal() fix
It seems it yields to missing wake-up events with the
result of SF loosing on time as reported by many people.

So revert the patch and use a more robust approach: assume
there can be spurious wake ups events and make the code to
work also in those cases.

While debugging I found that WaitForSingleObject() had wrong
parameter 0 instead of INFINITE yielding to a crash while
exiting under Windows, strangely unnoticed til now.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2012-01-02 16:44:04 +01:00
Marco Costalba
67338e6f32 Big renaming of move's helpers
The aim is to have shorter names without losing
readibility but, if possible, increasing it.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2012-01-02 12:03:54 +01:00
Marco Costalba
8300ab149c Simplify Book APIs
Retire open(), close() and name() from public visibility
and greately simplify the code. It is amazing how much
can be squeezed out of an already mature code !

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2012-01-01 14:46:18 +01:00
Marco Costalba
c00443b19e Restore development version
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-31 15:44:00 +01:00
Marco Costalba
9db9e4f7d3 Stockfish 2.2
stockfish bench signature is: 5457475

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-31 15:43:28 +01:00
Marco Costalba
22e40c8c10 Fix cond_signal() semantics when using OLD_LOCKS
In Windows when OLD_LOCKS is defined we use SetEvent() to mimic
the semantic of the POSIX pthread_cond_signal().

Unfortunatly there is not a direct mapping because with SetEvent()
the state of an event object remains signaled until it is set
explicitly to the nonsignaled state or until a single waiting thread
has been released. Instead in case of pthread_cond_signal(), if there
are no waiting threads it has no effect. What we may want is something
like PulseEvent() instead of SetEvent(). Unfortunatly it is documented
by Mcrosoft as 'unreliable' due to spurious wakes up that could
filter out the signal resetting. So we opt to reset manually any
pending signaled state before to go to sleep.

This fixes the strange misbehaves during 'stockfish bench'
when using OLD_LOCKS under Windows.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-31 15:40:12 +01:00
Marco Costalba
e9296d694c Unify BitCountType selection
Now that HasPopCnt is a compile time constant we can
centralize and unify the BitCountType selection.

Also rename count_1s() in the more standard popcount()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-31 10:46:14 +01:00
Marco Costalba
fb4b4f772e Fix Windows 64 build
Broken by previous patch.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-31 08:48:16 +01:00
Marco Costalba
f4dadee5e2 Reformat types.h
Retire obsolete code and reshuffle stuff.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-30 19:13:44 +01:00
Marco Costalba
808a312e1c Simplify debug functions
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-30 16:23:11 +01:00
Marco Costalba
93e539d909 Assorted cleanups in benchmark.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-30 15:23:33 +01:00
Marco Costalba
9d7a36121a Retire RootMove::nodes
Was used for time management but is no more used
today.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-30 14:16:15 +01:00
Marco Costalba
8307da0de7 Update copyright year to 2012
And refresh Readme.txt while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-30 13:52:16 +01:00
Marco Costalba
ad43ce1436 Simplify printing of engine info
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-30 13:19:20 +01:00
Marco Costalba
0a6532a39d Retire run-time detection of hardware POPCNT
It was meant to build a single binary optimized
for any kind of CPU: with and without hardware POPCNT.

This is a nice idea but in practice was never used, or
people builds binary with popcnt enabled or not, mainly
according to their type of CPU. And it was also never
used in the official Jim's builds where, in case, would
be easier for a number of reasons, do build two different
versions: with and without SEE42 support.

So retire this feature and simplify the code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-30 12:17:03 +01:00
Marco Costalba
20a6f99cdb Fix an off-by-one bug in ucioption.cpp
Harmless but anyhow wrong.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-30 11:58:55 +01:00
Marco Costalba
4554d8b2ac Better use STL algorithms in Endgame functions
This leads to a further and unexpected simplification
of this already very size optimized code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-30 11:58:54 +01:00
Marco Costalba
9cb187762a Wait for main thread to finish before to exit
Currently after a 'quit' command UI thread raises stop
signal, exits from uci_loop() and calls Threads.exit()
while the search threads are still active.

In Threads.exit() main thread is asked to terminate, but
if it is parked in idle_loop() it will exit and free its
resources (in particular the shared Movepicker object) while
sibling slaves are still active and this leads to a crash.

The fix is to let the UI thread always wait for main thread
to finish the search before to return from uci_loop().

Found by Valgrind when running with 8 threads.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-29 10:33:06 +01:00
Marco Costalba
4a8c1b2470 Use for_each() in Endgames d'tor
And fix some comments while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-29 10:25:11 +01:00
Marco Costalba
0759d8f430 Add user-defined conversions to UCIOption
Greatly improves the usage. User defined conversions
are a novelity for SF, another amazing C++ facility
at work !

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-28 19:42:50 +01:00
Marco Costalba
ae65ab25d5 Fix score_to_uci()
The condition for a mate score was wrong:

abs(v) < VALUE_MATE - PLY_MAX * ONE_PLY

instead of

abs(v) < VALUE_MATE_IN_PLY_MAX

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-28 14:20:24 +01:00
Marco Costalba
24417a6cd9 Better document how mate scores are stored in TT
During the search we score a mate as "plies to mate
from the root" to compare in an homogeneous way the
values returned by different sub-trees. However we
store in TT a mate score as "plies to mate from the
current position" the let the TT value remain valid
across the game.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-28 13:33:31 +01:00
Marco Costalba
ad4739a6d4 Retire SquaresByColorBB[] and enum SquareColor
Use same_color_squares() instead.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-28 10:57:08 +01:00
Marco Costalba
a695ed65a8 Rename Pieces
Align with PieceType naming convention and
make them more readable.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-28 10:38:48 +01:00
Marco Costalba
750ac9ac50 Document mate distance pruning
It is simple but somewhat tricky code that deserves
a bit of documentation. A bit of renaming while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-27 18:53:00 +01:00
Marco Costalba
07f3f0384a Assert enhancements in search
Add the check that alpha < beta - 1 if and only if PvNode is true.
The current code would not flag PvNode and alpha == beta - 1. In
other words, the || is not an exclusive OR!.

Also sync assert conditions of search() and qsearch()

Suggested by Rein Halbersma.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-27 01:04:00 +01:00
Marco Costalba
87b483f999 Reformat UCI option code
Make a better use of C++ operators overloading to
streamline the APIs.

Also sync polyglot.ini file while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-27 00:56:11 +01:00
Marco Costalba
c2d42ea833 Rename getters functions removing 'get_' prefix
Follow the suggested Qt style:

http://doc.qt.nokia.com/qq/qq13-apis.html

It seems to me simpler and easier to read.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-25 11:50:59 +01:00
Marco Costalba
b5f6c2241b Restore std::cout instead of printf()
I am not able to reproduce the speed regression anymore,
and also we were using cout even before speed regression
so probably the reason is not there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-25 09:29:51 +01:00
Marco Costalba
e89a8e0913 Correctly define operators in types.h
Be consistent with the way these operators are defined
in plain C (and in C++).

Spotted by Lucas Braesch.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-24 09:58:46 +01:00
Marco Costalba
d543a64cc7 Don't update killers for evasions
We don't use killers to order evasions, so it
seems natural do not consider an evasion cut-off
move as a possible killer. Test shows almost no
change, as it should be becuase this is a really
tiny change, but neverthless seems the correct
thing to do.

After 11893 games
Mod vs Orig 1773 - 1696 - 8424 ELO +2 (+-3.4)

Idea from Critter.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-24 09:25:20 +01:00
Marco Costalba
939b621e5c Use ADL to skip std:: qualifier
Take advantage of argument-dependent lookup (ADL) to
avoid specifying std:: qualifier in some STL functions.
When a function argument refers to a namespace (in this
case std) then the compiler will search the unqualified
function in that namespace too.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-18 21:18:51 +01:00
Marco Costalba
a77a3b723f Disable again buffering at startup
Partially revert efd2167998
Without this patch SF does not send "bestmove" to GUI.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-17 16:59:32 +01:00
Marco Costalba
976270916b Headers cleanup in ucioption.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-17 15:58:19 +01:00
Marco Costalba
87f7e99bc4 Use printf() instead of std::cout()
Seems sensibly faster: On a

./stockfish bench > /dev/null

We have +2% on mingw and even +5% on MSVC !

Also removed the nice but complex enum set960 machinery,
use directly the underlying move_to_uci() function.

Speed regression reported by Heinz van Saanen.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-17 15:50:06 +01:00
Marco Costalba
72d8d27234 Retire update_history() Inline the only caller site
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-16 19:17:47 +01:00
Marco Costalba
1ae6ae9b60 Fix book move with searchmoves compatibility
Do not return the book move if is not among the
RootMoves,in particular if we have been asked to
search on a move subset with "searchmoves" then
return book move only if it is among this subset.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-16 07:23:24 +01:00
Marco Costalba
af4fadebda Simplify id_loop() signature
And related assorted cleanup of this
very important function.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-14 21:56:37 +01:00
Marco Costalba
0af3af5d25 Reformat sending of PV information
Introduce pv_info_to_log() and pv_info_to_uci() and
greatly cleanup this stuff.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-14 19:22:22 +01:00
Marco Costalba
852d45a600 Further simplify aspiration code
Actually after last patch it happens that delta
starts always with the fixed value of 16.

So further remove useless code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-14 06:18:33 +01:00
Marco Costalba
96213689e4 Simplify aspiration window calculation
It seems that we just need to look at previous score to
compute aspiration window size.

After 5350 games:
Mod vs Orig 800 - 803  - 3647 ELO +0 (+- 5.2)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-14 05:56:53 +01:00
Marco Costalba
4e59c5c274 Retire RootMoveList
Diretcly use the underlying std::vector<Move> and the
STL algorithms. Also a bit of cleanup while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-12 20:13:24 +01:00
Marco Costalba
7d97ebfe7f Fix another crash triggered by previous patch
It is ok to redirect st pointer to startState, but the latter
should be updated with the content pointed by the st of the
original position. The bug is hidden when startState and *st
are the same as is the case of searching from start position,
but as soon as moves are made (as is the case when splitting)
the bug leads to a crash.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-11 11:44:09 +01:00
Marco Costalba
377c406c74 Fix a crash when quitting while searching
The Position object used by UI thread is a local variable in
uci_loop(), so after receiving "quit" command the function
returns and the position is freed from the stack.

This should not be a problem becuase in start_thinking() we copy
the position to RootPosition that is the one used by main search
thread. Unfortunatly we blindly copy also StateInfo pointer that
still points to the startState struct inside UI position. So the
pointer becomes stale as soon as UI thread leaves uci_loop() and
because this happens while main search thread is still recovering
after the 'stop' signal we have a crash.

The fix is to update the pointer to the correct startState after
the copy.

Found with Valgrind.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-11 10:31:46 +01:00
Marco Costalba
91601d7f95 Prune silly comments in search()
Comments should be informative but not pedantic / obvious.
The only exception is the function description where we
indulge a bit on the "chatty" side, but has always been like
this since Glaurung times, so we continue with this tradition.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-10 19:14:49 +01:00
Marco Costalba
f3728e66f8 Allow to prune also first move
Tested togheter with previous patch; shows no regression and
is a semplification.

After 5817 games:
Mod vs Orig 939 - 892 - 3986 ELO +2 (+- 5.1)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-10 17:35:37 +01:00
Marco Costalba
3f14ed6602 Don't update bestValue when pruning
Simply return a fail-low score

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-10 17:35:36 +01:00
Marco Costalba
14df99130f Fix description of endgame scaling functions
Triggered by a comment of Eelco on talkchess. Also
a bit of cleanup while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-10 12:40:05 +01:00
Marco Costalba
47bcb892af Fix compile for 64 bits
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-08 13:55:27 +01:00
Marco Costalba
6e05055f06 Set captureThreshold according to static evaluation
Consider negative captures as good if
still enough to reach beta.

After 7502 games:
Mod vs Orig 1225 - 1158 - 5119 ELO +3 (+- 4.5)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-08 13:48:18 +01:00
Marco Costalba
da6e53a436 Remove some (int) casts
A cast rarely is the right solution. In this case was enough
to redifine 3 variables with type size_t instead of int

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-07 17:30:28 +01:00
Marco Costalba
56774fff20 Retire all extensions (but checks) for non-PV nodes
It seems we don't have any added value. Note that the
moves that were used to be extended are still flagged
as dangerous so to avoid at least pruning them.

After 9555 games
Mod vs Orig 1562 - 1540 - 6453 ELO +0 (+- 4)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-07 07:49:24 +01:00
Marco Costalba
3527a42063 Prefer empty() to size()
As Heinz says:

"Function empty() should have a constant run-time even
 on lousy compilers and you spare the not.

The change is even measurable: + 100-150 nodes/sec. Wow:-)"

Patch from Heinz van Saanen

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-06 19:41:48 +01:00
Marco Costalba
98352a5e84 Use operator() instead of apply() in endgames
It is more idiomatic for a functor (a function object) as are
the endgames.

Suggested by Rein Halbersma.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-05 21:04:32 +01:00
Marco Costalba
11a7980976 Fix disambiguation bug in move_to_san()
A pinned piece cannot move and so does not play any role
in SAN disambiguation.

Reported by Steven Edwards.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-04 12:24:15 +01:00
Marco Costalba
5b8ca1eee7 Move SearchStack under Search namespace
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-04 12:03:59 +01:00
Marco Costalba
81cd417b45 Retire move.h
Also some assorted comments fixes and other trivia.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-04 11:36:03 +01:00
Marco Costalba
a44c5cf4f7 Prefer 0 to EmptyBoardBB
Easier and even faster or at least easier to optimize.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-03 12:02:13 +01:00
Marco Costalba
5c5af4fa65 Retire neighboring_files_bb() overload
Rarely used and we prefer to not hide the complexity.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-03 11:58:55 +01:00
Marco Costalba
efd2167998 Don't disable IO buffering at startup
It was never clear to me why we needed this trick, and now
that we rely only on C++ std::getline() and std::cout for
input / output it is even more a mistery what this code does.

So disable it and wait to see if someone screams ;-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-03 10:54:44 +01:00
Marco Costalba
348f824104 Tidy up comments in uci.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-03 10:48:31 +01:00
Marco Costalba
0f7cbaca75 Tidy up comments in thread.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-12-03 09:58:46 +01:00
Marco Costalba
e870afa5d5 Include <cstring> in search.h
Now we use memset() directly there.

Spotted by Justin Blanchard.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-28 07:30:31 +01:00
Marco Costalba
9bacd921fa Little reformat of elapsed_search_time()
Change name and argument type.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-27 22:36:13 +01:00
Marco Costalba
bb3427ca85 Detach search arguments from UI thread
Detach from the UI thread the input arguments used by
the search threads so that the UI thread is able to receive
and process any command sent by the GUI while other threads
keep searching.

With this patch there is no more need to block the UI
thread after a "stop", so it is a more reliable and
robust solution than the previous patch.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-27 17:46:18 +01:00
Marco Costalba
6809b57cfc After a "stop" do not read new input until search finishes
Unfortunatly xboard sends immediately the new position to
search after sending "stop" when we have a ponder miss.

Becuase main thread position is not copied but is referenced
directly from root position and the latter is modified by
the "position.." UCI command we end up with the working position
that changes under our feet while the search is still recovering
after the "stop" and this causes a crash.

This happens only with the (broken) xboard, native UCI does not
have this problem.

Reported by otello1984

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-27 12:19:33 +01:00
Marco Costalba
ffa75215cc Fix a race in pondering mode
Fixes an hang when playing with ponder ON. Perhaps there is still
a very small race but now it seems engine does not hang anymore.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-26 18:29:40 +01:00
Marco Costalba
c4517c013c Introduce Search namespace
Move global search-related variables under "Search" namespace.

As a side effect we can move uci_async_command() and
wait_for_stop_or_ponderhit() away from search.cpp

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-26 13:43:22 +01:00
Marco Costalba
ed04c010eb Rewrite async I/O
Use the starting thread to wait for GUI input and instead use
the other threads to search. The consequence is that now think()
is alwasy started on a differnt thread than the caller that
returns immediately waiting for input. This reformat greatly
simplifies the code and is more in line with the common way
to implement this feature.

As a side effect now we don't need anymore Makefile tricks
with sleep() to allow profile builds.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-26 11:51:12 +01:00
Marco Costalba
e9dc2e9e1e Reformat search dispatch code
Reduce indentation level and lines of code and tidy up
some comment.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-20 00:02:13 +01:00
Marco Costalba
9c7d72739c Fix regression with printing of debug info
Output of debug info each second was disabled
due to recent patches.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-19 14:37:57 +01:00
Marco Costalba
3fc08f8ab6 Don't check for early stop when StopOnPonderhit is set
If we are pondering we will stop the search only when
GUI sends "ponderhit" or "stop" commands or when we reach
maximum depth. In all the other cases we continue to search
so there is no need to verify for available time.

Also better clarify why wait_for_stop_or_ponderhit() before
to exit in some cases.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-19 12:04:42 +01:00
Marco Costalba
c56a7ee803 Early stop: retire redundant Rml.size() == 1 case
In case there is only 1 legal move we will stop the
search at depth 10 anyway because the exclusion search
probe will fail low.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-19 11:19:12 +01:00
Marco Costalba
35fa4fc71f Rewrite early stop logic
In the "easy move" paradigm we verify if the best move has
ever changed over a good number of iterations and if the
biggest part of the searched nodes are consumed on it.
This is a kind of hacky ad indirect heuristic to deduce
if one move is much better than others.

Rewrite the early stop condition to verify directly if one
move is much better than others performing an exclusion
search.

Idea to use exclusion search for time management if form Critter.

After 12245 games at 30"+0.1
Mod vs Orig 1776 - 1775 - 8694 ELO +0 (+-3.4)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-18 21:01:34 +01:00
Marco Costalba
b56a098cfb CLOP: Passed pawns weights tuning
Tuned with CLOP against a pool of 3 engines. Result
verified with a direct match:

After 11720 games at 10"+0.1
Mod vs Orig 1922 - 1832 - 7966 ELO +2 (+-3.6)

So no change in self match but if CLOP is right it should
be a bit better against an engine pool.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-14 09:05:20 +01:00
Marco Costalba
4cc272cb94 Rename value in bestValue in id_loop()
The value returned by root search it is actually
our best value, so rename the variable to reflect this.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-13 10:54:30 +01:00
Marco Costalba
c4fc82c6b7 Rewrite link time optimization in Makefile
Instead of binding link time optimization to the choice of
popcount support, do the right thing and add -flto option
when gcc 4.5 or later is detected.

Although it should be supported also under mingw, it happens
that it doesn't, at least on my 4.6.1 due to some known bugs.

Thanks to Mike for helping me with this patch.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-12 11:55:45 +01:00
Marco Costalba
a40ded2884 Simplify passed pawns logic
Remove the bonus for no *friendly* pieces in the pawn's path and
reduce a bit the bonus based on kings proximity.

This patch is part of to the ongoing effort to remove form evaluation
all the terms that do not add value.

After 16284 games:

Mod vs Orig 2728 - 2651 - 10911 ELO +1 (+- 3.1)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-12 09:09:41 +01:00
Marco Costalba
44c78fdb7a Fix regression: engine hangs while pondering
After a "stop" due to a ponder miss Xboard sends
immediately the new position to search, without
waiting for engine to effectively stop the search.

It is not clear if this is a GUI bug (as I suspect)
or allowed behaviour, but because it won't be fixed
anyway workaround this issue making listener thread
to switch to in-sync mode as soon as a "stop" command
is received.

Thanks to Mike Whiteley for reporting this.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-10 15:08:53 +01:00
Marco Costalba
ecb98a3330 Stop is not an unknown command
If GUI sends stop while we are waiting for
a command do not reply with a silly:

Unknown command: stop

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-10 15:06:28 +01:00
Marco Costalba
9b6b510ca8 Another fix to profile-build on gcc 4.6
Oliver reports profile builds error with new gcc 4.6, he says:

"We need to add -lgov with profile-generate AND profile-use.
So it has to be added to the second stage of building too.

The problem occurred first with the introduction of gcc4.6 and
I think this is because the previous version did find the gcov
library automatically. gcc4.6 needs more precise options and
does less guesses. I have seen it in debian, Ubuntu and also with
mingw on Windows. And all use gcc4.6."

This patch fixes the issue.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-09 05:20:35 +01:00
Marco Costalba
c2600a73cf Fix profile-build
After async I/O patches 'bench' changed behaviour and now waits for
input at the end of the test run. This is due to listener thread stay
blocked on std::getline() even after test run is finished, as soon as
we feed something the thread unblocks and then quickly exits.

This is not a big problem, but has the bad side effect of breaking
profile builds that hang forever at the end of the test run.

The tricky workaround is to create a pipe that connects to stockfish
input and then, when test run is finished, breaking the pipe: this
makes std::getline() immediately return.

So this patch adds a 'sleep 10' piped into 'stockfish bench' test run
command. After 10 seconds sleep ends, the pipe breaks and 'bench'
finishes as usual.

Thanks to Oliver Korff for reporting the issue, and to Mike Whiteley
for having co-authored this solution.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-08 07:39:06 +01:00
Marco Costalba
43204d9ac2 Reformat all_slaves_finished()
Rename and move under ThreadsManager class.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-06 13:45:47 +01:00
Marco Costalba
369789b426 Better document and reshuffle stuff in think()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-06 13:32:25 +01:00
Marco Costalba
8fa53a5b92 Better define wait_for_stop_or_ponderhit()
Use do_uci_async_cmd() instead of process input commands
directly and clarify that what we are waiting for is
something that is able to raise StopRequest flag.

Also fix some stale comments in do_uci_async_cmd(). Here
we need to reset Limits.ponder only upon receiving "ponderhit".
In the case of "quit" or "stop" resetting Limits.ponder has no
effect because the search is going to be stopped anyway.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-06 12:48:16 +01:00
Marco Costalba
d58176bfea Use a timer to avoid polling
The timer will be fired asynchronously to handle
time management flags, while other threads are
searching.

This implementation uses a thread waiting on a
timed condition variable instead of real timers.
This approach allow to reduce platform dependant
code to a minimum and also is the most portable given
that timers libraries are very different among platforms
and also the best ones are not compatible with olds
Windows.

Also retire the now unused polling code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-05 18:19:38 +01:00
Marco Costalba
0095f423f2 Retire now unused input_available()
With our new listener thread we don't need anymore
this ugly and platform dependent code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-05 08:43:44 +01:00
Marco Costalba
2617aa415e Rewrite how commands from GUI are read
Instead of polling for input use a dedicated listener
thread to read commands from the GUI independently
from other threads.

To do this properly we have to delegate to the listener
all the reading from the GUI: while searching but also
while waiting for a command, like in std::getline().

So we have two possible behaviours: in-sync mode, in which
the thread mimics std::getline() and the caller blocks until
something is read from GUI, and async mode where the listener
continuously reads and processes GUI commands while other
threads are searching.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-05 08:35:17 +01:00
Marco Costalba
22b9307aba Further touches to magic bitboards code
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-11-01 10:38:01 +01:00
Marco Costalba
ac7339877b Fix compile error in cpu_count()
The std::min() template function requires both arguments
to be of the same type.

But here we have the integer MAX_THREADS compared to a long:

long sysconf(int name);

So cast to integer and fix the compile.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-31 20:03:30 +01:00
Marco Costalba
90890844ad Document magics bitboards code
Add comments and rename stuff to better clarify what the
magic bitboard initialization code does.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-31 18:57:13 +01:00
mcostalba
8a89b12641 Merge pull request #1 from Panthee/master
Code Cleanup - Replacing macros Min() and Max() with corresponding STL algorithms std::min() and std::max()
2011-10-31 05:32:18 -07:00
Alexander Kure
4a3b162c8c Retire update_gains() 2011-10-31 03:28:59 -04:00
Alexander Kure
5c8af7ccb8 Replaced macros Min() and Max() with corresponding STL algorithms std::min() and std::max() 2011-10-31 00:38:44 -04:00
Marco Costalba
7942e6f3bf Retire update_gains()
Called from one place only.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-30 23:05:31 +01:00
Marco Costalba
c6f497f09d Fix small bug in move_attacks_square()
We test if the piece moved in 'to' attacks the square 's' with:

bit_is_set(attacks_from(piece, to), s))

But we should instead consider the new occupancy, changed after
the piece is moved, and so test with:

bit_is_set(attacks_from(piece, to, occ), s))

Otherwise we can miss some cases, for instance a queen in b1 that
moves in c1 is not detected to attack a1 while instead she does.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-30 19:31:50 +01:00
Marco Costalba
29be28e1a2 Inline pinned_pieces() and discovered_check_candidates()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-30 18:48:23 +01:00
Marco Costalba
e7939f450f Code style and 80 chars cols in Position::from_fen()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-30 18:02:18 +01:00
Marco Costalba
81801d395f Sync do_move() and undo_move()
It is not possible to unify due to the fact that the
sequence steps are reversed. What we can do is to try
to sync comments and code as much as we can to easy
reading and documentation.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-30 13:58:44 +01:00
Marco Costalba
bc76c62c63 Explicitly use a dedicated bitboard for occupied squares
Instead of byTypeBB[0]. This better self-documents the code.

No functional and speed change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-30 13:51:20 +01:00
Marco Costalba
fd5d6c5340 Retire do_capture_move()
It is called only in do_move() that now has been fully
expanded. This is the most time consuming function of
all the engine.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-30 10:59:55 +01:00
Marco Costalba
08abe8b4a3 Retire undo_null_move()
Use a templetized do_null_move() to do/undo the null move.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-29 18:01:56 +01:00
Marco Costalba
e896368496 Retire undo_castle_move()
Use a templetized do_castle_move() to do/undo the castling.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-29 17:31:15 +01:00
Marco Costalba
2fe4e10b0b Retire Position::set_castling_rights()
Is called in just one place. And rename set_castle() in the
now free to use and more appropiate set_castle_right().

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-29 13:43:44 +01:00
Marco Costalba
f2e78d9f84 Retire PieceValueXXX[] getters
They don't add any value given that the corresponding
table has global visibility anyhow.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-22 16:06:59 +01:00
Marco Costalba
b5bbc1f713 Simplify the promotion case of move_gives_check()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-22 15:01:21 +01:00
Marco Costalba
23943208ec Remove redundancy in definitions of attack helpers
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-22 14:25:53 +01:00
Marco Costalba
c555e1aa96 Convert PST tables to relative values
This is a prerequisite to allow changing piece values
at runtime, needed for tuning.

Also use scores instead of separated midgame and endgame values.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-22 13:17:24 +01:00
Marco Costalba
36cc214703 Increase Mobility
First tuning with CLOP against a pool of 3 engines. Result
verified with a direct match:

After 8736 games at 10"+0.1
Mod vs Orig 1470 - 1496 - 5770 ELO -1 (+-4.3)

So no change in self match but if CLOP is right it should
be a bit better against an engine pool.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-20 07:06:05 +01:00
Marco Costalba
8f7d36a85d Better document mate and stalemate detection
In particular add that we can have an harmless false positive
in case StopRequest or thread.cutoff_occurred() are set.

Reported by David Lee.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-18 20:01:21 +01:00
Marco Costalba
e7cfe42d3f Use newly added log facility instead of LogFile
As a side effect now log file is open and closed every
time it is used instead of remaining open for the whole
thinking time.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-17 21:07:14 +01:00
Marco Costalba
500fff920b Add basic log facility
Mainly used to log stuff to a file while playing, when
stdout is used for the comunication with the GUI.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-17 21:07:00 +01:00
Marco Costalba
782c3f36cc Fix compile error in debug mode
Build broken by commit 3141490374
where we renamed move_is_ok() in is_ok() and this clashes
with the same named method in Position that overrides the
move's one causing compile errors.

The fix is to rename the method in Position.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-16 23:56:25 +01:00
Marco Costalba
8272dcb6cd Link Time Optimization doesn't needs -static
Justin reports that it breaks the compilation on Fedore 15 and as Tom says:

-static is only needed to work around the gcc on ubuntu 11.10 beta bug.
If -static introduces issues on its own then it is better to remove it.
It will not be needed in most environments.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-09 08:24:56 +01:00
Marco Costalba
fec623d68d Better document how MultiPV search works
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-08 12:11:53 +01:00
Marco Costalba
a3bf09c5c9 Send again all the PV lines in multiPV searching
Partially revert 1036cadcec because UCI protocol
in case of multipv explicitly requires:

for the best move/pv add "multipv 1" in the string when you send the pv.
in k-best mode always send all k variants in k strings together.

Thanks to Justin Blanchard for pointing this out.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-08 10:24:54 +01:00
Marco Costalba
325dedc7da Added gcc -msse3 support
It is enabled when selecting x86-64-modern target, this gives
another nice speed up:

On a Core i5-2500 (3300 Mhz, Sandy Bridge):

64 bit download version: 1597151 n/s

-flto : 1659664 n/s

-flto -msse3: 1732344 n/s

Patch suggested by Tom Vijlbrief.

Also unify flto, popcount and msse3 optimization under "modern"
target, note that this can break the "modern" build on old gcc that
do not support -flto option: in this case update gcc ;-) or default
to the standard build.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-08 08:50:11 +01:00
Tom Vijlbrief
09b5949cd2 Added gcc lto (Link Time Optimization) option
Just by adding the -flto option to CXXFLAGS link command
we can gain a few percent in speed.

On a Core i5-2500 (3300 Mhz, Sandy Bridge):

64 bit download version:

Without -flto: 1597151 n/s
With -flto : 1659664 n/s

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-06 20:10:12 +01:00
Marco Costalba
3141490374 Shrink names of move helpers
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-03 14:18:57 +01:00
Marco Costalba
1a8e3f0b2e Small touches in position.h
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-03 14:18:56 +01:00
Marco Costalba
80dd90f972 Small touches to book.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-03 14:18:30 +01:00
Marco Costalba
c2c185423b Better naming borrowed from Critter
In line with http://chessprogramming.wikispaces.com conventions.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-02 10:16:59 +01:00
Marco Costalba
25b4d0c127 Revert "Retire Rml full PV search at depth == 1"
Yet another random crash source !

Hopefully this is the last one.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-02 07:40:46 +01:00
Marco Costalba
2225e3bbe7 Rename kingZone[] and reverse the king's color
Seems easier to understand to me. From Critter.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-02 06:54:57 +01:00
Marco Costalba
a90a990118 Document why Book is defined static
This was not clear to someone on talkchess and actually
is not trivial to understand.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-02 06:54:57 +01:00
Marco Costalba
83d8fe2d59 When exiting wake up all threads at once
It seems we have a very rare crash under Linux, once
every 10K games without this patch.

Is faster to wake up all the threads, especially on SMP,
where the threads can then exit in parallel while the main
thread is waiting for the next one to terminate.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-10-02 06:54:43 +01:00
Marco Costalba
63a04134d0 No need to test for MOVE_NONE before move_is_ok()
Function move_is_ok() already catches the move == MOVE_NONE case.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-09-25 16:30:29 +01:00
Marco Costalba
6bc16f3ff1 Update killers after a TT hit
Almost no increase but seems the logic thing to do.

After 16707 games 2771 - 2595 - 11341 ELO +3 (+- 3.2)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-09-24 17:20:35 +01:00
Marco Costalba
10b24af98a Correctly score capture underpromotions
Be sure a queen capture promotion is tried in front of
an underpromotion.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-09-24 17:13:14 +01:00
Marco Costalba
be9aba2fa0 Don't lock before check for termination
Restore old locking scheme changed with
commit 1e92df6b20.

This seems to prevent a very rare crash that occurs
once every 5-10K games.

With this patch we have no crashes after 33K games.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-09-24 17:12:36 +01:00
Marco Costalba
35018fa307 Use the map type template parameter to access map()
It is more natural than using the family subtype and also
use two single maps instead of a std::pair.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-09-11 11:38:23 +01:00
Marco Costalba
b706165527 Lookup square distance instead of calculate on the fly
Microptimization that gives a +0.7% speed increase.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-09-11 10:11:43 +01:00
Marco Costalba
6963c3802d Detect family type of endgame from its enum value
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-22 00:49:47 +01:00
Marco Costalba
3b67636f0e Indulge a bit on the template wizardy
Push the template pedal a bit in our "showoff" endgame code ;-)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-14 13:15:58 +01:00
Marco Costalba
48e39c5c8e Small simplification of endgame functions API
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-14 12:12:14 +01:00
Marco Costalba
13524bea9b Fix use of uninitialized variable
When initializing endgames map we build a faked FEN string
in mat_key() to get the position hash's key.

This fen string lacks full move numbers, so when parsing the
fen in Position::from_fen() we leave startPosPly un-initialized.

Spotted by Valgrind (this is a kind of bug that is almost impossible
for humans to find).

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-12 11:56:11 +01:00
Marco Costalba
500c7f44ab Fix silly icc remark #2259
Another stupid remark to quiet out:

remark #2259: non-pointer conversion from "int" to "UINT16={unsigned short}"
may lose significant bits

In this case icc always converts to an integer the result of a shift operation
if the bit size of the operand is smaller, hence the warning when assignin
back to n.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-12 11:54:54 +01:00
Marco Costalba
d156e7a20b Use a boolean instead as thread's state
Now that we have just two mutually exclusive thread's states
we can repleace them by a simple boolean.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-10 12:26:52 +01:00
Marco Costalba
c386ce0023 Remove Thread::WORKISWAITING
Set the state directly to Thread::SEARCHING

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-10 12:05:33 +01:00
Marco Costalba
b69d9ee3f7 Don't need pthread_detach() after pthread_join()
Spotted by Joona and verified with Valgrind.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-10 08:17:15 +01:00
Marco Costalba
7d5b8fcf77 Change start_routine argument
Directly pass the thread pointer.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-09 14:19:44 +01:00
Marco Costalba
bc6a6e04a0 Retire Rml full PV search at depth == 1
Now that Rml ordering is based on normal MovePicker logic,
apart for the ttMove that is given, we can avoid to score
all the root moves at depth 1. We only need it for easy move
detection logic, but in this case we just need to score the
first two best moves and not all the Rml set.

No regression after 6400 games
Mod vs Orig 1052 1012 4336 ELO +2 (+- 4.9)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-09 09:58:10 +01:00
Marco Costalba
e5ffe9959c Retire ThreadsManager::init_hash_tables()
Allocation of pawn and material hash tables should
be strictly bounded to the change of the number of
activeThreads, so move the code inside set_size().

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-08 23:08:34 +01:00
Marco Costalba
86b95f2105 Retire Thread::TERMINATED
Use proper way to detect for thread terimnation instead of
our homegrown flag.

It adds more code than it removes and adds also platform specific
code, neverthless I think is the way to go becuase Thread::TERMINATED
flag is intrinsecly racy given that when we raise it thread is still
_not_ terminated nor it can be, and also we don't want to reinvent
the (broken) wheel of thread termination detection when there is
already available the proper one.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-08 22:10:01 +01:00
Marco Costalba
1e92df6b20 Retire Thread::INITIALIZING
Was used to prevent issues when creating multiple threads
on Windows, but now it seems we can remove it safely.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-08 14:12:02 +01:00
Marco Costalba
ba85c59d96 Move idle_loop() under Thread
This greatly removes clutter from the difficult idle_loop() function

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-08 13:23:03 +01:00
Marco Costalba
dafd5b5864 Tidy up comments in thread.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-08 11:49:58 +01:00
Marco Costalba
eabba1119f Retire broken SendSearchedNodes
Now that we can split at root it happens that SendSearchedNodes
works only once at the end of the iteration, but this is useless
becuase speed info is sent anyhow toghter with the pv line.

So retire for now, waiting to find something SMP compatible.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-08 10:08:41 +01:00
Marco Costalba
06e0d48794 Sync search() and qsearch() alpha update
Change qsearch() to reflect alpha update logic
of search().

To be consistent changed also moves loop condition and
futility pruning condition.

No regression after 5072 games at TC 10"+0.1

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-08 07:46:01 +01:00
Marco Costalba
4a71c86270 Retire Thread::BOOKED
Start a slave as soon as is allocated.

No functional change with faked split.

Regression tested the full split() series and after
2000 games no regression and no crash.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-08 07:45:24 +01:00
Marco Costalba
68583f4d48 Fix obey the "maxThreadsPerSplitPoint" setting
Spotted by Joona.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-07 15:15:19 +01:00
Marco Costalba
5b35c149e8 Do not modify alpha in split()
When calling split or we immediately return because unable to
find available slaves, or we start searching on _all_ the moves
of the node or until a cut-off occurs, so that when returning
from split we immediately leave the moves loop.

Because of this we don't need to change alpha inside split() and
we can use a signature similar to search() so to better clarify
that split() is actually a search on the remaining node's moves.

No functional change with faked split.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-07 15:10:41 +01:00
Marco Costalba
9a542d9698 Initialize a new split point out of lock
Allocate and initialize a new split point
out of lock becuase modified data is local to
master thread only.

Also better document why we need a lock at
the end of split().

No functional change with faked split.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-07 14:37:14 +01:00
Marco Costalba
cd27ed9a74 Update comment on why we call root search with ss+1
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-07 10:36:14 +01:00
Marco Costalba
b9f8cb7837 Fix an assert when stopping the search
When StopRequest is raised we cannot immediately exit the
move loop but first we need to update bestValue so to avoid
assert:

assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-07 10:36:13 +01:00
Joona Kiiski
ffa150bec3 Split at root!
Another great success by Joona !

After 5876 games at 10"+0.1
Mod vs Orig: 1073 - 849 - 3954 ELO +13 (+- 5.2)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-07 10:35:56 +01:00
Joona Kiiski
13bc6ba2c6 Preparations for splitting at root
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-06 10:31:30 +01:00
Marco Costalba
30b3edf328 Simplify MovePickerExt<>
Now that we don't special case the root moves anymore
we don't need to pass NodeType anymore as template parameter,
a simple bool to detect a SpNode will be enough.

Spotted by Joona.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-05 07:23:54 +01:00
Marco Costalba
7902d6089e Fix silly bug in uci loop
After issuing "go"-command, at the end of the search
SF shows: "Unknown command: ...".

Spotted by Joona.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-05 07:15:45 +01:00
Marco Costalba
b6b0878da8 Fix a (silly) warning under icc compiler
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-04 10:10:03 +01:00
Marco Costalba
3a76163aba Use std::lexicographical_compare() in UCI options
Instead of our home grown function to perform a case
insensitive compare on option names as required by UCI
protocol.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-03 15:00:23 +01:00
Marco Costalba
1e7c6fc761 Consistently set ttMove to Rml.pv[0] in root node
No functional change, but reduce risks of subtle aliasing bugs.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-02 22:28:03 +01:00
Marco Costalba
c50ad85c3c Fix an off-by-one error in UCI print loop
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-02 21:47:31 +01:00
Marco Costalba
bb6a6e159a Rename ok_to_use_TT() in can_return_tt()
Seems more appropiate. From Lucas Braesch's DoubleCheck.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-02 18:49:06 +01:00
Marco Costalba
1036cadcec Send PV only for updated lines
It seems FritzGUI already remembers the old lines, so
we just need to update PV info only for the new lines.

Also introduced prevScore field in RootMove to avoid
a bulk copy of Rml.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-02 18:00:47 +01:00
Marco Costalba
c71ae794df Sort PV moves always in two steps
This should fix following issue:

Suppose the search with MultiPVIteration == 0 returns an exact score

move = Nxf4, score = 100

Now search with MultiPVIteration == 1 and get two scores

move = Qg8, score = 150
move = Ra1, score = 180

If we now reorder all the moves in one step we end up with

pv[0] = Ra1, pv[1] = Qg8

Instead reordering as the current patch we end up in:

pv[0] = Ra1, pv[1] = Nxf4

preserving the first searched move.

No functional change in single PV.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-02 18:00:47 +01:00
Marco Costalba
409930e98c Small cleanup of previous patches
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-02 18:00:22 +01:00
Joona Kiiski
b88f7df387 Reimplement MultiPV mode
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-02 06:47:33 +01:00
Joona Kiiski
adcfffceeb Reimplement support for "searchmoves" option
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-02 06:47:22 +01:00
Joona Kiiski
a3c1d64a5f Remove now unused RootMove.non_pv_score
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-02 06:47:06 +01:00
Joona Kiiski
ce24a229df Make root search to use standard MovePicker.
This patch temporarily breaks MultiPV and searchmove
features, but they will be re-implemented in future
patches.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-08-02 06:46:50 +01:00
Joona Kiiski
ce619b3b6c Don't probe TT at RootNode
In that case we should also update RootMoveList to avoid
bogus output

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-29 12:42:22 +01:00
Marco Costalba
2e2a4b4ea3 Fix pretty_pv() output in Chess960
And move it to search.cpp

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-26 12:39:15 +01:00
Joona Kiiski
7f519a2463 Fix PV output in Chess960
We missed to set chess960 flag into the std::stringstream used to
setup the PV line.

Bug introduced with commit f803f33e63
of 30/12/2010 when we started to print PV line into a std::stringstream
instead of directly into cout, where the chess960 flag is correctly set.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-24 18:27:29 +01:00
Marco Costalba
ff1ecb5d6c Tidy up benchmark.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-24 08:53:36 +01:00
Marco Costalba
dab1cd8af9 Rename execute_uci_command() to uci_loop()
As a side effect now root position can be directly
allocated on the stack and doesn't need to be defined
static anymore.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-24 08:12:07 +01:00
Marco Costalba
5b0c6b9bc0 Unhide the istringstream behind UCIParser
It is misnamed because it is not a parser, perhaps a
tokenizer, anyhow better call it for what it is, an
input string stream.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-24 07:39:07 +01:00
Marco Costalba
fc290dc30b Fix startpos_ply_counter() regression
Return the correct number of played plies at the end
of the setup moves. Currently it always returns 0 when
starting from start position, like in real games.

We fix this adding st->pliesFromNull that starts from 0
and is incremented after each setup move and is never
reset in the setup phase but only once search is started.

It is an hack because startpos_ply_counter() will return
different values during the search and is correct only
at the beginning of the search.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-24 06:59:14 +01:00
Marco Costalba
5f7eb20090 Use a circular buffer to keep track of setup states
This fixes a regression on real games due to the fact that
we have some mismatches:

    history[st->gamePly - i] != stp->key

when st->gamePly - i == 0,this is due to a nasty bug I have
introduced when using std::vector<> as StateInfo backup. The
point is that StateInfo keeps inside a pointer to the previous
StateInfo in a kind of linked list. But when std::vector<> is
resized reallocates a larger chunk of memory and moves the
data there so these pointers became stale.

This patch fixes the issue.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-24 06:15:40 +01:00
Marco Costalba
03ad183384 Don't update gamePly after each move
We just need startup value to calculate available
thinking time. So remove from state.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-24 06:15:39 +01:00
Marco Costalba
527a2ec541 Use std::vector<Move> to store UCI search moves
Avoid the ugly and anyhow incorrect hard limit on the
maximum number of moves and allow to handle an arbitrary
number of moves to search.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-24 06:15:38 +01:00
Marco Costalba
3185c36a65 Use st->gamePly to store fullMoves
This allow to retire do_setup_move() and also to simplify
draw detection logic becuase now we always have:

Min(st->rule50, st->gamePly) = st->rule50

This was already true when starting from starting position,
but now is true even when starting from a FEN string because
now we take in account fullmove number in counting gamePly so
that it is always.

st->rule50 <= st->gamePly

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-24 06:15:36 +01:00
Marco Costalba
3d8140a541 Retire history[]
Use key saved in state instead.

No functional change (in real games) and no speed regression.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-24 06:15:35 +01:00
Joona Kiiski
a6fc3d6ee5 Do not exit early even when seeing mate
Fixes the reported KNNK ending problem:

http://talkchess.com/forum/viewtopic.php?t=39347

Joona says:

Now I finally had a time to take a look at on this issue.

I've reproduced the problem starting from this position:
1B6/1B2k3/P7/1P3p2/1K6/8/4b3/4b3 w - - 6 85

I made Stockfish play as white and Fruit as black.
I repeated test ten times and once SF was not able to deliver mate.

But I observed several times that SF had reported on last something like mate in 10.
However next time it played move with score mate in 15.

Easiest way to solve the problem is attached as a patch. I tested it several times and SF always
ended up playing the optimal move. Of course the downside is that now delivering mate
takes a bit longer, but IMO it's better to lose once in a while by time in sudden death
game than not being able to deliver simple mate with long time controls.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-24 06:13:29 +01:00
Marco Costalba
a1f9bf19d9 Revert previous patches due to bug
We have a bug (possibly because of returning draw from
root move list), it is possible to see when looking at
games with a GUI, we can see rarely but consistently the
score return as #0 for many depths until it comes back to
normal values.

Revert patches until it is not fixed.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-20 03:34:39 +01:00
Joona Kiiski
4ad6a3496b Move the draw check also for qsearch
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-19 17:36:22 +01:00
Joona Kiiski
969ad8001c Move draw checks right after doing the move
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-19 17:36:14 +01:00
Marco Costalba
07e0dd27fb Small touches in set_option()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-17 12:55:26 +01:00
Marco Costalba
b8eb699db7 Validate input UCI moves
Running following command:

  position startpos moves e1e8

Makes SF to assert in debug mode in do_move() but to accept
bad input and continue in release mode where probably it is
going to crash little later.

So validate input before to feed do_move().

Suggestion by Yakovlev Vadim.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-17 10:22:55 +01:00
Marco Costalba
ad1f28bc1c Remove some useless include
Spotted by Rein Halbersma.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-16 22:59:14 +01:00
Marco Costalba
67686b7684 Don't need to assert for pos.is_ok() when position is constant
It's only necessary to do the checking at the end of every non-const
member (including the constructors and from_fen()) of class Position.
Once the post-condition of every modifier guarantees the class invariant,
we don't need to verify sanity of the position as preconditions for outside
callers such as movegen, search etc. For non-class types such as Move and
Square we still need to assert of course.

Suggested by Rein Halbersma.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-16 10:53:34 +01:00
Marco Costalba
69f4954df1 Change hidden checkers API
After previous patch is no more needed to pass
the color, becuase it is always the side to move.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-16 10:12:46 +01:00
Marco Costalba
4894231ff7 Simplified discovered check connected_moves()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-16 09:50:35 +01:00
Marco Costalba
36bb57a47e Simplify and micro-optimize hidden_checkers()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-16 08:53:21 +01:00
Marco Costalba
a042449f5d No need to declare default Position c'tor
Pointed out by Rein Halbersma.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-15 21:53:47 +01:00
Marco Costalba
f5e434c2d9 Fix a warning under MSVC
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-15 12:20:31 +01:00
Marco Costalba
37d551fb39 Fix parametrized direction in pawns generation
It worked by accident because we always called both directions,
but definition was wrong.

Functional change due to different generation order, but
perft numbers are the correct ones.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-15 12:13:55 +01:00
Marco Costalba
9c8c0de538 Cleanup handling of Delta enums
Ispired by Rein's code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-15 12:13:48 +01:00
Marco Costalba
fbdabe2975 Use std library to sort moves
Functional change due to the fact that now pick_best() is
stable, but should be no change in strenght.

Example code and ideas by Rein Halbersma.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-14 12:43:13 +01:00
Marco Costalba
0cfb30e5be Fix icc's "unreachable code" warning
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-11 11:17:50 +01:00
Marco Costalba
c081a81daf Teach to_fen() about Halfmove and Fullmove number
And also fix the last '/' at the end of the piece placement field.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-03 12:08:02 +01:00
Marco Costalba
155bed18f5 Use MoveList also in Position::move_is_pl_slow()
And rename it in Position::move_is_legal()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-03 11:00:28 +01:00
Marco Costalba
95d9687d95 Retire move_is_short_castle() and move_is_long_castle()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-03 10:27:15 +01:00
Marco Costalba
ff41b8df76 Restore startpos_ply_counter() instead of full_moves()
And pass correct currentPly to TimeManager::init().

This restores old behaviour, in particular now black has
a different timing than white becuase is no more:

currentPly = 2 * fullMoveNumber;

but becomes

2 * (fullMoves - 1) + int(sideToMove == BLACK)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-03 06:54:46 +01:00
Marco Costalba
53ccba8457 Introduce and use struct MoveList
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-02 14:04:33 +01:00
Marco Costalba
7ac6e3b850 Remove MSVC debug window hack in bench
Interference with profile-build under mingw

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-02 11:52:22 +01:00
Marco Costalba
d15217b953 Rearrange structs to avoid internal padding
Found with gcc -Wpadded gcc option.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-02 11:01:12 +01:00
Marco Costalba
bc54a44010 Revert PHQ-2
No clear advantage again standard, possibly we will
retest before to release.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-07-02 09:47:06 +01:00
Marco Costalba
3f806df0ca Small touches to do/undo_castle_move()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-30 20:04:46 +01:00
Marco Costalba
f3799aa750 Better document generate_castle_moves()
No functional change also in Chess960

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-30 19:58:44 +01:00
Marco Costalba
30ca6935a5 Small tweaks to search()
No functional change also in faked split mode

To be sure verified in real games with 4 threads TC 2"+0.1
After 11125 games 2497 - 2469 - 6159 ELO +0 (+- 4.4)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-30 06:54:09 +01:00
Marco Costalba
f25582d4b8 Remove duplicated enum Phase definition
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-29 17:54:12 +01:00
Marco Costalba
fb2fdb21d3 Retire find_checkers()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-28 18:01:51 +01:00
Marco Costalba
31a0d2200c Retire square_is_weak()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-28 17:22:33 +01:00
Marco Costalba
e0a00c4996 Retire one piece_list() overload
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-28 17:11:03 +01:00
Marco Costalba
e5077dc11e Rename pieces_of_color() in pieces()
To be uniform with other overloads.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-28 17:10:44 +01:00
Marco Costalba
01a191936e Retire redundant square_is_occupied()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-28 17:10:27 +01:00
Marco Costalba
8094b2add8 Change Position::pst() signature
To be more clear what is the underlying table.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-28 17:10:18 +01:00
Marco Costalba
ffb638995d Fix Shredder-FEN regression in from_fen()
Fix also an incredible 3% speed regression by an almost
never called function. I guess this is due to mingw very low
quality standard libraries implementation.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-28 17:10:05 +01:00
Marco Costalba
c2a4856f9e Greatly simplify castling rights handling
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-27 19:26:30 +01:00
Marco Costalba
c9b24c3358 Assume input FEN string is correct in from_fen()
And also tolerate a 0 value for full move number.

Revert BUG_41 patch, now we set initial King file only
if a castling is possible, so we don't need the fix
anymore in case of correct FEN.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-27 12:08:12 +01:00
Marco Costalba
9305983018 Fix a bug in Position::is_ok()
If we cannot castle castleRightsMask[] could be not valid,
for instance when king initial file is FILE_A as queen rook.

In this case castleRightsMask[] at initialQRFile is different
from the expected (ALL_CASTLES ^ WHITE_OOO).

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-26 11:44:12 +01:00
Marco Costalba
ae2f5f25cd Rename type_of_piece() and color_of_piece()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-26 10:52:42 +01:00
Marco Costalba
923b14afaa Retire Position::color_of_piece_on()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-26 10:37:13 +01:00
Marco Costalba
a9782b94e6 Retire Position::type_of_piece_on()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-26 10:28:54 +01:00
Marco Costalba
351ef5c85b Retire seeValues[] and move PieceValue[] out of Position
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-26 10:19:37 +01:00
Marco Costalba
be2925b3c5 Restore user weights to 100
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-24 10:31:03 +01:00
Marco Costalba
ace27831ee PHQ settings for King and Mobility
See:
http://talkchess.com/forum/viewtopic.php?t=39327

After 8130 games on QUAD at 20"+0.1
1342 - 1359 - 5429 ELO +0 (+- 4.4)

Tried also version with just king settings changed:
After 5932 games 962 - 1052 - 3918 ELO -5 (+- 5.2)

And with just mobility settings changed:
After 4114 games 618 - 619  - 2877 ELO +0 (+- 5.9)

Frank has tested only 1200 games, but at longer TC and
against many engines, so because PHQ results are not worst
than other combination and not worst than original let's
commit his version.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-24 09:47:30 +01:00
Marco Costalba
6a1707889c Fix move_is_capture() to detect capture promotions
We miss to account as a capture a promotion capture !

Incredible bug in this critical function that is here
since a long time (b50921fd5c of 21/10/2009 !!)

This patch fixes the bug and readds the faster
move_is_capture_or_promotion() that slightly increases
overall speed.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-23 12:09:31 +01:00
Marco Costalba
1c42d15340 Rewrite how uci info is sent to GUI
It is now much more modular than before and also we
always send the seldepth when we send the depth, this
avoids to make seldepth disappearing from GUI at the
start of a new iteration.

Print also fails high/low pv lines at high enough
search depths.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-22 17:32:22 +01:00
Marco Costalba
fe26967ea0 Simplify sliding_attacks()
Easy, almost trivial simplification, I don't understand
how I missed this before !!

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-21 19:01:00 +01:00
Marco Costalba
e7413417ce Retire ksq from CheckInfo
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-21 12:13:26 +01:00
Marco Costalba
018022b866 Use CheckInfo to store pinned bitboard
This trivial change gives an impressive 2,5% speedup !!!!

Also retire one unused move_gives_check() overload.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-20 12:09:11 +01:00
Marco Costalba
7ea38e980b Omit mate distance pruning at root
Restore original behaviour, before root unification and
remove a now useless ugly hack for alpha in multi-pv case.

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-18 17:11:09 +01:00
Marco Costalba
8173d92dd2 Use an array index instead of an iterator in root list
It is not correct to use an iterator stick on a vector that
is sorted becuase iterator is invalidated in general case.

It happens to work by accident because iterators are implemented
as pointers and so they behave in the same (correct) way then
using array indices, but the latters are the correct thing to use.

Also better document the code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-18 08:03:59 +01:00
Marco Costalba
808a4fe817 Remove useless bestValue = alpha assignement
It is a fossil from the root_search() era, no more
needed today.

Spotted by Onno

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-15 12:49:59 +01:00
Marco Costalba
72760c05c6 Try only recaptures in qsearch if depth is very low
This avoids search explosion in qsearch for some
patological cases like:

r1n1n1b1/1P1P1P1P/1N1N1N2/2RnQrRq/2pKp3/3BNQbQ/k7/4Bq2 w - - 0 1

After 9078 games 20"+0.1 QUAD:
Mod vs Orig 1413 - 1319 - 6346 ELO +3 (+- 4)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-15 12:17:49 +01:00
Marco Costalba
15683034a7 Speed up kpk initialization
The trick is to classify more position at first cycle,
so to reduce following work. Speed up is of about 50% !

Also some cleanup while there.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-15 12:11:35 +01:00
Marco Costalba
4c9d570e43 Use Carry-Rippler trick to speed up magics
Nice trick discovered on:

http://chessprogramming.wikispaces.com/Traversing+Subsets+of+a+Set

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-15 02:15:41 +01:00
Marco Costalba
fc519ca74a Retire init_piece_square_tables()
Merge in init_zobrist() and rename the latter.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-13 17:28:09 +01:00
Marco Costalba
a24c0a736c Increase LMR limit by one ply
Seems there is no regression so prefer to prune less.

After 8278 games
Mod vs Orig 1246 - 1265 - 5767 +0 ELO (+- 4.2)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-12 21:14:07 +01:00
Marco Costalba
b3a0b389d2 Better self-document init_zobrist()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-12 11:50:19 +01:00
Marco Costalba
47959c56fd Fix initialization of BSFTable[]
We should start from i = 0, it works by accident because
static storage BSFTable[] is init to zero by default.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-12 11:37:02 +01:00
Marco Costalba
aee75ae105 Don't update_gains() in qsearch
Is almost unuseful becuase captures are skipped.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-12 07:09:30 +01:00
Marco Costalba
4b8a7f2793 Fix score_captures() for the case of capture promotions
In case we have more than one promotion move, prefer
the one that captures the biggest piece.

Almost no functional change, anyhow I don't expect any
ELO change, it is just the correct thing to do.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-11 22:12:13 +01:00
Marco Costalba
89ec224cb9 Retire some unused functions
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-11 15:56:12 +01:00
Marco Costalba
b21a5e2f06 Micro-optimize castling handling in do_move()
And better self-document the code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-11 15:31:39 +01:00
Marco Costalba
735cac5d53 Retire PieceLetters struct
Use a much simpler std::string instead.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-10 17:12:10 +01:00
Marco Costalba
bc4f3155ae Better document move_to_san()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-10 11:59:53 +01:00
Marco Costalba
a21a110188 Revert refinedValue in ProbCut
It seems much worst in number of nodes seacrhed to reach
the depth and anyhow does not give any advantage to the
Onno's oroginal one.

So revert by now and perhaps readd when we find something
clearly better.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-09 21:59:24 +01:00
Marco Costalba
b414fc0dfd Use double rotate for magic generation
Allow to choose among 4096 instances of pseudo-random
sequences instead of the previous 64 so the probability
to find a better sequence increases and actually we have
a much better 64 bit case and we can also use the 64 bit
version of pick_magic() also for 32 bits and althoug sub
optimal, because now we can have more choices results are
even slightly better also for 32 bit.

Use also a faster submask().

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-09 18:47:58 +01:00
Marco Costalba
e0215f3222 Use refinedValue in ProbCut condition
After 12613 games at 20"+0.1 on QUAD
Mod vs Orig 1870 - 1863 - 8880 ELO +0 (+- 3.3)

So no performance change but it is a code semplification
and also is more easy to understand.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-08 18:03:26 +01:00
Marco Costalba
3dfff5bdae Small pick_magic() touches
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-08 17:59:47 +01:00
Marco Costalba
d632e77058 Find magics on the fly
Good result for 32 bit case where computation is very fast,
still not satisfying on 64 bit case where the magics seem
a bit harder to get.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-07 20:59:12 +01:00
Marco Costalba
6d665b7f78 Partially revert previous patches
Due to a -2% speed penalty. This patch takes the best
of the previous series without the regression due to
introduction of Magic struct.

Speedup against previous revision is of almost 3% !!!!

No functional change both in 32 and 64 bits.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-06 11:56:17 +01:00
Marco Costalba
b1b0c64046 Skip offset calculation in slider attacks
Another small simplification and micro optimization.

No functional change in both 32 and 64 bits.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-05 15:01:22 +01:00
Marco Costalba
670cee44f0 Get rid of Shift[] tables
We can calculate them counting the masks bits.

Also small tweak to sliding_attacks()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-05 14:13:41 +01:00
Marco Costalba
3092f0c646 Better name and document magic botboard stuff
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-05 12:28:36 +01:00
Marco Costalba
2f6142cb9b Try to keep memory access in the same cache line
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-05 12:27:53 +01:00
Marco Costalba
3b2bcee0a8 Skip draw by repetition check in qsearch
Cut in half the time spent in pos.draw() that accounts
for a whopping 1% of total time !

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-04 11:29:54 +01:00
Marco Costalba
91407f4f74 Move bitboards initializations under one function
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-04 11:05:12 +01:00
Marco Costalba
025d57855a Calculate Bit Scan tables at initialization
Instead of hard-coding them.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-04 09:59:18 +01:00
Marco Costalba
8647fbd6ed Do not sort negative non captures at low depth
Speedup of the whole 3 patch series is of 2,5% !!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-04 06:35:24 +01:00
Marco Costalba
811037c845 Split non capture in two sets when ordering
But keep same ordering. This patch is prerequisite
for future work.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-03 22:10:23 +01:00
Marco Costalba
181cc3f93f Inline extension()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-03 13:14:03 +01:00
Marco Costalba
91b919fd1d Use TT also in Root nodes
And other small stuff ti be tested in SMP

No functional change in single thread.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-03 12:59:50 +01:00
Marco Costalba
5ff6289afd Microoptimize generate<MV_EVASION>
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-06-02 12:49:40 +01:00
Marco Costalba
fca0a2dd88 New extended probcut implementation
Here the idea is to test probcut not only after bad
captures, but after any bad move, i.e. any move that
leaves the opponent with a good capture.

Ported by a patch from Onno, the difference from
original version is that we have moved probcut after
null search.

After 7917 games 4 threads 20"+0.1
Mod vs Orig: 1261 - 1095 - 5561 ELO +7 (+- 4.2) LOS 96%

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-30 20:49:04 +01:00
Marco Costalba
462a39ec49 Fix SAN disambiguation bug
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-29 10:52:03 +01:00
Marco Costalba
70125a3be0 Rename PH_TT_MOVES in PH_TT_MOVE
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-29 09:17:03 +01:00
Marco Costalba
cff8877a1a Retire mateKiller
Practically useless:
After 6456 games 1281 - 1293 - 3882 ELO +0 (+- 5.5)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-28 22:50:22 +01:00
Marco Costalba
8f51f09de7 Unify MovePickerExt template parameters
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-28 13:23:32 +01:00
Marco Costalba
013dc43d5d Unify search() template parameters
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-28 12:44:39 +01:00
Marco Costalba
853e2a9495 Fix moveCount after legality check delay
We really want PV moves and also Split Point moves to be
legal to avoid messing the move counter and corresonding
PV move detection or shared Split Point's counter variable.

This fixes a real bug where a position with only one move
allowed returns bestValue == -VALUE_INFINITE if the move
turns out to be illegal.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-28 11:16:00 +01:00
Marco Costalba
4c3a000211 A bit of reformatting after previous series
And some documentation update.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-24 21:24:40 +01:00
Marco Costalba
9884573561 Test for legality only after futility pruning
Although there is a small functional change it seems
an improvment of about 2% in speed !

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-23 20:21:02 +01:00
Marco Costalba
4b232f5ddc Move legal check out of MovePicker
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-23 20:20:52 +01:00
Marco Costalba
45ce92b89c Rename move_is_legal() in move_is_pl()
We disjoint pseudo legal detection from full legal detection.

It will be used by future patches.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-23 20:20:42 +01:00
Marco Costalba
bc86668ba4 Output debug info to cerr
So to be clearly visible when redirecting stdout to /dev/null

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-23 20:20:31 +01:00
Marco Costalba
0783211950 Fix a shadowed variable warning under gcc
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-23 20:20:19 +01:00
Marco Costalba
13fe7ee4df Bug wrong evasion detection for king moves
When we are in check and we move the king then testing with
pl_move_is_legal(m, pinned) is not enough becuase we cannot
rely on attackers_to() but we have to explicitly remove the
king form the occupied bitboard to catch as invalid moves like
b1a1 when opposite queen is on c1.

Our move generator already produces correct evasions so we
just need to add the extra verification to move_is_legal().

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-22 11:51:28 +01:00
Marco Costalba
21fc66c246 Add file distance condition in move_is_legal()
Found another missed control in move_is_legal() thanks to
brute force testing.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-22 09:49:44 +01:00
Marco Costalba
ff9e49bac9 Remove useless casts in types.h
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-22 08:52:39 +01:00
Marco Costalba
90e83fa879 Promotion piece must be empty if is not a promotion
Add a new check in  move_is_legal()

Avoid useless casting in move.h while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-22 08:48:19 +01:00
Marco Costalba
3ef4fdeaa0 Introduce MovePicker::isBadCapture() and use in probcut
Small functional change due to the fact that now we skip
probcut on evasions.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-21 10:40:36 +01:00
Marco Costalba
13d8af1852 Correctly handle castle in see()
Suggested by Onno.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-20 06:58:53 +01:00
Marco Costalba
5b7a141065 Fix brekage from previous patches
It is interesting the fact that we need to test for
move_is_castle(m) anyway and not relying on testing
if destination square is attacked. Indeed the latter
condition fails if the castling rook is attacked,
castling is coded as "king captures the rook" but it
is legal in that case.

Verified no functional change with beginning of the series.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-18 07:05:36 +01:00
Marco Costalba
89a06f6651 Micro-optimize pl_move_is_legal()
Remove the check for castling moves because it is
already implicit in the check for king moves and castling
is so rare that doing the check is just a slow down.

Thanks to Marek Kwiatkowski.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-17 23:47:26 +01:00
Marco Costalba
a2e924039b Retire move_is_capture_or_promotion()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-17 23:39:14 +01:00
Marco Costalba
85d1f9c5ec Fix move_is_capture() definition
The structure of move is changed so should also the two
functions. It happens that it works by accident !

Bug spotted by Marek Kwiatkowski

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-17 23:31:40 +01:00
Marco Costalba
e444e18d2b Retire test for king moves in see()
We already test this condition in see_sign() and
so it is almost always a redundant verification.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-17 12:25:49 +01:00
Marco Costalba
ad0fdf0da6 Retire Position::see(Square from, Square to) overload
Alomst unuseful.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-17 12:17:57 +01:00
Marco Costalba
fbbc7e421c Prefer an assert to a comment in position.h
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-17 12:17:48 +01:00
Marco Costalba
1cc42ac9e4 Let 'make' with no arguments to show compilation options
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-17 12:17:38 +01:00
Marco Costalba
6624105b5b Prefer ttMove to tte->move() in search()
Avoids aliasing problems due to TT overwrites.

Node changes becuase of IID.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-17 12:17:29 +01:00
Marco Costalba
de58594b0f Use standard naming conventions in book.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-08 11:50:38 +01:00
Marco Costalba
d5f0b91c06 Reintroduce operator>>() in Book class
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-08 09:15:18 +01:00
Marco Costalba
f78488bbdb Restore development version
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-08 09:11:36 +01:00
Marco Costalba
e3b23eb818 Stockfish 2.1.1
stockfish bench signature is: 6487630

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-08 08:46:33 +01:00
Marco Costalba
d494725400 Spell fix in evaluate.cpp
Spotted by Eelco.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-07 10:08:53 +01:00
Marco Costalba
2535dc1340 Fix reading of book file
Bug is subtle because appears only under MSVC 32 bits in
optimized version, hence was missed before.

Bug is due to the fact that evaluation order of terms of a
sum is undefined by the standard, so in get_int() we have:

return 256 * get_int<n-1>() + bookFile.get();

And if get() is evaluated before get_int() we have a corrupted
key.

The patch rewrites the code in a more natural and predictable way.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-07 09:51:33 +01:00
Marco Costalba
339bf9b7e1 Remove redundant assignment in search()
It is already assigned few lines before.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-05 12:16:26 +01:00
Marco Costalba
bb86691a0d Restore development version
No functional change.
2011-05-05 06:35:42 +01:00
Marco Costalba
f7fee4c616 Fix a warning in debug mode
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-03 19:29:21 +01:00
Marco Costalba
315c58354e Stockfish 2.1
stockfish bench signature is: 6487630

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-03 12:11:19 +01:00
Marco Costalba
5ef2b8c494 Reintroduce permanent PV entries in TT
We are now ready to release so restore this
improvment before 2.1

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-03 12:11:10 +01:00
Marco Costalba
9c5a53ca45 Update Readme.txt to 32 threads and bsfq on Windows
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-03 12:11:02 +01:00
Marco Costalba
b1929960f9 Fix bug in evaluate_passed_pawns()
If blockSq is already on rank 8, blockSq + pawn_push(Us) is on rank 9,
outside of board. It does not make sense to measure king distance to
a field outside the board.

Bug spotted by Fruity:
http://open-chess.org/viewtopic.php?f=5&t=1156&start=10

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-03 12:10:53 +01:00
Marco Costalba
8447248705 Retire "Pawn Structure" UCI option
Almost useless for the user and now is in sync with
the material value that is already weighted.

A small speedup of 0,4% because we avoid an apply_weight()
call in a fast path.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-02 17:50:46 +01:00
Marco Costalba
a10487b074 Rename stuff in evaluate.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-02 17:50:37 +01:00
Marco Costalba
db31efb8a6 Additional tweaks in evaluate_unstoppable_pawns()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-01 12:15:40 +01:00
Marco Costalba
75acd52415 Remove redundancy in evaluate_unstoppable_pawns()
Spotted by Fruity
http://open-chess.org/viewtopic.php?f=5&t=1156&start=20

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-01 10:31:27 +01:00
Marco Costalba
18c9b5ee86 Small reformat in evaluate_unstoppable_pawns()
Also simplify tracing because evaluate_unstoppable_pawns()
return always zero if both colors have non pawn material.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-01 09:58:45 +01:00
Marco Costalba
33bd67e052 Update polyglot.ini
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-05-01 07:49:40 +01:00
Marco Costalba
4dc7ba1619 Rename check related functions
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-29 18:56:48 +01:00
Marco Costalba
92d70fb667 Small renaming in thread.cpp
To better self document the code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-29 13:08:35 +01:00
Marco Costalba
0bf475ec55 Rename Option in UCIOPtion
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-29 13:08:27 +01:00
Marco Costalba
bb7713c8e9 Limit history range to +-2000
Extensive test series on tweaking history limit and bonus
formula. At the end this was the best.

After 11959 games:

Mod vs Orig 2087 - 1934 - 7938 ELO +4 (+- 3.7) LOS 92%

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-28 08:00:34 +01:00
Marco Costalba
e656ddcf18 Perft counts leaf nodes not generated moves.
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-27 23:21:46 +01:00
Marco Costalba
1d0159075e Use probe() as name for looking up into an hash table
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-27 07:31:51 +01:00
Marco Costalba
321320b081 Tidy up uci.cpp and siblings
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-26 13:23:47 +01:00
Marco Costalba
ca9d40c145 Move OpeningBook and RK where are actually used
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-26 13:23:39 +01:00
Marco Costalba
03f4d1e8d6 Fix a compile error with gcc
It seems gcc does not like an extra semicolon.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-25 22:59:56 +01:00
Marco Costalba
87f2b52ace Move MovePickerExt specializations away from headings
This unclutters a bit the heading part of search.cpp

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-25 13:35:13 +01:00
Marco Costalba
09d01ee9dc Tidy up benchmark.cpp
Node count is different just becuase now we don't log on
"bench.txt" file anymore so that we avoid some calls to
pretty_pv() that calls Position::do_move().

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-25 12:07:30 +01:00
Marco Costalba
05cfb00f26 Large API rename in ThreadsManager
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-25 10:30:39 +01:00
Marco Costalba
339e1b49f6 Don't allocate MAX_THREADS hash tables if not necessary
This prevent crashing on mobile devices with limited RAM,
currently with MAX_THREADS = 32 we would need 44MB that
could be too much for a poor cellphone.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-24 19:23:07 +01:00
Marco Costalba
fecefbb99c Move pawn and material tables under Thread class
This change allows to remove some quite a bit of code
and seems the natural thing to do.

Introduced file thread.cpp to move away from search.cpp a lot
of threads related stuff.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-24 17:07:22 +01:00
Marco Costalba
c9d7e99de6 Rename MOVES_MAX in MAX_MOVES
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-24 08:54:36 +01:00
Marco Costalba
ccd5ccbcdb Retire extensions as UCI option
There is no real need why an user should change these values.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-24 08:52:16 +01:00
Marco Costalba
633c83f648 Document why we use per-thread pawn and material tables
Arisen from a discussion on talkchess.

No fnctional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-24 08:18:39 +01:00
Marco Costalba
fe213d30fa Fix some comments in early stop detection
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-23 15:52:51 +01:00
Marco Costalba
8b2adcf99e Retire UseLogFile in search.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-23 15:00:44 +01:00
Marco Costalba
1d368bbbdc Introduce and use SearchLimits
Pack a bit of global variables related to search limits in
a single struct.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-23 13:11:03 +01:00
Marco Costalba
bbfe452f85 Use move_is_special() in pawn endgame condition
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-22 12:30:51 +01:00
Marco Costalba
8bf9dc8254 Retire SearchStartTime global
Use a static variable inside current_search_time() instead.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-22 12:30:43 +01:00
Marco Costalba
f349143a6b Reduce loops in init_threads() and exit_threads()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-22 12:30:35 +01:00
Marco Costalba
79e50a2fbf Move wake_sleeping_thread() to Thread class
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-20 12:05:07 +01:00
Marco Costalba
2c317d7b28 Correctly implementg selDepth feature
Send to GUI the deepest search depth apart from
qsearch of the PV line.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-20 12:04:59 +01:00
Marco Costalba
fdc9f8cbd7 Move sleepLock and sleepCond under Thread
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-20 12:04:52 +01:00
Marco Costalba
2e6839c9a0 Increase risk of blunders at low skill levels
According to Heinz's tests current setup is in fact too
strong for weak players. This seems the best according
to his tests.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-20 12:04:43 +01:00
Marco Costalba
67b0d0b1cc Use only history to score non captures
It seems gain is practically unuseful, so remove.

After 13554 games:
Mod vs Orig 2252 - 2319 - 8983 ELO -1 (+- 3.4)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-17 22:32:12 +01:00
Marco Costalba
068561f86a Small simplification in scale_by_game_phase()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-17 10:31:26 +01:00
Marco Costalba
076b62310e Move ply to SearchStack
Shrink search() signature for better readibility.

We get also a nice 1.3% speed increase.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-17 08:59:54 +01:00
Marco Costalba
5ba85ef441 Remove one indentation level in get_next_move()
Small renaming and fix some comments.

No functional and no speed change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-16 12:57:06 +01:00
Marco Costalba
c13b53a514 Code style in tt.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-16 10:49:35 +01:00
Marco Costalba
a860576493 Better self-document LMR reduction() formula
Suggested by Onno

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-16 10:49:27 +01:00
Marco Costalba
786564068b Promote OptionsMap to a class
And add a bit of documentation too.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-16 10:49:20 +01:00
Marco Costalba
6056a43419 Fix a stale comment
Spotted by Onno

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-16 10:21:31 +01:00
Marco Costalba
f8e767388b Remove src/COPYING file
It is enough the one in the base directory

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-14 07:06:56 +01:00
Marco Costalba
b41b590457 Remove "divide by zero" workaround
It is now useless because of the condition at the beginning.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-14 07:04:32 +01:00
Marco Costalba
7f367e6019 Cleanup debug counters
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-13 18:51:56 +01:00
Marco Costalba
54f1c383d3 Move move_is_legal() under Position class
It is a more logical place than in move generation file.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-13 13:18:19 +01:00
Marco Costalba
fe8f5b3497 Some more cleanup in endgame.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-13 13:17:21 +01:00
Marco Costalba
6608a16a6a Fix some warnings and a compile error with icc
Unfortunatly icc does not understand that weakerSide and
strongerSide belongs to the base class :-(

So we have define them in the derived class.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-12 08:05:41 +01:00
Marco Costalba
b5d5646c84 Move EndgameFunctions to endgame.cpp
And cleanup code while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-11 21:25:24 +01:00
Marco Costalba
08c464c690 Increase MaterialTableSize 8 times
Now that we prefetch in material hash table we
can increase its size and gain something.

Hit rate is now of 98% from 92%

Speedup of 0.8%

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-11 18:15:40 +01:00
Marco Costalba
f28ddbb852 Introduce and use NoPawnsSF[] in material.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-11 18:11:16 +01:00
Marco Costalba
c88eebc989 Tempeltize material imbalance
Speedup of almost 1%

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-11 12:35:54 +01:00
Marco Costalba
7a84b8ca34 Sync material.h with pawns.h
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-11 12:24:10 +01:00
Marco Costalba
6738b65be9 Prefetch also material tables
Prefetch both pawn and material tables in do_move() and
prefetch always, not only after a pawn move or a capture.

Speed up of 0,7%

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-11 12:24:02 +01:00
Marco Costalba
2f1935078d Assorted code style and comments in pawns.cpp and pawns.h
The only interesting thing is that a backward or isolated
pawn cannot be a candidate passer, so code this condition.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-10 12:16:36 +01:00
Marco Costalba
8e71ee7ec6 Retire mate threat extension
It seems we have a lot of totally useless code !

After 8577 games 1504 - 1451 - 5622 ELO +2 (+- 4.4)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-08 07:48:05 +01:00
Marco Costalba
9bee5f51d8 Fix a compile error in debug mode
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-07 08:09:41 +01:00
Marco Costalba
927f1b0bd3 Assorted code style and comments in search.cpp
Nothing really serious....

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-05 19:00:40 +01:00
Marco Costalba
04108d4541 Added -Wshadow option and fixed resulting warnings
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-04 12:11:01 +01:00
Marco Costalba
f7ef48b478 Teach SF to blunder
Add blunder cabability to skill level feature.

The idea is that instead of choosing the best move at the end
of the ID loop, we now do this at a randomly chosen sampling depth
dependent on SkillLevel, so that at low skill levels we sample when
ID loop has reached only a small depth and so we have an higher
probability to pick up a blunder.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-02 10:04:34 +01:00
Joona Kiiski
2e8998eac9 Use prob cut search to prune bad captures
The idea is to try a shallow search with reduced beta
on bad captures so to quickly prune them out in case
are really bad.

After 5529 games 966 - 868 - 3695  ELO +6 (+- 5.4) LOS 91%

Tested also version without upper limitation to 8 plies:

After 8780 games 1537 - 1398 - 5850  ELO +5 (+- 4.3) LOS 93%

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-02 08:39:54 +01:00
Marco Costalba
8402b40341 Retire recapture extension also for PvNode
Seems that extension is useless.

After 10105 games
Mod vs Orig 1738 - 1702 - 6665  ELO +1 (+- 4)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-01 22:02:18 +01:00
Marco Costalba
408fdcc93f Use a constant instead of value_mate_in(PLY_MAX)
And also apply the same to value_mated_in(PLY_MAX)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-01 21:46:45 +01:00
Marco Costalba
b27e237b04 Retire value_is_mate()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-01 21:46:34 +01:00
Marco Costalba
f5b8db7a1e Simplify wait_for_stop_or_ponderhit()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-01 21:46:27 +01:00
Marco Costalba
8d4caebabe Retire update_killers()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-04-01 21:46:12 +01:00
Marco Costalba
d173285da5 Fine tune skill level
Rescaled Skill level from 0 to 20. At level 19 is still
comparable with Crafty 20.14, while at low levels strength
increase is now less steep.

Thanks to Joona and Heinz for testing and valuable
comments.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-28 13:09:13 +01:00
Marco Costalba
41fe70d703 Add "Skill level functionality
It is now possible to adjust skill level of Stockfish
from 10 (full strength) to 0.

Skill adjustment is done in such a way that is CPU speed and
time control largely independent, at least at low skills. It
means that given a skill we have same play level on a mobile
phone and on a super OCTAL CPU, at 1' per game or at 180'.

At skill 9 strength is that of an average engine, I have used
Crafty 20.14 to tune and we are more or less there. At skill 0
engine is pretty weak but still shows a realistic play.

When skill is not used we don't have any impact on the regular
code.

Idea to use MultiPV is from Heinz van Saanen, implementation and
formulas by me.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-27 11:50:22 +01:00
Marco Costalba
d372f2e39a Fix a compile error with icc
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-26 09:25:26 +01:00
Marco Costalba
4270aec558 Send PV line to GUI only after resolving a fail high
This is how Shredder, Rybka and others do and
avoids user is confused by a fail high (sent to GUI)
followed by a fail low (not sent).

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-24 13:21:54 +01:00
Marco Costalba
f427acbd27 Triviality in position.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-24 13:21:47 +01:00
Marco Costalba
87ca13a79a Retire move_ambiguity() altogether
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-23 13:09:04 +01:00
Marco Costalba
d52d91064f Simplify move_ambiguity()
And additional small touches in move.cpp

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-22 13:23:41 +01:00
Marco Costalba
920b1abede Do not send ponder move if we don't have it
Has been reported by Justin Blanchard that
this creates problems on some buggy GUI.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-19 16:08:19 +01:00
Marco Costalba
5ea08e79c4 Use intrinsic in pop_1st_bit() under MSVC 64 bits
Around 1% speedup when compiled with MSVC 64

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-17 14:29:09 +01:00
Marco Costalba
635be39acf Additional cleanup in bitbase.cpp
Also better document what code does.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-12 18:22:22 +01:00
Marco Costalba
c1c0984452 Move KPKBitbase[] where it belongs
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-12 12:12:41 +01:00
Marco Costalba
d653aeca05 Fix a couple of issues in bitbase.cpp
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-12 11:22:02 +01:00
Marco Costalba
09d217bff7 Reintroduce initialization of some bitboards
With off-by-one bug in InFrontBB[] loop fixed.

Also use int instead of File to workaround a bug
in mingw 4.4.0 in first loop that cycles forever.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-10 19:23:39 +01:00
Marco Costalba
d9113d127b Rename NonSlidingAttacksBB[] in StepAttacksBB[]
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-10 08:10:26 +01:00
Marco Costalba
c2511243b4 Update copyright notes in rkiss.h
New info after a thread on talkchess:

http://www.talkchess.com/forum/viewtopic.php?t=38313

and some emails exchange with Heinz.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-10 08:08:34 +01:00
Marco Costalba
d85cf6d9c3 Revert previous patch due to miscompile under gcc
I need to understand what's going on, in the
meantime revert.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-10 08:08:04 +01:00
Marco Costalba
a617b03875 Change initialization of some bitboards
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-08 19:44:19 +01:00
Marco Costalba
c980163316 Increase MAX_THREADS to 32
No speed regression after 8731 games:
Mod vs Orig 1394 - 1342 - 5995  ELO +2 (+- 4.1)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-08 13:16:33 +01:00
Marco Costalba
76506bd3d1 Introduce and use rot() in rkiss.h
Also fix indentation.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-07 19:04:54 +01:00
Marco Costalba
9069193125 Simplify aspirationDelta update rule
After 7522 games:
Mod vs Orig 1229 - 1148 - 5145  ELO +3 (+- 4.5) LOS 83%

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-02 22:01:30 +01:00
Marco Costalba
0c775fae4b Be sure to read options before to call trace_evaluate()
Otherwise in case we change an option with setoption and
then ask for "eval" command the evaluation is not updated.

Spotted by Justin Blanchard.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-03-01 13:32:42 +01:00
Marco Costalba
1f73a9ed63 Fix aspiration corner case
Fix a corner case where we start aspiration window and
suddendly we get a VALUE_KNOWN_WIN / MATE score, this makes
aspiration to blow up in a series of researches loops.

Exit aspiration loop in that case.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-28 20:17:57 +01:00
Marco Costalba
af236373cb Remove a FIXME in id_loop()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-28 20:16:22 +01:00
Marco Costalba
ce2845d333 Score root move list during first iteration
Use first iteration to get a proper startup score
and possibly detect an easy move.

After 5180 games:
Mod vs Orig 847 - 823 - 3510  ELO +1 (+- 5.5)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-28 07:51:28 +01:00
Marco Costalba
204efb109b Remove an useless condition in equal SEE pruning
Because we are never in check there and evaluation cannot
return a mated value the condition is useless.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-27 09:45:54 +01:00
Marco Costalba
91a2766308 Prune moves with equal SEE in qsearch
After 5166 games:
Mod vs Orig 890 - 762 - 3514  ELO +8 (+- 5.5) LOS 96%

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-27 09:19:59 +01:00
Marco Costalba
bd33766da0 Add evaluation tracing code
This patch is based on Justin Blanchard's original
work and allows to breakdown evaluation in its sub terms and
show to the user.

Tracing code has zero speed impact when not used.

Note that tracing code is not thread-safe, but this
should not be a problem given the typical usage scenario.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-26 14:26:27 +01:00
Marco Costalba
dd718d92a7 Correctly round evaluation to grain size
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-23 23:52:51 +01:00
Marco Costalba
23cbb221b2 Depth dependant singular extension margin
After 7965 games:
Mod vs Orig 1324 - 1249 - 5392  ELO +3 (+- 4.4) LOS 81%

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-23 23:51:20 +01:00
Marco Costalba
0fcda095df Move all enum types definitions to types.h
Cleanup headers while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-23 21:52:55 +01:00
Marco Costalba
95212222c7 Retire color.h
Move contents to piece.h and square.h

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-23 18:42:45 +01:00
Marco Costalba
2ff2b59727 Rename piece_of_color_and_type() to make_piece()
To be aligned with make_square()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-23 18:42:35 +01:00
Marco Costalba
5b2ac7590c Retire piece_type_from_char()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-23 18:42:27 +01:00
Marco Costalba
2511386155 Triviality in main.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-23 18:41:58 +01:00
Marco Costalba
deb212cb05 Retire enum SquareDelta
Use Square instead. At the end is the same because we were
anyway foreseen operators on mixed terms (Square, SquareDelta).

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-23 18:41:35 +01:00
Marco Costalba
aa40d0a917 Small simplifications in square.h
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-23 18:41:27 +01:00
Marco Costalba
b3108547de Introduce and use speed_to_uci()
And retire nps()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-19 13:31:35 +01:00
Marco Costalba
706b44a966 Rename SplitPoint parentSstack
Now that we don't have anymore a search stack array in
SplitPoint we can rename this data member to somthing more
usual.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-18 17:04:55 +01:00
Marco Costalba
823a5918e7 Retire SearchStack sstack[] from SplitPoint
Use a local variable instead. To make it work we need to
correctly init next ply search stack at the beginning of the
search because now that ss is allocated on the stack instead
of on the global storage it contains garbage.

As a side effect we can peform a fast search stack
init in id_loop().

With this patch size of SplitPoint goes from 71944 to 136 bytes,
and consequently size of Thread goes from 575568 to 1104 bytes.

Finally the size of ThreadsManager that contains all the thread
info goes from 9209248 to just 17824 bytes !!

No functional change also in faked split.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-18 16:54:49 +01:00
Marco Costalba
932ae761c6 Sync Root new depth to what we do in search()
This allow us to restore the old depth 12 benchmark
and fixes one and for all the depth mess.

Test confirms no regression:
After 5658 games 892 - 924 - 3842  ELO -1 (+- 5.2)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-18 11:24:42 +01:00
Marco Costalba
29fa6f3c5f Unify best move update logic
Try to rewrite the Root case using as most as common
code as possible.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-17 09:51:22 +01:00
Marco Costalba
5815718177 Do not special case reductions for MultiPV case
Note that this introduces an asymmetry in which best move
is searched deeper then others also in MultiPV, but this is
not an error per se.

No functional change when MultiPV = 1

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-17 09:08:27 +01:00
Marco Costalba
6a19f5832a Avoid permanent PV entries in TT
This patch removes a condition that allows a PV entry to remain
in TT across games for an unlimited time.

Although this produces a nice ELO boost in the long term it
is an artifact that affects tests results bewteen version
with and without this feature.

So remove now and readd before to release because it actually
seems a strong feature.

As example a verification tournament against SF 2.0.1 starting around
+10 ELO after 4K games sligltly climbed to +21 ELO after 14K games !!!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-16 08:57:35 +01:00
Marco Costalba
4ead60e2a7 Write the LogFile only at the end of an iteration
Skip writing fail high/low sequences. Note that we don't need
fail high/low markers anymore in pretty_pv().

No functional change but some do/undo move sequences.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-13 11:45:49 +01:00
Marco Costalba
2786aed195 Spell checking fixes in search.cpp
Reported by Eelco on open-chess.org

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-12 19:06:07 +01:00
Marco Costalba
876ceb1feb Rename iteration in depth in id_loop()
And retire the redundant one.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-12 18:53:02 +01:00
Marco Costalba
29076043e0 Start to count iterations from 1
First search should be done at iteration = 1, not 2. So offset
the variable by one.

As a nice side effect now search correctly stops at PLY_MAX
included, not after searching (PLY_MAX - 1) as before.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-12 18:17:37 +01:00
Marco Costalba
aa84731fb9 Fix wrong reported depth
Interestingly this patch will make people complain search depth
is reduced against 2.0.1 ;-) but actually it is only an artifact.

Spotted by Joona.

No functional change apart from a different do / undo move
sequence due to teh fact that we don't call pv_info_to_uci()
anymore before entering id loop.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-12 17:58:25 +01:00
Marco Costalba
c006435bb4 Move sending of PV line to id_loop()
No functional change apart form move reordering because
pv_info_to_uci() performs a do / undo_move sequence.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-11 06:28:55 +01:00
Marco Costalba
141410f177 Maximum aspiration delta of 24
After 9080 games
1430 - 1342 - 6308  ELO +3 (+- 2.9)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-10 21:09:20 +01:00
Joona Kiiski
3abff79df3 Maximum aspiration delta of 64
After 9242 games
Mod vs Orig: 1483 - 1373 - 6386  ELO +4 (+- 2.9)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-09 23:52:24 +01:00
Marco Costalba
62c707e1d5 Simplify latest patches
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-06 12:41:47 +01:00
Joona Kiiski
26e7673c18 Retire some conditions from ok_to_use_TT_pv
After 4844 games 768 - 747 - 3329  ELO +2

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-02-05 11:06:08 +01:00
Marco Costalba
b366c7dc38 Use TT for pruning also in PV nodes
Biggest advantage is be able to analize positions
without "loss of memory" when goind back/forth in
a position.

Patch has proven to fix analysys problems and is even
worths some elo points.

After 5811 games Mod- Orig:
1037 - 902 - 3872 +8 ELO  (+- 3.6) LOS 97%

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-31 13:07:26 +01:00
Marco Costalba
2f6788104f Silence silly MSVC warning c4146
Warning C4146: unary minus operator applied to
unsigned type, result still unsigned.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-29 14:10:05 +01:00
Marco Costalba
69726f4df3 Remove defined(IS_64BIT) in init_sliding_attacks()
No functional change bith in 32 and 64 bits.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-29 14:06:29 +01:00
Marco Costalba
f3e0b32def Do not use <algorithm> in to_fen()
Seems there are some problems on HP-UX compiler.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-29 13:28:00 +01:00
Marco Costalba
188700d7f1 Retire obsolete reentrancy check in pos.print()
We dont' call MovePicker from print() anymore, so that
reentrancy check in now not needed.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-29 12:17:47 +01:00
Marco Costalba
9ba7f701ea Retire singleEvasion
This let us get rid of number_of_evasions()

After 5487 games
Mod- Orig: 851 - 852 - 3784 +0 ELO  (+- 3.7)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-27 07:55:04 +01:00
Marco Costalba
afae86bfb4 Add a MovePicker c'tor specialized for qsearch
This simple patch shows a speed increase of
more then 2% !

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-23 23:13:14 +01:00
Marco Costalba
f352008958 Introduce and use qsearch_scoring()
Move qsearch scoring functionality out of RootMoveList
initialization. Will be needed by future patches.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-23 10:54:16 +01:00
Marco Costalba
6849f0800e Retire InitialDepth
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-23 10:52:51 +01:00
Marco Costalba
5194b2bb06 Pass TT move instead of Rml[0].pv[0] to MovePicker
This is used for secondary scoring so it does not
changes the fact that Rml[0].pv[0] is always tried
as first anyhow.

It happens this is even a no functional change patch
becuase we reinsert PV in TT after a search so that
TT move is actually Rml[0].pv[0].

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-23 09:11:31 +01:00
Joona Kiiski
a8f457d425 Different searchedMoves system
After 8751 games on russian cluster
Mod- Orig: 1426 - 1323 - 6002  ELO +4 (+- 2.9) LOS 86%

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-23 08:36:47 +01:00
Marco Costalba
79b1a7417f Remove special Root cases
So to better spot where the differences really
count. Also add some more additional cleanup.

Harmless functional change and no regression.

After 5780 games
Mod- Orig: 931 - 955 - 3894 ELO -1 (+- 3.6)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-23 08:36:12 +01:00
Marco Costalba
b67de36671 Retire init_ss_array()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-20 19:34:25 +01:00
Marco Costalba
59c85346d2 Small cleanup in init_sliding_attacks()
No functional change both in 32 and 64 bits.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-19 19:50:44 +01:00
Marco Costalba
e8f885145b Numbers formatting in bitboard.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-19 19:50:32 +01:00
Marco Costalba
324ca87aff Use opposite_color_squares() instead of same_color_squares()
It is almost alwasy the requested test and is a bit faster too.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-19 13:50:51 +01:00
Marco Costalba
4f3fe89fb6 Retire RelativeRankBB[]
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-19 13:33:38 +01:00
Marco Costalba
45acec1865 Retire some unused functions in bitboard.h
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-19 13:33:26 +01:00
Marco Costalba
a38b14bd33 Fix some warnings under icc
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-18 18:53:19 +01:00
Marco Costalba
d91d6da3c4 Sort root moves moves in MovePickerExt
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-18 18:52:52 +01:00
Marco Costalba
5bad5fc0a7 Fix a (bestValue == -VALUE_INFINITE) assert
In case of a Root node we can leave with bestValue set
to -VALUE_INFINITE if search is stopped by the GUI and
stopReques flag is raised.

This patch fixes the issue.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-18 13:30:13 +01:00
Marco Costalba
6119e4ea37 Additional cleanup in id_loop()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-18 13:30:13 +01:00
Marco Costalba
5555b60b38 Use a global RootMoveList object instead of a pointer
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-18 13:30:12 +01:00
Marco Costalba
846087e4fb Move globals to id_loop()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-18 13:30:11 +01:00
Marco Costalba
2e2f1064ba Introduce and use MovePickerExt
A bit of template magic to restore a proper and readable moves
'while' loop that now is again 'similar' to the one that used
to be in search().

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-18 13:30:11 +01:00
Marco Costalba
392c7f2ab6 Unify root_search() step 3
Retire root_search()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-18 13:30:10 +01:00
Marco Costalba
6b8026806c Unify root_search() step 2
Enable the change: now we use search() instead of root_search()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-18 13:29:57 +01:00
Marco Costalba
299bda9ea3 Unify root_search() step 1
Teach search() to behave as a root node if requested.
Just added code, but still no functional change.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-18 13:28:34 +01:00
Joona Kiiski
998845763a Fix very theoretical History corner case
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-17 20:22:10 +01:00
Marco Costalba
842efefcad Sync root_search() with search()
This will let unification easier.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-16 13:45:34 +01:00
Marco Costalba
c17a127c42 Move fail loops out of root_search() to id_loop()
And sync root_search() with search()

After 9384 games Mod - Orig:
1532 - 1433 - 6419  ELO +3 (+- 2.8)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-16 13:45:23 +01:00
Marco Costalba
e06c99cad0 Last touches in history.h
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-15 18:03:43 +01:00
Marco Costalba
04001f776e Fix a warning with __popcnt64() intrinsics
Returns an int64_t while we want a simple int.

This occurs only when compiling with MSVC on a 64 bit platform.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-15 12:05:31 +01:00
Marco Costalba
877b468e3e Partially restore HistoryMax
Should be not useful but better safe than sorry.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-15 11:31:14 +01:00
Marco Costalba
13a42284b6 Move Min() and Max() macros to types.h
As usual a bit of cleanup while there...

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-15 11:00:00 +01:00
Marco Costalba
3bb1ab34e4 Clarify we want Score and Value to be integers
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-15 10:37:36 +01:00
Marco Costalba
7faeab0878 Retire history.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-15 10:02:45 +01:00
Marco Costalba
2052407090 Retire HistoryMax
Infact we don't use it anymore already.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-15 09:30:39 +01:00
Joona Kiiski
d6fdd4f6d9 Set HistoryMax infinitely high
Respin this old idea. Earlier we tried only
with < 1000 games and result was inconclusive.

After 5845 games
Mod vs Orig: 935 - 936 - 3974 ELO (+-3.6)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-14 19:13:22 +01:00
Marco Costalba
b85bcc039c Simplify from_fen()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-14 12:56:31 +01:00
Marco Costalba
62cd133b3a Initialize killers at ss+2 also in root_search()
After 4955 games:
Mod - Orig: 786 - 768 - 3401 +1 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-14 07:27:06 +01:00
Marco Costalba
6442981cb6 Fix an hang on 32 bits while allocating big TT table
If size_t is defined as a 32 bit quanitity then we have an
overflow in the left term of the while condition if mbSize
is bigger then 2048.

For instance if mbSize is 2049 then when newSize will reach
0x80000000 (2048MB) comparison is still true, 'while' loops
again and we have an overflow in the expression (2*newSize)
so that result is 0 and at that point 'while' keeps looping
forever hanging the application.

This patch fixes the bug and also makes operator new do not
throw an exception upon failure but return a NULL pointer
instead.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-13 22:03:18 +01:00
Marco Costalba
d4b92ae9a0 Set unbuffered I/O also for C standard library
In input_available() we use function select(), so
we have to set as unbuffered also C library I/O
functions otherwise we can miss some input.

For instance in case GUI sends "go infinite\nstop\n" we
parse the "go infinite" but then input_available() under Linux
is unable to detect that we still have "stop" to be processed.

This is because "select" uses file descriptors instead of file
pointers. So it cannot know about the buffer associated to a file
pointer.

This patch, by BB+, should fix the problem.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-11 18:58:56 +01:00
Marco Costalba
611a29f767 Big book.cpp cleanup
Better document PolyGlot formats and greatly
reduce line count.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-10 19:55:02 +01:00
Marco Costalba
d84ffc0cfa Compile fix in types.h
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-10 12:54:08 +01:00
Marco Costalba
caa02b0e43 Small cleanup in execute_uci_command()
With a little fall out in siblings functions...

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-09 16:24:30 +01:00
Marco Costalba
a8741bd59f Simplify set_option()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-09 15:15:52 +01:00
Joona Kiiski
06c14d0a37 TTEntry simplification
Now that move is fitted in 16 bits we can simplify TTEntry.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-09 13:20:04 +01:00
Marco Costalba
15153a1de7 Don't copy Position in pretty_pv()
Also let do_setup_move() don't reuse same StateInfo so that
we can remove the check about different StateInfo objects
before memcpy() in do_move.

Functional change due to harmless additionals
do_move() / undo_move() steps.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-09 12:55:22 +01:00
Marco Costalba
c89762288b Merge line_to_san() into pretty_pv()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-08 18:31:14 +01:00
Marco Costalba
b4acf83704 Ressurect move.cpp
Actually it is san.cpp renamed. Because now has the move
conversions functions and doesn't have any more the bulky
move_from_san(), it is better to call it move.cpp

Remove san.h while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-08 17:52:02 +01:00
Joona Kiiski
ee0afea1e5 Fix build failure under Linux
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-08 16:26:55 +01:00
Marco Costalba
c82906a2c3 Retire move_from_san()
It is unused and it is big.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-08 16:23:46 +01:00
Marco Costalba
6b49d509a1 Greatly simplify move_from_uci()
Use a reverse logic: among the list of generated legal moves
transformed in UCI coordinate notation find the one that
matches the given string.

It is a bit slower, but here is not performance critical and
is much more simplified then before.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-08 16:12:42 +01:00
Marco Costalba
82d5386435 Move uci move parsing under san.cpp
This partially reverts 1e7aaed8bc keeping the conversion
functions from/to move to uci string in the same file.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-08 15:53:49 +01:00
Joona Kiiski
f4b4d4901c Change Emergency time maximum from 60000 to 30000
I got report from Werner that Shredder Gui has problems with
UCI values which maximum value is greater than 30000.

Of course it's stupid to change engine to fix a GUI's bug,
but on the other hand 30000 ms as maximum value is clearly enough,
so why not to be merciful

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-08 14:27:11 +01:00
Joona Kiiski
8d86e95e37 Fix Makefile's GPL-notice to be similar to other files
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-08 14:26:59 +01:00
Marco Costalba
0f81f97bb6 Improve I/O responsivness
Added checking of (stdin->_cnt > 0) from Greko.

This seems to greatly improve responsivness when running
under console. Now while running a 'stockfish bench', any key
press immediately is detected by SF while before there was a
delay of some fraction of a second.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-08 14:17:41 +01:00
Marco Costalba
d9b96f0e49 Fix reading a book under-promotion move
This is an old Glaurung bug that prevented a Polyglot
book move to be read correctly in case of underpromotion.

This patch fixes the bug restoring support for both
queen and underpromotions.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-08 13:23:25 +01:00
Marco Costalba
4fa0395eb8 Triviality in data_available()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-08 12:53:41 +01:00
Marco Costalba
b3545737fa Force inlining of move generation functions
MSVC (and possibly other compilers) does not inline
as requested, so force it to do so.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-07 16:57:15 +01:00
Marco Costalba
44fbbeafc9 Small tweak to generate_castle_moves()
Move the castling condition test out of the
function. This avoids a function call most of
the times.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-07 16:57:14 +01:00
Marco Costalba
57b3ca916f Unify move generation
Functional change due only to moves reorder. Anyhow after
5242 games at 15"+0.1 TC verified we have no regression.

Mod vs Orig 994 - 958 - 3290 +2 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-07 16:56:42 +01:00
Marco Costalba
12f4bbc8f2 Templetize move generation API
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-07 14:46:29 +01:00
Marco Costalba
1e7aaed8bc Retire move.cpp
Move its functions where they belong.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-07 13:40:13 +01:00
Marco Costalba
a46b53e1c2 Use 16 bits to store a move instead of 17
Shrink of 1 bit so to fit a move in an uint_16 and
possibly a MoveStack in an uint_32.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-07 12:13:05 +01:00
Marco Costalba
dcbc8a7e75 Use a 32 bit bitwise 'and' in SimpleHash lookup
A bit faster on 32 bits machines, more similar to
TranspositionTable::first_entry() and same result.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-07 11:25:13 +01:00
Marco Costalba
0ddf84870a Introduce SimpleHash class
And use it for pawns and material infos.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-07 11:20:49 +01:00
Marco Costalba
803c8e0be3 Small tidy up of inttypes for Windows
There was a strange "int16" type and "int64_t"
was defined twice.

Spotted by Joona.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-06 23:28:06 +01:00
Joona Kiiski
fca74b1882 Simplify 50 move rule condition
We never reach a position where rule50 > 100.
When rule50 == 100, it's either draw or mate and
there is no way search could go deeper.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-06 14:46:49 +01:00
Joona Kiiski
b08ba446f6 Clean up position setup code
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-06 13:54:03 +01:00
Joona Kiiski
1a20d72701 Parse halfmove clock and fullmove number from FEN
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-06 13:44:11 +01:00
Joona Kiiski
916c0cbfbc Minimal restructuring of value.h
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-06 13:36:02 +01:00
Marco Costalba
2e46db4369 Do not make any assumption on the move in move_is_legal()
We must be able to filter out also moves where move_is_ok()
is false.

And actually we are. Tested on all the default position injecting
a number from -1000000 to 1000000 casted to a Move.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-06 13:33:40 +01:00
Marco Costalba
5fc8f86a4f Change move_is_ok() and square_is_ok() in something useful
As is defined now is always true, tested with:

  for (long i=-1000000; i < 1000000; i++)
      if (!move_is_ok(Move(i)))
          exit(0);

Reason is that move_from() and move_to() already truncate the
input value to something in the range [0, 63] that is always
a possible square.

So change definition to something useful.

The same applies also to square_is_ok()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-06 10:55:48 +01:00
Marco Costalba
c14dae1fa2 Improve update_killers() signature
Will be used by future patches and is cleaner.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-06 09:09:53 +01:00
Joona Kiiski
d4ded09e17 Fix variable naming in prototypes at uci.cpp
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-05 23:41:08 +01:00
Joona Kiiski
631fa6a100 Remove a false comment
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-05 23:38:33 +01:00
Marco Costalba
dadf6a6fe9 Set moveCount base to 1 as in search()
Now first move has moveCount == 1 also in root_search()

Also added small readibility touches.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-05 23:19:12 +01:00
Marco Costalba
6a5dc14251 Use killers also in root_search()
After 4238 games
Mod-Orig 800 - 686 - 2752 +9 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-05 23:17:28 +01:00
Marco Costalba
55b16593a4 Perft should return an int64_t not an int
Found by Louis Zulli with his super fast
hardware: 65M nodes/sec at perft !

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-05 21:13:21 +01:00
Marco Costalba
7614501362 Fix POPCNT support for Intel compiler under Windows
Reported by Martin Wyngaarden that also confirmed
this patch to work.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-05 21:12:19 +01:00
Marco Costalba
22ca7a601f Esplicitly inline generate_piece_moves() & friends
Should be already inlined by the compiler when
optimizing but better safe than sorry ;-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-05 09:59:20 +01:00
Marco Costalba
97212bafc9 Use 'moveCount' name also in RootSearch
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-04 11:35:54 +01:00
Marco Costalba
07fcc8076d Use -O3 instead of -fast for Linux icc
Reported by Heinz and confirmed by Joona to increase
the speed of 6% !

No change for icc on OSX

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-04 11:12:43 +01:00
Marco Costalba
be5b32bb9c Another round of bitboard.cpp cleanups
Also renamed StepAttackBB[] in NonSlidingAttacksBB[]

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-04 11:12:31 +01:00
Marco Costalba
9da1f45b1d Restore development version
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-04 09:55:42 +01:00
Marco Costalba
096351d1f5 Stockfish 2.0.1
Always same siganture: 7224363

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-04 08:24:05 +01:00
Marco Costalba
6b96e6f33d Update Readme and polyglot files
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-03 23:55:12 +01:00
Marco Costalba
f200f3ccd2 Another attempt at fixing Chess960
Keep the isChess960 flag inside Position so that is
copied with the Position, but esplicitly highlight the
fact that a FEN string has not enough information to detect
Chess960 in general case. To do this add a boolean argument
isChess960 to from_fen() function so to self document this
shortcoming of FEN notation.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-03 22:50:38 +01:00
Marco Costalba
2bb555025f Revert Chess960 fix
Will be substituted by a better next patch.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-03 22:48:08 +01:00
Tord Romstad
d5f2e32b5c Reintroduce the old "trapped bishop in the corner" evaluation term
for Chess960 games.

After 1918 games at 30"
Mod - Orig: 1052-866 (+532,-346,=1040), Elo +33.8
2011-01-03 22:32:57 +01:00
Joona Kiiski
83d8d54216 Use simple macro to enable operators
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-03 22:27:17 +01:00
Marco Costalba
078354060e Workaround broken function-style cast support in HP-UX
It seems HP's ANSI C++ doesn't understand very well
standard function-style cast.

Reported by Richard Lloyd.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-03 11:36:32 +01:00
Marco Costalba
5973e09854 Readd SRWLOCK and Condition Variables under Windows
And set them as default.

Introduce compile switch OLD_LOCKS to allow to fallback on
compatible locks supported by Windows XP and older versions.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-03 10:49:33 +01:00
Marco Costalba
22ede4442c Fix Chess960 regression
Introduced by me in before 1.9 and found by Tord that says:

The 'isChess960' slot in the 'Position' class is currently
set depending on the initial files of the rooks, and not on the value
of the UCI_Chess960 parameter. This is incorrect, as there are lots of
Chess960 positions where the rooks start on the usual files. As a
consequence (unless I am missing something), Stockfish will occasionally
output castling moves as e1g1/e1c1 rather than the correct e1h1/e1a1 format
in Chess960 games. It is possible that some or even most GUIs are robust
enough to accept both notations, but I wouldn't bet on it. And in any case,
Stockfish's behavior clearly violates the protocol.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-03 00:41:39 +01:00
Marco Costalba
deee18c758 Another (final?) attempt at squares_delta()
This time I have removed the function alltogether !

Sorry to work above a patch of UncombedCoconut (Justin Blanchard)
but I couldn't resist ;-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-02 11:52:51 +01:00
Marco Costalba
0693ff178e Fix old Glaurung bug related to search logging
When we log best and ponder move to a file before to
return from think we change the position. If position is
then not resended by GUI, as for manual user input we got
an error:

justinb@malibu:~$ stockfish
Stockfish 2.0 JA 64bit by Tord Romstad, Marco Costalba, Joona Kiiski
setoption name Use Search Log value true
go depth 1
info depth 1
info depth 1 seldepth 1 multipv 1 score cp 72 time 59 nodes 20 nps 338 pv g1f3
info depth 2
info depth 2 seldepth 2 multipv 1 score cp 12 time 59 nodes 44 nps 745 pv g1f3 g8f6
info nodes 84 nps 1423 time 59
bestmove g1f3 ponder g8f6
go depth 1
info depth 1 score mate 0
info nodes 87 nps 0 time 0
bestmove (none) ponder (none)

Bug spotted and fixed by UncombedCoconut.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-02 11:22:41 +01:00
Marco Costalba
57c51dd1ef Simplify squares_delta()
And rename in ray_direction()

Patch from UncombedCoconut.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-02 10:59:08 +01:00
Marco Costalba
f902ddaa89 Fix a crash on multi-pv
Bug reported by Tobias Haspel and fixed by Joona.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-01 23:10:37 +01:00
Marco Costalba
24485df3df Restore development version
And set "Use Sleeping Threads" to true because it keeps
much more responsive and cool my QUAD during tests :-)

It will be reverted back before to release that's the
reason to bundle it here.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-01 16:19:08 +01:00
Marco Costalba
aa2de53a83 Stockfish 2.0 (take 2)
Always same siganture: 7224363

Hopefully some more bug fixed and restored
compatibility with WIndows XP.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-01 16:10:30 +01:00
Marco Costalba
f826923f8e Don't use SRWLOCK and Condition Variables under Windows
They are not compatible with Windows XP

Revert to old CRITICAL_SECTION locks and events.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-01 16:07:32 +01:00
Marco Costalba
3201a43460 Fix an off-by-one bug in sort_multipv()
Second parameter of insertion_sort() is a pointer to the
element _after_ the last of the list, e.g. end() when sorting
all items.

If we want to sort say the first 2 moves we should write:

sort_multipv(2);

So, becuase in root moves loop move counter 'i' starts
from 0, we need to pass:

sort_multipv(i+1);

To sort up to move 'i' included.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-01 16:07:30 +01:00
Marco Costalba
5405efabcb Remove artificial Iteration >= 3 constraint on time manager
It doesn't seem to have any meaning.

Also add a FIXME on the MaxNodes condition that now is broken
in SMP case due to known issue with pos.nodes_searched()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-01 16:07:29 +01:00
Marco Costalba
6df86fc9da Fix: Honour UCI "quit" command while still in the book
We were not quitting the engine after a "quit" command
while still in the book and pondering.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-01 16:07:28 +01:00
Marco Costalba
7315001f37 Simplify "ponderhit" handling
If flag StopOnPonderhit is set it means that we UseTimeManagement
and also we are at Iteration >= 3.

So we can safely simplify the formula.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-01 16:07:26 +01:00
Marco Costalba
191662a159 Retire ponderhit()
It is called only from one place, so move code there.

Add a bit of renaming and documentation while at there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-01 16:07:25 +01:00
Marco Costalba
a01df59f5e Restore development version
And set "Use Sleeping Threads" to true because it keeps
much more responsive and cool my QUAD during tests :-)

It will be reverted back before to release that's the
reason to bundle it here.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-01 12:30:03 +01:00
Marco Costalba
9f3c7ded5c Stockfish 2.0
stockfish bench signature is: 7224363

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2011-01-01 11:47:34 +01:00
Marco Costalba
df73af30dd Send correct searched nodes statistic
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-31 19:47:17 +01:00
Marco Costalba
9394db765f Remove dubious castle detector
It was introduced by patch 66d16592 of 22/3/2009 merging
from Glarurung iPhone.

Tord says:
That change is only found in the Glaurung iPhone app, and not
in the latest Glaurung UCI source code. I don't remember why
this was added (and the iPhone app, unlike the UCI engine,
was never version controlled), but it was almost certainly
because it was somehow needed in the communication between
the engine and the iPhone GUI, and that it was never meant to be
included in the UCI engine. My guess is that it has something to
do with castling moves being entered as e1-g1 in the GUI, but
represented as e1-h1 in the chess engine.

Removing it in Stockfish should be completely safe, and won't harm
the iPhone version. Initially the iPhone GUI called functions in the
chess engine for checking for legality of moves, writing the move
list in SAN format, and various other tasks, but this is no longer
the case in the current version.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-31 14:32:25 +01:00
Marco Costalba
4d6258bb32 Implement "seldepth" UCI info
This is the "selective search depth in plies" and we set
equal to PV line length.

Tested that works under FritzGUI.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-31 14:27:24 +01:00
Marco Costalba
3e8bb6f63d Retire a couple of unused debug functions
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-30 16:44:10 +01:00
Marco Costalba
3835f49aa1 Leave threads go to sleep when waiting for a ponderhit
No need to heat up CPU in this case ;-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-30 16:18:22 +01:00
Marco Costalba
8e75384dd2 Move printing of best move on think
It seems a more appropiate place (IMHO) and helps to clarify
that idle_loop() should return a move, not a score.

Fix also handling of stalemate positions (we were not
sending any score) and we don't need to wait on "ponderhit",
this is done when returning in think().

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-30 16:12:51 +01:00
Marco Costalba
db4a68a99b Unify single and multi PV 'new best move' handling
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-30 14:03:08 +01:00
Marco Costalba
f803f33e63 Move print_pv_info() under RootMove
And rename to pv_info_to_uci()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-30 12:27:59 +01:00
Marco Costalba
6f2e4c006c Better document value_to_uci()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-30 11:46:53 +01:00
Marco Costalba
afe0203f98 Standardize root_search() signature
Now pass alpha and beta by copy as in serach()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-30 10:54:33 +01:00
Marco Costalba
b01e5fc612 Move extract_pv_from_tt() and insert_pv_in_tt() under RootMove
Functional change only due to additional do/undo move
but absolutly harmless.

Also handle re-insertion in tt of PV lines also for multi PV case.
2010-12-29 15:24:40 +01:00
Marco Costalba
d2a4aac53d Use rml[0].pv[] instead of dedicated pv[] array
We have a small functionality change in case we have a
fail-high so that both rml[].pv and pv[] are updated, but if,
after researching, we have a fail-low then rml score is updated
again but pv[] remains the same and coming back from search we
used a PV line that has failed-low (after having failed-high).

With this patch we always use the 'correct' PV line, i.e. the
line with highest score at the end of the whole search.

Retire also redundant RootMove's 'move' member and directly
use pv[0] instead.
2010-12-29 09:22:30 +01:00
Marco Costalba
58c6e64069 Last small touches in RootMoveList
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-28 23:10:21 +01:00
Marco Costalba
3346ccc9d9 Retire LMR intermediate research
It does not seem to improve anything.

After 8344 games Mod - Orig:
1362 - 1321 - 5661 ELO +2

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-28 18:51:08 +01:00
Marco Costalba
0007b43a91 Use insertion_sort() in RootMoveList
Simplify code and get a bit of extra speed, about +0.5%

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-28 18:36:34 +01:00
Marco Costalba
6235904898 Redefine MoveStack comparison as the natural one
Define symbol '<' to mean 'minor of', as it should be. Its meaning
was reversed to be used with std::sort() that sorts in ascending order
while we want a descending order.

But now that we use our own sorting code we don't need this
trick anymore.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-28 13:06:53 +01:00
Marco Costalba
5b08494312 Fix broken last patch series
When a reference breaks things !

Here we take a reference (that is a pointer) to an
entry in a vector that changes below us --> BOOM !

References are essential but should be considered with
care in C++ because could lead to nasty surprises.

Restored functionality.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-28 13:01:14 +01:00
Marco Costalba
30c14fdc95 Speedup moves root list sorting
Instead of a default member by member copy use set_pv()
to copy the useful part of pv[] array and skip the remaining.

This greatly speeds up sorting of root move list !

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-27 13:55:34 +01:00
Marco Costalba
e8b5420300 Use a std::vector to store root moves
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-27 13:10:32 +01:00
Marco Costalba
12eb27b6e9 Rename RootMoveList members removing 'move'
It is redundant being a move list ;-)

Also better document the two scores used by root list.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-27 11:36:57 +01:00
Marco Costalba
e7ab3a0d16 Retire DirectionTable[]
With this patch even word 'direction' is disappeared !

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-27 03:08:10 +01:00
Marco Costalba
4dded4e72f Retire direction.cpp
Move the code to bitboard.cpp

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-26 16:51:21 +01:00
Marco Costalba
cb7f20913e Retire enum Direction
Use SquareDelta instead

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-26 16:17:51 +01:00
Marco Costalba
f08a6eed0d Retire SignedDirectionTable[] and RayBB[]
Function ray_bb() was used just in one endgame where can
be used squares_in_front_of() instead.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-26 12:12:58 +01:00
Marco Costalba
6080fecf9c Retire direction.h
Move all to square.h

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-26 10:58:52 +01:00
Marco Costalba
94a67c49b0 Simplify enum SquareDelta definition
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-26 10:43:22 +01:00
Marco Costalba
0a73a23dc9 Unify MovePicker c'tor call
And use the standard one.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-25 18:03:43 +01:00
Marco Costalba
a0f0a7dc4f Use generate_moves() in san.cpp
Instead of MovePicker and cleanup san.cpp

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-25 17:54:08 +01:00
Marco Costalba
61c03b9d22 Ignore two braindamaged remarks under icc
Remark 1418: external function definition with no prior declaration

and

Remark 1419: external declaration in primary source file

Can be safely ignored because are pure idiocy.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-25 09:16:30 +01:00
Marco Costalba
dee8780829 Renamed thread_should_stop() in cutoff_at_splitpoint()
It is more clear what happened.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-25 00:11:53 +01:00
Marco Costalba
d40a12f948 Simplify a condition in update of best move
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-24 17:09:39 +01:00
Marco Costalba
f97c5b6909 Triviality in struct PieceLetters
And little touches in search() too.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-24 16:58:25 +01:00
Marco Costalba
d55a5a4d81 Better clarify how we use TT depth in qsearch
Namely we use only two types of depth in TT:
DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-18 11:19:31 +01:00
Marco Costalba
201e8d5f87 Second cleanup wave on check_is_useless()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-18 10:20:15 +01:00
Joona Kiiski
47f5560e2d Let check_is_useless() follow SF coding style
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-14 18:57:22 +01:00
Tord Romstad
cf85ffbb97 Fixed a bug in move_from_uci(): En passant captures were not handled
correctly.
2010-12-14 12:07:37 +01:00
Joona Kiiski
6596dc9516 Selective checks at qsearch
After 5821 games
Mod- Orig:  1014 - 869 - 3938 ELO +8 (+- 3.6) LOS 97%

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-14 07:50:37 +01:00
Marco Costalba
6afcfd00f2 Retire uci_main_loop()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-13 20:38:41 +01:00
Marco Costalba
2d63f2157e Small cleanup in uci.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-13 20:29:40 +01:00
Marco Costalba
56de5ae561 Retire square_from_string()
And rename move_from/to_string() in a more specific
move_from/to_uci() that is a simple coordinate notation.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-13 20:29:38 +01:00
Marco Costalba
556b63b6b6 Move the last multi-threads globals to ThreadsManager
Also rename ThreadsManager memeber data to be lower case.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-13 07:30:59 +01:00
Marco Costalba
4ad03c9bad Further reduce sleep lock contention
Use one sleep lock per thread insted of a single one shared.

Also renamed WaitLock in SleepLock.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-13 07:30:59 +01:00
Marco Costalba
dedc6d7588 Allow threads to sleep when available
By mean of an an UCI option it is possible let the available
threads to sleep, this should help with Hyper Threading although
is not the best solution when number of threads equals number
of available cores.

Option is disabled by default.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-11 09:22:38 +01:00
Marco Costalba
38e7ec3e44 Increase MAX_THREADS to 16
No speed regression and no functional change.

After 7826 games Mod- Orig:
1188 - 1230 - 5408 ELO -1 (+- 3.1)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-10 07:24:48 +01:00
Marco Costalba
421f7b74c6 Increase PV LMR to SF 1.8 levels
Non-PV LMR is left unchanged.

After 8819 games
Mod- Orig:  1442 - 1343 - 6034 ELO +3 (+- 2.9) LOS 86%

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-07 13:13:06 +01:00
Marco Costalba
0da461f23b Various cleanups in Position's ancillary functions
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-06 18:01:18 +01:00
Marco Costalba
97a6e1559e Fix a crash due to a broken Book::open()
Bug introduced in 9dcc2aad98

We can be asked to open a non-exsistent file,
in this case we should gracefully handle the
case and silently return instead of exiting.

Bug discovered and bisected down by Joona.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-05 09:24:18 +01:00
Joona Kiiski
8a858aea34 New try for unstoppable pawn evaluation
This time we try very hard to avoid false positives.
The obvious downside is that we also miss many true
winning positions.

After 10544 games on RC
Mod- Orig:  1744  - 1646 - 7154 ELO +3 (+- 2.7) LOS 83%

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-04 09:07:45 +01:00
Marco Costalba
03dd1d3c13 Allow razoring after a null move
After 8322 games on Russian Cluster
Mod- Orig:  1341 - 1281 - 5700 ELO +2 (+- 3) LOS 75%

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-04 09:04:54 +01:00
Joona Kiiski
5529706426 Prune all negative see moves at low depths
After 2036 games Mod- Orig:
381 - 278 - 1377 ELO +17 (+- 6.2) LOS 99%

One of the biggest increases ever !

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-12-02 07:42:18 +01:00
Marco Costalba
6ed409ecee Fix bestmove output in multi PV case
When MultiPV > 1, always take bestmove from the RootMoveList
(and don't bother with a ponder move). Without that the bestmove
is most probably incorrect.

Patch from Peter Petrov.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-28 17:05:49 +01:00
Marco Costalba
200fc56e9c Fix 'generation' type to uint8_t
When we store this value in TT we cut this to 9 bits,
so we need a smaller variable otherwise comparisons
like:

   replace->generation() == generation

Are always false if generation is bigger then the maximum
TT storable value.

This fixes a very nasty and difficult to spot bug (2 weeks for
regression hunting).

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-28 17:01:01 +01:00
Marco Costalba
d0dc05ad41 Revert sleeping threads
Revert 141caf1d5b + c59efc53c9

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-27 21:26:00 +01:00
Marco Costalba
9ecdfd2401 Revert "Allow split point master to sleep (take 2)"
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-27 21:25:59 +01:00
Marco Costalba
5d6b2f2144 We don't need a stringstream in buildKey()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-23 13:01:11 +01:00
Marco Costalba
efeb37c33f Retire Application class
It is a redundant boiler plate, just call initialization and
resource release directly from main()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-22 18:36:18 +01:00
Marco Costalba
00d9fe8af0 Retire piece.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-22 13:13:48 +01:00
Marco Costalba
85df24624a UCI options names should not be case sensitive
Correctly handle uci option names in a case insensitive way.

Alos fix some indentation while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-21 23:52:51 +01:00
Marco Costalba
f44aea7508 Retire "New Game" UCI option
Was introduced by 403db5a6e9
on 1/12/2009 to correctly handle "loose on time"
LSN filtering functionality, but is now unused.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-21 14:25:30 +01:00
Marco Costalba
fa80479b1d Remove hardcoded 16 from benchmark default positions size
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-21 13:06:53 +01:00
Marco Costalba
df6ba1fa5c Micro-optimize pl_move_is_legal()
This L1/L2 optimization has an incredible +4.7% speedup
in perft test where this function is the most time consumer.

Verified a speed up also in normal bench, although smaller.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-21 12:49:16 +01:00
Marco Costalba
f57d51b7f3 Store "true" and "false" in bool options
UCI protocol uses "true" and "false" for check and button types,
so store that values instead of "1" and "0", this simplifies a
bit the code.

Also a bit strictier option's type checking in debug mode.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-20 18:06:38 +01:00
Marco Costalba
358ccf206b Debug counters don't need to be global
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-20 11:48:04 +01:00
Marco Costalba
24e6ed907b Small touches to engine_name()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-19 23:57:11 +01:00
Marco Costalba
bdfd656c24 Use occupied_squares() in book_key()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-16 19:28:09 +01:00
Marco Costalba
d08a8d76f7 Rearrange pawn moves generation
This patch greatly cleanups generation of pawn moves but
we change the order in which moves are generated so there is
a change in functionality, but not in perft.

The only real functionality change is that now when type == CHECK
we generate knight underpromotion captures only if give check and
not always as before.

Perft is 2% faster and fully verified.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-16 13:43:05 +01:00
Marco Costalba
6f70e762a9 Introduce generate_promotions()
A bit ugly to guarantee no functional change.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-16 13:02:52 +01:00
Marco Costalba
b36900ef44 Simplify generate_pawn_captures()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-15 18:58:15 +01:00
Marco Costalba
a1c02815cc Cleanup Bioskey()
And rename in dataAvailable()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-15 18:58:00 +01:00
Marco Costalba
660378d10e Let bench to have full defaults arguments
Now stockfish bench' defaults to

stockfish bench 128 1 12 default depth

that is the most used line (at least by me)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-09 05:05:08 +01:00
Marco Costalba
9dcc2aad98 Various cleanup in book.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-08 18:51:42 +01:00
Marco Costalba
fad595f5b6 Let benchmark to default to depth 12
And also simplify a lot the code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-08 13:53:44 +01:00
Marco Costalba
d2d953713f Move PieceValue[] and SlidingArray[] where they belong
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-08 13:18:18 +01:00
Marco Costalba
c28b9ef182 Allow split point master to sleep (take 2)
Let to sleep even split point master, it will be waken
up by its slaves when they return from the search.

This time let it be enabled by an UCI option, so
people is free to test it on their Hyper Thread box.

Option is disabled by default.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-07 23:51:09 +01:00
Marco Costalba
da6e2b5fd1 Use namespace in position.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-07 13:51:03 +01:00
Marco Costalba
b06f0460a2 Retire uci.h and benchmark.h
Moved the single prototipes where are needed.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-07 13:31:33 +01:00
Marco Costalba
d2ad5acddd Object OpeningBook doen't need to be global
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-07 13:12:48 +01:00
Marco Costalba
4cd53b68d0 Make rkiss seed deterministic
Search at fixed depth with one thread must be
reproducible so remove randomess from time().

Also better license description.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-07 12:48:23 +01:00
Marco Costalba
8fb16df70e Let rkiss.h to follow SF coding style
Fix also Makefile after mersenne.cpp has been removed

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-07 12:22:15 +01:00
Marco Costalba
f5e28ef512 Use Heinz's RKiss instead of marsenne
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-07 11:52:59 +01:00
Marco Costalba
287556f97d Fix an off by one bug in print_uci_options()
Last option was not printed.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-07 10:53:31 +01:00
Marco Costalba
469e7c5143 Retire bitbase.h
Moved the only prototipe where is needed.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-07 10:53:19 +01:00
Marco Costalba
bacb645939 Rewrite options handling in an object oriented fashion
Big rewrite and about 100 lines removed.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-05 06:10:05 +01:00
Marco Costalba
fb50e16cdd Retire push_button() and button_was_pressed()
Directly access the underlying bool option.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-03 13:19:55 +01:00
Marco Costalba
9f626725ae Prefer int to uint8_t when possible
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-01 13:17:01 +01:00
Marco Costalba
cfca92cd7c Add "mingw" compiler to Makefile
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-01 12:17:54 +01:00
Marco Costalba
d607febb38 Fix MinGW warnings
I finally got SF to compile under MinGW (after adding pthread libraries)
and here are the fixed warnings.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-11-01 11:44:46 +01:00
Marco Costalba
19cf779629 Allocate RootPosition on the stack
And pass it as an argument.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-31 11:53:49 +01:00
Marco Costalba
d74025a34e Update nodes after a do_move()
And also store the node counter in Position and not in Thread.
This will allow to properly count nodes also in sub trees with
SMP active.

This requires a surprisingly high number of changes
in a lot of places to make it work properly.

No functional change but node count changed for obvious reasons.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-31 11:22:40 +01:00
Marco Costalba
49a6fee4fa Fix some icc's "statement is unreachable" warnings
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-30 19:19:40 +01:00
Marco Costalba
2991ff0dc2 Move moveCount update near the SpNode case
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-30 18:26:41 +01:00
Marco Costalba
c416133e2f Introduce and use TranspositionTable::refresh()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-30 15:22:10 +01:00
Marco Costalba
ff95bbd41f Use margins[] array in evaluate
It will be used by future patches.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-30 14:24:19 +01:00
Marco Costalba
2d7a417d0a More readable search/qsearch dispatch
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-30 12:32:38 +01:00
Marco Costalba
f790752daa Fix last leak detected by Valgrind
This was subtle and google was my friend.

The leak was in _dl_allocate_tls called by pthread_create() and
is due to the fact that threads are created in joinable state so that
once terminated are not freed. To make the thread to release
its resources upon termination we should set them in detached state.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-24 09:57:30 +01:00
Marco Costalba
5254ca22f3 Fix a memcpy() warning under Valgrind
Fix warning: "Source and destination overlap in memcpy"

This happens when we call multiple time do_move() with the
same state, for instance when we don't need to undo the move.

This is what valgrind docs say:

You don't want the two blocks to overlap because one of them could
get partially overwritten by the copying.

You might think that Memcheck is being overly pedantic reporting this
in the case where 'dst' is less than 'src'. For example, the obvious way
to implement memcpy() is by copying from the first byte to the last.
However, the optimisation guides of some architectures recommend copying
from the last byte down to the first. Also, some implementations of
memcpy() zero 'dst' before copying, because zeroing the destination's
cache line(s) can improve performance.

In addition, for many of these functions, the POSIX standards have wording
along the lines "If copying takes place between objects that overlap,
the behavior is undefined." Hence overlapping copies violate the standard.

The moral of the story is: if you want to write truly portable code, don't
make any assumptions about the language implementation.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-24 09:56:57 +01:00
Marco Costalba
5b445cdf59 Revert previous patch
It seems we have a speed regression under Linux, anyhow
commit and revert to leave some documentation in case we
want to try again in the future.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-24 09:53:19 +01:00
Marco Costalba
96e589646d Allow split point master to sleep
Let to sleep even split point master, it will be waken up
by its slaves when they return from the search.

With this patch we get maximum HT speedup

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-23 13:50:54 +01:00
Marco Costalba
c81bf3743f Re-add "Pass evalMargin through SearchStack as eval"
It has more sense to treat the two evaluation metrics
in the same way.

As a side effect now we use the correct eval margin when
pruning in a SplitPoint node.

No functional change in single thread.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-23 08:07:26 +01:00
Marco Costalba
f6e11ee2a3 Finally retire sp_search()
Fix the movcount updating bug and let search() to completely
subsititute sp_search().

No functional change even with fakes split.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-23 07:51:35 +01:00
Marco Costalba
65606bc49e Temporary restore old sp_search()
There is a bug in the conversion that is triggered when testing
with faked split and that I missed somehow :-(

To allow proper testing on cluster restore old sp_search()
until I don't fiugre up what's happened.

Restored to be functional equivalent to old behaviour both in
single thread and in faked split.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-18 08:34:25 +01:00
Marco Costalba
3b7bf34b02 Revert "Pass evalMargin through SearchStack as eval"
Restore full no functional change also in Faked Split mode.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-18 08:19:48 +01:00
Marco Costalba
141caf1d5b Don't wake up /sleep threads in think() anymore
When entering and exiting from think() we don't need any special
wake up / sleeping code because we want available threads to keep
sleeping.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-17 13:12:58 +01:00
Marco Costalba
c59efc53c9 Enable sleeping of available threads
This simple patch has devastating consequences ;-)

Now an available thread goes to sleep and is waked up after
being allocated.

This patch allows Stockfish to dramatically increase performances
on HyperThreading systems.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-17 11:38:00 +01:00
Marco Costalba
8fdc635255 Use fast SRWLOCK locks under Windows
They are fast and also have the same semantic of Linux ones.

This allow to simplify the code and especially to use
SleepConditionVariableSRW() to wait on a condition releaseing the lock,
this has the same semantic as pthread_cond_wait().

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-17 11:04:52 +01:00
Marco Costalba
472971f851 Remove some ifdef from wake_sleeping_thread()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-17 09:35:44 +01:00
Marco Costalba
389edb8099 Retire put_threads_to_sleep()
Obsoleted by previous patches.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-17 09:03:39 +01:00
Marco Costalba
13d8231746 Retire THREAD_SLEEPING and use THREAD_AVAILABLE instead
This is a prerequisite for future work and anyhow removes
a state flag, so it is good anyhow.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-17 08:59:07 +01:00
Marco Costalba
9440fb06da Retire AllThreadsShouldSleep flag
It is redundant and complicates the already complicated
SMP code for no reason.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-17 08:39:03 +01:00
Marco Costalba
3a564ed5db Destroy wait conditions before exiting
We already do this for locks. Also rename SitIdleEvent
in WaitCond to be uniform with Lunix naming.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-17 07:36:14 +01:00
Marco Costalba
1fdb436e78 Change thread API to use one wait condition per thread
This is the native way done in Windows and we will use it
for future work, so change Linux to do the same.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-17 08:00:42 +01:00
Marco Costalba
dcf2edfdea Do not shadow SplitPoint struct with search() parameter
Also retire move_is_killer() is called only from one place.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-16 15:39:07 +01:00
Marco Costalba
85a7456bd7 Fixed some warnings when using -Weffc++ gcc option
Plus some other icc warnings popped up with new and strictier
compile options.

No functional and speed change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-16 15:00:20 +01:00
Marco Costalba
d664773a83 Fix a shadowed variable warning under icc
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-16 15:00:07 +01:00
Marco Costalba
f092667460 Retire now obsoleted do_sp_search() trampoline code
We can call search() directly from idle_loop()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-16 12:20:16 +01:00
Marco Costalba
19ff8e2902 Pass evalMargin through SearchStack as eval
It has more sense to treat the two evaluation metrics
in the same way.

As a side effect now we use the correct eval margin when
pruning in a SplitPoint node.

No functional change in single thread.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-16 11:54:44 +01:00
Marco Costalba
a7f4ee7540 Unify sp_search() and search() step 3
Remove old sp_search() code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-16 11:40:49 +01:00
Marco Costalba
f7722d4de7 Unify sp_search() and search() step 2
Modify search() to be able to handle split points

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-16 11:20:43 +01:00
Marco Costalba
37055ad002 Unify sp_search() and search() step 1
Rewrite sp_search() to have same signature of search()

This is the first prerequistite step toward unification.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-16 09:49:45 +01:00
Marco Costalba
79a7647fe0 Pass moveCount by value in split()
Actually it is an error to update back moveCount value after split()
because it is used in update_history() to access movesSearched[]
array. But becasue this vector is not updated in the split point
we end up with an access of stale data.

Bug has been hidden til now because we 'forgot' to update
moveCount before returning from split().

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-12 12:33:44 +01:00
Marco Costalba
00950fec00 Sync sp_search() with search()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-12 12:19:47 +01:00
Marco Costalba
7c7a77698a Better document some threads functions
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-12 12:11:20 +01:00
Marco Costalba
083ed1ce94 Document an assert in idle_loop()
Thanks to Bruno Causse for the clarification.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-11 19:56:35 +01:00
Marco Costalba
2feeb206ff Use VALUE_DRAW instead of VALUE_ZERO where better
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-10 09:05:46 +01:00
Marco Costalba
5dfbbb79be Use do_move_bb() in move_attacks_square()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-10 08:32:12 +01:00
Marco Costalba
d440ddb487 Another cleanup in evaluate_pawns()
Suggested by Marek Kwiatkowski.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-10 08:32:03 +01:00
Marco Costalba
9c9914d72a Micro optimize open files calculation
Committed mostly because is also a cleanup...

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-09 15:22:00 +01:00
Marco Costalba
a0474a72a6 Rearrange pawn penalities arrays
A clean up that is also a prerequisite for next patches.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-09 13:43:43 +01:00
Marco Costalba
7733dadfd7 Small codestyle touches
Mostly suggested by Justin (UncombedCoconut), the 0ULL -> 0 conversion
is mine.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-09 13:05:58 +01:00
Marco Costalba
9ca4359f36 Properly set to zero stuff returned by 'new'
Language guarantees that c'tor is called, but without any c'tor
it happens to work by accident because OS zeroes out the freshly
allocated pages. The problem is that if I deallocate and allocate
again, the second time pages are no more newly come by the OS and
so could contain stale info.

A practical case could be if we change TT size or numbers of
threads on the fly while already running.

Bug spotted by Justin Blanchard.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-07 03:57:33 +01:00
Marco Costalba
f00c976bb2 Retire updateKingTables[]
Suggested by Marek Kwiatkowski.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-06 19:28:27 +01:00
Marco Costalba
1bbbc13b46 Skip ei.kingZone[] initialization together with king safety
Another microptimization by Marek Kwiatkowski.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-05 22:32:53 +01:00
Marco Costalba
1ee1d852fe Skip an useless compare in space evaluation
Spotted by Marek Kwiatkowski.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-05 22:16:09 +01:00
Marco Costalba
812e843939 Restore development version
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-05 19:40:49 +01:00
Marco Costalba
71e14bb67b Stockfish 1.9.1
Fix release to workaround chess960 on some GUIs

Signature is:

stockfish bench 128 1 12 default depth

Node counts: 10914593

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-05 12:00:24 +01:00
Marco Costalba
66a64406ca Fix broken chess960 under Shredder GUI
We need to add a dummy option anyway to make GUIs happy.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-05 12:00:16 +01:00
Marco Costalba
d4876dc963 Rewrite bit counting functions
Get rid of macros and use templates instead,
this is safer and allows us fix the warning:

ISO C++ forbids braced-groups within expressions

That broke compilation with -pedantic flag under
gcc and POPCNT enabled.

No functional and no performance change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-04 18:40:44 +01:00
Marco Costalba
3249777cdb Remove -pedantic option
Breaks current POPCNT code.

Perhaps we will readd with a proper fix...

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-03 14:43:17 +01:00
Marco Costalba
544adf7e41 Use special handling for promotions in move_is_legal()
Simplifies a bit the code and the common case too.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-03 11:15:53 +01:00
Marco Costalba
98b09b4038 Fix an obsoleted NO_PIECE_TYPE in a comment
Spotted by Ralph Stoesser.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-02 18:57:46 +01:00
Marco Costalba
0aeba002c8 Restore development version
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-02 14:36:43 +01:00
Marco Costalba
247c2cd207 Increase warning level
Both under gcc and icc: sf compiles with no warnings !

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-02 14:32:43 +01:00
Marco Costalba
46c16ab783 Stockfish 1.9
Signature is:

stockfish bench 128 1 12 default depth

Node counts: 10914593

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-10-02 09:55:10 +01:00
Joona Kiiski
3fd0079807 Less aggressive move count based futility pruning
This patch from Joona greatly reduces move count pruning,
below is the old and new move count limits starting from
ONE_PLY with half-play increment:

Old: 4,5,5,5, 7, 7,11,11,11,19,19,19,35,35
New: 4,5,7,9,12,15,19,23,28,33,39,45,52,59

Surprisingly results are even a bit better at a quite
fast time control.

After 5260 games at 30"+0.1
Mod - Orig:  864 - 806 - 3590  ELO +3 (+- 3.8)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-26 10:27:15 +01:00
Marco Costalba
a28f4a56d3 Fix handling of 50 move rule and remove a fixme
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-25 11:24:20 +01:00
Marco Costalba
7305b56957 Shrink OutpostBonus[] definition
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-25 11:12:55 +01:00
Marco Costalba
045beac156 Simplify scale factors implementation
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-24 12:56:45 +01:00
Marco Costalba
0e3535ea23 Rename no_mob_area in mobilityArea
It is the correct name.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-24 12:56:38 +01:00
Marco Costalba
c254861ee6 Small code style in qsearch
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-21 20:04:15 +01:00
Marco Costalba
c1558dde12 Do not update killers in qsearch
It seems totally unuseful because killers are not
used to order the moves in qsearch. Although there
is some functionality change, probably just a small
side effect.

After 5656 games on rc
Mod vs Orig: 1007 - 980 - 3669  ELO +1 (+- 3.7)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-21 06:25:47 +01:00
Marco Costalba
9d1522b24f A king move can never have negative SEE
So there is no need to explicitly check for king moves
when detecting prunable evasions.

Perhaps teoretically a very bit slower (I didn't test),
but it is more clear now what evasions we consider prunable.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-19 13:56:50 +01:00
Marco Costalba
23fd379694 Simplify SEE
Greatly cleanup SEE code and now it is also a bit
faster on gcc, about +0.6%.

Thanks to Mike Whiteley new SEE code that gave me
fresh ideas on how to cleanup this old stuff.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-19 13:41:54 +01:00
Marco Costalba
9ab0e1bb13 Retire NullMoveMargin
A code semplification that could even be a slight increase,
anyhow is a reducing pruning patch, so it is good even
at equal strenght.

After 6342 games
Mod - Orig:  1040 - 974 - 4328  ELO +3 (+- 3.5)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-16 08:22:39 +01:00
Marco Costalba
debc815352 We need just one eval margin in search
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-14 18:06:10 +01:00
Marco Costalba
dd8a076128 Reintroduce rook contact checks
Were removed when merged from Glaurung 2.2, but without
any test.

Note that weight has been increased from original 2 to 4 and
has been also fixed a bug where in the original version were
considered also diagonal sqaures for the rook, that are
contact squares but not checks.

After 4449 games at 30"+0.1
Mod - Orig:  717 - 649 - 3083  ELO +5 (+- 4.1)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-14 13:48:26 +01:00
Marco Costalba
4350d9e8a6 Fix a warning under icc
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-14 07:56:02 +01:00
Marco Costalba
42ed488987 Retire badCaptures[] array in MovePicker
Use the tail of moves[] array to store bad captures.

No functional change but some move reorder. Verified with old perft.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-13 13:22:00 +01:00
Marco Costalba
4143d00011 Increase QueenContactCheckBonus
And also other check bonuses.

After 4272 games on russian cluster at 30"+0.1
Mod - Orig:  711 - 612 - 2949  ELO +8 (+- 4.2)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-13 00:10:48 +01:00
Marco Costalba
1a2768705a Do not update king tables when we skip king safety
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-12 14:28:07 +01:00
Joona Kiiski
fa2478a81f Retire pawn storm evaluation
More then 100 lines of almost useless evaluations. Prefer
code semplification to a very small and dubious advantage.

After 7457 games on russian cluster:
Mod - Orig: 1285 - 1334 - 4838  ELO -2 (+- 3.2)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-11 09:46:00 +01:00
Marco Costalba
5b5b496a6d Array FutilityMarginsMatrix stores Values
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-09-04 14:10:48 +01:00
Marco Costalba
6096ca7a95 Remove get_* prefix from RootMoveList API
And small additional cleanup in RootMoveList.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-30 12:56:12 +01:00
Marco Costalba
427dc2a82c Use only cumulativeNodes in RootMoveList
And rename in nodes now that we have only one.

After the beta-cut off counters removing we can
get rid also of this one.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-30 12:56:04 +01:00
Marco Costalba
b177e6dd91 Use evaluation margins also in main search
For now keep FutilityMarginsMatrix[] unchanged, in
future we are going to reduce to compensate for extra
margin.

At this moment it is enough we don't have regressions.

After 9694 games on russian cluster
Mod - Orig 1608 - 1578 - 6508  ELO +1 (+- 2.8)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-28 12:07:15 +01:00
Marco Costalba
d9dc9dbd65 Split branches in generate_piece_moves()
Instead of one comparison in while() condition use two,
the first to check if the piece is exsistant and the second
to loop across pieces of that type.

This should help branch prediction in cases we have only
one piece of the same type, for instance for queens, the
first branch is always true and the second is almost always
false.

Increased speed of 0.3-0.5 % on Gcc pgo compiles.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-27 13:28:07 +01:00
Marco Costalba
2a2353aac6 Speed up updateShelter()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-26 18:52:53 +02:00
Marco Costalba
1b4084b4a5 Assorted code style in evaluation.cpp
Renaming, cleanu up, etc.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-26 13:47:38 +01:00
Marco Costalba
c7dd9b8d0c Finally remove value from EvalInfo
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-26 13:47:29 +01:00
Marco Costalba
9ee42d83b6 Remove dependency from ei.value in evaluate functions
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-26 13:41:28 +01:00
Marco Costalba
3107e68c03 Remove margin[] from EvalInfo
Directly pass arguments to king evaluation.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-26 13:41:28 +01:00
Marco Costalba
d4250c52f0 Remove MaterialInfo* from EvalInfo
Use a local variable instead.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-26 13:41:27 +01:00
Marco Costalba
15d265cc66 Change evaluate() signature
Hide EvalInfo and return just the score and the margin.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-26 13:41:26 +01:00
Marco Costalba
fff59319b0 Retire attackedBy[] access functions
Currently are used by evaluation itself and the
whole EvalInfo will be removed from global visibility
by next patch, so no reason to use them.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-26 13:41:26 +01:00
Marco Costalba
b196af4dcd Decrypt some magics in bitboards definitions
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-26 13:41:25 +01:00
Marco Costalba
eb4858256b We don't need EvalInfo c'tor anymore
We know always get complete info from TT, so this
code is obsolete.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-25 00:20:53 +01:00
Marco Costalba
c7a932bc74 Rename ei.kingDanger in ei.margin
It will be more clear when we will go to add stuff
apart from king danger itself.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-24 19:16:03 +01:00
Marco Costalba
00469d1798 Call apply_weight() only once in passed pawns evaluation
First accumulate the bonus for each pawn, then call the
not very fast apply_weight().

Should be no functional change apart from rounding issues.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-24 19:13:13 +01:00
Marco Costalba
17d820e248 Don't need to memset() EvalInfo
Set manually to zero the few fields that are
optionally populated and that's enough.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-24 18:58:51 +01:00
Marco Costalba
d73eea3f71 There is no need of storing mobility in EvalInfo
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-24 18:55:40 +01:00
Marco Costalba
74033b004e Refresh comments in evaluate.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-24 18:55:31 +01:00
Marco Costalba
6125966da0 Unify single MobilityBonus[] tables in a big single one
Avoid one address lookup in a very critical time path.

Unified also outpost bonus tables for knights and bishops.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-24 13:34:41 +01:00
Marco Costalba
421867ea2d Retire trapped bishop evaluation
Another 100 lines of dubious and ad-hoc code.

After 7644 games on russian cluster:
Mod - Orig 1285 - 1249 - 5110  ELO +1 (+- 3.2)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-24 13:13:20 +01:00
Marco Costalba
e17fa64aec Retire UCI_Chess960 option
We don't need that !

We can infere from starting fen string if we are in
a Chess960 game or not. And note that this is a per-position
property, not an application wide one.

A nice trick is to use a custom manipulator (that is an
enum actually) to keep using the handy operator<<() on the
move when sending to std::cout, yes, I have indulged a
bit here ;-)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-22 16:51:20 +01:00
Marco Costalba
7b721b3663 Prefetch pawn hash key
Plus a bunch of other minor optimizations.

With this power pack we have an increase
of a whopping 1.4%  :-)

...and it took 3 good hours of profiling + hacking to get it out !

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-22 14:04:06 +01:00
Marco Costalba
b6ba5f7fe4 Retire unstoppable pawns evaluation
One hundred lines of code should be compensated by an
important ELO increase, otherwise are candidate for removal...

...and is not the case. We are well within error margin, so
remove the code even if we lose a couple of elo points, but
semplification is huge.

After 6494 games on russian cluster
Orig vs Mod 1145 - 1107 - 4242 (-2 ELO)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-22 01:39:31 +01:00
Marco Costalba
73f1179d39 Remove my address from README
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-21 17:21:44 +01:00
Marco Costalba
0363b54358 Retire beta counters stuff
Is now obsoleted by previous patch.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-20 18:33:19 +01:00
Joona Kiiski
a44f79141e Use MovePicker's move ordering also at root
After testing on our russian cluster: +3 elo after 4200 games

So keep it becuase it allows a good semplification.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-20 18:04:02 +01:00
Marco Costalba
79a28841f9 Move StartPositionFEN out of the header
It is not needed to have global visibility.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 18:22:48 +01:00
Marco Costalba
df4b106716 Move piece values in piece.h / piece.cpp
Where they belong.

Note that array PieceValueMidgame[] and PieceValueEndgame[]
are now declared extern in the header and moved in piece.cpp
so to avoid allocate the array each time the header is
included !

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 18:22:48 +01:00
Marco Costalba
a952c6bc6d Retire is_upper_bound() and friend
Directly expand in the few places where is called.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 18:22:47 +01:00
Marco Costalba
391e176274 Retire useless piece_value_midgame() overloads
Directly access the table in the few call places.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 18:22:46 +01:00
Marco Costalba
5bed82cd4e Introduce and use SCORE_ZERO
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 18:22:46 +01:00
Marco Costalba
4419924fcf Do not score PH_QCHECKS
They are picked unsorted anyway, so score is unuseful.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 14:50:02 +01:00
Marco Costalba
a5ae7fe260 Disable templetized operators by default
To avoid nasty bugs due to silently overriding of
common operator we enable the templates on a type
by type base using partial template specialization.

No functional change, zero overhead at runtime.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 13:48:41 +01:00
Marco Costalba
94b9c65e09 Introduce enum VALUE_ZERO instead of Value(0)
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 13:48:38 +01:00
Marco Costalba
0e800c527a Use Use templetized operations for Score and Value
Note that in value we leave two specialized functions
to allow adding an integer, we don't want to add this
as a template becasue we want to control implicit
conversions to integer of an enum.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 13:48:37 +01:00
Marco Costalba
13bd0cff0d Use templetized operations for Piece
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 13:48:35 +01:00
Marco Costalba
8e31764c49 Use templetized operations for Square
This is tricky because there are some special
binary fnctions with SquareDelta that we should
leave as they are.

Also note that we needed to add Unary minus template
to fix a comile error in SERIALIZE_MOVES_D macro that was
triggered because now we don't allow conversion to int.

No fuctional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 13:48:33 +01:00
Marco Costalba
4ce08482c3 Use templetized operations for File and Rank
Doing the conversion the compiler is now able to
spot two possible ambiguity calls that now we can
easily fix.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 13:48:30 +01:00
Marco Costalba
80bee85d5f Use templetize enum operations for Depth
Instead of hardcoded ones.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 13:48:28 +01:00
Marco Costalba
4f96f420a3 Store in TT with depth == -OnePly instead of -1
When depth < DEPTH_ZERO we store with the same depth all
the positions, use -OnePly instead of -1 for consistency
with depth arithmetic.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 13:48:26 +01:00
Marco Costalba
4f28e19fc0 (Re)introduce DEPTH_ZERO to replace Depth(0)
No functional changes.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 13:48:24 +01:00
Marco Costalba
ea2b8a93eb Retire some unused Depth operator() functions
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 13:48:23 +01:00
Marco Costalba
4aeffc8c9a Rename OnePly in ONE_PLY
Use enum values standard naming policy also for this one.

No fuctional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 13:48:20 +01:00
Marco Costalba
cfb52fcd5d Define OnePly as a Depth enum costant
There is no reason to use a variable for this.

Also remove unused DEPTH_ZERO and DEPTH_MAX.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-19 13:48:11 +01:00
Marco Costalba
cf4c28ff86 Revert F_90 and F_92
Regression test found the patches to be harmless,
so revert to keep code simpler.

Test1 at 20+0.1: (2500 - 3000) +0 ELO
Test2 at 1+0: (~1000) +2 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-18 10:07:28 +01:00
Marco Costalba
252537fd9c Cleanup and optimize Position::has_mate_threat()
There is a functional change because we now skip
more moves and because do_move() / undo_move() is
well known to be not reversible we end up with a
change in node count, although there is actually
no change but a bit speed up.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-09 12:30:33 +01:00
Marco Costalba
f26e0fec64 Usual material.cpp small touches
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-08 13:14:18 +01:00
Marco Costalba
e6376d9b8d Rename constants to use *_NONE scheme
To be uniform across the sources. As a nice side effect
I quickly spotted a couple of needed renames:

captured_piece() -> captured_piece_type()
st->capture      -> st->capturedType

Proposed by Ralph and done with QtCreator

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-07 18:56:24 +01:00
Marco Costalba
2170fa18bf Move depth computation out of fail low loop
In root_search() we can compute depth at the beginning
once and for all.

Spotted by Ralph Stoesser.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-06 22:30:50 +01:00
Marco Costalba
be540b6dd7 Another push to perft speed
We don't need to generate captures and non
captures in a separate step. This gives another
7% push to perft speed.

yes, I know, it is totally useless :-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-06 12:10:07 +01:00
Marco Costalba
3a2cd37080 Faster perft
Skip moves scoring and sorting: this more then
doubles the speed !

Verified is correct.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-06 11:15:41 +01:00
Marco Costalba
d6904157aa Rename TM in ThreadsMgr
This avoid misunderstandings with new TimeManager
object called TimeMgr.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-03 13:06:56 +01:00
Marco Costalba
5fc98745c3 TimeManager API rename
We can now set member data as private because is no more
directly accessed.

Should be more clear now.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-03 11:49:28 +01:00
Marco Costalba
c295599e4a Move time related global variables under TimeManager
Move OptimumSearchTime, MaximumSearchTime and
ExtraSearchTime in TimeManager.

Note that we remove an useless initialization to 0 because
these variables are used only with time management.

Also introduce and use TimeManager::available_time()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-03 11:47:52 +01:00
Marco Costalba
dda53e831d Introduce TimeManager class
Firt step in unifying all time management under
a single umbrella. Just introduced the class without
even member data.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-03 11:39:42 +01:00
Marco Costalba
977f6349a9 Small cleanup in search Step.5
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-02 22:09:20 +01:00
Marco Costalba
5aef9186ac Reset bestMove before entering main moves loop
After razoring, IID, null verification and singular
extension searches we have could have a dirty ss->bestMove,
restore to MOVE_NONE before to enter moves loop.

This should avoid to store in TT a stale move when
we fail low.

Tested together with previous patch that is the
one that gives ELO.

After 1152 games at 1+0 on my QUAD
Mod vs Orig +233 =716 -203 (+9 ELO)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-02 22:02:59 +01:00
Marco Costalba
cbcc581a86 Use past SE information also for success cases
If singular extension search was succesful in the past then
skip another the SE search and extend of one ply.

Another way to mitigate the cost of SE at the price of
some more spurious extension, but on 90% of cases info
is correct.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-02 18:47:27 +01:00
Marco Costalba
fe23c70cf1 Rename MaxSearchTime and AbsoluteMaxSearchTime
Renamed in OptimumSearchTime and MaximumSearchTime,
should be more clear now.

Suggested by Joona.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-02 18:41:55 +01:00
Marco Costalba
cf0295f1ad Templetize xxx_time_for_MTG()
Also fixed some warnings under MSVC.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-02 11:55:45 +01:00
Marco Costalba
391cd57b52 Little timeman.cpp massage
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-02 11:49:49 +01:00
Joona Kiiski
f40e481fd6 Tweak default values for ucioptions
I created three different systems, tested them all separately and
attached one did best:

1/40: Orig - Mod: 841 - 850 (+2 elo)
1+1 : Orig - Mod: 474 - 498 (+9 elo)
1+0 : Orig - Mod: 455 - 495 (+15 elo)

Because such testing system is not statistically reliable, I made a
confirmation test:

1/40: Orig - Mod: 502 - 543 (+14 elo)
1+1: Orig - Mod: 447 - 489 (+16 elo)
1+0: Orig - Mod: 641 - 656 (+4 elo)

All tests show positive score :-)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-02 11:49:31 +01:00
Joona Kiiski
c0616d773d New Time management system
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-08-02 11:48:03 +01:00
Marco Costalba
87139d018c Always use ss->bestMove to store ply best move
Instead of ss->currentMove. It is more consistent and
clear to understand.

Remark by Ralph Stoesser.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-31 07:29:29 +01:00
Marco Costalba
9645e8e4e7 Lower SingularExtensionDepth to 7 plies for non-pv
To compensate for the extra work skip singular
searches deemed to fail because excluded node
failed high already in the past.

After 1200 games at 1+0
Mod vs Orig +387 =1274 -339  (+8 ELO)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-30 22:50:03 +01:00
Marco Costalba
935fc09fd4 Two small fixes in passed pawns evaluation
The one in evaluate_passed_pawns() is just a micro
optimization, the other in evaluate_unstoppable_pawns()
is indeed a fix, although almost unmeasurable in real
games.

Bugs report and fixes by Marek Kwiatkowski

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-26 06:10:01 +01:00
Marco Costalba
5ee7dfebf7 Fix KBNK endgame
Broken by recent patch. Also better document what's
happening there.

Verified to restore original behaviour.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-25 21:58:09 +01:00
Marco Costalba
6b6f3c4ca4 Rename EMPTY in NO_PIECE
It is more correct and more in line with enum PieceType

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-25 12:10:22 +01:00
Marco Costalba
14f059072a Introduce enum SquareColor
Square and piece colors are two different things,
so use different types to avoid misunderstandings.

Suggested by Tord.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-25 11:49:58 +01:00
Marco Costalba
9b1d5bd534 Introduce and use same_color_squares()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-25 11:49:32 +01:00
Marco Costalba
a84e4b2049 Cleanup Position::print()
And remove not used OUTSIDE enum Piece.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-25 09:57:57 +01:00
Joona Kiiski
4d438fae9e Fix build failure on GCC
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-25 08:57:23 +01:00
Marco Costalba
02882dfe81 Cleanup Position::to_fen()
Less invasive then previous patches, but still a good
enhancement.

Also some indulge on STL algorithms :-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-24 18:56:07 +01:00
Marco Costalba
c2048136ec Last touches to from_fen()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-24 16:31:12 +01:00
Marco Costalba
839088205e Rewrite Position::from_fen()
Complete rewrite the function and extend compatibility
also to X-FEN notation for Chess960.

We are now able to read standard FEN, Shredder-FEN and X-FEN.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-24 09:43:01 +01:00
Joona Kiiski
098ac5e44e Don't initialize psqt-tables when 'ucinewgame' is received
After 'Randomness' is retired, this is no longer necessary.

NOTE: Possibly some extra care is needed when tuning branch is synced

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-23 12:21:54 +01:00
Joona Kiiski
d3260ce70f Retire 'Randomness' ucioption
Using multiple threads and good opening book is
much better and more reliable source of randomness than
spoiling psqt-tables

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-23 12:21:46 +01:00
Joona Kiiski
71ba48c4ff Always init pthread locks to NULL
This is the only way to keep Windows and POSIX behaviour in sync,
so better hardcode it.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-23 07:03:39 +01:00
Joona Kiiski
65f8b6dbc0 Remove other locking options
Currently broken and we use pthreads in search.cpp
anyway, so I see no reason to keep these around

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-23 07:03:32 +01:00
Marco Costalba
d5520977b9 Retire SearchStack init() and initKillers()
Let be explicit about what this functions do, and
we save some code lines too.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-23 02:42:27 +01:00
Marco Costalba
d004ec924d Fix errouneus reset of ss->threatMove
After we set ss->threatMove we could go under a IID step that
resets SearchStack ss and so also ss->threatMove.

When later we use that field in futility pruning we have this
set to MOVE_NONE !

The fix is to use a local variable and add threatMove to SplitPoint
to pass this move to slaves.

Spotted by Ralph Stoesser, fix suggested by Richard Vida.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-23 02:26:57 +01:00
Marco Costalba
5c3aeae566 Revert previous patch
Improvement is easily in error bar and there is
some added complexity making future changes more
difficult.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-22 18:30:18 +01:00
Marco Costalba
26a8b84417 Weight backward-ness of a pawn
Because not all backward pawns are the same ;-) if the
blocking enemy pawn is near then our pawn is more backward
than another whose enemy pawn is far away so that can advance
for some sqaures.

After 2925 games at 30"+0 on my QUAD
Mod vs Orig +602 =1745 -578 +3 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-22 18:15:16 +01:00
Joona Kiiski
6aef4429fd ValueType needs only 2 bits to be stored in TT
Also update some more TT documentation

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-22 17:51:33 +01:00
Joona Kiiski
23db43e698 Update TT documentation
Update outdated and even misleading documentation.

Also check #include-directives

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-22 17:51:26 +01:00
Marco Costalba
6f6f59ea6a Move insert_pv() and extract_pv() out of TT class
These functions have little to do with TranspositionTable
class and more with the search and in particular with the PV
handling. So move them where they belong.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-21 12:09:09 +01:00
Marco Costalba
e2c0b5f995 Store position static score in TT as soon as possible
So to maximize the possibility to avoid to recalculate it
in the future. A small speed-up of 0.8%

Idea by Ralph Stoesser.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-21 12:08:45 +01:00
Marco Costalba
02f96fcf5e Introduce DEPTH_NONE and use it
Also better fix previous patch.

Suggestions by Joona and Ralph.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-20 19:06:09 +01:00
Joona Kiiski
28feb2c6b0 Remove pointless tte->static_value() != VALUE_NONE checks
Now in non-check nodes we are guaranteed to always have static value
in TT Entry.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-20 19:01:10 +01:00
Joona Kiiski
ba1a44f216 Store static value and king danger in TT also in TT.insert_pv() method
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-20 19:01:01 +01:00
Marco Costalba
0fb5d7a737 Fix "pass ss->eval to qsearch()" condition
The seocond check is no more needed now and
anyhow is wrong to overwrite a TT entry if
present.

Spotted by Ralph Stoesser.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-19 12:28:33 +01:00
Marco Costalba
201f924d53 Triviality in material.cpp
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-19 12:01:36 +01:00
Marco Costalba
95388a952b Small rewrite of backward pawn test
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-19 07:13:50 +01:00
Joona Kiiski
b5178597bd Initialize SearchStack only once at RootMoveList c'tor
Just fix current ugly behaviour :-)

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-19 03:53:37 +01:00
Joona Kiiski
b75e68860c Every node is responsible for initializing its own SearchStack entry
More logical than doing partly initialization at init_ss_array()

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-19 03:52:21 +01:00
Joona Kiiski
66c5835080 Drop KILLER_MAX. Hardcode to 2 instead.
KILLER_MAX in search.h is quite pointless, because
we already hardcode this to 2 in MovePicker anyway.

By hard-coding this to 2 we can keep code simpler.

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-19 03:51:25 +01:00
Joona Kiiski
a6d13428f6 Do not initialize ss->reduction to zero in the beginning of node
It must already be zero because zeroed in SearchStack initialization

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-19 03:48:51 +01:00
Joona Kiiski
1322ab97c7 Do not reset ss->eval in the beginning of the node
This avoids problems with IID clearing ss->eval and
eval not being available when we return

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-19 03:43:58 +01:00
Marco Costalba
6e06db93fd Fix isolated and backward pawns scoring
It is more clear and also more correct because we
consider enemy pawns only in fornt of us and not just
on our file.

Very small functional change, almost not measurable, but
keep the patch for documenting purposes.

Spotted by Marek Kwiatkowski.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-17 17:32:54 +01:00
Marco Costalba
53bbcb78d5 Triviality in endgame.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-17 14:00:25 +01:00
Joona Kiiski
a6dcaa575f Update Makefile
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-16 12:04:02 +01:00
Joona Kiiski
05c5442633 Find balance between 1.7 and 1.8 reductions
Almost no change so commit because is a pruning
reduction patch.

After 1088 games at 1'+0 with QUAD
Mod vs Orig +178 =727 -183  (-2 ELO)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-15 20:53:16 +01:00
Marco Costalba
b6ab610e2f Remove redundant argument in think()
We don't need to pass side_to_move because we can get
it directly from the position object.

Note that in benchmark we always used to pass '0' and
it was a bug, but with no effect because was used only
in time[] and increment[], set always to 0 for both
colors.

Also additional small cleanup while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-15 17:14:30 +01:00
Marco Costalba
a98dee7835 Retire apply_scale_factor() and scale.h
Directly inline in the only occurence.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-15 17:05:23 +01:00
Marco Costalba
3e38e61565 Inline history and gain getters
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-15 16:55:35 +01:00
Marco Costalba
bc0c1c8d7b Retire value.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-15 12:16:36 +01:00
Marco Costalba
605b3aedd5 Retire LSN machinery
Now that we use cutechess-cli we can set the auto-resign
parameter that makes LSN less effective.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-14 17:29:36 +01:00
Marco Costalba
8547798345 Triviality in ucioption.cpp
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-14 17:29:34 +01:00
Marco Costalba
3703d12eb9 Add moves from failed high nodes in PV
Considering only VALUE_TYPE_EXACT nodes is too
restrictive and has a number of side-effects, most
notably the truncation of PV line after a fail high
at root.

Note that in this way we are no more guaranteed that
PV line is built up with PV nodes only, because
it could happen that a side search overwrites with a
cut-off move a PV node and this cut-off move ends up
in PV.

Change should be almost not measurable, perhaps with
ponder on we could have some beneficial effect.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-12 21:06:40 +01:00
Marco Costalba
a47a7dadeb Fix (zugzwang) verification to be shallower then null search
Currently starting from depth 12*OnePly on we have a verification
search deeper then the null search.

Note that, although reduction is R we start from one ply less then
null search, so actually we reach a depth that is OnePly shallower
then null search.

After 1130 games at 1'+0 on QUAD
Mod vs Orig +202 =756 -172  +9 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-12 21:03:30 +01:00
Joona Kiiski
00e86078a5 Remove TranspositionTable::overwrites variable
Doesn't provide useful information and
can cause slowdown with many Threads.

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-11 22:25:02 +01:00
Marco Costalba
2adbb80b8b Space inflate bitbase.cpp
Also heavy cleanup while there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-11 12:05:06 +01:00
Marco Costalba
ee8cdb1721 There is no need to clear TT at allocation time
Operator new() already returns a zeroed memory.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-11 09:42:04 +01:00
Marco Costalba
82bd61a8fa Revert previous patch
After the previous patch, it's impossible to build
anything else than x86 32-bit binary!

So revert.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-10 16:43:05 +01:00
Marco Costalba
87502c0fcb Makefile: default on gcc 32 bits when type 'make'
From Vratko Polak

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-10 12:16:43 +01:00
Marco Costalba
aa172032c4 Reword singular extension comments
Should be more stick to original definition (Hsu, Campbell)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-06 17:56:04 +01:00
Joona Kiiski
8689ff7d03 Tweak Makefile a bit
To fix some build problems on debian's
automatic building system.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-06 06:24:58 +01:00
Marco Costalba
04e1ba8aa2 Move SplitPoint array under its thread
And cleanup / rename that part of code.

No functional change also with faked split.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-05 20:55:01 +01:00
Marco Costalba
2dfec0f614 Tweak non-captures scoring
Tested with Orig set at f5ef5632f so to evaluate
direct gain against 1.8

After 3239 games at 10"+0.1
Mod vs Orig +701 =1906 -632 +7 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-04 21:49:23 +01:00
Joona Kiiski
e0056c3851 Fix TT documentation
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-04 20:15:09 +01:00
Marco Costalba
a5c85d3cfc Reintroduce GCC/ICC rounding hack
Unfortunatly the source of this issue is not in the
different handling of log(0) illegal value.

No functional change on MSVC.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-03 19:05:04 +01:00
Joona Kiiski
d0fdc20231 Fix Makefile for HPUX
On hpux there is no prefetch.

Reported by Richard Lloyd

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-03 18:54:34 +01:00
Marco Costalba
1d4e7bbdf5 Fix DIVIDE BY ZERO exception in init_search()
It happens that when d == 0 we calculate:

log(double(0 * 0) / 2)

Unfortunately, log(0) is "illegal" and can generate either a
floating point exception or return a nonsense "huge" value
depending on the platform.

This fixs in the proper way the GCC/ICC rounding difference,
bug was from our side, not in the intel compiler.

Also fixed some few other warnings.

Bug spotted by Richard Lloyd.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-03 16:12:20 +01:00
Marco Costalba
3578207974 PSQT access functions can be static
Also renamed history access value in something more
in line with the meaning.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-03 05:49:13 +01:00
Marco Costalba
40ad5194aa Use only history to score non-captures
It seems there is absolutely no difference in using gains.

After 7025 games at 5"+0
Mod vs Orig +1903 =3236 -1886 (+1 ELO)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-03 05:36:53 +01:00
Marco Costalba
f5ef5632ff Restore development version
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2010-07-03 05:34:57 +01:00
65 changed files with 7405 additions and 11815 deletions

View File

@@ -1,22 +1,20 @@
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<6F>, Arena, Sigma Chess, Shredder,
Chess Partner, or Fritz) in order to be used comfortably. Read the
documentation for your GUI of choice for information about how to use
Stockfish with your GUI.
Stockfish is a free UCI chess engine derived from Glaurung 2.1. It is not a
complete chess program, but requires some UCI compatible GUI (like XBoard
with PolyGlot, eboard, Arena, Sigma Chess, Shredder, Chess Partner or Fritz)
in order to be used comfortably. Read the documentation for your GUI of choice
for information about how to use Stockfish with your GUI.
This version of Stockfish supports up to 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.
This version of Stockfish supports up to 32 CPUs, but has not been tested
thoroughly with more than 4. The program tries to detect the number of
CPUs on your computer and set the number of search threads accordingly, but
please be aware that the detection is not always correct. It is therefore
recommended to inspect the value of the "Threads" UCI parameter, and to
make sure it equals the number of CPU cores on your computer. If you are
using more than eight threads, it is recommended to raise the value of
"Min Split Depth" UCI parameter to 7.
2. Files
@@ -30,9 +28,9 @@ This distribution of Stockfish consists of the following files:
License.
* src/, a subdirectory containing the full source code, including a
Makefile that can be used to compile Stockfish on Unix-like
systems. For further information about how to compile Stockfish
yourself, read section 4 below.
Makefile that can be used to compile Stockfish on Unix-like systems.
For further information about how to compile Stockfish yourself
read section 4 below.
* polyglot.ini, for using Stockfish with Fabien Letouzey's PolyGlot
adapter.
@@ -41,35 +39,32 @@ This distribution of Stockfish consists of the following files:
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".
This version of Stockfish has support for PolyGlot opening books.
For information about how to create such books, consult the PolyGlot
documentation. The book file can be selected by setting the UCI
parameter "Book File".
4. Compiling it yourself
------------------------
On Unix-like systems, it should usually be possible to compile
Stockfish directly from the source code with the included Makefile.
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 support for 32 or 64 bits CPUS, big-endian machines, like
Power PC, hardware POPCNT instruction and other platforms.
Stockfish has POPCNT instruction runtime detection and support. This can
give an extra speed on Core i7 or similar systems. To enable this feature
compile with 'make icc-profile-popcnt'
On 64 bit 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
In general is recommended to run 'make help' to see a list of make targets
with corresponding descriptions. When not using Makefile to compile, for
instance with Microsoft MSVC, you need to manually set/unset in the compiler
command line some swicthes, see file types.h for a quick reference.
5. Terms of use
---------------
Stockfish is free, and distributed under the GNU General Public License
(GPL). Essentially, this means that you are free to do almost exactly
(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
@@ -77,14 +72,8 @@ using it as the starting point for a software project of your own.
The only real limitation is that whenever you distribute Stockfish in
some way, you must always include the full source code, or a pointer
to where the source code can be found. If you make any changes to the
to where the source code can be found. If you make any changes to the
source code, these changes must also be made available under the GPL.
For full details, read the copy of the GPL found in the file named
Copying.txt.
6. Feedback
-----------
The author's e-mail address is mcostalba@gmail.com

View File

@@ -15,34 +15,29 @@ ResignScore = 600
[Engine]
Hash = 128
Threads = 1
OwnBook = false
Book File = book.bin
Best Book Move = false
Use Search Log = false
Search Log Filename = SearchLog.txt
Book File = book.bin
Best Book Move = false
Mobility (Middle Game) = 100
Mobility (Endgame) = 100
Pawn Structure (Middle Game) = 100
Pawn Structure (Endgame) = 100
Passed Pawns (Middle Game) = 100
Passed Pawns (Endgame) = 100
Space = 100
Aggressiveness = 100
Cowardice = 100
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
Randomness = 0
Minimum Split Depth = 4
Maximum Number of Threads per Split Point = 5
Min Split Depth = 4
Max Threads per Split Point = 5
Threads = 1
Use Sleeping Threads = false
Hash = 128
Ponder = true
OwnBook = false
MultiPV = 1
Skill Level = 20
Emergency Move Horizon = 40
Emergency Base Time = 200
Emergency Move Time = 70
Minimum Thinking Time = 20
UCI_Chess960 = false
UCI_AnalyseMode = false

View File

@@ -1,674 +0,0 @@
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>.

View File

@@ -1,8 +1,6 @@
# Stockfish, a UCI chess playing engine derived from Glaurung 2.1
# Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
# Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
#
# This file is part of Stockfish.
# Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
#
# Stockfish is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
@@ -33,11 +31,9 @@ BINDIR = $(PREFIX)/bin
PGOBENCH = ./$(EXE) bench 32 1 10 default depth
### Object files
OBJS = application.o bitboard.o pawns.o material.o endgame.o evaluate.o main.o \
misc.o move.o movegen.o history.o movepick.o search.o piece.o \
position.o direction.o tt.o value.o uci.o ucioption.o \
mersenne.o book.o bitbase.o san.o benchmark.o
OBJS = benchmark.o bitbase.o bitboard.o book.o endgame.o evaluate.o main.o \
material.o misc.o move.o movegen.o movepick.o pawns.o position.o \
search.o thread.o timeman.o tt.o uci.o ucioption.o
### ==========================================================================
### Section 2. High-level Configuration
@@ -46,16 +42,16 @@ OBJS = application.o bitboard.o pawns.o material.o endgame.o evaluate.o main.o \
# flag --- Comp switch --- Description
# ----------------------------------------------------------------------------
#
# debug = no/yes --- -DNDEBUG --- Enable/Disable debug mode
# debug = yes/no --- -DNDEBUG --- Enable/Disable debug mode
# optimize = yes/no --- (-O3/-fast etc.) --- Enable/Disable optimizations
# arch = (name) --- (-arch) --- Target architecture
# os = (name) --- --- Target operating system
# bits = 64/32 --- -DIS_64BIT --- 64-/32-bit operating system
# bigendian = no/yes --- -DBIGENDIAN --- big/little-endian byte order
# prefetch = no/yes --- -DUSE_PREFETCH --- Use prefetch x86 asm-instruction
# bsfq = no/yes --- -DUSE_BSFQ --- Use bsfq x86_64 asm-instruction
# --- (Works only with GCC and ICC 64-bit)
# popcnt = no/yes --- -DUSE_POPCNT --- Use popcnt x86_64 asm-instruction
# arch = (name) --- (-arch) --- Target architecture
# os = (name) --- --- Target operating system
# bits = 64/32 --- -DIS_64BIT --- 64-/32-bit operating system
# bigendian = yes/no --- -DBIGENDIAN --- big/little-endian byte order
# prefetch = yes/no --- -DUSE_PREFETCH --- Use prefetch x86 asm-instruction
# bsfq = yes/no --- -DUSE_BSFQ --- Use bsfq x86_64 asm-instruction (only
# with GCC and ICC 64-bit)
# popcnt = yes/no --- -DUSE_POPCNT --- Use popcnt x86_64 asm-instruction
#
# Note that Makefile is space sensitive, so when adding new architectures
# or modifying existing flags, you have to make sure there are no extra spaces
@@ -200,6 +196,15 @@ ifeq ($(COMP),)
COMP=gcc
endif
ifeq ($(COMP),mingw)
comp=mingw
CXX=g++
profile_prepare = gcc-profile-prepare
profile_make = gcc-profile-make
profile_use = gcc-profile-use
profile_clean = gcc-profile-clean
endif
ifeq ($(COMP),gcc)
comp=gcc
CXX=g++
@@ -219,10 +224,18 @@ ifeq ($(COMP),icc)
endif
### 3.2 General compiler settings
CXXFLAGS += -g -Wall -fno-exceptions -fno-rtti $(EXTRACXXFLAGS)
CXXFLAGS = -g -Wall -Wcast-qual -fno-exceptions -fno-rtti $(EXTRACXXFLAGS)
ifeq ($(comp),gcc)
CXXFLAGS += -ansi -pedantic -Wno-long-long -Wextra -Wshadow
endif
ifeq ($(comp),mingw)
CXXFLAGS += -Wextra -Wshadow
endif
ifeq ($(comp),icc)
CXXFLAGS += -wd383,869,981,10187,10188,11505,11503
CXXFLAGS += -wd383,981,1418,1419,10187,10188,11505,11503 -Wcheck -Wabi -Wdeprecated -strict-ansi
endif
ifeq ($(os),osx)
@@ -230,7 +243,7 @@ ifeq ($(os),osx)
endif
### 3.3 General linker settings
LDFLAGS += -lpthread $(EXTRALDFLAGS)
LDFLAGS = -lpthread $(EXTRALDFLAGS)
ifeq ($(os),osx)
LDFLAGS += -arch $(arch)
@@ -257,11 +270,15 @@ ifeq ($(optimize),yes)
endif
endif
ifeq ($(comp),icc)
CXXFLAGS += -fast
ifeq ($(comp),mingw)
CXXFLAGS += -O3
endif
ifeq ($(comp),icc)
ifeq ($(os),osx)
CXXFLAGS += -mdynamic-no-pic
CXXFLAGS += -fast -mdynamic-no-pic
else
CXXFLAGS += -O3
endif
endif
endif
@@ -291,16 +308,25 @@ endif
### 3.10 popcnt
ifeq ($(popcnt),yes)
CXXFLAGS += -DUSE_POPCNT
CXXFLAGS += -msse3 -DUSE_POPCNT
endif
### 3.11 Link Time Optimization, it works since gcc 4.5 but not on mingw.
### This is a mix of compile and link time options because the lto link phase
### needs access to the optimization flags.
ifeq ($(comp),gcc)
GCC_MAJOR := `gcc -dumpversion | cut -f1 -d.`
GCC_MINOR := `gcc -dumpversion | cut -f2 -d.`
ifeq (1,$(shell expr \( $(GCC_MAJOR) \> 4 \) \| \( $(GCC_MAJOR) \= 4 \& $(GCC_MINOR) \>= 5 \)))
CXXFLAGS += -flto
LDFLAGS += $(CXXFLAGS)
endif
endif
### ==========================================================================
### Section 4. Public targets
### ==========================================================================
default:
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) build
help:
@echo ""
@echo "To compile stockfish, type: "
@@ -311,7 +337,7 @@ help:
@echo ""
@echo "build > Build unoptimized version"
@echo "profile-build > Build PGO-optimized version"
@echo "popcnt-profile-build > Build PGO-optimized version with optional popcnt-support"
@echo "double-profile-build > Build PGO-optimized version with and without popcnt support"
@echo "strip > Strip executable"
@echo "install > Install executable"
@echo "clean > Clean up"
@@ -320,7 +346,7 @@ help:
@echo "Supported archs:"
@echo ""
@echo "x86-64 > x86 64-bit"
@echo "x86-64-modern > x86 64-bit with runtime support for popcnt-instruction"
@echo "x86-64-modern > x86 64-bit with runtime support for popcnt instruction"
@echo "x86-32 > x86 32-bit excluding very old hardware without SSE-support"
@echo "x86-32-old > x86 32-bit including also very old hardware"
@echo "osx-ppc-64 > PPC-Mac OS X 64 bit"
@@ -336,6 +362,7 @@ help:
@echo ""
@echo "gcc > Gnu compiler (default)"
@echo "icc > Intel compiler"
@echo "mingw > Gnu compiler with MinGW under Windows"
@echo ""
@echo "Non-standard targets:"
@echo ""
@@ -371,7 +398,7 @@ profile-build:
@echo "Step 4/4. Deleting profile data ..."
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) $(profile_clean)
popcnt-profile-build:
double-profile-build:
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) config-sanity
@echo ""
@echo "Step 0/6. Preparing for profile build."
@@ -408,11 +435,14 @@ install:
-strip $(BINDIR)/$(EXE)
clean:
$(RM) $(EXE) *.o .depend *~ core bench.txt
$(RM) $(EXE) $(EXE).exe *.o .depend *~ core bench.txt *.gcda
testrun:
@$(PGOBENCH)
default:
help
### ==========================================================================
### Section 5. Private targets
### ==========================================================================
@@ -449,7 +479,7 @@ config-sanity:
@test "$(prefetch)" = "yes" || test "$(prefetch)" = "no"
@test "$(bsfq)" = "yes" || test "$(bsfq)" = "no"
@test "$(popcnt)" = "yes" || test "$(popcnt)" = "no"
@test "$(comp)" = "gcc" || test "$(comp)" = "icc"
@test "$(comp)" = "gcc" || test "$(comp)" = "icc" || test "$(comp)" = "mingw"
$(EXE): $(OBJS)
$(CXX) -o $@ $(OBJS) $(LDFLAGS)
@@ -466,6 +496,7 @@ gcc-profile-make:
gcc-profile-use:
$(MAKE) ARCH=$(ARCH) COMP=$(COMP) \
EXTRACXXFLAGS='-fprofile-use' \
EXTRALDFLAGS='-lgcov' \
all
gcc-profile-clean:
@@ -500,7 +531,7 @@ icc-profile-clean:
hpux:
$(MAKE) \
CXX='/opt/aCC/bin/aCC -AA +hpxstd98 -DBIGENDIAN -mt +O3 -DNDEBUG' \
CXX='/opt/aCC/bin/aCC -AA +hpxstd98 -DBIGENDIAN -mt +O3 -DNDEBUG -DNO_PREFETCH' \
CXXFLAGS="" \
LDFLAGS="" \
all

View File

@@ -1,78 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// 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_search();
init_threads();
// Make random number generation less deterministic, for book moves
for (int i = abs(get_system_time() % 10000); i > 0; i--)
genrand_int32();
}
void Application::initialize() {
// A static Application object is allocated
// once only when this function is called.
static Application singleton;
}
void Application::free_resources() {
// Warning, following functions reference global objects that
// must be still alive when free_resources() is called.
exit_threads();
quit_eval();
}
void Application::exit_with_failure() {
exit(EXIT_FAILURE);
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,29 +17,23 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// Includes
////
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
#include "benchmark.h"
#include "misc.h"
#include "position.h"
#include "search.h"
#include "thread.h"
#include "ucioption.h"
using namespace std;
using namespace Search;
////
//// Variables
////
const string BenchmarkPositions[] = {
static const char* Defaults[] = {
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -",
"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - -",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 10",
"8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 11",
"4rrk1/pp1n3p/3q2pQ/2p1pb2/2PP4/2P3N1/P2B2PP/4RRK1 b - - 7 19",
"rq3rk1/ppp2ppp/1bnpb3/3N2B1/3NP3/7P/PPPQ1PP1/2KR3R w - - 7 14",
"r1bq1r1k/1pp1n1pp/1p1p4/4p2Q/4Pp2/1BNP4/PPP2PPP/3R1RK1 w - - 2 14",
@@ -51,136 +45,91 @@ const string BenchmarkPositions[] = {
"r1bq1r1k/b1p1npp1/p2p3p/1p6/3PP3/1B2NN2/PP3PPP/R2Q1RK1 w - - 1 16",
"3r1rk1/p5pp/bpp1pp2/8/q1PP1P2/b3P3/P2NQRPP/1R2B1K1 b - - 6 22",
"r1q2rk1/2p1bppp/2Pp4/p6b/Q1PNp3/4B3/PP1R1PPP/2K4R w - - 2 18",
"4k2r/1pb2ppp/1p2p3/1R1p4/3P4/2r1PN2/P4PPP/1R4K1 b - 3 22",
"4k2r/1pb2ppp/1p2p3/1R1p4/3P4/2r1PN2/P4PPP/1R4K1 b - - 3 22",
"3q2k1/pb3p1p/4pbp1/2r5/PpN2N2/1P2P2P/5PP1/Q2R2K1 b - - 4 26"
};
////
//// Functions
////
/// benchmark() runs a simple benchmark by letting Stockfish analyze a set
/// of positions for a given time each. There are four parameters; the
/// of positions for a given limit each. There are five parameters; the
/// transposition table size, the number of search threads that should
/// be used, the time in seconds spent for each position (optional, default
/// is 60) and an optional file name where to look for positions in fen
/// format (default are the BenchmarkPositions defined above).
/// The analysis is written to a file named bench.txt.
/// be used, the limit value spent for each position (optional, default is
/// depth 12), an optional file name where to look for positions in fen
/// format (defaults are the positions defined above) and the type of the
/// limit value: depth (default), time in secs or number of nodes.
void benchmark(const string& commandLine) {
void benchmark(int argc, char* argv[]) {
istringstream csVal(commandLine);
istringstream csStr(commandLine);
string ttSize, threads, fileName, limitType, timFile;
int val, secsPerPos, maxDepth, maxNodes;
vector<string> fens;
LimitsType limits;
int time;
int64_t nodes = 0;
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 > MAX_THREADS)
{
cerr << "The number of threads must be between 1 and " << MAX_THREADS << 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");
// Assign default values to missing arguments
string ttSize = argc > 2 ? argv[2] : "128";
string threads = argc > 3 ? argv[3] : "1";
string valStr = argc > 4 ? argv[4] : "12";
string fenFile = argc > 5 ? argv[5] : "default";
string valType = argc > 6 ? argv[6] : "depth";
csVal >> val;
csVal >> fileName;
csVal >> limitType;
csVal >> timFile;
Options["Hash"] = ttSize;
Options["Threads"] = threads;
Options["OwnBook"] = false;
secsPerPos = maxDepth = maxNodes = 0;
if (valType == "time")
limits.maxTime = 1000 * atoi(valStr.c_str()); // maxTime is in ms
else if (valType == "nodes")
limits.maxNodes = atoi(valStr.c_str());
if (limitType == "time")
secsPerPos = val * 1000;
else if (limitType == "depth" || limitType == "perft")
maxDepth = val;
else
maxNodes = val;
limits.maxDepth = atoi(valStr.c_str());
vector<string> positions;
if (fileName != "default")
if (fenFile != "default")
{
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]));
string fen;
ifstream file(fenFile.c_str());
ofstream timingFile;
if (!timFile.empty())
{
timingFile.open(timFile.c_str(), ios::out | ios::app);
if (!timingFile.is_open())
if (!file.is_open())
{
cerr << "Unable to open timing file " << timFile << endl;
Application::exit_with_failure();
cerr << "Unable to open file " << fenFile << endl;
exit(EXIT_FAILURE);
}
while (getline(file, fen))
if (!fen.empty())
fens.push_back(fen);
file.close();
}
else
fens.assign(Defaults, Defaults + 16);
time = system_time();
for (size_t i = 0; i < fens.size(); i++)
{
Position pos(fens[i], false, 0);
cerr << "\nPosition: " << i + 1 << '/' << fens.size() << endl;
if (valType == "perft")
{
int64_t cnt = perft(pos, limits.maxDepth * ONE_PLY);
cerr << "\nPerft " << limits.maxDepth << " leaf nodes: " << cnt << endl;
nodes += cnt;
}
else
{
Threads.start_thinking(pos, limits, vector<Move>(), false);
nodes += RootPosition.nodes_searched();
}
}
vector<string>::iterator it;
int cnt = 1;
int64_t totalNodes = 0;
int startTime = get_system_time();
time = system_time() - time;
for (it = positions.begin(); it != positions.end(); ++it, ++cnt)
{
Move moves[1] = {MOVE_NONE};
int dummy[2] = {0, 0};
Position pos(*it, 0);
cerr << "\nBench position: " << cnt << '/' << positions.size() << endl << endl;
if (limitType == "perft")
{
int64_t perftCnt = perft(pos, maxDepth * OnePly);
cerr << "\nPerft " << maxDepth << " result (nodes searched): " << perftCnt << endl << endl;
totalNodes += perftCnt;
} else {
if (!think(pos, false, false, 0, dummy, dummy, 0, maxDepth, maxNodes, secsPerPos, moves))
break;
totalNodes += nodes_searched();
}
}
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
cerr << "\n==========================="
<< "\nTotal time (ms) : " << time
<< "\nNodes searched : " << nodes
<< "\nNodes/second : " << int(nodes / (time / 1000.0)) << endl;
}

View File

@@ -1,37 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(BENCHMARK_H_INCLUDED)
#define BENCHMARK_H_INCLUDED
////
//// Includes
////
#include <string>
////
//// Prototypes
////
extern void benchmark(const std::string& commandLine);
#endif // !defined(BENCHMARK_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,22 +17,10 @@
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
////
#include "types.h"
namespace {
@@ -40,311 +28,244 @@ namespace {
RESULT_UNKNOWN,
RESULT_INVALID,
RESULT_WIN,
RESULT_LOSS,
RESULT_DRAW
};
struct KPKPosition {
Result classify_knowns(int index);
Result classify(int index, Result db[]);
private:
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;
Result classify_white(const Result db[]);
Result classify_black(const Result db[]);
Bitboard wk_attacks() const { return StepAttacksBB[W_KING][whiteKingSquare]; }
Bitboard bk_attacks() const { return StepAttacksBB[B_KING][blackKingSquare]; }
Bitboard pawn_attacks() const { return StepAttacksBB[W_PAWN][pawnSquare]; }
Square whiteKingSquare, blackKingSquare, pawnSquare;
Color sideToMove;
};
// The possible pawns squares are 24, the first 4 files and ranks from 2 to 7
const int IndexMax = 2 * 24 * 64 * 64; // color * wp_sq * wk_sq * bk_sq = 196608
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);
// Each uint32_t stores results of 32 positions, one per bit
uint32_t KPKBitbase[IndexMax / 32];
int compute_index(Square wksq, Square bksq, Square wpsq, Color stm);
}
////
//// Functions
////
uint32_t probe_kpk_bitbase(Square wksq, Square wpsq, Square bksq, Color stm) {
void generate_kpk_bitbase(uint8_t bitbase[]) {
// Allocate array and initialize:
Bitbase = new Result[IndexMax];
initialize();
int index = compute_index(wksq, bksq, wpsq, stm);
// Iterate until all positions are classified:
while(next_iteration());
return KPKBitbase[index / 32] & (1 << (index & 31));
}
// 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;
void kpk_bitbase_init() {
Result db[IndexMax];
KPKPosition pos;
int index, bit, repeat = 1;
// Initialize table
for (index = 0; index < IndexMax; index++)
db[index] = pos.classify_knowns(index);
// Iterate until all positions are classified (30 cycles needed)
while (repeat)
for (repeat = index = 0; index < IndexMax; index++)
if ( db[index] == RESULT_UNKNOWN
&& pos.classify(index, db) != RESULT_UNKNOWN)
repeat = 1;
// Map 32 position results into one KPKBitbase[] entry
for (index = 0; index < IndexMax / 32; index++)
for (bit = 0; bit < 32; bit++)
if (db[32 * index + bit] == RESULT_WIN)
KPKBitbase[index] |= (1 << bit);
}
namespace {
// A KPK bitbase index is an integer in [0, IndexMax] range
//
// Information is mapped in this way
//
// bit 0: side to move (WHITE or BLACK)
// bit 1- 6: black king square (from SQ_A1 to SQ_H8)
// bit 7-12: white king square (from SQ_A1 to SQ_H8)
// bit 13-14: white pawn file (from FILE_A to FILE_D)
// bit 15-17: white pawn rank - 1 (from RANK_2 - 1 to RANK_7 - 1)
int compute_index(Square wksq, Square bksq, Square wpsq, Color stm) {
assert(file_of(wpsq) <= FILE_D);
int p = file_of(wpsq) + 4 * (rank_of(wpsq) - 1);
int r = stm + 2 * bksq + 128 * wksq + 8192 * p;
assert(r >= 0 && r < IndexMax);
return r;
}
void KPKPosition::from_index(int index) {
int s;
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 s = index >> 13;
sideToMove = Color(index & 1);
blackKingSquare = Square((index >> 1) & 63);
whiteKingSquare = Square((index >> 7) & 63);
pawnSquare = make_square(File(s & 3), Rank((s >> 2) + 1));
}
Result KPKPosition::classify_knowns(int index) {
int KPKPosition::to_index() const {
return compute_index(whiteKingSquare, blackKingSquare, pawnSquare,
sideToMove);
from_index(index);
// Check if two pieces are on the same square
if ( whiteKingSquare == pawnSquare
|| whiteKingSquare == blackKingSquare
|| blackKingSquare == pawnSquare)
return RESULT_INVALID;
// Check if a king can be captured
if ( bit_is_set(wk_attacks(), blackKingSquare)
|| (bit_is_set(pawn_attacks(), blackKingSquare) && sideToMove == WHITE))
return RESULT_INVALID;
// The position is an immediate win if it is white to move and the
// white pawn can be promoted without getting captured.
if ( rank_of(pawnSquare) == RANK_7
&& sideToMove == WHITE
&& whiteKingSquare != pawnSquare + DELTA_N
&& ( square_distance(blackKingSquare, pawnSquare + DELTA_N) > 1
|| bit_is_set(wk_attacks(), pawnSquare + DELTA_N)))
return RESULT_WIN;
// Check for known draw positions
//
// Case 1: Stalemate
if ( sideToMove == BLACK
&& !(bk_attacks() & ~(wk_attacks() | pawn_attacks())))
return RESULT_DRAW;
// Case 2: King can capture pawn
if ( sideToMove == BLACK
&& bit_is_set(bk_attacks(), pawnSquare) && !bit_is_set(wk_attacks(), pawnSquare))
return RESULT_DRAW;
// Case 3: Black king in front of white pawn
if ( blackKingSquare == pawnSquare + DELTA_N
&& rank_of(pawnSquare) < RANK_7)
return RESULT_DRAW;
// Case 4: White king in front of pawn and black has opposition
if ( whiteKingSquare == pawnSquare + DELTA_N
&& blackKingSquare == pawnSquare + DELTA_N + DELTA_N + DELTA_N
&& rank_of(pawnSquare) < RANK_5
&& sideToMove == WHITE)
return RESULT_DRAW;
// Case 5: Stalemate with rook pawn
if ( blackKingSquare == SQ_A8
&& file_of(pawnSquare) == FILE_A)
return RESULT_DRAW;
return RESULT_UNKNOWN;
}
Result KPKPosition::classify(int index, Result db[]) {
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;
from_index(index);
db[index] = (sideToMove == WHITE ? classify_white(db) : classify_black(db));
return db[index];
}
Result KPKPosition::classify_white(const Result db[]) {
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.
// If one move leads to a position classified as RESULT_WIN, the result
// of the current position is RESULT_WIN. If all moves lead to positions
// classified as RESULT_DRAW, the current position is classified RESULT_DRAW
// otherwise the current position is classified as RESULT_UNKNOWN.
bool unknownFound = false;
Bitboard b;
Square s;
Result r;
// King moves
b = 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;
b = wk_attacks();
while (b)
{
s = pop_1st_bit(&b);
r = db[compute_index(s, blackKingSquare, pawnSquare, BLACK)];
case RESULT_UNKNOWN:
unknownFound = true;
break;
if (r == RESULT_WIN)
return RESULT_WIN;
case RESULT_DRAW: case RESULT_INVALID:
break;
default:
assert(false);
}
if (r == RESULT_UNKNOWN)
unknownFound = true;
}
// 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;
if (rank_of(pawnSquare) < RANK_7)
{
s = pawnSquare + DELTA_N;
r = db[compute_index(whiteKingSquare, blackKingSquare, s, BLACK)];
case RESULT_UNKNOWN:
unknownFound = true;
break;
if (r == RESULT_WIN)
return RESULT_WIN;
case RESULT_DRAW: case RESULT_INVALID:
break;
if (r == RESULT_UNKNOWN)
unknownFound = true;
default:
assert(false);
}
// Double pawn push
if (rank_of(s) == RANK_3 && r != RESULT_INVALID)
{
s += DELTA_N;
r = db[compute_index(whiteKingSquare, blackKingSquare, s, BLACK)];
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;
if (r == RESULT_WIN)
return RESULT_WIN;
case RESULT_UNKNOWN:
unknownFound = true;
break;
case RESULT_DRAW: case RESULT_INVALID:
break;
default:
assert(false);
if (r == RESULT_UNKNOWN)
unknownFound = true;
}
}
}
return unknownFound? RESULT_UNKNOWN : RESULT_DRAW;
return unknownFound ? RESULT_UNKNOWN : RESULT_DRAW;
}
Result classify_btm(const KPKPosition &p) {
Result KPKPosition::classify_black(const Result db[]) {
// 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.
// of the current position is RESULT_DRAW. If all moves lead to positions
// classified as RESULT_WIN, the position is classified as RESULT_WIN.
// Otherwise, the current position is classified as RESULT_UNKNOWN.
bool unknownFound = false;
Bitboard b;
Square s;
Result r;
// King moves
b = 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;
b = bk_attacks();
while (b)
{
s = pop_1st_bit(&b);
r = db[compute_index(whiteKingSquare, s, pawnSquare, WHITE)];
case RESULT_UNKNOWN:
unknownFound = true;
break;
if (r == RESULT_DRAW)
return RESULT_DRAW;
case RESULT_WIN: case RESULT_INVALID:
break;
default:
assert(false);
}
if (r == RESULT_UNKNOWN)
unknownFound = true;
}
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;
return unknownFound ? RESULT_UNKNOWN : RESULT_WIN;
}
}

View File

@@ -1,38 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(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)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,215 +17,34 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// Includes
////
#include <algorithm>
#include <cstring>
#include <iostream>
#include "bitboard.h"
#include "bitcount.h"
#include "direction.h"
#include "rkiss.h"
Bitboard RMasks[64];
Bitboard RMagics[64];
Bitboard* RAttacks[64];
int RShifts[64];
#if defined(IS_64BIT)
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
};
const uint64_t RMult[64] = {
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
};
const int BShift[64] = {
58, 59, 59, 59, 59, 59, 59, 58, 59, 59, 59, 59, 59, 59, 59, 59,
59, 59, 57, 57, 57, 57, 59, 59, 59, 59, 57, 55, 55, 57, 59, 59,
59, 59, 57, 55, 55, 57, 59, 59, 59, 59, 57, 57, 57, 57, 59, 59,
59, 59, 59, 59, 59, 59, 59, 59, 58, 59, 59, 59, 59, 59, 59, 58
};
const int RShift[64] = {
52, 53, 53, 53, 53, 53, 53, 52, 53, 54, 54, 54, 54, 54, 54, 53,
53, 54, 54, 54, 54, 54, 54, 53, 53, 54, 54, 54, 54, 54, 54, 53,
53, 54, 54, 54, 54, 54, 54, 53, 53, 54, 54, 54, 54, 54, 54, 53,
53, 54, 54, 54, 54, 54, 54, 53, 52, 53, 53, 53, 53, 53, 53, 52
};
#else // if !defined(IS_64BIT)
const uint64_t BMult[64] = {
0x54142844c6a22981ULL, 0x710358a6ea25c19eULL, 0x704f746d63a4a8dcULL,
0xbfed1a0b80f838c5ULL, 0x90561d5631e62110ULL, 0x2804260376e60944ULL,
0x84a656409aa76871ULL, 0xf0267f64c28b6197ULL, 0x70764ebb762f0585ULL,
0x92aa09e0cfe161deULL, 0x41ee1f6bb266f60eULL, 0xddcbf04f6039c444ULL,
0x5a3fab7bac0d988aULL, 0xd3727877fa4eaa03ULL, 0xd988402d868ddaaeULL,
0x812b291afa075c7cULL, 0x94faf987b685a932ULL, 0x3ed867d8470d08dbULL,
0x92517660b8901de8ULL, 0x2d97e43e058814b4ULL, 0x880a10c220b25582ULL,
0xc7c6520d1f1a0477ULL, 0xdbfc7fbcd7656aa6ULL, 0x78b1b9bfb1a2b84fULL,
0x2f20037f112a0bc1ULL, 0x657171ea2269a916ULL, 0xc08302b07142210eULL,
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 BMasks[64];
Bitboard BMagics[64];
Bitboard* BAttacks[64];
int BShifts[64];
Bitboard SetMaskBB[65];
Bitboard ClearMaskBB[65];
Bitboard StepAttackBB[16][64];
Bitboard RayBB[64][8];
Bitboard FileBB[8];
Bitboard RankBB[8];
Bitboard NeighboringFilesBB[8];
Bitboard ThisAndNeighboringFilesBB[8];
Bitboard InFrontBB[2][8];
Bitboard StepAttacksBB[16][64];
Bitboard BetweenBB[64][64];
Bitboard SquaresInFrontMask[2][64];
Bitboard PassedPawnMask[2][64];
Bitboard AttackSpanMask[2][64];
@@ -235,105 +54,60 @@ Bitboard RookPseudoAttacks[64];
Bitboard QueenPseudoAttacks[64];
uint8_t BitCount8Bit[256];
////
//// Local definitions
////
int SquareDistance[64][64];
namespace {
void init_masks();
void init_ray_bitboards();
void init_attacks();
void init_between_bitboards();
void init_pseudo_attacks();
Bitboard index_to_bitboard(int index, Bitboard mask);
Bitboard sliding_attacks(int sq, Bitboard block, int dirs, int deltas[][2],
int fmin, int fmax, int rmin, int rmax);
void init_sliding_attacks(Bitboard attacks[], int attackIndex[], Bitboard mask[],
const int shift[], const Bitboard mult[], int deltas[][2]);
CACHE_LINE_ALIGNMENT
int BSFTable[64];
Bitboard RookTable[0x19000]; // Storage space for rook attacks
Bitboard BishopTable[0x1480]; // Storage space for bishop attacks
void init_magic_bitboards(PieceType pt, Bitboard* attacks[], Bitboard magics[],
Bitboard masks[], int shifts[]);
}
////
//// Functions
////
/// print_bitboard() prints a bitboard in an easily readable format to the
/// standard output. This is sometimes useful for debugging.
/// standard output. This is sometimes useful for debugging.
void print_bitboard(Bitboard b) {
for (Rank r = RANK_8; r >= RANK_1; r--)
{
std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
std::cout << "+---+---+---+---+---+---+---+---+" << '\n';
for (File f = FILE_A; f <= FILE_H; f++)
std::cout << "| " << (bit_is_set(b, make_square(f, r))? 'X' : ' ') << ' ';
std::cout << "| " << (bit_is_set(b, make_square(f, r)) ? "X " : " ");
std::cout << "|" << std::endl;
std::cout << "|\n";
}
std::cout << "+---+---+---+---+---+---+---+---+" << std::endl;
}
/// init_bitboards() initializes various bitboard arrays. It is called during
/// program initialization.
void init_bitboards() {
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();
}
/// 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(IS_64BIT) && !defined(USE_BSFQ)
static CACHE_LINE_ALIGNMENT
const int BitTable[64] = {
0, 1, 2, 7, 3, 13, 8, 19, 4, 25, 14, 28, 9, 34, 20, 40, 5, 17, 26, 38, 15,
46, 29, 48, 10, 31, 35, 54, 21, 50, 41, 57, 63, 6, 12, 18, 24, 27, 33, 39,
16, 37, 45, 47, 30, 53, 49, 56, 62, 11, 23, 32, 36, 44, 52, 55, 61, 22, 43,
51, 60, 42, 59, 58
};
Square first_1(Bitboard b) {
return Square(BitTable[((b & -b) * 0x218a392cd3d5dbfULL) >> 58]);
return Square(BSFTable[((b & -b) * 0x218A392CD3D5DBFULL) >> 58]);
}
Square pop_1st_bit(Bitboard* b) {
Bitboard bb = *b;
*b &= (*b - 1);
return Square(BitTable[((bb & -bb) * 0x218a392cd3d5dbfULL) >> 58]);
return Square(BSFTable[((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]);
uint32_t fold = unsigned(b) ^ unsigned(b >> 32);
return Square(BSFTable[(fold * 0x783A9B23) >> 26]);
}
// Use type-punning
@@ -360,185 +134,233 @@ Square pop_1st_bit(Bitboard* bb) {
if (u.dw.l)
{
ret = Square(BitTable[((u.dw.l ^ (u.dw.l - 1)) * 0x783a9b23) >> 26]);
ret = Square(BSFTable[((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]);
ret = Square(BSFTable[((~(u.dw.h ^ (u.dw.h - 1))) * 0x783A9B23) >> 26]);
u.dw.h &= (u.dw.h - 1);
*bb = u.b;
return ret;
}
#endif
#endif // !defined(USE_BSFQ)
/// bitboards_init() initializes various bitboard arrays. It is called during
/// program initialization.
void bitboards_init() {
for (Bitboard b = 0; b < 256; b++)
BitCount8Bit[b] = (uint8_t)popcount<Max15>(b);
for (Square s = SQ_A1; s <= SQ_H8; s++)
{
SetMaskBB[s] = 1ULL << s;
ClearMaskBB[s] = ~SetMaskBB[s];
}
ClearMaskBB[SQ_NONE] = ~0ULL;
FileBB[FILE_A] = FileABB;
RankBB[RANK_1] = Rank1BB;
for (int f = FILE_B; f <= FILE_H; f++)
{
FileBB[f] = FileBB[f - 1] << 1;
RankBB[f] = RankBB[f - 1] << 8;
}
for (int f = FILE_A; f <= FILE_H; f++)
{
NeighboringFilesBB[f] = (f > FILE_A ? FileBB[f - 1] : 0) | (f < FILE_H ? FileBB[f + 1] : 0);
ThisAndNeighboringFilesBB[f] = FileBB[f] | NeighboringFilesBB[f];
}
for (int rw = RANK_7, rb = RANK_2; rw >= RANK_1; rw--, rb++)
{
InFrontBB[WHITE][rw] = InFrontBB[WHITE][rw + 1] | RankBB[rw + 1];
InFrontBB[BLACK][rb] = InFrontBB[BLACK][rb - 1] | RankBB[rb - 1];
}
for (Color c = WHITE; c <= BLACK; c++)
for (Square s = SQ_A1; s <= SQ_H8; s++)
{
SquaresInFrontMask[c][s] = in_front_bb(c, s) & file_bb(s);
PassedPawnMask[c][s] = in_front_bb(c, s) & this_and_neighboring_files_bb(file_of(s));
AttackSpanMask[c][s] = in_front_bb(c, s) & neighboring_files_bb(file_of(s));
}
for (Square s1 = SQ_A1; s1 <= SQ_H8; s1++)
for (Square s2 = SQ_A1; s2 <= SQ_H8; s2++)
SquareDistance[s1][s2] = std::max(file_distance(s1, s2), rank_distance(s1, s2));
for (int i = 0; i < 64; i++)
if (!Is64Bit) // Matt Taylor's folding trick for 32 bit systems
{
Bitboard b = 1ULL << i;
b ^= b - 1;
b ^= b >> 32;
BSFTable[uint32_t(b * 0x783A9B23) >> 26] = i;
}
else
BSFTable[((1ULL << i) * 0x218A392CD3D5DBFULL) >> 58] = i;
int steps[][9] = { {}, { 7, 9 }, { 17, 15, 10, 6, -6, -10, -15, -17 },
{}, {}, {}, { 9, 7, -7, -9, 8, 1, -1, -8 } };
for (Color c = WHITE; c <= BLACK; c++)
for (PieceType pt = PAWN; pt <= KING; pt++)
for (Square s = SQ_A1; s <= SQ_H8; s++)
for (int k = 0; steps[pt][k]; k++)
{
Square to = s + Square(c == WHITE ? steps[pt][k] : -steps[pt][k]);
if (square_is_ok(to) && square_distance(s, to) < 3)
set_bit(&StepAttacksBB[make_piece(c, pt)][s], to);
}
init_magic_bitboards(ROOK, RAttacks, RMagics, RMasks, RShifts);
init_magic_bitboards(BISHOP, BAttacks, BMagics, BMasks, BShifts);
for (Square s = SQ_A1; s <= SQ_H8; s++)
{
BishopPseudoAttacks[s] = bishop_attacks_bb(s, 0);
RookPseudoAttacks[s] = rook_attacks_bb(s, 0);
QueenPseudoAttacks[s] = queen_attacks_bb(s, 0);
}
for (Square s1 = SQ_A1; s1 <= SQ_H8; s1++)
for (Square s2 = SQ_A1; s2 <= SQ_H8; s2++)
if (bit_is_set(QueenPseudoAttacks[s1], s2))
{
Square delta = (s2 - s1) / square_distance(s1, s2);
for (Square s = s1 + delta; s != s2; s += delta)
set_bit(&BetweenBB[s1][s2], s);
}
}
namespace {
// All functions below are used to precompute various bitboards during
// program initialization. Some of the functions may be difficult to
// understand, but they all seem to work correctly, and it should never
// be necessary to touch any of them.
Bitboard sliding_attacks(PieceType pt, Square sq, Bitboard occupied) {
void init_masks() {
Square deltas[][4] = { { DELTA_N, DELTA_E, DELTA_S, DELTA_W },
{ DELTA_NE, DELTA_SE, DELTA_SW, DELTA_NW } };
Bitboard attacks = 0;
Square* delta = (pt == ROOK ? deltas[0] : deltas[1]);
SetMaskBB[SQ_NONE] = 0ULL;
ClearMaskBB[SQ_NONE] = ~SetMaskBB[SQ_NONE];
for (Square s = SQ_A1; s <= SQ_H8; s++)
for (int i = 0; i < 4; i++)
{
SetMaskBB[s] = (1ULL << s);
ClearMaskBB[s] = ~SetMaskBB[s];
}
Square s = sq + delta[i];
for (Color c = WHITE; c <= BLACK; c++)
for (Square s = SQ_A1; s <= SQ_H8; s++)
while (square_is_ok(s) && square_distance(s, s - delta[i]) == 1)
{
SquaresInFrontMask[c][s] = in_front_bb(c, s) & file_bb(s);
PassedPawnMask[c][s] = in_front_bb(c, s) & this_and_neighboring_files_bb(s);
AttackSpanMask[c][s] = in_front_bb(c, s) & neighboring_files_bb(s);
}
set_bit(&attacks, s);
for (Bitboard b = 0ULL; b < 256ULL; b++)
BitCount8Bit[b] = (uint8_t)count_1s(b);
}
int remove_bit_8(int i) { return ((i & ~15) >> 1) | (i & 7); }
void init_ray_bitboards() {
int d[8] = {1, -1, 16, -16, 17, -17, 15, -15};
for (int i = 0; i < 128; i = (i + 9) & ~8)
for (int j = 0; j < 8; j++)
{
RayBB[remove_bit_8(i)][j] = EmptyBoardBB;
for (int k = i + d[j]; (k & 0x88) == 0; k += d[j])
set_bit(&(RayBB[remove_bit_8(i)][j]), Square(remove_bit_8(k)));
}
}
void init_attacks() {
const 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 (int i = 0; i < 64; i++)
for (int j = 0; j <= int(BK); j++)
{
StepAttackBB[j][i] = EmptyBoardBB;
for (int k = 0; k < 8 && step[j][k] != 0; k++)
{
int 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;
int fl = sq % 8;
for (int i = 0; i < dirs; i++)
{
int dx = deltas[i][0];
int dy = deltas[i][1];
int f = fl + dx;
int r = rk + dy;
while ( (dx == 0 || (f >= fmin && f <= fmax))
&& (dy == 0 || (r >= rmin && r <= rmax)))
{
result |= (1ULL << (f + r*8));
if (block & (1ULL << (f + r*8)))
if (bit_is_set(occupied, s))
break;
f += dx;
r += dy;
s += delta[i];
}
}
return result;
return attacks;
}
void init_between_bitboards() {
const SquareDelta step[8] = { DELTA_E, DELTA_W, DELTA_N, DELTA_S,
DELTA_NE, DELTA_SW, DELTA_NW, DELTA_SE };
Bitboard pick_random(Bitboard mask, RKISS& rk, int booster) {
for (Square s1 = SQ_A1; s1 <= SQ_H8; s1++)
for (Square s2 = SQ_A1; s2 <= SQ_H8; s2++)
{
BetweenBB[s1][s2] = EmptyBoardBB;
SignedDirection d = signed_direction_between_squares(s1, s2);
Bitboard magic;
if (d != SIGNED_DIR_NONE)
{
for (Square s3 = s1 + step[d]; s3 != s2; s3 += step[d])
set_bit(&(BetweenBB[s1][s2]), s3);
}
}
}
// Values s1 and s2 are used to rotate the candidate magic of a
// quantity known to be the optimal to quickly find the magics.
int s1 = booster & 63, s2 = (booster >> 6) & 63;
Bitboard index_to_bitboard(int index, Bitboard mask) {
Bitboard result = 0ULL;
int bits = count_1s(mask);
for (int i = 0; i < bits; i++)
while (true)
{
int j = pop_1st_bit(&mask);
if (index & (1 << i))
result |= (1ULL << j);
}
return result;
}
magic = rk.rand<Bitboard>();
magic = (magic >> s1) | (magic << (64 - s1));
magic &= rk.rand<Bitboard>();
magic = (magic >> s2) | (magic << (64 - s2));
magic &= rk.rand<Bitboard>();
void init_sliding_attacks(Bitboard attacks[], int attackIndex[], Bitboard mask[],
const int shift[], const Bitboard mult[], int deltas[][2]) {
for (int i = 0, index = 0; i < 64; i++)
{
attackIndex[i] = index;
mask[i] = sliding_attacks(i, 0ULL, 4, deltas, 1, 6, 1, 6);
#if defined(IS_64BIT)
int j = (1 << (64 - shift[i]));
#else
int j = (1 << (32 - shift[i]));
#endif
for (int k = 0; k < j; k++)
{
#if defined(IS_64BIT)
Bitboard b = index_to_bitboard(k, mask[i]);
attacks[index + ((b * mult[i]) >> shift[i])] = sliding_attacks(i, b, 4, deltas);
#else
Bitboard b = index_to_bitboard(k, mask[i]);
unsigned v = int(b) * int(mult[i]) ^ int(b >> 32) * int(mult[i] >> 32);
attacks[index + (v >> shift[i])] = sliding_attacks(i, b, 4, deltas);
#endif
}
index += j;
if (BitCount8Bit[(mask * magic) >> 56] >= 6)
return magic;
}
}
void init_pseudo_attacks() {
// init_magic_bitboards() computes all rook and bishop magics at startup.
// Magic bitboards are used to look up attacks of sliding pieces. As reference
// see chessprogramming.wikispaces.com/Magic+Bitboards. In particular, here we
// use the so called "fancy" approach.
void init_magic_bitboards(PieceType pt, Bitboard* attacks[], Bitboard magics[],
Bitboard masks[], int shifts[]) {
int MagicBoosters[][8] = { { 3191, 2184, 1310, 3618, 2091, 1308, 2452, 3996 },
{ 1059, 3608, 605, 3234, 3326, 38, 2029, 3043 } };
RKISS rk;
Bitboard occupancy[4096], reference[4096], edges, b;
int i, size, index, booster;
// attacks[s] is a pointer to the beginning of the attacks table for square 's'
attacks[SQ_A1] = (pt == ROOK ? RookTable : BishopTable);
for (Square s = SQ_A1; s <= SQ_H8; s++)
{
BishopPseudoAttacks[s] = bishop_attacks_bb(s, EmptyBoardBB);
RookPseudoAttacks[s] = rook_attacks_bb(s, EmptyBoardBB);
QueenPseudoAttacks[s] = queen_attacks_bb(s, EmptyBoardBB);
// Board edges are not considered in the relevant occupancies
edges = ((Rank1BB | Rank8BB) & ~rank_bb(s)) | ((FileABB | FileHBB) & ~file_bb(s));
// Given a square 's', the mask is the bitboard of sliding attacks from
// 's' computed on an empty board. The index must be big enough to contain
// all the attacks for each possible subset of the mask and so is 2 power
// the number of 1s of the mask. Hence we deduce the size of the shift to
// apply to the 64 or 32 bits word to get the index.
masks[s] = sliding_attacks(pt, s, 0) & ~edges;
shifts[s] = (Is64Bit ? 64 : 32) - popcount<Max15>(masks[s]);
// Use Carry-Rippler trick to enumerate all subsets of masks[s] and
// store the corresponding sliding attacks bitboard in reference[].
b = size = 0;
do {
occupancy[size] = b;
reference[size++] = sliding_attacks(pt, s, b);
b = (b - masks[s]) & masks[s];
} while (b);
// Set the offset for the table of the next square. We have individual
// table sizes for each square with "Fancy Magic Bitboards".
if (s < SQ_H8)
attacks[s + 1] = attacks[s] + size;
booster = MagicBoosters[Is64Bit][rank_of(s)];
// Find a magic for square 's' picking up an (almost) random number
// until we find the one that passes the verification test.
do {
magics[s] = pick_random(masks[s], rk, booster);
memset(attacks[s], 0, size * sizeof(Bitboard));
// A good magic must map every possible occupancy to an index that
// looks up the correct sliding attack in the attacks[s] database.
// Note that we build up the database for square 's' as a side
// effect of verifying the magic.
for (i = 0; i < size; i++)
{
index = (pt == ROOK ? rook_index(s, occupancy[i])
: bishop_index(s, occupancy[i]));
if (!attacks[s][index])
attacks[s][index] = reference[i];
else if (attacks[s][index] != reference[i])
break;
}
} while (i != size);
}
}
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -18,77 +18,36 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(BITBOARD_H_INCLUDED)
#define BITBOARD_H_INCLUDED
////
//// Includes
////
#include "direction.h"
#include "piece.h"
#include "square.h"
#include "types.h"
////
//// Constants and variables
////
const Bitboard EmptyBoardBB = 0ULL;
const Bitboard WhiteSquaresBB = 0x55AA55AA55AA55AAULL;
const Bitboard BlackSquaresBB = 0xAA55AA55AA55AA55ULL;
const Bitboard FileABB = 0x0101010101010101ULL;
const Bitboard FileBBB = 0x0202020202020202ULL;
const Bitboard FileCBB = 0x0404040404040404ULL;
const Bitboard FileDBB = 0x0808080808080808ULL;
const Bitboard FileEBB = 0x1010101010101010ULL;
const Bitboard FileFBB = 0x2020202020202020ULL;
const Bitboard FileGBB = 0x4040404040404040ULL;
const Bitboard FileHBB = 0x8080808080808080ULL;
const Bitboard Rank1BB = 0xFFULL;
const Bitboard Rank2BB = 0xFF00ULL;
const Bitboard Rank3BB = 0xFF0000ULL;
const Bitboard Rank4BB = 0xFF000000ULL;
const Bitboard Rank5BB = 0xFF00000000ULL;
const Bitboard Rank6BB = 0xFF0000000000ULL;
const Bitboard Rank7BB = 0xFF000000000000ULL;
const Bitboard Rank8BB = 0xFF00000000000000ULL;
extern const Bitboard SquaresByColorBB[2];
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 FileBB[8];
extern Bitboard NeighboringFilesBB[8];
extern Bitboard ThisAndNeighboringFilesBB[8];
extern Bitboard RankBB[8];
extern Bitboard InFrontBB[2][8];
extern Bitboard SetMaskBB[65];
extern Bitboard ClearMaskBB[65];
extern Bitboard StepAttackBB[16][64];
extern Bitboard RayBB[64][8];
extern Bitboard StepAttacksBB[16][64];
extern Bitboard BetweenBB[64][64];
extern Bitboard SquaresInFrontMask[2][64];
extern Bitboard PassedPawnMask[2][64];
extern Bitboard AttackSpanMask[2][64];
extern const uint64_t RMult[64];
extern const int RShift[64];
extern Bitboard RMask[64];
extern int RAttackIndex[64];
extern Bitboard RAttacks[0x19000];
extern uint64_t RMagics[64];
extern int RShifts[64];
extern Bitboard RMasks[64];
extern Bitboard* RAttacks[64];
extern const uint64_t BMult[64];
extern const int BShift[64];
extern Bitboard BMask[64];
extern int BAttackIndex[64];
extern Bitboard BAttacks[0x1480];
extern uint64_t BMagics[64];
extern int BShifts[64];
extern Bitboard BMasks[64];
extern Bitboard* BAttacks[64];
extern Bitboard BishopPseudoAttacks[64];
extern Bitboard RookPseudoAttacks[64];
@@ -97,10 +56,6 @@ extern Bitboard QueenPseudoAttacks[64];
extern uint8_t BitCount8Bit[256];
////
//// Inline functions
////
/// Functions for testing whether a given bit is set in a bitboard, and for
/// setting and clearing bits.
@@ -108,11 +63,11 @@ inline Bitboard bit_is_set(Bitboard b, Square s) {
return b & SetMaskBB[s];
}
inline void set_bit(Bitboard *b, Square s) {
inline void set_bit(Bitboard* b, Square s) {
*b |= SetMaskBB[s];
}
inline void clear_bit(Bitboard *b, Square s) {
inline void clear_bit(Bitboard* b, Square s) {
*b &= ClearMaskBB[s];
}
@@ -124,11 +79,12 @@ inline Bitboard make_move_bb(Square from, Square to) {
return SetMaskBB[from] | SetMaskBB[to];
}
inline void do_move_bb(Bitboard *b, Bitboard move_bb) {
inline void do_move_bb(Bitboard* b, Bitboard move_bb) {
*b ^= move_bb;
}
/// rank_bb() and file_bb() take a file or a square as input, and return
/// rank_bb() and file_bb() take a file or a square as input and return
/// a bitboard representing all squares on the given file or rank.
inline Bitboard rank_bb(Rank r) {
@@ -136,7 +92,7 @@ inline Bitboard rank_bb(Rank r) {
}
inline Bitboard rank_bb(Square s) {
return rank_bb(square_rank(s));
return RankBB[rank_of(s)];
}
inline Bitboard file_bb(File f) {
@@ -144,45 +100,25 @@ inline Bitboard file_bb(File f) {
}
inline Bitboard file_bb(Square s) {
return file_bb(square_file(s));
return FileBB[file_of(s)];
}
/// neighboring_files_bb takes a file or a square as input, and returns a
/// bitboard representing all squares on the neighboring files.
/// neighboring_files_bb takes a file as input and returns a bitboard representing
/// all squares on the neighboring files.
inline Bitboard neighboring_files_bb(File f) {
return NeighboringFilesBB[f];
}
inline Bitboard neighboring_files_bb(Square s) {
return NeighboringFilesBB[square_file(s)];
}
/// this_and_neighboring_files_bb takes a file or a square as input, and
/// returns a bitboard representing all squares on the given and neighboring
/// files.
/// this_and_neighboring_files_bb takes a file as input and returns a bitboard
/// representing all squares on the given and neighboring files.
inline Bitboard this_and_neighboring_files_bb(File f) {
return ThisAndNeighboringFilesBB[f];
}
inline Bitboard this_and_neighboring_files_bb(Square s) {
return ThisAndNeighboringFilesBB[square_file(s)];
}
/// relative_rank_bb() takes a color and a rank as input, and returns a bitboard
/// representing all squares on the given rank from the given color's point of
/// view. For instance, relative_rank_bb(WHITE, 7) gives all squares on the
/// 7th rank, while relative_rank_bb(BLACK, 7) gives all squares on the 2nd
/// rank.
inline Bitboard relative_rank_bb(Color c, Rank r) {
return RelativeRankBB[c][r];
}
/// in_front_bb() takes a color and a rank or square as input, and returns a
/// bitboard representing all the squares on all ranks in front of the rank
@@ -195,28 +131,7 @@ inline Bitboard in_front_bb(Color c, Rank r) {
}
inline Bitboard in_front_bb(Color c, Square s) {
return InFrontBB[c][square_rank(s)];
}
/// 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.
inline Bitboard behind_bb(Color c, Rank r) {
return InFrontBB[opposite_color(c)][r];
}
inline Bitboard behind_bb(Color c, Square s) {
return InFrontBB[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];
return InFrontBB[c][rank_of(s)];
}
@@ -227,36 +142,35 @@ inline Bitboard ray_bb(Square s, SignedDirection d) {
#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])];
FORCE_INLINE unsigned rook_index(Square s, Bitboard occ) {
return unsigned(((occ & RMasks[s]) * RMagics[s]) >> RShifts[s]);
}
inline Bitboard bishop_attacks_bb(Square s, Bitboard blockers) {
Bitboard b = blockers & BMask[s];
return BAttacks[BAttackIndex[s] + ((b * BMult[s]) >> BShift[s])];
FORCE_INLINE unsigned bishop_index(Square s, Bitboard occ) {
return unsigned(((occ & BMasks[s]) * BMagics[s]) >> BShifts[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])];
FORCE_INLINE unsigned rook_index(Square s, Bitboard occ) {
Bitboard b = occ & RMasks[s];
return unsigned(int(b) * int(RMagics[s]) ^ int(b >> 32) * int(RMagics[s] >> 32)) >> RShifts[s];
}
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])];
FORCE_INLINE unsigned bishop_index(Square s, Bitboard occ) {
Bitboard b = occ & BMasks[s];
return unsigned(int(b) * int(BMagics[s]) ^ int(b >> 32) * int(BMagics[s] >> 32)) >> BShifts[s];
}
#endif
inline Bitboard rook_attacks_bb(Square s, Bitboard occ) {
return RAttacks[s][rook_index(s, occ)];
}
inline Bitboard bishop_attacks_bb(Square s, Bitboard occ) {
return BAttacks[s][bishop_index(s, occ)];
}
inline Bitboard queen_attacks_bb(Square s, Bitboard blockers) {
return rook_attacks_bb(s, blockers) | bishop_attacks_bb(s, blockers);
}
@@ -282,14 +196,6 @@ inline Bitboard squares_in_front_of(Color c, Square 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 SquaresInFrontMask[opposite_color(c)][s];
}
/// passed_pawn_mask takes a color and a square as input, and returns a
/// bitboard mask which can be used to test if a pawn of the given color on
/// the given square is a passed pawn. Definition of the table is:
@@ -310,19 +216,47 @@ inline Bitboard attack_span_mask(Color c, Square s) {
}
/// squares_aligned returns true if the squares s1, s2 and s3 are aligned
/// either on a straight or on a diagonal line.
inline bool squares_aligned(Square s1, Square s2, Square s3) {
return (BetweenBB[s1][s2] | BetweenBB[s1][s3] | BetweenBB[s2][s3])
& ( SetMaskBB[s1] | SetMaskBB[s2] | SetMaskBB[s3]);
}
/// same_color_squares() returns a bitboard representing all squares with
/// the same color of the given square.
inline Bitboard same_color_squares(Square s) {
return bit_is_set(0xAA55AA55AA55AA55ULL, s) ? 0xAA55AA55AA55AA55ULL
: ~0xAA55AA55AA55AA55ULL;
}
/// 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
#if defined(USE_BSFQ)
inline Square first_1(Bitboard b) {
#if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
FORCE_INLINE Square first_1(Bitboard b) {
unsigned long index;
_BitScanForward64(&index, b);
return (Square) index;
}
#else
FORCE_INLINE Square first_1(Bitboard b) { // Assembly code by Heinz van Saanen
Bitboard dummy;
__asm__("bsfq %1, %0": "=r"(dummy): "rm"(b) );
return (Square)(dummy);
return (Square) dummy;
}
#endif
inline Square pop_1st_bit(Bitboard* b) {
FORCE_INLINE Square pop_1st_bit(Bitboard* b) {
const Square s = first_1(*b);
*b &= ~(1ULL<<s);
return s;
@@ -336,12 +270,7 @@ extern Square pop_1st_bit(Bitboard* b);
#endif
////
//// Prototypes
////
extern void print_bitboard(Bitboard b);
extern void init_bitboards();
extern void bitboards_init();
#endif // !defined(BITBOARD_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -18,33 +18,32 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(BITCOUNT_H_INCLUDED)
#define BITCOUNT_H_INCLUDED
#include <cassert>
#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(USE_POPCNT)
#define POPCNT_INTRINSIC(x) 0
#elif defined(_MSC_VER)
#define POPCNT_INTRINSIC(x) (int)__popcnt64(x)
#elif defined(__GNUC__)
enum BitCountType {
CNT_64,
CNT_64_MAX15,
CNT_32,
CNT_32_MAX15,
CNT_HW_POPCNT
};
#define POPCNT_INTRINSIC(x) ({ \
unsigned long __ret; \
__asm__("popcnt %1, %0" : "=r" (__ret) : "r" (x)); \
__ret; })
#endif
/// Determine at compile time the best popcount<> specialization according if
/// platform is 32 or 64 bits, to the maximum number of nonzero bits to count or
/// use hardware popcnt instruction when available.
const BitCountType Full = HasPopCnt ? CNT_HW_POPCNT : Is64Bit ? CNT_64 : CNT_32;
const BitCountType Max15 = HasPopCnt ? CNT_HW_POPCNT : Is64Bit ? CNT_64_MAX15 : CNT_32_MAX15;
/// Software implementation of bit count functions
/// popcount() counts the number of nonzero bits in a bitboard
template<BitCountType> inline int popcount(Bitboard);
#if defined(IS_64BIT)
inline int count_1s(Bitboard b) {
template<>
inline int popcount<CNT_64>(Bitboard b) {
b -= ((b>>1) & 0x5555555555555555ULL);
b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
b = ((b>>4) + b) & 0x0F0F0F0F0F0F0F0FULL;
@@ -52,16 +51,16 @@ inline int count_1s(Bitboard b) {
return int(b >> 56);
}
inline int count_1s_max_15(Bitboard b) {
template<>
inline int popcount<CNT_64_MAX15>(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) {
template<>
inline int popcount<CNT_32>(Bitboard b) {
unsigned w = unsigned(b >> 32), v = unsigned(b);
v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits
w -= (w >> 1) & 0x55555555;
@@ -73,7 +72,8 @@ inline int count_1s(Bitboard b) {
return int(v >> 24);
}
inline int count_1s_max_15(Bitboard b) {
template<>
inline int popcount<CNT_32_MAX15>(Bitboard b) {
unsigned w = unsigned(b >> 32), v = unsigned(b);
v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits
w -= (w >> 1) & 0x55555555;
@@ -84,51 +84,29 @@ inline int count_1s_max_15(Bitboard b) {
return int(v >> 28);
}
#endif // BITCOUNT
template<>
inline int popcount<CNT_HW_POPCNT>(Bitboard b) {
#if !defined(USE_POPCNT)
/// 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.
assert(false);
return int(b != 0); // Avoid 'b not used' warning
template<bool UseIntrinsic>
inline int count_1s(Bitboard b) {
#elif defined(_MSC_VER) && defined(__INTEL_COMPILER)
return UseIntrinsic ? POPCNT_INTRINSIC(b) : count_1s(b);
}
return _mm_popcnt_u64(b);
template<bool UseIntrinsic>
inline int count_1s_max_15(Bitboard b) {
#elif defined(_MSC_VER)
return UseIntrinsic ? POPCNT_INTRINSIC(b) : count_1s_max_15(b);
}
return (int)__popcnt64(b);
// Detect hardware POPCNT support
inline bool cpu_has_popcnt() {
int CPUInfo[4] = {-1};
__cpuid(CPUInfo, 0x00000001);
return (CPUInfo[2] >> 23) & 1;
}
// 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.
#if defined(USE_POPCNT)
const bool CpuHasPOPCNT = cpu_has_popcnt();
#else
const bool CpuHasPOPCNT = false;
#endif
unsigned long ret;
__asm__("popcnt %1, %0" : "=r" (ret) : "r" (b));
return ret;
// 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)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,46 +17,26 @@
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
by Fabien Letouzey. PolyGlot is available under the GNU General
Public License, and can be downloaded from http://wbec-ridderkerk.nl
*/
////
//// Includes
////
#include <algorithm>
#include <cassert>
#include <iostream>
#include "book.h"
#include "mersenne.h"
#include "misc.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] = {
// Random numbers from PolyGlot, used to compute book hash keys
const Key PolyGlotRandoms[781] = {
0x9D39247E33776D41ULL, 0x2AF7398005AAA5C7ULL, 0x44DB015024623547ULL,
0x9C15F73E62A76AE2ULL, 0x75834465489C0C89ULL, 0x3290AC3A203001BFULL,
0x0FBBAD1F61042279ULL, 0xE83A908FF2FB60CAULL, 0x0D7E765D58755C10ULL,
@@ -320,276 +300,188 @@ namespace {
0xF8D626AAAF278509ULL
};
// Offsets to the PolyGlotRandoms[] array of zobrist keys
const Key* ZobPiece = PolyGlotRandoms + 0;
const Key* ZobCastle = PolyGlotRandoms + 768;
const Key* ZobEnPassant = PolyGlotRandoms + 772;
const Key* ZobTurn = PolyGlotRandoms + 780;
/// Indices to the Random64[] array
// PieceOffset is calculated as 64 * (PolyPiece ^ 1) where PolyPiece
// is: BP = 0, WP = 1, BN = 2, WN = 3 ... BK = 10, WK = 11
const int PieceOffset[] = { 0, 64, 192, 320, 448, 576, 704, 0,
0, 0, 128, 256, 384, 512, 640 };
const int RandomPiece = 0;
const int RandomCastle = 768;
const int RandomEnPassant = 772;
const int RandomTurn = 780;
// book_key() returns the PolyGlot hash key of the given position
uint64_t book_key(const Position& pos) {
uint64_t key = 0;
Bitboard b = pos.occupied_squares();
while (b)
{
Square s = pop_1st_bit(&b);
key ^= ZobPiece[PieceOffset[pos.piece_on(s)] + s];
}
b = (pos.can_castle(WHITE_OO) << 0) | (pos.can_castle(WHITE_OOO) << 1)
| (pos.can_castle(BLACK_OO) << 2) | (pos.can_castle(BLACK_OOO) << 3);
while (b)
key ^= ZobCastle[pop_1st_bit(&b)];
if (pos.ep_square() != SQ_NONE)
key ^= ZobEnPassant[file_of(pos.ep_square())];
if (pos.side_to_move() == WHITE)
key ^= ZobTurn[0];
return key;
}
} // namespace
Book::Book() : size(0) {
for (int i = abs(system_time() % 10000); i > 0; i--)
RKiss.rand<unsigned>(); // Make random number generation less deterministic
}
Book::~Book() { if (is_open()) close(); }
/// Prototypes
/// Book::operator>>() reads sizeof(T) chars from the file's binary byte stream
/// and converts them in a number of type T. A Polyglot book stores numbers in
/// big-endian format.
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);
template<typename T> Book& Book::operator>>(T& n) {
n = 0;
for (size_t i = 0; i < sizeof(T); i++)
n = T((n << 8) + ifstream::get());
return *this;
}
template<> Book& Book::operator>>(BookEntry& e) {
return *this >> e.key >> e.move >> e.count >> e.learn;
}
////
//// Functions
////
/// Book::open() tries to open a book file with the given name after closing
/// any exsisting one.
bool Book::open(const char* fName) {
/// Destructor. Be sure file is closed before we leave.
fileName = "";
Book::~Book() {
if (is_open()) // Cannot close an already closed file
close();
close();
}
ifstream::open(fName, ifstream::in | ifstream::binary | ios::ate);
/// 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;
return false; // Silently fail if the file is not found
// Get the book size in number of entries
seekg(0, ios::end);
bookSize = tellg() / EntrySize;
seekg(0, ios::beg);
// Get the book size in number of entries, we are already at the end of file
size = tellg() / sizeof(BookEntry);
if (!good())
{
cerr << "Failed to open book file " << fileName << endl;
Application::exit_with_failure();
cerr << "Failed to open book file " << fName << endl;
exit(EXIT_FAILURE);
}
fileName = fName; // Set only if successful
return true;
}
/// 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.
/// Book::probe() tries to find a book move for the given position. If no move
/// is found returns MOVE_NONE. If pickBest is true returns always the highest
/// rated move, otherwise randomly chooses one, based on the move score.
void Book::close() {
Move Book::probe(const Position& pos, const string& fName, bool pickBest) {
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() { // Not const to compile on HP-UX 11.X
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, bool findBestMove) {
if (!is_open() || bookSize == 0)
return MOVE_NONE;
BookEntry entry;
int bookMove = MOVE_NONE;
int scoresSum = 0, bestScore = 0;
BookEntry e;
uint16_t best = 0;
unsigned sum = 0;
Move move = MOVE_NONE;
uint64_t key = book_key(pos);
// Choose a book move among the possible moves for the given position
for (int idx = find_key(key); idx < bookSize; idx++)
{
read_entry(entry, idx);
if (entry.key != key)
break;
int score = entry.count;
assert(score > 0);
// If findBestMove is true choose highest rated book move
if (findBestMove)
{
if (score > bestScore)
{
bestScore = score;
bookMove = entry.move;
}
continue;
}
// 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)
if (fileName != fName && !open(fName.c_str()))
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;
binary_search(key);
while (*this >> e, e.key == key && good())
{
best = max(best, e.count);
sum += e.count;
// Choose book move according to its score. If a move has a very
// high score it has higher probability to be choosen than a move
// with lower score. Note that first entry is always chosen.
if ( (RKiss.rand<unsigned>() % sum < e.count)
|| (pickBest && e.count == best))
move = Move(e.move);
}
if (!move)
return MOVE_NONE;
// A PolyGlot book move is encoded as follows:
//
// bit 0- 5: destination square (from 0 to 63)
// bit 6-11: origin square (from 0 to 63)
// bit 12-14: promotion piece (from KNIGHT == 1 to QUEEN == 4)
//
// Castling moves follow "king captures rook" representation. So in case book
// move is a promotion we have to convert to our representation, in all the
// other cases we can directly compare with a Move after having masked out
// the special Move's flags (bit 14-15) that are not supported by PolyGlot.
int pt = (move >> 12) & 7;
if (pt)
move = make_promotion(from_sq(move), to_sq(move), PieceType(pt + 1));
// Add 'special move' flags and verify it is legal
for (MoveList<MV_LEGAL> ml(pos); !ml.end(); ++ml)
if (move == (ml.move() & 0x3FFF))
return ml.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.
/// Book::binary_search() takes a book key as input, and does a binary search
/// through the book file for the given key. File stream current position is set
/// to the leftmost book entry with the same key as the input.
int Book::find_key(uint64_t key) {
void Book::binary_search(uint64_t key) {
int left, right, mid;
BookEntry entry;
size_t low, high, mid;
BookEntry e;
// Binary search (finds the leftmost entry)
left = 0;
right = bookSize - 1;
low = 0;
high = size - 1;
assert(left <= right);
assert(low <= high);
while (left < right)
while (low < high && good())
{
mid = (left + right) / 2;
mid = (low + high) / 2;
assert(mid >= left && mid < right);
assert(mid >= low && mid < high);
read_entry(entry, mid);
if (key <= entry.key)
right = mid;
seekg(mid * sizeof(BookEntry), ios_base::beg);
*this >> e;
if (key <= e.key)
high = mid;
else
left = mid + 1;
low = mid + 1;
}
assert(left == right);
assert(low == high);
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);
}
seekg(low * sizeof(BookEntry), ios_base::beg);
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,71 +17,42 @@
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"
#include "rkiss.h"
////
//// Types
////
/// A Polyglot book is a series of "entries" of 16 bytes. All integers are
/// stored highest byte first (regardless of size). The entries are ordered
/// according to key. Lowest key first.
struct BookEntry {
uint64_t key;
uint16_t move;
uint16_t count;
uint16_t n;
uint16_t sum;
uint32_t learn;
};
class Book : private std::ifstream {
Book(const Book&); // just decleared..
Book& operator=(const Book&); // ..to avoid a warning
public:
Book() {}
Book();
~Book();
void open(const std::string& fName);
void close();
const std::string file_name();
Move get_move(const Position& pos, bool findBestMove);
Move probe(const Position& pos, const std::string& fName, bool pickBest);
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; }
template<typename T> Book& operator>>(T& n);
uint64_t read_integer(int size);
void read_entry(BookEntry& e, int n);
int find_key(uint64_t key);
bool open(const char* fName);
void binary_search(uint64_t key);
RKISS RKiss;
std::string fileName;
int bookSize;
size_t size;
};
////
//// Global variables
////
extern Book OpeningBook;
#endif // !defined(BOOK_H_INCLUDED)

View File

@@ -1,50 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(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)

View File

@@ -1,61 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(DEPTH_H_INCLUDED)
#define DEPTH_H_INCLUDED
////
//// Types
////
enum Depth {
DEPTH_ZERO = 0,
DEPTH_MAX = 200, // 100 * OnePly;
DEPTH_ENSURE_SIGNED = -1
};
////
//// 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 void operator-= (Depth &d1, Depth d2) { d1 -= int(d2); }
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)

View File

@@ -1,87 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// 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;
}
}
}
}

View File

@@ -1,92 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(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)

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,90 +17,104 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(ENDGAME_H_INCLUDED)
#define ENDGAME_H_INCLUDED
////
//// Includes
////
#include <map>
#include <string>
#include "position.h"
#include "scale.h"
#include "value.h"
#include "types.h"
////
//// Types
////
/// EndgameType lists all supported endgames
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
// Evaluation functions
// 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
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
SCALE_FUNS,
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
/// Some magic to detect family type of endgame from its enum value
template<bool> struct bool_to_type { typedef Value type; };
template<> struct bool_to_type<true> { typedef ScaleFactor type; };
template<EndgameType E> struct eg_family : public bool_to_type<(E > SCALE_FUNS)> {};
/// Base and derived templates for endgame evaluation and scaling functions
template<typename T>
class EndgameFunctionBase {
public:
EndgameFunctionBase(Color c) : strongerSide(c), weakerSide(opposite_color(c)) {}
virtual ~EndgameFunctionBase() {}
virtual T apply(const Position&) const = 0;
Color color() const { return strongerSide; }
struct EndgameBase {
protected:
virtual ~EndgameBase() {}
virtual Color color() const = 0;
virtual T operator()(const Position&) const = 0;
};
template<EndgameType E, typename T = typename eg_family<E>::type>
struct Endgame : public EndgameBase<T> {
explicit Endgame(Color c) : strongerSide(c), weakerSide(flip(c)) {}
Color color() const { return strongerSide; }
T operator()(const Position&) const;
private:
Color strongerSide, weakerSide;
};
typedef EndgameFunctionBase<Value> EndgameEvaluationFunctionBase;
typedef EndgameFunctionBase<ScaleFactor> EndgameScalingFunctionBase;
/// Endgames class stores in two std::map the pointers to endgame evaluation
/// and scaling base objects. Then we use polymorphism to invoke the actual
/// endgame function calling its operator() method that is virtual.
/// Templates subclass for various concrete endgames
class Endgames {
template<EndgameType>
struct EvaluationFunction : public EndgameEvaluationFunctionBase {
typedef EndgameEvaluationFunctionBase Base;
explicit EvaluationFunction(Color c): EndgameEvaluationFunctionBase(c) {}
Value apply(const Position&) const;
typedef std::map<Key, EndgameBase<Value>*> M1;
typedef std::map<Key, EndgameBase<ScaleFactor>*> M2;
M1 m1;
M2 m2;
M1& map(Value*) { return m1; }
M2& map(ScaleFactor*) { return m2; }
template<EndgameType E> void add(const std::string& code);
public:
Endgames();
~Endgames();
template<typename T> EndgameBase<T>* get(Key key) {
return map((T*)0).count(key) ? map((T*)0)[key] : NULL;
}
};
template<EndgameType>
struct ScalingFunction : public EndgameScalingFunctionBase {
typedef EndgameScalingFunctionBase Base;
explicit ScalingFunction(Color c) : EndgameScalingFunctionBase(c) {}
ScaleFactor apply(const Position&) const;
};
////
//// Prototypes
////
extern void init_bitbases();
#endif // !defined(ENDGAME_H_INCLUDED)

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,94 +17,15 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(EVALUATE_H_INCLUDED)
#define EVALUATE_H_INCLUDED
////
//// Includes
////
#include "types.h"
#include <iostream>
#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;
struct EvalInfo {
EvalInfo() { kingDanger[0] = kingDanger[1] = Value(0); }
// Middle game and endgame evaluations
Score value;
// Pointers to material and pawn hash table entries
MaterialInfo* mi;
PawnInfo* pi;
// 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]; }
// kingZone[color] is the zone around the enemy king which is considered
// by the king safety evaluation. This consists of the squares directly
// adjacent to the king, and the three (or two, for a king on an edge file)
// squares two ranks in front of the king. For instance, if black's king
// is on g8, kingZone[WHITE] is a bitboard containing the squares f8, h8,
// f7, g7, h7, f6, g6 and h6.
Bitboard kingZone[2];
// 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];
// 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];
// Middle game and endgame mobility scores
Score mobility;
// Value of the danger for the king of the given color
Value kingDanger[2];
};
////
//// Prototypes
////
extern Value evaluate(const Position& pos, EvalInfo& ei);
extern void init_eval(int threads);
extern void quit_eval();
extern void read_weights(Color sideToMove);
extern Value evaluate(const Position& pos, Value& margin);
extern std::string trace_evaluate(const Position& pos);
extern void read_evaluation_uci_options(Color sideToMove);
#endif // !defined(EVALUATE_H_INCLUDED)

View File

@@ -1,115 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// 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));
memset(maxStaticValueDelta, 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] /= 2;
}
/// 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);
// Prevent history underflow
if (history[p][to] <= -HistoryMax)
for (int i = 0; i < 16; i++)
for (int j = 0; j < 64; j++)
history[i][j] /= 2;
}
/// 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];
}
/// History::set_gain() and History::gain() store and retrieve the
/// gain of a move given the delta of the static position evaluations
/// before and after the move.
void History::set_gain(Piece p, Square to, Value delta)
{
if (delta >= maxStaticValueDelta[p][to])
maxStaticValueDelta[p][to] = delta;
else
maxStaticValueDelta[p][to]--;
}
Value History::gain(Piece p, Square to) const
{
return Value(maxStaticValueDelta[p][to]);
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,23 +17,12 @@
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"
#include "value.h"
////
//// Types
////
#include "types.h"
#include <cstring>
#include <algorithm>
/// The History class stores statistics about how often different moves
/// have been successful or unsuccessful during the current search. These
@@ -45,33 +34,38 @@
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;
void set_gain(Piece p, Square to, Value delta);
Value value(Piece p, Square to) const;
void add(Piece p, Square to, Value bonus);
Value gain(Piece p, Square to) const;
void update_gain(Piece p, Square to, Value g);
static const Value MaxValue = Value(2000);
private:
int history[16][64]; // [piece][square]
int maxStaticValueDelta[16][64]; // [piece][from_square][to_square]
Value history[16][64]; // [piece][to_square]
Value maxGains[16][64]; // [piece][to_square]
};
inline void History::clear() {
memset(history, 0, 16 * 64 * sizeof(Value));
memset(maxGains, 0, 16 * 64 * sizeof(Value));
}
////
//// Constants and variables
////
inline Value History::value(Piece p, Square to) const {
return history[p][to];
}
/// 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 2. 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.
inline void History::add(Piece p, Square to, Value bonus) {
if (abs(history[p][to] + bonus) < MaxValue) history[p][to] += bonus;
}
const int HistoryMax = 50000 * OnePly;
inline Value History::gain(Piece p, Square to) const {
return maxGains[p][to];
}
inline void History::update_gain(Piece p, Square to, Value g) {
maxGains[p][to] = std::max(g, maxGains[p][to] - 1);
}
#endif // !defined(HISTORY_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,85 +17,68 @@
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)
#if !defined(_MSC_VER)
# include <pthread.h>
typedef pthread_mutex_t Lock;
typedef pthread_cond_t WaitCondition;
# define lock_init(x, y) pthread_mutex_init(x, y)
# define lock_init(x) pthread_mutex_init(x, NULL)
# define lock_grab(x) pthread_mutex_lock(x)
# define lock_release(x) pthread_mutex_unlock(x)
# define lock_destroy(x) pthread_mutex_destroy(x)
# define cond_destroy(x) pthread_cond_destroy(x)
# define cond_init(x) pthread_cond_init(x, NULL)
# define cond_signal(x) pthread_cond_signal(x)
# define cond_wait(x,y) pthread_cond_wait(x,y)
# define cond_timedwait(x,y,z) pthread_cond_timedwait(x,y,z)
#else
#define NOMINMAX // disable macros min() and max()
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
#undef NOMINMAX
// Default fast and race free locks and condition variables
#if !defined(OLD_LOCKS)
typedef SRWLOCK Lock;
typedef CONDITION_VARIABLE WaitCondition;
# define lock_init(x) InitializeSRWLock(x)
# define lock_grab(x) AcquireSRWLockExclusive(x)
# define lock_release(x) ReleaseSRWLockExclusive(x)
# define lock_destroy(x) (x)
# define cond_destroy(x) (x)
# define cond_init(x) InitializeConditionVariable(x)
# define cond_signal(x) WakeConditionVariable(x)
# define cond_wait(x,y) SleepConditionVariableSRW(x,y,INFINITE,0)
# define cond_timedwait(x,y,z) SleepConditionVariableSRW(x,y,z,0)
// Fallback solution to build for Windows XP and older versions, note that
// cond_wait() is racy between lock_release() and WaitForSingleObject().
#else
typedef CRITICAL_SECTION Lock;
# define lock_init(x, y) InitializeCriticalSection(x)
typedef HANDLE WaitCondition;
# define lock_init(x) InitializeCriticalSection(x)
# define lock_grab(x) EnterCriticalSection(x)
# define lock_release(x) LeaveCriticalSection(x)
# define lock_destroy(x) DeleteCriticalSection(x)
# define cond_init(x) { *x = CreateEvent(0, FALSE, FALSE, 0); }
# define cond_destroy(x) CloseHandle(*x)
# define cond_signal(x) SetEvent(*x)
# define cond_wait(x,y) { lock_release(y); WaitForSingleObject(*x, INFINITE); lock_grab(y); }
# define cond_timedwait(x,y,z) { lock_release(y); WaitForSingleObject(*x,z); lock_grab(y); }
#endif
#endif

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,75 +17,41 @@
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 <string>
#include "benchmark.h"
#include "bitcount.h"
#include "bitboard.h"
#include "misc.h"
#include "uci.h"
#ifdef USE_CALLGRIND
#include <valgrind/callgrind.h>
#endif
#include "position.h"
#include "search.h"
#include "thread.h"
using namespace std;
extern void uci_loop();
extern void benchmark(int argc, char* argv[]);
extern void kpk_bitbase_init();
////
//// Functions
////
int main(int argc, char* argv[]) {
int main(int argc, char *argv[]) {
bitboards_init();
Position::init();
kpk_bitbase_init();
Search::init();
Threads.init();
// Disable IO buffering
cout.rdbuf()->pubsetbuf(NULL, 0);
cin.rdbuf()->pubsetbuf(NULL, 0);
cout << engine_info() << endl;
// Initialization through global resources manager
Application::initialize();
if (argc == 1)
uci_loop();
#ifdef USE_CALLGRIND
CALLGRIND_START_INSTRUMENTATION;
#endif
else if (string(argv[1]) == "bench")
benchmark(argc, argv);
if (argc <= 1)
{
// Print copyright notice
cout << engine_name()
<< " by Tord Romstad, Marco Costalba, Joona Kiiski" << endl;
else
cerr << "\nUsage: stockfish bench [hash size = 128] [threads = 1] "
<< "[limit = 12] [fen positions file = default] "
<< "[limited by depth, time, nodes or perft = depth]" << endl;
if (CpuHasPOPCNT)
cout << "Good! CPU has hardware POPCNT." << endl;
// Enter UCI mode
uci_main_loop();
}
else // Process command line arguments
{
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);
}
}
Application::free_resources();
return 0;
Threads.exit();
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,65 +17,56 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// Includes
////
#include <cassert>
#include <sstream>
#include <map>
#include <cstring>
#include <algorithm>
#include "material.h"
using namespace std;
////
//// Local definitions
////
namespace {
// Values modified by Joona Kiiski
const Value MidgameLimit = Value(15581);
const Value EndgameLimit = Value(3998);
// Scale factors used when one side has no more pawns
const int NoPawnsSF[4] = { 6, 12, 32 };
// 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] = {
const int QuadraticCoefficientsSameColor[][8] = {
{ 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] = {
const int QuadraticCoefficientsOppositeColor[][8] = {
{ 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 } };
typedef EndgameEvaluationFunctionBase EF;
typedef EndgameScalingFunctionBase SF;
// Endgame evaluation and scaling functions accessed direcly and not through
// the function maps because correspond to more then one material hash key.
EvaluationFunction<KmmKm> EvaluateKmmKm[] = { EvaluationFunction<KmmKm>(WHITE), EvaluationFunction<KmmKm>(BLACK) };
EvaluationFunction<KXK> EvaluateKXK[] = { EvaluationFunction<KXK>(WHITE), EvaluationFunction<KXK>(BLACK) };
ScalingFunction<KBPsK> ScaleKBPsK[] = { ScalingFunction<KBPsK>(WHITE), ScalingFunction<KBPsK>(BLACK) };
ScalingFunction<KQKRPs> ScaleKQKRPs[] = { ScalingFunction<KQKRPs>(WHITE), ScalingFunction<KQKRPs>(BLACK) };
ScalingFunction<KPsK> ScaleKPsK[] = { ScalingFunction<KPsK>(WHITE), ScalingFunction<KPsK>(BLACK) };
ScalingFunction<KPKP> ScaleKPKP[] = { ScalingFunction<KPKP>(WHITE), ScalingFunction<KPKP>(BLACK) };
Endgame<KmmKm> EvaluateKmmKm[] = { Endgame<KmmKm>(WHITE), Endgame<KmmKm>(BLACK) };
Endgame<KXK> EvaluateKXK[] = { Endgame<KXK>(WHITE), Endgame<KXK>(BLACK) };
Endgame<KBPsK> ScaleKBPsK[] = { Endgame<KBPsK>(WHITE), Endgame<KBPsK>(BLACK) };
Endgame<KQKRPs> ScaleKQKRPs[] = { Endgame<KQKRPs>(WHITE), Endgame<KQKRPs>(BLACK) };
Endgame<KPsK> ScaleKPsK[] = { Endgame<KPsK>(WHITE), Endgame<KPsK>(BLACK) };
Endgame<KPKP> ScaleKPKP[] = { Endgame<KPKP>(WHITE), Endgame<KPKP>(BLACK) };
// Helper templates used to detect a given material distribution
template<Color Us> bool is_KXK(const Position& pos) {
const Color Them = (Us == WHITE ? BLACK : WHITE);
return pos.non_pawn_material(Them) == Value(0)
return pos.non_pawn_material(Them) == VALUE_ZERO
&& pos.piece_count(Them, PAWN) == 0
&& pos.non_pawn_material(Us) >= RookValueMidgame;
}
template<Color Us> bool is_KBPsK(const Position& pos) {
template<Color Us> bool is_KBPsKs(const Position& pos) {
return pos.non_pawn_material(Us) == BishopValueMidgame
&& pos.piece_count(Us, BISHOP) == 1
&& pos.piece_count(Us, PAWN) >= 1;
@@ -89,101 +80,26 @@ namespace {
&& pos.piece_count(Them, ROOK) == 1
&& pos.piece_count(Them, PAWN) >= 1;
}
}
} // namespace
////
//// Classes
////
/// MaterialInfoTable c'tor and d'tor allocate and free the space for Endgames
/// 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; }
void MaterialInfoTable::init() { Base::init(); if (!funcs) funcs = new Endgames(); }
MaterialInfoTable::~MaterialInfoTable() { delete funcs; }
////
//// 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,
/// MaterialInfoTable::material_info() takes a position object as input,
/// computes or looks up a MaterialInfo object, and returns a pointer to it.
/// If the material configuration is not already present in the table, it
/// is stored there, so we don't have to recompute everything when the
/// same material configuration occurs again.
MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
MaterialInfo* MaterialInfoTable::material_info(const Position& pos) const {
Key key = pos.get_material_key();
int index = key & (size - 1);
MaterialInfo* mi = entries + index;
Key key = pos.material_key();
MaterialInfo* mi = probe(key);
// If mi->key matches the position's material hash key, it means that we
// have analysed this material configuration before, and we can simply
@@ -191,9 +107,10 @@ MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
if (mi->key == key)
return mi;
// Clear the MaterialInfo object, and set its key
mi->clear();
// Initialize MaterialInfo entry
memset(mi, 0, sizeof(MaterialInfo));
mi->key = key;
mi->factor[WHITE] = mi->factor[BLACK] = (uint8_t)SCALE_FACTOR_NORMAL;
// Store game phase
mi->gamePhase = MaterialInfoTable::game_phase(pos);
@@ -201,17 +118,22 @@ MaterialInfo* MaterialInfoTable::get_material_info(const Position& 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)
if ((mi->evaluationFunction = funcs->get<Value>(key)) != NULL)
return mi;
else if (is_KXK<WHITE>(pos) || is_KXK<BLACK>(pos))
if (is_KXK<WHITE>(pos))
{
mi->evaluationFunction = is_KXK<WHITE>(pos) ? &EvaluateKXK[WHITE] : &EvaluateKXK[BLACK];
mi->evaluationFunction = &EvaluateKXK[WHITE];
return mi;
}
else if ( pos.pieces(PAWN) == EmptyBoardBB
&& pos.pieces(ROOK) == EmptyBoardBB
&& pos.pieces(QUEEN) == EmptyBoardBB)
if (is_KXK<BLACK>(pos))
{
mi->evaluationFunction = &EvaluateKXK[BLACK];
return mi;
}
if (!pos.pieces(PAWN) && !pos.pieces(ROOK) && !pos.pieces(QUEEN))
{
// Minor piece endgame with at least one minor piece per side and
// no pawns. Note that the case KmmK is already handled by KXK.
@@ -221,7 +143,7 @@ MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
if ( pos.piece_count(WHITE, BISHOP) + pos.piece_count(WHITE, KNIGHT) <= 2
&& pos.piece_count(BLACK, BISHOP) + pos.piece_count(BLACK, KNIGHT) <= 2)
{
mi->evaluationFunction = &EvaluateKmmKm[WHITE];
mi->evaluationFunction = &EvaluateKmmKm[pos.side_to_move()];
return mi;
}
}
@@ -231,9 +153,9 @@ MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
//
// We face problems when there are several conflicting applicable
// scaling functions and we need to decide which one to use.
SF* sf;
EndgameBase<ScaleFactor>* sf;
if ((sf = funcs->get<SF>(key)) != NULL)
if ((sf = funcs->get<ScaleFactor>(key)) != NULL)
{
mi->scalingFunction[sf->color()] = sf;
return mi;
@@ -242,10 +164,10 @@ MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
// Generic scaling functions that refer to more then one material
// distribution. Should be probed after the specialized ones.
// Note that these ones don't return after setting the function.
if (is_KBPsK<WHITE>(pos))
if (is_KBPsKs<WHITE>(pos))
mi->scalingFunction[WHITE] = &ScaleKBPsK[WHITE];
if (is_KBPsK<BLACK>(pos))
if (is_KBPsKs<BLACK>(pos))
mi->scalingFunction[BLACK] = &ScaleKBPsK[BLACK];
if (is_KQKRPs<WHITE>(pos))
@@ -254,7 +176,10 @@ MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
else if (is_KQKRPs<BLACK>(pos))
mi->scalingFunction[BLACK] = &ScaleKQKRPs[BLACK];
if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) == Value(0))
Value npm_w = pos.non_pawn_material(WHITE);
Value npm_b = pos.non_pawn_material(BLACK);
if (npm_w + npm_b == VALUE_ZERO)
{
if (pos.piece_count(BLACK, PAWN) == 0)
{
@@ -275,156 +200,87 @@ MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
}
}
// Compute the space weight
if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) >=
2*QueenValueMidgame + 4*RookValueMidgame + 2*KnightValueMidgame)
// No pawns makes it difficult to win, even with a material advantage
if (pos.piece_count(WHITE, PAWN) == 0 && npm_w - npm_b <= BishopValueMidgame)
{
int minorPieceCount = pos.piece_count(WHITE, KNIGHT)
+ pos.piece_count(BLACK, KNIGHT)
+ pos.piece_count(WHITE, BISHOP)
+ pos.piece_count(BLACK, BISHOP);
mi->factor[WHITE] = uint8_t
(npm_w == npm_b || npm_w < RookValueMidgame ? 0 : NoPawnsSF[std::min(pos.piece_count(WHITE, BISHOP), 2)]);
}
if (pos.piece_count(BLACK, PAWN) == 0 && npm_b - npm_w <= BishopValueMidgame)
{
mi->factor[BLACK] = uint8_t
(npm_w == npm_b || npm_b < RookValueMidgame ? 0 : NoPawnsSF[std::min(pos.piece_count(BLACK, BISHOP), 2)]);
}
// Compute the space weight
if (npm_w + npm_b >= 2 * QueenValueMidgame + 4 * RookValueMidgame + 2 * KnightValueMidgame)
{
int minorPieceCount = pos.piece_count(WHITE, KNIGHT) + pos.piece_count(WHITE, BISHOP)
+ pos.piece_count(BLACK, KNIGHT) + pos.piece_count(BLACK, BISHOP);
mi->spaceWeight = minorPieceCount * minorPieceCount;
}
// Evaluate the material 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;
// Evaluate the material imbalance. We use PIECE_TYPE_NONE as a place holder
// for the bishop pair "extended piece", this allow us to be more flexible
// in defining bishop pair bonuses.
const int pieceCount[2][8] = {
{ pos.piece_count(WHITE, BISHOP) > 1, pos.piece_count(WHITE, PAWN), pos.piece_count(WHITE, KNIGHT),
pos.piece_count(WHITE, BISHOP) , pos.piece_count(WHITE, ROOK), pos.piece_count(WHITE, QUEEN) },
{ pos.piece_count(BLACK, BISHOP) > 1, pos.piece_count(BLACK, PAWN), pos.piece_count(BLACK, KNIGHT),
pos.piece_count(BLACK, BISHOP) , pos.piece_count(BLACK, ROOK), pos.piece_count(BLACK, QUEEN) } };
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);
mi->value = int16_t((imbalance<WHITE>(pieceCount) - imbalance<BLACK>(pieceCount)) / 16);
return mi;
}
/// EndgameFunctions member definitions.
/// MaterialInfoTable::imbalance() calculates imbalance comparing piece count of each
/// piece type for both colors.
EndgameFunctions::EndgameFunctions() {
template<Color Us>
int MaterialInfoTable::imbalance(const int pieceCount[][8]) {
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");
const Color Them = (Us == WHITE ? BLACK : WHITE);
add<ScalingFunction<KNPK> >("KNPK");
add<ScalingFunction<KRPKR> >("KRPKR");
add<ScalingFunction<KBPKB> >("KBPKB");
add<ScalingFunction<KBPPKB> >("KBPPKB");
add<ScalingFunction<KBPKN> >("KBPKN");
add<ScalingFunction<KRPPKRP> >("KRPPKRP");
int pt1, pt2, pc, v;
int value = 0;
// Redundancy of major pieces, formula based on Kaufman's paper
// "The Evaluation of Material Imbalances in Chess"
if (pieceCount[Us][ROOK] > 0)
value -= RedundantRookPenalty * (pieceCount[Us][ROOK] - 1)
+ RedundantQueenPenalty * pieceCount[Us][QUEEN];
// Second-degree polynomial material imbalance by Tord Romstad
for (pt1 = NO_PIECE_TYPE; pt1 <= QUEEN; pt1++)
{
pc = pieceCount[Us][pt1];
if (!pc)
continue;
v = LinearCoefficients[pt1];
for (pt2 = NO_PIECE_TYPE; pt2 <= pt1; pt2++)
v += QuadraticCoefficientsSameColor[pt1][pt2] * pieceCount[Us][pt2]
+ QuadraticCoefficientsOppositeColor[pt1][pt2] * pieceCount[Them][pt2];
value += pc * v;
}
return value;
}
EndgameFunctions::~EndgameFunctions() {
for (map<Key, EF*>::iterator it = maps.first.begin(); it != maps.first.end(); ++it)
delete (*it).second;
/// 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.
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(), 0).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);
Phase MaterialInfoTable::game_phase(const Position& pos) {
Value npm = pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK);
return npm >= MidgameLimit ? PHASE_MIDGAME
: npm <= EndgameLimit ? PHASE_ENDGAME
: Phase(((npm - EndgameLimit) * 128) / (MidgameLimit - EndgameLimit));
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,22 +17,22 @@
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"
#include "tt.h"
#include "types.h"
const int MaterialTableSize = 8192;
/// Game phase
enum Phase {
PHASE_ENDGAME = 0,
PHASE_MIDGAME = 128
};
////
//// Types
////
/// MaterialInfo is a class which contains various information about a
/// material configuration. It contains a material balance evaluation,
@@ -49,8 +49,6 @@ 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;
@@ -59,66 +57,34 @@ public:
Value evaluate(const Position& pos) const;
private:
inline void clear();
Key key;
int16_t value;
uint8_t factor[2];
EndgameEvaluationFunctionBase* evaluationFunction;
EndgameScalingFunctionBase* scalingFunction[2];
EndgameBase<Value>* evaluationFunction;
EndgameBase<ScaleFactor>* 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 {
/// The MaterialInfoTable class represents a pawn hash table. The most important
/// method is material_info(), which returns a pointer to a MaterialInfo object.
class MaterialInfoTable : public SimpleHash<MaterialInfo, MaterialTableSize> {
public:
MaterialInfoTable(unsigned numOfEntries);
~MaterialInfoTable();
MaterialInfo* get_material_info(const Position& pos);
void init();
MaterialInfo* material_info(const Position& pos) const;
static Phase game_phase(const Position& pos);
private:
unsigned size;
MaterialInfo* entries;
EndgameFunctions* funcs;
template<Color Us>
static int imbalance(const int pieceCount[][8]);
Endgames* 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
@@ -128,50 +94,31 @@ inline void MaterialInfo::clear() {
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]);
if (!scalingFunction[c])
return ScaleFactor(factor[c]);
ScaleFactor sf = (*scalingFunction[c])(pos);
return sf == SCALE_FACTOR_NONE ? ScaleFactor(factor[c]) : sf;
}
inline Value MaterialInfo::evaluate(const Position& pos) const {
return (*evaluationFunction)(pos);
}
/// MaterialInfo::space_weight() simply returns the weight for the space
/// evaluation for this material configuration.
inline Score MaterialInfo::material_value() const {
return make_score(value, value);
}
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)

View File

@@ -1,171 +0,0 @@
/*
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 "mersenne.h"
namespace {
// Period parameters
const int N = 624;
const int M = 397;
const unsigned long MATRIX_A = 0x9908b0dfUL; // Constant vector a
const unsigned long UPPER_MASK = 0x80000000UL; // Most significant w-r bits
const unsigned long LOWER_MASK = 0x7fffffffUL; // Least significant r bits
unsigned long mt[N]; // The array for the state vector
int mti = N + 1; // mti == N+1 means mt[N] is not initialized
// Initializes mt[N] with a seed
void init_genrand(unsigned long s) {
mt[0]= s & 0xffffffffUL;
for (mti = 1; mti < N; 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] = 1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti;
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
void init_by_array(unsigned long init_key[], int key_length) {
int i = 1;
int j = 0;
int k = (N > key_length ? N : key_length);
init_genrand(19650218UL);
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
}
} // namespace
// Generates a random number on [0,0xffffffff]-interval
uint32_t genrand_int32() {
unsigned long y;
static unsigned long mag01[2] = {0x0UL, MATRIX_A};
/* mag01[x] = x * MATRIX_A for x=0,1 */
// Generate N words at one time
if (mti >= N)
{
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() {
uint64_t x, y;
x = genrand_int32();
y = genrand_int32();
return (x << 32) | y;
}
void init_mersenne() {
unsigned long init[4] = {0x123, 0x234, 0x345, 0x456};
unsigned long length = 4;
init_by_array(init, length);
}

View File

@@ -1,40 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(MERSENNE_H_INCLUDED)
#define MERSENNE_H_INCLUDED
////
//// Includes
////
#include "types.h"
////
//// Prototypes
////
extern uint32_t genrand_int32();
extern uint64_t genrand_int64();
extern void init_mersenne();
#endif // !defined(MERSENNE_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,12 +17,14 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if defined(_MSC_VER)
////
//// Includes
////
#define _CRT_SECURE_NO_DEPRECATE
#define NOMINMAX // disable macros min() and max()
#include <windows.h>
#include <sys/timeb.h>
#if !defined(_MSC_VER)
#else
# include <sys/time.h>
# include <sys/types.h>
@@ -31,18 +33,13 @@
# include <sys/pstat.h>
# endif
#else
#define _CRT_SECURE_NO_DEPRECATE
#include <windows.h>
#include <sys/timeb.h>
#endif
#if !defined(NO_PREFETCH)
# include <xmmintrin.h>
#endif
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <iomanip>
@@ -55,263 +52,153 @@
using namespace std;
/// Version number. If this is left empty, the current date (in the format
/// YYMMDD) is used as a version number.
/// Version number. If Version is left empty, then Tag plus current
/// date (in the format YYMMDD) is used as a version number.
static const string EngineVersion = "1.8";
static const string AppName = "Stockfish";
static const string AppTag = "";
static const string Version = "2.2.1";
static const string Tag = "";
////
//// Variables
////
/// engine_info() returns the full name of the current Stockfish version.
/// This will be either "Stockfish YYMMDD" (where YYMMDD is the date when
/// the program was compiled) or "Stockfish <version number>", depending
/// on whether Version is empty.
bool Chess960;
const string engine_info(bool to_uci) {
uint64_t dbg_cnt0 = 0;
uint64_t dbg_cnt1 = 0;
const string months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
const string cpu64(Is64Bit ? " 64bit" : "");
const string popcnt(HasPopCnt ? " SSE4.2" : "");
bool dbg_show_mean = false;
bool dbg_show_hit_rate = false;
string month, day, year;
stringstream s, date(__DATE__); // From compiler, format is "Sep 21 2008"
if (Version.empty())
{
date >> month >> day >> year;
////
//// Functions
////
s << "Stockfish " << Tag
<< setfill('0') << " " << year.substr(2)
<< setw(2) << (1 + months.find(month) / 4)
<< setw(2) << day << cpu64 << popcnt;
}
else
s << "Stockfish " << Version << cpu64 << popcnt;
void dbg_hit_on(bool b) {
assert(!dbg_show_mean);
dbg_show_hit_rate = true;
dbg_cnt0++;
if (b)
dbg_cnt1++;
}
void dbg_hit_on_c(bool c, bool b) {
if (c)
dbg_hit_on(b);
}
void dbg_before() {
assert(!dbg_show_mean);
dbg_show_hit_rate = true;
dbg_cnt0++;
}
void dbg_after() {
assert(!dbg_show_mean);
dbg_show_hit_rate = true;
dbg_cnt1++;
}
void dbg_mean_of(int v) {
assert(!dbg_show_hit_rate);
dbg_show_mean = true;
dbg_cnt0++;
dbg_cnt1 += v;
}
void dbg_print_hit_rate() {
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;
s << (to_uci ? "\nid author ": " by ")
<< "Tord Romstad, Marco Costalba and Joona Kiiski";
return s.str();
}
/// get_system_time() returns the current system time, measured in
/// milliseconds.
/// Debug functions used mainly to collect run-time statistics
int get_system_time() {
static uint64_t hits[2], means[2];
void dbg_hit_on(bool b) { hits[0]++; if (b) hits[1]++; }
void dbg_hit_on_c(bool c, bool b) { if (c) dbg_hit_on(b); }
void dbg_mean_of(int v) { means[0]++; means[1] += v; }
void dbg_print() {
if (hits[0])
cerr << "Total " << hits[0] << " Hits " << hits[1]
<< " hit rate (%) " << 100 * hits[1] / hits[0] << endl;
if (means[0])
cerr << "Total " << means[0] << " Mean "
<< (float)means[1] / means[0] << endl;
}
/// system_time() returns the current system time, measured in milliseconds
int system_time() {
#if defined(_MSC_VER)
struct _timeb t;
_ftime(&t);
return int(t.time*1000 + t.millitm);
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;
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.
/// cpu_count() tries to detect the number of CPU cores
#if !defined(_MSC_VER)
int cpu_count() {
#if defined(_MSC_VER)
SYSTEM_INFO s;
GetSystemInfo(&s);
return std::min(int(s.dwNumberOfProcessors), MAX_THREADS);
#else
# if defined(_SC_NPROCESSORS_ONLN)
int cpu_count() {
return Min(sysconf(_SC_NPROCESSORS_ONLN), MAX_THREADS);
}
return std::min((int)sysconf(_SC_NPROCESSORS_ONLN), MAX_THREADS);
# elif defined(__hpux)
int cpu_count() {
struct pst_dynamic psd;
if (pstat_getdynamic(&psd, sizeof(psd), (size_t)1, 0) == -1)
return 1;
return Min(psd.psd_proc_cnt, MAX_THREADS);
}
return std::min((int)psd.psd_proc_cnt, MAX_THREADS);
# else
int cpu_count() {
return 1;
}
# endif
#endif
}
/// timed_wait() waits for msec milliseconds. It is mainly an helper to wrap
/// conversion from milliseconds to struct timespec, as used by pthreads.
void timed_wait(WaitCondition* sleepCond, Lock* sleepLock, int msec) {
#if defined(_MSC_VER)
int tm = msec;
#else
struct timeval t;
struct timespec abstime, *tm = &abstime;
int cpu_count() {
SYSTEM_INFO s;
GetSystemInfo(&s);
return Min(s.dwNumberOfProcessors, MAX_THREADS);
}
gettimeofday(&t, NULL);
abstime.tv_sec = t.tv_sec + (msec / 1000);
abstime.tv_nsec = (t.tv_usec + (msec % 1000) * 1000) * 1000;
if (abstime.tv_nsec > 1000000000LL)
{
abstime.tv_sec += 1;
abstime.tv_nsec -= 1000000000LL;
}
#endif
/*
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));
cond_timedwait(sleepCond, sleepLock, tm);
}
#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;
// 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;
return 0;
}
}
#endif
/// prefetch() preloads the given address in L1/L2 cache. This is a non
/// blocking function and do not stalls the CPU waiting for data to be
/// loaded from RAM, that can be very slow.
/// loaded from memory, that can be quite slow.
#if defined(NO_PREFETCH)
void prefetch(char*) {}
#else
void prefetch(char* addr) {
#if defined(__INTEL_COMPILER) || defined(__ICL)
# if defined(__INTEL_COMPILER) || defined(__ICL)
// This hack prevents prefetches to be optimized away by
// Intel compiler. Both MSVC and gcc seems not affected.
__asm__ ("");
#endif
# endif
_mm_prefetch(addr, _MM_HINT_T2);
_mm_prefetch(addr+64, _MM_HINT_T2); // 64 bytes ahead
}
#endif

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,65 +17,34 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(MISC_H_INCLUDED)
#define MISC_H_INCLUDED
////
//// Includes
////
#include <fstream>
#include <string>
#include "application.h"
#include "lock.h"
#include "types.h"
////
//// Macros
////
#define Min(x, y) (((x) < (y))? (x) : (y))
#define Max(x, y) (((x) < (y))? (y) : (x))
////
//// Variables
////
extern bool Chess960;
////
//// Prototypes
////
extern const std::string engine_name();
extern int get_system_time();
extern const std::string engine_info(bool to_uci = false);
extern int system_time();
extern int cpu_count();
extern int Bioskey();
extern void timed_wait(WaitCondition*, Lock*, int);
extern void prefetch(char* addr);
////
//// Debug
////
extern bool dbg_show_mean;
extern bool dbg_show_hit_rate;
extern uint64_t dbg_cnt0;
extern uint64_t dbg_cnt1;
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);
extern void dbg_print();
class Position;
extern Move move_from_uci(const Position& pos, const std::string& str);
extern const std::string move_to_uci(Move m, bool chess960);
extern const std::string move_to_san(Position& pos, Move m);
struct Log : public std::ofstream {
Log(const std::string& f = "log.txt") : std::ofstream(f.c_str(), std::ios::out | std::ios::app) {}
~Log() { if (is_open()) close(); }
};
#endif // !defined(MISC_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,136 +17,143 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// Includes
////
#include <cassert>
#include <cstring>
#include <string>
#include "move.h"
#include "piece.h"
#include "movegen.h"
#include "position.h"
using std::string;
////
//// Functions
////
/// move_to_uci() converts a move to a string in coordinate notation
/// (g1f3, a7a8q, etc.). The only special case is castling moves, where we
/// print in the e1g1 notation in normal chess mode, and in e1h1 notation in
/// Chess960 mode. Instead internally Move is coded as "king captures rook".
/// 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.
const string move_to_uci(Move m, bool chess960) {
Move move_from_string(const Position& pos, const std::string& str) {
Square from = from_sq(m);
Square to = to_sq(m);
string promotion;
Square from, to;
Piece piece;
Color us = pos.side_to_move();
if (m == MOVE_NONE)
return "(none)";
if (str.length() < 4)
return MOVE_NONE;
if (m == MOVE_NULL)
return "0000";
// Read the from and to squares
from = square_from_string(str.substr(0, 2));
to = square_from_string(str.substr(2, 4));
if (is_castle(m) && !chess960)
to = from + (file_of(to) == FILE_H ? Square(2) : -Square(2));
// Find the moving piece
piece = pos.piece_on(from);
if (is_promotion(m))
promotion = char(tolower(piece_type_to_char(promotion_piece_type(m))));
// 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);
return square_to_string(from) + square_to_string(to) + promotion;
}
/// 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.
/// move_from_uci() takes a position and a string representing a move in
/// simple coordinate notation and returns an equivalent Move if any.
/// Moves are guaranteed to be legal.
const std::string move_to_string(Move move) {
Move move_from_uci(const Position& pos, const string& str) {
std::string str;
Square from = move_from(move);
Square to = move_to(move);
for (MoveList<MV_LEGAL> ml(pos); !ml.end(); ++ml)
if (str == move_to_uci(ml.move(), pos.is_chess960()))
return ml.move();
if (move == MOVE_NONE)
str = "(none)";
else if (move == MOVE_NULL)
str = "0000";
return MOVE_NONE;
}
/// move_to_san() takes a position and a move as input, where it is assumed
/// that the move is a legal move for the position. The return value is
/// a string containing the move in short algebraic notation.
const string move_to_san(Position& pos, Move m) {
if (m == MOVE_NONE)
return "(none)";
if (m == MOVE_NULL)
return "(null)";
assert(is_ok(m));
Bitboard attackers;
bool ambiguousMove, ambiguousFile, ambiguousRank;
Square sq, from = from_sq(m);
Square to = to_sq(m);
PieceType pt = type_of(pos.piece_on(from));
string san;
if (is_castle(m))
san = (to_sq(m) < from_sq(m) ? "O-O-O" : "O-O");
else
{
if (!Chess960)
if (pt != PAWN)
{
if (move_is_short_castle(move))
return (from == SQ_E1 ? "e1g1" : "e8g8");
san = piece_type_to_char(pt);
if (move_is_long_castle(move))
return (from == SQ_E1 ? "e1c1" : "e8c8");
// Disambiguation if we have more then one piece with destination 'to'
// note that for pawns is not needed because starting file is explicit.
attackers = pos.attackers_to(to) & pos.pieces(pt, pos.side_to_move());
clear_bit(&attackers, from);
ambiguousMove = ambiguousFile = ambiguousRank = false;
while (attackers)
{
sq = pop_1st_bit(&attackers);
// Pinned pieces are not included in the possible sub-set
if (!pos.pl_move_is_legal(make_move(sq, to), pos.pinned_pieces()))
continue;
if (file_of(sq) == file_of(from))
ambiguousFile = true;
if (rank_of(sq) == rank_of(from))
ambiguousRank = true;
ambiguousMove = true;
}
if (ambiguousMove)
{
if (!ambiguousFile)
san += file_to_char(file_of(from));
else if (!ambiguousRank)
san += rank_to_char(rank_of(from));
else
san += square_to_string(from);
}
}
if (pos.is_capture(m))
{
if (pt == PAWN)
san += file_to_char(file_of(from));
san += 'x';
}
san += square_to_string(to);
if (is_promotion(m))
{
san += '=';
san += piece_type_to_char(promotion_piece_type(m));
}
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));
// The move gives check? We don't use pos.move_gives_check() here
// because we need to test for a mate after the move is done.
StateInfo st;
pos.do_move(m, st);
if (pos.in_check())
san += pos.is_mate() ? "#" : "+";
pos.undo_move(m);
return san;
}

View File

@@ -1,210 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(MOVE_H_INCLUDED)
#define MOVE_H_INCLUDED
////
//// 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), first splits
// positive scores from ramining then order seaprately the two sets.
template<typename T>
inline void sort_moves(T* firstMove, T* lastMove, T** lastPositive)
{
T tmp;
T *p, *d;
d = lastMove;
p = firstMove - 1;
d->score = -1; // right guard
// Split positives vs non-positives
do {
while ((++p)->score > 0) {}
if (p != d)
{
while (--d != p && d->score <= 0) {}
tmp = *p;
*p = *d;
*d = tmp;
}
} while (p != d);
// Sort just positive scored moves, remaining only when we get there
insertion_sort<T>(firstMove, p);
*lastPositive = p;
}
// Picks up the best move in range [curMove, lastMove), one per cycle.
// It is faster then sorting all the moves in advance when moves are few,
// as normally are the possible captures. Note that is not a stable alghoritm.
template<typename T>
inline T pick_best(T* curMove, T* lastMove)
{
T bestMove, tmp;
bestMove = *curMove;
while (++curMove != lastMove)
{
if (*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)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,15 +17,12 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// Includes
////
#include <cassert>
#include <algorithm>
#include "bitcount.h"
#include "movegen.h"
#include "position.h"
// Simple macro to wrap a very common while loop, no facny, no flexibility,
// hardcoded list name 'mlist' and from square 'from'.
@@ -34,10 +31,6 @@
// 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 {
enum CastlingSide {
@@ -45,123 +38,178 @@ namespace {
QUEEN_SIDE
};
enum MoveType {
CAPTURE,
NON_CAPTURE,
CHECK,
EVASION
};
template<CastlingSide>
MoveStack* generate_castle_moves(const Position&, MoveStack*, Color us);
// Helper templates
template<CastlingSide Side>
MoveStack* generate_castle_moves(const Position&, MoveStack*);
template<Color Us, MoveType Type>
template<Color, MoveType>
MoveStack* generate_pawn_moves(const Position&, MoveStack*, Bitboard, Square);
// Template generate_piece_moves (captures and non-captures) with specializations and overloads
template<PieceType>
MoveStack* generate_piece_moves(const Position&, MoveStack*, Color, Bitboard);
template<PieceType Pt>
inline MoveStack* generate_discovered_checks(const Position& pos, MoveStack* mlist, Square from) {
assert(Pt != QUEEN && Pt != PAWN);
Bitboard b = pos.attacks_from<Pt>(from) & pos.empty_squares();
if (Pt == KING)
b &= ~QueenPseudoAttacks[pos.king_square(flip(pos.side_to_move()))];
SERIALIZE_MOVES(b);
return mlist;
}
template<PieceType Pt>
inline MoveStack* generate_direct_checks(const Position& pos, MoveStack* mlist, Color us,
Bitboard dc, Square ksq) {
assert(Pt != KING && Pt != PAWN);
Bitboard checkSqs, b;
Square from;
const Square* pl = pos.piece_list(us, Pt);
if ((from = *pl++) == SQ_NONE)
return mlist;
checkSqs = pos.attacks_from<Pt>(ksq) & pos.empty_squares();
do
{
if ( (Pt == QUEEN && !(QueenPseudoAttacks[from] & checkSqs))
|| (Pt == ROOK && !(RookPseudoAttacks[from] & checkSqs))
|| (Pt == BISHOP && !(BishopPseudoAttacks[from] & checkSqs)))
continue;
if (dc && bit_is_set(dc, from))
continue;
b = pos.attacks_from<Pt>(from) & checkSqs;
SERIALIZE_MOVES(b);
} while ((from = *pl++) != SQ_NONE);
return mlist;
}
template<>
MoveStack* generate_piece_moves<KING>(const Position&, MoveStack*, Color, Bitboard);
FORCE_INLINE MoveStack* generate_direct_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
template<PieceType Piece, MoveType Type>
inline MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us, Bitboard t) {
return (us == WHITE ? generate_pawn_moves<WHITE, MV_CHECK>(p, m, dc, ksq)
: generate_pawn_moves<BLACK, MV_CHECK>(p, m, dc, ksq));
}
assert(Piece == PAWN);
assert(Type == CAPTURE || Type == NON_CAPTURE || Type == EVASION);
template<PieceType Pt, MoveType Type>
FORCE_INLINE MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us, Bitboard t) {
assert(Pt == PAWN);
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 Pt>
FORCE_INLINE MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
template<PieceType Piece>
MoveStack* generate_discovered_checks(const Position&, MoveStack*, Square);
Bitboard b;
Square from;
const Square* pl = pos.piece_list(us, Pt);
template<PieceType>
MoveStack* generate_direct_checks(const Position&, MoveStack*, Color, Bitboard, Square);
if (*pl != SQ_NONE)
{
do {
from = *pl;
b = pos.attacks_from<Pt>(from) & target;
SERIALIZE_MOVES(b);
} while (*++pl != SQ_NONE);
}
return mlist;
}
template<>
inline MoveStack* generate_direct_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
FORCE_INLINE MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
return (us == WHITE ? generate_pawn_moves<WHITE, CHECK>(p, m, dc, ksq)
: generate_pawn_moves<BLACK, CHECK>(p, m, dc, ksq));
Bitboard b;
Square from = pos.king_square(us);
b = pos.attacks_from<KING>(from) & target;
SERIALIZE_MOVES(b);
return mlist;
}
}
////
//// Functions
////
/// generate_captures() generates all pseudo-legal captures and queen
/// generate<MV_CAPTURE> generates all pseudo-legal captures and queen
/// promotions. Returns a pointer to the end of the move list.
MoveStack* generate_captures(const Position& pos, MoveStack* mlist) {
assert(pos.is_ok());
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
///
/// generate<MV_NON_CAPTURE> generates all pseudo-legal non-captures and
/// underpromotions. Returns a pointer to the end of the move list.
///
/// generate<MV_NON_EVASION> generates all pseudo-legal captures and
/// non-captures. Returns a pointer to the end of the move list.
MoveStack* generate_noncaptures(const Position& pos, MoveStack* mlist) {
template<MoveType Type>
MoveStack* generate(const Position& pos, MoveStack* mlist) {
assert(pos.is_ok());
assert(!pos.is_check());
assert(Type == MV_CAPTURE || Type == MV_NON_CAPTURE || Type == MV_NON_EVASION);
assert(!pos.in_check());
Color us = pos.side_to_move();
Bitboard target = pos.empty_squares();
Bitboard target;
mlist = generate_piece_moves<PAWN, NON_CAPTURE>(pos, mlist, us, target);
if (Type == MV_CAPTURE)
target = pos.pieces(flip(us));
else if (Type == MV_NON_CAPTURE)
target = pos.empty_squares();
else if (Type == MV_NON_EVASION)
target = pos.pieces(flip(us)) | pos.empty_squares();
mlist = generate_piece_moves<PAWN, Type>(pos, mlist, us, target);
mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
mlist = generate_piece_moves<KING>(pos, mlist, us, target);
mlist = generate_castle_moves<KING_SIDE>(pos, mlist);
return generate_castle_moves<QUEEN_SIDE>(pos, mlist);
if (Type != MV_CAPTURE && pos.can_castle(us))
{
if (pos.can_castle(us == WHITE ? WHITE_OO : BLACK_OO))
mlist = generate_castle_moves<KING_SIDE>(pos, mlist, us);
if (pos.can_castle(us == WHITE ? WHITE_OOO : BLACK_OOO))
mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist, us);
}
return mlist;
}
// Explicit template instantiations
template MoveStack* generate<MV_CAPTURE>(const Position& pos, MoveStack* mlist);
template MoveStack* generate<MV_NON_CAPTURE>(const Position& pos, MoveStack* mlist);
template MoveStack* generate<MV_NON_EVASION>(const Position& pos, MoveStack* mlist);
/// generate_non_capture_checks() generates all pseudo-legal non-captures and knight
/// generate<MV_NON_CAPTURE_CHECK> generates all pseudo-legal non-captures and knight
/// underpromotions that give check. Returns a pointer to the end of the move list.
template<>
MoveStack* generate<MV_NON_CAPTURE_CHECK>(const Position& pos, MoveStack* mlist) {
MoveStack* generate_non_capture_checks(const Position& pos, MoveStack* mlist) {
assert(pos.is_ok());
assert(!pos.is_check());
assert(!pos.in_check());
Bitboard b, dc;
Square from;
Color us = pos.side_to_move();
Square ksq = pos.king_square(opposite_color(us));
Square ksq = pos.king_square(flip(us));
assert(pos.piece_on(ksq) == piece_of_color_and_type(opposite_color(us), KING));
assert(pos.piece_on(ksq) == make_piece(flip(us), KING));
// Discovered non-capture checks
b = dc = pos.discovered_check_candidates(us);
b = dc = pos.discovered_check_candidates();
while (b)
{
from = pop_1st_bit(&b);
switch (pos.type_of_piece_on(from))
switch (type_of(pos.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;
@@ -181,13 +229,12 @@ MoveStack* generate_non_capture_checks(const Position& pos, MoveStack* mlist) {
}
/// generate_evasions() generates all pseudo-legal check evasions when
/// the side to move is in check. Returns a pointer to the end of the move list.
/// generate<MV_EVASION> generates all pseudo-legal check evasions when the side
/// to move is in check. Returns a pointer to the end of the move list.
template<>
MoveStack* generate<MV_EVASION>(const Position& pos, MoveStack* mlist) {
MoveStack* generate_evasions(const Position& pos, MoveStack* mlist) {
assert(pos.is_ok());
assert(pos.is_check());
assert(pos.in_check());
Bitboard b, target;
Square from, checksq;
@@ -195,9 +242,9 @@ MoveStack* generate_evasions(const Position& pos, MoveStack* mlist) {
Color us = pos.side_to_move();
Square ksq = pos.king_square(us);
Bitboard checkers = pos.checkers();
Bitboard sliderAttacks = EmptyBoardBB;
Bitboard sliderAttacks = 0;
assert(pos.piece_on(ksq) == piece_of_color_and_type(us, KING));
assert(pos.piece_on(ksq) == make_piece(us, KING));
assert(checkers);
// Find squares attacked by slider checkers, we will remove
@@ -209,26 +256,31 @@ MoveStack* generate_evasions(const Position& pos, MoveStack* mlist) {
checkersCnt++;
checksq = pop_1st_bit(&b);
assert(pos.color_of_piece_on(checksq) == opposite_color(us));
assert(color_of(pos.piece_on(checksq)) == flip(us));
switch (pos.type_of_piece_on(checksq))
switch (type_of(pos.piece_on(checksq)))
{
case BISHOP: sliderAttacks |= BishopPseudoAttacks[checksq]; break;
case ROOK: sliderAttacks |= RookPseudoAttacks[checksq]; break;
case 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);
// If queen and king are far we can safely remove all the squares attacked
// in the other direction becuase are not reachable by the king anyway.
if (squares_between(ksq, checksq) || (RookPseudoAttacks[checksq] & (1ULL << ksq)))
sliderAttacks |= QueenPseudoAttacks[checksq];
// Otherwise, if king and queen are adjacent and on a diagonal line, we need to
// use real rook attacks to check if king is safe to move in the other direction.
// For example: king in B2, queen in A1 a knight in B1, and we can safely move to C1.
else
sliderAttacks |= BishopPseudoAttacks[checksq] | pos.attacks_from<ROOK>(checksq);
default:
break;
}
} while (b);
// Generate evasions for king, capture and non capture moves
b = pos.attacks_from<KING>(ksq) & ~pos.pieces_of_color(us) & ~sliderAttacks;
b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
from = ksq;
SERIALIZE_MOVES(b);
@@ -240,7 +292,7 @@ MoveStack* generate_evasions(const Position& pos, MoveStack* mlist) {
// checker piece is possible.
target = squares_between(checksq, ksq) | checkers;
mlist = generate_piece_moves<PAWN, EVASION>(pos, mlist, us, target);
mlist = generate_piece_moves<PAWN, MV_EVASION>(pos, mlist, us, target);
mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
@@ -248,450 +300,238 @@ MoveStack* generate_evasions(const Position& pos, MoveStack* mlist) {
}
/// 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.
/// generate<MV_LEGAL> computes a complete list of legal moves in the current position
MoveStack* generate_moves(const Position& pos, MoveStack* mlist, bool pseudoLegal) {
assert(pos.is_ok());
template<>
MoveStack* generate<MV_LEGAL>(const Position& pos, MoveStack* mlist) {
MoveStack *last, *cur = mlist;
Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
Bitboard pinned = pos.pinned_pieces();
// 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;
last = pos.in_check() ? generate<MV_EVASION>(pos, mlist)
: generate<MV_NON_EVASION>(pos, mlist);
// Remove illegal moves from the list
while (cur != last)
if (pos.pl_move_is_legal(cur->move, pinned))
cur++;
else
if (!pos.pl_move_is_legal(cur->move, pinned))
cur->move = (--last)->move;
else
cur++;
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;
// The promotion piece, if any, must be valid
if (move_promotion_piece(m) > QUEEN || move_promotion_piece(m) == PAWN)
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)
{
b = pos.attacks_from<Piece>(from) & target;
SERIALIZE_MOVES(b);
}
return mlist;
}
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>
template<Square Delta>
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;
return Delta == DELTA_N ? p << 8 : Delta == DELTA_S ? p >> 8 :
Delta == DELTA_NE ? p << 9 : Delta == DELTA_SE ? p >> 7 :
Delta == DELTA_NW ? p << 7 : Delta == DELTA_SW ? p >> 9 : p;
}
template<Color Us, MoveType Type, SquareDelta Diagonal>
inline MoveStack* generate_pawn_captures(MoveStack* mlist, Bitboard pawns, Bitboard enemyPieces) {
template<Square Delta>
inline MoveStack* generate_pawn_captures(MoveStack* mlist, Bitboard pawns, Bitboard target) {
// 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);
const Bitboard TFileABB = (Delta == DELTA_NE || Delta == DELTA_SE ? FileABB : FileHBB);
Bitboard b1, b2;
Bitboard b;
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;
b = move_pawns<Delta>(pawns) & target & ~TFileABB;
SERIALIZE_MOVES_D(b, -Delta);
return mlist;
}
// Capturing promotions and under-promotions
if (b1 & TRank8BB)
template<MoveType Type, Square Delta>
inline MoveStack* generate_promotions(const Position& pos, MoveStack* mlist, Bitboard pawnsOn7, Bitboard target) {
const Bitboard TFileABB = (Delta == DELTA_NE || Delta == DELTA_SE ? FileABB : FileHBB);
Bitboard b;
Square to;
// Promotions and under-promotions, both captures and non-captures
b = move_pawns<Delta>(pawnsOn7) & target;
if (Delta != DELTA_N && Delta != DELTA_S)
b &= ~TFileABB;
while (b)
{
b2 = b1 & TRank8BB;
b1 &= ~TRank8BB;
while (b2)
to = pop_1st_bit(&b);
if (Type == MV_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
(*mlist++).move = make_promotion(to - Delta, to, QUEEN);
if (Type == MV_NON_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
{
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);
(*mlist++).move = make_promotion(to - Delta, to, ROOK);
(*mlist++).move = make_promotion(to - Delta, to, BISHOP);
(*mlist++).move = make_promotion(to - Delta, to, KNIGHT);
}
// This is the only possible under promotion that can give a check
// not already included in the queen-promotion.
if ( Type == MV_CHECK
&& bit_is_set(pos.attacks_from<KNIGHT>(to), pos.king_square(Delta > 0 ? BLACK : WHITE)))
(*mlist++).move = make_promotion(to - Delta, to, KNIGHT);
else (void)pos; // Silence a warning under MSVC
}
// 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);
// Calculate our parametrized parameters at compile time, named
// according to the point of view of white side.
const Color Them = (Us == WHITE ? BLACK : WHITE);
const Bitboard TRank7BB = (Us == WHITE ? Rank7BB : Rank2BB);
const Bitboard TRank3BB = (Us == WHITE ? Rank3BB : Rank6BB);
const Square UP = (Us == WHITE ? DELTA_N : DELTA_S);
const Square RIGHT_UP = (Us == WHITE ? DELTA_NE : DELTA_SW);
const Square LEFT_UP = (Us == WHITE ? DELTA_NW : DELTA_SE);
Square to;
Bitboard b1, b2, enemyPieces, emptySquares;
Bitboard b1, b2, dc1, dc2, pawnPushes, emptySquares;
Bitboard pawns = pos.pieces(PAWN, Us);
Bitboard pawnsOn7 = pawns & TRank7BB;
Bitboard enemyPieces = (Type == MV_CAPTURE ? target : pos.pieces(Them));
// Standard captures and capturing promotions and underpromotions
if (Type == CAPTURE || Type == EVASION || (pawns & TRank7BB))
// Pre-calculate pawn pushes before changing emptySquares definition
if (Type != MV_CAPTURE)
{
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);
emptySquares = (Type == MV_NON_CAPTURE ? target : pos.empty_squares());
pawnPushes = move_pawns<UP>(pawns & ~TRank7BB) & emptySquares;
}
// Non-capturing promotions and underpromotions
if (pawns & TRank7BB)
if (Type == MV_EVASION)
{
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);
}
emptySquares &= target; // Only blocking squares
enemyPieces &= target; // Capture only the checker piece
}
// Standard pawn pushes and double pushes
if (Type != CAPTURE)
// Promotions and underpromotions
if (pawnsOn7)
{
emptySquares = (Type == NON_CAPTURE ? target : pos.empty_squares());
if (Type == MV_CAPTURE)
emptySquares = 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;
pawns &= ~TRank7BB;
mlist = generate_promotions<Type, RIGHT_UP>(pos, mlist, pawnsOn7, enemyPieces);
mlist = generate_promotions<Type, LEFT_UP>(pos, mlist, pawnsOn7, enemyPieces);
mlist = generate_promotions<Type, UP>(pos, mlist, pawnsOn7, emptySquares);
}
// Filter out unwanted pushes according to the move type
if (Type == EVASION)
// Standard captures
if (Type == MV_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
{
mlist = generate_pawn_captures<RIGHT_UP>(mlist, pawns, enemyPieces);
mlist = generate_pawn_captures<LEFT_UP>(mlist, pawns, enemyPieces);
}
// Single and double pawn pushes
if (Type != MV_CAPTURE)
{
b1 = (Type != MV_EVASION ? pawnPushes : pawnPushes & emptySquares);
b2 = move_pawns<UP>(pawnPushes & TRank3BB) & emptySquares;
if (Type == MV_CHECK)
{
b1 &= target;
b2 &= target;
}
else if (Type == CHECK)
{
// Pawn moves which give direct cheks
// Consider only pawn moves which give direct checks
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.
// Add pawn moves which gives discovered check. This is possible only
// if the pawn is not on the same file as the enemy king, because we
// don't generate captures.
if (pawns & target) // For CHECK type target is dc bitboard
{
Bitboard dc1 = move_pawns<Us, DELTA_N>(pawns & target & ~file_bb(ksq)) & emptySquares & ~TRank8BB;
Bitboard dc2 = move_pawns<Us, DELTA_N>(dc1 & TRank3BB) & emptySquares;
dc1 = move_pawns<UP>(pawns & target & ~file_bb(ksq)) & emptySquares;
dc2 = move_pawns<UP>(dc1 & TRank3BB) & emptySquares;
b1 |= dc1;
b2 |= dc2;
}
}
SERIALIZE_MOVES_D(b1, -TDELTA_N);
SERIALIZE_MOVES_D(b2, -TDELTA_N -TDELTA_N);
SERIALIZE_MOVES_D(b1, -UP);
SERIALIZE_MOVES_D(b2, -UP -UP);
}
// En passant captures
if ((Type == CAPTURE || Type == EVASION) && pos.ep_square() != SQ_NONE)
if ( (Type == MV_CAPTURE || Type == MV_EVASION || Type == MV_NON_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);
assert(Us != WHITE || rank_of(pos.ep_square()) == RANK_6);
assert(Us != BLACK || rank_of(pos.ep_square()) == RANK_3);
// An en passant capture can be an evasion only if the checking piece
// is the double pushed pawn and so is in the target. Otherwise this
// is a discovery check and we are forced to do otherwise.
if (Type == EVASION && !bit_is_set(target, pos.ep_square() - TDELTA_N))
if (Type == MV_EVASION && !bit_is_set(target, pos.ep_square() - UP))
return mlist;
b1 = pawns & pos.attacks_from<PAWN>(pos.ep_square(), Them);
assert(b1 != EmptyBoardBB);
assert(b1);
while (b1)
{
to = pop_1st_bit(&b1);
(*mlist++).move = make_ep_move(to, pos.ep_square());
(*mlist++).move = make_enpassant(to, pos.ep_square());
}
}
return mlist;
}
template<PieceType Piece>
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)
{
Square ksq = pos.king_square(opposite_color(pos.side_to_move()));
b &= ~QueenPseudoAttacks[ksq];
}
SERIALIZE_MOVES(b);
return mlist;
}
template<PieceType Piece>
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
{
if ( (Piece == QUEEN && !(QueenPseudoAttacks[from] & checkSqs))
|| (Piece == ROOK && !(RookPseudoAttacks[from] & checkSqs))
|| (Piece == BISHOP && !(BishopPseudoAttacks[from] & checkSqs)))
continue;
if (dc && bit_is_set(dc, from))
continue;
b = pos.attacks_from<Piece>(from) & checkSqs;
SERIALIZE_MOVES(b);
} while ((from = *ptr++) != SQ_NONE);
return mlist;
}
template<CastlingSide Side>
MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist) {
MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist, Color us) {
Color us = pos.side_to_move();
CastleRight f = CastleRight((Side == KING_SIDE ? WHITE_OO : WHITE_OOO) << us);
Color them = flip(us);
if ( (Side == KING_SIDE && pos.can_castle_kingside(us))
||(Side == QUEEN_SIDE && pos.can_castle_queenside(us)))
// After castling, the rook and king's final positions are exactly the same
// in Chess960 as they would be in standard chess.
Square kfrom = pos.king_square(us);
Square rfrom = pos.castle_rook_square(f);
Square kto = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
Square rto = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
assert(!pos.in_check());
assert(pos.piece_on(kfrom) == make_piece(us, KING));
assert(pos.piece_on(rfrom) == make_piece(us, ROOK));
// Unimpeded rule: All the squares between the king's initial and final squares
// (including the final square), and all the squares between the rook's initial
// and final squares (including the final square), must be vacant except for
// the king and castling rook.
for (Square s = std::min(kfrom, kto); s <= std::max(kfrom, kto); s++)
if ( (s != kfrom && s != rfrom && !pos.square_is_empty(s))
||(pos.attackers_to(s) & pos.pieces(them)))
return mlist;
for (Square s = std::min(rfrom, rto); s <= std::max(rfrom, rto); s++)
if (s != kfrom && s != rfrom && !pos.square_is_empty(s))
return mlist;
// Because we generate only legal castling moves we need to verify that
// when moving the castling rook we do not discover some hidden checker.
// For instance an enemy queen in SQ_A1 when castling rook is in SQ_B1.
if (pos.is_chess960())
{
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);
Bitboard occ = pos.occupied_squares();
clear_bit(&occ, rfrom);
if (pos.attackers_to(kto, occ) & pos.pieces(them))
return mlist;
}
(*mlist++).move = make_castle(kfrom, rfrom);
return mlist;
}
}
} // namespace

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,28 +17,40 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(MOVEGEN_H_INCLUDED)
#define MOVEGEN_H_INCLUDED
////
//// Includes
////
#include "types.h"
#include "position.h"
enum MoveType {
MV_CAPTURE,
MV_NON_CAPTURE,
MV_CHECK,
MV_NON_CAPTURE_CHECK,
MV_EVASION,
MV_NON_EVASION,
MV_LEGAL
};
class Position;
////
//// Prototypes
////
template<MoveType>
MoveStack* generate(const Position& pos, MoveStack* mlist);
extern MoveStack* generate_captures(const Position& pos, MoveStack* mlist);
extern MoveStack* generate_noncaptures(const Position& pos, MoveStack* mlist);
extern MoveStack* generate_non_capture_checks(const Position& pos, MoveStack* mlist);
extern MoveStack* generate_evasions(const Position& pos, MoveStack* mlist);
extern MoveStack* generate_moves(const Position& pos, MoveStack* mlist, bool pseudoLegal = false);
extern bool move_is_legal(const Position& pos, const Move m, Bitboard pinned);
extern bool move_is_legal(const Position& pos, const Move m);
/// The MoveList struct is a simple wrapper around generate(), sometimes comes
/// handy to use this class instead of the low level generate() function.
template<MoveType T>
struct MoveList {
explicit MoveList(const Position& pos) : cur(mlist), last(generate<T>(pos, mlist)) {}
void operator++() { cur++; }
bool end() const { return cur == last; }
Move move() const { return cur->move; }
int size() const { return int(last - mlist); }
private:
MoveStack mlist[MAX_MOVES];
MoveStack *cur, *last;
};
#endif // !defined(MOVEGEN_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -18,101 +18,138 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// Includes
////
#include <algorithm>
#include <cassert>
#include "history.h"
#include "movegen.h"
#include "movepick.h"
#include "search.h"
#include "value.h"
////
//// Local definitions
////
#include "types.h"
namespace {
enum MovegenPhase {
PH_TT_MOVES, // Transposition table move and mate killer
PH_GOOD_CAPTURES, // Queen promotions and captures with SEE values >= 0
PH_KILLERS, // Killer moves from the current ply
PH_NONCAPTURES, // Non-captures and underpromotions
PH_BAD_CAPTURES, // Queen promotions and captures with SEE values < 0
PH_EVASIONS, // Check evasions
PH_QCAPTURES, // Captures in quiescence search
PH_QCHECKS, // Non-capture checks in quiescence search
PH_TT_MOVE, // Transposition table move
PH_GOOD_CAPTURES, // Queen promotions and captures with SEE values >= captureThreshold (captureThreshold <= 0)
PH_GOOD_PROBCUT, // Queen promotions and captures with SEE values > captureThreshold (captureThreshold >= 0)
PH_KILLERS, // Killer moves from the current ply
PH_NONCAPTURES_1, // Non-captures and underpromotions with positive score
PH_NONCAPTURES_2, // Non-captures and underpromotions with non-positive score
PH_BAD_CAPTURES, // Queen promotions and captures with SEE values < captureThreshold (captureThreshold <= 0)
PH_EVASIONS, // Check evasions
PH_QCAPTURES, // Captures in quiescence search
PH_QRECAPTURES, // Recaptures in quiescence search
PH_QCHECKS, // Non-capture checks in quiescence search
PH_STOP
};
CACHE_LINE_ALIGNMENT
const uint8_t MainSearchPhaseTable[] = { PH_TT_MOVES, PH_GOOD_CAPTURES, PH_KILLERS, PH_NONCAPTURES, PH_BAD_CAPTURES, PH_STOP};
const uint8_t EvasionsPhaseTable[] = { PH_TT_MOVES, PH_EVASIONS, PH_STOP};
const uint8_t QsearchWithChecksPhaseTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_QCHECKS, PH_STOP};
const uint8_t QsearchWithoutChecksPhaseTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_STOP};
const uint8_t MainSearchTable[] = { PH_TT_MOVE, PH_GOOD_CAPTURES, PH_KILLERS, PH_NONCAPTURES_1, PH_NONCAPTURES_2, PH_BAD_CAPTURES, PH_STOP };
const uint8_t EvasionTable[] = { PH_TT_MOVE, PH_EVASIONS, PH_STOP };
const uint8_t QsearchWithChecksTable[] = { PH_TT_MOVE, PH_QCAPTURES, PH_QCHECKS, PH_STOP };
const uint8_t QsearchWithoutChecksTable[] = { PH_TT_MOVE, PH_QCAPTURES, PH_STOP };
const uint8_t QsearchRecapturesTable[] = { PH_TT_MOVE, PH_QRECAPTURES, PH_STOP };
const uint8_t ProbCutTable[] = { PH_TT_MOVE, PH_GOOD_PROBCUT, PH_STOP };
// Unary predicate used by std::partition to split positive scores from remaining
// ones so to sort separately the two sets, and with the second sort delayed.
inline bool has_positive_score(const MoveStack& move) { return move.score > 0; }
// Picks and pushes to the front the best move in range [firstMove, lastMove),
// it is faster than sorting all the moves in advance when moves are few, as
// normally are the possible captures.
inline MoveStack* pick_best(MoveStack* firstMove, MoveStack* lastMove)
{
std::swap(*firstMove, *std::max_element(firstMove, lastMove));
return firstMove;
}
}
////
//// Functions
////
/// Constructor for the MovePicker class. Apart from the position for which
/// it is asked to pick legal moves, MovePicker also wants some information
/// Constructors for the MovePicker class. As arguments we pass information
/// to help it to return the presumably good moves first, to decide which
/// moves to return (in the quiescence search, for instance, we only want to
/// search captures, promotions and some checks) and about how important good
/// move ordering is at the current node.
MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h,
SearchStack* ss, Value beta) : pos(p), H(h) {
int searchTT = ttm;
ttMoves[0].move = ttm;
badCaptureThreshold = 0;
lastBadCapture = badCaptures;
Search::Stack* ss, Value beta) : pos(p), H(h), depth(d) {
captureThreshold = 0;
badCaptures = moves + MAX_MOVES;
pinned = p.pinned_pieces(pos.side_to_move());
assert(d > DEPTH_ZERO);
if (ss && !p.is_check())
if (p.in_check())
{
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))
{
// Consider sligtly negative captures as good if at low
// depth and far from beta.
if (ss && ss->eval < beta - PawnValueMidgame && d < 3 * OnePly)
badCaptureThreshold = -PawnValueMidgame;
phasePtr = MainSearchPhaseTable;
killers[0].move = killers[1].move = MOVE_NONE;
phasePtr = EvasionTable;
}
else if (d == Depth(0))
phasePtr = QsearchWithChecksPhaseTable;
else
{
phasePtr = QsearchWithoutChecksPhaseTable;
killers[0].move = ss->killers[0];
killers[1].move = ss->killers[1];
// Consider sligtly negative captures as good if at low depth and far from beta
if (ss && ss->eval < beta - PawnValueMidgame && d < 3 * ONE_PLY)
captureThreshold = -PawnValueMidgame;
// Consider negative captures as good if still enough to reach beta
else if (ss && ss->eval > beta)
captureThreshold = beta - ss->eval;
phasePtr = MainSearchTable;
}
ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
phasePtr += int(ttMove == MOVE_NONE) - 1;
go_next_phase();
}
MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h, Square recaptureSq)
: pos(p), H(h) {
assert(d <= DEPTH_ZERO);
if (p.in_check())
phasePtr = EvasionTable;
else if (d >= DEPTH_QS_CHECKS)
phasePtr = QsearchWithChecksTable;
else if (d >= DEPTH_QS_RECAPTURES)
{
phasePtr = QsearchWithoutChecksTable;
// Skip TT move if is not a capture or a promotion, this avoids
// qsearch tree explosion due to a possible perpetual check or
// similar rare cases when TT table is full.
if (ttm != MOVE_NONE && !pos.move_is_capture_or_promotion(ttm))
searchTT = ttMoves[0].move = MOVE_NONE;
if (ttm != MOVE_NONE && !pos.is_capture_or_promotion(ttm))
ttm = MOVE_NONE;
}
else
{
phasePtr = QsearchRecapturesTable;
recaptureSquare = recaptureSq;
ttm = MOVE_NONE;
}
phasePtr += int(!searchTT) - 1;
ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
phasePtr += int(ttMove == MOVE_NONE) - 1;
go_next_phase();
}
MovePicker::MovePicker(const Position& p, Move ttm, const History& h, PieceType parentCapture)
: pos(p), H(h) {
assert (!pos.in_check());
// In ProbCut we consider only captures better than parent's move
captureThreshold = PieceValueMidgame[Piece(parentCapture)];
phasePtr = ProbCutTable;
if ( ttm != MOVE_NONE
&& (!pos.is_capture(ttm) || pos.see(ttm) <= captureThreshold))
ttm = MOVE_NONE;
ttMove = (ttm && pos.is_pseudo_legal(ttm) ? ttm : MOVE_NONE);
phasePtr += int(ttMove == MOVE_NONE) - 1;
go_next_phase();
}
@@ -126,13 +163,13 @@ void MovePicker::go_next_phase() {
phase = *(++phasePtr);
switch (phase) {
case PH_TT_MOVES:
curMove = ttMoves;
lastMove = curMove + 2;
case PH_TT_MOVE:
lastMove = curMove + 1;
return;
case PH_GOOD_CAPTURES:
lastMove = generate_captures(pos, moves);
case PH_GOOD_PROBCUT:
lastMove = generate<MV_CAPTURE>(pos, moves);
score_captures();
return;
@@ -141,37 +178,48 @@ void MovePicker::go_next_phase() {
lastMove = curMove + 2;
return;
case PH_NONCAPTURES:
lastMove = generate_noncaptures(pos, moves);
case PH_NONCAPTURES_1:
lastNonCapture = lastMove = generate<MV_NON_CAPTURE>(pos, moves);
score_noncaptures();
sort_moves(moves, lastMove, &lastGoodNonCapture);
lastMove = std::partition(curMove, lastMove, has_positive_score);
sort<MoveStack>(curMove, lastMove);
return;
case PH_NONCAPTURES_2:
curMove = lastMove;
lastMove = lastNonCapture;
if (depth >= 3 * ONE_PLY)
sort<MoveStack>(curMove, lastMove);
return;
case PH_BAD_CAPTURES:
// Bad captures SEE value is already calculated so just sort them
// to get SEE move ordering.
// Bad captures SEE value is already calculated so just pick
// them in order to get SEE move ordering.
curMove = badCaptures;
lastMove = lastBadCapture;
lastMove = moves + MAX_MOVES;
return;
case PH_EVASIONS:
assert(pos.is_check());
lastMove = generate_evasions(pos, moves);
score_evasions_or_checks();
assert(pos.in_check());
lastMove = generate<MV_EVASION>(pos, moves);
score_evasions();
return;
case PH_QCAPTURES:
lastMove = generate_captures(pos, moves);
lastMove = generate<MV_CAPTURE>(pos, moves);
score_captures();
return;
case PH_QRECAPTURES:
lastMove = generate<MV_CAPTURE>(pos, moves);
return;
case PH_QCHECKS:
lastMove = generate_non_capture_checks(pos, moves);
score_evasions_or_checks();
lastMove = generate<MV_NON_CAPTURE_CHECK>(pos, moves);
return;
case PH_STOP:
lastMove = curMove + 1; // Avoids another go_next_phase() call
lastMove = curMove + 1; // Avoid another go_next_phase() call
return;
default:
@@ -184,7 +232,7 @@ void MovePicker::go_next_phase() {
/// MovePicker::score_captures(), MovePicker::score_noncaptures() and
/// MovePicker::score_evasions() assign a numerical move ordering score
/// to each move in a move list. The moves with highest scores will be
/// picked first by get_next_move().
/// picked first by next_move().
void MovePicker::score_captures() {
// Winning and equal captures in the main search are ordered by MVV/LVA.
@@ -206,41 +254,28 @@ void MovePicker::score_captures() {
for (MoveStack* cur = moves; cur != lastMove; cur++)
{
m = cur->move;
if (move_is_promotion(m))
cur->score = QueenValueMidgame;
else
cur->score = pos.midgame_value_of_piece_on(move_to(m))
- pos.type_of_piece_on(move_from(m));
cur->score = PieceValueMidgame[pos.piece_on(to_sq(m))]
- type_of(pos.piece_on(from_sq(m)));
if (is_promotion(m))
cur->score += PieceValueMidgame[Piece(promotion_piece_type(m))];
}
}
void MovePicker::score_noncaptures() {
// First score by history, when no history is available then use
// piece/square tables values. This seems to be better then a
// random choice when we don't have an history for any move.
Move m;
Piece piece;
Square from, to;
int hs;
Square from;
for (MoveStack* cur = moves; cur != lastMove; cur++)
{
m = cur->move;
from = move_from(m);
to = move_to(m);
piece = pos.piece_on(from);
hs = H.move_ordering_score(piece, to);
// Ensure history has always highest priority
if (hs > 0)
hs += 10000;
// Gain table based scoring
cur->score = hs + 16 * H.gain(piece, to);
from = from_sq(m);
cur->score = H.value(pos.piece_on(from), to_sq(m));
}
}
void MovePicker::score_evasions_or_checks() {
void MovePicker::score_evasions() {
// Try good captures ordered by MVV/LVA, then non-captures if
// destination square is not under attack, ordered by history
// value, and at the end bad-captures and non-captures with a
@@ -256,113 +291,109 @@ void MovePicker::score_evasions_or_checks() {
{
m = cur->move;
if ((seeScore = pos.see_sign(m)) < 0)
cur->score = seeScore - HistoryMax; // Be sure are at the bottom
else if (pos.move_is_capture(m))
cur->score = pos.midgame_value_of_piece_on(move_to(m))
- pos.type_of_piece_on(move_from(m)) + HistoryMax;
cur->score = seeScore - History::MaxValue; // Be sure we are at the bottom
else if (pos.is_capture(m))
cur->score = PieceValueMidgame[pos.piece_on(to_sq(m))]
- type_of(pos.piece_on(from_sq(m))) + History::MaxValue;
else
cur->score = H.move_ordering_score(pos.piece_on(move_from(m)), move_to(m));
cur->score = H.value(pos.piece_on(from_sq(m)), to_sq(m));
}
}
/// MovePicker::get_next_move() is the most important method of the MovePicker
/// class. It returns a new legal move every time it is called, until there
/// are no more moves left.
/// It picks the move with the biggest score from a list of generated moves taking
/// care not to return the tt move if has already been searched previously.
/// Note that this function is not thread safe so should be lock protected by
/// caller when accessed through a shared MovePicker object.
/// MovePicker::next_move() is the most important method of the MovePicker class.
/// It returns a new pseudo legal move every time it is called, until there
/// are no more moves left. It picks the move with the biggest score from a list
/// of generated moves taking care not to return the tt move if has already been
/// searched previously. Note that this function is not thread safe so should be
/// lock protected by caller when accessed through a shared MovePicker object.
Move MovePicker::get_next_move() {
Move MovePicker::next_move() {
Move move;
while (true)
{
while (curMove != lastMove)
{
switch (phase) {
while (curMove == lastMove)
go_next_phase();
case PH_TT_MOVES:
move = (curMove++)->move;
if ( move != MOVE_NONE
&& move_is_legal(pos, move, pinned))
switch (phase) {
case PH_TT_MOVE:
curMove++;
return ttMove;
break;
case PH_GOOD_CAPTURES:
move = pick_best(curMove++, lastMove)->move;
if (move != ttMove)
{
assert(captureThreshold <= 0); // Otherwise we must use see instead of see_sign
// Check for a non negative SEE now
int seeValue = pos.see_sign(move);
if (seeValue >= captureThreshold)
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 >= badCaptureThreshold)
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_is_legal(pos, move, pinned)
&& move != ttMoves[0].move
&& move != ttMoves[1].move
&& !pos.move_is_capture(move))
return move;
break;
case PH_NONCAPTURES:
// Sort negative scored moves only when we get there
if (curMove == lastGoodNonCapture)
insertion_sort(lastGoodNonCapture, lastMove);
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;
// Losing capture, move it to the tail of the array
(--badCaptures)->move = move;
badCaptures->score = seeValue;
}
break;
case PH_GOOD_PROBCUT:
move = pick_best(curMove++, lastMove)->move;
if ( move != ttMove
&& pos.see(move) > captureThreshold)
return move;
break;
case PH_KILLERS:
move = (curMove++)->move;
if ( move != MOVE_NONE
&& pos.is_pseudo_legal(move)
&& move != ttMove
&& !pos.is_capture(move))
return move;
break;
case PH_NONCAPTURES_1:
case PH_NONCAPTURES_2:
move = (curMove++)->move;
if ( move != ttMove
&& move != killers[0].move
&& move != killers[1].move)
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 != ttMove)
return move;
break;
case PH_QRECAPTURES:
move = (curMove++)->move;
if (to_sq(move) == recaptureSquare)
return move;
break;
case PH_QCHECKS:
move = (curMove++)->move;
if (move != ttMove)
return move;
break;
case PH_STOP:
return MOVE_NONE;
default:
assert(false);
break;
}
go_next_phase();
}
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,71 +17,48 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined MOVEPICK_H_INCLUDED
#define MOVEPICK_H_INCLUDED
////
//// Includes
////
#include "depth.h"
#include "history.h"
#include "position.h"
#include "search.h"
#include "types.h"
////
//// Types
////
struct SearchStack;
/// MovePicker is a class which is used to pick one legal move at a time from
/// the current position. It is initialized with a Position object and a few
/// MovePicker is a class which is used to pick one pseudo legal move at a time
/// from the current position. It is initialized with a Position object and a few
/// 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.
/// MovePicker::next_move(), which returns a new pseudo legal move each time
/// it is called, until there are no moves left, when MOVE_NONE is returned.
/// In order to improve the efficiency of the alpha beta algorithm, MovePicker
/// attempts to return the moves which are most likely to be strongest first.
/// attempts to return the moves which are most likely to get a cut-off first.
class MovePicker {
MovePicker& operator=(const MovePicker&); // silence a warning under MSVC
MovePicker& operator=(const MovePicker&); // Silence a warning under MSVC
public:
MovePicker(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss = NULL, Value beta = -VALUE_INFINITE);
Move get_next_move();
int number_of_evasions() const;
MovePicker(const Position&, Move, Depth, const History&, Search::Stack*, Value);
MovePicker(const Position&, Move, Depth, const History&, Square recaptureSq);
MovePicker(const Position&, Move, const History&, PieceType parentCapture);
Move next_move();
private:
void score_captures();
void score_noncaptures();
void score_evasions_or_checks();
void score_evasions();
void go_next_phase();
const Position& pos;
const History& H;
Bitboard pinned;
MoveStack ttMoves[2], killers[2];
int badCaptureThreshold, phase;
Depth depth;
Move ttMove;
MoveStack killers[2];
Square recaptureSquare;
int captureThreshold, phase;
const uint8_t* phasePtr;
MoveStack *curMove, *lastMove, *lastGoodNonCapture, *lastBadCapture;
MoveStack moves[256], badCaptures[64];
MoveStack *curMove, *lastMove, *lastNonCapture, *badCaptures;
MoveStack moves[MAX_MOVES];
};
////
//// 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)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,46 +17,37 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// Includes
////
#include <cassert>
#include <cstring>
#include "bitboard.h"
#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)
};
// Doubled pawn penalty by opposed flag and file
const Score DoubledPawnPenalty[2][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) },
{ 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)
};
// Isolated pawn penalty by opposed flag and file
const Score IsolatedPawnPenalty[2][8] = {
{ S(37, 45), S(54, 52), S(60, 52), S(60, 52),
S(60, 52), S(60, 52), S(54, 52), S(37, 45) },
{ S(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)
};
// Backward pawn penalty by opposed flag and file
const Score BackwardPawnPenalty[2][8] = {
{ S(30, 42), S(43, 46), S(49, 46), S(49, 46),
S(49, 46), S(49, 46), S(43, 46), S(30, 42) },
{ S(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] = {
@@ -70,86 +61,26 @@ namespace {
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 QStormOpenFileBonus[8] = { 31, 31, 18, 0, 0, 0, 0, 0 };
const int16_t KStormOpenFileBonus[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 };
const Score PawnStructureWeight = S(233, 201);
#undef S
}
////
//// Functions
////
/// PawnInfoTable c'tor and d'tor instantiated one each thread
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();
inline Score apply_weight(Score v, Score w) {
return make_score((int(mg_value(v)) * mg_value(w)) / 0x100,
(int(eg_value(v)) * eg_value(w)) / 0x100);
}
}
PawnInfoTable::~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
/// PawnInfoTable::pawn_info() takes a position object as input, computes
/// a PawnInfo object, and returns a pointer to it. The result is also stored
/// in a hash table, so we don't have to recompute everything when the same
/// in an hash table, so we don't have to recompute everything when the same
/// pawn structure occurs again.
PawnInfo* PawnInfoTable::get_pawn_info(const Position& pos) const {
PawnInfo* PawnInfoTable::pawn_info(const Position& pos) const {
assert(pos.is_ok());
Key key = pos.get_pawn_key();
int index = int(key & (size - 1));
PawnInfo* pi = entries + index;
Key key = pos.pawn_key();
PawnInfo* pi = probe(key);
// If pi->key matches the position's pawn hash key, it means that we
// have analysed this pawn structure before, and we can simply return
@@ -157,19 +88,24 @@ PawnInfo* PawnInfoTable::get_pawn_info(const Position& pos) const {
if (pi->key == key)
return pi;
// Clear the PawnInfo object, and set the key
pi->clear();
// Initialize PawnInfo entry
pi->key = key;
pi->passedPawns[WHITE] = pi->passedPawns[BLACK] = 0;
pi->kingSquares[WHITE] = pi->kingSquares[BLACK] = SQ_NONE;
pi->halfOpenFiles[WHITE] = pi->halfOpenFiles[BLACK] = 0xFF;
// Calculate pawn attacks
Bitboard 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);
Bitboard wPawns = pos.pieces(PAWN, WHITE);
Bitboard bPawns = pos.pieces(PAWN, BLACK);
pi->pawnAttacks[WHITE] = ((wPawns << 9) & ~FileABB) | ((wPawns << 7) & ~FileHBB);
pi->pawnAttacks[BLACK] = ((bPawns >> 7) & ~FileABB) | ((bPawns >> 9) & ~FileHBB);
// Evaluate pawns for both colors and weight the result
pi->value = evaluate_pawns<WHITE>(pos, wPawns, bPawns, pi)
- evaluate_pawns<BLACK>(pos, bPawns, wPawns, pi);
pi->value = apply_weight(pi->value, PawnStructureWeight);
// Evaluate pawns for both colors
pi->value = evaluate_pawns<WHITE>(pos, whitePawns, blackPawns, pi)
- evaluate_pawns<BLACK>(pos, blackPawns, whitePawns, pi);
return pi;
}
@@ -178,63 +114,49 @@ PawnInfo* PawnInfoTable::get_pawn_info(const Position& pos) const {
template<Color Us>
Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
Bitboard theirPawns, PawnInfo* pi) const {
Bitboard theirPawns, PawnInfo* pi) {
const Color Them = (Us == WHITE ? BLACK : WHITE);
Bitboard b;
Square s;
File f;
Rank r;
int bonus;
bool passed, isolated, doubled, opposed, chain, backward, candidate;
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);
}
Score value = SCORE_ZERO;
const Square* pl = pos.piece_list(Us, PAWN);
// Loop through all pawns of the current color and score each pawn
while ((s = *ptr++) != SQ_NONE)
while ((s = *pl++) != SQ_NONE)
{
f = square_file(s);
r = square_rank(s);
assert(pos.piece_on(s) == make_piece(Us, PAWN));
assert(pos.piece_on(s) == piece_of_color_and_type(Us, PAWN));
f = file_of(s);
r = rank_of(s);
// Calculate kingside and queenside pawn storm scores for both colors to be
// used when evaluating middle game positions with opposite side castling.
bonus = (f >= FILE_F ? evaluate_pawn_storm<Us, KingSide>(s, r, f, theirPawns) : 0);
pi->ksStormValue[Us] += KStormTable[relative_square(Us, s)] + bonus;
// This file cannot be half open
pi->halfOpenFiles[Us] &= ~(1 << f);
bonus = (f <= FILE_C ? evaluate_pawn_storm<Us, QueenSide>(s, r, f, theirPawns) : 0);
pi->qsStormValue[Us] += QStormTable[relative_square(Us, s)] + bonus;
// Our rank plus previous one. Used for chain detection
b = rank_bb(r) | rank_bb(Us == WHITE ? r - Rank(1) : r + Rank(1));
// Our rank plus previous one. Used for chain detection.
b = rank_bb(r) | rank_bb(r + (Us == WHITE ? -1 : 1));
// Passed, isolated, doubled or member of a pawn
// chain (but not the backward one) ?
// Flag the pawn as passed, isolated, doubled or member of a pawn
// chain (but not the backward one).
passed = !(theirPawns & passed_pawn_mask(Us, s));
doubled = ourPawns & squares_behind(Us, s);
doubled = ourPawns & squares_in_front_of(Us, s);
opposed = theirPawns & squares_in_front_of(Us, s);
isolated = !(ourPawns & neighboring_files_bb(f));
chain = ourPawns & neighboring_files_bb(f) & b;
// Test for backward pawn
//
// 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 & attack_span_mask(opposite_color(Us), s))
|| (pos.attacks_from<PAWN>(s, Us) & theirPawns))
backward = false;
else
backward = false;
// If the pawn is passed, isolated, or member of a pawn chain it cannot
// be backward. If there are friendly pawns behind on neighboring files
// or if can capture an enemy pawn it cannot be backward either.
if ( !(passed | isolated | chain)
&& !(ourPawns & attack_span_mask(Them, s))
&& !(pos.attacks_from<PAWN>(s, Us) & theirPawns))
{
// We now know that there are no friendly pawns beside or behind this
// pawn on neighboring files. We now check whether the pawn is
@@ -247,103 +169,72 @@ Score PawnInfoTable::evaluate_pawns(const Position& pos, Bitboard ourPawns,
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.
// 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;
}
assert(passed | opposed | (attack_span_mask(Us, s) & theirPawns));
assert(opposed | passed | (attack_span_mask(Us, s) & theirPawns));
// Test for candidate passed pawn
candidate = !(opposed | passed)
&& (b = attack_span_mask(opposite_color(Us), s + pawn_push(Us)) & ourPawns) != EmptyBoardBB
&& count_1s_max_15(b) >= count_1s_max_15(attack_span_mask(Us, s) & theirPawns);
// A not passed pawn is a candidate to become passed if it is free to
// advance and if the number of friendly pawns beside or behind this
// pawn on neighboring files is higher or equal than the number of
// enemy pawns in the forward direction on the neighboring files.
candidate = !(opposed | passed | backward | isolated)
&& (b = attack_span_mask(Them, s + pawn_push(Us)) & ourPawns) != 0
&& popcount<Max15>(b) >= popcount<Max15>(attack_span_mask(Us, s) & theirPawns);
// 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;
// Mark the pawn as passed. Pawn will be properly scored in evaluation
// because we need full attack info to evaluate passed pawns.
if (passed)
set_bit(&(pi->passedPawns), s);
// Passed pawns will be properly scored in evaluation because we need
// full attack info to evaluate passed pawns. Only the frontmost passed
// pawn on each file is considered a true passed pawn.
if (passed && !doubled)
set_bit(&(pi->passedPawns[Us]), s);
// Score this pawn
if (isolated)
{
value -= IsolatedPawnPenalty[f];
if (!(theirPawns & file_bb(f)))
value -= IsolatedPawnPenalty[f] / 2;
}
value -= IsolatedPawnPenalty[opposed][f];
if (doubled)
value -= DoubledPawnPenalty[f];
value -= DoubledPawnPenalty[opposed][f];
if (backward)
{
value -= BackwardPawnPenalty[f];
if (!(theirPawns & file_bb(f)))
value -= BackwardPawnPenalty[f] / 2;
}
value -= BackwardPawnPenalty[opposed][f];
if (chain)
value += ChainBonus[f];
if (candidate)
value += CandidateBonus[relative_rank(Us, s)];
}
return value;
}
/// PawnInfoTable::evaluate_pawn_storm() evaluates each pawn which seems
/// to have good chances of creating an open file by exchanging itself
/// against an enemy pawn on an adjacent file.
/// PawnInfo::updateShelter() calculates and caches king shelter. It is called
/// only when king square changes, about 20% of total king_shelter() calls.
template<Color Us>
Score PawnInfo::updateShelter(const Position& pos, Square ksq) {
template<Color Us, PawnInfoTable::SideType Side>
int PawnInfoTable::evaluate_pawn_storm(Square s, Rank r, File f, Bitboard theirPawns) const {
const int Shift = (Us == WHITE ? 8 : -8);
const Bitboard StormFilesBB = (Side == KingSide ? FileFBB | FileGBB | FileHBB
: FileABB | FileBBB | FileCBB);
const int K = (Side == KingSide ? 2 : 4);
const File RookFile = (Side == KingSide ? FILE_H : FILE_A);
Bitboard pawns;
int r, shelter = 0;
Bitboard b = attack_span_mask(Us, s) & theirPawns & StormFilesBB;
int bonus = 0;
while (b)
if (relative_rank(Us, ksq) <= RANK_4)
{
// Give a bonus according to the distance of the nearest enemy pawn
Square s2 = pop_1st_bit(&b);
Rank r2 = square_rank(s2);
int v = StormLeverBonus[f] - K * rank_distance(r, r2);
// If enemy pawn has no pawn beside itself is particularly vulnerable.
// Big bonus, especially against a weakness on the rook file
if (!(theirPawns & neighboring_files_bb(s2) & rank_bb(s2)))
v *= (square_file(s2) == RookFile ? 4 : 2);
bonus += v;
pawns = pos.pieces(PAWN, Us) & this_and_neighboring_files_bb(file_of(ksq));
r = ksq & (7 << 3);
for (int i = 0; i < 3; i++)
{
r += Shift;
shelter += BitCount8Bit[(pawns >> r) & 0xFF] << (6 - i);
}
}
return bonus;
kingSquares[Us] = ksq;
kingShelters[Us] = make_score(shelter, 0);
return kingShelters[Us];
}
/// 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) {
Bitboard pawns = pos.pieces(PAWN, c) & this_and_neighboring_files_bb(ksq);
unsigned shelter = 0;
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;
}
// Explicit template instantiation
template Score PawnInfo::updateShelter<WHITE>(const Position& pos, Square ksq);
template Score PawnInfo::updateShelter<BLACK>(const Position& pos, Square ksq);

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,112 +17,78 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(PAWNS_H_INCLUDED)
#define PAWNS_H_INCLUDED
////
//// Includes
////
#include "position.h"
#include "tt.h"
#include "types.h"
#include "bitboard.h"
#include "value.h"
////
//// Types
////
const int PawnTableSize = 16384;
/// 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;
/// to add further information in the future. A lookup to the pawn hash
/// table (performed by calling the pawn_info method in a PawnInfoTable
/// object) returns a pointer to a PawnInfo object.
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;
Bitboard passed_pawns(Color c) 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];
Square kingSquares[2];
Score value;
int16_t ksStormValue[2], qsStormValue[2];
uint8_t halfOpenFiles[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 {
enum SideType { KingSide, QueenSide };
public:
PawnInfoTable(unsigned numOfEntries);
~PawnInfoTable();
PawnInfo* get_pawn_info(const Position& pos) const;
template<Color Us>
Score king_shelter(const Position& pos, Square ksq);
private:
template<Color Us>
Score evaluate_pawns(const Position& pos, Bitboard ourPawns, Bitboard theirPawns, PawnInfo* pi) const;
Score updateShelter(const Position& pos, Square ksq);
template<Color Us, SideType Side>
int evaluate_pawn_storm(Square s, Rank r, File f, Bitboard theirPawns) const;
unsigned size;
PawnInfo* entries;
Key key;
Bitboard passedPawns[2];
Bitboard pawnAttacks[2];
Square kingSquares[2];
Score value;
int halfOpenFiles[2];
Score kingShelters[2];
};
////
//// Inline functions
////
/// The PawnInfoTable class represents a pawn hash table. The most important
/// method is pawn_info, which returns a pointer to a PawnInfo object.
class PawnInfoTable : public SimpleHash<PawnInfo, PawnTableSize> {
public:
PawnInfo* pawn_info(const Position& pos) const;
private:
template<Color Us>
static Score evaluate_pawns(const Position& pos, Bitboard ourPawns, Bitboard theirPawns, PawnInfo* pi);
};
inline Score PawnInfo::pawns_value() const {
return value;
}
inline Bitboard PawnInfo::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 Bitboard PawnInfo::passed_pawns(Color c) const {
return passedPawns[c];
}
inline int PawnInfo::file_is_half_open(Color c, File f) const {
return (halfOpenFiles[c] & (1 << int(f)));
return halfOpenFiles[c] & (1 << int(f));
}
inline int PawnInfo::has_open_file_to_left(Color c, File f) const {
@@ -133,8 +99,9 @@ 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));
template<Color Us>
inline Score PawnInfo::king_shelter(const Position& pos, Square ksq) {
return kingSquares[Us] == ksq ? kingShelters[Us] : updateShelter<Us>(pos, ksq);
}
#endif // !defined(PAWNS_H_INCLUDED)

View File

@@ -1,49 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// 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 + int(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;
}

View File

@@ -1,107 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(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)

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,79 +17,26 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(POSITION_H_INCLUDED)
#define POSITION_H_INCLUDED
// Disable some silly and noisy warning from MSVC compiler
#if defined(_MSC_VER)
// Forcing value to bool 'true' or 'false' (performance warning)
#pragma warning(disable: 4800)
// Conditional expression is constant
#pragma warning(disable: 4127)
#endif
////
//// Includes
////
#include <cassert>
#include "bitboard.h"
#include "color.h"
#include "direction.h"
#include "move.h"
#include "piece.h"
#include "square.h"
#include "value.h"
#include "types.h"
////
//// Constants
////
/// FEN string for the initial position
const std::string StartPosition = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
/// 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.
/// The checkInfo struct is initialized at c'tor time and keeps info used
/// to detect if a move gives check.
class Position;
struct CheckInfo {
explicit CheckInfo(const Position&);
explicit CheckInfo(const Position&);
Bitboard dcCandidates;
Bitboard checkSq[8];
Square ksq;
};
/// Castle rights, encoded as bit fields
enum CastleRights {
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
Bitboard dcCandidates;
Bitboard pinned;
Bitboard checkSq[8];
};
@@ -100,14 +47,14 @@ enum Phase {
struct StateInfo {
Key pawnKey, materialKey;
int castleRights, rule50, gamePly, pliesFromNull;
Square epSquare;
Score value;
Value npMaterial[2];
int castleRights, rule50, pliesFromNull;
Score value;
Square epSquare;
PieceType capture;
Key key;
Bitboard checkersBB;
PieceType capturedType;
StateInfo* previous;
};
@@ -136,39 +83,24 @@ struct StateInfo {
class Position {
friend class MaterialInfo;
friend class EndgameFunctions;
Position(); // No default or copy c'tor allowed
Position(const Position& pos);
// No copy c'tor or assignment operator allowed
Position(const Position&);
Position& operator=(const Position&);
public:
enum GamePhase {
MidGame,
EndGame
};
// Constructors
explicit Position(int threadID);
Position(const Position& pos, int threadID);
Position(const std::string& fen, int threadID);
Position() {}
Position(const Position& pos, int th) { copy(pos, th); }
Position(const std::string& fen, bool isChess960, int th);
// Text input/output
void from_fen(const std::string& fen);
void copy(const Position& pos, int th);
void from_fen(const std::string& fen, bool isChess960);
const std::string to_fen() const;
void print(Move m = MOVE_NONE) const;
// Copying
void flipped_copy(const Position& pos);
// The piece on a given square
Piece piece_on(Square s) const;
PieceType type_of_piece_on(Square s) const;
Color color_of_piece_on(Square s) const;
bool square_is_empty(Square s) const;
bool square_is_occupied(Square s) const;
Value midgame_value_of_piece_on(Square s) const;
Value endgame_value_of_piece_on(Square s) const;
// Side to move
Color side_to_move() const;
@@ -176,7 +108,7 @@ public:
// Bitboard representation of the position
Bitboard empty_squares() const;
Bitboard occupied_squares() const;
Bitboard pieces_of_color(Color c) const;
Bitboard pieces(Color c) const;
Bitboard pieces(PieceType pt) const;
Bitboard pieces(PieceType pt, Color c) const;
Bitboard pieces(PieceType pt1, PieceType pt2) const;
@@ -192,68 +124,59 @@ public:
Square king_square(Color c) const;
// Castling rights
bool can_castle_kingside(Color c) const;
bool can_castle_queenside(Color c) const;
bool can_castle(CastleRight f) const;
bool can_castle(Color c) const;
Square initial_kr_square(Color c) const;
Square initial_qr_square(Color c) const;
Square castle_rook_square(CastleRight f) const;
// Bitboards for pinned pieces and discovered check candidates
Bitboard discovered_check_candidates(Color c) const;
Bitboard pinned_pieces(Color c) const;
Bitboard discovered_check_candidates() const;
Bitboard pinned_pieces() const;
// Checking pieces and under check information
Bitboard checkers() const;
bool is_check() const;
bool in_check() const;
// Piece lists
Square piece_list(Color c, PieceType pt, int index) const;
const Square* piece_list_begin(Color c, PieceType pt) const;
const Square* piece_list(Color c, PieceType pt) const;
// Information about attacks to or from a given square
Bitboard attackers_to(Square s) const;
Bitboard attackers_to(Square s, Bitboard occ) const;
Bitboard attacks_from(Piece p, Square s) const;
static Bitboard attacks_from(Piece p, Square s, Bitboard occ);
template<PieceType> Bitboard attacks_from(Square s) const;
template<PieceType> Bitboard attacks_from(Square s, Color c) const;
// Properties of moves
bool pl_move_is_legal(Move m, Bitboard pinned) const;
bool pl_move_is_evasion(Move m, Bitboard pinned) const;
bool move_is_check(Move m) const;
bool move_is_check(Move m, const CheckInfo& ci) const;
bool move_is_capture(Move m) const;
bool move_is_capture_or_promotion(Move m) const;
bool move_is_passed_pawn_push(Move m) const;
bool move_gives_check(Move m, const CheckInfo& ci) const;
bool move_attacks_square(Move m, Square s) const;
bool pl_move_is_legal(Move m, Bitboard pinned) const;
bool is_pseudo_legal(const Move m) const;
bool is_capture(Move m) const;
bool is_capture_or_promotion(Move m) const;
bool is_passed_pawn_push(Move m) const;
// Piece captured with previous moves
PieceType captured_piece() const;
PieceType captured_piece_type() const;
// Information about pawns
bool pawn_is_passed(Color c, Square s) const;
// Weak squares
bool square_is_weak(Square s, Color c) const;
// Doing and undoing moves
void detach();
void do_move(Move m, StateInfo& st);
void do_move(Move m, StateInfo& st, const CheckInfo& ci, bool moveIsCheck);
void undo_move(Move m);
void do_null_move(StateInfo& st);
void undo_null_move();
template<bool Do> void do_null_move(StateInfo& st);
// Static exchange evaluation
int see(Square from, Square to) const;
int see(Move m) const;
int see(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;
Key key() const;
Key exclusion_key() const;
Key pawn_key() const;
Key material_key() const;
// Incremental evaluation
Score value() const;
@@ -262,47 +185,40 @@ public:
// Game termination checks
bool is_mate() const;
bool is_draw() const;
template<bool SkipRepetition> 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;
// Plies from start position to the beginning of search
int startpos_ply_counter() const;
// Other properties of the position
bool opposite_colored_bishops() const;
bool has_pawn_on_7th(Color c) const;
bool is_chess960() const;
// Current thread ID searching on the position
int thread() const;
// Reset the gamePly variable to 0
void reset_game_ply();
int64_t nodes_searched() const;
void set_nodes_searched(int64_t n);
// Position consistency check, for debugging
bool is_ok(int* failedStep = NULL) const;
bool pos_is_ok(int* failedStep = NULL) const;
void flip_me();
// Static member functions
static void init_zobrist();
static void init_piece_square_tables();
// Global initialization
static void init();
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);
void set_castle_right(Square ksq, Square rsq);
bool move_is_legal(const Move m) const;
// Helper functions for doing and undoing moves
void do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep);
void do_castle_move(Move m);
void undo_castle_move(Move m);
void find_checkers();
template<bool FindPinned>
Bitboard hidden_checkers(Color c) const;
// Helper template functions
template<bool Do> void do_castle_move(Move m);
template<bool FindPinned> Bitboard hidden_checkers() const;
// Computing hash keys from scratch (for initialization and debugging)
Key compute_key() const;
@@ -310,72 +226,59 @@ private:
Key compute_material_key() const;
// Computing incremental evaluation scores and material counts
Score pst(Color c, PieceType pt, Square s) const;
Score pst(Piece p, Square s) const;
Score compute_value() const;
Value compute_non_pawn_material(Color c) const;
// Board
Piece board[64];
Piece board[64]; // [square]
// Bitboards
Bitboard byTypeBB[8], byColorBB[2];
Bitboard byTypeBB[8]; // [pieceType]
Bitboard byColorBB[2]; // [color]
Bitboard occupied;
// Piece counts
int pieceCount[2][8]; // [color][pieceType]
int pieceCount[2][8]; // [color][pieceType]
// Piece lists
Square pieceList[2][8][16]; // [color][pieceType][index]
int index[64]; // [square]
Square pieceList[2][8][16]; // [color][pieceType][index]
int index[64]; // [square]
// Other info
Color sideToMove;
Key history[MaxGameLength];
int castleRightsMask[64];
int castleRightsMask[64]; // [square]
Square castleRookSquare[16]; // [castleRight]
StateInfo startState;
File initialKFile, initialKRFile, initialQRFile;
int64_t nodes;
int startPosPly;
Color sideToMove;
int threadID;
StateInfo* st;
int chess960;
// Static variables
static Key zobrist[2][8][64];
static Key zobEp[64];
static Key zobCastle[16];
static Score pieceSquareTable[16][64]; // [piece][square]
static Key zobrist[2][8][64]; // [color][pieceType][square]/[piece count]
static Key zobEp[64]; // [square]
static Key zobCastle[16]; // [castleRight]
static Key zobSideToMove;
static Score PieceSquareTable[16][64];
static Key zobExclusion;
};
inline int64_t Position::nodes_searched() const {
return nodes;
}
////
//// Inline functions
////
inline void Position::set_nodes_searched(int64_t n) {
nodes = n;
}
inline Piece Position::piece_on(Square s) const {
return board[s];
}
inline Color Position::color_of_piece_on(Square s) const {
return color_of_piece(piece_on(s));
}
inline PieceType Position::type_of_piece_on(Square s) const {
return type_of_piece(piece_on(s));
}
inline bool Position::square_is_empty(Square s) const {
return piece_on(s) == EMPTY;
}
inline bool Position::square_is_occupied(Square s) const {
return !square_is_empty(s);
}
inline Value Position::midgame_value_of_piece_on(Square s) const {
return piece_value_midgame(piece_on(s));
}
inline Value Position::endgame_value_of_piece_on(Square s) const {
return piece_value_endgame(piece_on(s));
return board[s] == NO_PIECE;
}
inline Color Position::side_to_move() const {
@@ -383,14 +286,14 @@ inline Color Position::side_to_move() const {
}
inline Bitboard Position::occupied_squares() const {
return byTypeBB[0];
return occupied;
}
inline Bitboard Position::empty_squares() const {
return ~(occupied_squares());
return ~occupied;
}
inline Bitboard Position::pieces_of_color(Color c) const {
inline Bitboard Position::pieces(Color c) const {
return byColorBB[c];
}
@@ -414,11 +317,7 @@ inline int Position::piece_count(Color c, PieceType pt) const {
return pieceCount[c][pt];
}
inline Square Position::piece_list(Color c, PieceType pt, int idx) const {
return pieceList[c][pt][idx];
}
inline const Square* Position::piece_list_begin(Color c, PieceType pt) const {
inline const Square* Position::piece_list(Color c, PieceType pt) const {
return pieceList[c][pt];
}
@@ -430,34 +329,26 @@ inline Square Position::king_square(Color c) const {
return pieceList[c][KING][0];
}
inline bool Position::can_castle_kingside(Color side) const {
return st->castleRights & (1+int(side));
inline bool Position::can_castle(CastleRight f) const {
return st->castleRights & f;
}
inline bool Position::can_castle_queenside(Color side) const {
return st->castleRights & (4+4*int(side));
inline bool Position::can_castle(Color c) const {
return st->castleRights & ((WHITE_OO | WHITE_OOO) << c);
}
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));
inline Square Position::castle_rook_square(CastleRight f) const {
return castleRookSquare[f];
}
template<>
inline Bitboard Position::attacks_from<PAWN>(Square s, Color c) const {
return StepAttackBB[piece_of_color_and_type(c, PAWN)][s];
return StepAttacksBB[make_piece(c, PAWN)][s];
}
template<PieceType Piece> // Knight and King and white pawns
inline Bitboard Position::attacks_from(Square s) const {
return StepAttackBB[Piece][s];
return StepAttacksBB[Piece][s];
}
template<>
@@ -475,44 +366,56 @@ inline Bitboard Position::attacks_from<QUEEN>(Square s) const {
return attacks_from<ROOK>(s) | attacks_from<BISHOP>(s);
}
inline Bitboard Position::attacks_from(Piece p, Square s) const {
return attacks_from(p, s, occupied_squares());
}
inline Bitboard Position::attackers_to(Square s) const {
return attackers_to(s, occupied_squares());
}
inline Bitboard Position::checkers() const {
return st->checkersBB;
}
inline bool Position::is_check() const {
return st->checkersBB != EmptyBoardBB;
inline bool Position::in_check() const {
return st->checkersBB != 0;
}
inline Bitboard Position::discovered_check_candidates() const {
return hidden_checkers<false>();
}
inline Bitboard Position::pinned_pieces() const {
return hidden_checkers<true>();
}
inline bool Position::pawn_is_passed(Color c, Square s) const {
return !(pieces(PAWN, opposite_color(c)) & passed_pawn_mask(c, s));
return !(pieces(PAWN, flip(c)) & passed_pawn_mask(c, s));
}
inline bool Position::square_is_weak(Square s, Color c) const {
return !(pieces(PAWN, opposite_color(c)) & attack_span_mask(c, s));
}
inline Key Position::get_key() const {
inline Key Position::key() const {
return st->key;
}
inline Key Position::get_exclusion_key() const {
inline Key Position::exclusion_key() const {
return st->key ^ zobExclusion;
}
inline Key Position::get_pawn_key() const {
inline Key Position::pawn_key() const {
return st->pawnKey;
}
inline Key Position::get_material_key() const {
inline Key Position::material_key() const {
return st->materialKey;
}
inline Score Position::pst(Color c, PieceType pt, Square s) const {
return PieceSquareTable[piece_of_color_and_type(c, pt)][s];
inline Score Position::pst(Piece p, Square s) const {
return pieceSquareTable[p][s];
}
inline Score Position::pst_delta(Piece piece, Square from, Square to) const {
return PieceSquareTable[piece][to] - PieceSquareTable[piece][from];
return pieceSquareTable[piece][to] - pieceSquareTable[piece][from];
}
inline Score Position::value() const {
@@ -523,44 +426,46 @@ inline Value Position::non_pawn_material(Color c) const {
return st->npMaterial[c];
}
inline bool Position::move_is_passed_pawn_push(Move m) const {
inline bool Position::is_passed_pawn_push(Move m) const {
Color c = side_to_move();
return piece_on(move_from(m)) == piece_of_color_and_type(c, PAWN)
&& pawn_is_passed(c, move_to(m));
return board[from_sq(m)] == make_piece(sideToMove, PAWN)
&& pawn_is_passed(sideToMove, to_sq(m));
}
inline int Position::rule_50_counter() const {
return st->rule50;
inline int Position::startpos_ply_counter() const {
return startPosPly + st->pliesFromNull; // HACK
}
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));
return pieceCount[WHITE][BISHOP] == 1
&& pieceCount[BLACK][BISHOP] == 1
&& opposite_colors(pieceList[WHITE][BISHOP][0], pieceList[BLACK][BISHOP][0]);
}
inline bool Position::has_pawn_on_7th(Color c) const {
return pieces(PAWN, c) & relative_rank_bb(c, RANK_7);
return pieces(PAWN, c) & rank_bb(relative_rank(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::is_chess960() const {
return chess960;
}
inline bool Position::move_is_capture_or_promotion(Move m) const {
inline bool Position::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));
assert(is_ok(m));
return is_special(m) ? !is_castle(m) : !square_is_empty(to_sq(m));
}
inline PieceType Position::captured_piece() const {
return st->capture;
inline bool Position::is_capture(Move m) const {
// Note that castle is coded as "king captures the rook"
assert(is_ok(m));
return (!square_is_empty(to_sq(m)) && !is_castle(m)) || is_enpassant(m);
}
inline PieceType Position::captured_piece_type() const {
return st->capturedType;
}
inline int Position::thread() const {

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,172 +17,82 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(PSQTAB_H_INCLUDED)
#define PSQTAB_H_INCLUDED
////
//// Includes
////
#include "types.h"
#include "value.h"
#define S(mg, eg) make_score(mg, eg)
////
//// Constants modified by Joona Kiiski
////
/// PSQT[PieceType][Square] contains Piece-Square scores. For each piece type on
/// a given square a (midgame, endgame) score pair is assigned. PSQT is defined
/// for white side, for black side the tables are symmetric.
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] = {
static const Score PSQT[][64] = {
{ },
{// Pawn
// A B C D E F G H
0, 0, 0, 0, 0, 0, 0, 0,
MP-28, MP-6, MP+ 4, MP+14, MP+14, MP+ 4, MP-6, MP-28,
MP-28, MP-6, MP+ 9, MP+36, MP+36, MP+ 9, MP-6, MP-28,
MP-28, MP-6, MP+17, MP+58, MP+58, MP+17, MP-6, MP-28,
MP-28, MP-6, MP+17, MP+36, MP+36, MP+17, MP-6, MP-28,
MP-28, MP-6, MP+ 9, MP+14, MP+14, MP+ 9, MP-6, MP-28,
MP-28, MP-6, MP+ 4, MP+14, MP+14, MP+ 4, MP-6, MP-28,
0, 0, 0, 0, 0, 0, 0, 0
{ // Pawn
S( 0, 0), S( 0, 0), S( 0, 0), S( 0, 0), S(0, 0), S( 0, 0), S( 0, 0), S( 0, 0),
S(-28,-8), S(-6,-8), S( 4,-8), S(14,-8), S(14,-8), S( 4,-8), S(-6,-8), S(-28,-8),
S(-28,-8), S(-6,-8), S( 9,-8), S(36,-8), S(36,-8), S( 9,-8), S(-6,-8), S(-28,-8),
S(-28,-8), S(-6,-8), S(17,-8), S(58,-8), S(58,-8), S(17,-8), S(-6,-8), S(-28,-8),
S(-28,-8), S(-6,-8), S(17,-8), S(36,-8), S(36,-8), S(17,-8), S(-6,-8), S(-28,-8),
S(-28,-8), S(-6,-8), S( 9,-8), S(14,-8), S(14,-8), S( 9,-8), S(-6,-8), S(-28,-8),
S(-28,-8), S(-6,-8), S( 4,-8), S(14,-8), S(14,-8), S( 4,-8), S(-6,-8), S(-28,-8),
S( 0, 0), S( 0, 0), S( 0, 0), S( 0, 0), S(0, 0), S( 0, 0), S( 0, 0), S( 0, 0)
},
{// Knight
// A B C D E F G H
MK-135, MK-107, MK-80, MK-67, MK-67, MK-80, MK-107, MK-135,
MK- 93, MK- 67, MK-39, MK-25, MK-25, MK-39, MK- 67, MK- 93,
MK- 53, MK- 25, MK+ 1, MK+13, MK+13, MK+ 1, MK- 25, MK- 53,
MK- 25, MK+ 1, MK+27, MK+41, MK+41, MK+27, MK+ 1, MK- 25,
MK- 11, MK+ 13, MK+41, MK+55, MK+55, MK+41, MK+ 13, MK- 11,
MK- 11, MK+ 13, MK+41, MK+55, MK+55, MK+41, MK+ 13, MK- 11,
MK- 53, MK- 25, MK+ 1, MK+13, MK+13, MK+ 1, MK- 25, MK- 53,
MK-193, MK- 67, MK-39, MK-25, MK-25, MK-39, MK- 67, MK-193
{ // Knight
S(-135,-104), S(-107,-79), S(-80,-55), S(-67,-42), S(-67,-42), S(-80,-55), S(-107,-79), S(-135,-104),
S( -93, -79), S( -67,-55), S(-39,-30), S(-25,-17), S(-25,-17), S(-39,-30), S( -67,-55), S( -93, -79),
S( -53, -55), S( -25,-30), S( 1, -6), S( 13, 5), S( 13, 5), S( 1, -6), S( -25,-30), S( -53, -55),
S( -25, -42), S( 1,-17), S( 27, 5), S( 41, 18), S( 41, 18), S( 27, 5), S( 1,-17), S( -25, -42),
S( -11, -42), S( 13,-17), S( 41, 5), S( 55, 18), S( 55, 18), S( 41, 5), S( 13,-17), S( -11, -42),
S( -11, -55), S( 13,-30), S( 41, -6), S( 55, 5), S( 55, 5), S( 41, -6), S( 13,-30), S( -11, -55),
S( -53, -79), S( -25,-55), S( 1,-30), S( 13,-17), S( 13,-17), S( 1,-30), S( -25,-55), S( -53, -79),
S(-193,-104), S( -67,-79), S(-39,-55), S(-25,-42), S(-25,-42), S(-39,-55), S( -67,-79), S(-193,-104)
},
{// Bishop
// A B C D E F G H
MB-40, MB-40, MB-35, MB-30, MB-30, MB-35, MB-40, MB-40,
MB-17, MB+ 0, MB- 4, MB+ 0, MB+ 0, MB- 4, MB+ 0, MB-17,
MB-13, MB- 4, MB+ 8, MB+ 4, MB+ 4, MB+ 8, MB- 4, MB-13,
MB- 8, MB+ 0, MB+ 4, MB+17, MB+17, MB+ 4, MB+ 0, MB- 8,
MB- 8, MB+ 0, MB+ 4, MB+17, MB+17, MB+ 4, MB+ 0, MB- 8,
MB-13, MB- 4, MB+ 8, MB+ 4, MB+ 4, MB+ 8, MB- 4, MB-13,
MB-17, MB+ 0, MB- 4, MB+ 0, MB+ 0, MB- 4, MB+ 0, MB-17,
MB-17, MB-17, MB-13, MB- 8, MB- 8, MB-13, MB-17, MB-17
{ // Bishop
S(-40,-59), S(-40,-42), S(-35,-35), S(-30,-26), S(-30,-26), S(-35,-35), S(-40,-42), S(-40,-59),
S(-17,-42), S( 0,-26), S( -4,-18), S( 0,-11), S( 0,-11), S( -4,-18), S( 0,-26), S(-17,-42),
S(-13,-35), S( -4,-18), S( 8,-11), S( 4, -4), S( 4, -4), S( 8,-11), S( -4,-18), S(-13,-35),
S( -8,-26), S( 0,-11), S( 4, -4), S( 17, 4), S( 17, 4), S( 4, -4), S( 0,-11), S( -8,-26),
S( -8,-26), S( 0,-11), S( 4, -4), S( 17, 4), S( 17, 4), S( 4, -4), S( 0,-11), S( -8,-26),
S(-13,-35), S( -4,-18), S( 8,-11), S( 4, -4), S( 4, -4), S( 8,-11), S( -4,-18), S(-13,-35),
S(-17,-42), S( 0,-26), S( -4,-18), S( 0,-11), S( 0,-11), S( -4,-18), S( 0,-26), S(-17,-42),
S(-17,-59), S(-17,-42), S(-13,-35), S( -8,-26), S( -8,-26), S(-13,-35), S(-17,-42), S(-17,-59)
},
{// Rook
// A B C D E F G H
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12
{ // Rook
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3),
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3),
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3),
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3),
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3),
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3),
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3),
S(-12, 3), S(-7, 3), S(-2, 3), S(2, 3), S(2, 3), S(-2, 3), S(-7, 3), S(-12, 3)
},
{// Queen
// A B C D E F G H
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8
{ // Queen
S(8,-80), S(8,-54), S(8,-42), S(8,-30), S(8,-30), S(8,-42), S(8,-54), S(8,-80),
S(8,-54), S(8,-30), S(8,-18), S(8, -6), S(8, -6), S(8,-18), S(8,-30), S(8,-54),
S(8,-42), S(8,-18), S(8, -6), S(8, 6), S(8, 6), S(8, -6), S(8,-18), S(8,-42),
S(8,-30), S(8, -6), S(8, 6), S(8, 18), S(8, 18), S(8, 6), S(8, -6), S(8,-30),
S(8,-30), S(8, -6), S(8, 6), S(8, 18), S(8, 18), S(8, 6), S(8, -6), S(8,-30),
S(8,-42), S(8,-18), S(8, -6), S(8, 6), S(8, 6), S(8, -6), S(8,-18), S(8,-42),
S(8,-54), S(8,-30), S(8,-18), S(8, -6), S(8, -6), S(8,-18), S(8,-30), S(8,-54),
S(8,-80), S(8,-54), S(8,-42), S(8,-30), S(8,-30), S(8,-42), S(8,-54), S(8,-80)
},
{// King
//A B C D E F G H
287, 311, 262, 214, 214, 262, 311, 287,
262, 287, 238, 190, 190, 238, 287, 262,
214, 238, 190, 142, 142, 190, 238, 214,
190, 214, 167, 119, 119, 167, 214, 190,
167, 190, 142, 94, 94, 142, 190, 167,
142, 167, 119, 69, 69, 119, 167, 142,
119, 142, 94, 46, 46, 94, 142, 119,
94, 119, 69, 21, 21, 69, 119, 94
}
};
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
{ // King
S(287, 18), S(311, 77), S(262,105), S(214,135), S(214,135), S(262,105), S(311, 77), S(287, 18),
S(262, 77), S(287,135), S(238,165), S(190,193), S(190,193), S(238,165), S(287,135), S(262, 77),
S(214,105), S(238,165), S(190,193), S(142,222), S(142,222), S(190,193), S(238,165), S(214,105),
S(190,135), S(214,193), S(167,222), S(119,251), S(119,251), S(167,222), S(214,193), S(190,135),
S(167,135), S(190,193), S(142,222), S( 94,251), S( 94,251), S(142,222), S(190,193), S(167,135),
S(142,105), S(167,165), S(119,193), S( 69,222), S( 69,222), S(119,193), S(167,165), S(142,105),
S(119, 77), S(142,135), S( 94,165), S( 46,193), S( 46,193), S( 94,165), S(142,135), S(119, 77),
S(94, 18), S(119, 77), S( 69,105), S( 21,135), S( 21,135), S( 69,105), S(119, 77), S( 94, 18)
}
};
#undef S
#endif // !defined(PSQTAB_H_INCLUDED)

78
src/rkiss.h Normal file
View File

@@ -0,0 +1,78 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
This file is based on original code by Heinz van Saanen and is
available under the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
*/
#if !defined(RKISS_H_INCLUDED)
#define RKISS_H_INCLUDED
#include "types.h"
/// RKISS is our pseudo random number generator (PRNG) used to compute hash keys.
/// George Marsaglia invented the RNG-Kiss-family in the early 90's. This is a
/// specific version that Heinz van Saanen derived from some public domain code
/// by Bob Jenkins. Following the feature list, as tested by Heinz.
///
/// - Quite platform independent
/// - Passes ALL dieharder tests! Here *nix sys-rand() e.g. fails miserably:-)
/// - ~12 times faster than my *nix sys-rand()
/// - ~4 times faster than SSE2-version of Mersenne twister
/// - Average cycle length: ~2^126
/// - 64 bit seed
/// - Return doubles with a full 53 bit mantissa
/// - Thread safe
class RKISS {
// Keep variables always together
struct S { uint64_t a, b, c, d; } s;
uint64_t rotate(uint64_t x, uint64_t k) const {
return (x << k) | (x >> (64 - k));
}
// Return 64 bit unsigned integer in between [0, 2^64 - 1]
uint64_t rand64() {
const uint64_t
e = s.a - rotate(s.b, 7);
s.a = s.b ^ rotate(s.c, 13);
s.b = s.c + rotate(s.d, 37);
s.c = s.d + e;
return s.d = e + s.a;
}
// Init seed and scramble a few rounds
void raninit() {
s.a = 0xf1ea5eed;
s.b = s.c = s.d = 0xd4e12c77;
for (int i = 0; i < 73; i++)
rand64();
}
public:
RKISS() { raninit(); }
template<typename T> T rand() { return T(rand64()); }
};
#endif // !defined(RKISS_H_INCLUDED)

View File

@@ -1,440 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// 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(Position& pos, Move m) {
assert(pos.is_ok());
assert(move_is_ok(m));
string san;
Square from = move_from(m);
Square to = move_to(m);
PieceType pt = type_of_piece(pos.piece_on(move_from(m)));
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);
}
}
// The move gives check ? We don't use pos.move_is_check() here
// because we need to test for mate after the move is done.
StateInfo st;
pos.do_move(m, st);
if (pos.is_check())
san += pos.is_mate() ? "#" : "+";
pos.undo_move(m);
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, pos.thread());
for (Move* m = line; *m != MOVE_NONE; m++)
{
moveStr = move_to_san(p, *m);
length += moveStr.length() + 1;
if (breakLines && length > maxLength)
{
s << "\n" << std::setw(startColumn) << " ";
length = moveStr.length() + 1;
}
s << moveStr << ' ';
if (*m == MOVE_NULL)
p.do_null_move(st);
else
p.do_move(*m, 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[]) {
const uint64_t K = 1000;
const uint64_t M = 1000000;
std::stringstream s;
// Depth
s << std::setw(2) << depth << " ";
// Score
s << (type == VALUE_TYPE_LOWER ? ">" : type == VALUE_TYPE_UPPER ? "<" : " ")
<< std::setw(7) << score_string(score);
// Time
s << std::setw(8) << time_string(time) << " ";
// Nodes
if (nodes < M)
s << std::setw(8) << nodes / 1 << " ";
else if (nodes < K * M)
s << std::setw(7) << nodes / K << "K ";
else
s << std::setw(7) << nodes / M << "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 millisecs) {
const int MSecMinute = 1000 * 60;
const int MSecHour = 1000 * 60 * 60;
std::stringstream s;
s << std::setfill('0');
int hours = millisecs / MSecHour;
int minutes = (millisecs - hours * MSecHour) / MSecMinute;
int seconds = (millisecs - hours * MSecHour - minutes * MSecMinute) / 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();
}
}

View File

@@ -1,44 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(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(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)

View File

@@ -1,52 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(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)

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,66 +17,66 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(SEARCH_H_INCLUDED)
#define SEARCH_H_INCLUDED
////
//// Includes
////
#include <cstring>
#include <vector>
#include "depth.h"
#include "move.h"
#include "value.h"
#include "types.h"
class Position;
struct SplitPoint;
////
//// Constants
////
namespace Search {
const int PLY_MAX = 100;
const int PLY_MAX_PLUS_2 = 102;
const int KILLER_MAX = 2;
/// The Stack struct keeps track of the information we need to remember from
/// nodes shallower and deeper in the tree during the search. Each search thread
/// has its own array of Stack objects, indexed by the current ply.
////
//// Types
////
/// The SearchStack struct keeps track of the information we need to remember
/// from nodes shallower and deeper in the tree during the search. Each
/// search thread has its own array of SearchStack objects, indexed by the
/// current ply.
struct EvalInfo;
struct SearchStack {
struct Stack {
SplitPoint* sp;
int ply;
Move currentMove;
Move mateKiller;
Move threatMove;
Move excludedMove;
Move bestMove;
Move killers[KILLER_MAX];
Move killers[2];
Depth reduction;
Value eval;
bool skipNullMove;
void init();
void initKillers();
Value evalMargin;
int skipNullMove;
};
////
//// Prototypes
////
/// The LimitsType struct stores information sent by GUI about available time
/// to search the current move, maximum depth/time, if we are in analysis mode
/// or if we have to ponder while is our opponent's side to move.
extern void init_search();
extern void init_threads();
extern void exit_threads();
extern bool think(const Position &pos, bool infinite, bool ponder, int side_to_move,
int time[], int increment[], int movesToGo, int maxDepth,
int maxNodes, int maxTime, Move searchMoves[]);
extern int perft(Position &pos, Depth depth);
extern int64_t nodes_searched();
struct LimitsType {
LimitsType() { memset(this, 0, sizeof(LimitsType)); }
bool use_time_management() const { return !(maxTime | maxDepth | maxNodes | infinite); }
int time, increment, movesToGo, maxTime, maxDepth, maxNodes, infinite, ponder;
};
/// The SignalsType struct stores volatile flags updated during the search
/// typically in an async fashion, for instance to stop the search by the GUI.
struct SignalsType {
bool stopOnPonderhit, firstRootMove, stop, failedLowAtRoot;
};
extern volatile SignalsType Signals;
extern LimitsType Limits;
extern std::vector<Move> SearchMoves;
extern Position RootPosition;
extern void init();
extern int64_t perft(Position& pos, Depth depth);
extern void think();
} // namespace
#endif // !defined(SEARCH_H_INCLUDED)

View File

@@ -1,201 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(SQUARE_H_INCLUDED)
#define SQUARE_H_INCLUDED
////
//// Includes
////
#include <cstdlib> // for abs()
#include <string>
#include "color.h"
#include "misc.h"
////
//// Types
////
enum Square {
SQ_A1, SQ_B1, SQ_C1, SQ_D1, SQ_E1, SQ_F1, SQ_G1, SQ_H1,
SQ_A2, SQ_B2, SQ_C2, SQ_D2, SQ_E2, SQ_F2, SQ_G2, SQ_H2,
SQ_A3, SQ_B3, SQ_C3, SQ_D3, SQ_E3, SQ_F3, SQ_G3, SQ_H3,
SQ_A4, SQ_B4, SQ_C4, SQ_D4, SQ_E4, SQ_F4, SQ_G4, SQ_H4,
SQ_A5, SQ_B5, SQ_C5, SQ_D5, SQ_E5, SQ_F5, SQ_G5, SQ_H5,
SQ_A6, SQ_B6, SQ_C6, SQ_D6, SQ_E6, SQ_F6, SQ_G6, SQ_H6,
SQ_A7, SQ_B7, SQ_C7, SQ_D7, SQ_E7, SQ_F7, SQ_G7, SQ_H7,
SQ_A8, SQ_B8, SQ_C8, SQ_D8, SQ_E8, SQ_F8, SQ_G8, SQ_H8,
SQ_NONE
};
enum File {
FILE_A, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H, FILE_NONE
};
enum Rank {
RANK_1, RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8, RANK_NONE
};
enum SquareDelta {
DELTA_SSW = -021, DELTA_SS = -020, DELTA_SSE = -017, DELTA_SWW = -012,
DELTA_SW = -011, DELTA_S = -010, DELTA_SE = -07, DELTA_SEE = -06,
DELTA_W = -01, DELTA_ZERO = 0, DELTA_E = 01, DELTA_NWW = 06, DELTA_NW = 07,
DELTA_N = 010, DELTA_NE = 011, DELTA_NEE = 012, DELTA_NNW = 017,
DELTA_NN = 020, DELTA_NNE = 021
};
////
//// Constants
////
const int FlipMask = 070;
const int FlopMask = 07;
////
//// Inline functions
////
inline File operator+ (File x, int i) { return File(int(x) + i); }
inline File operator+ (File x, File y) { return x + int(y); }
inline void operator++ (File &x, int) { x = File(int(x) + 1); }
inline void operator+= (File &x, int i) { x = File(int(x) + i); }
inline File operator- (File x, int i) { return File(int(x) - i); }
inline void operator-- (File &x, int) { x = File(int(x) - 1); }
inline void operator-= (File &x, int i) { x = File(int(x) - i); }
inline Rank operator+ (Rank x, int i) { return Rank(int(x) + i); }
inline Rank operator+ (Rank x, Rank y) { return x + int(y); }
inline void operator++ (Rank &x, int) { x = Rank(int(x) + 1); }
inline void operator+= (Rank &x, int i) { x = Rank(int(x) + i); }
inline Rank operator- (Rank x, int i) { return Rank(int(x) - i); }
inline void operator-- (Rank &x, int) { x = Rank(int(x) - 1); }
inline void operator-= (Rank &x, int i) { x = Rank(int(x) - i); }
inline Square operator+ (Square x, int i) { return Square(int(x) + i); }
inline void operator++ (Square &x, int) { x = Square(int(x) + 1); }
inline void operator+= (Square &x, int i) { x = Square(int(x) + i); }
inline Square operator- (Square x, int i) { return Square(int(x) - i); }
inline void operator-- (Square &x, int) { x = Square(int(x) - 1); }
inline void operator-= (Square &x, int i) { x = Square(int(x) - i); }
inline Square operator+ (Square x, SquareDelta i) { return Square(int(x) + i); }
inline void operator+= (Square &x, SquareDelta i) { x = Square(int(x) + i); }
inline Square operator- (Square x, SquareDelta i) { return Square(int(x) - i); }
inline void operator-= (Square &x, SquareDelta i) { x = Square(int(x) - i); }
inline SquareDelta operator- (Square x, Square y) {
return SquareDelta(int(x) - int(y));
}
inline Square make_square(File f, Rank r) {
return Square(int(f) | (int(r) << 3));
}
inline File square_file(Square s) {
return File(int(s) & 7);
}
inline Rank square_rank(Square s) {
return Rank(int(s) >> 3);
}
inline Square flip_square(Square s) {
return Square(int(s) ^ FlipMask);
}
inline Square flop_square(Square s) {
return Square(int(s) ^ FlopMask);
}
inline Square relative_square(Color c, Square s) {
return Square(int(s) ^ (int(c) * FlipMask));
}
inline Rank relative_rank(Color c, Square s) {
return square_rank(relative_square(c, s));
}
inline Color square_color(Square s) {
return Color((int(square_file(s)) + int(square_rank(s))) & 1);
}
inline int file_distance(File f1, File f2) {
return abs(int(f1) - int(f2));
}
inline int file_distance(Square s1, Square s2) {
return file_distance(square_file(s1), square_file(s2));
}
inline int rank_distance(Rank r1, Rank r2) {
return abs(int(r1) - int(r2));
}
inline int rank_distance(Square s1, Square s2) {
return rank_distance(square_rank(s1), square_rank(s2));
}
inline int square_distance(Square s1, Square s2) {
return Max(file_distance(s1, s2), rank_distance(s1, s2));
}
inline File file_from_char(char c) {
return File(c - 'a') + FILE_A;
}
inline char file_to_char(File f) {
return char(f - FILE_A + int('a'));
}
inline Rank rank_from_char(char c) {
return Rank(c - '1') + RANK_1;
}
inline char rank_to_char(Rank r) {
return char(r - RANK_1 + int('1'));
}
inline Square square_from_string(const std::string& str) {
return make_square(file_from_char(str[0]), rank_from_char(str[1]));
}
inline const std::string square_to_string(Square s) {
std::string str;
str += file_to_char(square_file(s));
str += rank_to_char(square_rank(s));
return str;
}
inline bool file_is_ok(File f) {
return f >= FILE_A && f <= FILE_H;
}
inline bool rank_is_ok(Rank r) {
return r >= RANK_1 && r <= RANK_8;
}
inline bool square_is_ok(Square s) {
return file_is_ok(square_file(s)) && rank_is_ok(square_rank(s));
}
#endif // !defined(SQUARE_H_INCLUDED)

502
src/thread.cpp Normal file
View File

@@ -0,0 +1,502 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "search.h"
#include "thread.h"
#include "ucioption.h"
using namespace Search;
ThreadsManager Threads; // Global object
namespace { extern "C" {
// start_routine() is the C function which is called when a new thread
// is launched. It simply calls idle_loop() of the supplied thread. The first
// and last thread are special. First one is the main search thread while the
// last one mimics a timer, they run in main_loop() and timer_loop().
#if defined(_MSC_VER)
DWORD WINAPI start_routine(LPVOID thread) {
#else
void* start_routine(void* thread) {
#endif
Thread* th = (Thread*)thread;
if (th->threadID == 0)
th->main_loop();
else if (th->threadID == MAX_THREADS)
th->timer_loop();
else
th->idle_loop(NULL);
return 0;
}
} }
// wake_up() wakes up the thread, normally at the beginning of the search or,
// if "sleeping threads" is used, when there is some work to do.
void Thread::wake_up() {
lock_grab(&sleepLock);
cond_signal(&sleepCond);
lock_release(&sleepLock);
}
// cutoff_occurred() checks whether a beta cutoff has occurred in the current
// active split point, or in some ancestor of the split point.
bool Thread::cutoff_occurred() const {
for (SplitPoint* sp = splitPoint; sp; sp = sp->parent)
if (sp->is_betaCutoff)
return true;
return false;
}
// is_available_to() checks whether the thread is available to help the thread with
// threadID "master" at a split point. An obvious requirement is that thread must be
// idle. With more than two threads, this is not by itself sufficient: If the thread
// is the master of some active split point, it is only available as a slave to the
// threads which are busy searching the split point at the top of "slave"'s split
// point stack (the "helpful master concept" in YBWC terminology).
bool Thread::is_available_to(int master) const {
if (is_searching)
return false;
// Make a local copy to be sure doesn't become zero under our feet while
// testing next condition and so leading to an out of bound access.
int localActiveSplitPoints = activeSplitPoints;
// No active split points means that the thread is available as a slave for any
// other thread otherwise apply the "helpful master" concept if possible.
if ( !localActiveSplitPoints
|| splitPoints[localActiveSplitPoints - 1].is_slave[master])
return true;
return false;
}
// read_uci_options() updates number of active threads and other parameters
// according to the UCI options values. It is called before to start a new search.
void ThreadsManager::read_uci_options() {
maxThreadsPerSplitPoint = Options["Max Threads per Split Point"];
minimumSplitDepth = Options["Min Split Depth"] * ONE_PLY;
useSleepingThreads = Options["Use Sleeping Threads"];
set_size(Options["Threads"]);
}
// set_size() changes the number of active threads and raises do_sleep flag for
// all the unused threads that will go immediately to sleep.
void ThreadsManager::set_size(int cnt) {
assert(cnt > 0 && cnt <= MAX_THREADS);
activeThreads = cnt;
for (int i = 1; i < MAX_THREADS; i++) // Ignore main thread
if (i < activeThreads)
{
// Dynamically allocate pawn and material hash tables according to the
// number of active threads. This avoids preallocating memory for all
// possible threads if only few are used.
threads[i].pawnTable.init();
threads[i].materialTable.init();
threads[i].do_sleep = false;
}
else
threads[i].do_sleep = true;
}
// init() is called during startup. Initializes locks and condition variables
// and launches all threads sending them immediately to sleep.
void ThreadsManager::init() {
// Initialize sleep condition and lock used by thread manager
cond_init(&sleepCond);
lock_init(&threadsLock);
// Initialize thread's sleep conditions and split point locks
for (int i = 0; i <= MAX_THREADS; i++)
{
lock_init(&threads[i].sleepLock);
cond_init(&threads[i].sleepCond);
for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
lock_init(&(threads[i].splitPoints[j].lock));
}
// Allocate main thread tables to call evaluate() also when not searching
threads[0].pawnTable.init();
threads[0].materialTable.init();
// Create and launch all the threads, threads will go immediately to sleep
for (int i = 0; i <= MAX_THREADS; i++)
{
threads[i].is_searching = false;
threads[i].do_sleep = (i != 0); // Avoid a race with start_thinking()
threads[i].threadID = i;
#if defined(_MSC_VER)
threads[i].handle = CreateThread(NULL, 0, start_routine, &threads[i], 0, NULL);
bool ok = (threads[i].handle != NULL);
#else
bool ok = !pthread_create(&threads[i].handle, NULL, start_routine, &threads[i]);
#endif
if (!ok)
{
std::cerr << "Failed to create thread number " << i << std::endl;
::exit(EXIT_FAILURE);
}
}
}
// exit() is called to cleanly terminate the threads when the program finishes
void ThreadsManager::exit() {
for (int i = 0; i <= MAX_THREADS; i++)
{
threads[i].do_terminate = true; // Search must be already finished
threads[i].wake_up();
// Wait for thread termination
#if defined(_MSC_VER)
WaitForSingleObject(threads[i].handle, INFINITE);
CloseHandle(threads[i].handle);
#else
pthread_join(threads[i].handle, NULL);
#endif
// Now we can safely destroy associated locks and wait conditions
lock_destroy(&threads[i].sleepLock);
cond_destroy(&threads[i].sleepCond);
for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
lock_destroy(&(threads[i].splitPoints[j].lock));
}
lock_destroy(&threadsLock);
cond_destroy(&sleepCond);
}
// available_slave_exists() tries to find an idle thread which is available as
// a slave for the thread with threadID 'master'.
bool ThreadsManager::available_slave_exists(int master) const {
assert(master >= 0 && master < activeThreads);
for (int i = 0; i < activeThreads; i++)
if (threads[i].is_available_to(master))
return true;
return false;
}
// split_point_finished() checks if all the slave threads of a given split
// point have finished searching.
bool ThreadsManager::split_point_finished(SplitPoint* sp) const {
for (int i = 0; i < activeThreads; i++)
if (sp->is_slave[i])
return false;
return true;
}
// split() does the actual work of distributing the work at a node between
// several available threads. If it does not succeed in splitting the node
// (because no idle threads are available, or because we have no unused split
// point objects), the function immediately returns. If splitting is possible, a
// SplitPoint object is initialized with all the data that must be copied to the
// helper threads and then helper threads are told that they have been assigned
// work. This will cause them to instantly leave their idle loops and call
// search(). When all threads have returned from search() then split() returns.
template <bool Fake>
Value ThreadsManager::split(Position& pos, Stack* ss, Value alpha, Value beta,
Value bestValue, Depth depth, Move threatMove,
int moveCount, MovePicker* mp, int nodeType) {
assert(pos.pos_is_ok());
assert(bestValue > -VALUE_INFINITE);
assert(bestValue <= alpha);
assert(alpha < beta);
assert(beta <= VALUE_INFINITE);
assert(depth > DEPTH_ZERO);
assert(pos.thread() >= 0 && pos.thread() < activeThreads);
assert(activeThreads > 1);
int i, master = pos.thread();
Thread& masterThread = threads[master];
// If we already have too many active split points, don't split
if (masterThread.activeSplitPoints >= MAX_ACTIVE_SPLIT_POINTS)
return bestValue;
// Pick the next available split point from the split point stack
SplitPoint* sp = &masterThread.splitPoints[masterThread.activeSplitPoints];
// Initialize the split point
sp->parent = masterThread.splitPoint;
sp->master = master;
sp->is_betaCutoff = false;
sp->depth = depth;
sp->threatMove = threatMove;
sp->alpha = alpha;
sp->beta = beta;
sp->nodeType = nodeType;
sp->bestValue = bestValue;
sp->mp = mp;
sp->moveCount = moveCount;
sp->pos = &pos;
sp->nodes = 0;
sp->ss = ss;
for (i = 0; i < activeThreads; i++)
sp->is_slave[i] = false;
// If we are here it means we are not available
assert(masterThread.is_searching);
int workersCnt = 1; // At least the master is included
// Try to allocate available threads and ask them to start searching setting
// is_searching flag. This must be done under lock protection to avoid concurrent
// allocation of the same slave by another master.
lock_grab(&threadsLock);
for (i = 0; !Fake && i < activeThreads && workersCnt < maxThreadsPerSplitPoint; i++)
if (threads[i].is_available_to(master))
{
workersCnt++;
sp->is_slave[i] = true;
threads[i].splitPoint = sp;
// This makes the slave to exit from idle_loop()
threads[i].is_searching = true;
if (useSleepingThreads)
threads[i].wake_up();
}
lock_release(&threadsLock);
// We failed to allocate even one slave, return
if (!Fake && workersCnt == 1)
return bestValue;
masterThread.splitPoint = sp;
masterThread.activeSplitPoints++;
// Everything is set up. The master thread enters the idle loop, from which
// it will instantly launch a search, because its is_searching flag is set.
// We pass the split point as a parameter to the idle loop, which means that
// the thread will return from the idle loop when all slaves have finished
// their work at this split point.
masterThread.idle_loop(sp);
// In helpful master concept a master can help only a sub-tree of its split
// point, and because here is all finished is not possible master is booked.
assert(!masterThread.is_searching);
// We have returned from the idle loop, which means that all threads are
// finished. Note that changing state and decreasing activeSplitPoints is done
// under lock protection to avoid a race with Thread::is_available_to().
lock_grab(&threadsLock);
masterThread.is_searching = true;
masterThread.activeSplitPoints--;
lock_release(&threadsLock);
masterThread.splitPoint = sp->parent;
pos.set_nodes_searched(pos.nodes_searched() + sp->nodes);
return sp->bestValue;
}
// Explicit template instantiations
template Value ThreadsManager::split<false>(Position&, Stack*, Value, Value, Value, Depth, Move, int, MovePicker*, int);
template Value ThreadsManager::split<true>(Position&, Stack*, Value, Value, Value, Depth, Move, int, MovePicker*, int);
// Thread::timer_loop() is where the timer thread waits maxPly milliseconds and
// then calls do_timer_event(). If maxPly is 0 thread sleeps until is woken up.
extern void check_time();
void Thread::timer_loop() {
while (!do_terminate)
{
lock_grab(&sleepLock);
timed_wait(&sleepCond, &sleepLock, maxPly ? maxPly : INT_MAX);
lock_release(&sleepLock);
check_time();
}
}
// ThreadsManager::set_timer() is used to set the timer to trigger after msec
// milliseconds. If msec is 0 then timer is stopped.
void ThreadsManager::set_timer(int msec) {
Thread& timer = threads[MAX_THREADS];
lock_grab(&timer.sleepLock);
timer.maxPly = msec;
cond_signal(&timer.sleepCond); // Wake up and restart the timer
lock_release(&timer.sleepLock);
}
// Thread::main_loop() is where the main thread is parked waiting to be started
// when there is a new search. Main thread will launch all the slave threads.
void Thread::main_loop() {
while (true)
{
lock_grab(&sleepLock);
do_sleep = true; // Always return to sleep after a search
is_searching = false;
while (do_sleep && !do_terminate)
{
cond_signal(&Threads.sleepCond); // Wake up UI thread if needed
cond_wait(&sleepCond, &sleepLock);
}
is_searching = true;
lock_release(&sleepLock);
if (do_terminate)
return;
think(); // This is the search entry point
}
}
// ThreadsManager::start_thinking() is used by UI thread to wake up the main
// thread parked in main_loop() and starting a new search. If asyncMode is true
// then function returns immediately, otherwise caller is blocked waiting for
// the search to finish.
void ThreadsManager::start_thinking(const Position& pos, const LimitsType& limits,
const std::vector<Move>& searchMoves, bool asyncMode) {
Thread& main = threads[0];
lock_grab(&main.sleepLock);
// Wait main thread has finished before to launch a new search
while (!main.do_sleep)
cond_wait(&sleepCond, &main.sleepLock);
// Copy input arguments to initialize the search
RootPosition.copy(pos, 0);
Limits = limits;
SearchMoves = searchMoves;
// Reset signals before to start the new search
memset((void*)&Signals, 0, sizeof(Signals));
main.do_sleep = false;
cond_signal(&main.sleepCond); // Wake up main thread and start searching
if (!asyncMode)
while (!main.do_sleep)
cond_wait(&sleepCond, &main.sleepLock);
lock_release(&main.sleepLock);
}
// ThreadsManager::stop_thinking() is used by UI thread to raise a stop request
// and to wait for the main thread finishing the search. Needed to wait exiting
// and terminate the threads after a 'quit' command.
void ThreadsManager::stop_thinking() {
Thread& main = threads[0];
Search::Signals.stop = true;
lock_grab(&main.sleepLock);
cond_signal(&main.sleepCond); // In case is waiting for stop or ponderhit
while (!main.do_sleep)
cond_wait(&sleepCond, &main.sleepLock);
lock_release(&main.sleepLock);
}
// ThreadsManager::wait_for_stop_or_ponderhit() is called when the maximum depth
// is reached while the program is pondering. The point is to work around a wrinkle
// in the UCI protocol: When pondering, the engine is not allowed to give a
// "bestmove" before the GUI sends it a "stop" or "ponderhit" command. We simply
// wait here until one of these commands (that raise StopRequest) is sent and
// then return, after which the bestmove and pondermove will be printed.
void ThreadsManager::wait_for_stop_or_ponderhit() {
Signals.stopOnPonderhit = true;
Thread& main = threads[0];
lock_grab(&main.sleepLock);
while (!Signals.stop)
cond_wait(&main.sleepCond, &main.sleepLock);
lock_release(&main.sleepLock);
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,34 +17,20 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(THREAD_H_INCLUDED)
#define THREAD_H_INCLUDED
////
//// Includes
////
#include <cstring>
#include "lock.h"
#include "material.h"
#include "movepick.h"
#include "pawns.h"
#include "position.h"
#include "search.h"
////
//// Constants and variables
////
const int MAX_THREADS = 8;
const int ACTIVE_SPLIT_POINTS_MAX = 8;
////
//// Types
////
const int MAX_THREADS = 32;
const int MAX_ACTIVE_SPLIT_POINTS = 8;
struct SplitPoint {
@@ -52,44 +38,105 @@ struct SplitPoint {
SplitPoint* parent;
const Position* pos;
Depth depth;
bool pvNode, mateThreat;
Value beta;
int nodeType;
int ply;
SearchStack sstack[MAX_THREADS][PLY_MAX_PLUS_2];
int master;
Move threatMove;
// Const pointers to shared data
MovePicker* mp;
SearchStack* parentSstack;
Search::Stack* ss;
// Shared data
Lock lock;
volatile int64_t nodes;
volatile Value alpha;
volatile Value bestValue;
volatile int moveCount;
volatile bool stopRequest;
volatile int slaves[MAX_THREADS];
volatile bool is_betaCutoff;
volatile bool is_slave[MAX_THREADS];
};
// ThreadState type is used to represent thread's current state
enum ThreadState
{
THREAD_SEARCHING, // thread is performing work
THREAD_AVAILABLE, // thread is polling for work
THREAD_SLEEPING, // we are not thinking, so thread is sleeping
THREAD_BOOKED, // other thread (master) has booked us as a slave
THREAD_WORKISWAITING, // master has ordered us to start
THREAD_TERMINATED // we are quitting and thread is terminated
};
/// Thread struct keeps together all the thread related stuff like locks, state
/// and especially split points. We also use per-thread pawn and material hash
/// tables so that once we get a pointer to an entry its life time is unlimited
/// and we don't have to care about someone changing the entry under our feet.
struct Thread {
void wake_up();
bool cutoff_occurred() const;
bool is_available_to(int master) const;
void idle_loop(SplitPoint* sp);
void main_loop();
void timer_loop();
SplitPoint splitPoints[MAX_ACTIVE_SPLIT_POINTS];
MaterialInfoTable materialTable;
PawnInfoTable pawnTable;
int threadID;
int maxPly;
Lock sleepLock;
WaitCondition sleepCond;
SplitPoint* volatile splitPoint;
volatile int activeSplitPoints;
uint64_t nodes;
uint64_t betaCutOffs[2];
volatile ThreadState state;
unsigned char pad[64]; // set some distance among local data for each thread
volatile bool is_searching;
volatile bool do_sleep;
volatile bool do_terminate;
#if defined(_MSC_VER)
HANDLE handle;
#else
pthread_t handle;
#endif
};
/// ThreadsManager class handles all the threads related stuff like init, starting,
/// parking and, the most important, launching a slave thread at a split point.
/// All the access to shared thread data is done through this class.
class ThreadsManager {
/* As long as the single ThreadsManager object is defined as a global we don't
need to explicitly initialize to zero its data members because variables with
static storage duration are automatically set to zero before enter main()
*/
public:
Thread& operator[](int threadID) { return threads[threadID]; }
void init();
void exit();
bool use_sleeping_threads() const { return useSleepingThreads; }
int min_split_depth() const { return minimumSplitDepth; }
int size() const { return activeThreads; }
void set_size(int cnt);
void read_uci_options();
bool available_slave_exists(int master) const;
bool split_point_finished(SplitPoint* sp) const;
void set_timer(int msec);
void wait_for_stop_or_ponderhit();
void stop_thinking();
void start_thinking(const Position& pos, const Search::LimitsType& limits,
const std::vector<Move>& searchMoves, bool asyncMode);
template <bool Fake>
Value split(Position& pos, Search::Stack* ss, Value alpha, Value beta, Value bestValue,
Depth depth, Move threatMove, int moveCount, MovePicker* mp, int nodeType);
private:
friend struct Thread;
Thread threads[MAX_THREADS + 1]; // Last one is used as a timer
Lock threadsLock;
Depth minimumSplitDepth;
int maxThreadsPerSplitPoint;
int activeThreads;
bool useSleepingThreads;
WaitCondition sleepCond;
};
extern ThreadsManager Threads;
#endif // !defined(THREAD_H_INCLUDED)

162
src/timeman.cpp Normal file
View File

@@ -0,0 +1,162 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cmath>
#include <algorithm>
#include "misc.h"
#include "search.h"
#include "timeman.h"
#include "ucioption.h"
namespace {
/// Constants
const int MoveHorizon = 50; // Plan time management at most this many moves ahead
const float MaxRatio = 3.0f; // When in trouble, we can step over reserved time with this ratio
const float StealRatio = 0.33f; // However we must not steal time from remaining moves over this ratio
// MoveImportance[] is based on naive statistical analysis of "how many games are still undecided
// after n half-moves". Game is considered "undecided" as long as neither side has >275cp advantage.
// Data was extracted from CCRL game database with some simple filtering criteria.
const int MoveImportance[512] = {
7780, 7780, 7780, 7780, 7780, 7780, 7780, 7780, 7780, 7780, 7780, 7780, 7780, 7780, 7780, 7780,
7780, 7780, 7780, 7780, 7778, 7778, 7776, 7776, 7776, 7773, 7770, 7768, 7766, 7763, 7757, 7751,
7743, 7735, 7724, 7713, 7696, 7689, 7670, 7656, 7627, 7605, 7571, 7549, 7522, 7493, 7462, 7425,
7385, 7350, 7308, 7272, 7230, 7180, 7139, 7094, 7055, 7010, 6959, 6902, 6841, 6778, 6705, 6651,
6569, 6508, 6435, 6378, 6323, 6253, 6152, 6085, 5995, 5931, 5859, 5794, 5717, 5646, 5544, 5462,
5364, 5282, 5172, 5078, 4988, 4901, 4831, 4764, 4688, 4609, 4536, 4443, 4365, 4293, 4225, 4155,
4085, 4005, 3927, 3844, 3765, 3693, 3634, 3560, 3479, 3404, 3331, 3268, 3207, 3146, 3077, 3011,
2947, 2894, 2828, 2776, 2727, 2676, 2626, 2589, 2538, 2490, 2442, 2394, 2345, 2302, 2243, 2192,
2156, 2115, 2078, 2043, 2004, 1967, 1922, 1893, 1845, 1809, 1772, 1736, 1702, 1674, 1640, 1605,
1566, 1536, 1509, 1479, 1452, 1423, 1388, 1362, 1332, 1304, 1289, 1266, 1250, 1228, 1206, 1180,
1160, 1134, 1118, 1100, 1080, 1068, 1051, 1034, 1012, 1001, 980, 960, 945, 934, 916, 900, 888,
878, 865, 852, 828, 807, 787, 770, 753, 744, 731, 722, 706, 700, 683, 676, 671, 664, 652, 641,
634, 627, 613, 604, 591, 582, 568, 560, 552, 540, 534, 529, 519, 509, 495, 484, 474, 467, 460,
450, 438, 427, 419, 410, 406, 399, 394, 387, 382, 377, 372, 366, 359, 353, 348, 343, 337, 333,
328, 321, 315, 309, 303, 298, 293, 287, 284, 281, 277, 273, 265, 261, 255, 251, 247, 241, 240,
235, 229, 218, 217, 213, 212, 208, 206, 197, 193, 191, 189, 185, 184, 180, 177, 172, 170, 170,
170, 166, 163, 159, 158, 156, 155, 151, 146, 141, 138, 136, 132, 130, 128, 125, 123, 122, 118,
118, 118, 117, 115, 114, 108, 107, 105, 105, 105, 102, 97, 97, 95, 94, 93, 91, 88, 86, 83, 80,
80, 79, 79, 79, 78, 76, 75, 72, 72, 71, 70, 68, 65, 63, 61, 61, 59, 59, 59, 58, 56, 55, 54, 54,
52, 49, 48, 48, 48, 48, 45, 45, 45, 44, 43, 41, 41, 41, 41, 40, 40, 38, 37, 36, 34, 34, 34, 33,
31, 29, 29, 29, 28, 28, 28, 28, 28, 28, 28, 27, 27, 27, 27, 27, 24, 24, 23, 23, 22, 21, 20, 20,
19, 19, 19, 19, 19, 18, 18, 18, 18, 17, 17, 17, 17, 17, 16, 16, 15, 15, 14, 14, 14, 12, 12, 11,
9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 2, 2, 2,
2, 1, 1, 1, 1, 1, 1, 1 };
int move_importance(int ply) { return MoveImportance[std::min(ply, 511)]; }
/// Function Prototypes
enum TimeType { OptimumTime, MaxTime };
template<TimeType>
int remaining(int myTime, int movesToGo, int fullMoveNumber);
}
void TimeManager::pv_instability(int curChanges, int prevChanges) {
unstablePVExtraTime = curChanges * (optimumSearchTime / 2)
+ prevChanges * (optimumSearchTime / 3);
}
void TimeManager::init(const Search::LimitsType& limits, int currentPly)
{
/* We support four different kind of time controls:
increment == 0 && movesToGo == 0 means: x basetime [sudden death!]
increment == 0 && movesToGo != 0 means: x moves in y minutes
increment > 0 && movesToGo == 0 means: x basetime + z increment
increment > 0 && movesToGo != 0 means: x moves in y minutes + z increment
Time management is adjusted by following UCI parameters:
emergencyMoveHorizon: Be prepared to always play at least this many moves
emergencyBaseTime : Always attempt to keep at least this much time (in ms) at clock
emergencyMoveTime : Plus attempt to keep at least this much time for each remaining emergency move
minThinkingTime : No matter what, use at least this much thinking before doing the move
*/
int hypMTG, hypMyTime, t1, t2;
// Read uci parameters
int emergencyMoveHorizon = Options["Emergency Move Horizon"];
int emergencyBaseTime = Options["Emergency Base Time"];
int emergencyMoveTime = Options["Emergency Move Time"];
int minThinkingTime = Options["Minimum Thinking Time"];
// Initialize to maximum values but unstablePVExtraTime that is reset
unstablePVExtraTime = 0;
optimumSearchTime = maximumSearchTime = limits.time;
// We calculate optimum time usage for different hypothetic "moves to go"-values and choose the
// minimum of calculated search time values. Usually the greatest hypMTG gives the minimum values.
for (hypMTG = 1; hypMTG <= (limits.movesToGo ? std::min(limits.movesToGo, MoveHorizon) : MoveHorizon); hypMTG++)
{
// Calculate thinking time for hypothetic "moves to go"-value
hypMyTime = limits.time
+ limits.increment * (hypMTG - 1)
- emergencyBaseTime
- emergencyMoveTime * std::min(hypMTG, emergencyMoveHorizon);
hypMyTime = std::max(hypMyTime, 0);
t1 = minThinkingTime + remaining<OptimumTime>(hypMyTime, hypMTG, currentPly);
t2 = minThinkingTime + remaining<MaxTime>(hypMyTime, hypMTG, currentPly);
optimumSearchTime = std::min(optimumSearchTime, t1);
maximumSearchTime = std::min(maximumSearchTime, t2);
}
if (Options["Ponder"])
optimumSearchTime += optimumSearchTime / 4;
// Make sure that maxSearchTime is not over absoluteMaxSearchTime
optimumSearchTime = std::min(optimumSearchTime, maximumSearchTime);
}
namespace {
template<TimeType T>
int remaining(int myTime, int movesToGo, int currentPly)
{
const float TMaxRatio = (T == OptimumTime ? 1 : MaxRatio);
const float TStealRatio = (T == OptimumTime ? 0 : StealRatio);
int thisMoveImportance = move_importance(currentPly);
int otherMovesImportance = 0;
for (int i = 1; i < movesToGo; i++)
otherMovesImportance += move_importance(currentPly + 2 * i);
float ratio1 = (TMaxRatio * thisMoveImportance) / float(TMaxRatio * thisMoveImportance + otherMovesImportance);
float ratio2 = (thisMoveImportance + TStealRatio * otherMovesImportance) / float(thisMoveImportance + otherMovesImportance);
return int(floor(myTime * std::min(ratio1, ratio2)));
}
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,23 +17,23 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(TIMEMAN_H_INCLUDED)
#define TIMEMAN_H_INCLUDED
#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&);
/// The TimeManager class computes the optimal time to think depending on the
/// maximum available time, the move game number and other parameters.
class TimeManager {
public:
static void initialize();
static void free_resources();
static void exit_with_failure();
void init(const Search::LimitsType& limits, int currentPly);
void pv_instability(int curChanges, int prevChanges);
int available_time() const { return optimumSearchTime + unstablePVExtraTime; }
int maximum_time() const { return maximumSearchTime; }
private:
int optimumSearchTime;
int maximumSearchTime;
int unstablePVExtraTime;
};
#endif // !defined(APPLICATION_H_INCLUDED)
#endif // !defined(TIMEMAN_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,30 +17,17 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// Includes
////
#include <cassert>
#include <cmath>
#include <cstring>
#include <iostream>
#include "movegen.h"
#include "tt.h"
// The main transposition table
TranspositionTable TT;
////
//// Functions
////
TranspositionTable TT; // Our global transposition table
TranspositionTable::TranspositionTable() {
size = overwrites = 0;
entries = 0;
generation = 0;
size = generation = 0;
entries = NULL;
}
TranspositionTable::~TranspositionTable() {
@@ -49,38 +36,39 @@ TranspositionTable::~TranspositionTable() {
}
/// TranspositionTable::set_size sets the size of the transposition table,
/// TranspositionTable::set_size() sets the size of the transposition table,
/// measured in megabytes.
void TranspositionTable::set_size(size_t mbSize) {
size_t newSize = 1024;
// We store a cluster of ClusterSize number of TTEntry for each position
// and newSize is the maximum number of storable positions.
while ((2 * newSize) * sizeof(TTCluster) <= (mbSize << 20))
// Transposition table consists of clusters and each cluster consists
// of ClusterSize number of TTEntries. Each non-empty entry contains
// information of exactly one position and newSize is the number of
// clusters we are going to allocate.
while (2ULL * newSize * sizeof(TTCluster) <= (mbSize << 20))
newSize *= 2;
if (newSize != size)
if (newSize == size)
return;
size = newSize;
delete [] entries;
entries = new (std::nothrow) TTCluster[size];
if (!entries)
{
size = newSize;
delete [] entries;
entries = new TTCluster[size];
if (!entries)
{
std::cerr << "Failed to allocate " << mbSize
<< " MB for transposition table." << std::endl;
Application::exit_with_failure();
}
clear();
std::cerr << "Failed to allocate " << mbSize
<< "MB for transposition table." << std::endl;
exit(EXIT_FAILURE);
}
clear();
}
/// TranspositionTable::clear overwrites the entire transposition table
/// TranspositionTable::clear() overwrites the entire transposition table
/// with zeroes. It is called whenever the table is resized, or when the
/// user asks the program to clear the table (from the UCI interface).
/// Perhaps we should also clear it when the "ucinewgame" command is recieved?
void TranspositionTable::clear() {
@@ -88,28 +76,27 @@ void TranspositionTable::clear() {
}
/// TranspositionTable::store writes a new entry containing a position,
/// a value, a value type, a search depth, and a best move to the
/// transposition table. Transposition table is organized in clusters of
/// four TTEntry objects, and when a new entry is written, it replaces
/// the least valuable of the four entries in a cluster. A TTEntry t1 is
/// considered to be more valuable than a TTEntry t2 if t1 is from the
/// current search and t2 is from a previous search, or if the depth of t1
/// is bigger than the depth of t2. A TTEntry of type VALUE_TYPE_EVAL
/// never replaces another entry for the same position.
/// TranspositionTable::store() writes a new entry containing position key and
/// valuable information of current position. The lowest order bits of position
/// key are used to decide on which cluster the position will be placed.
/// When a new entry is written and there are no empty entries available in cluster,
/// it replaces the least valuable of entries. A TTEntry t1 is considered to be
/// more valuable than a TTEntry t2 if t1 is from the current search and t2 is from
/// a previous search, or if the depth of t1 is bigger than the depth of t2.
void TranspositionTable::store(const Key posKey, Value v, ValueType t, Depth d, Move m, Value statV, Value kingD) {
int c1, c2, c3;
TTEntry *tte, *replace;
uint32_t posKey32 = posKey >> 32; // Use the high 32 bits as key
uint32_t posKey32 = posKey >> 32; // Use the high 32 bits as key inside the cluster
tte = replace = first_entry(posKey);
for (int i = 0; i < ClusterSize; i++, tte++)
{
if (!tte->key() || tte->key() == posKey32) // empty or overwrite old
if (!tte->key() || tte->key() == posKey32) // Empty or overwrite old
{
// Preserve any exsisting ttMove
// Preserve any existing ttMove
if (m == MOVE_NONE)
m = tte->move();
@@ -117,26 +104,23 @@ void TranspositionTable::store(const Key posKey, Value v, ValueType t, Depth d,
return;
}
if (i == 0) // replace would be a no-op in this common case
continue;
// Implement replace strategy
c1 = (replace->generation() == generation ? 2 : 0);
c2 = (tte->generation() == generation ? -2 : 0);
c2 = (tte->generation() == generation || tte->type() == VALUE_TYPE_EXACT ? -2 : 0);
c3 = (tte->depth() < replace->depth() ? 1 : 0);
if (c1 + c2 + c3 > 0)
replace = tte;
}
replace->save(posKey32, v, t, d, m, generation, statV, kingD);
overwrites++;
}
/// TranspositionTable::retrieve looks up the current position in the
/// transposition table. Returns a pointer to the TTEntry or NULL
/// if position is not found.
/// TranspositionTable::probe() looks up the current position in the
/// transposition table. Returns a pointer to the TTEntry or NULL if
/// position is not found.
TTEntry* TranspositionTable::retrieve(const Key posKey) const {
TTEntry* TranspositionTable::probe(const Key posKey) const {
uint32_t posKey32 = posKey >> 32;
TTEntry* tte = first_entry(posKey);
@@ -155,72 +139,5 @@ TTEntry* TranspositionTable::retrieve(const Key posKey) const {
/// entries from the current search.
void TranspositionTable::new_search() {
generation++;
overwrites = 0;
}
/// TranspositionTable::insert_pv() is called at the end of a search
/// iteration, and inserts the PV back into the PV. This makes sure
/// the old PV moves are searched first, even if the old TT entries
/// have been overwritten.
void TranspositionTable::insert_pv(const Position& pos, Move pv[]) {
StateInfo st;
Position p(pos, pos.thread());
for (int i = 0; pv[i] != MOVE_NONE; i++)
{
TTEntry *tte = retrieve(p.get_key());
if (!tte || tte->move() != pv[i])
store(p.get_key(), VALUE_NONE, VALUE_TYPE_NONE, Depth(-127*OnePly), pv[i], VALUE_NONE, VALUE_NONE);
p.do_move(pv[i], st);
}
}
/// TranspositionTable::extract_pv() extends a PV by adding moves from the
/// transposition table at the end. This should ensure that the PV is almost
/// always at least two plies long, which is important, because otherwise we
/// will often get single-move PVs when the search stops while failing high,
/// and a single-move PV means that we don't have a ponder move.
void TranspositionTable::extract_pv(const Position& pos, Move bestMove, Move pv[], const int PLY_MAX) {
const TTEntry* tte;
StateInfo st;
Position p(pos, pos.thread());
int ply = 0;
assert(bestMove != MOVE_NONE);
pv[ply] = bestMove;
p.do_move(pv[ply++], st);
// Extract moves from TT when possible. We try hard to always
// get a ponder move, that's the reason of ply < 2 conditions.
while ( (tte = retrieve(p.get_key())) != NULL
&& tte->move() != MOVE_NONE
&& (tte->type() == VALUE_TYPE_EXACT || ply < 2)
&& move_is_legal(p, tte->move())
&& (!p.is_draw() || ply < 2)
&& ply < PLY_MAX)
{
pv[ply] = tte->move();
p.do_move(pv[ply++], st);
}
pv[ply] = MOVE_NONE;
}
/// TranspositionTable::full() returns the permill of all transposition table
/// entries which have received at least one overwrite during the current search.
/// It is used to display the "info hashfull ..." information in UCI.
int TranspositionTable::full() const {
double N = double(size) * ClusterSize;
return int(1000 * (1 - exp(overwrites * log(1.0 - 1.0/N))));
}

152
src/tt.h
View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,125 +17,157 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(TT_H_INCLUDED)
#define TT_H_INCLUDED
////
//// Includes
////
#include <iostream>
#include "depth.h"
#include "position.h"
#include "value.h"
#include "misc.h"
#include "types.h"
////
//// Types
////
/// The TTEntry class is the class of transposition table entries
/// The TTEntry is the class of transposition table entries
///
/// A TTEntry needs 96 bits to be stored
/// A TTEntry needs 128 bits to be stored
///
/// bit 0-31: key
/// bit 32-63: data
/// bit 64-79: value
/// bit 80-95: depth
/// bit 96-111: static value
/// bit 112-127: margin of static value
///
/// the 32 bits of the data field are so defined
///
/// bit 0-16: move
/// bit 17-19: not used
/// bit 20-22: value type
/// bit 0-15: move
/// bit 16-20: not used
/// bit 21-22: value type
/// bit 23-31: generation
class TTEntry {
public:
void save(uint32_t k, Value v, ValueType t, Depth d, Move m, int g, Value statV, Value kd) {
void save(uint32_t k, Value v, ValueType t, Depth d, Move m, int g, Value statV, Value statM) {
key32 = k;
data = (m & 0x1FFFF) | (t << 20) | (g << 23);
value16 = int16_t(v);
depth16 = int16_t(d);
staticValue = int16_t(statV);
kingDanger = int16_t(kd);
key32 = (uint32_t)k;
move16 = (uint16_t)m;
valueType = (uint8_t)t;
generation8 = (uint8_t)g;
value16 = (int16_t)v;
depth16 = (int16_t)d;
staticValue = (int16_t)statV;
staticMargin = (int16_t)statM;
}
void set_generation(int g) { generation8 = (uint8_t)g; }
uint32_t key() const { return key32; }
Depth depth() const { return Depth(depth16); }
Move move() const { return Move(data & 0x1FFFF); }
Value value() const { return Value(value16); }
ValueType type() const { return ValueType((data >> 20) & 7); }
int generation() const { return data >> 23; }
Value static_value() const { return Value(staticValue); }
Value king_danger() const { return Value(kingDanger); }
uint32_t key() const { return key32; }
Depth depth() const { return (Depth)depth16; }
Move move() const { return (Move)move16; }
Value value() const { return (Value)value16; }
ValueType type() const { return (ValueType)valueType; }
int generation() const { return (int)generation8; }
Value static_value() const { return (Value)staticValue; }
Value static_value_margin() const { return (Value)staticMargin; }
private:
uint32_t key32;
uint32_t data;
int16_t value16;
int16_t depth16;
int16_t staticValue;
int16_t kingDanger;
uint16_t move16;
uint8_t valueType, generation8;
int16_t value16, depth16, staticValue, staticMargin;
};
/// This is the number of TTEntry slots for each position
/// This is the number of TTEntry slots for each cluster
const int ClusterSize = 4;
/// Each group of ClusterSize number of TTEntry form a TTCluster
/// that is indexed by a single position key. TTCluster size must
/// be not bigger then a cache line size, in case it is less then
/// it should be padded to guarantee always aligned accesses.
/// TTCluster consists of ClusterSize number of TTEntries. Size of TTCluster
/// must not be bigger than a cache line size. In case it is less, it should
/// be padded to guarantee always aligned accesses.
struct TTCluster {
TTEntry data[ClusterSize];
};
/// The transposition table class. This is basically just a huge array
/// containing TTEntry objects, and a few methods for writing new entries
/// and reading new ones.
/// The transposition table class. This is basically just a huge array containing
/// TTCluster objects, and a few methods for writing and reading entries.
class TranspositionTable {
TranspositionTable(const TranspositionTable&);
TranspositionTable& operator=(const TranspositionTable&);
public:
TranspositionTable();
~TranspositionTable();
void set_size(size_t mbSize);
void clear();
void store(const Key posKey, Value v, ValueType type, Depth d, Move m, Value statV, Value kingD);
TTEntry* retrieve(const Key posKey) const;
TTEntry* probe(const Key posKey) const;
void new_search();
void insert_pv(const Position& pos, Move pv[]);
void extract_pv(const Position& pos, Move bestMove, Move pv[], const int PLY_MAX);
int full() const;
TTEntry* first_entry(const Key posKey) const;
void refresh(const TTEntry* tte) const;
private:
// Be sure 'overwrites' is at least one cache line away
// from read only variables.
unsigned char pad_before[64 - sizeof(unsigned)];
unsigned overwrites; // heavy SMP read/write access here
unsigned char pad_after[64];
size_t size;
TTCluster* entries;
uint8_t generation;
uint8_t generation; // Size must be not bigger then TTEntry::generation8
};
extern TranspositionTable TT;
/// TranspositionTable::first_entry returns a pointer to the first
/// entry of a cluster given a position. The low 32 bits of the key
/// are used to get the index in the table.
/// TranspositionTable::first_entry() returns a pointer to the first entry of
/// a cluster given a position. The lowest order bits of the key are used to
/// get the index of the cluster.
inline TTEntry* TranspositionTable::first_entry(const Key posKey) const {
return entries[uint32_t(posKey) & (size - 1)].data;
return entries[((uint32_t)posKey) & (size - 1)].data;
}
/// TranspositionTable::refresh() updates the 'generation' value of the TTEntry
/// to avoid aging. Normally called after a TT hit.
inline void TranspositionTable::refresh(const TTEntry* tte) const {
const_cast<TTEntry*>(tte)->set_generation(generation);
}
/// A simple fixed size hash table used to store pawns and material
/// configurations. It is basically just an array of Entry objects.
/// Without cluster concept or overwrite policy.
template<class Entry, int HashSize>
struct SimpleHash {
typedef SimpleHash<Entry, HashSize> Base;
void init() {
if (entries)
return;
entries = new (std::nothrow) Entry[HashSize];
if (!entries)
{
std::cerr << "Failed to allocate " << HashSize * sizeof(Entry)
<< " bytes for hash table." << std::endl;
exit(EXIT_FAILURE);
}
memset(entries, 0, HashSize * sizeof(Entry));
}
virtual ~SimpleHash() { delete [] entries; }
Entry* probe(Key key) const { return entries + ((uint32_t)key & (HashSize - 1)); }
void prefetch(Key key) const { ::prefetch((char*)probe(key)); }
protected:
Entry* entries;
};
#endif // !defined(TT_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,96 +17,496 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(TYPES_H_INCLUDED)
#define TYPES_H_INCLUDED
#if !defined(_MSC_VER)
/// For Linux and OSX configuration is done automatically using Makefile. To get
/// started type 'make help'.
///
/// For Windows, part of the configuration is detected automatically, but some
/// switches need to be set manually:
///
/// -DNDEBUG | Disable debugging mode. Use always.
///
/// -DNO_PREFETCH | Disable use of prefetch asm-instruction. A must if you want
/// | the executable to run on some very old machines.
///
/// -DUSE_POPCNT | Add runtime support for use of popcnt asm-instruction. Works
/// | only in 64-bit mode. For compiling requires hardware with
/// | popcnt support.
///
/// -DOLD_LOCKS | Under Windows are used the fast Slim Reader/Writer (SRW)
/// | Locks and Condition Variables: these are not supported by
/// | Windows XP and older, to compile for those platforms you
/// | should enable OLD_LOCKS.
#include <inttypes.h>
#include <climits>
#include <cstdlib>
#else
#if defined(_MSC_VER)
typedef __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef __int16 int16;
// Disable some silly and noisy warning from MSVC compiler
#pragma warning(disable: 4127) // Conditional expression is constant
#pragma warning(disable: 4146) // Unary minus operator applied to unsigned type
#pragma warning(disable: 4800) // Forcing value to bool 'true' or 'false'
// MSVC does not support <inttypes.h>
typedef signed __int8 int8_t;
typedef unsigned __int8 uint8_t;
typedef signed __int16 int16_t;
typedef unsigned __int16 uint16_t;
typedef __int32 int32_t;
typedef signed __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef signed __int64 int64_t;
typedef unsigned __int64 uint64_t;
typedef __int16 int16_t;
typedef __int64 int64_t;
#else
# include <inttypes.h>
#endif
#endif // !defined(_MSC_VER)
#if defined(_WIN64)
# include <intrin.h> // MSVC popcnt and bsfq instrinsics
# define IS_64BIT
# define USE_BSFQ
#endif
#if defined(USE_POPCNT) && defined(_MSC_VER) && defined(__INTEL_COMPILER)
# include <nmmintrin.h> // Intel header for _mm_popcnt_u64() intrinsic
#endif
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
# define CACHE_LINE_ALIGNMENT __declspec(align(64))
#else
# define CACHE_LINE_ALIGNMENT __attribute__ ((aligned(64)))
#endif
#if defined(_MSC_VER)
# define FORCE_INLINE __forceinline
#elif defined(__GNUC__)
# define FORCE_INLINE inline __attribute__((always_inline))
#else
# define FORCE_INLINE inline
#endif
#if defined(USE_POPCNT)
const bool HasPopCnt = true;
#else
const bool HasPopCnt = false;
#endif
#if defined(IS_64BIT)
const bool Is64Bit = true;
#else
const bool Is64Bit = false;
#endif
// Hash keys
typedef uint64_t Key;
// Bitboard type
typedef uint64_t Bitboard;
const int MAX_MOVES = 256;
const int MAX_PLY = 100;
const int MAX_PLY_PLUS_2 = MAX_PLY + 2;
////
//// Configuration
////
const Bitboard FileABB = 0x0101010101010101ULL;
const Bitboard FileBBB = FileABB << 1;
const Bitboard FileCBB = FileABB << 2;
const Bitboard FileDBB = FileABB << 3;
const Bitboard FileEBB = FileABB << 4;
const Bitboard FileFBB = FileABB << 5;
const Bitboard FileGBB = FileABB << 6;
const Bitboard FileHBB = FileABB << 7;
//// For Linux and OSX configuration is done automatically using Makefile.
//// To get started type "make help".
////
//// For windows part of the configuration is detected automatically, but
//// some switches need to be set manually:
////
//// -DNDEBUG | Disable debugging mode. Use always.
////
//// -DNO_PREFETCH | Disable use of prefetch asm-instruction. A must if you want the
//// | executable to run on some very old machines.
////
//// -DUSE_POPCNT | Add runtime support for use of popcnt asm-instruction.
//// | Works only in 64-bit mode. For compiling requires hardware
//// | with popcnt support. Around 4% speed-up.
const Bitboard Rank1BB = 0xFF;
const Bitboard Rank2BB = Rank1BB << (8 * 1);
const Bitboard Rank3BB = Rank1BB << (8 * 2);
const Bitboard Rank4BB = Rank1BB << (8 * 3);
const Bitboard Rank5BB = Rank1BB << (8 * 4);
const Bitboard Rank6BB = Rank1BB << (8 * 5);
const Bitboard Rank7BB = Rank1BB << (8 * 6);
const Bitboard Rank8BB = Rank1BB << (8 * 7);
// Automatic detection for 64-bit under Windows
#if defined(_WIN64)
#define IS_64BIT
#endif
// Automatic detection for use of bsfq asm-instruction under Windows.
// Works only in 64-bit mode. Does not work with MSVC.
#if defined(_WIN64) && defined(__INTEL_COMPILER)
#define USE_BSFQ
#endif
/// A move needs 16 bits to be stored
///
/// bit 0- 5: destination square (from 0 to 63)
/// bit 6-11: origin square (from 0 to 63)
/// bit 12-13: promotion piece type - 2 (from KNIGHT-2 to QUEEN-2)
/// bit 14-15: special move flag: promotion (1), en passant (2), castle (3)
///
/// Special cases are MOVE_NONE and MOVE_NULL. We can sneak these in because in
/// any normal move destination square is always different from origin square
/// while MOVE_NONE and MOVE_NULL have the same origin and destination square.
// Cache line alignment specification
#if defined(_MSC_VER) || defined(__INTEL_COMPILER)
#define CACHE_LINE_ALIGNMENT __declspec(align(64))
#else
#define CACHE_LINE_ALIGNMENT __attribute__ ((aligned(64)))
#endif
enum Move {
MOVE_NONE = 0,
MOVE_NULL = 65
};
// Define a __cpuid() function for gcc compilers, for Intel and MSVC
// is already available as an intrinsic.
#if defined(_MSC_VER)
#include <intrin.h>
#elif defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
inline void __cpuid(int CPUInfo[4], int InfoType)
{
int* eax = CPUInfo + 0;
int* ebx = CPUInfo + 1;
int* ecx = CPUInfo + 2;
int* edx = CPUInfo + 3;
struct MoveStack {
Move move;
int score;
};
*eax = InfoType;
*ecx = 0;
__asm__("cpuid" : "=a" (*eax), "=b" (*ebx), "=c" (*ecx), "=d" (*edx)
: "0" (*eax), "2" (*ecx));
inline bool operator<(const MoveStack& f, const MoveStack& s) {
return f.score < s.score;
}
enum CastleRight {
CASTLES_NONE = 0,
WHITE_OO = 1,
BLACK_OO = 2,
WHITE_OOO = 4,
BLACK_OOO = 8,
ALL_CASTLES = 15
};
enum ScaleFactor {
SCALE_FACTOR_DRAW = 0,
SCALE_FACTOR_NORMAL = 64,
SCALE_FACTOR_MAX = 128,
SCALE_FACTOR_NONE = 255
};
enum ValueType {
VALUE_TYPE_NONE = 0,
VALUE_TYPE_UPPER = 1,
VALUE_TYPE_LOWER = 2,
VALUE_TYPE_EXACT = VALUE_TYPE_UPPER | VALUE_TYPE_LOWER
};
enum Value {
VALUE_ZERO = 0,
VALUE_DRAW = 0,
VALUE_KNOWN_WIN = 15000,
VALUE_MATE = 30000,
VALUE_INFINITE = 30001,
VALUE_NONE = 30002,
VALUE_MATE_IN_MAX_PLY = VALUE_MATE - MAX_PLY,
VALUE_MATED_IN_MAX_PLY = -VALUE_MATE + MAX_PLY,
VALUE_ENSURE_INTEGER_SIZE_P = INT_MAX,
VALUE_ENSURE_INTEGER_SIZE_N = INT_MIN
};
enum PieceType {
NO_PIECE_TYPE = 0,
PAWN = 1, KNIGHT = 2, BISHOP = 3, ROOK = 4, QUEEN = 5, KING = 6
};
enum Piece {
NO_PIECE = 16, // color_of(NO_PIECE) == NO_COLOR
W_PAWN = 1, W_KNIGHT = 2, W_BISHOP = 3, W_ROOK = 4, W_QUEEN = 5, W_KING = 6,
B_PAWN = 9, B_KNIGHT = 10, B_BISHOP = 11, B_ROOK = 12, B_QUEEN = 13, B_KING = 14
};
enum Color {
WHITE, BLACK, NO_COLOR
};
enum Depth {
ONE_PLY = 2,
DEPTH_ZERO = 0 * ONE_PLY,
DEPTH_QS_CHECKS = -1 * ONE_PLY,
DEPTH_QS_NO_CHECKS = -2 * ONE_PLY,
DEPTH_QS_RECAPTURES = -4 * ONE_PLY,
DEPTH_NONE = -127 * ONE_PLY
};
enum Square {
SQ_A1, SQ_B1, SQ_C1, SQ_D1, SQ_E1, SQ_F1, SQ_G1, SQ_H1,
SQ_A2, SQ_B2, SQ_C2, SQ_D2, SQ_E2, SQ_F2, SQ_G2, SQ_H2,
SQ_A3, SQ_B3, SQ_C3, SQ_D3, SQ_E3, SQ_F3, SQ_G3, SQ_H3,
SQ_A4, SQ_B4, SQ_C4, SQ_D4, SQ_E4, SQ_F4, SQ_G4, SQ_H4,
SQ_A5, SQ_B5, SQ_C5, SQ_D5, SQ_E5, SQ_F5, SQ_G5, SQ_H5,
SQ_A6, SQ_B6, SQ_C6, SQ_D6, SQ_E6, SQ_F6, SQ_G6, SQ_H6,
SQ_A7, SQ_B7, SQ_C7, SQ_D7, SQ_E7, SQ_F7, SQ_G7, SQ_H7,
SQ_A8, SQ_B8, SQ_C8, SQ_D8, SQ_E8, SQ_F8, SQ_G8, SQ_H8,
SQ_NONE,
DELTA_N = 8,
DELTA_E = 1,
DELTA_S = -8,
DELTA_W = -1,
DELTA_NN = DELTA_N + DELTA_N,
DELTA_NE = DELTA_N + DELTA_E,
DELTA_SE = DELTA_S + DELTA_E,
DELTA_SS = DELTA_S + DELTA_S,
DELTA_SW = DELTA_S + DELTA_W,
DELTA_NW = DELTA_N + DELTA_W
};
enum File {
FILE_A, FILE_B, FILE_C, FILE_D, FILE_E, FILE_F, FILE_G, FILE_H
};
enum Rank {
RANK_1, RANK_2, RANK_3, RANK_4, RANK_5, RANK_6, RANK_7, RANK_8
};
/// Score enum keeps a midgame and an endgame value in a single integer (enum),
/// first LSB 16 bits are used to store endgame value, while upper bits are used
/// for midgame value. Compiler is free to choose the enum type as long as can
/// keep its data, so ensure Score to be an integer type.
enum Score {
SCORE_ZERO = 0,
SCORE_ENSURE_INTEGER_SIZE_P = INT_MAX,
SCORE_ENSURE_INTEGER_SIZE_N = INT_MIN
};
inline Score make_score(int mg, int eg) { return Score((mg << 16) + eg); }
/// Extracting the signed lower and upper 16 bits it not so trivial because
/// according to the standard a simple cast to short is implementation defined
/// and so is a right shift of a signed integer.
inline Value mg_value(Score s) { return Value(((s + 32768) & ~0xffff) / 0x10000); }
/// On Intel 64 bit we have a small speed regression with the standard conforming
/// version, so use a faster code in this case that, although not 100% standard
/// compliant it seems to work for Intel and MSVC.
#if defined(IS_64BIT) && (!defined(__GNUC__) || defined(__INTEL_COMPILER))
inline Value eg_value(Score s) { return Value(int16_t(s & 0xffff)); }
#else
inline void __cpuid(int CPUInfo[4], int)
{
CPUInfo[0] = CPUInfo[1] = CPUInfo[2] = CPUInfo[3] = 0;
inline Value eg_value(Score s) {
return Value((int)(unsigned(s) & 0x7fffu) - (int)(unsigned(s) & 0x8000u));
}
#endif
#define ENABLE_SAFE_OPERATORS_ON(T) \
inline T operator+(const T d1, const T d2) { return T(int(d1) + int(d2)); } \
inline T operator-(const T d1, const T d2) { return T(int(d1) - int(d2)); } \
inline T operator*(int i, const T d) { return T(i * int(d)); } \
inline T operator*(const T d, int i) { return T(int(d) * i); } \
inline T operator-(const T d) { return T(-int(d)); } \
inline T& operator+=(T& d1, const T d2) { d1 = d1 + d2; return d1; } \
inline T& operator-=(T& d1, const T d2) { d1 = d1 - d2; return d1; } \
inline T& operator*=(T& d, int i) { d = T(int(d) * i); return d; }
#define ENABLE_OPERATORS_ON(T) ENABLE_SAFE_OPERATORS_ON(T) \
inline T operator++(T& d, int) { d = T(int(d) + 1); return d; } \
inline T operator--(T& d, int) { d = T(int(d) - 1); return d; } \
inline T operator/(const T d, int i) { return T(int(d) / i); } \
inline T& operator/=(T& d, int i) { d = T(int(d) / i); return d; }
ENABLE_OPERATORS_ON(Value)
ENABLE_OPERATORS_ON(PieceType)
ENABLE_OPERATORS_ON(Piece)
ENABLE_OPERATORS_ON(Color)
ENABLE_OPERATORS_ON(Depth)
ENABLE_OPERATORS_ON(Square)
ENABLE_OPERATORS_ON(File)
ENABLE_OPERATORS_ON(Rank)
/// Added operators for adding integers to a Value
inline Value operator+(Value v, int i) { return Value(int(v) + i); }
inline Value operator-(Value v, int i) { return Value(int(v) - i); }
ENABLE_SAFE_OPERATORS_ON(Score)
/// Only declared but not defined. We don't want to multiply two scores due to
/// a very high risk of overflow. So user should explicitly convert to integer.
inline Score operator*(Score s1, Score s2);
/// Division of a Score must be handled separately for each term
inline Score operator/(Score s, int i) {
return make_score(mg_value(s) / i, eg_value(s) / i);
}
#undef ENABLE_OPERATORS_ON
#undef ENABLE_SAFE_OPERATORS_ON
const Value PawnValueMidgame = Value(0x0C6);
const Value PawnValueEndgame = Value(0x102);
const Value KnightValueMidgame = Value(0x331);
const Value KnightValueEndgame = Value(0x34E);
const Value BishopValueMidgame = Value(0x344);
const Value BishopValueEndgame = Value(0x359);
const Value RookValueMidgame = Value(0x4F6);
const Value RookValueEndgame = Value(0x4FE);
const Value QueenValueMidgame = Value(0x9D9);
const Value QueenValueEndgame = Value(0x9FE);
extern const Value PieceValueMidgame[17];
extern const Value PieceValueEndgame[17];
extern int SquareDistance[64][64];
inline Value mate_in(int ply) {
return VALUE_MATE - ply;
}
inline Value mated_in(int ply) {
return -VALUE_MATE + ply;
}
inline Piece make_piece(Color c, PieceType pt) {
return Piece((c << 3) | pt);
}
inline PieceType type_of(Piece p) {
return PieceType(p & 7);
}
inline Color color_of(Piece p) {
return Color(p >> 3);
}
inline Color flip(Color c) {
return Color(c ^ 1);
}
inline Square make_square(File f, Rank r) {
return Square((r << 3) | f);
}
inline bool square_is_ok(Square s) {
return s >= SQ_A1 && s <= SQ_H8;
}
inline File file_of(Square s) {
return File(s & 7);
}
inline Rank rank_of(Square s) {
return Rank(s >> 3);
}
inline Square flip(Square s) {
return Square(s ^ 56);
}
inline Square mirror(Square s) {
return Square(s ^ 7);
}
inline Square relative_square(Color c, Square s) {
return Square(s ^ (c * 56));
}
inline Rank relative_rank(Color c, Rank r) {
return Rank(r ^ (c * 7));
}
inline Rank relative_rank(Color c, Square s) {
return relative_rank(c, rank_of(s));
}
inline bool opposite_colors(Square s1, Square s2) {
int s = s1 ^ s2;
return ((s >> 3) ^ s) & 1;
}
inline int file_distance(Square s1, Square s2) {
return abs(file_of(s1) - file_of(s2));
}
inline int rank_distance(Square s1, Square s2) {
return abs(rank_of(s1) - rank_of(s2));
}
inline int square_distance(Square s1, Square s2) {
return SquareDistance[s1][s2];
}
inline char piece_type_to_char(PieceType pt) {
return " PNBRQK"[pt];
}
inline char file_to_char(File f) {
return char(f - FILE_A + int('a'));
}
inline char rank_to_char(Rank r) {
return char(r - RANK_1 + int('1'));
}
inline Square pawn_push(Color c) {
return c == WHITE ? DELTA_N : DELTA_S;
}
inline Square from_sq(Move m) {
return Square((m >> 6) & 0x3F);
}
inline Square to_sq(Move m) {
return Square(m & 0x3F);
}
inline bool is_special(Move m) {
return m & (3 << 14);
}
inline bool is_promotion(Move m) {
return (m & (3 << 14)) == (1 << 14);
}
inline int is_enpassant(Move m) {
return (m & (3 << 14)) == (2 << 14);
}
inline int is_castle(Move m) {
return (m & (3 << 14)) == (3 << 14);
}
inline PieceType promotion_piece_type(Move m) {
return PieceType(((m >> 12) & 3) + 2);
}
inline Move make_move(Square from, Square to) {
return Move(to | (from << 6));
}
inline Move make_promotion(Square from, Square to, PieceType pt) {
return Move(to | (from << 6) | (1 << 14) | ((pt - 2) << 12)) ;
}
inline Move make_enpassant(Square from, Square to) {
return Move(to | (from << 6) | (2 << 14));
}
inline Move make_castle(Square from, Square to) {
return Move(to | (from << 6) | (3 << 14));
}
inline bool is_ok(Move m) {
return from_sq(m) != to_sq(m); // Catches also MOVE_NULL and MOVE_NONE
}
#include <string>
inline const std::string square_to_string(Square s) {
char ch[] = { file_to_char(file_of(s)), rank_to_char(rank_of(s)), 0 };
return ch;
}
/// Our insertion sort implementation, works with pointers and iterators and is
/// guaranteed to be stable, as is needed.
template<typename T, typename K>
void sort(K firstMove, K lastMove)
{
T value;
K cur, p, d;
if (firstMove != lastMove)
for (cur = firstMove + 1; cur != lastMove; cur++)
{
p = d = cur;
value = *p--;
if (*p < value)
{
do *d = *p;
while (--d != firstMove && *--p < value);
*d = value;
}
}
}
#endif // !defined(TYPES_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,309 +17,246 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// Includes
////
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include "book.h"
#include "evaluate.h"
#include "misc.h"
#include "move.h"
#include "movegen.h"
#include "position.h"
#include "san.h"
#include "search.h"
#include "uci.h"
#include "thread.h"
#include "ucioption.h"
using namespace std;
////
//// Local definitions:
////
namespace {
// UCIInputParser is a class for parsing UCI input. The class
// is actually a string stream built on a given input string.
// FEN string of the initial position, normal chess
const char* StartFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
typedef istringstream UCIInputParser;
// Keep track of position keys along the setup moves (from start position to the
// position just before to start searching). This is needed by draw detection
// where, due to 50 moves rule, we need to check at most 100 plies back.
StateInfo StateRingBuf[102], *SetupState = StateRingBuf;
// The root position. This is set up when the user (or in practice, the GUI)
// sends the "position" UCI command. The root position is sent to the think()
// function when the program receives the "go" command.
Position RootPosition(0);
// Local functions
bool handle_command(const string& command);
void set_option(UCIInputParser& uip);
void set_position(UCIInputParser& uip);
bool go(UCIInputParser& uip);
void perft(UCIInputParser& uip);
void set_option(istringstream& up);
void set_position(Position& pos, istringstream& up);
void go(Position& pos, istringstream& up);
void perft(Position& pos, istringstream& up);
}
////
//// Functions
////
/// Wait for a command from the user, parse this text string as an UCI command,
/// and call the appropriate functions. Also intercepts EOF from stdin to ensure
/// that we exit gracefully if the GUI dies unexpectedly. In addition to the UCI
/// commands, the function also supports a few debug commands.
/// uci_main_loop() is the only global function in this file. It is
/// called immediately after the program has finished initializing.
/// The program remains in this loop until it receives the "quit" UCI
/// command. It waits for a command from the user, and passes this
/// command to handle_command and also intercepts EOF from stdin,
/// by translating EOF to the "quit" command. This ensures that Stockfish
/// exits gracefully if the GUI dies unexpectedly.
void uci_loop() {
void uci_main_loop() {
Position pos(StartFEN, false, 0); // The root position
string cmd, token;
RootPosition.from_fen(StartPosition);
string command;
while (token != "quit")
{
if (!getline(cin, cmd)) // Block here waiting for input
cmd = "quit";
do {
// Wait for a command from stdin
if (!getline(cin, command))
command = "quit";
istringstream is(cmd);
} while (handle_command(command));
}
is >> skipws >> token;
if (token == "quit" || token == "stop")
Threads.stop_thinking();
////
//// Local functions
////
else if (token == "ponderhit")
{
// The opponent has played the expected move. GUI sends "ponderhit" if
// we were told to ponder on the same move the opponent has played. We
// should continue searching but switching from pondering to normal search.
Search::Limits.ponder = false;
namespace {
if (Search::Signals.stopOnPonderhit)
Threads.stop_thinking();
}
// handle_command() takes a text string as input, uses a
// UCIInputParser object to parse this text string as a UCI command,
// and calls the appropriate functions. In addition to the UCI
// commands, the function also supports a few debug commands.
else if (token == "go")
go(pos, is);
bool handle_command(const string& command) {
else if (token == "ucinewgame")
pos.from_fen(StartFEN, false);
UCIInputParser uip(command);
string token;
else if (token == "isready")
cout << "readyok" << endl;
if (!(uip >> token)) // operator>>() skips any whitespace
return true;
else if (token == "position")
set_position(pos, is);
if (token == "quit")
return false;
else if (token == "setoption")
set_option(is);
if (token == "go")
return go(uip);
else if (token == "perft")
perft(pos, is);
if (token == "uci")
{
cout << "id name " << engine_name()
<< "\nid author Tord Romstad, Marco Costalba, Joona Kiiski\n";
print_uci_options();
cout << "uciok" << endl;
}
else if (token == "ucinewgame")
{
push_button("New Game");
Position::init_piece_square_tables();
RootPosition.from_fen(StartPosition);
}
else if (token == "isready")
cout << "readyok" << endl;
else if (token == "position")
set_position(uip);
else if (token == "setoption")
set_option(uip);
else if (token == "d")
pos.print();
// The remaining commands are for debugging purposes only.
// Perhaps they should be removed later in order to reduce the
// size of the program binary.
else if (token == "d")
RootPosition.print();
else if (token == "flip")
{
Position p(RootPosition, RootPosition.thread());
RootPosition.flipped_copy(p);
}
else if (token == "eval")
{
EvalInfo ei;
cout << "Incremental mg: " << mg_value(RootPosition.value())
<< "\nIncremental eg: " << eg_value(RootPosition.value())
<< "\nFull eval: " << evaluate(RootPosition, ei) << endl;
}
else if (token == "key")
cout << "key: " << hex << RootPosition.get_key()
<< "\nmaterial key: " << RootPosition.get_material_key()
<< "\npawn key: " << RootPosition.get_pawn_key() << endl;
else if (token == "perft")
perft(uip);
else
cout << "Unknown command: " << command << endl;
else if (token == "flip")
pos.flip_me();
return true;
else if (token == "eval")
{
read_evaluation_uci_options(pos.side_to_move());
cout << trace_evaluate(pos) << endl;
}
else if (token == "key")
cout << "key: " << hex << pos.key()
<< "\nmaterial key: " << pos.material_key()
<< "\npawn key: " << pos.pawn_key() << endl;
else if (token == "uci")
cout << "id name " << engine_info(true)
<< "\n" << Options
<< "\nuciok" << endl;
else
cout << "Unknown command: " << cmd << endl;
}
}
// set_position() is called when Stockfish receives the "position" UCI
// command. The input parameter is a UCIInputParser. It is assumed
// that this parser has consumed the first token of the UCI command
// ("position"), and is ready to read the second token ("startpos"
// or "fen", if the input is well-formed).
namespace {
void set_position(UCIInputParser& uip) {
// set_position() is called when engine receives the "position" UCI
// command. The function sets up the position described in the given
// fen string ("fen") or the starting position ("startpos") and then
// makes the moves given in the following move list ("moves").
string token;
void set_position(Position& pos, istringstream& is) {
if (!(uip >> token)) // operator>>() skips any whitespace
return;
Move m;
string token, fen;
is >> token;
if (token == "startpos")
RootPosition.from_fen(StartPosition);
else if (token == "fen")
{
string fen;
while (uip >> token && token != "moves")
{
fen += token;
fen += ' ';
}
RootPosition.from_fen(fen);
fen = StartFEN;
is >> token; // Consume "moves" token if any
}
else if (token == "fen")
while (is >> token && token != "moves")
fen += token + " ";
else
return;
if (uip.good())
pos.from_fen(fen, Options["UCI_Chess960"]);
// Parse move list (if any)
while (is >> token && (m = move_from_uci(pos, token)) != MOVE_NONE)
{
if (token != "moves")
uip >> token;
pos.do_move(m, *SetupState);
if (token == "moves")
{
Move move;
StateInfo st;
while (uip >> token)
{
move = move_from_string(RootPosition, token);
RootPosition.do_move(move, st);
if (RootPosition.rule_50_counter() == 0)
RootPosition.reset_game_ply();
}
// Our StateInfo st is about going out of scope so copy
// its content inside RootPosition before they disappear.
RootPosition.detach();
}
// Increment pointer to StateRingBuf circular buffer
if (++SetupState - StateRingBuf >= 102)
SetupState = StateRingBuf;
}
}
// set_option() is called when Stockfish receives the "setoption" UCI
// command. The input parameter is a UCIInputParser. It is assumed
// that this parser has consumed the first token of the UCI command
// ("setoption"), and is ready to read the second token ("name", if
// the input is well-formed).
// set_option() is called when engine receives the "setoption" UCI command. The
// function updates the UCI option ("name") to the given value ("value").
void set_option(UCIInputParser& uip) {
void set_option(istringstream& is) {
string token, name, value;
if (!(uip >> token)) // operator>>() skips any whitespace
return;
is >> token; // Consume "name" token
if (token == "name" && uip >> name)
{
while (uip >> token && token != "value")
name += (" " + token);
// Read option name (can contain spaces)
while (is >> token && token != "value")
name += string(" ", !name.empty()) + token;
if (token == "value" && uip >> value)
{
while (uip >> token)
value += (" " + token);
// Read option value (can contain spaces)
while (is >> token)
value += string(" ", !value.empty()) + token;
set_option_value(name, value);
} else
push_button(name);
}
if (!Options.count(name))
cout << "No such option: " << name << endl;
else if (value.empty()) // UCI buttons don't have a value
Options[name] = true;
else
Options[name] = value;
}
// go() is called when Stockfish receives the "go" UCI command. The
// input parameter is a UCIInputParser. It is assumed that this
// parser has consumed the first token of the UCI command ("go"),
// and is ready to read the second token. The function sets the
// thinking time and other parameters from the input string, and
// calls think() (defined in search.cpp) with the appropriate
// parameters. Returns false if a quit command is received while
// thinking, returns true otherwise.
// go() is called when engine receives the "go" UCI command. The function sets
// the thinking time and other parameters from the input string, and then starts
// the main searching thread.
bool go(UCIInputParser& uip) {
void go(Position& pos, istringstream& is) {
string token;
Search::LimitsType limits;
std::vector<Move> searchMoves;
int time[] = { 0, 0 }, inc[] = { 0, 0 };
int time[2] = {0, 0}, inc[2] = {0, 0};
int movesToGo = 0, depth = 0, nodes = 0, moveTime = 0;
bool infinite = false, ponder = false;
Move searchMoves[500];
searchMoves[0] = MOVE_NONE;
while (uip >> token)
while (is >> token)
{
if (token == "infinite")
infinite = true;
limits.infinite = true;
else if (token == "ponder")
ponder = true;
limits.ponder = true;
else if (token == "wtime")
uip >> time[0];
is >> time[WHITE];
else if (token == "btime")
uip >> time[1];
is >> time[BLACK];
else if (token == "winc")
uip >> inc[0];
is >> inc[WHITE];
else if (token == "binc")
uip >> inc[1];
is >> inc[BLACK];
else if (token == "movestogo")
uip >> movesToGo;
is >> limits.movesToGo;
else if (token == "depth")
uip >> depth;
is >> limits.maxDepth;
else if (token == "nodes")
uip >> nodes;
is >> limits.maxNodes;
else if (token == "movetime")
uip >> moveTime;
is >> limits.maxTime;
else if (token == "searchmoves")
{
int numOfMoves = 0;
while (uip >> token)
searchMoves[numOfMoves++] = move_from_string(RootPosition, token);
searchMoves[numOfMoves] = MOVE_NONE;
}
while (is >> token)
searchMoves.push_back(move_from_uci(pos, token));
}
assert(RootPosition.is_ok());
limits.time = time[pos.side_to_move()];
limits.increment = inc[pos.side_to_move()];
return think(RootPosition, infinite, ponder, RootPosition.side_to_move(),
time, inc, movesToGo, depth, nodes, moveTime, searchMoves);
Threads.start_thinking(pos, limits, searchMoves, true);
}
void perft(UCIInputParser& uip) {
string token;
int depth, tm, n;
Position pos(RootPosition, RootPosition.thread());
// perft() is called when engine receives the "perft" command. The function
// calls perft() with the required search depth then prints counted leaf nodes
// and elapsed time.
if (!(uip >> depth))
void perft(Position& pos, istringstream& is) {
int depth, time;
if (!(is >> depth))
return;
tm = get_system_time();
time = system_time();
n = perft(pos, depth * OnePly);
int64_t n = Search::perft(pos, depth * ONE_PLY);
time = system_time() - time;
tm = get_system_time() - tm;
std::cout << "\nNodes " << n
<< "\nTime (ms) " << tm
<< "\nNodes/second " << (int)(n/(tm/1000.0)) << std::endl;
<< "\nTime (ms) " << time
<< "\nNodes/second " << int(n / (time / 1000.0)) << std::endl;
}
}

View File

@@ -1,31 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(UCI_H_INCLUDED)
#define UCI_H_INCLUDED
////
//// Prototypes
////
extern void uci_main_loop();
#endif // !defined(UCI_H_INCLUDED)

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,17 +17,8 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// Includes
////
#include <algorithm>
#include <cassert>
#include <map>
#include <string>
#include <sstream>
#include <vector>
#include "misc.h"
#include "thread.h"
@@ -35,308 +26,102 @@
using std::string;
////
//// Local definitions
////
namespace {
///
/// Types
///
enum OptionType { SPIN, COMBO, CHECK, STRING, BUTTON };
typedef std::vector<string> ComboValues;
struct Option {
string name, defaultValue, currentValue;
OptionType type;
size_t idx;
int minValue, maxValue;
ComboValues comboValues;
Option();
Option(const char* defaultValue, OptionType = STRING);
Option(bool defaultValue, OptionType = CHECK);
Option(int defaultValue, int minValue, int maxValue);
bool operator<(const Option& o) const { return this->idx < o.idx; }
};
typedef std::map<string, Option> Options;
///
/// Constants
///
// load_defaults populates the options map with the hard
// coded names and default values.
void load_defaults(Options& o) {
o["Use Search Log"] = Option(false);
o["Search Log Filename"] = Option("SearchLog.txt");
o["Book File"] = Option("book.bin");
o["Best Book Move"] = Option(false);
o["Mobility (Middle Game)"] = Option(100, 0, 200);
o["Mobility (Endgame)"] = Option(100, 0, 200);
o["Pawn Structure (Middle Game)"] = Option(100, 0, 200);
o["Pawn Structure (Endgame)"] = Option(100, 0, 200);
o["Passed Pawns (Middle Game)"] = Option(100, 0, 200);
o["Passed Pawns (Endgame)"] = Option(100, 0, 200);
o["Space"] = Option(100, 0, 200);
o["Aggressiveness"] = Option(100, 0, 200);
o["Cowardice"] = Option(100, 0, 200);
o["Check Extension (PV nodes)"] = Option(2, 0, 2);
o["Check Extension (non-PV nodes)"] = Option(1, 0, 2);
o["Single Evasion Extension (PV nodes)"] = Option(2, 0, 2);
o["Single Evasion Extension (non-PV nodes)"] = Option(2, 0, 2);
o["Mate Threat Extension (PV nodes)"] = Option(2, 0, 2);
o["Mate Threat Extension (non-PV nodes)"] = Option(2, 0, 2);
o["Pawn Push to 7th Extension (PV nodes)"] = Option(1, 0, 2);
o["Pawn Push to 7th Extension (non-PV nodes)"] = Option(1, 0, 2);
o["Passed Pawn Extension (PV nodes)"] = Option(1, 0, 2);
o["Passed Pawn Extension (non-PV nodes)"] = Option(0, 0, 2);
o["Pawn Endgame Extension (PV nodes)"] = Option(2, 0, 2);
o["Pawn Endgame Extension (non-PV nodes)"] = Option(2, 0, 2);
o["Randomness"] = Option(0, 0, 10);
o["Minimum Split Depth"] = Option(4, 4, 7);
o["Maximum Number of Threads per Split Point"] = Option(5, 4, 8);
o["Threads"] = Option(1, 1, MAX_THREADS);
o["Hash"] = Option(32, 4, 8192);
o["Clear Hash"] = Option(false, BUTTON);
o["New Game"] = Option(false, BUTTON);
o["Ponder"] = Option(true);
o["OwnBook"] = Option(true);
o["MultiPV"] = Option(1, 1, 500);
o["UCI_Chess960"] = Option(false);
o["UCI_AnalyseMode"] = Option(false);
// Any option should know its name so to be easily printed
for (Options::iterator it = o.begin(); it != o.end(); ++it)
it->second.name = it->first;
}
///
/// Variables
///
Options options;
// stringify converts a value of type T to a std::string
template<typename T>
string stringify(const T& v) {
std::ostringstream ss;
ss << v;
return ss.str();
}
OptionsMap Options; // Global object
// get_option_value implements the various get_option_value_<type>
// functions defined later, because only the option value
// type changes a template seems a proper solution.
/// Our case insensitive less() function as required by UCI protocol
static bool ci_less(char c1, char c2) { return tolower(c1) < tolower(c2); }
template<typename T>
T get_option_value(const string& optionName) {
T ret = T();
if (options.find(optionName) == options.end())
return ret;
std::istringstream ss(options[optionName].currentValue);
ss >> ret;
return ret;
}
// Specialization for std::string where instruction 'ss >> ret;'
// would erroneusly tokenize a string with spaces.
template<>
string get_option_value<string>(const string& optionName) {
if (options.find(optionName) == options.end())
return string();
return options[optionName].currentValue;
}
}
////
//// Functions
////
/// init_uci_options() initializes the UCI options. Currently, the only
/// thing this function does is to initialize the default value of the
/// "Threads" parameter to the number of available CPU cores.
void init_uci_options() {
load_defaults(options);
// Set optimal value for parameter "Minimum Split Depth"
// according to number of available cores.
assert(options.find("Threads") != options.end());
assert(options.find("Minimum Split Depth") != options.end());
Option& thr = options["Threads"];
Option& msd = options["Minimum Split Depth"];
thr.defaultValue = thr.currentValue = stringify(cpu_count());
if (cpu_count() >= 8)
msd.defaultValue = msd.currentValue = stringify(7);
bool CaseInsensitiveLess::operator() (const string& s1, const string& s2) const {
return lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end(), ci_less);
}
/// print_uci_options() prints all the UCI options to the standard output,
/// in the format defined by the UCI protocol.
/// OptionsMap c'tor initializes the UCI options to their hard coded default
/// values and initializes the default value of "Threads" and "Min Split Depth"
/// parameters according to the number of CPU cores detected.
void print_uci_options() {
OptionsMap::OptionsMap() {
static const char optionTypeName[][16] = {
"spin", "combo", "check", "string", "button"
};
int cpus = std::min(cpu_count(), MAX_THREADS);
int msd = cpus < 8 ? 4 : 7;
OptionsMap& o = *this;
// Build up a vector out of the options map and sort it according to idx
// field, that is the chronological insertion order in options map.
std::vector<Option> vec;
for (Options::const_iterator it = options.begin(); it != options.end(); ++it)
vec.push_back(it->second);
std::sort(vec.begin(), vec.end());
for (std::vector<Option>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
std::cout << "\noption name " << it->name
<< " type " << optionTypeName[it->type];
if (it->type == BUTTON)
continue;
if (it->type == CHECK)
std::cout << " default " << (it->defaultValue == "1" ? "true" : "false");
else
std::cout << " default " << it->defaultValue;
if (it->type == SPIN)
std::cout << " min " << it->minValue << " max " << it->maxValue;
else if (it->type == COMBO)
for (ComboValues::const_iterator itc = it->comboValues.begin();
itc != it->comboValues.end(); ++itc)
std::cout << " var " << *itc;
}
std::cout << std::endl;
o["Use Search Log"] = UCIOption(false);
o["Search Log Filename"] = UCIOption("SearchLog.txt");
o["Book File"] = UCIOption("book.bin");
o["Best Book Move"] = UCIOption(false);
o["Mobility (Middle Game)"] = UCIOption(100, 0, 200);
o["Mobility (Endgame)"] = UCIOption(100, 0, 200);
o["Passed Pawns (Middle Game)"] = UCIOption(100, 0, 200);
o["Passed Pawns (Endgame)"] = UCIOption(100, 0, 200);
o["Space"] = UCIOption(100, 0, 200);
o["Aggressiveness"] = UCIOption(100, 0, 200);
o["Cowardice"] = UCIOption(100, 0, 200);
o["Min Split Depth"] = UCIOption(msd, 4, 7);
o["Max Threads per Split Point"] = UCIOption(5, 4, 8);
o["Threads"] = UCIOption(cpus, 1, MAX_THREADS);
o["Use Sleeping Threads"] = UCIOption(false);
o["Hash"] = UCIOption(32, 4, 8192);
o["Clear Hash"] = UCIOption(false, "button");
o["Ponder"] = UCIOption(true);
o["OwnBook"] = UCIOption(true);
o["MultiPV"] = UCIOption(1, 1, 500);
o["Skill Level"] = UCIOption(20, 0, 20);
o["Emergency Move Horizon"] = UCIOption(40, 0, 50);
o["Emergency Base Time"] = UCIOption(200, 0, 30000);
o["Emergency Move Time"] = UCIOption(70, 0, 5000);
o["Minimum Thinking Time"] = UCIOption(20, 0, 5000);
o["UCI_Chess960"] = UCIOption(false);
o["UCI_AnalyseMode"] = UCIOption(false);
}
/// get_option_value_bool() returns the current value of a UCI parameter of
/// type "check".
/// operator<<() is used to output all the UCI options in chronological insertion
/// order (the idx field) and in the format defined by the UCI protocol.
std::ostream& operator<<(std::ostream& os, const OptionsMap& om) {
bool get_option_value_bool(const string& optionName) {
for (size_t idx = 0; idx < om.size(); idx++)
for (OptionsMap::const_iterator it = om.begin(); it != om.end(); ++it)
if (it->second.idx == idx)
{
const UCIOption& o = it->second;
os << "\noption name " << it->first << " type " << o.type;
return get_option_value<bool>(optionName);
if (o.type != "button")
os << " default " << o.defaultValue;
if (o.type == "spin")
os << " min " << o.min << " max " << o.max;
break;
}
return os;
}
/// get_option_value_int() returns the value of a UCI parameter as an integer.
/// Normally, this function will be used for a parameter of type "spin", but
/// it could also be used with a "combo" parameter, where all the available
/// values are integers.
/// UCIOption class c'tors
int get_option_value_int(const string& optionName) {
return get_option_value<int>(optionName);
}
/// get_option_value_string() returns the current value of a UCI parameter as
/// a string. It is used with parameters of type "combo" and "string".
string get_option_value_string(const string& optionName) {
return get_option_value<string>(optionName);
}
/// set_option_value() inserts a new value for a UCI parameter. Note that
/// the function does not check that the new value is legal for the given
/// parameter: This is assumed to be the responsibility of the GUI.
void set_option_value(const string& name, const string& value) {
// UCI protocol uses "true" and "false" instead of "1" and "0", so convert
// value according to standard C++ convention before to store it.
string v(value);
if (v == "true")
v = "1";
else if (v == "false")
v = "0";
if (options.find(name) == options.end())
{
std::cout << "No such option: " << name << std::endl;
return;
}
// Normally it's up to the GUI to check for option's limits,
// but we could receive the new value directly from the user
// by teminal window. So let's check the bounds anyway.
Option& opt = options[name];
if (opt.type == CHECK && v != "0" && v != "1")
return;
else if (opt.type == SPIN)
{
int val = atoi(v.c_str());
if (val < opt.minValue || val > opt.maxValue)
return;
}
opt.currentValue = v;
}
/// push_button() is used to tell the engine that a UCI parameter of type
/// "button" has been selected:
void push_button(const string& buttonName) {
set_option_value(buttonName, "true");
}
/// button_was_pressed() tests whether a UCI parameter of type "button" has
/// been selected since the last time the function was called, in this case
/// it also resets the button.
bool button_was_pressed(const string& buttonName) {
if (!get_option_value<bool>(buttonName))
return false;
set_option_value(buttonName, "false");
return true;
}
namespace {
// Define constructors of Option class.
Option::Option() {} // To allow insertion in a std::map
Option::Option(const char* def, OptionType t)
: defaultValue(def), currentValue(def), type(t), idx(options.size()), minValue(0), maxValue(0) {}
Option::Option(bool def, OptionType t)
: defaultValue(stringify(def)), currentValue(stringify(def)), type(t), idx(options.size()), minValue(0), maxValue(0) {}
Option::Option(int def, int minv, int maxv)
: defaultValue(stringify(def)), currentValue(stringify(def)), type(SPIN), idx(options.size()), minValue(minv), maxValue(maxv) {}
UCIOption::UCIOption(const char* v) : type("string"), min(0), max(0), idx(Options.size())
{ defaultValue = currentValue = v; }
UCIOption::UCIOption(bool v, string t) : type(t), min(0), max(0), idx(Options.size())
{ defaultValue = currentValue = (v ? "true" : "false"); }
UCIOption::UCIOption(int v, int minv, int maxv) : type("spin"), min(minv), max(maxv), idx(Options.size())
{ std::ostringstream ss; ss << v; defaultValue = currentValue = ss.str(); }
/// UCIOption::operator=() updates currentValue. Normally it's up to the GUI to
/// check for option's limits, but we could receive the new value directly from
/// the user by teminal window, so let's check the bounds anyway.
void UCIOption::operator=(const string& v) {
assert(!type.empty());
if ( !v.empty()
&& (type == "check" || type == "button") == (v == "true" || v == "false")
&& (type != "spin" || (atoi(v.c_str()) >= min && atoi(v.c_str()) <= max)))
currentValue = v;
}

View File

@@ -1,7 +1,7 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,28 +17,58 @@
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(UCIOPTION_H_INCLUDED)
#define UCIOPTION_H_INCLUDED
////
//// Includes
////
#include <cassert>
#include <cstdlib>
#include <map>
#include <string>
////
//// Prototypes
////
struct OptionsMap;
extern void init_uci_options();
extern void print_uci_options();
extern bool get_option_value_bool(const std::string& optionName);
extern int get_option_value_int(const std::string& optionName);
extern std::string get_option_value_string(const std::string& optionName);
extern bool button_was_pressed(const std::string& buttonName);
extern void set_option_value(const std::string& optionName,const std::string& newValue);
extern void push_button(const std::string& buttonName);
/// UCIOption class implements an option as defined by UCI protocol
class UCIOption {
public:
UCIOption() {} // Required by std::map::operator[]
UCIOption(const char* v);
UCIOption(bool v, std::string type = "check");
UCIOption(int v, int min, int max);
void operator=(const std::string& v);
void operator=(bool v) { *this = std::string(v ? "true" : "false"); }
operator int() const {
assert(type == "check" || type == "button" || type == "spin");
return (type == "spin" ? atoi(currentValue.c_str()) : currentValue == "true");
}
operator std::string() const {
assert(type == "string");
return currentValue;
}
private:
friend std::ostream& operator<<(std::ostream&, const OptionsMap&);
std::string defaultValue, currentValue, type;
int min, max;
size_t idx;
};
/// Custom comparator because UCI options should be case insensitive
struct CaseInsensitiveLess {
bool operator() (const std::string&, const std::string&) const;
};
/// Our options container is actually a map with a customized c'tor
struct OptionsMap : public std::map<std::string, UCIOption, CaseInsensitiveLess> {
OptionsMap();
};
extern std::ostream& operator<<(std::ostream&, const OptionsMap&);
extern OptionsMap Options;
#endif // !defined(UCIOPTION_H_INCLUDED)

View File

@@ -1,96 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// Includes
////
#include <sstream>
#include <string>
#include "value.h"
////
//// Functions
////
/// value_to_tt() adjusts a mate score from "plies to mate from the root" to
/// "plies to mate from the current ply". Non-mate scores are unchanged.
/// The function is called before storing a value to the transposition table.
Value value_to_tt(Value v, int ply) {
if(v >= value_mate_in(100))
return v + ply;
else if(v <= value_mated_in(100))
return v - ply;
else
return v;
}
/// value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
/// from the transposition table to a mate score corrected for the current
/// ply depth.
Value value_from_tt(Value v, int ply) {
if(v >= value_mate_in(100))
return v - ply;
else if(v <= value_mated_in(100))
return v + ply;
else
return v;
}
/// value_to_centipawns() converts a value from Stockfish's somewhat unusual
/// scale of pawn = 256 to the more conventional pawn = 100.
int value_to_centipawns(Value v) {
return (int(v) * 100) / int(PawnValueMidgame);
}
/// value_from_centipawns() converts a centipawn value to Stockfish's internal
/// evaluation scale. It's used when reading the values of UCI options
/// containing material values (e.g. futility pruning margins).
Value value_from_centipawns(int cp) {
return Value((cp * 256) / 100);
}
/// value_to_string() converts a value to a string suitable for use with the
/// UCI protocol.
const std::string value_to_string(Value v) {
std::stringstream s;
if(abs(v) < VALUE_MATE - 200)
s << "cp " << value_to_centipawns(v);
else {
s << "mate ";
if(v > 0)
s << (VALUE_MATE - v + 1) / 2;
else
s << -(VALUE_MATE + v) / 2;
}
return s.str();
}

View File

@@ -1,205 +0,0 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2010 Marco Costalba, Joona Kiiski, Tord Romstad
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(VALUE_H_INCLUDED)
#define VALUE_H_INCLUDED
////
//// Includes
////
#include "piece.h"
////
//// Types
////
enum ValueType {
VALUE_TYPE_NONE = 0,
VALUE_TYPE_UPPER = 1, // Upper bound
VALUE_TYPE_LOWER = 2, // Lower bound
VALUE_TYPE_EXACT = VALUE_TYPE_UPPER | VALUE_TYPE_LOWER
};
enum Value {
VALUE_DRAW = 0,
VALUE_KNOWN_WIN = 15000,
VALUE_MATE = 30000,
VALUE_INFINITE = 30001,
VALUE_NONE = 30002,
VALUE_ENSURE_SIGNED = -1
};
/// Score enum keeps a midgame and an endgame value in a single
/// integer (enum), first LSB 16 bits are used to store endgame
/// value, while upper bits are used for midgame value.
// Compiler is free to choose the enum type as long as can keep
// its data, so ensure Score to be an integer type.
enum Score { ENSURE_32_BITS_SIZE_P = (1 << 16), ENSURE_32_BITS_SIZE_N = -(1 << 16)};
// Extracting the _signed_ lower and upper 16 bits it not so trivial
// because according to the standard a simple cast to short is
// implementation defined and so is a right shift of a signed integer.
inline Value mg_value(Score s) { return Value(((int(s) + 32768) & ~0xffff) / 0x10000); }
// Unfortunatly on Intel 64 bit we have a small speed regression, so use a faster code in
// this case, although not 100% standard compliant it seems to work for Intel and MSVC.
#if defined(IS_64BIT) && (!defined(__GNUC__) || defined(__INTEL_COMPILER))
inline Value eg_value(Score s) { return Value(int16_t(s & 0xffff)); }
#else
inline Value eg_value(Score s) { return Value((int)(unsigned(s) & 0x7fffu) - (int)(unsigned(s) & 0x8000u)); }
#endif
inline Score make_score(int mg, int eg) { return Score((mg << 16) + eg); }
inline Score operator-(Score s) { return Score(-int(s)); }
inline Score operator+(Score s1, Score s2) { return Score(int(s1) + int(s2)); }
inline Score operator-(Score s1, Score s2) { return Score(int(s1) - int(s2)); }
inline void operator+=(Score& s1, Score s2) { s1 = Score(int(s1) + int(s2)); }
inline void operator-=(Score& s1, Score s2) { s1 = Score(int(s1) - int(s2)); }
inline Score operator*(int i, Score s) { return Score(i * int(s)); }
// Division must be handled separately for each term
inline Score operator/(Score s, int i) { return make_score(mg_value(s) / i, eg_value(s) / i); }
// Only declared but not defined. We don't want to multiply two scores due to
// a very high risk of overflow. So user should explicitly convert to integer.
inline Score operator*(Score s1, Score s2);
////
//// Constants and variables
////
/// Piece values, middle game and endgame
/// Important: If the material values are changed, one must also
/// adjust the piece square tables, and the method game_phase() in the
/// Position class!
///
/// Values modified by Joona Kiiski
const Value PawnValueMidgame = Value(0x0C6);
const Value PawnValueEndgame = Value(0x102);
const Value KnightValueMidgame = Value(0x331);
const Value KnightValueEndgame = Value(0x34E);
const Value BishopValueMidgame = Value(0x344);
const Value BishopValueEndgame = Value(0x359);
const Value RookValueMidgame = Value(0x4F6);
const Value RookValueEndgame = Value(0x4FE);
const Value QueenValueMidgame = Value(0x9D9);
const Value QueenValueEndgame = Value(0x9FE);
const Value PieceValueMidgame[17] = {
Value(0),
PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
RookValueMidgame, QueenValueMidgame,
Value(0), Value(0), Value(0),
PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
RookValueMidgame, QueenValueMidgame,
Value(0), Value(0), Value(0)
};
const Value PieceValueEndgame[17] = {
Value(0),
PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
RookValueEndgame, QueenValueEndgame,
Value(0), Value(0), Value(0),
PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
RookValueEndgame, QueenValueEndgame,
Value(0), Value(0), Value(0)
};
/// Bonus for having the side to move (modified by Joona Kiiski)
const Score TempoValue = make_score(48, 22);
////
//// Inline functions
////
inline Value operator+ (Value v, int i) { return Value(int(v) + i); }
inline Value operator+ (Value v1, Value v2) { return Value(int(v1) + int(v2)); }
inline void operator+= (Value &v1, Value v2) {
v1 = Value(int(v1) + int(v2));
}
inline Value operator- (Value v, int i) { return Value(int(v) - i); }
inline Value operator- (Value v) { return Value(-int(v)); }
inline Value operator- (Value v1, Value v2) { return Value(int(v1) - int(v2)); }
inline void operator-= (Value &v1, Value v2) {
v1 = Value(int(v1) - int(v2));
}
inline Value operator* (Value v, int i) { return Value(int(v) * i); }
inline void operator*= (Value &v, int i) { v = Value(int(v) * i); }
inline Value operator* (int i, Value v) { return Value(int(v) * i); }
inline Value operator/ (Value v, int i) { return Value(int(v) / i); }
inline void operator/= (Value &v, int i) { v = Value(int(v) / i); }
inline Value value_mate_in(int ply) {
return Value(VALUE_MATE - Value(ply));
}
inline Value value_mated_in(int ply) {
return Value(-VALUE_MATE + Value(ply));
}
inline bool is_upper_bound(ValueType vt) {
return (int(vt) & int(VALUE_TYPE_UPPER)) != 0;
}
inline bool is_lower_bound(ValueType vt) {
return (int(vt) & int(VALUE_TYPE_LOWER)) != 0;
}
inline Value piece_value_midgame(PieceType pt) {
return PieceValueMidgame[pt];
}
inline Value piece_value_endgame(PieceType pt) {
return PieceValueEndgame[pt];
}
inline Value piece_value_midgame(Piece p) {
return PieceValueMidgame[p];
}
inline Value piece_value_endgame(Piece p) {
return PieceValueEndgame[p];
}
////
//// Prototypes
////
extern Value value_to_tt(Value v, int ply);
extern Value value_from_tt(Value v, int ply);
extern int value_to_centipawns(Value v);
extern Value value_from_centipawns(int cp);
extern const std::string value_to_string(Value v);
#endif // !defined(VALUE_H_INCLUDED)