Compare commits

...

743 Commits

Author SHA1 Message Date
Marco Costalba aaa07fb161 Stockfish 1.5
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-10-04 07:09:12 +01:00
Marco Costalba 1361ba75cb Small touches to increased mobility patch
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-10-04 06:59:06 +01:00
Marco Costalba da9c423989 Move a comment where it belongs in SEE
No functional change of course.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-10-03 10:48:20 +01:00
Marco Costalba 3713bb26ef Don't increase mobility if attacked piece is defended by a pawn
If an enemy piece is defended by a pawn don't give the
extra mobility bonus in case we attack it.

Joona says that "Paralyzing pawn" is usually worth of nothing.

On Joona QUAD after 964 games:
Orig - Patch_2: 191 - 218 - 555 (+ 10 elo)

On my PC after 999 games at 1+0:
Mod vs Orig +227 =550 -222 50.25%  502.0/999  +2 ELO

In both cases we tested against the original version (without
increased mobility), not against the previous patch that instead
seems to fail on Joona QUAD:
Orig vs. Prev.Patch: 237 - 217 - 627 (-6 elo)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-10-03 10:48:07 +01:00
Marco Costalba cff9ff2198 Count two times number of attacked pieces in mobility
Now in mobility we count enemy attacked pieces as
empty squares.

With this patch we try to give an higher score to positions
where the number of attacked pieces is higher.

After 999 games at 1+0

Mod vs Orig +262 =517 -219 52.15% 520.5/998 +15 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-30 16:11:45 +01:00
Marco Costalba a6c6037813 Optimize futilityValue calculation
Avoid calling evaluate() if we already have the score in TT

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-30 16:11:41 +01:00
Marco Costalba e677185567 Store pawn attacks in PawnInfo
They are pawn structure invariant so has a sense to
store togheter with pawn info instead of recalculating
them each time evaluate() is called.

Speed up is around 1%

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-30 16:11:37 +01:00
Tord Romstad 237dd331d5 Fixed a couple of typos in a comment.
No functional change, of course.
2009-09-30 09:53:29 +02:00
Marco Costalba 98c8a83bb8 Fix a MSVC warning in search.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-29 16:48:50 +01:00
Tord Romstad 73be819426 Temporarily removed the unfinished UCI_Elo code in preparation for
the release of the public Stockfish 1.5.
2009-09-29 13:40:00 +02:00
Marco Costalba 2940abdac8 Print RootMoveList startup scoring
This satisfies a specific user request of 28/8/2009

"The only issue I have is that during multiPV analysis, the depth 1
best move score is not reported by the engine (reporting for the best
move begins at depth 2).  I need it at depth 1 also. Would it be
possible to make this modification in future versions? This would be
of great help as otherwise I will have to use a lesser engine.

The goal of my project is to calculate the ELO performance in a game
and also the ELO rating of individual moves. For this I need depth 1
scores for lower rated performances. I intend to distribute the program
for free upon completion.

Thanks, Jack Welbourne"

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-29 10:14:43 +01:00
Marco Costalba fa0bffeafa Retire compute_weight() in evaluation.cpp
Is used only in weight_option() so inline there.
Unroll color loop also for evaluate_space() and
finally also some assorted code style fixes.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-28 17:56:04 +01:00
Marco Costalba d56345c9ae Unroll color loops in evaluate
Use templates to manually unroll the loops so that
many values could be calculated at compile time or at
runtime but with a fast direct memory access instead of
an indirect one.

This change gives a speed up of 3.5 % on pgo build !!!  :-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-28 11:44:12 +01:00
Marco Costalba 60e23693f0 Change back file mode of misc.cpp
It was erroneusly changed by 6bf22f35 from
mode 100644 to 100755.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-27 07:58:28 +01:00
Marco Costalba 91f0c08789 Update piece list iteration also in evaluate_pieces()
Move to what we already do in generate_piece_moves()

This simple patch gives a spped up of 1.4% !!

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-26 15:49:04 +02:00
Marco Costalba 6bf22f354f Retire faked Windows version of gettimeofday()
Use equivalent Windows function _ftime() instead.

This patch also removes two long standing warnings
under MSVC.

No functional change and no change for non-Windows systems.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-26 15:48:58 +02:00
Marco Costalba 48b74142ef Micro optimization of generate_piece_moves()
This patch make the piece list always terminated by SQ_NONE,
so that we can use a simpler and faster loop in move
generation.

Speedup is about 0.6%.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-24 07:11:39 +01:00
Marco Costalba dcb323bf0d Retire kingSquare[] array
It is redundant. Use pieceList[c][KING][0] instead.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-23 17:47:03 +01:00
Marco Costalba 44cb792c76 Reorder data layout and optimize access patern
With this very simple patch we get a speed boost
of 0.8% on my PC !

Sometime we find the most complex tricks to increase speed
when instead the best results come from the simplest solutions.

No functional change of course ;-)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-23 17:33:24 +01:00
Marco Costalba e68e135771 Fix a couple of Intel compiler warnings
And avoid calculating emptySquares for pawns captures
case.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-23 17:01:59 +01:00
Marco Costalba 46141b078c Fix a piece_of_color_and_type() / pieceS_of_color_and_type() typo
Bug introduced in 17c51192

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-23 17:01:30 +01:00
Marco Costalba 02fd34a5e8 Rename generate_piece_moves() in generate_piece_evasions()
A better and more specific name. Also a bit of code reshuffle.

Verified No functional change and No performance change
for the whole series.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-23 14:23:07 +01:00
Marco Costalba 20cac227bb Retire generate_pawn_captures()
And unify in generate_pawn_noncaptures() renamed
generate_pawn_moves()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-23 11:18:55 +01:00
Marco Costalba 4346445be3 Retire generate_pawn_blocking_evasions()
And unify in generate_pawn_noncaptures()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-23 10:47:11 +01:00
Marco Costalba 21850536d5 Standardize generate_pawn_blocking_evasions()
Rewrite in the form normally used in other similar
functions like generate_pawn_noncaptures()

This allow an easier reading of the pawn moves generators
and simplify a bit the code.

No functional change (tested on more then 100M nodes).

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-23 10:06:32 +01:00
Marco Costalba 0179a32cf5 Code style and subtle fix in move_is_legal()
A bunch of trivial code style and comment fixes.

Among them there is a real fix for a subtle case
involving promotion moves.

We currently check that a pawn push to 8/1th rank
must be a promotion, but we don't check the contary,
i.e. that a pawn push on a different rank must NOT be
a promotion. Note that, funny enough, we perform this
control for all the other pieces, but not for the pawns!

This patch fixes this really corner case.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-22 07:07:19 +01:00
Marco Costalba 8487069058 Simplify move legality check for uncommon cases
Remove a bunch of difficult and tricky code to test
legality of castle and ep moves and instead use a slower
but simpler check against the list of generated legal moves.

Because these moves are very rare the performance impact
is small but code semplification is ver big: almost 100 lines
of difficult code removed !

No functionality change. No performance change (strangely enough
there is no even minimal performance regression in pgo builds but
instead a slightly and unexpected increase).

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-22 07:07:18 +01:00
Marco Costalba 43ca5c926d Enable functionality of previous patch
Now under-promotion checks are generated.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-22 07:07:18 +01:00
Marco Costalba aed542d74c When generating checks add possibly under-promotions
In qsearch at depth 0 we generate only captures and checks.
Queen promotion moves are generated among the captures, but
under-promotion moves (both captures and non-captures) are
never generated even if they could give a discovery check.

This patch fixes this limitation extending generate_pawn_noncaptures()
to generate also check moves when required.

Apart for adding the (rare) case of an under-promotion that gives
discovery check, the patch is also a good cleanup because removes
generate_pawn_checks() altoghter.

This patch does the code clean-up but not enables the functional
change so to allow an easier debug.

No functional change and no performance change (actually a very
very small speed increase).

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-22 07:07:17 +01:00
Marco Costalba aaffcf973e Fix a bug in generate_piece_checks()
We are generating also king moves that give check !

Of course these moves are illegal so are in any case
filtered out in MovePicker. Neverthless we should avoid
to generate them.

Also simplify a bit the code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-22 07:07:16 +01:00
Marco Costalba 746bcb348f Small micro optimization in generate_evasions()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-22 07:07:16 +01:00
Marco Costalba a7cb05b1eb Change evaluation GrainSize from 4 to 8
Idea from Joona.

After 999 games at 1+0 on my Intel Core 2 Duo
Orig - Mod: +215 =538 -226 (+11 ELO)

On Joona QUAD after 845 games at 1+0
Orig - Mod: 151 - 181 - 513 (+13 elo)

So it seems a good change !

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-22 07:06:52 +01:00
Marco Costalba 9741694fca Save static evaluation also for failed low nodes
When a node fails low and bestValue is still equal to
the original static node evaluation, then save this
in TT along with usual info.

This will allow us to avoid a future costly evaluation() call.

This patch extends to failed low nodes what we already do
for failed high ones.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-20 20:05:40 +01:00
Marco Costalba e145c0d3e2 Revert evaluation drift
Still not clear if it helps and, especially, how it
helps. So revert for now to avoid any influence on
future feature now under test.

With this patch we come back to be functional
equivalent to patch e33c94883 F_53.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-20 19:39:54 +01:00
Marco Costalba 24cc3a97a4 Evaluation drift: add always 7 instead of ply
After 828 games at 1+0

Mod vs Orig +191 =447 -190 50.06%  414.5/828

So almost no difference. Patch is committed more for
documentation purposes then for other reasons.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-20 19:32:53 +01:00
Marco Costalba e4277c06bf Rename piece_attacks_from() in attacks_from()
It is in line with attackers_to() and is shorter and
piece is already redundant because is passed as template
parameter anyway.

Integrate also pawn_attacks_from() in the attacks_from()
family so to have an uniform attack info API.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-20 14:55:28 +01:00
Marco Costalba dd80b9abaf Remove undefined pinned_pieces(Color c, Bitboard& p)
It was added in revision 5f142ec2 but never used.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-20 11:01:56 +01:00
Marco Costalba 84d6fe0f31 Retire attackers_to(Square s, Color c)
Use the definition in the few places where is needed.

As a nice side effect there is also an optimization in
generate_evasions() where the bitboard of enemy pieces
is computed only once and out of a tight loop.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-20 10:47:59 +01:00
Marco Costalba 6845397c5c Rename piece_attacks() in piece_attacks_from()
It is a bit longer but much easier to understand especially
for people new to the sources. I remember it was not trivial
for me to understand the returned attack bitboard refers to
attacks launched from the given square and not attacking the
given square.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-20 10:26:54 +01:00
Marco Costalba f74f42b298 Cleanup piece_attacks_square() functions
Most of them are not required to be public and are
used in one place only so remove them and use its
definitions.

Also rename piece_attacks_square() in piece_attacks()
to be aligned to the current naming policy.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-20 10:12:56 +01:00
Marco Costalba 0e0adfe2e1 Rename attacks_to() in attackers_to()
These functions return bitboard of attacking pieces,
not the attacks themselfs so reflect this in the name.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-20 09:31:48 +01:00
Marco Costalba 049139d025 Change pawn_attacks() API
Instead of pawn_attacks(Color c, Square s) define as
pawn_attacks(Square s, Color c) to be more aligned to
the others attack info functions.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-20 09:09:27 +01:00
Marco Costalba 62a8f393f1 Clean up API for attack information
Remove undefined functions sliding_attacks() and ray_attacks()
and retire square_is_attacked(), use the corresponding definition
instead. It is more clear that we are computing full attack
info for the given square.

Alos fix some obsolete comments in move generation functions.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-20 08:48:10 +01:00
Marco Costalba c5f44ef45b Move kingSquare[] array to StateInfo
This avoids to reverting back when undoing the move.

No functional change. No performance change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-20 07:32:00 +01:00
Marco Costalba 7c55b0e880 Don't compensate TT for evaluation drift
It seems that it works better without compensation
of drifted value when saving static evaluation in TT.

After 818 games at 1+0

Mod vs Orig +217 =429 -172 52.75%  431.5/818  +19 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-19 12:52:57 +01:00
Marco Costalba 77ac1e7953 Use WIN32_LEAN_AND_MEAN in lock.h
This avoids inclusion of a bunch of not very commonly
used headers from windows.h

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-17 14:18:44 +01:00
Joona Kiiski cddda7cd19 Make static value saved in TT independent from ply
After 963 games at 1+0

Mod vs Orig +246 =511 -206 52.08%  501.0/962  +14 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-17 14:16:16 +01:00
Marco Costalba c81010a878 Evaluation drift
Increase evaluation score with ply.

After 940 games at 1+0

Mod vs Orig +247 =487 -206  +15 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-15 09:04:16 +01:00
Marco Costalba 6709b01903 Fix semantic of piece_attacks<PAWN>
Return the bitboard with the pawn attacks for both colors
so to be aligned to the meaning of the others piece_attacks<Piece>
templates.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-13 16:13:49 +01:00
Marco Costalba 3863cd191c Indirectly prefetch board[from]
One of the most time critical functions is move_is_check()
and in particular the call to type_of_piece_on(from) in the
switch statement.

This call lookups in board[] array and can be slow if board[from]
is not already cached. Few instructions before in the execution stream,
we check the move for legality with pl_move_is_legal().

This patch changes pl_move_is_legal() to use type_of_piece_on(from)
for checking for a king move so that board[from] is automatically
cached in L1 and ready to be used by the near follower move_is_check()

Another advantage is that the call to king_square(us) in pl_move_is_legal()
is avoided most of the times.

Speed up of this nice and tricky patch is 0.7% !

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-13 11:35:48 +01:00
Marco Costalba f205fe1fe5 Retire piece_is_slider(PieceType pt)
Is not used in any part of the sources.

No functional change, of course ;-)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-04 08:21:07 +01:00
Marco Costalba 9f28d8a854 Second take at unifying bitboard representation access
This patch is built on Tord idea to use functions instead of
templates to access position's bitboards. This has the added advantage
that we don't need fallback functions for cases where the piece
type or the color is a variable and not a constant.

Also added Joona suggestion to workaround request for two types
of pieces like bishop_and_queens() and rook_and_queens().

No functionality or performance change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-04 08:21:06 +01:00
Marco Costalba 76bed11f7b Templetize functions to get pieces by type
Use a single template to get bitboard representation of
the position given the type of piece as a constant.

This removes almost 80 lines of code and introduces an
uniform notation to be used for querying for piece type.

No functional change and no performance change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-04 08:21:05 +01:00
Marco Costalba e33c94883f Set LMRPVMoves to 10 instead of 14
After 934 games at 1+0

Mod vs Orig +228 =493 -213 50.80%  474.5/934   +6 ELO

So it seems not negative and there is also the added
benefit to unify LMRPVMoves use in search_pv() and in
root list.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-04 08:21:04 +01:00
Marco Costalba 46ffea46ea Fix poly values mismerge
I managed to completely mismerge correct values
for QuadraticCoefficientsOppositeColor table :-(

Now it correspond to tuning branch for real.

After 999 games at 1+0

Mod vs Orig +247 =512 -240 50.35%  503.0/999  +2 ELO

So almost no change, but the new values comes from the
same tuning session of the others, so has more sense to
use these ones.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-09-04 08:21:02 +01:00
Tord Romstad 03d6a86900 Bug fix for discovered checks in connected_moves().
Because of a hard-to-spot single-character bug in connected_moves(),
the discovered check code had no effect whatsoever. The condition
in the if (...) statement at the beginning of the code would always
return false.

Thanks to Edsel Apostol for pointing out this bug!
2009-09-02 09:58:15 +02:00
Marco Costalba 17c5119222 Retire pieces_of_color_and_type()
It is used mainly in a bunch of inline oneliners
just below its definition. So substitute it with
the explicit definition and avoid information hiding.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-31 16:23:04 +02:00
Marco Costalba cf71efc34b MovePicker: rename number_of_moves() in number_of_evasions()
It is more clear that only in that case the move number is
correct, otherwise is only a partial quantity: the number of
moves of that phase.

In case of PH_EVASIONS instead we have only one phase.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-31 15:32:31 +02:00
Marco Costalba c9d364f9ca Use pointers instead of array indices also for badCaptures
To have uniformity with moves array handling.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-31 12:33:44 +02:00
Marco Costalba 97dd7568ed Document index[] and pieceList[] are not invariants
Array index[] and pieceList[] are not guaranteed to be
invariant to a do_move() + undo_move() sequence when a
capture move is involved.

The reason is that the captured piece is removed form
the list and substituted with the last one in do_move()
while in undo_move() is added again but at the end of
the list.

Because index[] and pieceList[] are used in move generation
to scan the pieces it means that moves will be generated
in a different order before and after a do_move() + undo_move()
sequence as, for instance, the one in Position::has_mate_threat()

After latest patches, move generation could now be invoked
also by MovePicker c'tor and this explains why order of
picked moves is different if MovePicker object is istantiated
before or after a Position::has_mate_threat() call.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-31 11:02:28 +02:00
Marco Costalba af220cfd52 Workaround a bug in Position::has_mate_threat()
It seems that pos.has_mate_threat() changes the position !

So that calling MovePicker c'tor before or after the
has_mate_threat() call changes the things !

Bug was unhidden by previous patch that makes MovePicker c'tor
to generate, score and sort good captures under some circumstances.

Because scoring the captures is position dependent it seems that
the moves returned by MovePicker are different when c'tor is
called before has_mate_threat()

Of course this is only a workaround because the real bug is still
hidden :-(

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-30 20:10:09 +01:00
Marco Costalba 1130c8d815 Skip TT_MOVES phase when possible
If we don't have tt moves to search skip the
useless loop associated with TT_MOVES phase.

Another 1% speed boost that brings this series
to a +6.2% against original revision 595a90df

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-30 20:10:09 +01:00
Marco Costalba 607ac0687a Movepicker: take move's loop out of switch statement
This not only cleans up the code but gives another
speed boost of 1.8%

From revision 595a90dfd0 we have increased pgo compiled binary
speed of a whopping +5.2% without any functional change !!

This is really awsome considering that we have also
cut line count by 25 lines.

Sometime we spend days for getting an extra 1% from move
generation while instead the biggest optimizations come
from anonymous and apparently dull parts of the code.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-30 20:10:08 +01:00
Marco Costalba e9de96f0e4 Revert "null move reorder" series
Does not seem to improve on the standard, latest results
from Joona after 2040 games are negative:

Orig - Mod: 454 - 424 - 1162

And is more or less the same I got few days ago.

So revert for now.

Verified same functionality of 595a90dfd

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-30 20:09:58 +01:00
Marco Costalba 9ab84a8165 Convert handling of tt moves and killers to standard form
Use the same way of loop along the move list used for
the others move kinds so to be consistent in get_next_move()

And a bit of the usual clean up too, but just a bit.

It is even a bit (+0.3%) faster now. ;-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-29 19:51:00 +01:00
Marco Costalba ac65b14d30 Try null move before captures
Always after TT move but before captures.

This seems a better setup against version before this
patch.

After 999 games at 1+0

Mod - Orig +252 =527 -220 +11 ELO

Unfortunatly it does not seems to improve on the standard
version, with null move outside of movepicker (595a90df) with
the latest speed-up patches added in.

After 999 games at 1+0

Mod - Standard +244 =506 -249 -2 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-29 07:17:09 +01:00
Marco Costalba 9e4befe3f1 Use pointers instead of array indices in MovePicker
This avoids calculating the array entry position
at each access and gives another boost of almost 1%.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-29 06:48:31 +01:00
Marco Costalba 6cf28d4aa7 Change the flow in wich moves are generated and picked
In MovePicker we get the next move with pick_move_from_list(),
then check if the return value is equal to MOVE_NONE and
in this case we update the state to the new phase.

This patch reorders the flow so that now from pick_move_from_list()
renamed get_next_move() we directly call go_next_phase() to
generate and sort the next bunch of moves when there are no more
move to try. This avoids to always check for pick_move_from_list()
returned value and the flow is more linear and natural.

Also use a local variable instead of a pointer dereferencing in a
time critical switch statement in get_next_move()

With this patch alone we have an incredible speed up of 3.2% !!!

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-27 19:56:26 +01:00
Marco Costalba 129cde008c Disable again null move at depth == OnePly
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-26 16:59:58 +01:00
Joona Kiiski b088f0aefd Use special null move technique in low depth.
Try good captures before null move when depth < 3 * OnePly.
Use this kind of null move also in Depth == OnePly.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-26 16:30:39 +01:00
Joona Kiiski a5d699d62f Use nullMove only through MovePicker.
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-26 16:30:35 +01:00
Joona Kiiski f6d2452916 Add Null move support to MovePicker.
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-26 16:29:18 +01:00
Joona Kiiski 268c53ac51 Create useNullMove local variable
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-26 15:42:58 +01:00
Marco Costalba 595a90dfd0 Clean killers handling in movepicker
Original patch from Joona with added optimizations
by me.

Great cleanup of MovePicker with speed improvment of 1%

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-26 15:38:47 +01:00
Marco Costalba e217407450 Micro-optimze extension()
Explicitly write the conditions for pawn to 7th
and passed pawn instead of wrapping in redundant
helpers.

Also retire the now unused move_is_pawn_push_to_7th()
and the never used move_was_passed_pawn_push() and
move_is_deep_pawn_push()

Function extension() is so time critical that this
simple patch speeds up the pgo compile of 0.5% and
it is also more clear what actually happens there.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-25 15:11:05 +01:00
Marco Costalba 2078878376 Merge branch 'master' of git-Stockfish@free2.projectlocker.com:sf 2009-08-23 18:57:11 +01:00
Marco Costalba d1d4437699 Remove a local variable from pop_1st_bit()
Remove the 'b' uint32_t local variable.
Optimized assembly is more or less the same
(one 'mov' instruction less), but now it is
written in a way more similar to the final assembly
flow so it should be easier for compiler to optimize.

Also guarantee that BitTable[] is always aligned.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-23 18:55:07 +01:00
Marco Costalba ba04eb0446 Poly ampli+bias values after 73831 games
Verified correct against tuning branch.

After 999 games at 1+0

Mod vs Orig +257 =510 -232 51.20%  +9 ELO

Very small increase but an increase anyway !

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-23 18:51:01 +01:00
Tord Romstad ed347e7cbd Added a few new targets to the Makefile for OS X with icpc.
The following new targets were added:
   * osx-icc32: 32-bit x86 compiled with icpc.
   * osx-icc64: 64-bit x86 compiled with icpc.
   * osx-icc32-profile: 32-bit x86 compiled with icpc and pgo.
   * osx-icc64-profile: 64-bit x86 compiled with icpc and pgo.
2009-08-21 10:50:34 +02:00
Marco Costalba 95af1e28be Fix some asserts raised by is_ok()
There were two asserts.

The first was raised because is_ok() was called at the
beginning of do_castle_move() and this is wrong after
the last code reformatting because at that point the state
is already modified by the caller do_move().

The second, raised by debugIncrementalEval, was due to a
rounding error in compute_value() that occurs because
TempoValueEndgame was updated in an odd number by patch

"Merge Joona Kiiski evaluation tweaks" (3ed603cd) of 13/3/2009

This line in compute_value() is the guilty one:

result += (side_to_move() == WHITE)? TempoValue / 2 : -TempoValue / 2;

The fix is to increment TempoValueEndgame so to be even.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-20 17:48:52 +01:00
Tord Romstad e9aa20ad13 Fixed incorrect material key update when making promotion moves. 2009-08-20 16:54:20 +02:00
Marco Costalba e01fefbbaf More use of memset() in Position::clear()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-18 21:21:28 +01:00
Marco Costalba e4fc957898 Little do_move() micro optimizations
Also a few remaining style touches.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-18 08:58:19 +01:00
Marco Costalba 693b38a5e7 Better clarify how pieceList[] and index[] work
Rearrange the code a bit to be more self-documenting.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-17 23:15:35 +01:00
Marco Costalba fbec55e52e Unify patch series summary
This patch seems bigger then what actually is.

It just moves some code around and adds a bit of coding style fixes
to do_move() and undo_move() so to have uniformity of naming in both
functions.

The diffstat for the whole patch series is

239 insertions(+), 426 deletions(-)

And final MSVC pgo build is even a bit faster:

Before 448.051 nodes/sec

After 453.810  nodes/sec (+1.3%)

No functional change (tested on more then 100M of nodes)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-17 15:09:20 +01:00
Marco Costalba 05e70d6740 Unify undo_ep_move(m)
Integrate undo_ep_move in undo_move() this reduces line count
and code readibility.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-17 14:48:45 +01:00
Marco Costalba b4cb1a3a9e Unify undo_promotion_move()
Integrate do_ep_move in undo_move() this reduces line count
and code readibility.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-17 14:48:33 +01:00
Marco Costalba ec14fb1b33 Unify do_promotion_move()
Integrate do_promotion_move() in do_move() this reduces line count
and code readibility.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-17 14:48:20 +01:00
Marco Costalba cb506d3b16 Unify do_ep_move()
Integrate do_ep_move in do_move() this reduces line count
and code readibility.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-17 14:47:12 +01:00
Marco Costalba e0c47a6ceb L1/L2 friendly PhaseTable[]
In Movepicker c'tor we access during initialization one of
MainSearchPhaseIndex..QsearchWithoutChecksPhaseIndex globals.

Postpone definition of PhaseTable[] just after them so that
when PhaseTable[] will be accessed later in get_next_move()
it will be already present in L1/L2.

It works like an implicit prefetching of PhaseTable[].

Also shrink PhaseTable[] to fit an L1 cache line of 16 bytes
using uint8_t instead of int.

This apparentely innocuous patch gives an astonish speed
up of 1.6% under MSVC 2010 beta, pgo optimized !

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-15 16:09:10 +01:00
Marco Costalba f3d0b76feb Use optimized pop_1st_bit() under Windows 64 with icc
Intel compiler can handle this code even under Windows.

So lift the costrain.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-14 12:47:49 +01:00
Marco Costalba bfd4421f49 Better naming and document some endgame functions
In particular the generic scaling functions.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-14 08:19:55 +01:00
Marco Costalba fd12e8cb23 Finally fix prefetch on Linux
It was due to a missing -msse compiler option !

Without this option the CPU silently discards
prefetcht2 instructions during execution.

Also added a (gcc documented) hack to prevent Intel
compiler to optimize away the prefetches.

Special thanks to Heinz for testing and suggesting
improvments. And for Jim for testing icc on Windows.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-14 08:13:42 +01:00
Marco Costalba 166c09a7a0 Reuse 5 slots instead of 4
But this time with the guarantee of an always aligned
access so that prefetching is not adversely impacted.

On Joona PC
1+0, 64Mb hash:

Orig - Mod: 174 - 237 - 359

Instead after 1000 games at 1+0 with 128MB hash size
we are at + 1 ELO (just 4 games of difference).

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-14 08:13:13 +01:00
Marco Costalba 8d369600ec Double prefetch on Windows
After fixing the cpu frequency with RightMark tool I was
able to test speed all the different prefetch combinations.

Here the results:

OS Windows Vista 32bit, MSVC compile
CPU Intecl Core 2 Duo T5220 1.55 GHz
bench on depth 12, 1 thread, 26552844 nodes searched
results in nodes/sec

no-prefetch
402486, 402005, 402767, 401439, 403060

single prefetch (aligned 64)
410145, 409159, 408078, 410443, 409652

double prefetch (aligned 64) 0+32
414739, 411238, 413937, 414641, 413834

double prefetch (aligned 64) 0+64
413537, 414337, 413537, 414842, 414240

And now also some crazy stuff:

single prefetch (aligned 128)
410145, 407395, 406230, 410050, 409949

double prefetch (aligned 64) 0+0
409753, 410044, 409456

single prefetch (aligned 64) +32
408379, 408272, 406809

single prefetch (aligned 64) +64
408279, 409059, 407395

So it seems the best is a double prefetch at the addres + 32 or +64,
I will choose the second one because it seems more natural to me.

It is still a mystery why it doesn't work under Linux :-(

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-10 22:35:08 +01:00
Marco Costalba f4140ecc0c Avoid Intel compiler optimizes away prefetching
Without this hack Intel compiler happily optimizes
away the gcc builtin call.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-10 13:49:12 +01:00
Marco Costalba 60b5da4cc8 Use aligned prefetch address
Prefetch always form a chache line boundary. It seems
that if prefetch address is not cache line aligned then
performance is adversely impacted.

Hopefully we will resuse that 32 bits of padding for something
useful in the future.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-10 13:49:00 +01:00
Marco Costalba 55c46b2399 Remove old BishopPairBonus constants
Now that we have poly imbalance these ones
are no more used.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-10 13:47:39 +01:00
Marco Costalba 76ae0e36be Enable prefetch also for gcc
This fix a compile error under Linux with gcc when
there aren't the intel dev libraries.

Also simplify the previous patch moving TT definition
from search.cpp to tt.cpp so to avoid using passing a
pointer to TT to the current position.

Finally simplify do_move(), now we miss a prefetch in the
rare case of setting an en-passant square but code is
much cleaner and performance penalty is almost zero.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-10 01:42:35 +01:00
Marco Costalba 4251eac860 Try to prefetch as soon as position key is ready
Move prefetching code inside do_move() so to allow a
very early prefetching and to put as many instructions
as possible between prefetching and following retrieve().

With this patch retrieve() times are cutted of another 25%

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-09 16:45:37 +01:00
Marco Costalba cd4604b05c Add TT prefetching support
TT.retrieve() is the most time consuming function
because almost always involves a very slow RAM access.

TT table is so big that is never cached. This patch
prefetches TT data just after a move is done, so that
subsequent TT.retrieve will be very  fast.

Profiling with VTune shows that TT:retrieve() times are
almost cutted in half !

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-09 14:18:15 +01:00
Marco Costalba e6863f46de Use 5 TTEntry slots instead of 4
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-09 04:42:26 +01:00
Marco Costalba 6f1475b6fc Use 32 bit key in TT
Shrink key to 32 bits instead of 64. To still avoid
collisions use the high 32 bits of position key as the
TT key and the low 32 bits to retrieve the correct
cluster index in the table.

With this patch size og TTentry shrinks to 96 bits instead
of 128 and the cluster of 4 TTEntry sums to 48 bytes instead
of 64.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-09 04:42:07 +01:00
Marco Costalba 4a777954e1 Makefile: added 'make strip' target
Binaries are always built with symbol table in to easy
debugging and profiling.

It is now possible to run:

make strip

To remove symbol table from the compiled binary. This
could be useful to prepare the release version.

Patch by Heinz van Saanen.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-08 17:37:13 +01:00
Marco Costalba 54382f8b07 Let LMR at root be independent of MultiPV value
Current formula enable LMR when

i + MultiPV >= LMRPVMoves

It means that, for instance, if MultiPV == 1 then LMR
will be started to be considered at move i = LMRPVMoves - 1,
while if MultiPV == 3 then it will start before,
at move i = LMRPVMoves - 3.

With this patch the formula becomes

i >= MultiPV + LMRPVMoves - 2

So that LMR will always start after LMRPVMoves - 1 moves
from the last PV move.

No functional change when MultiPV == 1

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-08 17:30:46 +01:00
Marco Costalba 339bb8a524 Speed up polynomial material imbalance loop
Access pos.piece_count() only once and avoid some
branches in the inner loop.

Profiling with VTune shows a 20% speed improvement in
get_material_info(), and it is also a bit more cleaned
up this way ;-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-08 14:12:04 +01:00
Marco Costalba aa925a0e29 There is no need to special case KNNK ending
It is always draw, so use the corresponding proper
evaluation function.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-08 13:10:10 +01:00
Marco Costalba 23ceb66950 Move halfOpenFiles[] calculation out of a loop
And put it in an already existing one so to
optimze a bit.

Also additional cleanups and code shuffles
all around the place.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-08 09:21:42 +01:00
Marco Costalba 565d12bf42 Compile without DEBUG flag by default
And build also symbol table. It can easily stripped
after .exe is done and it is necessary for profiling.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-08 09:21:29 +01:00
Marco Costalba 00eab73399 Revert material balance values after 100000 games
After Joona's direct testing with ~2000 games it seems
values after 100.000 games does not give any advantage,
so revert for now.

Score of Stockfish_0 vs Stockfish_15: 491 - 392 - 1102
Score of Stockfish_0 vs Stockfish_40: 461 - 439 - 1076
Score of Stockfish_0 vs Stockfish_65: 442 - 518 - 1018 (13 elo)
Score of Stockfish_0 vs Stockfish_100: 504 - 502 - 984

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-08 03:49:49 +01:00
Joona Kiiski 5be3d98d17 Do not adjust Minimum Split Depth automatically
Currently minimum split depth is set automatically to 6
when number of CPUs is more than 4. I believe this is a bad
idea since for example my quad (4CPU with hyperthreading) is
detected as 8CPU computer. I've manually lowered down the number
of Threads, but so far I have played all games with Minimum
Split Depth set to 6!

Since 4CPU computers with hyperthreading are quite common and
8 CPU computers extremely rear (I expect we can get a direct
jump to 16 or 32 cores), this automatic adjusting is likely
to do more harm than good. Add a note in Readme.txt, so that
those rear 8CPU owners can manually tweak the "Minimum Split
Depth" parameter

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-08 03:36:20 +01:00
Marco Costalba 5b3fcab1ad Polished Makefile for *nix
Greately improved Makefile from Heinz van Saanen

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-08-08 03:30:27 +01:00
Tord Romstad 977ca40d6d Supply the "upperbound" and "lowerbound" parameters in UCI search
output when the score is outside the root window.
2009-08-07 16:26:24 +02:00
Tord Romstad ae49677446 Fixed a bug in PV extraction from the transposition table: The
previous used move_is_legal to verify that the move from the TT
was legal, and the old version of move_is_legal only works when
the side to move is not in check. Fixed this by adding a separate,
slower version of move_is_legal which works even when the side to
move is in check.
2009-08-06 18:07:32 +02:00
Tord Romstad 2fff532f4e Moved the code for extracting the PV from the TT to tt.cpp, where
it belongs.
2009-08-06 14:02:53 +02:00
Tord Romstad da854fe83a Added a new function build_pv(), which extends a PV by walking
down the transposition table.

When the search was stopped before a fail high at the root was
resolved, Stockfish would often print a very short PV, sometimes
consisting of just a single move. This was not only a little
user-unfriendly, but also harmed the strength a little in
ponder-on games: Single-move PVs mean that there is no ponder
move to search.

It is perhaps worth considering to remove the pv[][] array
entirely, and always build the entire PV from the transposition
table. This would simplify the source code somewhat and probably
make the program infinitesimally faster, at the expense of
sometimes getting shorter PVs or PVs with rubbish moves near
the end.
2009-08-06 13:27:49 +02:00
Tord Romstad a1096e55cf Initial work towards adjustable playing strength.
Added the UCI_LimitStrength and the UCI_Elo options, with an Elo
range of 2100-2900. When UCI_LimitStrength is enabled, the number
of threads is set to 1, and the search speed is slowed down according
to the chosen Elo level.

Todo:

1. Implement Elo levels below 2100 by blundering on purpose and/or
   crippling the evaluation.
2. Automatically calibrate the maximum Elo by measuring the CPU speed
   during program initialization, perhaps by doing some bitboard
   computations and measuring the time taken.

No functional change when UCI_LimitStrength is false (the default).
2009-08-04 11:31:25 +02:00
Tord Romstad dad632ce5b Added LMR at the root.
After 2000 games at 1+0

Mod vs Orig +534 =1033 -433 52.525%  1050.5/2000  +18 ELO
2009-08-03 09:08:59 +02:00
Joona Kiiski 2f7723fd44 Remove useless mate value special handling in null search
After 1200 games (1CPU), time control 1+0:

Mod vs Orig: +331 =564 -277  +16 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-26 18:55:17 +01:00
Marco Costalba 152f3b13b7 Yet another small touch to endgame functions handling
It is like a never finished painting. Everyday a little touch
more.

But this time it is very little ;-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-26 17:42:48 +01:00
Marco Costalba bb1b049b83 Remove unused members in Application class
Also rearrange a bit the remining methods.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-26 16:11:20 +01:00
Marco Costalba 50f92bed06 Fix a spurious extra space
This morning it seems there is nothing better to do...

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-26 09:07:42 +01:00
Marco Costalba bdb586ac2b Micro optimize extension() in search.cpp
Small micro-optimization in this very
time critical function.

Use bitwise 'or' instead of logic 'or' to avoid branches
in the assembly and use the result to skip an handful of checks.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-25 16:48:28 +01:00
Marco Costalba 1b0303b6e9 Polynomial material balance after 100.000 games
Verified it is equivalent to the tuning branch results
with parameter values sampled after 100.000 games.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-24 14:26:49 +01:00
Marco Costalba 5f232e0667 Revert Makefile changes
Some unwanted changes to Makefile slept in in patch
"Introduced the UCI_AnalyseMode option".

Revert them. No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-24 14:18:03 +01:00
Marco Costalba 080a4995a3 Simplify king shelter cache handling
This is more similar to how get_material_info() and
get_pawn_info() work and also removes some clutter from
evaluate_king().

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-24 14:13:13 +01:00
Marco Costalba 20224a5bbf Delay costly SEE call during captures ordering in MovePicker
When ordering moves we push all captures with negative SEE values
to badCaptures[] array during the scoring phase.

This patch delays the costly SEE call up to when the move has been
picked up in pick_move_from_list(), this way we save some SEE calls
in case we get a cutoff.

It seems we have a speed gain of about 1-1.5 % in terms of nodes/sec
and profiling seems to confirm the small but real speed increase.

Idea from Pablo Vazquez on talkchess.com
http://www.talkchess.com/forum/viewtopic.php?t=29018&start=20

It would be a no functional change but actually it is not because
now sorting set is different and so std::sort(), that is not a
stable sort, does not guarantees the order of same scored moves to
remain the same as before.

After 952 games at 1+0 we are below error bar, almost equal just
6 games of difference (+2 ELO)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-24 14:12:33 +01:00
Marco Costalba 8654fee18c Microptimization in do_evaluate()
Do not call count_1s_max_15() if not necessary, as is
not in the common case (>95%).

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-23 22:01:42 +01:00
Marco Costalba 8b45b60327 Use do_move_bb() helpers when doing a castle
Small cleanup.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-23 10:43:58 +01:00
Marco Costalba 044ad593b3 Add Tord's polynomial material balance
Use a polynomial weighted evaluation to calculate
material value.

This is far more flexible and elegant then applying
a series of single euristic rules as before.

Also correct a design issue in which we returned two
values, one for middle game and one for endgame, while
instead, because game phase is a function of board
material itself, only one value should be calculated and
used both for mid and end game.

Verified it is equivalent to the tuning branch results with
parameter values sampled after 40.000 games.

After 999 games at 1+0

Mod vs Orig +277 =482 -240 51.85%  518.0/999  +13 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-23 00:03:30 +01:00
Marco Costalba 5600d91cff Rename int32 in int32_t
To use the same naming rule of the other types and
to be compatible with inttypes.h, used under Linux.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-20 10:53:41 +01:00
Marco Costalba 1cc44bcaae Correctly set mateThreat in search()
We do not accept null search returned mate values,
but we always do a full search in those cases.

So the variable mateThreat that is set only if null move
search returns a mate value is always false.

Restore the functionality of mateThreat moving the
assignement where it can be triggered.

After 999 games at 1+0

Mod vs Orig +253 =517 -229 51.20%  +8 ELO

Bug reported by xiaozhi

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-20 08:05:48 +01:00
Marco Costalba 15eb59683e Use increased LMR horizont also in PV search
Tord says that using a lower horizon at PV nodes
looks strange and inconsistent with the general
philosophy of our search (i.e. always being more
conservative at PV nodes). So set LMR at 3 also
on search_pv().

Test result after 601 games seems to confirm this.

Mod vs Orig +156 =318 -127 52.41%  315.0/601  +17 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-18 12:47:37 +02:00
Marco Costalba 620cfbb676 Reintroduce null move dynamic reduction
Test extension of LMR horizon to 3 plies alone, without
touching null move search. To keep the patch minimal we still
don't change LMR horizon in PV search. This will be the object
of the next patch.

Result seems good after 998 games:

Mod vs Orig  +252/=518/-228 51.20%  511.0/998 +8 ELO

So dynamic null move reduction seems a bit stronger then
fixed reduction even with LMR horizon set to 3.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-18 06:08:06 +01:00
Marco Costalba fe523b2d18 Use increased LMR horizont only after a null move
Revert to LMR horizont of 2 plies. Only if parent move
is a null move increase to 3 so to avoid the bad combination
of null move reduction + LMR reduction. This is a more
aggressive patch then previous one, but it seems we are
going in the wromg direction.

After 531 games result is not good:

Mod vs Orig  +123/=265/-143 48.12%  255.5/531  -13 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-18 06:08:02 +01:00
Marco Costalba 2a203d8d6f Combine increased LMR horizont and fixed null move reduction
Set null move reduction to R=4, but increase the LMR horizon
to 3 plies. The two tweaks are related and should compensate
the combined effect of null move + LMR reduction at shallow
depths.

Idea from Tord.

After 999 games at 1+0

Mod vs Orig  +251 =522 -225 51.30% + 9 ELO

On Tord iMac Core 2 Duo 2.8 GHz, one thread,
Mac OS X 10.6, at 1+0 time control we have:

Mod vs Orig 994-1006  -1.4 ELO

But Orig version is pgo compiled and Mod is not.
The PGO compiled version is about 8% faster, which
corresponds to about 7 Elo points. This means that
results are reasonably consistent.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-18 06:07:58 +01:00
Tord Romstad b8326edea3 Introduced the UCI_AnalyseMode option, and made the evaluation function
symmetrical in analyse mode.

No functional change when playing games.
2009-07-17 22:26:01 +02:00
Marco Costalba 20e8738901 Fix two compile errors in new endgame code
Code that compiles cleanly under MSVC triggers one
compile error (correct) under Intel C++ and two(!)
under gcc.

The first is the same complained by Intel, but the second
is an interesting corner case of C++ standard (there are many)
that is correctly spotted only by gcc.

Both MSVC and Intel pass this silently, probably to avoid
breaking people code.

Now we are fully C++ compliant ;-)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-17 19:29:25 +01:00
Marco Costalba b3b1d3aaa7 Move constant bitboard arrays from header to cpp file
This avoid to duplicate storage allocation for every file
where they are used.

Note that simple numeric constant can remain in header because
are automatically folded by the compiler.

Patch suggested by Tord.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-17 16:25:53 +01:00
Marco Costalba 0d69ac33ff Remove even more redundancy in endgame functions handling
Push on the templatization even more to chip out some code
and take the opportunity to show some neat template trick ;-)

Ok. I would say we can stop here now....it is quickly becoming
a style exercise but we are not boost developers so give it a stop.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-17 16:05:19 +01:00
Tord Romstad 342c8c883c Removed an incorrect assert() statement in search.cpp, which asserted that
a static eval cached in the transposition table would always equal the static
eval of the current position. This is in general not true, because the cached
value could be from a previous search with different evaluation parameter
settings, or from a search from the opposite side (Stockfish's evaluation
function is assymmetric by default).
2009-07-17 09:12:59 +02:00
Marco Costalba 297c12e595 Simplify endgame functions handling
We really don't need to have global endgame functions. We can
allocate them on the heap at initialization time and store the
corresponding pointer directly in the functions maps. To avoid
leaks we just need to remember to deallocate them in map d'tor.

These functions are always created in couple, one for each color,
so remove a lot of redundant hard coded info and just use the minimum
required: the type and the corresponding named string.

This greatly simplifies the code and also it is less error prone,
now is much simpler to add a new endgame specialized function: just
add the corresponding enum in endgame.h and the obvious add_xx()
call in EndgameFunctions c'tor, and of course, the most important part,
the EvaluationFunction<xxx>::apply() specialization in endgame.cpp

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-17 07:55:51 +01:00
Tord Romstad 5c20f59788 Renamed the variable 'looseOnTime' to 'loseOnTime', because I'm a pedant.
No functional change.
2009-07-15 11:01:49 +02:00
Marco Costalba ea06200423 Remove "Last seconds noise" filtering UCI option
This feature makes sense during development, but
It doesn't seem to make sense for normal users.

Also fix a possible race where the GUI adjudicates
the game a fraction of second before the engine sets
looseOnTime flag so that it will bogusly waits until
it ran out of time at the beginning of the next new game.

The fix is to always reset looseOnTime at the beginning
of a new game.

Race condition spotted by Tord.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-15 08:35:00 +01:00
Marco Costalba 3849beb979 Introduce SERIALIZE_MOVES_D() macro and use it for pawn moves
This is another moves serialization macro but this time
focused on pawn moves where the 'from' square is given as
a delta from the 'to' square.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-14 10:28:41 +01:00
Marco Costalba 20ed03fc0b Micro optimize pawn moves generation
It is very rare we have pawns on 7(2) rank, so we
can skip the promotion handling stuff in most cases.

With this patch pawn moves generation is almost 20% faster.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-14 10:28:29 +01:00
Marco Costalba 2a461b4b74 Introduce see_sign() and use it to shortcut full see()
Mostly of times we are interested only in the sign of SEE,
namely if a capture is negative or not.

If the capturing piece is smaller then the captured one we
already know SEE cannot be negative and this information
is enough most of the times. And of course it is much
faster to detect then a full SEE.

Note that in case see_sign() is negative then the returned
value is exactly the see() value, this is very important,
especially for ordering capturing moves.

With this patch the calls to the costly see() are reduced
of almost 30%.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-12 08:37:43 +01:00
Marco Costalba 6f39a3fc80 Move some global variables to local scope in search.cpp
Some variables were global due to some old and now removed code,
but now can be moved in local scope.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-12 08:37:43 +01:00
Marco Costalba 7eefc1f6cc Joona tweaks of Weights and limits
Verification test give unusless result

After 999 games at 1+0
Mod vs Orig +250 =503 -246 50.20% +1 ELO

So we are well below our radar level. Neverthless
there are 100.000 games on Joona QUAD that we could
take in account and that shows that this tweak perhaps
has something good in it, altough very little.

Verification tests shows should not be a regression, at
least not a big one even in the worst case, so apply the
change anyway and keep the finger crossed ;-)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-12 08:37:28 +01:00
Marco Costalba 7622793080 Small tidy up of previous patch
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-10 18:50:43 +01:00
Tord Romstad 174b40c28d Strip whitespace from beginning of string sent to set_option_value().
It turned out that the input sent to set_option_value() when it is called by
set_option() in uci.cpp always started with at least one whitespace. In most
cases, this is not a problem, because the majority of UCI options have numeric
values. It did, however, cause a problem for UCI options with non-numerical
values, like options of type CHECK and COMBO. In particular, changing the
value of an option of type CHECK didn't work, because the comparisons with
"true" and "false" would always return false. This means that the "Ponder"
and "UCI_Chess960" options haven't been working for a while.
2009-07-10 18:34:56 +02:00
Marco Costalba 03f524c591 Revert last tweaks
Tests show no improvment, so revert for now.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-09 16:45:39 +01:00
Marco Costalba 3444b94735 Joona tweaks of tempos and misc parameters
Unfortunatly this tweak does not give good results.

After 894 games at 1+0 we have:

Mod vs Orig  +205/-236/=453 48.27%  -12 ELO !!

Perhaps we should test again, but in the mean time
we are going to revert this.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-09 16:45:17 +01:00
Marco Costalba 2693db616d Restore development versioning and LSN filtering
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-06 11:20:05 +01:00
Marco Costalba a5fce1958b Fix generation of check blocking promotion
A promotion move is not considered a possible evasion as it could be.

Bug introduced by patch

Convert also generate_pawn_blocking_evasions() to new API (7/5/2009)

Bug spotted by Kenny Dail.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-06 09:41:22 +01:00
Marco Costalba 67ac358ef2 Stockfish 1.4
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-04 21:57:12 +01:00
Marco Costalba 341f42be8c Small Makefile tweaks
Set gcc as default compiler on Linux, also compile
with symbols stripped to shrink binary file.

Original patch by Heinz van Saanen.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-04 21:56:59 +01:00
Marco Costalba 72ab2cd3e9 Fix bitcount.h compile warnings under Intel compiler
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-04 18:10:39 +01:00
Marco Costalba 92b625d04f Check Intel compiler before MSVC in bitcount.h
Predefined macro __INTEL_COMPILER is defined only for Intel,
while _MSC_VER is defined for both Intel C++ and MSVC.

So rearrange ifdefs to take in account this and test __INTEL_COMPILER
first and only if not defined check _MSC_VER for MSVC.

Patch suggested by Joona.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-04 18:03:49 +01:00
Marco Costalba 2b32571de8 Add support for saving timing file during benchmark
Add a new argument to bench to specify the name of the
file where timing information will be saved for each
benchmark session.

This argument is optional, if not specified file will
not be created.

Original patch by Heinz van Saanen

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-04 10:32:51 +01:00
Marco Costalba 36437f14e8 Disable POPCNT support per default
This is mainly intended to allow 64 bit compiles on any
system and avoid to crash when the binary, compiled on a
box where POPCNT is not supported, is run on a Core i7
system or similar CPU.

What could happen is that when compiled in a standard 64 bit
system, because the correct headers for the POPCNT intrinsic
are not found, the compiler creates dummy bit count functions
instead, these are never called at runtime on the machine where
Stockfish has been compiled. But if we run the same binary on a
Core i7 system, because POPCNT is detected at run time, the dummy
bitcount functions will be called giving false results that will
crash the application.

Note that would be possible to fallback on software bit count in
these cases, but this is even more subtle because POPCNT path is not
optimized so that we have an application working but at sub-optimal
speed, so better to crash, at least user is loudly warned that there
is something wrong.

If, instead, Stockfish is compiled on a Core i7 system with POPCNT
enabled, then if the PGO compile has been done properly, the same binary
will run at optimal speed _both_ on the Core i7 machine and on any other
64 bit standard machine. This is the ideal mode for binary distribution.

Finally this patch disables bsfq support under Windows, because it seems
inline assembly is not supported both by MSVC and by Intel Windows version.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-04 09:20:28 +01:00
Marco Costalba 08f3aac97c Do not compile POPCNT if NO_POPCNT is defined
Also rename DISABLE_POPCNT_SUPPORT in NO_POPCNT and simplify a bit
the macro logic.

Always define a __popcnt64()or _mm_popcnt_u64() template, if the proper
function with the same name is defined in the intrinsics header, then it
will be choosen as first otherwise we fall back on the dummy template
that is never called at runtime anyway because cpu_has_popcnt() returns
false.

This fixes the compile error reported by Jim.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-04 09:18:17 +01:00
Marco Costalba 48b0d41220 Microptimize pawns info access
Avoid indirect calling of piece_of_color_and_type(c, PAWN) and its
alias pawns(c) in the pawn evaluation loop, but use the pawns
bitboards accessed only once before entering the loop.

Also explicitly mark functions as static to better self-document.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-03 13:11:32 +01:00
Marco Costalba 5d79af9e0d Restore correct 64 bit version of pop_1st_bit()
Was erroneusly changed with the 32bit in recent
patch "Retire USE_COMPACT_ROOK_ATTACKS...".

Also another clean up of define magics. Move compiler
specific definitions in types.h and remove redundant cruft.

Now this macro ugly mess seems more reasonable.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-03 10:18:20 +02:00
Marco Costalba a87ea9846d Use bsfq asm instruction to count bits
On 64 bit systems we can use bsfq instruction to count
set bits in a bitboard.

This is a patch for GCC and Intel compilers to take advantage
of that and get a 2% speed up.

Original patch from Heinz van Saanen, adapted to current tree
by me.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-03 10:18:14 +02:00
Marco Costalba 063e2441b1 Retire USE_COMPACT_ROOK_ATTACKS and USE_FOLDED_BITSCAN defines
This greatly simplifies bitboard.cpp that now has only two setups,
respectively for 32 and 64 bits CPU according to IS_64BIT define
that is automatically set but can be tweaked manually in
bitboard.h

No functional change both in 32 and in 64 bits.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-03 07:52:10 +01:00
Marco Costalba b45936a8c7 Revert per-thread history tables
Testing on Joona QUAD failed to give any
advantage. Actually we had a little loss:

Mod - Orig: 342.0 - 374.0

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-02 06:29:25 +01:00
Marco Costalba d39ddb9077 Joona tweaks of piece values
This is the backport of tuned piece values.

We needed to change also the psqt tables so that their
values, that are relative to piece values, remain the same.

Amost no change after 999 games:

Mod vs Orig 594-495 + 2 ELO points so well within error bar

It was expected somehow given the very little change of the
parameters values.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-07-02 06:29:14 +01:00
Marco Costalba bbb2462576 Explicitly use delta psqt values when possible
Instead of add and subtract pqst values corrisponding to
the move starting and destination squares, do it in one
go with the helper function pst_delta<>()

This simplifies the code and also better documents that what
we need is a delta value, not an absolute one.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-28 06:30:13 +02:00
Marco Costalba d9e3be4790 Joona tweaks of pawns parameters
Test result after 999 games at 1+0

Mod vs Orig +278 =493 -228 52,50% +17 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-26 10:17:47 +02:00
Marco Costalba 36c0ab3a50 Fix compile errors in debug mode
Fall out of move_promotion() rename

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-20 19:18:00 +01:00
Marco Costalba ad4eac376f Use POPCNT in evaluate_space() when available
This was forgotten by the POCNT patches.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-20 14:45:11 +01:00
Marco Costalba 657286b0e5 Fix a couple of warnings under Intel compiler
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-20 14:45:03 +01:00
Marco Costalba 3a4d6e2034 Micro optimize and rename move_promotion()
Rename to move_is_promotion() to be more clear, also add
a new function move_promotion_piece() to get the
promotion piece type in the few places where is needed.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-20 09:04:32 +01:00
Marco Costalba b1e79fed99 Only on Windows do wait for input at the end of benchmark
Under MS Visual C++ debug window always unconditionally closes
when program exits, this is bad because we want to read results before.

So limit this kludge on Windows only.

Original patch by Heinz van Saanen.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-20 09:04:20 +01:00
Marco Costalba 190f88e532 Skip castle rights update when not needed
Micro optimization in do_move(), a quick check
avoid us to update castle rights in almost 90%
of cases.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-18 17:23:35 +01:00
Joona Kiiski 8acb1d7e4d Disable use of aspiration window in known win positions
When we are hunting for mate, transposition table is filled in
with mate scores. Current implemenatation of aspiration search
can't cope with this very well.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-18 07:35:24 +01:00
Joona Kiiski 46c0bdb74f Bugfix: KRK was not classified as KNOWN_WIN
Problem is that npMaterial is compared to _endgame_ value
of rook, although npMaterial is always (also in endgame!)
calculated using _middlegame_ values.

Bug was hidden as long as Rook middlegame
and endgame values were same.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-18 07:35:24 +01:00
Marco Costalba 8225fdd5bb Give proper credit to Joona
Stockfish would not be as where is now without his
contributions.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-18 07:35:23 +01:00
Marco Costalba e3c02d231a Joona tweaks of mobility and outposts bonus
These are the tuned values of mobility and outposts
after 100.000 games on Joona QUAD.

After 999 games at 1+0
Mod vs Orig +248 =537 -214 51.70% +12 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-18 07:35:08 +01:00
Marco Costalba 9847adf19f Fix king value in SEE
When SEE piece values changed in aaad48464b
of 9/12/2008 we forgot to update the value assigned in
case of captured king.

In that patch we changed the SEE piece values but without
proper testing. Probably it is a good idea to make some
tests with the old Glaurung values.

Bug spotted by Joona.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-16 19:22:22 +01:00
Marco Costalba 630fda2e2c Reduce SMP contention on TT
Move TT object away from heavy write accessed NodesSincePoll
and also, inside TT isolate the heavy accessed writes variable.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-13 11:13:09 +01:00
Marco Costalba 8bec65029d Better clarify why recent generate_pawn_checks() works
We can have false positives, but these are filtered out
anyhow by following conditions so they are harmless.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-12 13:12:42 +02:00
Marco Costalba b5685fc564 Code style triviality in search.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-12 13:12:23 +02:00
Marco Costalba d2c2af9e1c Remove global variables from search.h
Globals are not really needed, so redefine as locals.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-12 13:10:40 +02:00
Marco Costalba 3e0753bef3 MovePicker doesn't need to know if called from a pv node
This was needed by an old optimization in sorting of
non-captures that is now obsoleted by new std::sort()
approach.

Remove also the unused depth member data. Interestingly
this has always been unused since the Glaurung days.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-12 13:10:02 +02:00
Marco Costalba c7843f2f79 Joona tweaks of piece-square tables
These are the tuned psqt values after 100.000 games
on Joona QUAD. Results seem very good.

On PC 1 after 999 games
Mod vs Orig  +261 =511 -227 51.70 %  +12 ELO

On PC 2 after 913 games
Mod vs Orig  +254 =448 -211 52.35 %  +16 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-12 13:00:18 +02:00
Marco Costalba 9005ea6339 Move initialization of PawnInfo in its c'tor
Where it belongs.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-08 12:53:38 +01:00
Marco Costalba 6d117e4a23 Move initialization of MaterialInfo in its c'tor
Where it belongs.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-08 11:27:50 +01:00
Marco Costalba b8ab5d533b Micro optimize pretty_pv
Creating an History object requires clearing the History tables,
although fast is an useless job in san.cpp where History is used
just as a dummy argument for MovePicker c'tor.

So use a file scoped constant instead of creating a new History()
object each time MovePicker c'tor is called as in move_ambiguity()

This optimizes pretty_pv() through the following calling chain:
pretty_pv() -> line_to_san() -> move_to_san() -> move_ambiguity()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-08 10:52:03 +01:00
Marco Costalba bbd3e30b4e Give credit to Joona for optimized parameters
This also allow us to better track what is already
optimized and what still needs optimization.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-05 15:07:36 +01:00
Marco Costalba e41602b721 Use a specialized function for king evaluation
King evaluation is special in any case and as an added
benefit we can use the HasPopCnt optimization also for king.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-05 15:07:26 +01:00
Marco Costalba 48c95706c8 Split evaluate_outposts from evaluate_common
This is an old patch, was part of a series, but is
good also alone as a cleanup.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-03 17:38:42 +01:00
Marco Costalba 2f760cdf8d Document variables with heavy SMP read access
Also move NodesSincePoll away from the same cache line
of other heavy read accessed only variables.

Fortunatly we don't have anymore write access contention,
but still read access contention in some cases.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-03 17:36:50 +01:00
Marco Costalba b58ecb85c7 Retire UseQSearchFutilityPruning and UseFutilityPruning
They are always true anyway and are heavy used file scope
variables where there could be SMP contention. Although read only.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-03 17:35:56 +01:00
Marco Costalba b4a04d8038 Use one History table per thread
This reduces contention and reduce history trashing
effect especially at high search depths.

No functional change for single CPU case.

After 999 games at 1+0 on Dual Core Intel we have

Mod vs Orig  +233 =526 -240  -2 ELO

We need to test at longer time controls and possibly with
a QUAD where we could foreseen an improvment.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-03 17:34:35 +01:00
Marco Costalba c1b60269a2 Convert History table H in a local variable
This is a first step for future patches and in
any case seems a nice thing to do.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-02 09:57:15 +01:00
Marco Costalba e1ed67aacb Avoid using EmptySearchStack global
This reduces contention in SMP case and also
cleanups the code a bit.

No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-06-02 09:35:49 +01:00
Marco Costalba 5b1316f7bb Detach the state when copying a position
In Position we store a pointer to a StateInfo record
kept outside of the Position object.

When copying a position we copy also that pointer so
after the copy we have two Position objects pointing
to the same StateInfo record. This can be dangerous
so fix by copying also the StateInfo record inside
the new Position object and let the new st pointer
point to it. This completely detach the copied
Position from the original one.

Also rename setStartState() as saveState() and clean up
the API to state more clearly what the function does.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-29 17:23:21 +02:00
Marco Costalba bafb9f1a25 Order bad captures by SEE value
We have already calculated it, so just sorting the
moves adds a very little overhead.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-29 08:31:13 +02:00
Marco Costalba 738bf66a2d Passed pawns evaluation tweak
Do not penalize if in our adavncing pawn's path there are
non-pawns enemy pieces. Especially if they can be attacked
by us.

Patch is mine, but original idea and also fixing of a first, wrong,
version of the patch is from Eelco de Groot.

Tests with Joona framework seems to confirm patch is good

Results for patch 'disabled'   based on 5776 games: Win percentage:
41.309  (+- 0.526)  [+- 1.053]
Results for patch 'enabled'  based on 6400 games: Win percentage:
42.422  (+- 0.500)  [+- 1.000]

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-29 08:30:58 +02:00
Marco Costalba 3d0b60b065 Merge hardware POPCNT detection and use
Tests on Joona luxury iCore7 QUAD show that speed increase
against standrd 64bit routine is between 3% and 4%.

So it seems a good thing to have. Also the user feedback at
startup regarding the compile and the hardware detection can
be an useful debug tool.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-25 07:56:26 +01:00
Marco Costalba bdb1bfecfb Split killer moves from non-captures
In MovePicker consider killer moves as a separate
phase from non-capture picking.

Note that this change guarantees that killer1 is always
tried before killer2. Until now, because scoring difference
of the two moves was just 1 point, if psqt tables of killer1
gave a lower value then killer2, the latter was tried as first.

After 999 games at 1+0 we have
Mod vs Orig: +245 =527 -227 +6 ELO

Not a lot but patch is anyhow something worth to have.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-25 07:49:50 +01:00
Marco Costalba f1591447cf Revert _BitScanForward64 support
It shows almost no improvment and adds a good
bunch of complexity.

So remove for now. No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-25 07:28:55 +01:00
Marco Costalba d63ff85a43 Add a bit more pop_1st_bit<HasBSF> conversions
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-24 10:25:59 +01:00
Marco Costalba 76024ac40e Use compiler name lookup to simplify code
We don't need different names between a function and a
template. Compiler will know when use one or the other.

This let use restore original count_1s_xx() names instead of
sw_count_1s_xxx so to simplify a bit the code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-24 10:18:31 +01:00
Marco Costalba 6c9a64124a Enable _BitScanForward64 in move generation
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-24 10:07:03 +01:00
Marco Costalba f90f810ac4 Enable _BitScanForward64 at runtime
Only add infrastructure, still disabled.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-24 09:46:43 +01:00
Marco Costalba ce5d9eb19d Print info about use of 64bit functions and hardware POPCNT
With this patch at the applications startup a line is printed
with info about use of optimized 64 bit routines and hardware
POPCNT.

Also allow the possibility to disable POPCNT support during
PGO compiles to exercise the fallback software only path.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-23 16:12:26 +01:00
Marco Costalba 628f844c11 Fix compile errors under MSVC
Fallback from previous patches.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-21 17:08:34 +01:00
Marco Costalba c729e4e1ab Forgot two conversion to new POPCNT interface
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-21 16:50:19 +02:00
Marco Costalba 0228ff9ca0 Add temporary debug info on POPCNT support
To be removed before to release.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-21 16:42:07 +02:00
Marco Costalba e7d3a006cd Enable POPCNT at runtime
Runtime detect POPCNT instruction support and
use it.

Also if POPCNT is not supported we don't add _any_ overhead so
that we don't lose any speed in standard case.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-21 16:41:31 +02:00
Marco Costalba 3376c68f4b Introduce bitcount.h
It will be used for POPCNT intrinsics.

For now no bianry and functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-21 16:19:20 +02:00
Marco Costalba 1b0888708d Unify piece_attacks<> for KNIGHT and KING
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-21 12:15:52 +02:00
Marco Costalba 229274546f Use do_move_bb() also for en passant moves
Unfortunatly, due to Chess960 compatibility we cannot
extend also to castling where the destinations squares
are not guaranteed to be empty.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-21 11:28:51 +02:00
Marco Costalba 3e40bd0648 Introduce do_move_bb() to update bitboards after a move
Avoid a clear_bit() + set_bit() sequence but update bitboards
with only one xor instructions.

This is faster and simplifies the code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-21 10:55:23 +02:00
Marco Costalba 595c7d75a2 Backup some mor einfo in do_null_move()
Faster undo_null_move()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-21 09:54:48 +02:00
Marco Costalba 5603e25a7f Move npMaterial[2] to StateInfo in Position
So to have a bit faster undo_move() and also
a code semplification.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-21 09:47:03 +02:00
Marco Costalba 20c2a31464 Retire lastMove from Position class
Is not used in any way so remove.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-20 15:46:16 +02:00
Marco Costalba d3c4618b3a Small code style in headers
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-20 15:11:41 +02:00
Marco Costalba b98bcf858b Directly relate HistoryMax to OnePly
This obsoletes some remainding comments.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-20 14:43:17 +02:00
Marco Costalba 3b1e64ab72 Small code style massage in uci.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-20 12:40:07 +02:00
Marco Costalba 72ecd9e20d Space inflate and cleanup direction.cpp
Hopefully it is now more clear what's happening here.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-20 12:02:39 +02:00
Marco Costalba 25286e9932 Reduce history 4 times instead of 2 when reach the maximum
This gives more weight to newer entries.

After 999 games at 1'+ 0" we have:

Mod vs Orig +233/-208/=558 51.25% +9 ELO

Confirmed by another session of 437 games:

Mod vs Orig +109/-92/=236 51.95% +14 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-20 09:03:15 +02:00
Marco Costalba 4f7ec4128f Retire count_1s_8bit()
Use the plain array lookup in the only place where it
is used. This remove an unecessary indirection and better
clarifies what code does.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-19 15:49:54 +01:00
Marco Costalba 1e4472b651 Small code style triviality in evaluation
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-19 15:41:45 +01:00
Marco Costalba da579e46b7 Remove hardcode default values of UCI variables from evaluation
This is the same change we have already done in search.cpp,
this time for evaluation.cpp

If a variable will be populated reading an UCI option
then do not hard code its default values.

This avoids misleadings when reading the sources.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-19 15:35:12 +01:00
Marco Costalba f83b899f39 Cache king shelter info in pawns structure
It does not change often and is not so fast
to calculate.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-17 10:23:24 +01:00
Marco Costalba a75aa6035b Move beta counter variables to the per-thread data
This should reduce concurrent accessing in SMP case.

Suggestion by Tord Romstad.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-16 12:25:35 +01:00
Marco Costalba 436fa5c8fa Better document how history works
Both with added comment and changing the API to
reflect that only destination square and moved piece
is important for history.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-16 12:06:54 +01:00
Marco Costalba 8df816f869 Fix broken multi-pv with aspiration window search
Aspiration window search must be disabled for
multi-pv case.

We missed one point where aspiration window should
be disabled in this case.

Patch from Joona, with a little added edit by me.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-15 17:48:18 +01:00
Marco Costalba 9c428afb6d Fix a warning un using anonymous structs
No functional and no binary change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-12 12:10:40 +02:00
Marco Costalba 27619830d4 Use string instead of std::string
And others small code style touches.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-10 18:38:47 +01:00
Marco Costalba 78eecbf6d7 Use 64 bits for debug counters
Has happened 32 bits were not enough for
some test.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-10 17:42:04 +01:00
Marco Costalba 980124c609 Fix some Intel compilers warnings
Also a compile fix due to Makefile missing new
application.cpp file.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-09 12:09:25 +02:00
Marco Costalba 5f7d37273c Micro optimize generate_pawn_checks()
Use a better condition to find candidate direct check pawns.
In particular consider only pawns in the front ranks of the
enemy king, this greatly reduces pawns candidates bitboard
that now is empty more then 90% of the time so that we
can early skip further tests.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-08 10:56:59 +02:00
Marco Costalba be4ee0729d Convert also generate_pawn_blocking_evasions() to new API
New compact parameter passing API.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-07 17:08:55 +02:00
Marco Costalba 9fbe9af0a0 Better dscovery check condition in generate_pawn_checks()
Be more strict, is not enough dc bitboard is not empty, but
needs to inclde also at least one pawn.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-07 17:01:52 +02:00
Marco Costalba 1d15b38cd8 Further parametrize generate_pawn_captures
We can parametrize for the capture direction too.

Also use a single template parameter and calculate (at
compile time) remainin parameters directly in the function.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-07 16:41:36 +02:00
Marco Costalba 5c81602d14 Update copyright year
We are well in 2009 already.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-07 14:54:40 +02:00
Marco Costalba a88e762b4e Rewrite the way application exits
Centralize in a single object all the global resources
management and avoid a bunch of sparse exit() calls.

This is more reliable and clean and more stick to C++ coding
practices.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-07 12:59:19 +02:00
Marco Costalba 2155fb7825 Be sure book file is closed before we leave
Move closing of file in Book destructor. This
guarantees us against leaving the file open under
any case and simplifies also Book use.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-07 09:27:38 +02:00
Marco Costalba a03b8074c8 Rewrite Book implementation
Let Book be derived directly from std::ifstream
and rewrite the functions accordingly.

Also simplify file reading by use of operator>>()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-06 19:28:17 +01:00
Marco Costalba afadc33fb4 Space inflate book.cpp
Also document most interesting parts.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-06 12:19:20 +02:00
Marco Costalba 92ca97d121 Fix a couple of MSVC warnings
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-06 09:50:49 +02:00
Marco Costalba da91fab8cb Micro optimize move_is_ep() and move_is_castle()
Avoid a shift operation moving it at compile time.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-05 15:12:23 +02:00
Marco Costalba 6176357ac1 Faster Position::move_is_capture() condition
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-05 14:55:48 +02:00
Marco Costalba 46bb6c6dc3 Fix missing pawn color check in move_is_legal()
In case we have a correct white pawn move but pawn
is black (or the contrary) we fail to detect the
move as illegal.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-05 13:10:29 +02:00
Marco Costalba 5c703b7526 Update makefile to use PGO with Intel C++ v11.0
Update profiler guided optimization instructions in
Makefile to the latest Intel C++ compiler.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-04 11:58:26 +02:00
Marco Costalba 412d68fe4f Micro optimize SEE
Use pieces_of_type() instead of pieces_of_color_and_type()
in an hot loop and cut of almost 10% SEE execution time.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-04 11:18:24 +02:00
Marco Costalba 9144e48eb6 Avoid an usless check in pl_move_is_legal
Although very cheap this is a very hot path,
so avoid it.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-03 08:15:55 +01:00
Marco Costalba aabd526f7c Change TT interface to ask directly for a position key
Instead of a position because the key is all that we
need.

Interface is more clear and also very very little bit faster.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-03 08:11:36 +01:00
Marco Costalba fdb2242d34 Setup to use Callgrind profiler
Disabled by default.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-03 08:11:24 +01:00
Marco Costalba 991ab2bea8 Restore development versioning and LSN filtering
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-03 08:11:07 +01:00
Marco Costalba f032ba54c5 Stockfish 1.3.1
Mainteinance version to fix broken Glaurung 2
book reading.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-03 07:49:34 +01:00
Marco Costalba 5a7876d0d0 Revert Glaurung 1 book compatibility patch
It breaks also Glaurung 2 book parsing.

We really need to work on book.cpp, but for now just
leave compatibility just for Glaurung 2 books.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-03 07:46:27 +01:00
Marco Costalba e87931bbfc Stockfish 1.3
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-02 11:53:08 +01:00
Marco Costalba aa5c375ca9 Fix a very old UCI option parsing bug
We currently fail on an option with a sapece in the name,
as example

setoption name Clear Hash

returns error message "Option Clear not found". This
patch fixes this off-by-one type bug.

Thanks to Joona for spotting this.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-02 11:52:49 +01:00
Marco Costalba cd1cc39b04 Nicely simplify MovePicker::pick_move_from_list
It is a positive fall back from previous patch.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-02 10:08:10 +01:00
Marco Costalba 4e151f7e0d Sort moves just after scoring
Instead of a delayed selection sort so that the highest
score move is picked up from the list when needed, sort all
the moves up front just after score them.

Selection sort is O(n*n) while std::sort is O(n*log n), it
is true that delayed selection allows us to just pick the move
until a cut off occurs or up to a given limit (12), but with
an average of 30 non capture-moves delayed pick become slower
just after 5-6 moves and we now pick up to 12.

Profiling seem to prove this idea and movepick.cpp is now 10%
faster.

Also tests seem to confirm this:

After 700 games at 1+0: Mod vs Orig +178 -160 =362 +9 ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-05-02 10:07:46 +01:00
Marco Costalba d13e4c16c2 Update polyglot.ini
Upadte to new parameters and parameters values.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-30 15:16:35 +01:00
Marco Costalba 1906df4494 Stockfish 1.3 rc1
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-30 09:18:20 +02:00
Marco Costalba 39f2eda285 Do not razor after a null move
We don't want to return unproven null move fails high, so
that if a position is so good that null move fails high we
want to check this with real do_move() / undo_move() test,
not just razoring the position because, from the opponent
point of view, is very bad.

These are tests results at 1+0

Mod vs Orig +252 -264 =483  49.40%
Mod vs Toga II 1.4.1SE  +365 -325 =309  52.00%

So it seems a very slightly regression regarding orig version (but
withing error bar) and a nice increase against Toga that is what we
are interested most. Orig version scores 49.75% against Toga, so
we welcome this change ;-)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-30 08:55:38 +02:00
Marco Costalba 00a3380885 Fix assignment of pv[0] when creating root move list
It is bogusly assigned from moves[i].move instead of mlist[i].move
or equivalently to moves[count].move that it seem more clear to me.

Bug is hidden while all the moves are included, in this default case
moves[i].move and mlist[i].move are the same variable.

Also a bit of cleanup while there.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-29 16:01:57 +02:00
Marco Costalba f1d982e2c0 Merge Joona's razoring tweaks
After proof testing on 3 different engines these
are the results:

Stockfish - Toga II 1.4.1SE +130 -132 =132 49.75%
Stockfish - Deep Sieng 3.0  +145 -110 =150 54.45%
Stockfish - HIARCS 12 MP    +94  -149 =150 43.00%

So it seems no regressions occurs, although also no
improvment. But anyhow this patch increases Stockfish
strenght against itself, so merge it.

Note that this patch not only adds back razoring at depth
one, but also increases razor depth limit from 3 to 4
because hard coded depth 4 limit is no more overwritten
by UCI parameter that otherwise defaults to 3.
2009-04-28 09:00:09 +02:00
Marco Costalba fbca16da57 Hardcode depth limit for selective search
Because futility margins array has a fixed size we cannot
arbitrarly choose or change the SelectiveDepth parameter,
otherwise we have a crash for values bigger then array size.

On the other hand tweaking of this parameter requires some
modification to the hardcoded margins, so makes sense to hard
code also this very bounded one.

Who wants to experiment is of course free to change the sources.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-28 08:47:26 +02:00
Marco Costalba 1e97cdd9f3 Fix a warning under MSVC
Somehow silly warning C4800:
'int' :forcing value to bool 'true' or 'false'(performance warning)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-27 18:00:45 +01:00
Marco Costalba ab69f50c64 Micro optimize Position::move_is_check()
More then optimization it is worth a bit of better
code self documenting.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-27 17:39:59 +02:00
Marco Costalba b35e593551 Inline Position::move_is_capture()
This is a very hot path function, profiling on Intel compiler
shows that inlining cuts in half the overhead.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-27 16:36:33 +02:00
Marco Costalba 20d88dbf98 Retire timeoday.cpp
Move the only function gettimeofday in misc.cpp
where is used.

This avoids polluting the global namespace.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-27 13:48:14 +01:00
Marco Costalba ef60043725 Small cleanup in misc.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-27 13:38:47 +01:00
Marco Costalba 2f2e48fad2 Code style cleanup in transposition table code
Assorted fixes but no functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-27 13:21:49 +01:00
Marco Costalba 2550c6383b Fix a bogus assert in tt.cpp
Max hash size is 4096 MB, not 1024 MB, see the corresponding
"Hash" UCI parameter in ucioption.cpp

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-27 10:29:33 +01:00
Marco Costalba fb560fa5d7 Convert piece.cpp to C++
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-27 10:12:34 +01:00
Marco Costalba 11491e71ee Remove an useless comparison in futility pruning
Currently futility is allowed when depth < SelectiveDepth
and SelectiveDepth is 7*OnePly, so the comprison is
always true.

Patch could introduce a functional change only if
we choose to increase SelectiveDepth.

Currently no functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-27 09:45:15 +01:00
Marco Costalba bd26374f21 Small code tidy up and test results
When testing at 1'+0" time control results are still
reasonably good. We have made two sessions on two
different PC.

After 840 games Mod - Orig: +221 -194 =425 +10 ELO (two CPU)

After 935 games Mod - Orig: +246 -222 =467  +9 ELO (single CPU)

So it seems that with fast CPU and/or longer time controls
benefits of the patch are a bit reduced. This could be due
to the fact that only 3% of nodes are pruned by razoring at
depth one and these nodes are very swallow ones, mostly get
pruned anyway with only a slightly additional cost, even
without performing any do_move() call.

Another reason is that sometime (0,3%% of cases) a possible
good move is missed typically in positions when moving side
gives check, as example in the following one

3r2k1/pbpp1nbp/1p6/3P3q/6RP/1P4P1/P4Pb1/3Q2K1 w - -

The winning move Rxg7+ is missed.

Bottom line is that patch seems good for blitz times, perhaps
also for longer times. We should test against a third engine
(Toga ?) to have a final answer regarding this new setup.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-26 13:51:54 +01:00
Joona Kiiski d20e0cf048 Razor again at depth one
Some time ago it was found by Marco Costalba that it's better
to disable razoring at depth one, because given the very low
evaluation of the node, futility pruning would already do
the job at very low cost and avoiding missing important moves.

Now enable razoring there again, but only when our quickly evaluated
material advantage is more than a rook. The idea is to try razoring
only when it's extremely likely that it will succeed.

Extreme lightning speed test show promising result:
Orig - Mod: +1285 =1495 -1348

This needs to be tested with longer time controls though.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-26 13:51:50 +01:00
Joona Kiiski 342ceb1c91 Make futility and razor margins more tunable
Restructure RazorMargins and FutilityMargins arrays so that their
values can be more easily tuned.

Add RazorApprMargins array which replaces razorAtDepthOne concept,
because setting RazorApprMargin very high value at ply one is
same as not razoring there at all.

Comment out setting razoring and futility margins through uci to
avoid errors while tuning.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-26 13:51:47 +01:00
Marco Costalba f010b6db71 Do not hardcode default values of UCI variables
If a variable will be populated reading an UCI option
then do not hard code its default values.

This avoids misleadings when reading the sources.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-26 13:41:17 +01:00
Marco Costalba 7c267587fc Greatly speedup has_mate_threat()
Instead of loop across all legal moves to find a mate
loop across possible check moves only.

This reduces more then 10 times the number of moves to
check for a possible mate.

Also rename generate_checks() in generate_non_capture_checks()
so to better clarify what the function does.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-26 13:40:26 +01:00
Marco Costalba 24485c96ec Micro optimize generate_piece_checks() take 2
Add some missing bits of this patch.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-19 21:09:53 +02:00
Joona Kiiski f98385e129 Add missing header file to make stockfish compile with latest Inter C++ Compiler under Linux (memcpy needs cstring)
Correct some references glaurung -> stockfish in Makefile

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-19 20:57:23 +01:00
Marco Costalba 2acc89c6e8 Simplify Position::is_mate()
Should be a bit faster too.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-19 17:13:04 +01:00
Marco Costalba a52ab2afbf Micro optimize generate_piece_checks()
Avoid calculating piece attacks if there aren't
available check sqaures for the given piece.

About 15% of cases. Not a biggie but still something
especially in the middle game where king is well covered
inside his castle.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-18 16:28:12 +01:00
Marco Costalba de050db2b0 MovePicker: retire per square MVV/LVA ordering
Is not used anyway and in case we need it again we
can resurrect from git archives.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-18 14:24:21 +01:00
Marco Costalba e68ebe618c In qsearch store the cut move in TT
And upon reentering the same position try it as first.

Normally qsearch moves order is already very good, first move
is the cut off in almost 90% of cases. With this patch, we get
a cut off on TT move of 98%.

Another good side effect is that we don't generate captures
and/or checks when we already have a TT move.

Unfortunatly we found a TT move only in 1% of cases. So real
impact of this patch is relatively low.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-18 14:04:00 +01:00
Marco Costalba 4634be8ba6 Merge Joona's new aspiration window search
It seems very positive.

After 999 games at 1'+0" result is: +249 -216 =534 +11 ELO

And after another 456 games we still have: +122 -113 =221
2009-04-18 09:15:42 +01:00
Marco Costalba e7f03913ea Introduce move_pawns() helper in movegen.cpp
This let us to have more readable code keeping the
same speed.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-18 09:13:31 +01:00
Marco Costalba e30720b0bf Remove failHigh/Low bits from IterationInfoType
We don't use that info anyway.

Also document a little more new aspiration window code.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-18 09:12:41 +01:00
Joona Kiiski 7af1b40b4e Restore calling insert_pv after search is aborted + small clean-up
Restore old behaviour that after search is aborted we call insert_pv,
before breaking out from the iterative deepening loop.

Remove one useless FIXME and document other better.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-18 09:12:18 +01:00
Marco Costalba ecec7dbf89 Little code style tweaks
Let the code be more conformant to current style.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-18 09:12:07 +01:00
Marco Costalba 8da2153ee8 Revert previous patch as per Joona request
Joona says patch gives bad results after testing,
so revert for now.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-18 09:11:56 +01:00
Joona Kiiski 22f9f0cabe Improve handling of fail-highs in assumed PV
Check all fail highs in assumed PV with greater care (fruit/Toga already does this).
Add a flag when aspiration search fails high at ply 1 to prevent search to
be terminated prematurely.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-18 09:11:41 +01:00
Joona Kiiski 3e7e1a7c53 Revert "Implement a fallback system when aspiration search fails low and we are out of time."
This reverts commit 55dd98f7c717b94a659931cd20e088334b1cf7a6.

Revert fallback-system for root_search

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-18 09:11:30 +01:00
Joona Kiiski 0ea716463b Implement a fallback system when aspiration search fails low and we are out of time.
However also this patch is immediately reverted. For three reasons:
1) the case it affects is very rare (and then we are likely to lose anyway),
   so we can well live without this.

2) Because the case is so rare it's hard to test this change properly.

3) To perform fallback search, we must reset so many global variables that this
   patch is very likely both buggy and extremely bad style.

Consider including this again if we clean-up global variables one day...

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-18 09:11:15 +01:00
Joona Kiiski 6c4e36aab6 Revert "Implement bestValue in root_search."
This reverts commit 9a39f93f35254787b7b57980019dde276a89c48c.

Revert bestValue in root_search

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-18 09:11:05 +01:00
Joona Kiiski 6f28bcd483 Implement bestValue in root_search.
However just after finished writing this patch I realized that this
is not the way to go. So this will be immediately reverted.

(Just save this here in git in case I change my mind later :) )

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-18 09:10:54 +01:00
Joona Kiiski acef5d6a59 Dynamic aspiration search without research.
Implement system where aspiration search window is calculated using
values from previous iterations.

And then some crazy experimental stuff: If search fails low at the root,
don't widen window, but continue and hope we will find a better move
with given window. If search fails high at the root, cut immediately,
add some more time and start new iteration.

Note: this patch is not complete implementation, but a first test
for this idea. There are many FIXMEs left around. Most importantly
how to deal with the situation when we don't have any move!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-18 09:10:41 +01:00
Marco Costalba 44b497a972 Re-fix square.h warning to avoid a compile error under MSVC
This fix adds ugliness to an already ugly previous fix...hopefully
it is the last one :-(

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-13 12:02:22 +01:00
Marco Costalba b893583bb6 Fix a gcc warning due to order of initialization in Option
Move idx declaration before minValue and maxValue and silence
this last warning.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-13 12:02:14 +01:00
Marco Costalba e81d0d08c3 Fix a compile error with Intel icc
To make std::sort() work operator<() should be
declared const.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-13 12:02:06 +01:00
Marco Costalba 72c7595f8a Fix a warning under Intel compiler in square.h
We need to cast to char the whole expression...

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-13 12:01:55 +01:00
Marco Costalba e38ad4d42b Fix a very nasty conversion bug in Option c'tor
Sometimes C++ can be really bad!

In this case an hard coded c string selects Option c'tor
with int argument instead of the std::string one becuase
it is considered a better matching by the compiler.

Fix the bug changing the argument type from std::string to
const char* so to be a better match then the int one.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-12 01:10:50 +01:00
Marco Costalba fad772f387 Store UCI options of type CHECK according to C++ convention
Store boolean values as "1" and "0" instead of "true" and "false"
and convert back to UCI protocol convention when needed.

This is simpler then the other way around.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-11 16:01:33 +01:00
Marco Costalba ebb0f31928 Restore original UCI option printing order
For each option store its index so to be printed
according to insertion order.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-11 16:01:21 +01:00
Marco Costalba f0701e2b0f Use a map instead of a vector to store UCI options
Apart from the teoretical speed increase, the main reason
of this patch is a good amount of code cleanup.

Note that now UCI options are printed in alphabetical
order and not in insertion order as before. Next patch
will take care of restoring old behaviour.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-11 16:01:08 +01:00
Marco Costalba 95aadb5e53 Remove unused currentMoveCaptureValue from search stack
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-11 11:09:37 +01:00
Marco Costalba 17ef886fc3 Less aggressive null move dynamic reduction
In null move search do not jump directly in
qsearch() from depth(4*OnePly), but only
from depth(3*OnePly).

After 999 games at 1+0: +248 -224 =527 +8ELO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-11 10:58:10 +01:00
Marco Costalba 8590a6f3b7 Revert dynamic LMR
It doesn't seem to work against Toga. After more then 400 games
we are at -13 ELO while, without it we are at + 5 ELO after 1000
games.

So revert for now to keep code simple.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-04-03 20:34:22 +01:00
Marco Costalba 7b05b83bf2 Fix compile in the debug mode
Due to previous patches we end up with a compile
error in debug mode.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-31 20:50:24 +01:00
Marco Costalba d7ef09727a Silence idiotic warning on two's complement of an unsigned
MSVC gives:

warning C4146: unary minus operator applied to unsigned type,
               result still unsigned

When finds -b where b is an unsigned integer. So rewrite the two's
complement in a way to avoid the warning. Theoretically the new
version is slower, but in practice changes nothing.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-31 20:50:10 +01:00
Marco Costalba 683595fee1 Silence a bunch of warnings under MSVC /W4
Still some remain, but are really the silly ones.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-31 20:49:56 +01:00
Marco Costalba 659c54582d Revert setting a flag when TT value equals static evaluation
Strangely enough it seems that optimization doesn't work.

After 760 games at 1+0: +155 -184 =421 -13 ELO

Probably the overhead, although small, for setting the flag
is not compensated by the saved evaluation call.

This could be due to the fact that after a TT value is stored,
if and when we hit the position again the stored TT value is
actually used as a cut-off so that we don't need to go on
with another search and evaluation is avoided in any case.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-31 20:41:06 +01:00
Marco Costalba 2c0cd95ecf An VALUE_TYPE_EVAL score cannot overwrite an entry
If we want to store a value of type VALUE_TYPE_EVAL for
a given position and we found an already exsisting entry
for the same position then we skip.

We don't want to overwrite a more valuable score with a
lesser one. Note that also in case the exsisting entry is
of VALUE_TYPE_EVAL type the overwrite is unuseful because
we would store the same score again.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-30 09:09:27 +01:00
Marco Costalba 6a8e46d53e Remember when TT value equals static evaluation value
When the stored TT value equals the static value set a
proper flag so to not call evaluation() if we hit the
same position again but use the stored TT value instead.

This is another trick to avoid calling costly evaluation()
in qsearch.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-30 08:54:09 +01:00
Marco Costalba c6c4713ab2 Document TTEntry and move layouts
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-30 08:29:02 +01:00
Marco Costalba 9e44a6dba9 A move needs 17 bits not 19
Fix a bug in the way a move is stored and read in a TT entry.
We use a mask of 19 bits insteaad of 17 so that the last
two bits in the TT entry end up to be random data.

This bug will bite us when we will use these two until now
unused bits.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-29 17:23:41 +01:00
Marco Costalba 941f4e1643 Remove some obsolete code in movepick.cpp
This fixes some warning under Intel compiler.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-27 19:35:08 +01:00
Marco Costalba dcdac83187 Revert storing of TT when returning from "stand pat"
After testing it seems patch is bad:

After 999 games 1+0: +242 -271 =486 -10 ELO

So restore saving of TT at the end but using new Joona
idea of storing as VALUE_TYPE_UPPER/VALUE_TYPE_LOWER instead
of VALUE_TYPE_EXACT.

Some optimization is still possible but better test new ideas
one by one.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-27 15:30:45 +01:00
Marco Costalba 5a0581498c Cache evaluation score in qsearch
Instead of just drop evaluation score after stand pat
logic save it in TT so to be reused if the same position
occurs again.

Note that we NEVER use the cached value apart to avoid an
evaluation call, in particulary we never return to caller
after a succesful tt hit.

To accomodate this a new value type VALUE_TYPE_EVAL has been
introduced so that ok_to_use_TT() always returns false.

With this patch we cut about 15% of total evaluation calls.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-24 18:28:42 +01:00
Marco Costalba 1c087dd806 Let to toggle dynamic LMR
It is now disabled by default due to bad results
against a pool of engines...more testing is needed tough.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-24 18:28:25 +01:00
Marco Costalba 095a96b461 In qsearch update TT only if returning from stand pat
This is the only "correct" exact value we can store.

Otherwise there could be spurious failed high/low nodes.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-24 11:26:43 +01:00
Marco Costalba 72af519e7f When asked for position key print it as an hex value
Merged from Glaurung current development snapshot.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-24 10:50:13 +01:00
Marco Costalba db46602b1f Wait at least until iteration 3 before to stop the search
It was 2 before.

Merged from Glaurung current development snapshot.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-24 10:49:02 +01:00
Marco Costalba d3f99aea6b Let zobrist keys to be compatible with Glaurung 1
Some changes to the zobrist keys, to make them identical
to those used by Glaurung 1.

The only purpose is to make it possible for both programs
to use the same opening book.

Merged from Glaurung current development snapshot.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-24 10:40:22 +01:00
Marco Costalba 0e835bd334 Fixed a sliding attack bitboard bug in 32-bit mode
This is what prevented USE_32BIT_ATTACKS from working
on some architectures (like PowerPC).

Merged from Glaurung current development snapshot.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-24 10:30:27 +01:00
Marco Costalba 43276cbec5 Fix a bug in insert_pv() where minimum depth is zero
We implicitly considered the minimum depth stored in TT
to be Depth(0), but because we store values in TT also in
qsearch() where depth is < 0, we need to use a negative
number as minimum depth.

Bug spotted by Joona Kiiski.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-23 15:30:20 +01:00
Marco Costalba a9e55d4326 Revert odd depths razoring
I have just made a new rule that no modification
that increases pruning is allowed if after 1000 games
ELO is not increased by at least 10 point (was +5 in this case)

Yes, I like this kind of nosense rules :-)
2009-03-23 12:02:15 +01:00
Marco Costalba 4d70e3aeac More aggressive dynamic LMR
Previous setup didn't change anything

After 996 games 1+0: +267 -261 =468 +2 ELO

Now with this new setup we have

After 999 games 1+0: +277 -245 =477 +11 ELO

Seems reasonable...

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-23 11:58:28 +01:00
Marco Costalba 24b7ad54c7 LMR dynamic reduction
Reduce of two plies near the leafs and when we still
have enough depth to go so to limit horizon effects.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-22 23:53:22 +01:00
Marco Costalba 0ff3bf34cd Always print a best move when requested
Little fix merged from iPhone Glaurung.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-22 23:53:10 +01:00
Marco Costalba 66d165921d Better castle move detector in move_to_san()
Merged from iPhone Glaurung.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-22 23:52:59 +01:00
Marco Costalba b82c3021fa Fix a smal bug in Position::from_fen
We could fail to parse an en-passant position
in same cases.

Merged from iPhone Glaurung.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-22 23:52:23 +01:00
Marco Costalba 320630ca1a Merge new pawn storm evaluation
More accuracy in pawn storm evaluation
directly from iPhone Glaurung.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-22 23:52:06 +01:00
Marco Costalba ef8acdc73b Fix a small bug in king safety
Merged from iPhone Glaurung.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-22 13:11:24 +01:00
Marco Costalba cc8e915ed5 Merge KBPP vs KB endgame from iPhone Glaurung
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-22 13:06:29 +01:00
Marco Costalba 16abc165d8 Fix: In qsearch do not use TT value when in a PV node
We already do like this in search_pv(), so extend
also in qsearch().

Bug spotted by Joona Kiiski.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-21 14:51:31 +01:00
Marco Costalba 74160ac602 Big headers cleanup
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-19 12:55:32 +01:00
Marco Costalba feb5342b39 Safe guard some wild and ugly casts
These casts are needed but plain ugly, at least be
sure they don't hide any subtle conversion bug.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-16 13:59:41 +01:00
Marco Costalba 6cddf9183c Partially revert pawns storm bug fix
Try to save space and use the minimum size
possible.

In particular restore int16_t for values and int8_t
for halfOpenFiles.

Use int16_t for storm values insted of int and also
instead of original buggy and too small int8_t.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-16 08:02:33 +01:00
Marco Costalba b870f5a091 Silence a good bunch of Intel warnings
Note that some pawns and material info has been switched
to int from int8_t.

This is a waste of space but it is not clear if we have a
faster or slower code (or nothing changed), some test should be
needed.

Few warnings still are alive.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-15 18:19:08 +01:00
Marco Costalba fcecc5212e Fix an overflow bug in pawns stormValue
These fields are defined as int8_t but values bigger
then 127 are stored there so that we silently overflow.

Fix bringing up all the fields to a sane int type. This
will increase memory usage, but apart from being safe, it is
not clear if code is slower or faster. Test is needed.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-15 18:18:56 +01:00
Marco Costalba 8de91be61e Fix a silly warning on Intel compiler
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-15 18:18:42 +01:00
Marco Costalba ca4e78db8d Revert NULL move beta corrections
After testing result is bad -25 ELO
2009-03-15 16:44:12 +01:00
Marco Costalba bfcfaf7101 Retire Null Driven IID
It does not seem to clearly improve things and
in any case is disabled by default, so retire for now.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-15 16:43:28 +01:00
Marco Costalba c8773c720a Merge Joona Kiiski NULL search beta correction
Prune more moves after a null search because of
a lower beta limit then in main search.

In test positions reduces the searched nodes of 30% !!!!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-14 13:00:22 +01:00
Marco Costalba 3ed603cd64 Merge Joona Kiiski evaluation tweaks
Merge tewaks to many evaluation parameters
by Joona Kiiski.

After test they seem good!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-14 12:55:14 +01:00
Marco Costalba f637ddc1e8 Micro optimize move_is_check()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-07 21:05:49 +01:00
Marco Costalba 964bd86272 Micro optimize pl_move_is_legal()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-07 21:05:31 +01:00
Marco Costalba 72b88e09e1 Micro optimize previous patch
Also remove some Intel warnings, not all :-(

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-06 20:47:19 +01:00
Marco Costalba 3e663d8c50 Introduce evaluate_pieces<>() to remove redundancy
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-06 19:19:45 +01:00
Marco Costalba 8c9c51c721 Fix compile error with inlines under gcc and Intel
It seems that these compilers do not like inline functions
that call a template when template definition is not in scope.

So move functions from header to in *.cpp file

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-05 00:38:45 +01:00
Marco Costalba 7fe1632a49 Fix some comments in position.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-04 22:51:20 +01:00
Marco Costalba 7c84b39a42 Avoid to call useless sliders attacks in update_checkers()
Quickly filter out some calls to sliders attacks
when we already know that will fail for sure.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-04 22:51:04 +01:00
Marco Costalba 68e711aac6 Super fast hidden_checkers()
Rewritten hidden_checkers() to avoid calling
sliders attacks functions but just a much
faster squares_between()

Also a good code semplification.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-04 22:50:51 +01:00
Marco Costalba 02cd96e4c2 Cleanup SearchStack initialization
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-03 21:01:00 +01:00
Marco Costalba 772a37cd54 Micro optimize copy of new state in do_move()
Instead of copying all, copy only the fields that
are updated incrementally, not the ones that are
recalcuated form scratch anyway.

This reduces copy overhead of 30%.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-02 18:00:42 +01:00
Marco Costalba c02613860a Revert hidden checkers rework
It is slower the previous uglier but faster code.

So completely restore old one for now :-(

Just leave in the rework of status backup/restore in do_move().

We will cherry pick bits of previous work once we are sure
we have fixed the performance regression.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-03-02 16:20:00 +01:00
Marco Costalba 9b6b9e67fe Use checker info to remove a bunch of hidden checks updates
Another powerful condition let us remove a big chunk of
useless updates.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-28 18:43:36 +01:00
Marco Costalba 6a8cfe79da Stricter condition to check for dc candidates
Another optimization that let us remove another half
of find_hidden_checks(them, DcCandidates) calls.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-28 18:43:20 +01:00
Marco Costalba 1f97b48a31 Split calculation of pinners from dc candidates
This let us to calculate only pinners when we now that
dc candidates are not possible.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-28 18:43:02 +01:00
Marco Costalba a96cba0ec8 Slightly better condition in update_hidden_checks()
Use a more strict condition to check if we have captured
an opponent pinner or hidden checker.

With this patch the occurrence of checkerCaptured == true are
reduced of 50%.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-28 18:42:51 +01:00
Marco Costalba f9f30412e7 Compute pinned and friends incrementally
In do_move() use previous pinned bitboards values to compute
the new one after the move. In particulary we end up with the
same bitboards in most cases. So detect these cases and just
keep the old values.

This should speedup a lot this slow computation in a very hot
path so that we can use this important info everywhere in the
code at very cheap cost.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-28 18:42:30 +01:00
Marco Costalba 55f9afee2a Fix a subtle bug due to the StateInfo pointer became stale
There was one occurence when the StateInfo variable went
out of scope before the corresponding Position object.

This yelds to a crash. Bug was not hit before because occurs
only when using an UCI interface and not the usual benchmark.

The fix consists in copying internally the content of the
about to stale StateInfo.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-23 21:45:12 +01:00
Marco Costalba 962216440c Teach SEE about pinned pieces
Remove pinned pieces from attacks when calculating
SEE value.

Algorithm is not perfect, there should be no false
positives, but can happen that we miss to remove a
pinned piece. Currently we don't cach 100% of cases,
but is a tradeoff between speed and accuracy. In any
case we stay on the safe side, so we remove an attacker
when we are sure it is pinned.

About only 0,5% of cases are affected by this patch, not
a lot given the hard work: this is a difficult patch!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-23 21:45:01 +01:00
Marco Costalba 243fa483d7 Small Position::clear() cleanup
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-23 21:44:46 +01:00
Marco Costalba da7a62852a Do not copy the whole old state in do_move()
Instead of copy the old state in the new one, copy only
fields that will be updated incrementally, not the ones
that will be recalculcated anyway.

This let us copy 13 bytes instead of 28 for each do_move()
call.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-23 21:44:29 +01:00
Marco Costalba 0bf45823da Update pinned bitboards and friends in do_move()
Probably is slightly slow, but code is surely better
in this way. We will optimize later for speed.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-23 21:44:17 +01:00
Marco Costalba 4324276419 Fix some asserts unhidden by a debug compile
Fallback form previous patches.
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-23 21:44:04 +01:00
Marco Costalba 43bc5479c2 Avoid resetting pinners[c]
Small optimization. No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-22 21:19:04 +01:00
Marco Costalba 8f59de48f5 Introduce StateInfo instead of UndoInfo
We don't backup anymore but use the renamed StateInfo
argument passed in do_move() to store the new position
state when doing a move.

Backup is now just revert to previous StateInfo that we know
because we store a pointer to it.
Note that now backing store is up to the caller, Position is
stateless in that regard, state is accessed through a pointer.

This patch will let us remove all the backup/restore copying,
just a pointer switch is now necessary.

Note that do_null_move() still uses StateInfo as backup.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-22 21:18:50 +01:00
Marco Costalba 2f6c5f00e6 Wrap state variables in a named struct
This will allow us to more easily move the state
out of Position class.

No functioanl change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-22 21:18:35 +01:00
Marco Costalba 2f21ec39ad Convert also undo_null_move() to avoid passing UndoInfo object
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-22 21:18:14 +01:00
Marco Costalba 9b257ba29d Passing UndoInfo is not needed anymore when undoing the move
We store it now in the same UndoInfo struct as 'previous'
field, so when doing a move we also know where to get
the previous info when undoing the back the move.

This is needed for future patches and is a nice cleanup anyway.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-22 21:18:02 +01:00
Marco Costalba 1b0fee9b17 Remove two useless calls to pinned_pieces()
Are obsoleted by new pinned caching code.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-22 21:17:44 +01:00
Marco Costalba b7cb6180cf Position: Unify and templetize mg_pst() and eg_pst()
Also templetize compute_value() can be simpler now that
the above is templetized too.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-20 22:50:35 +01:00
Marco Costalba f30aa83f8a Unify compute_mg_value() and compute_eg_value()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-20 22:50:20 +01:00
Marco Costalba 1dc27f3232 Use a union to fast and simply backup info in do_move()
This nice union trick let us optimize the speed and
remove the now unuseful backup() and restore() functions.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-20 22:50:08 +01:00
Marco Costalba 95cfc0e306 In Position backup and restore contiguous data
Give the compiler one more chance to optimize the copy.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-20 22:49:54 +01:00
Marco Costalba 9e1d142fdd Finally remove any occurence of dcCandidates from search.cpp
This ends our cleanup series.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-19 17:35:23 +01:00
Marco Costalba 683e6dc656 Do not pass discovery check candidates in Position::do_move()
Also remove any bit of 'pinned' and co. from MovePicker class.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-19 17:29:36 +01:00
Marco Costalba c6630abe0d Do not pass pinned argument in Position::move_is_check()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-19 17:01:08 +01:00
Marco Costalba 734941672e Do not pass pinned argument in Position::pl_move_is_legal()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-19 16:48:57 +01:00
Marco Costalba 0a0ea36e25 Cleanup pinned and friends in movegen.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-19 16:37:03 +01:00
Marco Costalba 5f142ec209 Cache pinned and discovery check bitboards
After have been calculated cache their values
so to avoid another expensive call to hidden_checks()
if pinned_pieces() or discovered_check_candidates() are
called with the same position.

Add also interface to get pinners bitboard, we already have
this value so save it instead of discard.

Now that, after the first call to pinned_pieces() the following
are very cheap we can rewrite and cleanup all the checking handling.

So this patch is a prerequisite for future work.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-19 16:28:35 +01:00
Marco Costalba 7f4f18f959 Revert mobility of pinned pieces for now
We will redo after rewriting the handling of
pinned bitboard and its friends.
2009-02-19 15:49:54 +01:00
Marco Costalba c45818e9f8 Remove xxx_of_color() for real
Remove also from assert expressions. Was hidden
in release mode.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-17 17:26:15 +01:00
Marco Costalba 7013efce4e Change piece_attacks_square() API
An extra argument let us simplify some code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-17 12:00:05 +01:00
Marco Costalba 9f5b709db7 Mobility is zero for a pinned piece
A little bit more overhead, but better mobility evaluation.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-17 11:29:14 +01:00
Marco Costalba 2c955f25de Remove xxx_of_color() helpers
They hide the underlying uniform function call with
no benefit.

A little bit more verbose but now is clear what happens.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-17 10:54:47 +01:00
Marco Costalba f32992f88c Avoid a call to move_is_capture() in extension()
Pass value as an argument instead or recalculating it.
Altough call is cheap this is a very hot path so with
this patch total time spent for move_is_capture() is almost
halved.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-13 20:57:03 +01:00
Marco Costalba e71d520758 Add scan for X-ray attacks in piece_attacks_square()
Used to avoid pruning interesting moves.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-13 20:56:46 +01:00
Marco Costalba 52ed0e9563 Fix a subtle bug in Position::move_is_capture()
Currently fails if we test with a move that is not of
from the side to move but from the opponent.

This is the typical case of the threat from null move
search. The result is an erroneus prune of the defending
moves, see PruneDefendingMoves in ok_to_prune()

Fix the test to work also with threat moves.

Bug was always in but was unhidden by a patch of 17/12/2008
"Trigger of PawnEndgameExtension if capture is not a pawn"

Until then it was hidden by a tricky check in the prune
conditions instead of the natural move_is_capture()

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-13 20:56:26 +01:00
Marco Costalba 30e8f0c9ad Do not manually build endgame functions hash keys
Use Position::compute_material_key() to do the job,
so we are sure there is not key mismatch during
endgame function lookups.

This fixes two endgames hash errors that caused two
endgames to be disabled.

This patch is also a code cleanup because removes a lot
of messy key assignments.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-13 20:55:59 +01:00
Marco Costalba 67375f4693 Use template for endgame scaling functions
Also integrate scaling and evaluation in a
single base class.

Nice use of templates here :-)

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-13 20:55:29 +01:00
Marco Costalba 039badfda8 Use templates for end game evaluation functions
Huge simplification and no speed cost penalty.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-13 20:55:14 +01:00
Marco Costalba 088ecc242f Small code formatting in position.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-13 20:54:56 +01:00
Marco Costalba a188a047ab Use update_checkers<>() also for PAWN
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-13 20:54:37 +01:00
Marco Costalba 1d2247aea3 Introduce update_checkers() to simplify do_move()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-13 20:54:17 +01:00
Marco Costalba 8365f8ac1e Remove square_is_attacked()
Use attacks_to() instead. No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-13 20:53:58 +01:00
Marco Costalba 68d36b6f59 Rename generate_piece_blocking_evasions()
In generate_piece_moves() to be more uniform with other
functions. Unfortunatly the different number of calling arguments
do not allow us to easily integrate in generate_piece_moves()
template family.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-13 20:53:39 +01:00
Marco Costalba 33c608e140 Final touches to generate_evasions()
Small code tidy up and a little optimization
to avoid calling generate_piece_blocking_evasions()
when blockSquares is empty (30% of cases).

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-13 20:53:13 +01:00
Marco Costalba ff60dafe8d Simplify legality check in generate_evasions()
Now that we have removed sliders checkers attacks
from evasion's set we can simplyfy legality check.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-13 20:52:52 +01:00
Marco Costalba 214f9dcc27 generate_evasions() avoid an usless check for enpassant case
Remove ugly and useless code.
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-11 19:01:26 +01:00
Marco Costalba 1dc1cecf01 Optimize generate_piece_blocking_evasions()
Rewrite as in generate_piece_moves() using a for
loop instead of the slower serializing of the
bitboard with pop_1st_bit()

This will allow also to merge with generate_piece_moves()
when we will drop legality constrain on generate_evasions()

Generated moves are not changed, but are generated in a
different order, this changes the number of nodes at fixed
depth test.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-11 19:01:06 +01:00
Marco Costalba 67535711e8 generate_evasions() avoid to calculate pinned pieces
Pass as function argument.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-11 19:00:52 +01:00
Marco Costalba 56f607fe0f Drop a double semicolon
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-11 19:00:35 +01:00
Marco Costalba 9d044cf4ee Last touches to movegen.cpp
Of course no functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-10 19:01:51 +01:00
Marco Costalba 769f2fdecb Remove special case of pawn checks generation
Also additional renaming.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-10 19:01:49 +01:00
Marco Costalba 9bffe811c4 Remove special case of pawn move generatation
Code cleanup. No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-10 19:01:47 +01:00
Marco Costalba 3e20c6c07d Simplify generate_evasions()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-10 19:01:45 +01:00
Marco Costalba 4f5f97107e Simplify generate_checks()
Also rearrange signatures to be uniform.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-10 19:01:43 +01:00
Marco Costalba 151d47dc85 Micro-optimize do_generate_pawn_checks()
Discovery check candidates are normally empty, so
avoid discovery checks generation in that common case.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-10 19:01:41 +01:00
Marco Costalba 33ddeec5e0 Templetize generate_piece_checks_king()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-10 19:01:39 +01:00
Marco Costalba 4573d618e4 Small optimization in generate_evasions()
Find squares attacked by slider checkers, we will
remove them from king evasions set so to avoid a couple
of cycles in the slow king evasions legality check loop.

Not a biggie, but now generate_evasions() is faster then
generate_non_captures(), before was slower.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-07 13:26:57 +01:00
Marco Costalba 1156eb865b Simplify newly introduced castling_is_check()
Use bit_is_set() instead of open coding.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-07 13:26:50 +01:00
Marco Costalba 76381cbd69 Small code style tidy up
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-07 13:26:42 +01:00
Marco Costalba fa322b3768 Fix casting warnings under Intel Compiler
Int to Char warning fixed changing the function
signature to int.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-07 13:26:29 +01:00
Marco Costalba 2ea7449f2a Fix Makefile
Was broken after we removed color.cpp and square.cpp

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-07 13:26:17 +01:00
Marco Costalba ee6e8851be Templetize generate_castle_moves()
Cleanup the code and remove lines.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-06 07:14:38 +01:00
Marco Costalba 03211296f1 Add generation of castling checks
When we generate checks one case is missing: generation
of castling moves that give check to the opponent king.

This is a very rare case but anyway it is a case
and we can do this without slowing down the common
case of no castling checks.

So this is the patch.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-06 07:14:16 +01:00
Marco Costalba cc76951483 Remove square.cpp
Move the few stuff in square.h

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-04 19:41:56 +01:00
Marco Costalba f0858cd229 Move constants from piece.cpp to piece.h
Leave in piece.cpp only a couple of functions that
need #include <cstring>

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-04 19:41:38 +01:00
Marco Costalba 225d89c51b PawnInfo::clear() retire memset() and fix Ubuntu compile
Go back to original direct assignment, this allows to
add an include in pawns.h to teach about memset()

This fix a compile error under Ubuntu.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-04 19:41:17 +01:00
Marco Costalba 8bef9e59a0 Remove the useless color.cpp
Integrate the only (inline) function in color.h

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-04 19:40:43 +01:00
Marco Costalba 82bf08e4f2 Final endgame.cpp space inflate
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-04 19:40:31 +01:00
Marco Costalba c32904f0a0 Revert previous commit.
Optimization is correct but slightly slower
so it is a pessimization :-)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-02-04 19:40:09 +01:00
Marco Costalba 6cfb661ca5 Yet another count_1s() optimization
No functional change

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-25 19:29:15 +01:00
Marco Costalba be43219136 Rever count_1s() optimizations
They are wrong for all ones case.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-25 18:00:57 +01:00
Marco Costalba d5b77ad45e MovePicker, remove a variable
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-25 13:52:35 +01:00
Marco Costalba c6d62b7da5 MovePicker::find_best_index() never returns -1
So avoid checking for it.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-25 13:36:59 +01:00
Marco Costalba 3e6e57231e Rewrite count_1s() to be similar to 64bit counterpart
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-11 17:15:18 +01:00
Marco Costalba 14c1fd4d27 Micro optimize count_1s_max_15() for 32 bit system
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-11 17:05:29 +01:00
Marco Costalba 4b53bb02f6 Fix a very old bug in queen mobility
For queen mobility could be bigger then 15, so
we need count_1s() not count_1s_max_15().

This bug was introduced by patch:
"Group common evaluate code" of 24/9/2008

So it's almost 4 months and two release old!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-10 16:11:33 +01:00
Marco Costalba ec2927286a Start to space inflate endgame.cpp
Still a lot to do, it's a big file!

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-08 15:46:57 +01:00
Marco Costalba bdbbc4e06b Rewrite evaluate_common() as a template
Seems to speed up this very hot path and code is
cleaner too.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-07 15:48:22 +01:00
Marco Costalba 539051b1e0 Big trailing whitespace cleanup part 2
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-07 15:48:11 +01:00
Marco Costalba c97104e854 Big trailing whitespace cleanup part 1
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-07 15:47:59 +01:00
Marco Costalba 5cacefe7c6 Another micro-optmization in valuate_passed_pawns()
very small gain, but still a gain at the cost of
an extra indentation level.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-07 15:47:31 +01:00
Marco Costalba 9b87d151bc Fix a small bug in rook pawn evaluation
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-06 16:10:22 +01:00
Marco Costalba cbfbf25d1b evaluate_passed_pawns() micro-optmization
No functional change, only a bit faster.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-06 16:06:08 +01:00
Marco Costalba 90585a8a36 Final space inflate of evaluatio.cpp
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-06 15:59:08 +01:00
Marco Costalba e236a0c652 Space inflate evaluate_passed_pawns()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-06 15:49:33 +01:00
Marco Costalba d0804341c5 Piece mobility: filter out squares protected by pawns
Do not consider squares protected by enemy pawns
in mobility evaluation.

This reduces the mobility value by about 15%

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-05 15:14:16 +01:00
Marco Costalba dc4e2d8184 Take in account odd depths in razoring formula
This is somewhat taken from Stockfish 1.2 Default,
only the razoring thresold are updated, not the
razoring depth.

At the end razoring is a bit more aggressive. Results
seems slightly positive.

After 999 games +239 =536 -224 Elo +5

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2009-01-05 12:41:27 +01:00
Marco Costalba e828753a3a Fix dbg_mean_of() to enable statistics when called
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-30 12:54:21 +01:00
Marco Costalba 33bb8305a9 Restore development versioning and LSN filtering
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-30 12:42:23 +01:00
Marco Costalba cc3c1dc25a Stockfish 1.2 optimistic
Optimistic razoring settings. It is stronger with
most engines but weaker with someones.

The default is instead more solid and uniform with all
the opponents.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-29 12:24:34 +01:00
Marco Costalba 11763d2b7f Stockfish 1.2
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-29 12:18:49 +01:00
Marco Costalba d99a95df29 Micro optimization in extension()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-29 12:18:36 +01:00
Marco Costalba 0da1d6a846 Remove a gcc warning on an unused variable
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-29 12:18:23 +01:00
Marco Costalba 5d94305af3 Properly handle odd depths in razor formula
A little bit more aggressive, but should be more
in line with the depths logic.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-28 19:38:44 +01:00
Marco Costalba e4fd9a2df7 Safer razoring formula
Add also the possibility to razor at ply one.
It is disable dby default but it seems stronger
against Stockfish itself. It is still not clear if
is stronger against other engines. By now leave
disabled.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-28 12:55:33 +01:00
Marco Costalba aedc6c6f1f Don't silently accept an option name mismatch
With this we could have found earlier the futility
name option bug!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-28 12:37:13 +01:00
Marco Costalba dae4e7df07 Tweak again futility margings
Lower margins near the leafs, higher at high depth.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-25 20:08:45 +01:00
Marco Costalba 96a32eec69 Expose new futility margin interface to UCI
Now futility margin it's actually a scale factor
to apply to the base ones.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-25 19:41:24 +01:00
Marco Costalba e46d3670fd Tweak futility margins
Less prune at the bottom and at the middle, a bit more
at the top.

After 747 games: +215 =345 -187 +13 elo

Also introduced a vector of margins, now that start to be a lot
it is a more flexible solution.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-25 12:05:45 +01:00
Marco Costalba 8cd5cb930d Try razoring only for depth > OnePly
Because razoring verification after qsearch() cuts more
then 40% of candidates, do not waste a costly qsearch for
nodes at depth one that will be probably discarded anyway
by futility.

Also tight razoring conditions to keep dangerous false
negatives below 0,05%. Still not clear if it is enough.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-24 09:35:57 +01:00
Marco Costalba 2feb9d5100 Futility pruning till ply 6 included
Seems good:

After 796 games: +211 = 393 -192 +8 elo

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-24 09:34:09 +01:00
Marco Costalba d11426c777 Fix a comment
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-23 12:02:10 +01:00
Marco Costalba e96f56adfa Merge futility pruning from Glaurung 2.2
It seems much more powerful then previous one.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-23 12:01:48 +01:00
Marco Costalba e3b03f13b3 Passed pawns: consider enemy rooks or queens from behind
Merged from Glaurung 2.2

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-22 12:10:15 +01:00
Marco Costalba 54b7da120f King safety: retire rook contact check
Merged from Glaurung 2.2

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-22 12:07:00 +01:00
Marco Costalba 3fafc9768a Set the 'Problem' variable only at ply == 1
Bug fix merged from Glaurung 2.2 for search_pv()

Added the same fix also to sp_search_pv() where
was missing.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-22 11:44:00 +01:00
Marco Costalba 23490bd825 Retire EvaluatePawnStorms and UseEasyMove constants
Merged from Glaurung 2.2

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-21 20:10:20 +01:00
Marco Costalba 61c6a3d5a0 Merge cosmetics from Glaurung 2.2
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-21 17:02:34 +01:00
Marco Costalba 31d4f0b734 Merge space weigth evaluation fromGlaurung 2.2
Is a new evaluation rule that gives bonus in midgame
to the side that has more space behind pawns for its
minor pieces.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-21 16:26:36 +01:00
Marco Costalba f178f0a291 Merged two new endgames from Glaurung 2.2
It is two bishop against a knight and two minor
pieces against one minor piece.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-21 15:38:10 +01:00
Marco Costalba 72ca727b38 SEE: add support for enpassant moves
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-21 10:44:41 +01:00
Marco Costalba 2d0146fe1d Call poll() before to check for stopped search
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-21 10:44:12 +01:00
Marco Costalba 96d0501735 Less aggressive razoring
Use a margin to compare with beta so that positions
that after the verifying qsearch have gained a lot of points
are not discarded just becasue not above beta.

Also remove the second condition on depth <= OnePly, it
was too risky and added only a 2% more of pruned nodes.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-21 10:42:39 +01:00
Marco Costalba b58ad355ca Revert: "Do not razor when in check"
It is slightly weaker after 500 games. Keep the
check on mate values.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-18 22:01:56 +01:00
Marco Costalba 17000d1ea0 Trigger of PawnEndgameExtension if capture is not a pawn
Instead of a rook.

This gives an unexpected graeat increase!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-17 19:36:51 +01:00
Marco Costalba b09cbaebb9 search_pv: an enpassant move is a capture
Fix the logic in search_pv and sp_search_pv

An additional issue to consider is that a castle move
is not a capture but destination square is not empty.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-16 22:20:53 +01:00
Marco Costalba 725c504a5f qsearch: take in account enpassant in futility formula
Should not change anything at ELO level but it is
the correct thing to do.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-16 22:20:42 +01:00
Marco Costalba bfbfc24d07 qsearch: do not call evaluate when in check
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-16 22:20:18 +01:00
Marco Costalba a55b06d3c9 Restore development versioning and LSN filtering
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-15 22:23:03 +01:00
Marco Costalba ecc19381b4 Do not razor while in check or value is mate
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-15 22:20:03 +01:00
Marco Costalba dae2f600d6 Do not null search when beta is a mate value
Also do not return unproven mates in null search.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-15 22:19:25 +01:00
Marco Costalba 4c294932e7 Better document null move dynamic reduction
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-15 22:18:56 +01:00
Marco Costalba c831b00544 Introduce beta counters to order moves at ply one
Instead of number of searched nodes use the number of
opponent beta-cutoff occurred under the move subtree.

After 570 games 1+0 we have: +150 =288 -132 (+11 ELO)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-15 22:13:42 +01:00
Marco Costalba 5b853c9be6 Debugging: move debug function definitions in misc.cpp
Also activate writing on log file.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-14 17:26:05 +01:00
Marco Costalba 5f8f83bc05 Debugging: print to file
Print debug info on log file, not only on std::cout

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-14 14:57:17 +01:00
Marco Costalba 8ee3124487 Fix two bugs in ok_to_prune() (2)
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-12 22:27:43 +01:00
Marco Costalba 07b45151d2 Disable "Null driven IID" by default
Testing is not clear. Probably we need to test
at deeper depths to have some clear results.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-11 20:39:08 +01:00
Marco Costalba 9e3ab9099f Null move only for depth > OnePly
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-11 20:38:52 +01:00
Marco Costalba f09884d72f Null driven IID: remove IIDMargin from see() condition
This seems to cut searched nodes also more.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-10 21:43:09 +01:00
Marco Costalba ab29d8df67 Fix inflate pawns.cpp fallout
Catched counting the nodes searched at
fixed depth. A quick and reliable cross check,
expecially in inflate only patches.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-10 21:35:07 +01:00
Marco Costalba 389dc0e83b Add behind_bb() helper to simplify code logic
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-10 00:14:24 +01:00
Marco Costalba 67aac4889e Space inflate pawns.cpp
Hopefully no functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-10 00:14:15 +01:00
Marco Costalba aaad48464b Add a see() function that take only destination square
In this case firstlocates the least valuable attacker, if any,
then proceed as usual.

This will be used by next patch.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-10 00:13:59 +01:00
Marco Costalba 235df6a887 Stockfish 1.1a
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-08 12:03:46 +01:00
Marco Costalba 8d86c87e1e Add "Null driven IID" UCI option (default true)
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-08 10:57:40 +01:00
Marco Costalba c172af1b61 Null move driven internal iterative deepening
When a null move fails low due to a capture, try
to detect if without the capture we are above beta,
in this case there is a good possibility this is
a cut-node and the capture is just a null move
artifact due to side to move change. So if we still
don't have a TT move it's a good time to start an IID.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-08 10:46:52 +01:00
Marco Costalba b7c36d078b Stockfish 1.1
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-06 17:18:59 +01:00
Marco Costalba db1b0bfa1d Revert see() shortcut for LxH and equal captures
It happens that more then 70% of cases are HxL, where
we call see() anyway. The mesured saving of calling
see is about 0,5% of total time, but considering the
added burden in score_captures() the saving is only
0,35% locally and due to more difficult inlining of
the function it ends up that we have no advantage at all,
possibly a small slow down!

So revert.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-06 12:32:23 +01:00
Marco Costalba 6f946f823c Fix two gcc warnings in san.cpp
One good, the other silly.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-06 12:32:11 +01:00
Marco Costalba 2de78ebc7b Fix an Intel warning in san.cpp
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-06 12:31:48 +01:00
Marco Costalba 32934c0c8d MovePicker: avoid calling see() for LxH and equal captures
No functional change but should speed-up the captures scoring.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-06 11:37:19 +01:00
Marco Costalba b4fcfed55b Null capture pruning
Null move can fail low because of a capture artifact due
to the side to move change. Try to detect this condition
and fail high instead.

This pruning is very powerful, around 7% of nodes, but is
still experimental so is disabled by default.

Set UseNullCapturePruning to true to enable.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-06 11:31:14 +01:00
Marco Costalba dc2302b701 Position::move_is_capture() does not handle MOVE_NONE
Actually square 0 can be dirty, so that move_is_capture(0)
can return any random values.

Add an assert to be sure it is caught.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-06 11:18:31 +01:00
Marco Costalba 268c12bf31 Allow to call Position::print() from MovePicker
Fix a recursion issue that gives a stack overflow.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-06 11:18:08 +01:00
Marco Costalba 9f943a132a san.cpp: rewrite broken move_from_san
Use a state machine to parse the input. Fixed
the many broken cases.

Tested on more then 15 milions nodes.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-05 09:06:51 +01:00
Marco Costalba 20390fcb3c san.cpp cleanup
Hopefully no functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-12-05 09:06:30 +01:00
Marco Costalba d95b9189d8 Revert opponent time advantage logic
Strength increase was due to an hidden bug introduced
by the patch, namely the time per move to /30 instead
of /40 (see previous patch).

After testing this feature do not add any substantial
increase so is removed.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-30 19:23:33 +01:00
Marco Costalba 9d5d69e435 Revert sigmoid interpolator
After deep test (1000 games) it seems do not improve anything,
actually seems slightly weaker.

So remove it for now.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-30 21:16:47 +01:00
Marco Costalba 08265aef81 san.cpp pass position as constant reference
Make a copy of the position when needed instead
of passing as a reference. It is cleaner and
let us to simplify also Position::print()

A small space inflate while there.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-30 01:25:16 +01:00
Marco Costalba 9d1e4d041d piece_type_to_char() default argument in declaration
Default argument should be in declaration where it
is visible through header include, not in definition.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-30 00:38:33 +01:00
Marco Costalba cff3a6d33e Revert threat move ordering
Does not seem to improve anything.

Anyhow idea is nice, maybe we still have to find
correct recipe.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-26 11:22:30 +01:00
Marco Costalba 20a2ca366f Tweak allocated time per move
It seems better to give more time in middle game then
at the end.

Also Toga uses the same limit.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-25 20:41:06 +01:00
Marco Costalba c3ba5fb9d3 Rewrok the extendeable patch
Cleanup and document.

The real functional change is that not mate threat
moves are never pruned, as could happen before.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-25 20:40:49 +01:00
Marco Costalba eba8925d81 MovePicker: take advantage of threat move for ordering
If the null move was refuted by a capture then give a
bonus if we move away the captured piece.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-25 20:40:34 +01:00
Marco Costalba ee9f650242 Use extendable instead of depth extension
We can have depth(0) also in problematic cases
according to how extensions are tweaked by the user.

In any case we don't want to prune these moves.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-25 20:40:12 +01:00
Marco Costalba 8a0dd93c56 Generate moves for powerful pieces first
This seems to reduce searched nodes by a
surprising 2.5%

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-24 20:43:29 +01:00
Marco Costalba 5a72ff128e Benchmark: print nodes searched at the end of testing
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-24 20:43:11 +01:00
Marco Costalba 3f63dd1023 Easy debug macro enabling
Now you don't need to toggle show_debug_xxxx anymore

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-22 15:59:26 +01:00
Marco Costalba 62ab7e4612 Introduce node limited benchmarking
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-22 11:56:14 +01:00
Marco Costalba 1867785231 Introduce depth limited benchmarking
Also print some more info.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-22 11:02:05 +01:00
Marco Costalba bac4da70c9 Remove an include in movepick.h
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
Signed-off-by: unknown <Marco@.(none)>
2008-11-19 22:15:41 +01:00
Marco Costalba 8189ae9e1c Fix a silly bug that disabled second killer
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
Signed-off-by: unknown <Marco@.(none)>
2008-11-19 22:15:26 +01:00
Marco Costalba 1d525bb45f qsearch: restore pruning of pv nodes with negative SEE
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
Signed-off-by: unknown <Marco@.(none)>
2008-11-19 22:15:14 +01:00
Marco Costalba da7d872eda Fix Intel warnings and init_search_stack argument
Should be a reference not a copy!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:46:12 +01:00
Marco Costalba 49d52b8266 Set killer slots number to 2
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:37:48 +01:00
Marco Costalba 75d001addd MovePicker: fix a nasty bug in EvalInfo optimization
EvalInfo has missing attack info when a specialized
endgame function is used.

We missed this case and were using an empty attack bitboard
instead so that no captures were generated for endgames.

After testing the EvalInfo optimization gave worst results,
so after a (long) debug session this nasty bug was found.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:37:48 +01:00
Marco Costalba 7daaf03b39 Add and use update_killers()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:37:48 +01:00
Marco Costalba 2e778445d5 Add and use move_is_killer() helper
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:37:48 +01:00
Marco Costalba 93bc05cf69 Convert killers to a vector
Add infrastructure to threat killer moves as a vector,
this will allow us to easily parametrize the number of
killer moves, instead of hardcode this value to two as is now.

This patch just add the infrastructure, no functional
change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:37:47 +01:00
Marco Costalba a7227ac26f qsearch: do not prune pv nodes with negative SEE
Also small micro-optimization, take a line out of
the moves loop.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:37:47 +01:00
Marco Costalba bb0da595a7 Disable per-square MVV/LVA for now
Needs more testing.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:37:47 +01:00
Marco Costalba 20d7197a9b MovePicker: use EvalInfo to skip generating captures
When we know already no captures are possible in a given
position.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:37:46 +01:00
Marco Costalba f4758ced90 Position::to_fen(): fix a bug in side to move representation
Was introduced almost two months ago in patch:
"Space inflate Position::to_fen()"

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:37:46 +01:00
Marco Costalba 3c05bd70eb Print the move in addition to position
Teach Position::print() to optionally print a
given move in san notation in addition to
the ASCII representation of the board.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:37:46 +01:00
Marco Costalba 7000e100bd Enable per-square MVV/LVA
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:37:46 +01:00
Marco Costalba 2ed22e4fc8 MovePicker:find bad captures during scoring
Instead of pospone until picking. No functional
change and probably no performance change but it is
needed for following patch.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:37:46 +01:00
Marco Costalba 940c53c366 MovePicker: introduce per square MVV/LVA ordering
Just added the infrastructure, no functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:37:45 +01:00
Marco Costalba 4df8651c82 Fix hashfull info
Do not count has a replacement when a TT entry is
written in an empty slot.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-16 12:37:45 +01:00
Marco Costalba 2d4e2bc62a Fix in ok_to_history(): castle move is not a capture
It is erroneusly considered a capture because king
moves on the same square of the rook.

Use the correct function Position::move_is_capture()
instead of the open coded (and buggy) one.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-10 19:19:40 +01:00
Marco Costalba d89a03cc35 Small tidyup of TranspositionTable::store()
Hopefully without bugs this time!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-10 19:19:40 +01:00
Marco Costalba 34b1d0538b Fix a logic bug in TranspositionTable::store()
Make the logic work as advertised in the function
description.

Still a fallback from TT cleanup.

This should be less serious then the one in retrieve(),
but it's still a bug.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-10 19:19:40 +01:00
Marco Costalba cdf1f23bc5 Micro optimization of update_history()
Remove an useless comparison.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-10 19:19:40 +01:00
Marco Costalba e86468cc63 Use cut-off checks in qsearch as killer moves
Killers should not be captures, but checks are not
and are produced also in qsearch.

Use this information, will be useful for move ordering.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-10 19:19:40 +01:00
Marco Costalba e7bad2687a Smaller null move reduction when depth is high
Lower probability to miss something important.

It seems to increase strenght. Idea form Cyclone.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-10 19:19:39 +01:00
Marco Costalba 3f610e2b13 Introduce LastIterations variable
Is set during the last iteration.

Sometime also during the second last.

During the last iteration is set in the 95% of cases.

During the second last is set in the 40% of cases.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-10 19:19:39 +01:00
Marco Costalba 6cc11272e2 Restore development versioning and LSN filtering
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-10 19:19:39 +01:00
Marco Costalba a28c17ecb6 Fix a missed initialization in get_option_value()
Spotted and reported by Dann Corbit.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-04 20:59:11 +01:00
Marco Costalba ec23692433 Stockfish 1.01
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-04 20:56:30 +01:00
Marco Costalba 787d358554 Fix compile under Ubuntu 64bit
Some missing includes.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-04 20:56:30 +01:00
Marco Costalba ff0d9dad2b Fix a serious bug in TranspositionTable::retrieve()
Reported by Tord Romstad.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-04 20:56:30 +01:00
Marco Costalba 046fd4926f Restore development versioning
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-04 20:56:30 +01:00
Marco Costalba c595185b3c Restore LSN filtering
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-04 20:56:18 +01:00
Marco Costalba 1a158c0cf0 Revert movepick optimizations before to release
More testing is needed and better do not risk
just before release.

Reverted:

Disable LSN filtering as defualt for release
Use MVV/LVA in score_evasions()

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-02 15:58:10 +01:00
Marco Costalba 8097e99c69 Stockfish 1.0
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-02 15:35:32 +01:00
Marco Costalba 2fa9d25e82 Disable LSN filtering as defualt for release
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-02 15:35:02 +01:00
Marco Costalba 3e275680d5 Use MVV/LVA in score_evasions()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-02 15:00:28 +01:00
Marco Costalba d087b0a34a Delay SEE for scoring captures
Do not calculate SEE on all the moves in MovePicker::score_captures()
but delay until pick_move_from_list() when only the best ones are
double checked against their see value.

If a beta cut-off occurs then we avoid calculating SEE on all
the moves, but just the picked ones.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-02 15:00:28 +01:00
Marco Costalba 55b6464d40 search: micro optimization
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-02 15:00:28 +01:00
Marco Costalba b5232e2da3 Fix a couple of gcc warnings in position.cpp
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-02 15:00:19 +01:00
Marco Costalba 35bd334b30 Update README to Stockfish
Remove Glaurung references.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-02 15:00:09 +01:00
Marco Costalba 6e8bd8bf2d Final touches to material.cpp
No functional changes, altough a bit of code reshuffle.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:54 +01:00
Marco Costalba 899b9455d6 Material: lockless per-thread maps
Adds a good bunch of code but should be faster
and scalable because is lockless.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:54 +01:00
Marco Costalba 8b57416ace Revert "MovePicker::score_captures() order with SEE when pv"
Does not seem to increase the strenght.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:54 +01:00
Marco Costalba 1146fc8d09 Space inflate move.cpp
Also a little cleanup.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:53 +01:00
Marco Costalba 6e5cf2f3c5 Revert "Relax time constraints"
Does not seem to give an improvment, acutually it seems
a totally neutral change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:53 +01:00
Marco Costalba e5ebd4f5d1 Partially space inflate search.cpp
Space inflate main remaining functions in search.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:53 +01:00
Marco Costalba cf2bafb661 Relax time constraints
Allow a seacrh to take a bit more time if needed.

This reduces the chanches of wast all the search time
for the last iteration and also allow to start the last
iteration when we have less time remaining.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:53 +01:00
Marco Costalba 79513e3a43 Material: micro optimize map reading
Do only one map walk per read instead of two.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:52 +01:00
Marco Costalba bd3ec6af15 Material: protect global map access with locks
STL library is not guaranteed to be thread safe, even for
read-access.

So because these global maps are accessed by all the threads
we need to protect them.

This fixes a random crash experienced during testing.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:52 +01:00
Marco Costalba b2b86cfd27 MovePicker::score_captures() order with SEE when pv
Order PV nodes by SEE instead of MVV/LVA.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:52 +01:00
Marco Costalba 7d717df4e4 Revert "Last minute surprise" for now
It defenitly needs more testing. Just postponed.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:52 +01:00
Marco Costalba 5e906ea10e Finish material.cpp cleanup
Hopefully no regression this time!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:52 +01:00
Marco Costalba 73cce873de Start to simplify material.cpp
It is posisble to simplify a lot here!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:51 +01:00
Marco Costalba 038235ba35 Factor out Position::do_capture_move()
Start to slim line count i position.cpp

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:51 +01:00
Marco Costalba 5e2fc2aa16 Fix a bug in generate_evasions()
Introduced in the patch "movegen: prefer (*mlist++) to mlist[n++]"

This was nasty because due to a mismerge the repo in one PC had the bug,
but the testing one did not, so I had non reproducible results according
to which machine I used for testing.

This hopefully closes a more then one week regression that made me go crazy!

It was found by accident comparing, for other reasons, the sources of the
two PC's.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:51 +01:00
Marco Costalba 74fd57220e Refine "few moves" in "last minute surprise"
It seems that "few moves" works because we extend the good
captures at the last ply of PV, so code it directly.

This version seems defenitly stronger then previous one.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-11-01 12:46:51 +01:00
Marco Costalba 74f1efee26 Manual merge 2008-10-26 21:44:58 +01:00
Marco Costalba 0936a96a0e Space inflate extension() code
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-26 21:30:21 +01:00
Marco Costalba 13d1776a98 TEST: extend when few moves available
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-26 21:30:21 +01:00
Marco Costalba a56e1c662c Revert see shortcut when only one attacker
It does not seem to work after a little testing.

Perhaps it works on the long terms, but it is also
ugly because not correct, so revert for now.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-26 21:30:21 +01:00
Marco Costalba fcc49561a1 Prefer out of loop variables in MovePicker::score_captures()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-26 21:30:21 +01:00
Marco Costalba 714069e248 Effectively use MVV/LVA in MovePicker::score_captures()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-26 21:30:20 +01:00
Marco Costalba 88885399f4 Reintroduce piece/square tables to score non-captures
Was removed after original movepick restore. But proved
to be useful.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-26 21:30:20 +01:00
Marco Costalba a5c1b3e8f6 Position: fix a couple of Intel compiler warnings
Plus usual trailing whitespace.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-26 13:23:27 +01:00
Marco Costalba 8a85007023 Test with SEE shortcut
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-26 10:11:13 +01:00
Marco Costalba 4397e6c03e Better naming of pseudo-legality and legality testing
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-26 10:11:13 +01:00
Marco Costalba 4f14bd5032 Try to cleanup movepick
Hopefully without regressions.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-26 10:11:13 +01:00
Marco Costalba f8bc38a006 Restore original movepick modulo space inflation
We have a regression somewhere here so restart from zero
and proceed one change at a time.

With this modification we have the same strenght of
"Introduce Stockfish" patch that is our strongest to date.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-26 10:11:13 +01:00
Marco Costalba 5dd9159106 Space inflate position: complete!
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-26 10:10:56 +01:00
Marco Costalba ad956ef00a Space inflate position until do_promotion_move()
We will end some day ;-)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-24 21:10:05 +02:00
Marco Costalba d155cd88d1 Start to space inflate position.cpp
It's a big file!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-24 21:10:05 +02:00
Marco Costalba 2aebf8eb55 Fix a performance bug in generate_move_if_legal
Use the pinned argument in pos.move_is_legal()

No functional change, simply use pos.move_is_legal() as
was meant to be.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-24 21:10:05 +02:00
Marco Costalba 1ac2f50145 Unify pinned and discovery checks code
Templates are our friends here. No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-24 21:10:04 +02:00
Marco Costalba af59cb1d63 Refactor Position::pinned_pieces() to use templates
Also better document this interesting function.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-24 21:10:04 +02:00
Marco Costalba 2f8961beef movegen: add SERIALIZE_MOVES and hides a bunch of loops
Only syntactic sugar, perhaps we should leave as is, anyhow...

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-24 21:10:04 +02:00
Marco Costalba af5743837d Another generate_piece_moves() micro optimization
This time on the for loop.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-24 21:10:04 +02:00
Marco Costalba 5e768e4b0a Fix another template conversion bug in movegen
Hopefully the last one.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-24 21:09:51 +02:00
Marco Costalba 2d867109d9 movegen: prefer (*mlist++) to mlist[n++]
Teoretically faster, practically it helps to
removes some more lines.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-23 07:17:04 +02:00
Marco Costalba b145e99559 Fix a bug in generate_pawn_captures()
Introduced in "movegen: Introduce generate_pawn_captures()"
when unifiying black and white functions.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-23 07:17:04 +02:00
Marco Costalba 8f2c1c59eb Fully templetize pawn move generators
A little bit more syntax heavuer but surely faster.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-23 07:17:04 +02:00
Marco Costalba c40249e9d2 Micro optimize generate_piece_moves()
It is a time critical path. The biggest in move generation.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-21 00:10:27 +02:00
Marco Costalba ce93a202b5 Another Intel warning sqeezed
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:57:13 +02:00
Marco Costalba 279ed7ed48 Quiet a warning on Intel compiler
Plus usual trailing whitespace noise.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:55:43 +02:00
Marco Costalba af6571856e Shrink arguments in move generation functions
Perhaps no speedup, but it is more readable.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:21 +02:00
Marco Costalba 0c8659721f Fix a bug in king discoveries checks
Introduced in "Add a generate_piece_checks() specialization for the king"

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:20 +02:00
Marco Costalba 5dc2312121 Update copyright info
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:20 +02:00
Marco Costalba aa94f2f4c2 Last little touches to movegen
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:19 +02:00
Marco Costalba d7161c1ce6 Rename PawnOffsets in PawnParams
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:19 +02:00
Marco Costalba e2af0e775b Pawn move generator: dispatch at compile time
Instead of function pointers use templates to
dispatch shift operations.

It is more clear and possibly also faster because
branches are removed at compile time.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:19 +02:00
Marco Costalba ad1bb084dd Start to templetize pawn move generators
Still very soft, we will see if compiler is
enough or we need more aggressive templetization.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:18 +02:00
Marco Costalba 760f77872f Remove Positions::xxx_count() functions
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:18 +02:00
Marco Costalba 257689dec7 Remove white/black_pawn_attacks_square()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:18 +02:00
Marco Costalba ff211469ba Templetize Position::xxx_attacks_square()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:17 +02:00
Marco Costalba d4f14a8e83 Remove Position::xxx_list() functions
No useful, only obfuscating.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:17 +02:00
Marco Costalba 7eb290a509 Add a generate_piece_checks() specialization for the king
Also reshuffle the code a bit.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:17 +02:00
Marco Costalba d316b02771 Remove white/black_pawn_attacks()
Unuseful syntactic sugar, obfuscates the
real code.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:17 +02:00
Marco Costalba d9e54ceaa1 Prefer template to name decoration
This also allows faster code although bigger.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:16 +02:00
Marco Costalba 691de79eaa Fix a missing comma in BenchmarkPositions[]
An old bug introduced in 3e0dc9ee84 almost
one month ago.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:16 +02:00
Marco Costalba 3f38cca072 Position::is_ok()give more info on failed test
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:16 +02:00
Marco Costalba 6b8a07eccc Fix an assert due to a missing parentesis
Bitwise operators precedence issue here, was
causing an assert.

This is a fallout from recent patches.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:15 +02:00
Marco Costalba 8e85aa3a65 Final semplification of generate_evasions()
Now it's readable!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:15 +02:00
Marco Costalba 4f18528a1c Introduce generate_piece_blocking_evasions()
Start to simplify generate_evasions

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:15 +02:00
Marco Costalba 4a4d62da13 Space inflate generate_evasions()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-20 21:47:15 +02:00
Marco Costalba d3600c39a7 Update copyright info
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 20:43:33 +01:00
Marco Costalba f664ca41ed Last little touches to movegen
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 20:43:21 +01:00
Marco Costalba b397426785 Rename PawnOffsets in PawnParams
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 20:43:09 +01:00
Marco Costalba 68c78400c8 Pawn move generator: dispatch at compile time
Instead of function pointers use templates to
dispatch shift operations.

It is more clear and possibly also faster because
branches are removed at compile time.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 20:42:12 +01:00
Marco Costalba 1bd1f5a293 Start to templetize pawn move generators
Still very soft, we will see if compiler is
enough or we need more aggressive templetization.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 16:20:21 +01:00
Marco Costalba d0e51bc0f0 Remove Positions::xxx_count() functions
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 14:39:29 +01:00
Marco Costalba 0d19437703 Remove white/black_pawn_attacks_square()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 14:06:06 +01:00
Marco Costalba 8b5519a009 Templetize Position::xxx_attacks_square()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 13:56:57 +01:00
Marco Costalba 1eae58523f Remove Position::xxx_list() functions
No useful, only obfuscating.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 13:44:25 +01:00
Marco Costalba 305b711ca8 Add a generate_piece_checks() specialization for the king
Also reshuffle the code a bit.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 13:22:03 +01:00
Marco Costalba 2bea93975e Remove white/black_pawn_attacks()
Unuseful syntactic sugar, obfuscates the
real code.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 12:53:51 +01:00
Marco Costalba f036239521 Prefer template to name decoration
This also allows faster code although bigger.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 12:43:09 +01:00
Marco Costalba 832a8a2719 Fix a missing comma in BenchmarkPositions[]
An old bug introduced in 3e0dc9ee84 almost
one month ago.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 11:55:53 +01:00
Marco Costalba 11910d44e0 Position::is_ok()give more info on failed test
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 10:41:24 +01:00
Marco Costalba 00bcc64787 Fix an assert due to a missing parentesis
Bitwise operators precedence issue here, was
causing an assert.

This is a fallout from recent patches.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 10:17:17 +01:00
Marco Costalba f2ead1004a Final semplification of generate_evasions()
Now it's readable!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 09:33:33 +01:00
Marco Costalba 84ce43498a Introduce generate_piece_blocking_evasions()
Start to simplify generate_evasions

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 08:49:26 +01:00
Marco Costalba 987ff3b4b6 Space inflate generate_evasions()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-19 08:27:24 +01:00
Marco Costalba 72289fcfab movegen: Introduce generate_pawn_noncaptures()
This is the last of pawn moves generators converted
to new unified form.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:35 +02:00
Marco Costalba 73d0d2c0b2 movegen: Introduce generate_pawn_captures()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:35 +02:00
Marco Costalba c1257d45b2 movegen: Fix just introduced move counter bug
This is what happens when you don't tests your patches !!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:35 +02:00
Marco Costalba 34a515f20b movegen: Introduce generate_pawn_checks()
This greatly simplify redundant code.

Perhaps slihtly slower. Test needed.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:35 +02:00
Marco Costalba 5abe8a0816 generate_checks: fix a bug in black double pawn push
It was written pos.black_pawn_attacks(ksq) instead of
pos.white_pawn_attacks(ksq)

Updated to the undrlying pos.pawn_attacks(WHITE, ksq)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:34 +02:00
Marco Costalba 35fd5ce5bc Space inflate generate_castle_moves()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:34 +02:00
Marco Costalba 146bb2dfa7 Unify pieces check generation with generate_piece_checks()
Could be slower: test needed!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:34 +02:00
Marco Costalba ea16985ea5 Do not special case generate_king_moves()
Teoretically a little slowdown. If after testing we
verify the slowdown has impact on ELO we revert the
change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:34 +02:00
Marco Costalba 3b857d1625 Use a const pointer-to-member array for attacks
Allow the compiler to optimize member
function access.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:34 +02:00
Marco Costalba aa7121297d Use pointer-to-members to remove a bunch of duplicated code
Remove all generate_XXX_moves() functions, use an array
of pointer to members instead.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:34 +02:00
Marco Costalba 94f1b31484 movegen: revert see ordering in score_captures()
It works better with MVV ordering.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:33 +02:00
Marco Costalba c852a94009 Movegen: further simplify generate_move_if_legal
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:33 +02:00
Marco Costalba 8be2c483a1 Unify black and white code in generate_move_if_legal()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:33 +02:00
Marco Costalba 158911425b Space inflate movegen.cpp
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:33 +02:00
Marco Costalba cf8ee79b76 Movepick: add and use find_best_index() helper
This removes a bunch of redundant code.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:33 +02:00
Marco Costalba 06d6468ce9 Test with see
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:33 +02:00
Marco Costalba 173ecc0acf Use MVV to score captures when see >=0
This fix a couple of dubious bugs in MVV/LVA
ordering.

Tests seems to confirm now is slightly better.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:32 +02:00
Marco Costalba 2943e1ca31 MovePicker: use const reference instead of pointers
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:32 +02:00
Marco Costalba 486ec580f9 Space inflate movepick.cpp
Also added some FIXME to dubious points.

Still no functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:32 +02:00
Marco Costalba a930aafce0 Better comment previous patch
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:32 +02:00
Marco Costalba b3744eb4d0 Always add psqt scoring
When there is also history, history is always
preferred.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:32 +02:00
Marco Costalba a03ab94f44 Shortcut sorting when no move is in history
An alternative algorithm to psqt scoring.

Still unclear what is the best, more tests needed.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-18 21:35:20 +02:00
Marco Costalba 644db060ae Add psqt ordering when there is no history
This seems to increase strenght (about 15 ELO),
still to test some variations on this theme that
could increase ELO even more.

Idea from Rebel (http://members.home.nl/matador/chess840.htm)

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-15 07:18:05 +01:00
unknown cb76e4a814 Introduce Stockfish
Signed-off-by: unknown <Marco@.(none)>
2008-10-13 22:45:47 +01:00
Marco Costalba d8268024a9 Implement Last Seconds Noise (LSN) filtering
When an engine is in deep trouble at few
seconds from time limit then giveup without
fighting anymore.

This is used to reduce "lucky draws" and time pressure
blunders noises that can obfuscate results during tests
blitz games (typical one minute games).

Goal of this technique is to reduce number of matches
needed to reliably prove then an engine A is stronger
then an opponent B.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-13 20:40:48 +02:00
Marco Costalba 4fa5dd4db5 Add a second margin to razoring
Razor on ply one if the advantage is more then a pawn,
the only way to gap the advantage is to capture, so
go directly in quiesce.

This seems to have a positive effect.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-13 20:40:47 +02:00
Marco Costalba 58c7a5c477 Workaround a static data member bug in MSVC
Without this patch MSVC crashes when compiled
in release mode. It survives and works as
expected in debug mode and with gcc and Intel
compilers.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-13 20:40:47 +02:00
Marco Costalba 3901affb1d Yet another pop_1st_bit() optimization
Always for 32 bit but withot relying on MSVC intrinsics.

It is very similar to previous ones, but this does not
segfaults due to -fno-strict-aliasing compiler option.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-12 14:34:54 +02:00
Marco Costalba a6017aa728 Add mean calculation in debug tools
Another simple performance counter...

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-11 19:25:16 +02:00
Marco Costalba 6a15df1d82 Revert bad capture pruning
After testing does not seem to increase ELO.

Indeed Glaurung is a little bit weaker, so revert.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-11 19:03:59 +02:00
Marco Costalba bbf7a94d76 Better interface to get the current move type
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-06 05:44:23 +02:00
Marco Costalba a3477af2a1 Allow to prune bad captures
Only good capture are preserved from futility pruning
and LMR reducing.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-06 05:44:23 +02:00
Marco Costalba 310e07f292 Teach MovePicker::get_next_move() to return move type
This will be used in future patches.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-06 05:44:22 +02:00
Marco Costalba ea7bebb604 Fix single digit day in engine_name()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-05 10:37:05 +02:00
Marco Costalba 54071312f3 Add dbg_before() and dbg_after()
Other two debug utilities to compute filter rate.

Usage is:

dbg_before(); // counts passages from this point

if(..) // complex code stuff you want to audit
  return/continue
if(...)
  .....

dbg_after(); // counts passages from this point

Then somewhere in the code, normally in poll() add
dbg_print_hit_rate() and you will see the filter rate
of your code under auditing.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-04 10:01:54 +02:00
Marco Costalba 849809e97e Space inflate Position::to_fen()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-10-04 09:50:19 +02:00
Marco Costalba e9e51da4b8 position.cpp: fix a typo introduced by recent patch
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-28 10:59:20 +02:00
Marco Costalba f1f887b6d7 Use relative values in piece square tables
So that will be automatically changed when
pieces values change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-28 10:59:08 +02:00
Marco Costalba 88bb3c9422 Start to cleanup position.cpp
Still a lot to do. No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-28 10:58:56 +02:00
Marco Costalba 8d76de820f Add dbg_hit_on_c(c, x) tool
Like dbg_hit_on(x) but first filter out events and
only when condition 'c' is true the hit counter
is tested with 'x'.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-28 10:58:47 +02:00
Marco Costalba b00abed181 Space inflate evaluate_king()
This is the most complex piece of software
so far.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-26 05:54:49 +02:00
Marco Costalba 2e3faae067 Clarify difference between king zone and adjacent zone
There are subtle differences in the king evaluation
that should be clear to avoid misunderstandings.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-26 05:54:49 +02:00
Marco Costalba 453e815d4b Tidy up quick_evaluate()
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-26 05:54:49 +02:00
Marco Costalba 3e0dc9ee84 Tidy up middle game specific evaluation
Also add starting position to benchmarks.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-26 05:54:49 +02:00
Marco Costalba 597ef38c39 Code style massage evaluate()
No functional changes.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-26 05:54:49 +02:00
Marco Costalba d6618d7325 Add auto configuration for 32/64 bits
Instead of manually adjust defines in bitboard.h
now proper ones are automatically set.

It is anyhow possible to still set them manually
in case of problems.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-25 07:51:56 +02:00
Marco Costalba 3ee3cdc09b Evaluate: weight_option() is static
Declare function under local namespace. This removes a
warning from the picky Intel compiler.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-24 21:17:28 +02:00
Marco Costalba ca891e9760 Cleanup read_weights() in evaluate.cpp
Exception to 80 colums rule here, but result
seems better.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-24 21:02:16 +02:00
Marco Costalba dfcfed6432 Evaluate: rename king attack variables
A better naming IMHO

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-24 21:02:15 +02:00
Marco Costalba 34ca22486a Further cleanup evaluate()
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-24 21:02:15 +02:00
Marco Costalba f56af8e84d Rename pawn_rank() in relative_rank()
It is more clear, at last for me.

Also cleanup evaluate_rook() and evaluate_queen()

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-24 21:02:15 +02:00
Marco Costalba 3263ee8557 Add also outposts evaluation in common code
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-24 21:02:14 +02:00
Marco Costalba 853ce65f17 Group common evaluate code
This removes code redundancy but perhaps
impact performance due to uninlining.

Testing for regression is needed. For now
aim to best code readibility.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-24 21:02:14 +02:00
Marco Costalba 7dd0c39714 Warnings termination fest
A bunch of Intel C++ warnings removed, other silent out.

Still few remaining but need deeper look.

Also usual whitespace crap removal noise.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-24 00:32:53 +02:00
Marco Costalba 060eef4f4e Do not use evaluate() for razoring
Because razoring is reached 10% of times and about 50% of time
first two conditions are met we can save 5% of calls to the fairly
costly evaluate().

On the other side statistics have shown 95% of nodes that pass
the first two razoring conditions pass also the evaluate() test.
So the risk of dropping the third condition seems low enough.

Testing seems to validate this.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-23 23:36:51 +02:00
Marco Costalba 67f975e56b init_eval: small cleanup
Functionality not changed.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-23 08:07:50 +02:00
Marco Costalba 1d8994402b Fix InitKingDanger initialization
Last line was missing.

Also reformat tables constants to be more readable.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-23 08:07:42 +02:00
Marco Costalba 2a3ebc884e Optimize pop_1st_bit() take 2
This time we use MSVC intrinsics that are
C wrappers for Intel assembler 'bsf' instruction.

The speed up in node count is around 3%, probably
it does not worth the effort. Anyway this patch
can be useful at least for documentation purposes.

This optimization covers 32 bit systems only.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-21 22:19:07 +02:00
Marco Costalba 01dd46a309 Change the name to Glaurung clone
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-21 11:51:38 +02:00
Marco Costalba e5cc6f6b85 Switch to developer version numbering
Also clean up code while there.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-21 11:23:50 +02:00
Marco Costalba 29b01b6d82 Use optimized pop_1st_bit() only under Windows
Under Linux we have a segfault after a random time,
about a couple of minutes while running the benchmark.

This happens both with gcc and icc, and both with O2
and O3 optimizations.

Disable for Linux until we understand what's the deal.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-20 22:19:54 +02:00
Marco Costalba cde7b30b65 Add new superlinear interpolator
Faster transition and between phases and
more persistent during mid and ending game.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-20 21:56:46 +02:00
Marco Costalba 2dbc8feae3 Finally remove last old C style I/O stuff
Now I/O is fully done with C++ iostreams.

The only exception is in non-windows version
of Bioskey() in misc.cpp

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-20 06:53:06 +02:00
Marco Costalba c034cce27c Convert book.cpp to use C++ I/O
Instead of old C stdio.h

Also small code clean up while there.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-19 13:53:36 +02:00
Marco Costalba 1373a00187 Final touches to pop_1st_bit optimization
This final version is a little bit faster then
previous patch and is a bit cleaned up also.

On 32 bit x86 pop_1st_bit is now more then
two times faster then the original one that
is optimized for 64 bit processors.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-19 05:33:55 +02:00
Marco Costalba 9ae2b69235 Optimize pop_1st_bit() on 32 bits x86
Operations on 64 bits Bitboard types are slow
on x86 compiled with gcc, so optimize this case.

BTW profiling shows that pop_1st_bit() is a
veeery performance critical path!

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-18 16:09:19 +02:00
Marco Costalba 95ce27f926 Ignore non keyboard events in Bioskey()
Filter out mouse and windows type events.

This fix an issue where Glaurung hangs in console mode
under Windows.

To reproduce simply open a console under Windows (cmd.exe),
run "glaurung.exe bench 50 1", this starts benchmarking.
Then hide the windows and show again or clik the mouse
somewhere on the window, this hangs the benchmark
because Boiskey() returns true and poll() calls std::getline()
that hangs waiting for user pressing a return key.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-18 12:27:10 +02:00
Marco Costalba 5c4f6f6226 Cleanup poll()
Reshape this function in preparation
for future work.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-18 12:27:09 +02:00
Marco Costalba 18860cce40 Improve time managment
If we need some more and we are in time
advantage take it.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-18 12:27:09 +02:00
Marco Costalba d583176baf Pass also opponent time to think()
This patch modifies think() signature to accept
also opponent time. This is needed for future
changes to time managment.

Still no functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-18 12:27:09 +02:00
Marco Costalba 4c5eaeb363 Disable a stupid and noisy MSVC warning
Remove the crap from compiler messages.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-18 12:27:09 +02:00
Marco Costalba 925f97f4e7 Teach Benchmark to read positions from a file
This comes handy to test the engine on different
sets of positions, not only the 15 default ones.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-18 12:27:08 +02:00
Marco Costalba f1e245850f Reformat benchmark interface
Prepare to following patches, still no functional
change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-18 12:26:39 +02:00
Marco Costalba 2f5012a3eb Fix another conversion warning: Bitboard->int
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-18 12:26:31 +02:00
Marco Costalba 94929c36bd Document where we want a uint16_t instead of a uint64_t
This patch removes some conversion warnings and
better describe where we are going to expect a
small integer.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-18 12:26:24 +02:00
Marco Costalba a0aa8e760a Use size_t instead of int
Remove some warning.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-18 12:26:18 +02:00
Marco Costalba 52487c4f04 MovePicker: simplify move swapping
We don't need a full swap here because once found
and returned the best move will not be used again.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-18 12:26:10 +02:00
Marco Costalba 5080e72ea5 Prefer strncpy() to strcpy()
This removes a warning under MSVC++

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-18 12:25:55 +02:00
Marco Costalba 295352d04a Fix: "Ponder" option has type bool not int
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-18 12:25:22 +02:00
Marco Costalba 421fd9c3bf Space inflate sp_search_pv
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-09 11:37:27 +02:00
Marco Costalba eacb42092b Space inflate sp_search
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-09 11:15:58 +02:00
Marco Costalba a10c9632a5 Use TT in qsearch
Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-09 07:37:46 +02:00
Marco Costalba bc4e937f05 search: fix a bug and clear history update
When a move produces a beta-cut off is marked as
success in history and all the remaining ones are
marked as failures.

The loop across the searched moves, that is used
to register failures, does not skip the good one,
that is then registered as a failure too.

The patch fixes the bug and cleanup the code.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-07 09:38:19 +02:00
Marco Costalba 6c592955e1 Space inflate qsearch
No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-07 08:31:30 +02:00
Marco Costalba d517080ab6 Space inflate search()
Same as previous patch but for search() function.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-06 18:25:58 +02:00
Marco Costalba b7781e8faa search_pv: spaces inflate
It seems easier to understand, at least to me.

Hopefully no functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-06 17:12:39 +02:00
Marco Costalba a230dc1404 Split transposition table lookup in a separate function
This slims down the code and is a prerequisite for
future patches.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-06 15:53:43 +02:00
Marco Costalba c2c0ba875f TranspositionTable: add first_entry() helper
An inline function to retrieve the first TT entry
given a position.

Plus usual whitespace noise.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-06 12:30:07 +02:00
Marco Costalba 61f41a057d Add simple debug hit rate counter
Add a very simple debug framework to
measure the hit rate of a given condition.

Simply insert macro

dbg_hit_on(x);

Anywhere you want to compute hit rate of condition x
and then call, as example in poll(), function
dbg_print_hit_rate() to print current results.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-06 12:22:10 +02:00
Marco Costalba d786822b92 TranspositionTable: micro optimize first cycle
In the common case (>95%) tte == replace so skip
additional comparisons in this case.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-06 12:21:08 +02:00
Marco Costalba 392360e73b TranspositionTable: early skip on an empty TT entry
Instead of going for the whole 4 cycle loop early
skip if TT entry is empty.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-06 12:20:28 +02:00
Marco Costalba 7c93b171cb TranspositionTable: spaces inflate
No functional change, just a tidy up in
preparation for next patches.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-06 12:19:29 +02:00
Marco Costalba dad9a1eca7 RootMoveList: inline trivial accessors
Although not performance critical, trivial
accessors can be inlined without any harm.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-06 06:37:00 +02:00
Marco Costalba 731a9f3806 RootMoveList sorting: be compatible with std::sort
sort() and sort_multipv() are almost the same, so
use only one implementation.

Also introduce the natural RootMove::operator<() to
compare the moves instead of compare_root_moves(),
this will allow to use std::sort instead of our
home grown bubble-sort.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-05 09:04:45 +02:00
Marco Costalba bd3fd6501b scan_for_easy_move: we don't need a loop here
Moves are already sorted, so just consider the best
and the second one.

Some trailing whitespace remove noise crept in due
to my editor removes it before to save.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-03 23:33:49 +02:00
Marco Costalba 9ec12da028 Better document RootMoveList c'tor
Also some code tidy-up.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-03 23:29:04 +02:00
Marco Costalba 973eb543a4 Fix a couple of bugs (fallout from previous patches)
After testing and comparing output with standard Glaurung
a couple of issues arised.

A default value was wrong and init_uci_options() missed a couple
of stringify() calls. Also storing bool values as "false" and "true"
needs some care.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-01 22:05:23 +02:00
Marco Costalba e5068c4734 ucioptions: Fix stringification of a bool
We want stringify a bool as "true" and "false",
not "1" and "0".

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-01 16:58:02 +02:00
Marco Costalba 35010b4938 Preserve options order when printed
Use a vector instead of a map so that options
are printed according to their original order.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-01 16:03:01 +02:00
Marco Costalba 6c64f68ccf Rewrite ucioptions.cpp to use C++
Instead of old-style C string functions use standard
library to greatly streamline the implementation.

No functional change.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-01 14:05:02 +02:00
Marco Costalba 6ef44d4c4e Finally remove UCIInputParser class altogether
Class UCIInputParser is now a typedef of a std::istringstream,
this greatly simplifies the code, especially the many conversions
from string to integer are now handled automatically by the
stream instead of relying on a chunk of C-style atoi() calls.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-01 08:16:17 +02:00
Marco Costalba d22aeb1cc0 Use a string stream in UCIInputParser
Use a std::istringstream instead of an home
grown string tokenizer code.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-01 08:06:34 +02:00
Marco Costalba b8e487ff9c Avoid casts to handle isspace() arguments
Use proper standard conversion to deal
with negative values of a char.

Signed-off-by: Marco Costalba <mcostalba@gmail.com>
2008-09-01 08:03:21 +02:00
65 changed files with 9439 additions and 9823 deletions
+29 -266
View File
@@ -1,33 +1,28 @@
1. Introduction 1. Introduction
--------------- ---------------
Glaurung is a free UCI chess engine. It is not a complete chess Stockfish is a free UCI chess engine derived from Glaurung 2.1. It is
program, but requires some UCI compatible GUI (like XBoard with not a complete chess program, but requires some UCI compatible GUI
PolyGlot, eboard, José, Arena, Sigma Chess, Shredder, Chess Partner, (like XBoard with PolyGlot, eboard, Jos, Arena, Sigma Chess, Shredder,
or Fritz) in order to be used comfortably. Read the documentation for Chess Partner, or Fritz) in order to be used comfortably. Read the
your GUI of choice for information about how to use Glaurung with your documentation for your GUI of choice for information about how to use
GUI. Stockfish with your GUI.
Glaurung 2 is a completely rewritten version of Glaurung. Apart from This version of Stockfish supports up to 8 CPUs, but has not been
the parallel search code, almost no code is shared with Glaurung
1.2.1, the previous stable version. The new program is clearly
stronger than the old, but has a less attractive style of play,
because there are still a few major holes in its evaluation function
(most notably space and development).
This version of Glaurung supports up to 8 CPUs, but has not been
tested thoroughly with more than 2. The program tries to detect the 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 number of CPUs on your computer and set the number of search threads
accordingly, but please be aware that the detection is not always accordingly, but please be aware that the detection is not always
correct. It is therefore recommended to inspect the value of the correct. It is therefore recommended to inspect the value of the
"Threads" UCI parameter, and to make sure it equals the number of CPU "Threads" UCI parameter, and to make sure it equals the number of CPU
cores on your computer. cores on your computer. If you are using more than four threads, it
is recommended to raise the value of "Minimum Split Depth" UCI parameter
to 6.
2. Files 2. Files
-------- --------
This distribution of Glaurung consists of the following files: This distribution of Stockfish consists of the following files:
* Readme.txt, the file you are currently reading. * Readme.txt, the file you are currently reading.
@@ -35,284 +30,53 @@ This distribution of Glaurung consists of the following files:
License. License.
* src/, a subdirectory containing the full source code, including a * src/, a subdirectory containing the full source code, including a
Makefile that can be used to compile Glaurung on Unix-like Makefile that can be used to compile Stockfish on Unix-like
systems. For further information about how to compile Glaurung systems. For further information about how to compile Stockfish
yourself, read section 4 below. yourself, read section 4 below.
* MacOSX/, a subdirectory containing excutables for Apple Macintosh * polyglot.ini, for using Stockfish with Fabien Letouzey's PolyGlot
computers running Mac OS X 10.4 (Tiger) and newer. There are two
executables, one for OS X 10.4, and one for OS X 10.5. The
executable for OS X 10.4 will work in 10.5 as well, but the one
for 10.5 is faster.
* LinuxX86/, a subdirectory containing 32-bit and 64-bit x86 GNU/Linux
executables.
* Windows/, a subdirectory containing 32-bit and 64-bit Windows
executables.
* polyglot.ini, for using Glaurung with Fabien Letouzey's PolyGlot
adapter. adapter.
3. Opening books 3. Opening books
---------------- ----------------
This version of Glaurung has experimental support for PolyGlot opening This version of Stockfish has experimental support for PolyGlot opening
books. For information about how to create such books, consult the books. For information about how to create such books, consult the
PolyGlot documentation. The book file can be selected by setting the PolyGlot documentation. The book file can be selected by setting the
UCI parameter "Book File". UCI parameter "Book File".
A book file contributed by Salvo Spitaleri can be found on the
Glaurung web page.
4. Compiling it yourself 4. Compiling it yourself
------------------------ ------------------------
On Unix-like systems, it should usually be possible to compile On Unix-like systems, it should usually be possible to compile
Glaurung directly from the source code with the included Makefile. Stockfish directly from the source code with the included Makefile.
The exception is computer with big-endian CPUs, like PowerPC The exception is computer with big-endian CPUs, like PowerPC
Macintoshes. Some of the bitboard routines in the current version of Macintoshes. Some of the bitboard routines in the current version of
Glaurung are endianness-sensitive, and won't work on a big-endian CPU. Stockfish are endianness-sensitive, and won't work on a big-endian CPU.
Ensuring that the line with #define USE_32BIT_ATTACKS" near the top
of bitboard.h is commented out should solve this problem.
Commenting out the line with "#define USE_32BIT_ATTACKS" near the
There is also a problem with compiling Glaurung on certain 64-bit Stockfish has POPCNT instruction runtime detection and support. This can
systems, regardless of the endianness. If Glaurung segfaults give an extra speed on Core i7 or similar systems. To enable this feature
immediately after startup, try to comment out the line with (disabled by default) simply uncomment #define USE_POPCNT in bitcount.h
"#define USE_FOLDED_BITSCAN" near the beginning of bitboard.h and before to compile.
recompile.
Finally, even if Glaurung does work without any changes on your On 64 bit Unix-like systems the 'bsfq' assembly instruction will be used
computer, it might be possible to improve the performance by changing for bit counting. Detection is automatic at compile time, but in case you
some of the #define directives in bitboard.h. The default settings experience compile problems you can comment out #define USE_BSFQ line in types.h
are optimized for 64-bit CPUs. On 32-bit CPUs, it is probably better
to switch on USE_32BIT_ATTACKS, and to use BITCOUNT_SWAR_32 instead of
BITCOUNT_SWAR_64. For computers with very little memory (like
handheld devices), it is possible to conserve memory by defining
USE_COMPACT_ROOK_ATTACKS.
5. Terms of use
5. History
----------
2007-05-06: Glaurung 2 - epsilon
--------------------------------
The first public release, and the first version of my new program
which is able to match the old Glaurung 1.2.1 on a single CPU. Lots
of features and chess knowledge is still missing.
2007-05-10: Glaurung 2 - epsilon/2
----------------------------------
This version is very close to 2 - epsilon. The major changes are:
* A number of compatibility problems which appeared when trying to
compile Glaurung 2 - epsilon on various operating systems and CPUs
have been solved.
* Fixed a major bug in the detection of rooks trapped inside a
friendly king.
* Added knowledge about several types of drawn endgames.
* Fixed a few FRC related bugs. FRC now works, but because of
serious holes in the evaluation function the program plays very
badly.
* A slightly more sophisticated king safety evaluation.
2007-06-07: Glaurung 2 - epsilon/3
----------------------------------
The first public version with support for multiple CPUs. Unless you
have a dual-core (or better) computer, use Glaurung with a PolyGlot
book, or runs games with ponder on, you may want to skip this version,
which is almost certainly no stronger than 2 - epsilon/2 when running
on a single CPU. The main changes compared to the previous version
are:
* Parallel search, with support for 1-4 CPUs. The program currently
always allocates a separate pawn hash table and material hash
table for four threads, which is a pure waste of RAM if your
computer has just a single CPU. This will be fixed in a future
version.
* Fixed a bug in book randomization. When using Polyglot books, the
previous version would always select exactly the same move in the
same position after a restart of the program. Thanks to Pavel
Háse for pointing this out.
* Fixed a UCI pondering bug: Glaurung no longer instantly prints its
best move when the maximum depth is reached during a ponder
search, as the previous version did. According to the UCI
protocol, it is not allowed to print the best move before the
engine has received the "stop" or "quit" command.
* Additional search information: The new version displays hash
saturation and the current line(s) of search.
* Several minor bug fixes and optimizations in the search and
evaluation.
2007-06-08: Glaurung 2 - epsilon/4
----------------------------------
A bugfix release, with only a single important change:
* Fixed a very serious pondering bug. As pointed out by Marc
Lacrosse, the previous version would lose on time in almost every
single game with pondering enabled. The new version handles
pondering correctly (or so I hope). When playing with ponder
off, the new version is identical to version 2 - epsilon/3.
2007-06-25: Glaurung 2 - epsilon/5
----------------------------------
Another minor update, including the following improvements and bug
fixes:
* As Werner Schüle discovered, the previous version would sometimes
stop thinking and lose on time right before delivering checkmate
(which is of course a very unfortunate moment to lose on time).
I haven't been able to reproduce Werner's problem on my computer
(probably because I run a different OS), but I have fixed the bug
which I suspect caused the time losses. I hope the time losses
will no longer occur with 2 - epsilon/5.
* The program is now slightly less resource-hungry on computers
with less than 4 CPU cores: The previous version would always
allocated separate pawn and material hash tables for four
threads, even when running on a single-core CPU. The new version
only allocates pawn and material hash tables for the threads
which are actually used.
* A minor reorganization of the memory layout has made the parallel
search about 10% more efficient (at least on my computer, but the
results are likely to vary considerably on different systems).
* The Intel Mac OS X binary is much faster than before, thanks to
the Intel C++ compiler (previous versions were compiled with
GCC).
* A few other very minor bug fixes and enhancements.
2007-11-21: Glaurung 2.0
------------------------
The first stable (or so I hope) and feature-complete version of
Glaurung 2. The following are the main changes compared to the
previous version:
* The license has been changed from GPL version 2 to GPL version 3.
* MultiPV mode.
* Support for the "searchmoves" option in the UCI "go" command.
This means that it is possible to ask Glaurung to exclude some
moves from its analysis, or to restrict its analysis to just a
handful of moves selected by the user. This feature must also be
supported by the GUI under which Glaurung is run. Glaurung's own
GUI does currently not support this feature.
* Chess960 support now works. The program still plays this game
very badly, because of lack of opening knowledge.
* Much more aggressive pruning in the last few plies of the main
search.
* Somewhat better scaling on multi-CPU systems, and support for up
to 8 CPUs.
* Lots of new UCI parameters.
* Improved time managment, especially in games with pondering on
(i.e. when the engine is allowed to think when it's the
opponent's turn to move).
* Some evaluation improvements, and some new basic endgame
patterns.
* The program should no longer crash if the game lasts longer than
1000 plies.
* Many minor bug fixes and other tiny improvements throughout the
code.
* More generously commented code, and numerous cosmetic changes in
coding style.
2007-11-22: Glaurung 2.0.1
--------------------------
* Fixed (or so I hope) a bug which would occasionally cause one of
the search threads to get stuck forever in its idle loop.
2008-05-14: Glaurung 2.1
------------------------
This version contains far too many changes to list them all, but most
of them are minor and cosmetic. The most important and noticable
changes are a lot of new UCI parameters, and many improvements in the
evaluation function. The highlights are:
* Extensive changes in the evaluation function. The addition of
king safety is the most important improvement, but there are also
numerous little improvements elsewhere in the evaluation. There
is still much work left to do in the evaluation function, though.
Space and development are still missing, and the tuning is likely
to be very poor. Currently, the program is optimized for an
entertaining style rather than maximum strength.
* More accurate forward pruning. The previous version used the
null move refutation move to improve the pruning accuracy by
means of a very simple trick: It did not allow pruning of any
moves with the piece captured by the null move refutation move.
In Glaurung 2.1, this has been enhanced: It does not allow
pruning of moves which defend the destination square of the null
move refutation move, nor of moves which block the ray of the
piece in the case that the moving piece in the null move
refutation move is a slider.
* More conservative use of LMR at PV nodes. The previous version
searched the first 6 moves with full depth, 2.1 by default
searches the first 14 moves with full depth (but there is a new
UCI parameter for configuring this). I am not at all sure
whether this is an improvement. More thorough testing is
required.
* Feedback from the evaluation to the search. The search passes an
object of type 'EvalInfo' to the eval, and the eval fills this
struct with various potentially useful information (like the sets
of squares attacked by each piece type, the middle game and
endgame components of the eval, etc.). At the moment, almost
none of this information is actually used by the search. The
only exception is that the evaluation function is now used to
adjust the futility pruning margin in the quiescence search.
* Less extensions. This hurts the programs performance a lot in most
test suites, but I hope it improves the branching factor in deep
searches.
* A very long list of new UCI parameters, especially for tuning the
evaluation.
6. Terms of use
--------------- ---------------
Glaurung is free, and distributed under the GNU General Public License 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 what you want with the program, including distributing it among your
friends, making it available for download from your web site, selling friends, making it available for download from your web site, selling
it (either by itself or as part of some bigger software package), or it (either by itself or as part of some bigger software package), or
using it as the starting point for a software project of your own. using it as the starting point for a software project of your own.
The only real limitation is that whenever you distribute Glaurung in The only real limitation is that whenever you distribute Stockfish in
some way, you must always include the full source code, or a pointer 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. source code, these changes must also be made available under the GPL.
@@ -321,8 +85,7 @@ For full details, read the copy of the GPL found in the file named
Copying.txt. Copying.txt.
7. Feedback 6. Feedback
----------- -----------
The author's e-mail address is tord@glaurungchess.com The author's e-mail address is mcostalba@gmail.com
+3 -10
View File
@@ -2,13 +2,13 @@
[PolyGlot] [PolyGlot]
EngineDir = . EngineDir = .
EngineCommand = ./glaurung EngineCommand = ./stockfish
Book = false Book = false
BookFile = book.bin BookFile = book.bin
Log = true Log = true
LogFile = glaurung.log LogFile = stockfish.log
Resign = true Resign = true
ResignScore = 600 ResignScore = 600
@@ -34,8 +34,7 @@ King Safety Coefficient = 40
King Safety X Intercept = 0 King Safety X Intercept = 0
King Safety Max Slope = 30 King Safety Max Slope = 30
King Safety Max Value = 500 King Safety Max Value = 500
Queen Contact Check Bonus = 4 Queen Contact Check Bonus = 3
Rook Contact Check Bonus = 2
Queen Check Bonus = 2 Queen Check Bonus = 2
Rook Check Bonus = 1 Rook Check Bonus = 1
Bishop Check Bonus = 1 Bishop Check Bonus = 1
@@ -57,14 +56,8 @@ Pawn Endgame Extension (non-PV nodes) = 2
Full Depth Moves (PV nodes) = 14 Full Depth Moves (PV nodes) = 14
Full Depth Moves (non-PV nodes) = 3 Full Depth Moves (non-PV nodes) = 3
Threat Depth = 5 Threat Depth = 5
Selective Plies = 7
Futility Pruning (Main Search) = true Futility Pruning (Main Search) = true
Futility Pruning (Quiescence Search) = true Futility Pruning (Quiescence Search) = true
Futility Margin 0 = 50
Futility Margin 1 = 100
Futility Margin 2 = 300
Maximum Razoring Depth = 3
Razoring Margin = 300
Randomness = 0 Randomness = 0
Minimum Split Depth = 4 Minimum Split Depth = 4
Maximum Number of Threads per Split Point = 5 Maximum Number of Threads per Split Point = 5
+226 -108
View File
@@ -1,14 +1,15 @@
# Glaurung, a UCI chess playing engine. # Stockfish, a UCI chess playing engine derived from Glaurung 2.1
# Copyright (C) 2004-2007 Tord Romstad # Copyright (C) 2004-2007 Tord Romstad
# Copyright (C) 2008 Marco Costalba
# This file is part of Glaurung. # This file is part of Stockfish.
# #
# Glaurung is free software: you can redistribute it and/or modify # Stockfish is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# Glaurung is distributed in the hope that it will be useful, # Stockfish is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU General Public License for more details.
@@ -17,129 +18,246 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
### ### Executable name. Do not change
### Files EXE = stockfish
###
EXE = glaurung
OBJS = bitboard.o color.o pawns.o material.o endgame.o evaluate.o main.o \ ### ==========================================================================
### Compiler speed switches for both GCC and ICC. These settings are generally
### fast on a broad range of systems, but may be changed experimentally
### ==========================================================================
GCCFLAGS = -O3 -msse
ICCFLAGS = -fast -msse
ICCFLAGS-OSX = -fast -mdynamic-no-pic
### ==========================================================================
### Enable/disable debugging, disabled by default
### ==========================================================================
GCCFLAGS += -DNDEBUG
ICCFLAGS += -DNDEBUG
ICCFLAGS-OSX += -DNDEBUG
### ==========================================================================
### Run built-in benchmark for pgo-builds with: 32MB hash 1 thread 10 depth
### These settings are generally fast, but may be changed experimentally
### ==========================================================================
PGOBENCH = ./$(EXE) bench 32 1 10 default depth
### General compiler settings. Do not change
GCCFLAGS += -g -Wall -fno-exceptions -fno-rtti -fno-strict-aliasing
ICCFLAGS += -g -Wall -fno-exceptions -fno-rtti -fno-strict-aliasing -wd383,869,981,10187,10188,11505,11503
ICCFLAGS-OSX += -g -Wall -fno-exceptions -fno-rtti -fno-strict-aliasing -wd383,869,981,10187,10188,11505,11503
### General linker settings. Do not change
LDFLAGS = -lpthread
### Object files. Do not change
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 \ misc.o move.o movegen.o history.o movepick.o search.o piece.o \
position.o square.o direction.o tt.o value.o uci.o ucioption.o \ position.o direction.o tt.o value.o uci.o ucioption.o \
mersenne.o book.o bitbase.o san.o benchmark.o mersenne.o book.o bitbase.o san.o benchmark.o
### ### General rules. Do not change
### Rules default:
### $(MAKE) gcc
help:
@echo ""
@echo "Makefile options:"
@echo ""
@echo "make > Default: Compiler = g++"
@echo "make icc > Compiler = icpc"
@echo "make icc-profile > Compiler = icpc + automatic pgo-build"
@echo "make osx-ppc32 > PPC-Mac OS X 32 bit. Compiler = g++"
@echo "make osx-ppc64 > PPC-Mac OS X 64 bit. Compiler = g++"
@echo "make osx-x86 > x86-Mac OS X 32 bit. Compiler = g++"
@echo "make osx-x86_64 > x86-Mac OS X 64 bit. Compiler = g++"
@echo "make osx-icc32 > x86-Mac OS X 32 bit. Compiler = icpc"
@echo "make osx-icc64 > x86-Mac OS X 64 bit. Compiler = icpc"
@echo "make osx-icc32-profile > OSX 32 bit. Compiler = icpc + automatic pgo-build"
@echo "make osx-icc64-profile > OSX 64 bit. Compiler = icpc + automatic pgo-build"
@echo "make strip > Strip executable"
@echo "make clean > Clean up"
@echo ""
all: $(EXE) .depend all: $(EXE) .depend
clean: clean:
$(RM) *.o .depend glaurung $(RM) *.o .depend *~ $(EXE)
### ### Possible targets. You may add your own ones here
### Compiler: gcc:
### $(MAKE) \
CXX='g++' \
CXXFLAGS="$(GCCFLAGS)" \
all
CXX = g++ icc:
# CXX = g++-4.2 $(MAKE) \
# CXX = icpc CXX='icpc' \
CXXFLAGS="$(ICCFLAGS)" \
all
icc-profile-make:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS)" \
CXXFLAGS+='-prof-gen=srcpos -prof_dir ./profdir' \
all
icc-profile-use:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS)" \
CXXFLAGS+='-prof_use -prof_dir ./profdir' \
all
icc-profile:
@rm -rf profdir
@mkdir profdir
@touch *.cpp *.h
$(MAKE) icc-profile-make
@echo ""
@echo "Running benchmark for pgo-build ..."
@$(PGOBENCH) > /dev/null
@echo "Benchmark finished. Build final executable now ..."
@echo ""
@touch *.cpp *.h
$(MAKE) icc-profile-use
@rm -rf profdir bench.txt
osx-ppc32:
$(MAKE) \
CXX='g++' \
CXXFLAGS="$(GCCFLAGS)" \
CXXFLAGS+='-arch ppc' \
LDFLAGS+='-arch ppc' \
all
osx-ppc64:
$(MAKE) \
CXX='g++' \
CXXFLAGS="$(GCCFLAGS)" \
CXXFLAGS+='-arch ppc64' \
LDFLAGS+='-arch ppc64' \
all
osx-x86:
$(MAKE) \
CXX='g++' \
CXXFLAGS="$(GCCFLAGS)" \
CXXFLAGS+='-arch i386' \
LDFLAGS+='-arch i386' \
all
osx-x86_64:
$(MAKE) \
CXX='g++' \
CXXFLAGS="$(GCCFLAGS)" \
CXXFLAGS+='-arch x86_64' \
LDFLAGS+='-arch x86_64' \
all
osx-icc32:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS-OSX)" \
CXXFLAGS+='-arch i386' \
LDFLAGS+='-arch i386' \
all
osx-icc64:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS-OSX)" \
CXXFLAGS+='-arch x86_64' \
LDFLAGS+='-arch x86_64' \
all
osx-icc32-profile-make:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS-OSX)" \
CXXFLAGS+='-arch i386' \
CXXFLAGS+='-prof_gen -prof_dir ./profdir' \
LDFLAGS+='-arch i386' \
all
osx-icc32-profile-use:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS-OSX)" \
CXXFLAGS+='-arch i386' \
CXXFLAGS+='-prof_use -prof_dir ./profdir' \
LDFLAGS+='-arch i386' \
all
osx-icc32-profile:
@rm -rf profdir
@mkdir profdir
@touch *.cpp *.h
$(MAKE) osx-icc32-profile-make
@echo ""
@echo "Running benchmark for pgo-build ..."
@$(PGOBENCH) > /dev/null
@echo "Benchmark finished. Build final executable now ..."
@echo ""
@touch *.cpp *.h
$(MAKE) osx-icc32-profile-use
@rm -rf profdir bench.txt
osx-icc64-profile-make:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS-OSX)" \
CXXFLAGS+='-arch x86_64' \
CXXFLAGS+='-prof_gen -prof_dir ./profdir' \
LDFLAGS+='-arch x86_64' \
all
osx-icc64-profile-use:
$(MAKE) \
CXX='icpc' \
CXXFLAGS="$(ICCFLAGS-OSX)" \
CXXFLAGS+='-arch x86_64' \
CXXFLAGS+='-prof_use -prof_dir ./profdir' \
LDFLAGS+='-arch x86_64' \
all
osx-icc64-profile:
@rm -rf profdir
@mkdir profdir
@touch *.cpp *.h
$(MAKE) osx-icc64-profile-make
@echo ""
@echo "Running benchmark for pgo-build ..."
@$(PGOBENCH) > /dev/null
@echo "Benchmark finished. Build final executable now ..."
@echo ""
@touch *.cpp *.h
$(MAKE) osx-icc64-profile-use
@rm -rf profdir bench.txt
###
### Dependencies
###
strip:
strip $(EXE)
### Compilation. Do not change
$(EXE): $(OBJS) $(EXE): $(OBJS)
$(CXX) $(LDFLAGS) -o $@ $(OBJS) $(CXX) $(LDFLAGS) -o $@ $(OBJS)
### Dependencies. Do not change
.depend: .depend:
$(CXX) -MM $(OBJS:.o=.cpp) > $@ $(CXX) -msse -MM $(OBJS:.o=.cpp) > $@
include .depend include .depend
###
### Compiler and linker switches
###
# Enable/disable debugging:
CXXFLAGS += -DNDEBUG
# Compile with full warnings, and symbol names
CXXFLAGS += -Wall -g
# General optimization flags. Note that -O2 might be faster than -O3 on some
# systems; this requires testing.
CXXFLAGS += -O3 -fno-exceptions -fomit-frame-pointer -fno-rtti -fstrict-aliasing
# Compiler optimization flags for the Intel C++ compiler in Mac OS X:
# CXXFLAGS += -mdynamic-no-pic -no-prec-div -ipo -static -xP
# Profiler guided optimization with the Intel C++ compiler. To use it, first
# create the directory ./profdata if it does not already exist, and delete its
# contents if it does exist. Then compile with -prof_gen, and run the
# resulting binary for a while (for instance, do ./glaurung bench 128 1, and
# wait 15 minutes for the benchmark to complete). Then do a 'make clean', and
# recompile with -prof_use.
# CXXFLAGS += -prof_gen -prof_dir ./profdata
# CXXFLAGS += -prof_use -prof_dir ./profdata
# Profiler guided optimization with GCC. I've never been able to make this
# work.
# CXXFLAGS += -fprofile-generate
# LDFLAGS += -fprofile-generate
# CXXFLAGS += -fprofile-use
# CXXFLAGS += -fprofile-use
# General linker flags
LDFLAGS += -lm -lpthread
# Compiler switches for generating binaries for various CPUs in Mac OS X.
# Note that 'arch ppc' and 'arch ppc64' only works with g++, and not with
# the intel compiler.
# CXXFLAGS += -arch ppc
# CXXFLAGS += -arch ppc64
# CXXFLAGS += -arch i386
# CXXFLAGS += -arch x86_64
# LDFLAGS += -arch ppc
# LDFLAGS += -arch ppc64
# LDFLAGS += -arch i386
# LDFLAGS += -arch x86_64
# Backwards compatibility with Mac OS X 10.4 when compiling under 10.5 with
# GCC 4.0. I haven't found a way to make it work with GCC 4.2.
# CXXFLAGS += -isysroot /Developer/SDKs/MacOSX10.4u.sdk
# CXXFLAGS += -mmacosx-version-min=10.4
# LDFLAGS += -isysroot /Developer/SDKs/MacOSX10.4u.sdk
# LDFLAGS += -Wl,-syslibroot /Developer/SDKs/MacOSX10.4u.sdk
# LDFLAGS += -mmacosx-version-min=10.4
# Backwards compatibility with Mac OS X 10.4 when compiling with ICC. Doesn't
# work yet. :-(
# CXXFLAGS += -DMAC_OS_X_VERSION_MIN_REQUIRED=1040
# CXXFLAGS += -DMAC_OS_X_VERSION_MAX_ALLOWED=1040
# CXXFLAGS += -D__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__=1040
# CXXFLAGS += -F/Developer/SDKs/MacOSX10.4u.sdk/
# LDFLAGS += -Wl,-syslibroot -Wl,/Developer/SDKs/MacOSX10.4u.sdk
+75
View File
@@ -0,0 +1,75 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////
//// Includes
////
#include "bitboard.h"
#include "direction.h"
#include "endgame.h"
#include "evaluate.h"
#include "material.h"
#include "mersenne.h"
#include "misc.h"
#include "movepick.h"
#include "position.h"
#include "search.h"
#include "thread.h"
#include "ucioption.h"
/// Application class is in charge of initializing global resources
/// at startup and cleanly releases them when program terminates.
Application::Application() {
init_mersenne();
init_direction_table();
init_bitboards();
init_uci_options();
Position::init_zobrist();
Position::init_piece_square_tables();
init_eval(1);
init_bitbases();
init_threads();
// Make random number generation less deterministic, for book moves
for (int i = abs(get_system_time() % 10000); i > 0; i--)
genrand_int32();
}
Application::~Application() {
stop_threads();
quit_eval();
}
void Application::initialize() {
// A static Application object is allocated
// once only when this function is called.
static Application singleton;
}
void Application::exit_with_failure() {
exit(EXIT_FAILURE); // d'tor will be called automatically
}
+39
View File
@@ -0,0 +1,39 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(APPLICATION_H_INCLUDED)
#define APPLICATION_H_INCLUDED
/// Singleton class used to housekeep memory and global resources
/// so to be sure we always leave in a clean state.
class Application {
Application();
Application(const Application&);
~Application();
public:
static void initialize();
static void exit_with_failure();
};
#endif // !defined(APPLICATION_H_INCLUDED)
+115 -27
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -20,18 +21,23 @@
//// ////
//// Includes //// Includes
//// ////
#include <fstream>
#include <sstream>
#include <vector>
#include "benchmark.h" #include "benchmark.h"
#include "search.h" #include "search.h"
#include "thread.h" #include "thread.h"
#include "ucioption.h" #include "ucioption.h"
using namespace std;
//// ////
//// Variables //// Variables
//// ////
const std::string BenchmarkPositions[15] = { const string BenchmarkPositions[] = {
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"r4rk1/1b2qppp/p1n1p3/1p6/1b1PN3/3BRN2/PP3PPP/R2Q2K1 b - - 7 16", "r4rk1/1b2qppp/p1n1p3/1p6/1b1PN3/3BRN2/PP3PPP/R2Q2K1 b - - 7 16",
"4r1k1/ppq3pp/3b4/2pP4/2Q1p3/4B1P1/PP5P/R5K1 b - - 0 20", "4r1k1/ppq3pp/3b4/2pP4/2Q1p3/4B1P1/PP5P/R5K1 b - - 0 20",
"4rrk1/pp1n3p/3q2pQ/2p1pb2/2PP4/2P3N1/P2B2PP/4RRK1 b - - 7 19", "4rrk1/pp1n3p/3q2pQ/2p1pb2/2PP4/2P3N1/P2B2PP/4RRK1 b - - 7 19",
@@ -54,38 +60,120 @@ const std::string BenchmarkPositions[15] = {
//// Functions //// Functions
//// ////
/// benchmark() runs a simple benchmark by letting Glaurung analyze 15 /// benchmark() runs a simple benchmark by letting Stockfish analyze a set
/// positions for 60 seconds each. There are two parameters; the /// of positions for a given time each. There are four parameters; the
/// transposition table size and the number of search threads that should /// transposition table size, the number of search threads that should
/// be used. The analysis is written to a file named bench.txt. /// 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.
void benchmark(const std::string &ttSize, const std::string &threads) { void benchmark(const string& commandLine) {
Position pos;
Move moves[1] = {MOVE_NONE};
int i;
i = atoi(ttSize.c_str()); istringstream csVal(commandLine);
if(i < 4 || i > 1024) { istringstream csStr(commandLine);
std::cerr << "The hash table size must be between 4 and 1024" << std::endl; string ttSize, threads, fileName, limitType, timFile;
exit(EXIT_FAILURE); int val, secsPerPos, maxDepth, maxNodes;
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;
i = atoi(threads.c_str()); csVal >> val;
if(i < 1 || i > THREAD_MAX) { if (val < 1 || val > THREAD_MAX)
std::cerr << "The number of threads must be between 1 and " << THREAD_MAX {
<< std::endl; cerr << "The number of threads must be between 1 and " << THREAD_MAX << endl;
exit(EXIT_FAILURE); Application::exit_with_failure();
} }
set_option_value("Hash", ttSize); set_option_value("Hash", ttSize);
set_option_value("Threads", threads); set_option_value("Threads", threads);
set_option_value("OwnBook", "false"); set_option_value("OwnBook", "false");
set_option_value("Use Search Log", "true"); set_option_value("Use Search Log", "true");
set_option_value("Search Log Filename", "bench.txt"); set_option_value("Search Log Filename", "bench.txt");
for(i = 0; i < 15; i++) { csVal >> val;
pos.from_fen(BenchmarkPositions[i]); csVal >> fileName;
think(pos, true, false, 0, 0, 0, 0, 0, 60000, moves); csVal >> limitType;
csVal >> timFile;
secsPerPos = maxDepth = maxNodes = 0;
if (limitType == "time")
secsPerPos = val * 1000;
else if (limitType == "depth")
maxDepth = val;
else
maxNodes = val;
vector<string> positions;
if (fileName != "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]));
ofstream timingFile;
if (!timFile.empty())
{
timingFile.open(timFile.c_str(), ios::out | ios::app);
if (!timingFile.is_open())
{
cerr << "Unable to open timing file " << timFile << endl;
Application::exit_with_failure();
}
} }
vector<string>::iterator it;
int cnt = 1;
int64_t totalNodes = 0;
int startTime = get_system_time();
for (it = positions.begin(); it != positions.end(); ++it, ++cnt)
{
Move moves[1] = {MOVE_NONE};
int dummy[2] = {0, 0};
Position pos(*it);
cerr << "\nBench position: " << cnt << '/' << positions.size() << endl << endl;
if (!think(pos, true, 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
} }
+6 -6
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -31,7 +32,6 @@
//// Prototypes //// Prototypes
//// ////
extern void benchmark(const std::string &ttSize, const std::string &threads); extern void benchmark(const std::string& commandLine);
#endif // !defined(BENCHMARK_H_INCLUDED) #endif // !defined(BENCHMARK_H_INCLUDED)
+7 -5
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -88,7 +89,8 @@ void generate_kpk_bitbase(uint8_t bitbase[]) {
int i, j, b; int i, j, b;
for(i = 0; i < 24576; i++) { for(i = 0; i < 24576; i++) {
for(b = 0, j = 0; j < 8; b |= (compress_result(Bitbase[8*i+j]) << j), j++); for(b = 0, j = 0; j < 8; b |= (compress_result(Bitbase[8*i+j]) << j), j++);
bitbase[i] = b; assert(b == int(uint8_t(b)));
bitbase[i] = (uint8_t)b;
} }
// Release allocated memory: // Release allocated memory:
+5 -4
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
+229 -257
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -24,182 +25,11 @@
#include <iostream> #include <iostream>
#include "bitboard.h" #include "bitboard.h"
#include "bitcount.h"
#include "direction.h" #include "direction.h"
//// #if defined(IS_64BIT)
//// Constants and variables
////
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
}
};
#if defined(USE_COMPACT_ROOK_ATTACKS)
Bitboard RankAttacks[8][64], FileAttacks[8][64];
#elif defined(USE_32BIT_ATTACKS)
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 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
};
#else // if defined(USE_32BIT_ATTACKS)
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 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
};
#endif // defined(USE_32BIT_ATTACKS)
#if !defined(USE_COMPACT_ROOK_ATTACKS)
Bitboard RMask[64];
int RAttackIndex[64];
Bitboard RAttacks[0x19000];
#endif
#if defined(USE_32BIT_ATTACKS)
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 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
};
#else // if defined(USE_32BIT_ATTACKS)
const uint64_t BMult[64] = { const uint64_t BMult[64] = {
0x440049104032280ULL, 0x1021023c82008040ULL, 0x404040082000048ULL, 0x440049104032280ULL, 0x1021023c82008040ULL, 0x404040082000048ULL,
@@ -226,6 +56,31 @@ const uint64_t BMult[64] = {
0xa08520292120600ULL 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] = { const int BShift[64] = {
58, 59, 59, 59, 59, 59, 59, 58, 59, 59, 59, 59, 59, 59, 59, 59, 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, 57, 57, 57, 59, 59, 59, 59, 57, 55, 55, 57, 59, 59,
@@ -233,14 +88,139 @@ const int BShift[64] = {
59, 59, 59, 59, 59, 59, 59, 59, 58, 59, 59, 59, 59, 59, 59, 58 59, 59, 59, 59, 59, 59, 59, 59, 58, 59, 59, 59, 59, 59, 59, 58
}; };
#endif // defined(USE_32BIT_ATTACKS) 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]; Bitboard BMask[64];
int BAttackIndex[64]; int BAttackIndex[64];
Bitboard BAttacks[0x1480]; Bitboard BAttacks[0x1480];
Bitboard SetMaskBB[64]; Bitboard SetMaskBB[65];
Bitboard ClearMaskBB[64]; Bitboard ClearMaskBB[65];
Bitboard StepAttackBB[16][64]; Bitboard StepAttackBB[16][64];
Bitboard RayBB[64][8]; Bitboard RayBB[64][8];
@@ -253,12 +233,15 @@ Bitboard BishopPseudoAttacks[64];
Bitboard RookPseudoAttacks[64]; Bitboard RookPseudoAttacks[64];
Bitboard QueenPseudoAttacks[64]; Bitboard QueenPseudoAttacks[64];
uint8_t BitCount8Bit[256];
//// ////
//// Local definitions //// Local definitions
//// ////
namespace { namespace {
void init_masks(); void init_masks();
void init_ray_bitboards(); void init_ray_bitboards();
void init_attacks(); void init_attacks();
@@ -271,10 +254,7 @@ namespace {
const int shift[2], const Bitboard mult[], const int shift[2], const Bitboard mult[],
int deltas[][2]); int deltas[][2]);
void init_pseudo_attacks(); void init_pseudo_attacks();
#if defined(USE_COMPACT_ROOK_ATTACKS) }
void init_file_and_rank_attacks();
#endif
};
//// ////
@@ -305,49 +285,19 @@ void init_bitboards() {
init_ray_bitboards(); init_ray_bitboards();
init_attacks(); init_attacks();
init_between_bitboards(); init_between_bitboards();
#if defined(USE_COMPACT_ROOK_ATTACKS) init_sliding_attacks(RAttacks, RAttackIndex, RMask, RShift, RMult, rookDeltas);
init_file_and_rank_attacks(); init_sliding_attacks(BAttacks, BAttackIndex, BMask, BShift, BMult, bishopDeltas);
#else
init_sliding_attacks(RAttacks, RAttackIndex, RMask, RShift,
RMult, rookDeltas);
#endif
init_sliding_attacks(BAttacks, BAttackIndex, BMask, BShift,
BMult, bishopDeltas);
init_pseudo_attacks(); init_pseudo_attacks();
} }
#if defined(USE_FOLDED_BITSCAN)
static 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
};
/// first_1() finds the least significant nonzero bit in a nonzero bitboard. /// first_1() finds the least significant nonzero bit in a nonzero bitboard.
Square first_1(Bitboard b) {
b ^= (b - 1);
uint32_t fold = int(b) ^ int(b >> 32);
return Square(BitTable[(fold * 0x783a9b23) >> 26]);
}
/// pop_1st_bit() finds and clears the least significant nonzero bit in a /// pop_1st_bit() finds and clears the least significant nonzero bit in a
/// nonzero bitboard. /// nonzero bitboard.
Square pop_1st_bit(Bitboard *b) { #if defined(IS_64BIT) && !defined(USE_BSFQ)
Bitboard bb = *b ^ (*b - 1);
uint32_t fold = int(bb) ^ int(bb >> 32);
*b &= (*b - 1);
return Square(BitTable[(fold * 0x783a9b23) >> 26]);
}
#else
CACHE_LINE_ALIGNMENT
static const int BitTable[64] = { static const int BitTable[64] = {
0, 1, 2, 7, 3, 13, 8, 19, 4, 25, 14, 28, 9, 34, 20, 40, 5, 17, 26, 38, 15, 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, 46, 29, 48, 10, 31, 35, 54, 21, 50, 41, 57, 63, 6, 12, 18, 24, 27, 33, 39,
@@ -355,25 +305,60 @@ static const int BitTable[64] = {
51, 60, 42, 59, 58 51, 60, 42, 59, 58
}; };
/// first_1() finds the least significant nonzero bit in a nonzero bitboard.
Square first_1(Bitboard b) { Square first_1(Bitboard b) {
return Square(BitTable[((b & -b) * 0x218a392cd3d5dbfULL) >> 58]); return Square(BitTable[((b & -b) * 0x218a392cd3d5dbfULL) >> 58]);
} }
/// pop_1st_bit() finds and clears the least significant nonzero bit in a
/// nonzero bitboard.
Square pop_1st_bit(Bitboard* b) { Square pop_1st_bit(Bitboard* b) {
Bitboard bb = *b; Bitboard bb = *b;
*b &= (*b - 1); *b &= (*b - 1);
return Square(BitTable[((bb & -bb) * 0x218a392cd3d5dbfULL) >> 58]); return Square(BitTable[((bb & -bb) * 0x218a392cd3d5dbfULL) >> 58]);
} }
#endif // defined(USE_FOLDED_BITSCAN) #elif !defined(USE_BSFQ)
CACHE_LINE_ALIGNMENT
static const int BitTable[64] = {
63, 30, 3, 32, 25, 41, 22, 33, 15, 50, 42, 13, 11, 53, 19, 34, 61, 29, 2,
51, 21, 43, 45, 10, 18, 47, 1, 54, 9, 57, 0, 35, 62, 31, 40, 4, 49, 5, 52,
26, 60, 6, 23, 44, 46, 27, 56, 16, 7, 39, 48, 24, 59, 14, 12, 55, 38, 28,
58, 20, 37, 17, 36, 8
};
Square first_1(Bitboard b) {
b ^= (b - 1);
uint32_t fold = int(b) ^ int(b >> 32);
return Square(BitTable[(fold * 0x783a9b23) >> 26]);
}
// Use type-punning
union b_union {
Bitboard b;
struct {
uint32_t l;
uint32_t h;
} dw;
};
// WARNING: Needs -fno-strict-aliasing compiler option
Square pop_1st_bit(Bitboard* bb) {
b_union u;
u.b = *bb;
if (u.dw.l)
{
*((uint32_t*)bb) = u.dw.l & (u.dw.l - 1);
return Square(BitTable[((u.dw.l ^ (u.dw.l - 1)) * 0x783a9b23) >> 26]);
}
*((uint32_t*)bb+1) = u.dw.h & (u.dw.h - 1); // Little endian only?
return Square(BitTable[((~(u.dw.h ^ (u.dw.h - 1))) * 0x783a9b23) >> 26]);
}
#endif
namespace { namespace {
@@ -383,6 +368,8 @@ namespace {
// be necessary to touch any of them. // be necessary to touch any of them.
void init_masks() { void init_masks() {
SetMaskBB[SQ_NONE] = 0ULL;
ClearMaskBB[SQ_NONE] = ~SetMaskBB[SQ_NONE];
for(Square s = SQ_A1; s <= SQ_H8; s++) { for(Square s = SQ_A1; s <= SQ_H8; s++) {
SetMaskBB[s] = (1ULL << s); SetMaskBB[s] = (1ULL << s);
ClearMaskBB[s] = ~SetMaskBB[s]; ClearMaskBB[s] = ~SetMaskBB[s];
@@ -393,12 +380,15 @@ namespace {
in_front_bb(c, s) & this_and_neighboring_files_bb(s); in_front_bb(c, s) & this_and_neighboring_files_bb(s);
OutpostMask[c][s] = in_front_bb(c, s) & neighboring_files_bb(s); OutpostMask[c][s] = in_front_bb(c, s) & neighboring_files_bb(s);
} }
for (Bitboard b = 0ULL; b < 256ULL; b++)
BitCount8Bit[b] = (uint8_t)count_1s(b);
} }
void init_ray_bitboards() { void init_ray_bitboards() {
int d[8] = {1, -1, 16, -16, 17, -17, 15, -15}; int d[8] = {1, -1, 16, -16, 17, -17, 15, -15};
for(int i = 0; i < 128; i = i + 9 & ~8) { for(int i = 0; i < 128; i = (i + 9) & ~8) {
for(int j = 0; j < 8; j++) { for(int j = 0; j < 8; j++) {
RayBB[(i&7)|((i>>4)<<3)][j] = EmptyBoardBB; RayBB[(i&7)|((i>>4)<<3)][j] = EmptyBoardBB;
for(int k = i + d[j]; (k & 0x88) == 0; k += d[j]) for(int k = i + d[j]; (k & 0x88) == 0; k += d[j])
@@ -484,19 +474,26 @@ namespace {
for(i = 0; i < 64; i++) { for(i = 0; i < 64; i++) {
attackIndex[i] = index; attackIndex[i] = index;
mask[i] = sliding_attacks(i, 0ULL, 4, deltas, 1, 6, 1, 6); mask[i] = sliding_attacks(i, 0ULL, 4, deltas, 1, 6, 1, 6);
#if defined(IS_64BIT)
j = (1 << (64 - shift[i])); j = (1 << (64 - shift[i]));
#else
j = (1 << (32 - shift[i]));
#endif
for(k = 0; k < j; k++) { for(k = 0; k < j; k++) {
#if defined(USE_32BIT_ATTACKS)
#if defined(IS_64BIT)
b = index_to_bitboard(k, mask[i]);
attacks[index + ((b * mult[i]) >> shift[i])] =
sliding_attacks(i, b, 4, deltas);
#else
b = index_to_bitboard(k, mask[i]); b = index_to_bitboard(k, mask[i]);
attacks[index + attacks[index +
(unsigned(int(b) * int(mult[i]) ^ (unsigned(int(b) * int(mult[i]) ^
int(b >> 32) * int(mult[i] >> 32)) int(b >> 32) * int(mult[i] >> 32))
>> shift[i])] = >> shift[i])] =
sliding_attacks(i, b, 4, deltas); sliding_attacks(i, b, 4, deltas);
#else
b = index_to_bitboard(k, mask[i]);
attacks[index + ((b * mult[i]) >> shift[i])] =
sliding_attacks(i, b, 4, deltas);
#endif #endif
} }
index += j; index += j;
@@ -513,29 +510,4 @@ namespace {
} }
} }
#if defined(USE_COMPACT_ROOK_ATTACKS)
void init_file_and_rank_attacks() {
int i, j, k, l, m, s;
Bitboard b1, b2;
for(i = 0; i < 64; i++) {
for(m = 0; m <= 1; m++) {
b1 = 0ULL;
for(j = 0; j < 6; j++) if(i & (1<<j)) b1 |= (1ULL << ((j+1)*(1+m*7)));
for(j = 0; j < 8; j++) {
b2 = 0ULL;
for(k = 0, s = 1; k < 2; k++, s *= -1) {
for(l = j+s; l >= 0 && l <= 7; l += s) {
b2 |= (m? RankBB[l] : FileBB[l]);
if(b1 & (1ULL << (l*(1+m*7)))) break;
}
}
if(m) FileAttacks[j][(b1*0xd6e8802041d0c441ULL) >> 58] = b2;
else RankAttacks[j][i] = b2;
}
}
}
}
#endif // defined(USE_COMPACT_ROOK_ATTACKS)
} }
+67 -134
View File
@@ -1,13 +1,15 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful,
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -20,21 +22,6 @@
#if !defined(BITBOARD_H_INCLUDED) #if !defined(BITBOARD_H_INCLUDED)
#define BITBOARD_H_INCLUDED #define BITBOARD_H_INCLUDED
////
//// Defines
////
//#define USE_COMPACT_ROOK_ATTACKS
//#define USE_32BIT_ATTACKS
#define USE_FOLDED_BITSCAN
#define BITCOUNT_SWAR_64
//#define BITCOUNT_SWAR_32
//#define BITCOUNT_LOOP
//// ////
//// Includes //// Includes
//// ////
@@ -45,13 +32,6 @@
#include "types.h" #include "types.h"
////
//// Types
////
typedef uint64_t Bitboard;
//// ////
//// Constants and variables //// Constants and variables
//// ////
@@ -61,8 +41,6 @@ const Bitboard EmptyBoardBB = 0ULL;
const Bitboard WhiteSquaresBB = 0x55AA55AA55AA55AAULL; const Bitboard WhiteSquaresBB = 0x55AA55AA55AA55AAULL;
const Bitboard BlackSquaresBB = 0xAA55AA55AA55AA55ULL; const Bitboard BlackSquaresBB = 0xAA55AA55AA55AA55ULL;
extern const Bitboard SquaresByColorBB[2];
const Bitboard FileABB = 0x0101010101010101ULL; const Bitboard FileABB = 0x0101010101010101ULL;
const Bitboard FileBBB = 0x0202020202020202ULL; const Bitboard FileBBB = 0x0202020202020202ULL;
const Bitboard FileCBB = 0x0404040404040404ULL; const Bitboard FileCBB = 0x0404040404040404ULL;
@@ -72,10 +50,6 @@ const Bitboard FileFBB = 0x2020202020202020ULL;
const Bitboard FileGBB = 0x4040404040404040ULL; const Bitboard FileGBB = 0x4040404040404040ULL;
const Bitboard FileHBB = 0x8080808080808080ULL; const Bitboard FileHBB = 0x8080808080808080ULL;
extern const Bitboard FileBB[8];
extern const Bitboard NeighboringFilesBB[8];
extern const Bitboard ThisAndNeighboringFilesBB[8];
const Bitboard Rank1BB = 0xFFULL; const Bitboard Rank1BB = 0xFFULL;
const Bitboard Rank2BB = 0xFF00ULL; const Bitboard Rank2BB = 0xFF00ULL;
const Bitboard Rank3BB = 0xFF0000ULL; const Bitboard Rank3BB = 0xFF0000ULL;
@@ -85,12 +59,16 @@ const Bitboard Rank6BB = 0xFF0000000000ULL;
const Bitboard Rank7BB = 0xFF000000000000ULL; const Bitboard Rank7BB = 0xFF000000000000ULL;
const Bitboard Rank8BB = 0xFF00000000000000ULL; 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 RankBB[8];
extern const Bitboard RelativeRankBB[2][8]; extern const Bitboard RelativeRankBB[2][8];
extern const Bitboard InFrontBB[2][8]; extern const Bitboard InFrontBB[2][8];
extern Bitboard SetMaskBB[64]; extern Bitboard SetMaskBB[65];
extern Bitboard ClearMaskBB[64]; extern Bitboard ClearMaskBB[65];
extern Bitboard StepAttackBB[16][64]; extern Bitboard StepAttackBB[16][64];
extern Bitboard RayBB[64][8]; extern Bitboard RayBB[64][8];
@@ -99,15 +77,11 @@ extern Bitboard BetweenBB[64][64];
extern Bitboard PassedPawnMask[2][64]; extern Bitboard PassedPawnMask[2][64];
extern Bitboard OutpostMask[2][64]; extern Bitboard OutpostMask[2][64];
#if defined(USE_COMPACT_ROOK_ATTACKS)
extern Bitboard RankAttacks[8][64], FileAttacks[8][64];
#else
extern const uint64_t RMult[64]; extern const uint64_t RMult[64];
extern const int RShift[64]; extern const int RShift[64];
extern Bitboard RMask[64]; extern Bitboard RMask[64];
extern int RAttackIndex[64]; extern int RAttackIndex[64];
extern Bitboard RAttacks[0x19000]; extern Bitboard RAttacks[0x19000];
#endif // defined(USE_COMPACT_ROOK_ATTACKS)
extern const uint64_t BMult[64]; extern const uint64_t BMult[64];
extern const int BShift[64]; extern const int BShift[64];
@@ -119,6 +93,8 @@ extern Bitboard BishopPseudoAttacks[64];
extern Bitboard RookPseudoAttacks[64]; extern Bitboard RookPseudoAttacks[64];
extern Bitboard QueenPseudoAttacks[64]; extern Bitboard QueenPseudoAttacks[64];
extern uint8_t BitCount8Bit[256];
//// ////
//// Inline functions //// Inline functions
@@ -127,29 +103,30 @@ extern Bitboard QueenPseudoAttacks[64];
/// Functions for testing whether a given bit is set in a bitboard, and for /// Functions for testing whether a given bit is set in a bitboard, and for
/// setting and clearing bits. /// setting and clearing bits.
inline Bitboard set_mask_bb(Square s) {
// return 1ULL << s;
return SetMaskBB[s];
}
inline Bitboard clear_mask_bb(Square s) {
// return ~set_mask_bb(s);
return ClearMaskBB[s];
}
inline Bitboard bit_is_set(Bitboard b, Square s) { inline Bitboard bit_is_set(Bitboard b, Square s) {
return b & set_mask_bb(s); return b & SetMaskBB[s];
} }
inline void set_bit(Bitboard *b, Square s) { inline void set_bit(Bitboard *b, Square s) {
*b |= set_mask_bb(s); *b |= SetMaskBB[s];
} }
inline void clear_bit(Bitboard *b, Square s) { inline void clear_bit(Bitboard *b, Square s) {
*b &= clear_mask_bb(s); *b &= ClearMaskBB[s];
} }
/// Functions used to update a bitboard after a move. This is faster
/// then calling a sequence of clear_bit() + set_bit()
inline Bitboard make_move_bb(Square from, Square to) {
return SetMaskBB[from] | SetMaskBB[to];
}
inline void do_move_bb(Bitboard *b, Bitboard move_bb) {
*b ^= move_bb;
}
/// rank_bb() and file_bb() gives a bitboard containing all squares on a given /// rank_bb() and file_bb() gives a bitboard containing all squares on a given
/// file or rank. It is also possible to pass a square as input to these /// file or rank. It is also possible to pass a square as input to these
/// functions. /// functions.
@@ -222,6 +199,19 @@ inline Bitboard in_front_bb(Color c, Square 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 in_front_bb(opposite_color(c), square_rank(s));
}
/// ray_bb() gives a bitboard representing all squares along the ray in a /// ray_bb() gives a bitboard representing all squares along the ray in a
/// given direction from a given square. /// given direction from a given square.
@@ -235,24 +225,19 @@ inline Bitboard ray_bb(Square s, SignedDirection d) {
/// bitboard of occupied squares as input, and return a bitboard representing /// bitboard of occupied squares as input, and return a bitboard representing
/// all squares attacked by a rook, bishop or queen on the given square. /// all squares attacked by a rook, bishop or queen on the given square.
#if defined(USE_COMPACT_ROOK_ATTACKS) #if defined(IS_64BIT)
inline Bitboard file_attacks_bb(Square s, Bitboard blockers) {
Bitboard b = (blockers >> square_file(s)) & 0x01010101010100ULL;
return
FileAttacks[square_rank(s)][(b*0xd6e8802041d0c441ULL)>>58] & file_bb(s);
}
inline Bitboard rank_attacks_bb(Square s, Bitboard blockers) {
Bitboard b = (blockers >> ((s & 56) + 1)) & 63;
return RankAttacks[square_file(s)][b] & rank_bb(s);
}
inline Bitboard rook_attacks_bb(Square s, Bitboard blockers) { inline Bitboard rook_attacks_bb(Square s, Bitboard blockers) {
return file_attacks_bb(s, blockers) | rank_attacks_bb(s, blockers); Bitboard b = blockers & RMask[s];
return RAttacks[RAttackIndex[s] + ((b * RMult[s]) >> RShift[s])];
} }
#elif defined(USE_32BIT_ATTACKS) inline Bitboard bishop_attacks_bb(Square s, Bitboard blockers) {
Bitboard b = blockers & BMask[s];
return BAttacks[BAttackIndex[s] + ((b * BMult[s]) >> BShift[s])];
}
#else // if !defined(IS_64BIT)
inline Bitboard rook_attacks_bb(Square s, Bitboard blockers) { inline Bitboard rook_attacks_bb(Square s, Bitboard blockers) {
Bitboard b = blockers & RMask[s]; Bitboard b = blockers & RMask[s];
@@ -262,17 +247,6 @@ inline Bitboard rook_attacks_bb(Square s, Bitboard blockers) {
>> RShift[s])]; >> RShift[s])];
} }
#else
inline Bitboard rook_attacks_bb(Square s, Bitboard blockers) {
Bitboard b = blockers & RMask[s];
return RAttacks[RAttackIndex[s] + ((b * RMult[s]) >> RShift[s])];
}
#endif
#if defined(USE_32BIT_ATTACKS)
inline Bitboard bishop_attacks_bb(Square s, Bitboard blockers) { inline Bitboard bishop_attacks_bb(Square s, Bitboard blockers) {
Bitboard b = blockers & BMask[s]; Bitboard b = blockers & BMask[s];
return BAttacks[BAttackIndex[s] + return BAttacks[BAttackIndex[s] +
@@ -281,14 +255,7 @@ inline Bitboard bishop_attacks_bb(Square s, Bitboard blockers) {
>> BShift[s])]; >> BShift[s])];
} }
#else // defined(USE_32BIT_ATTACKS) #endif
inline Bitboard bishop_attacks_bb(Square s, Bitboard blockers) {
Bitboard b = blockers & BMask[s];
return BAttacks[BAttackIndex[s] + ((b * BMult[s]) >> BShift[s])];
}
#endif // defined(USE_32BIT_ATTACKS)
inline Bitboard queen_attacks_bb(Square s, Bitboard blockers) { inline Bitboard queen_attacks_bb(Square s, Bitboard blockers) {
return rook_attacks_bb(s, blockers) | bishop_attacks_bb(s, blockers); return rook_attacks_bb(s, blockers) | bishop_attacks_bb(s, blockers);
@@ -350,62 +317,30 @@ inline Bitboard isolated_pawn_mask(Square s) {
} }
/// count_1s() counts the number of nonzero bits in a bitboard. /// first_1() finds the least significant nonzero bit in a nonzero bitboard.
/// pop_1st_bit() finds and clears the least significant nonzero bit in a
/// nonzero bitboard.
#if defined(BITCOUNT_LOOP) #if defined(USE_BSFQ) // Assembly code by Heinz van Saanen
inline int count_1s(Bitboard b) { inline Square first_1(Bitboard b) {
int r; Bitboard dummy;
for(r = 0; b; r++, b &= b - 1); __asm__("bsfq %1, %0": "=r"(dummy): "rm"(b) );
return r; return (Square)(dummy);
} }
inline int count_1s_max_15(Bitboard b) { inline Square pop_1st_bit(Bitboard* b) {
return count_1s(b); const Square s = first_1(*b);
*b &= ~(1ULL<<s);
return s;
} }
#elif defined(BITCOUNT_SWAR_32) #else // if !defined(USE_BSFQ)
inline int count_1s(Bitboard b) { extern Square first_1(Bitboard b);
unsigned w = unsigned(b >> 32), v = unsigned(b); extern Square pop_1st_bit(Bitboard* b);
v = v - ((v >> 1) & 0x55555555);
w = w - ((w >> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
w = (w & 0x33333333) + ((w >> 2) & 0x33333333);
v = (v + (v >> 4)) & 0x0F0F0F0F;
w = (w + (w >> 4)) & 0x0F0F0F0F;
v = ((v+w) * 0x01010101) >> 24; // mul is fast on amd procs
return int(v);
}
inline int count_1s_max_15(Bitboard b) { #endif
unsigned w = unsigned(b >> 32), v = unsigned(b);
v = v - ((v >> 1) & 0x55555555);
w = w - ((w >> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
w = (w & 0x33333333) + ((w >> 2) & 0x33333333);
v = ((v+w) * 0x11111111) >> 28;
return int(v);
}
#elif defined(BITCOUNT_SWAR_64)
inline int count_1s(Bitboard b) {
b -= ((b>>1) & 0x5555555555555555ULL);
b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
b = ((b>>4) + b) & 0x0F0F0F0F0F0F0F0FULL;
b *= 0x0101010101010101ULL;
return int(b >> 56);
}
inline int count_1s_max_15(Bitboard b) {
b -= (b>>1) & 0x5555555555555555ULL;
b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
b *= 0x1111111111111111ULL;
return int(b >> 60);
}
#endif // BITCOUNT
//// ////
@@ -414,8 +349,6 @@ inline int count_1s_max_15(Bitboard b) {
extern void print_bitboard(Bitboard b); extern void print_bitboard(Bitboard b);
extern void init_bitboards(); extern void init_bitboards();
extern Square first_1(Bitboard b);
extern Square pop_1st_bit(Bitboard *b);
#endif // !defined(BITBOARD_H_INCLUDED) #endif // !defined(BITBOARD_H_INCLUDED)
+161
View File
@@ -0,0 +1,161 @@
/*
Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(BITCOUNT_H_INCLUDED)
#define BITCOUNT_H_INCLUDED
// To enable POPCNT support uncomment USE_POPCNT define. For PGO compile on a Core i7
// you may want to collect profile data first with USE_POPCNT disabled and then, in a
// second profiling session, with USE_POPCNT enabled so to exercise both paths. Don't
// forget to leave USE_POPCNT enabled for the final optimized compile though ;-)
//#define USE_POPCNT
#include "types.h"
// Select type of intrinsic bit count instruction to use
#if defined(__INTEL_COMPILER) && defined(IS_64BIT) && defined(USE_POPCNT) // Intel compiler
#include <nmmintrin.h>
inline bool cpu_has_popcnt() {
int CPUInfo[4] = {-1};
__cpuid(CPUInfo, 0x00000001);
return (CPUInfo[2] >> 23) & 1;
}
// Define a dummy template to workaround a compile error if _mm_popcnt_u64() is not defined.
//
// If _mm_popcnt_u64() is defined in <nmmintrin.h> it will be choosen first due to
// C++ overload rules that always prefer a function to a template with the same name.
// If not, we avoid a compile error and because cpu_has_popcnt() should return false,
// our templetized _mm_popcnt_u64() is never called anyway.
template<typename T> inline unsigned _mm_popcnt_u64(T) { return 0; } // Is never called
#define POPCNT_INTRINSIC(x) _mm_popcnt_u64(x)
#elif defined(_MSC_VER) && defined(IS_64BIT) && defined(USE_POPCNT) // Microsoft compiler
#include <intrin.h>
inline bool cpu_has_popcnt() {
int CPUInfo[4] = {-1};
__cpuid(CPUInfo, 0x00000001);
return (CPUInfo[2] >> 23) & 1;
}
// See comment of _mm_popcnt_u64<>() few lines above for an explanation.
template<typename T> inline unsigned __popcnt64(T) { return 0; } // Is never called
#define POPCNT_INTRINSIC(x) __popcnt64(x)
#else // Safe fallback for unsupported compilers or when USE_POPCNT is disabled
inline bool cpu_has_popcnt() { return false; }
#define POPCNT_INTRINSIC(x) 0
#endif // cpu_has_popcnt() and POPCNT_INTRINSIC() definitions
/// Software implementation of bit count functions
#if defined(IS_64BIT)
inline int count_1s(Bitboard b) {
b -= ((b>>1) & 0x5555555555555555ULL);
b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
b = ((b>>4) + b) & 0x0F0F0F0F0F0F0F0FULL;
b *= 0x0101010101010101ULL;
return int(b >> 56);
}
inline int count_1s_max_15(Bitboard b) {
b -= (b>>1) & 0x5555555555555555ULL;
b = ((b>>2) & 0x3333333333333333ULL) + (b & 0x3333333333333333ULL);
b *= 0x1111111111111111ULL;
return int(b >> 60);
}
#else // if !defined(IS_64BIT)
inline int count_1s(Bitboard b) {
unsigned w = unsigned(b >> 32), v = unsigned(b);
v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits
w -= (w >> 1) & 0x55555555;
v = ((v >> 2) & 0x33333333) + (v & 0x33333333); // 0-4 in 4 bits
w = ((w >> 2) & 0x33333333) + (w & 0x33333333);
v = ((v >> 4) + v) & 0x0F0F0F0F; // 0-8 in 8 bits
v += (((w >> 4) + w) & 0x0F0F0F0F); // 0-16 in 8 bits
v *= 0x01010101; // mul is fast on amd procs
return int(v >> 24);
}
inline int count_1s_max_15(Bitboard b) {
unsigned w = unsigned(b >> 32), v = unsigned(b);
v -= (v >> 1) & 0x55555555; // 0-2 in 2 bits
w -= (w >> 1) & 0x55555555;
v = ((v >> 2) & 0x33333333) + (v & 0x33333333); // 0-4 in 4 bits
w = ((w >> 2) & 0x33333333) + (w & 0x33333333);
v += w; // 0-8 in 4 bits
v *= 0x11111111;
return int(v >> 28);
}
#endif // BITCOUNT
/// count_1s() counts the number of nonzero bits in a bitboard.
/// If template parameter is true an intrinsic is called, otherwise
/// we fallback on a software implementation.
template<bool UseIntrinsic>
inline int count_1s(Bitboard b) {
return UseIntrinsic ? POPCNT_INTRINSIC(b) : count_1s(b);
}
template<bool UseIntrinsic>
inline int count_1s_max_15(Bitboard b) {
return UseIntrinsic ? POPCNT_INTRINSIC(b) : count_1s_max_15(b);
}
// Global constant initialized at startup that is set to true if
// CPU on which application runs supports POPCNT intrinsic. Unless
// USE_POPCNT is not defined.
const bool CpuHasPOPCNT = cpu_has_popcnt();
// Global constant used to print info about the use of 64 optimized
// functions to verify that a 64 bit compile has been correctly built.
#if defined(IS_64BIT)
const bool CpuHas64BitPath = true;
#else
const bool CpuHas64BitPath = false;
#endif
#endif // !defined(BITCOUNT_H_INCLUDED)
+121 -116
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -29,12 +30,12 @@
//// ////
#include <cassert> #include <cassert>
#include <cstdio>
#include "book.h" #include "book.h"
#include "mersenne.h" #include "mersenne.h"
#include "movegen.h" #include "movegen.h"
using namespace std;
//// ////
//// Global variables //// Global variables
@@ -49,7 +50,11 @@ Book OpeningBook;
namespace { namespace {
/// Random numbers from PolyGlot, used to compute book hash keys. /// Book entry size in bytes
const int EntrySize = 16;
/// Random numbers from PolyGlot, used to compute book hash keys
const uint64_t Random64[781] = { const uint64_t Random64[781] = {
0x9D39247E33776D41ULL, 0x2AF7398005AAA5C7ULL, 0x44DB015024623547ULL, 0x9D39247E33776D41ULL, 0x2AF7398005AAA5C7ULL, 0x44DB015024623547ULL,
@@ -324,13 +329,6 @@ namespace {
const int RandomTurn = 780; const int RandomTurn = 780;
/// Convert pieces to the range 0..1
const int PieceTo12[] = {
0, 0, 2, 4, 6, 8, 10, 0, 0, 1, 3, 5, 7, 9, 11
};
/// Prototypes /// Prototypes
uint64_t book_key(const Position& pos); uint64_t book_key(const Position& pos);
@@ -338,9 +336,6 @@ namespace {
uint64_t book_castle_key(const Position& pos); uint64_t book_castle_key(const Position& pos);
uint64_t book_ep_key(const Position& pos); uint64_t book_ep_key(const Position& pos);
uint64_t book_color_key(const Position& pos); uint64_t book_color_key(const Position& pos);
uint64_t read_integer(FILE *file, int size);
} }
@@ -349,89 +344,97 @@ namespace {
//// ////
/// Constructor /// Destructor. Be sure file is closed before we leave.
Book::Book() { Book::~Book() {
bookFile = NULL;
bookSize = 0; close();
} }
/// Book::open() opens a book file with a given file name. /// 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();
void Book::open(const std::string &fName) {
fileName = fName; fileName = fName;
bookFile = fopen(fileName.c_str(), "rb"); ifstream::open(fileName.c_str(), ifstream::in | ifstream::binary);
if(bookFile != NULL) { if (!is_open())
if(fseek(bookFile, 0, SEEK_END) == -1) { return;
std::cerr << "Failed to open book file " << fileName << std::endl;
exit(EXIT_FAILURE); // Get the book size in number of entries
} seekg(0, ios::end);
bookSize = ftell(bookFile) / 16; bookSize = tellg() / EntrySize;
if(bookSize == -1) { seekg(0, ios::beg);
std::cerr << "Failed to open book file " << fileName << std::endl;
exit(EXIT_FAILURE); if (!good())
} {
cerr << "Failed to open book file " << fileName << endl;
Application::exit_with_failure();
} }
} }
/// Book::close() closes the currently open book file. /// Book::close() closes the file only if it is open, otherwise
/// we can end up in a little mess due to how std::ifstream works.
void Book::close() { void Book::close() {
if(bookFile != NULL && fclose(bookFile) == EOF) {
std::cerr << "Failed to close book file" << std::endl;
exit(EXIT_FAILURE);
}
}
if (is_open())
/// Book::is_open() tests whether a book file has been opened. ifstream::close();
bool Book::is_open() const {
return bookFile != NULL && bookSize != 0;
} }
/// Book::file_name() returns the file name of the currently active book, /// Book::file_name() returns the file name of the currently active book,
/// or the empty string if no book is open. /// or the empty string if no book is open.
const std::string Book::file_name() const { const string Book::file_name() const {
return this->is_open()? fileName : "";
return is_open() ? fileName : "";
} }
/// Book::get_move() gets a book move for a given position. Returns /// Book::get_move() gets a book move for a given position. Returns
/// MOVE_NONE if no book move is found. /// MOVE_NONE if no book move is found.
Move Book::get_move(const Position &pos) const { Move Book::get_move(const Position& pos) {
if(this->is_open()) {
int bestMove = 0, bestScore = 0, move, score; if (!is_open() || bookSize == 0)
return MOVE_NONE;
int bookMove = 0, scoresSum = 0;
uint64_t key = book_key(pos); uint64_t key = book_key(pos);
BookEntry entry; BookEntry entry;
for(int i = this->find_key(key); i < bookSize; i++) { // Choose a book move among the possible moves for the given position
this->read_entry(entry, i); for (int idx = find_key(key); idx < bookSize; idx++)
{
read_entry(entry, idx);
if (entry.key != key) if (entry.key != key)
break; break;
move = entry.move;
score = entry.count; int score = entry.count;
assert(score > 0); assert(score > 0);
bestScore += score; // Choose book move according to its score. If a move has a very
if(int(genrand_int32() % bestScore) < score) // high score it has more probability to be choosen then a one with
bestMove = move; // lower score. Note that first entry is always chosen.
scoresSum += score;
if (int(genrand_int32() % scoresSum) < score)
bookMove = entry.move;
} }
if (!bookMove)
return MOVE_NONE;
MoveStack mlist[256];
MoveStack* last = generate_moves(pos, mlist);
for (MoveStack* cur = mlist; cur != last; cur++)
if ((int(cur->move) & 07777) == bookMove)
return cur->move;
if(bestMove != 0) {
MoveStack moves[256];
int n, j;
n = generate_legal_moves(pos, moves);
for(j = 0; j < n; j++)
if((int(moves[j].move) & 07777) == bestMove)
return moves[j].move;
}
}
return MOVE_NONE; return MOVE_NONE;
} }
@@ -441,7 +444,8 @@ Move Book::get_move(const Position &pos) const {
/// entry with the same key as the input is returned. When the key is not /// entry with the same key as the input is returned. When the key is not
/// found in the book file, bookSize is returned. /// found in the book file, bookSize is returned.
int Book::find_key(uint64_t key) const { int Book::find_key(uint64_t key) {
int left, right, mid; int left, right, mid;
BookEntry entry; BookEntry entry;
@@ -451,12 +455,13 @@ int Book::find_key(uint64_t key) const {
assert(left <= right); assert(left <= right);
while(left < right) { while (left < right)
{
mid = (left + right) / 2; mid = (left + right) / 2;
assert(mid >= left && mid < right); assert(mid >= left && mid < right);
this->read_entry(entry, mid); read_entry(entry, mid);
if (key <= entry.key) if (key <= entry.key)
right = mid; right = mid;
else else
@@ -465,8 +470,7 @@ int Book::find_key(uint64_t key) const {
assert(left == right); assert(left == right);
this->read_entry(entry, left); read_entry(entry, left);
return (entry.key == key)? left : bookSize; return (entry.key == key)? left : bookSize;
} }
@@ -475,20 +479,35 @@ int Book::find_key(uint64_t key) const {
/// input, and looks up the opening book entry at the given index in the book /// 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. /// file. The book entry is copied to the first input parameter.
void Book::read_entry(BookEntry& entry, int n) const { void Book::read_entry(BookEntry& entry, int idx) {
assert(n >= 0 && n < bookSize);
assert(bookFile != NULL);
if(fseek(bookFile, n*16, SEEK_SET) == -1) { assert(idx >= 0 && idx < bookSize);
std::cerr << "Failed to read book entry at index " << n << std::endl; assert(is_open());
exit(EXIT_FAILURE);
seekg(idx * EntrySize, ios_base::beg);
*this >> entry;
if (!good())
{
cerr << "Failed to read book entry at index " << idx << endl;
Application::exit_with_failure();
}
} }
entry.key = read_integer(bookFile, 8);
entry.move = read_integer(bookFile, 2); /// Book::read_integer() reads size chars from the file stream
entry.count = read_integer(bookFile, 2); /// and converts them in an integer number.
entry.n = read_integer(bookFile, 2);
entry.sum = read_integer(bookFile, 2); 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;
} }
@@ -499,80 +518,66 @@ void Book::read_entry(BookEntry& entry, int n) const {
namespace { namespace {
uint64_t book_key(const Position& pos) { uint64_t book_key(const Position& pos) {
uint64_t result = 0ULL; uint64_t result = 0ULL;
for(Color c = WHITE; c <= BLACK; c++) { for (Color c = WHITE; c <= BLACK; c++)
{
Bitboard b = pos.pieces_of_color(c); Bitboard b = pos.pieces_of_color(c);
Square s;
Piece p; while (b)
while(b != EmptyBoardBB) { {
s = pop_1st_bit(&b); Square s = pop_1st_bit(&b);
p = pos.piece_on(s); Piece p = pos.piece_on(s);
assert(piece_is_ok(p)); assert(piece_is_ok(p));
assert(color_of_piece(p) == c); assert(color_of_piece(p) == c);
result ^= book_piece_key(p, s); result ^= book_piece_key(p, s);
} }
} }
result ^= book_castle_key(pos); result ^= book_castle_key(pos);
result ^= book_ep_key(pos); result ^= book_ep_key(pos);
result ^= book_color_key(pos); result ^= book_color_key(pos);
return result; return result;
} }
uint64_t book_piece_key(Piece p, Square s) { 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)]; return Random64[RandomPiece + (PieceTo12[int(p)]^1) * 64 + int(s)];
} }
uint64_t book_castle_key(const Position& pos) { uint64_t book_castle_key(const Position& pos) {
uint64_t result = 0ULL; uint64_t result = 0ULL;
if (pos.can_castle_kingside(WHITE)) if (pos.can_castle_kingside(WHITE))
result ^= Random64[RandomCastle+0]; result ^= Random64[RandomCastle+0];
if (pos.can_castle_queenside(WHITE)) if (pos.can_castle_queenside(WHITE))
result ^= Random64[RandomCastle+1]; result ^= Random64[RandomCastle+1];
if (pos.can_castle_kingside(BLACK)) if (pos.can_castle_kingside(BLACK))
result ^= Random64[RandomCastle+2]; result ^= Random64[RandomCastle+2];
if (pos.can_castle_queenside(BLACK)) if (pos.can_castle_queenside(BLACK))
result ^= Random64[RandomCastle+3]; result ^= Random64[RandomCastle+3];
return result; return result;
} }
uint64_t book_ep_key(const Position& pos) { uint64_t book_ep_key(const Position& pos) {
return (pos.ep_square() == SQ_NONE)? return (pos.ep_square() == SQ_NONE ? 0ULL : Random64[RandomEnPassant + square_file(pos.ep_square())]);
0ULL : Random64[RandomEnPassant + square_file(pos.ep_square())];
} }
uint64_t book_color_key(const Position& pos) { uint64_t book_color_key(const Position& pos) {
return (pos.side_to_move() == WHITE)? Random64[RandomTurn] : 0ULL; return (pos.side_to_move() == WHITE ? Random64[RandomTurn] : 0ULL);
} }
uint64_t read_integer(FILE *file, int size) {
uint64_t n = 0ULL;;
int i;
int b;
assert(file != NULL);
assert(size > 0 && size <= 8);
for(i = 0; i < size; i++) {
b = fgetc(file);
if(b == EOF) {
std::cerr << "Failed to read " << size << " bytes from book file"
<< std::endl;
exit(EXIT_FAILURE);
}
assert(b >= 0 && b < 256);
n = (n << 8) | b;
}
return n;
}
} }
+16 -21
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -32,6 +33,7 @@
//// Includes //// Includes
//// ////
#include <fstream>
#include <string> #include <string>
#include "move.h" #include "move.h"
@@ -50,31 +52,24 @@ struct BookEntry {
uint16_t sum; uint16_t sum;
}; };
class Book { class Book : private std::ifstream {
public: public:
// Constructors ~Book();
Book();
// Open and close book files
void open(const std::string& fName); void open(const std::string& fName);
void close(); void close();
// Testing if a book is opened
bool is_open() const;
// The file name of the currently active book
const std::string file_name() const; const std::string file_name() const;
Move get_move(const Position& pos);
// Get a book move for a given position
Move get_move(const Position &pos) const;
private: private:
int find_key(uint64_t key) const; Book& operator>>(uint64_t& n) { n = read_integer(8); return *this; }
void read_entry(BookEntry &entry, int n) const; Book& operator>>(uint16_t& n) { n = (uint16_t)read_integer(2); return *this; }
void operator>>(BookEntry& e) { *this >> e.key >> e.move >> e.count >> e.n >> e.sum; }
uint64_t read_integer(int size);
void read_entry(BookEntry& e, int n);
int find_key(uint64_t key);
std::string fileName; std::string fileName;
FILE *bookFile;
int bookSize; int bookSize;
}; };
-35
View File
@@ -1,35 +0,0 @@
/*
Glaurung, a UCI chess playing engine.
Copyright (C) 2004-2008 Tord Romstad
Glaurung 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.
Glaurung 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 "color.h"
////
//// Functions
////
/// color_is_ok(), for debugging:
bool color_is_ok(Color c) {
return c == WHITE || c == BLACK;
}
+9 -19
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -20,12 +21,6 @@
#if !defined(COLOR_H_INCLUDED) #if !defined(COLOR_H_INCLUDED)
#define COLOR_H_INCLUDED #define COLOR_H_INCLUDED
////
//// Includes
////
#include "misc.h"
//// ////
//// Types //// Types
@@ -42,19 +37,14 @@ enum Color {
//// Inline functions //// Inline functions
//// ////
inline Color operator+ (Color c, int i) { return Color(int(c) + i); } inline void operator++ (Color &c, int) { c = Color(int(c) + 1); }
inline void operator++ (Color &c, int i) { c = Color(int(c) + 1); }
inline Color opposite_color(Color c) { inline Color opposite_color(Color c) {
return Color(int(c) ^ 1); return Color(int(c) ^ 1);
} }
inline bool color_is_ok(Color c) {
//// return c == WHITE || c == BLACK;
//// Prototypes }
////
extern bool color_is_ok(Color c);
#endif // !defined(COLOR_H_INCLUDED) #endif // !defined(COLOR_H_INCLUDED)
+5 -7
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -34,9 +35,6 @@ enum Depth {
//// Constants //// Constants
//// ////
/// Note: If OnePly is changed, the constant HistoryMax in history.h should
/// probably also be changed.
const Depth OnePly = Depth(2); const Depth OnePly = Depth(2);
+41 -16
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -25,6 +26,32 @@
#include "square.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 //// Variables
//// ////
@@ -38,21 +65,19 @@ uint8_t SignedDirectionTable[64][64];
//// ////
void init_direction_table() { void init_direction_table() {
SquareDelta deltas[8] = {
DELTA_E, DELTA_W, DELTA_N, DELTA_S, DELTA_NE, DELTA_SW, DELTA_NW, DELTA_SE
};
for (Square s1 = SQ_A1; s1 <= SQ_H8; s1++) for (Square s1 = SQ_A1; s1 <= SQ_H8; s1++)
for(Square s2 = SQ_A1; s2 <= SQ_H8; s2++) { for (Square s2 = SQ_A1; s2 <= SQ_H8; s2++)
{
DirectionTable[s1][s2] = uint8_t(DIR_NONE); DirectionTable[s1][s2] = uint8_t(DIR_NONE);
SignedDirectionTable[s1][s2] = uint8_t(SIGNED_DIR_NONE); SignedDirectionTable[s1][s2] = uint8_t(SIGNED_DIR_NONE);
if(s1 == s2) continue; if (s1 == s2)
for(SignedDirection d = SIGNED_DIR_E; d <= SIGNED_DIR_SE; d++) { continue;
SquareDelta delta = deltas[d];
Square s3, s4; for (SignedDirection d = SIGNED_DIR_E; d != SIGNED_DIR_NONE; d++)
for(s4 = s1 + delta, s3 = s1; {
square_distance(s4, s3) == 1 && s4 != s2 && square_is_ok(s4); if (reachable(s1, s2, d))
s3 = s4, s4 += delta); {
if(s4 == s2 && square_distance(s4, s3) == 1) {
SignedDirectionTable[s1][s2] = uint8_t(d); SignedDirectionTable[s1][s2] = uint8_t(d);
DirectionTable[s1][s2] = uint8_t(d / 2); DirectionTable[s1][s2] = uint8_t(d / 2);
break; break;
+15 -5
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -57,7 +58,9 @@ extern uint8_t SignedDirectionTable[64][64];
//// Inline functions //// Inline functions
//// ////
inline void operator++ (Direction &d, int) { d = Direction(int(d) + 1); } inline void operator++ (Direction& d, int) {
d = Direction(int(d) + 1);
}
inline void operator++ (SignedDirection& d, int) { inline void operator++ (SignedDirection& d, int) {
d = SignedDirection(int(d) + 1); d = SignedDirection(int(d) + 1);
@@ -71,6 +74,13 @@ inline SignedDirection signed_direction_between_squares(Square s1, Square s2) {
return SignedDirection(SignedDirectionTable[s1][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 //// Prototypes
+390 -345
View File
File diff suppressed because it is too large Load Diff
+53 -189
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -33,204 +34,67 @@
//// Types //// Types
//// ////
/// Abstract base class for all special endgame evaluation functions: enum EndgameType {
class EndgameEvaluationFunction { // Evaluation functions
KXK, // Generic "mate lone king" eval
KBNK, // KBN vs K
KPK, // KP vs K
KRKP, // KR vs KP
KRKB, // KR vs KB
KRKN, // KR vs KN
KQKR, // KQ vs KR
KBBKN, // KBB vs KN
KNNK, // KNN vs K
KmmKm, // K and two minors vs K and one or two minors
// Scaling functions
KBPsK, // KB+pawns vs K
KQKRPs, // KQ vs KR+pawns
KRPKR, // KRP vs KR
KRPPKRP, // KRPP vs KRP
KPsK, // King and pawns vs king
KBPKB, // KBP vs KB
KBPPKB, // KBPP vs KB
KBPKN, // KBP vs KN
KNPK, // KNP vs K
KPKP // KP vs KP
};
/// Template abstract base class for all special endgame functions
template<typename T>
class EndgameFunctionBase {
public: public:
EndgameEvaluationFunction(Color c); EndgameFunctionBase(Color c) : strongerSide(c), weakerSide(opposite_color(c)) {}
virtual ~EndgameEvaluationFunction() { } virtual ~EndgameFunctionBase() {}
virtual T apply(const Position&) = 0;
virtual Value apply(const Position &pos) =0; Color color() const { return strongerSide; }
protected: protected:
Color strongerSide, weakerSide; Color strongerSide, weakerSide;
}; };
typedef EndgameFunctionBase<Value> EndgameEvaluationFunctionBase;
typedef EndgameFunctionBase<ScaleFactor> EndgameScalingFunctionBase;
/// Subclasses for various concrete endgames:
// Generic "mate lone king" eval: /// Templates subclass for various concrete endgames
class KXKEvaluationFunction : public EndgameEvaluationFunction {
public: template<EndgameType>
KXKEvaluationFunction(Color c); struct EvaluationFunction : public EndgameEvaluationFunctionBase {
Value apply(const Position &pos); typedef EndgameEvaluationFunctionBase Base;
explicit EvaluationFunction(Color c): EndgameEvaluationFunctionBase(c) {}
Value apply(const Position&);
}; };
// KBN vs K: template<EndgameType>
class KBNKEvaluationFunction : public EndgameEvaluationFunction { struct ScalingFunction : public EndgameScalingFunctionBase {
public: typedef EndgameScalingFunctionBase Base;
KBNKEvaluationFunction(Color c); explicit ScalingFunction(Color c) : EndgameScalingFunctionBase(c) {}
Value apply(const Position &pos); ScaleFactor apply(const Position&);
}; };
// KP vs K:
class KPKEvaluationFunction : public EndgameEvaluationFunction {
public:
KPKEvaluationFunction(Color c);
Value apply(const Position &pos);
};
// KR vs KP:
class KRKPEvaluationFunction : public EndgameEvaluationFunction {
public:
KRKPEvaluationFunction(Color c);
Value apply(const Position &pos);
};
// KR vs KB:
class KRKBEvaluationFunction : public EndgameEvaluationFunction {
public:
KRKBEvaluationFunction(Color c);
Value apply(const Position &pos);
};
// KR vs KN:
class KRKNEvaluationFunction : public EndgameEvaluationFunction {
public:
KRKNEvaluationFunction(Color c);
Value apply(const Position &pos);
};
// KQ vs KR:
class KQKREvaluationFunction : public EndgameEvaluationFunction {
public:
KQKREvaluationFunction(Color c);
Value apply(const Position &pos);
};
/// Abstract base class for all evaluation scaling functions:
class ScalingFunction {
public:
ScalingFunction(Color c);
virtual ~ScalingFunction() { }
virtual ScaleFactor apply(const Position &pos) =0;
protected:
Color strongerSide, weakerSide;
};
/// Subclasses for various concrete endgames:
// KBP vs K:
class KBPKScalingFunction : public ScalingFunction {
public:
KBPKScalingFunction(Color c);
ScaleFactor apply(const Position &pos);
};
// KQ vs KRP:
class KQKRPScalingFunction: public ScalingFunction {
public:
KQKRPScalingFunction(Color c);
ScaleFactor apply(const Position &pos);
};
// KRP vs KR:
class KRPKRScalingFunction : public ScalingFunction {
public:
KRPKRScalingFunction(Color c);
ScaleFactor apply(const Position &pos);
};
// KRPP vs KRP:
class KRPPKRPScalingFunction : public ScalingFunction {
public:
KRPPKRPScalingFunction(Color c);
ScaleFactor apply(const Position &pos);
};
// King and pawns vs king:
class KPsKScalingFunction : public ScalingFunction {
public:
KPsKScalingFunction(Color c);
ScaleFactor apply(const Position &pos);
};
// KBP vs KB:
class KBPKBScalingFunction : public ScalingFunction {
public:
KBPKBScalingFunction(Color c);
ScaleFactor apply(const Position &pos);
};
// KBP vs KN:
class KBPKNScalingFunction : public ScalingFunction {
public:
KBPKNScalingFunction(Color c);
ScaleFactor apply(const Position &pos);
};
// KNP vs K:
class KNPKScalingFunction : public ScalingFunction {
public:
KNPKScalingFunction(Color c);
ScaleFactor apply(const Position &pos);
};
// KP vs KP:
class KPKPScalingFunction : public ScalingFunction {
public:
KPKPScalingFunction(Color c);
ScaleFactor apply(const Position &pos);
};
////
//// Constants and variables
////
// Generic "mate lone king" eval:
extern KXKEvaluationFunction EvaluateKXK, EvaluateKKX;
// KBN vs K:
extern KBNKEvaluationFunction EvaluateKBNK, EvaluateKKBN;
// KP vs K:
extern KPKEvaluationFunction EvaluateKPK, EvaluateKKP;
// KR vs KP:
extern KRKPEvaluationFunction EvaluateKRKP, EvaluateKPKR;
// KR vs KB:
extern KRKBEvaluationFunction EvaluateKRKB, EvaluateKBKR;
// KR vs KN:
extern KRKNEvaluationFunction EvaluateKRKN, EvaluateKNKR;
// KQ vs KR:
extern KQKREvaluationFunction EvaluateKQKR, EvaluateKRKQ;
// KBP vs K:
extern KBPKScalingFunction ScaleKBPK, ScaleKKBP;
// KQ vs KRP:
extern KQKRPScalingFunction ScaleKQKRP, ScaleKRPKQ;
// KRP vs KR:
extern KRPKRScalingFunction ScaleKRPKR, ScaleKRKRP;
// KRPP vs KRP:
extern KRPPKRPScalingFunction ScaleKRPPKRP, ScaleKRPKRPP;
// King and pawns vs king:
extern KPsKScalingFunction ScaleKPsK, ScaleKKPs;
// KBP vs KB:
extern KBPKBScalingFunction ScaleKBPKB, ScaleKBKBP;
// KBP vs KN:
extern KBPKNScalingFunction ScaleKBPKN, ScaleKNKBP;
// KNP vs K:
extern KNPKScalingFunction ScaleKNPK, ScaleKKNP;
// KP vs KP:
extern KPKPScalingFunction ScaleKPKPw, ScaleKPKPb;
//// ////
//// Prototypes //// Prototypes
+675 -674
View File
File diff suppressed because it is too large Load Diff
+28 -25
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -26,13 +27,13 @@
#include "material.h" #include "material.h"
#include "pawns.h" #include "pawns.h"
#include "position.h"
//// ////
//// Types //// Types
//// ////
/// The EvalInfo struct contains various information computed and collected /// The EvalInfo struct contains various information computed and collected
/// by the evaluation function. An EvalInfo object is passed as one of the /// 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 /// arguments to the evaluation function, and the search can make use of its
@@ -40,47 +41,49 @@
/// ///
/// At the moment, this is not utilized very much: The only part of the /// At the moment, this is not utilized very much: The only part of the
/// EvalInfo object which is used by the search is futilityMargin. /// EvalInfo object which is used by the search is futilityMargin.
class Position;
struct EvalInfo { struct EvalInfo {
// Middle game and endgame evaluations: // Middle game and endgame evaluations
Value mgValue, egValue; Value mgValue, egValue;
// Pointers to material and pawn hash table entries: // Pointers to material and pawn hash table entries
MaterialInfo* mi; MaterialInfo* mi;
PawnInfo* pi; PawnInfo* pi;
// attackedBy[color][piece type] is a bitboard representing all squares // attackedBy[color][piece type] is a bitboard representing all squares
// attacked by a given color and piece type. attackedBy[color][0] contains // attacked by a given color and piece type, attackedBy[color][0] contains
// all squares attacked by the given color. // all squares attacked by the given color.
Bitboard attackedBy[2][8]; Bitboard attackedBy[2][8];
Bitboard attacked_by(Color c) const { return attackedBy[c][0]; } Bitboard attacked_by(Color c) const { return attackedBy[c][0]; }
Bitboard attacked_by(Color c, PieceType pt) const { return attackedBy[c][pt]; } Bitboard attacked_by(Color c, PieceType pt) const { return attackedBy[c][pt]; }
// attackZone[color] is the zone around the enemy king which is considered
// kingZone[color] is the zone around the enemy king which is considered
// by the king safety evaluation. This consists of the squares directly // by the king safety evaluation. This consists of the squares directly
// adjacent to the king, and the three (or two, for a king on an edge file) // 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 // squares two ranks in front of the king. For instance, if black's king
// is on g8, attackZone[WHITE] is a bitboard containing the squares f8, h8, // is on g8, kingZone[WHITE] is a bitboard containing the squares f8, h8,
// f7, g7, h7, f6, g6 and h6. // f7, g7, h7, f6, g6 and h6.
Bitboard attackZone[2]; Bitboard kingZone[2];
// attackCount[color] is the number of pieces of the given color which // kingAttackersCount[color] is the number of pieces of the given color
// attack a square adjacent to the enemy king. // which attack a square in the kingZone of the enemy king.
int attackCount[2]; int kingAttackersCount[2];
// attackWeight[color] is the sum of the "weight" of the pieces of the given // kingAttackersWeight[color] is the sum of the "weight" of the pieces of the
// color which attack a square adjacent to the enemy king. The weights of // given color which attack a square in the kingZone of the enemy king. The
// the individual piece types are given by the variables QueenAttackWeight, // weights of the individual piece types are given by the variables
// RookAttackWeight, BishopAttackWeight and KnightAttackWeight in // QueenAttackWeight, RookAttackWeight, BishopAttackWeight and
// evaluate.cpp. // KnightAttackWeight in evaluate.cpp
int attackWeight[2]; int kingAttackersWeight[2];
// attacked[color] is the number of enemy piece attacks to squares directly // kingAdjacentZoneAttacksCount[color] is the number of attacks to squares
// adjacent to the king of the given color. Pieces which attack more // directly adjacent to the king of the given color. Pieces which attack
// than one square are counted multiple times. For instance, if black's // more than one square are counted multiple times. For instance, if black's
// king is on g8 and there's a white knight on g5, this knight adds // king is on g8 and there's a white knight on g5, this knight adds
// 2 to attacked[BLACK]. // 2 to kingAdjacentZoneAttacksCount[BLACK].
int attacked[2]; int kingAdjacentZoneAttacksCount[2];
// mateThreat[color] is a move for the given side which gives a direct mate. // mateThreat[color] is a move for the given side which gives a direct mate.
Move mateThreat[2]; Move mateThreat[2];
+34 -29
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -22,6 +23,7 @@
//// ////
#include <cassert> #include <cassert>
#include <cstring>
#include "history.h" #include "history.h"
@@ -30,14 +32,13 @@
//// Functions //// Functions
//// ////
/// Constructor /// Constructor
History::History() { History::History() { clear(); }
this->clear();
}
/// History::clear() clears the history tables. /// History::clear() clears the history tables
void History::clear() { void History::clear() {
memset(history, 0, 2 * 8 * 64 * sizeof(int)); memset(history, 0, 2 * 8 * 64 * sizeof(int));
@@ -48,21 +49,22 @@ void History::clear() {
/// History::success() registers a move as being successful. This is done /// History::success() registers a move as being successful. This is done
/// whenever a non-capturing move causes a beta cutoff in the main search. /// whenever a non-capturing move causes a beta cutoff in the main search.
/// The three parameters are the moving piece, the move itself, and the /// The three parameters are the moving piece, the destination square, and
/// search depth. /// the search depth.
void History::success(Piece p, Square to, Depth d) {
void History::success(Piece p, Move m, Depth d) {
assert(piece_is_ok(p)); assert(piece_is_ok(p));
assert(move_is_ok(m)); assert(square_is_ok(to));
history[p][move_to(m)] += int(d) * int(d); history[p][to] += int(d) * int(d);
successCount[p][move_to(m)]++; successCount[p][to]++;
// Prevent history overflow: // Prevent history overflow
if(history[p][move_to(m)] >= HistoryMax) if (history[p][to] >= HistoryMax)
for (int i = 0; i < 16; i++) for (int i = 0; i < 16; i++)
for (int j = 0; j < 64; j++) for (int j = 0; j < 64; j++)
history[i][j] /= 2; history[i][j] /= 4;
} }
@@ -70,31 +72,34 @@ void History::success(Piece p, Move m, Depth d) {
/// called for each non-capturing move which failed to produce a beta cutoff /// called for each non-capturing move which failed to produce a beta cutoff
/// at a node where a beta cutoff was finally found. /// at a node where a beta cutoff was finally found.
void History::failure(Piece p, Move m) { void History::failure(Piece p, Square to) {
assert(piece_is_ok(p));
assert(move_is_ok(m));
failureCount[p][move_to(m)]++; assert(piece_is_ok(p));
assert(square_is_ok(to));
failureCount[p][to]++;
} }
/// History::move_ordering_score() returns an integer value used to order the /// History::move_ordering_score() returns an integer value used to order the
/// non-capturing moves in the MovePicker class. /// non-capturing moves in the MovePicker class.
int History::move_ordering_score(Piece p, Move m) const { int History::move_ordering_score(Piece p, Square to) const {
assert(piece_is_ok(p));
assert(move_is_ok(m));
return history[p][move_to(m)]; assert(piece_is_ok(p));
assert(square_is_ok(to));
return history[p][to];
} }
/// History::ok_to_prune() decides whether a move has been sufficiently /// History::ok_to_prune() decides whether a move has been sufficiently
/// unsuccessful that it makes sense to prune it entirely. /// unsuccessful that it makes sense to prune it entirely.
bool History::ok_to_prune(Piece p, Move m, Depth d) const { bool History::ok_to_prune(Piece p, Square to, Depth d) const {
assert(piece_is_ok(p));
assert(move_is_ok(m));
return (int(d) * successCount[p][move_to(m)] < failureCount[p][move_to(m)]); assert(piece_is_ok(p));
assert(square_is_ok(to));
return (int(d) * successCount[p][to] < failureCount[p][to]);
} }
+16 -16
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -33,19 +34,22 @@
//// Types //// Types
//// ////
/// The History class stores statistics about how often different moves have /// The History class stores statistics about how often different moves
/// been successful or unsuccessful during the current search. These /// have been successful or unsuccessful during the current search. These
/// statistics are used for reduction and move ordering decisions. /// statistics are used for reduction and move ordering decisions. History
/// entries are stored according only to moving piece and destination square,
/// in particular two moves with different origin but same destination and
/// same piece will be considered identical.
class History { class History {
public: public:
History(); History();
void clear(); void clear();
void success(Piece p, Move m, Depth d); void success(Piece p, Square to, Depth d);
void failure(Piece p, Move m); void failure(Piece p, Square to);
int move_ordering_score(Piece p, Move m) const; int move_ordering_score(Piece p, Square to) const;
bool ok_to_prune(Piece p, Move m, Depth d) const; bool ok_to_prune(Piece p, Square to, Depth d) const;
private: private:
int history[16][64]; // [piece][square] int history[16][64]; // [piece][square]
@@ -65,12 +69,8 @@ private:
/// the effect that parts of the search tree which have been searched /// the effect that parts of the search tree which have been searched
/// recently have a bigger importance for move ordering than the moves which /// recently have a bigger importance for move ordering than the moves which
/// have been searched a long time ago. /// have been searched a long time ago.
///
/// Note that HistoryMax should probably be changed whenever the constant
/// OnePly in depth.h is changed. This is somewhat annoying. Perhaps it
/// would be better to scale down the history table at regular intervals?
const int HistoryMax = 50000; const int HistoryMax = 25000 * OnePly;
#endif // !defined(HISTORY_H_INCLUDED) #endif // !defined(HISTORY_H_INCLUDED)
+7 -5
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -85,8 +86,9 @@ typedef pthread_mutex_t Lock;
#else #else
#define WIN32_LEAN_AND_MEAN
#include <windows.h> #include <windows.h>
#undef WIN32_LEAN_AND_MEAN
typedef CRITICAL_SECTION Lock; typedef CRITICAL_SECTION Lock;
# define lock_init(x, y) InitializeCriticalSection(x) # define lock_init(x, y) InitializeCriticalSection(x)
+43 -49
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -16,28 +17,27 @@
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
// To profile with callgrind uncomment following line
//#define USE_CALLGRIND
//// ////
//// Includes //// Includes
//// ////
#include <cstdlib>
#include <iostream> #include <iostream>
#include <string>
#include "benchmark.h" #include "benchmark.h"
#include "bitboard.h" #include "bitcount.h"
#include "direction.h"
#include "endgame.h"
#include "evaluate.h"
#include "material.h"
#include "mersenne.h"
#include "misc.h" #include "misc.h"
#include "movepick.h"
#include "position.h"
#include "search.h"
#include "thread.h"
#include "uci.h" #include "uci.h"
#include "ucioption.h"
#ifdef USE_CALLGRIND
#include <valgrind/callgrind.h>
#endif
using namespace std;
//// ////
@@ -47,49 +47,43 @@
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
// Disable IO buffering // Disable IO buffering
setbuf(stdin, NULL); cout.rdbuf()->pubsetbuf(NULL, 0);
setbuf(stdout, NULL); cin.rdbuf()->pubsetbuf(NULL, 0);
std::cout.rdbuf()->pubsetbuf(NULL, 0);
std::cin.rdbuf()->pubsetbuf(NULL, 0);
// Initialization // Initialization through global resources manager
Application::initialize();
init_mersenne(); #ifdef USE_CALLGRIND
init_direction_table(); CALLGRIND_START_INSTRUMENTATION;
init_bitboards(); #endif
init_uci_options();
Position::init_zobrist();
Position::init_piece_square_tables();
MaterialInfo::init();
MovePicker::init_phase_table();
init_eval(1);
init_bitbases();
init_threads();
// Make random number generation less deterministic, for book moves // Process command line arguments if any
int i = abs(get_system_time() % 10000); if (argc > 1)
for(int j = 0; j < i; j++) {
genrand_int32(); if (string(argv[1]) != "bench" || argc < 4 || argc > 8)
cout << "Usage: stockfish bench <hash size> <threads> "
// Process command line arguments << "[time = 60s] [fen positions file = default] "
if(argc >= 2) { << "[time, depth or node limited = time] "
if(std::string(argv[1]) == "bench") { << "[timing file name = none]" << endl;
if(argc != 4) { else
std::cout << "Usage: glaurung bench <hash> <threads>" << std::endl; {
exit(0); 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);
} }
benchmark(std::string(argv[2]), std::string(argv[3]));
return 0; return 0;
} }
}
// Print copyright notice // Print copyright notice
std::cout << engine_name() << ". " cout << engine_name()
<< "Copyright (C) 2004-2008 Tord Romstad." << ". By Tord Romstad, Marco Costalba, Joona Kiiski." << endl;
<< std::endl;
if (CpuHasPOPCNT)
cout << "Good! CPU has hardware POPCNT. We will use it." << endl;
// Enter UCI mode // Enter UCI mode
uci_main_loop(); uci_main_loop();
return 0; return 0;
} }
+288 -289
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -22,9 +23,13 @@
//// ////
#include <cassert> #include <cassert>
#include <sstream>
#include <map>
#include "material.h" #include "material.h"
using namespace std;
//// ////
//// Local definitions //// Local definitions
@@ -32,150 +37,98 @@
namespace { namespace {
const Value BishopPairMidgameBonus = Value(100); // Polynomial material balance parameters
const Value BishopPairEndgameBonus = Value(100); const Value RedundantQueenPenalty = Value(320);
const Value RedundantRookPenalty = Value(554);
const int LinearCoefficients[6] = { 1617, -162, -1172, -190, 105, 26 };
Key KPKMaterialKey, KKPMaterialKey; const int QuadraticCoefficientsSameColor[][6] = {
Key KBNKMaterialKey, KKBNMaterialKey; { 7, 7, 7, 7, 7, 7 }, { 39, 2, 7, 7, 7, 7 }, { 35, 271, -4, 7, 7, 7 },
Key KRKPMaterialKey, KPKRMaterialKey; { 7, 25, 4, 7, 7, 7 }, { -27, -2, 46, 100, 56, 7 }, { 58, 29, 83, 148, -3, -25 } };
Key KRKBMaterialKey, KBKRMaterialKey;
Key KRKNMaterialKey, KNKRMaterialKey;
Key KQKRMaterialKey, KRKQMaterialKey;
Key KRPKRMaterialKey, KRKRPMaterialKey;
Key KRPPKRPMaterialKey, KRPKRPPMaterialKey;
Key KNNKMaterialKey, KKNNMaterialKey;
Key KBPKBMaterialKey, KBKBPMaterialKey;
Key KBPKNMaterialKey, KNKBPMaterialKey;
Key KNPKMaterialKey, KKNPMaterialKey;
Key KPKPMaterialKey;
const int QuadraticCoefficientsOppositeColor[][6] = {
{ 41, 41, 41, 41, 41, 41 }, { 37, 41, 41, 41, 41, 41 }, { 10, 62, 41, 41, 41, 41 },
{ 57, 64, 39, 41, 41, 41 }, { 50, 40, 23, -22, 41, 41 }, { 106, 101, 3, 151, 171, 41 } };
// Named endgame evaluation and scaling functions, these
// are accessed direcly and not through the function maps.
EvaluationFunction<KmmKm> EvaluateKmmKm(WHITE);
EvaluationFunction<KXK> EvaluateKXK(WHITE), EvaluateKKX(BLACK);
ScalingFunction<KBPsK> ScaleKBPsK(WHITE), ScaleKKBPs(BLACK);
ScalingFunction<KQKRPs> ScaleKQKRPs(WHITE), ScaleKRPsKQ(BLACK);
ScalingFunction<KPsK> ScaleKPsK(WHITE), ScaleKKPs(BLACK);
ScalingFunction<KPKP> ScaleKPKPw(WHITE), ScaleKPKPb(BLACK);
typedef EndgameEvaluationFunctionBase EF;
typedef EndgameScalingFunctionBase SF;
}
////
//// Classes
////
/// EndgameFunctions class stores endgame evaluation and scaling functions
/// in two std::map. Because STL library is not guaranteed to be thread
/// safe even for read access, the maps, although with identical content,
/// are replicated for each thread. This is faster then using locks.
class EndgameFunctions {
public:
EndgameFunctions();
~EndgameFunctions();
template<class T> T* get(Key key) const;
private:
template<class T> void add(const string& keyCode);
static Key buildKey(const string& keyCode);
static const string swapColors(const string& keyCode);
// Here we store two maps, for evaluate and scaling functions
pair<map<Key, EF*>, map<Key, SF*> > maps;
// Maps accessing functions returning const and non-const references
template<typename T> const map<Key, T*>& get() const { return maps.first; }
template<typename T> map<Key, T*>& get() { return maps.first; }
}; };
// Explicit specializations of a member function shall be declared in
// the namespace of which the class template is a member.
template<> const map<Key, SF*>&
EndgameFunctions::get<SF>() const { return maps.second; }
template<> map<Key, SF*>&
EndgameFunctions::get<SF>() { return maps.second; }
//// ////
//// Functions //// Functions
//// ////
/// MaterialInfo::init() is called during program initialization. It /// MaterialInfoTable c'tor and d'tor, called once by each thread
/// precomputes material hash keys for a few basic endgames, in order
/// to make it easy to recognize such endgames when they occur.
void MaterialInfo::init() { MaterialInfoTable::MaterialInfoTable(unsigned int numOfEntries) {
KPKMaterialKey = Position::zobMaterial[WHITE][PAWN][1];
KKPMaterialKey = Position::zobMaterial[BLACK][PAWN][1];
KBNKMaterialKey =
Position::zobMaterial[WHITE][BISHOP][1] ^
Position::zobMaterial[WHITE][KNIGHT][1];
KKBNMaterialKey =
Position::zobMaterial[BLACK][BISHOP][1] ^
Position::zobMaterial[BLACK][KNIGHT][1];
KRKPMaterialKey =
Position::zobMaterial[WHITE][ROOK][1] ^
Position::zobMaterial[BLACK][PAWN][1];
KPKRMaterialKey =
Position::zobMaterial[WHITE][PAWN][1] ^
Position::zobMaterial[BLACK][ROOK][1];
KRKBMaterialKey =
Position::zobMaterial[WHITE][ROOK][1] ^
Position::zobMaterial[BLACK][BISHOP][1];
KBKRMaterialKey =
Position::zobMaterial[WHITE][BISHOP][1] ^
Position::zobMaterial[BLACK][ROOK][1];
KRKNMaterialKey =
Position::zobMaterial[WHITE][ROOK][1] ^
Position::zobMaterial[BLACK][KNIGHT][1];
KNKRMaterialKey =
Position::zobMaterial[WHITE][KNIGHT][1] ^
Position::zobMaterial[BLACK][ROOK][1];
KQKRMaterialKey =
Position::zobMaterial[WHITE][QUEEN][1] ^
Position::zobMaterial[BLACK][ROOK][1];
KRKQMaterialKey =
Position::zobMaterial[WHITE][ROOK][1] ^
Position::zobMaterial[BLACK][QUEEN][1];
KRPKRMaterialKey =
Position::zobMaterial[WHITE][ROOK][1] ^
Position::zobMaterial[WHITE][PAWN][1] ^
Position::zobMaterial[BLACK][ROOK][1];
KRKRPMaterialKey =
Position::zobMaterial[WHITE][ROOK][1] ^
Position::zobMaterial[BLACK][ROOK][1] ^
Position::zobMaterial[BLACK][PAWN][1];
KRPPKRPMaterialKey =
Position::zobMaterial[WHITE][ROOK][1] ^
Position::zobMaterial[WHITE][PAWN][1] ^
Position::zobMaterial[WHITE][PAWN][2] ^
Position::zobMaterial[BLACK][ROOK][1] ^
Position::zobMaterial[BLACK][PAWN][1];
KRPKRPPMaterialKey =
Position::zobMaterial[WHITE][ROOK][1] ^
Position::zobMaterial[WHITE][PAWN][1] ^
Position::zobMaterial[BLACK][ROOK][1] ^
Position::zobMaterial[BLACK][PAWN][1] ^
Position::zobMaterial[BLACK][PAWN][2];
KNNKMaterialKey =
Position::zobMaterial[WHITE][KNIGHT][1] ^
Position::zobMaterial[WHITE][KNIGHT][2];
KKNNMaterialKey =
Position::zobMaterial[BLACK][KNIGHT][1] ^
Position::zobMaterial[BLACK][KNIGHT][2];
KBPKBMaterialKey =
Position::zobMaterial[WHITE][BISHOP][1] ^
Position::zobMaterial[WHITE][PAWN][1] ^
Position::zobMaterial[BLACK][BISHOP][1];
KBKBPMaterialKey =
Position::zobMaterial[WHITE][BISHOP][1] ^
Position::zobMaterial[BLACK][BISHOP][1] ^
Position::zobMaterial[BLACK][PAWN][1];
KBPKNMaterialKey =
Position::zobMaterial[WHITE][BISHOP][1] ^
Position::zobMaterial[WHITE][PAWN][1] ^
Position::zobMaterial[BLACK][KNIGHT][1];
KNKBPMaterialKey =
Position::zobMaterial[WHITE][KNIGHT][1] ^
Position::zobMaterial[BLACK][BISHOP][1] ^
Position::zobMaterial[BLACK][PAWN][1];
KNPKMaterialKey =
Position::zobMaterial[WHITE][KNIGHT][1] ^
Position::zobMaterial[WHITE][PAWN][1];
KKNPMaterialKey =
Position::zobMaterial[BLACK][KNIGHT][1] ^
Position::zobMaterial[BLACK][PAWN][1];
KPKPMaterialKey =
Position::zobMaterial[WHITE][PAWN][1] ^
Position::zobMaterial[BLACK][PAWN][1];
}
/// Constructor for the MaterialInfoTable class.
MaterialInfoTable::MaterialInfoTable(unsigned numOfEntries) {
size = numOfEntries; size = numOfEntries;
entries = new MaterialInfo[size]; entries = new MaterialInfo[size];
if(entries == NULL) { funcs = new EndgameFunctions();
std::cerr << "Failed to allocate " << (numOfEntries * sizeof(MaterialInfo))
<< " bytes for material hash table." << std::endl;
exit(EXIT_FAILURE);
}
this->clear();
}
if (!entries || !funcs)
/// Destructor for the MaterialInfoTable class. {
cerr << "Failed to allocate " << numOfEntries * sizeof(MaterialInfo)
<< " bytes for material hash table." << endl;
Application::exit_with_failure();
}
}
MaterialInfoTable::~MaterialInfoTable() { MaterialInfoTable::~MaterialInfoTable() {
delete funcs;
delete [] entries; delete [] entries;
} }
/// MaterialInfoTable::clear() clears a material hash table by setting
/// all entries to 0.
void MaterialInfoTable::clear() {
memset(entries, 0, size * sizeof(MaterialInfo));
}
/// MaterialInfoTable::get_material_info() takes a position object as input, /// MaterialInfoTable::get_material_info() takes a position object as input,
/// computes or looks up a MaterialInfo object, and returns a pointer to it. /// 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 /// If the material configuration is not already present in the table, it
@@ -183,89 +136,57 @@ void MaterialInfoTable::clear() {
/// same material configuration occurs again. /// same material configuration occurs again.
MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) { MaterialInfo* MaterialInfoTable::get_material_info(const Position& pos) {
Key key = pos.get_material_key(); Key key = pos.get_material_key();
int index = key & (size - 1); int index = key & (size - 1);
MaterialInfo* mi = entries + index; MaterialInfo* mi = entries + index;
// If mi->key matches the position's material hash key, it means that we // If mi->key matches the position's material hash key, it means that we
// have analysed this material configuration before, and we can simply // have analysed this material configuration before, and we can simply
// return the information we found the last time instead of recomputing it: // return the information we found the last time instead of recomputing it.
if (mi->key == key) if (mi->key == key)
return mi; return mi;
// Clear the MaterialInfo object, and set its key: // Clear the MaterialInfo object, and set its key
mi->clear(); mi->clear();
mi->key = key; mi->key = key;
// A special case before looking for a specialized evaluation function:
// KNN vs K is a draw:
if(key == KNNKMaterialKey || key == KKNNMaterialKey) {
mi->factor[WHITE] = mi->factor[BLACK] = 0;
return mi;
}
// Let's look if we have a specialized evaluation function for this // Let's look if we have a specialized evaluation function for this
// particular material configuration: // particular material configuration. First we look for a fixed
if(key == KPKMaterialKey) { // configuration one, then a generic one if previous search failed.
mi->evaluationFunction = &EvaluateKPK; if ((mi->evaluationFunction = funcs->get<EF>(key)) != NULL)
return mi; return mi;
}
else if(key == KKPMaterialKey) { else if ( pos.non_pawn_material(BLACK) == Value(0)
mi->evaluationFunction = &EvaluateKKP; && pos.piece_count(BLACK, PAWN) == 0
return mi; && pos.non_pawn_material(WHITE) >= RookValueMidgame)
} {
else if(key == KBNKMaterialKey) {
mi->evaluationFunction = &EvaluateKBNK;
return mi;
}
else if(key == KKBNMaterialKey) {
mi->evaluationFunction = &EvaluateKKBN;
return mi;
}
else if(key == KRKPMaterialKey) {
mi->evaluationFunction = &EvaluateKRKP;
return mi;
}
else if(key == KPKRMaterialKey) {
mi->evaluationFunction = &EvaluateKPKR;
return mi;
}
else if(key == KRKBMaterialKey) {
mi->evaluationFunction = &EvaluateKRKB;
return mi;
}
else if(key == KBKRMaterialKey) {
mi->evaluationFunction = &EvaluateKBKR;
return mi;
}
else if(key == KRKNMaterialKey) {
mi->evaluationFunction = &EvaluateKRKN;
return mi;
}
else if(key == KNKRMaterialKey) {
mi->evaluationFunction = &EvaluateKNKR;
return mi;
}
else if(key == KQKRMaterialKey) {
mi->evaluationFunction = &EvaluateKQKR;
return mi;
}
else if(key == KRKQMaterialKey) {
mi->evaluationFunction = &EvaluateKRKQ;
return mi;
}
else if(pos.non_pawn_material(BLACK) == Value(0) &&
pos.pawn_count(BLACK) == 0 &&
pos.non_pawn_material(WHITE) >= RookValueEndgame) {
mi->evaluationFunction = &EvaluateKXK; mi->evaluationFunction = &EvaluateKXK;
return mi; return mi;
} }
else if(pos.non_pawn_material(WHITE) == Value(0) && else if ( pos.non_pawn_material(WHITE) == Value(0)
pos.pawn_count(WHITE) == 0 && && pos.piece_count(WHITE, PAWN) == 0
pos.non_pawn_material(BLACK) >= RookValueEndgame) { && pos.non_pawn_material(BLACK) >= RookValueMidgame)
{
mi->evaluationFunction = &EvaluateKKX; mi->evaluationFunction = &EvaluateKKX;
return mi; return mi;
} }
else if ( pos.pieces(PAWN) == EmptyBoardBB
&& pos.pieces(ROOK) == EmptyBoardBB
&& pos.pieces(QUEEN) == EmptyBoardBB)
{
// Minor piece endgame with at least one minor piece per side and
// no pawns. Note that the case KmmK is already handled by KXK.
assert((pos.pieces(KNIGHT, WHITE) | pos.pieces(BISHOP, WHITE)));
assert((pos.pieces(KNIGHT, BLACK) | pos.pieces(BISHOP, BLACK)));
if ( pos.piece_count(WHITE, BISHOP) + pos.piece_count(WHITE, KNIGHT) <= 2
&& pos.piece_count(BLACK, BISHOP) + pos.piece_count(BLACK, KNIGHT) <= 2)
{
mi->evaluationFunction = &EvaluateKmmKm;
return mi;
}
}
// OK, we didn't find any special evaluation function for the current // OK, we didn't find any special evaluation function for the current
// material configuration. Is there a suitable scaling function? // material configuration. Is there a suitable scaling function?
@@ -274,133 +195,211 @@ MaterialInfo *MaterialInfoTable::get_material_info(const Position &pos) {
// if we decide to add more special cases. We face problems when there // if we decide to add more special cases. We face problems when there
// are several conflicting applicable scaling functions and we need to // are several conflicting applicable scaling functions and we need to
// decide which one to use. // decide which one to use.
SF* sf;
if(key == KRPKRMaterialKey) { if ((sf = funcs->get<SF>(key)) != NULL)
mi->scalingFunction[WHITE] = &ScaleKRPKR; {
return mi; mi->scalingFunction[sf->color()] = sf;
}
if(key == KRKRPMaterialKey) {
mi->scalingFunction[BLACK] = &ScaleKRKRP;
return mi;
}
if(key == KRPPKRPMaterialKey) {
mi->scalingFunction[WHITE] = &ScaleKRPPKRP;
return mi;
}
else if(key == KRPKRPPMaterialKey) {
mi->scalingFunction[BLACK] = &ScaleKRPKRPP;
return mi;
}
if(key == KBPKBMaterialKey) {
mi->scalingFunction[WHITE] = &ScaleKBPKB;
return mi;
}
if(key == KBKBPMaterialKey) {
mi->scalingFunction[BLACK] = &ScaleKBKBP;
return mi;
}
if(key == KBPKNMaterialKey) {
mi->scalingFunction[WHITE] = &ScaleKBPKN;
return mi;
}
if(key == KNKBPMaterialKey) {
mi->scalingFunction[BLACK] = &ScaleKNKBP;
return mi;
}
if(key == KNPKMaterialKey) {
mi->scalingFunction[WHITE] = &ScaleKNPK;
return mi;
}
if(key == KKNPMaterialKey) {
mi->scalingFunction[BLACK] = &ScaleKKNP;
return mi; return mi;
} }
if(pos.non_pawn_material(WHITE) == BishopValueMidgame && // Generic scaling functions that refer to more then one material
pos.bishop_count(WHITE) == 1 && pos.pawn_count(WHITE) >= 1) // distribution. Should be probed after the specialized ones.
mi->scalingFunction[WHITE] = &ScaleKBPK; // Note that these ones don't return after setting the function.
if(pos.non_pawn_material(BLACK) == BishopValueMidgame && if ( pos.non_pawn_material(WHITE) == BishopValueMidgame
pos.bishop_count(BLACK) == 1 && pos.pawn_count(BLACK) >= 1) && pos.piece_count(WHITE, BISHOP) == 1
mi->scalingFunction[BLACK] = &ScaleKKBP; && pos.piece_count(WHITE, PAWN) >= 1)
mi->scalingFunction[WHITE] = &ScaleKBPsK;
if(pos.pawn_count(WHITE) == 0 && if ( pos.non_pawn_material(BLACK) == BishopValueMidgame
pos.non_pawn_material(WHITE) == QueenValueMidgame && && pos.piece_count(BLACK, BISHOP) == 1
pos.queen_count(WHITE) == 1 && && pos.piece_count(BLACK, PAWN) >= 1)
pos.rook_count(BLACK) == 1 && pos.pawn_count(BLACK) >= 1) mi->scalingFunction[BLACK] = &ScaleKKBPs;
mi->scalingFunction[WHITE] = &ScaleKQKRP;
else if(pos.pawn_count(BLACK) == 0 &&
pos.non_pawn_material(BLACK) == QueenValueMidgame &&
pos.queen_count(BLACK) == 1 &&
pos.rook_count(WHITE) == 1 && pos.pawn_count(WHITE) >= 1)
mi->scalingFunction[BLACK] = &ScaleKRPKQ;
if(pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) == Value(0)) { if ( pos.piece_count(WHITE, PAWN) == 0
if(pos.pawn_count(BLACK) == 0) { && pos.non_pawn_material(WHITE) == QueenValueMidgame
assert(pos.pawn_count(WHITE) >= 2); && pos.piece_count(WHITE, QUEEN) == 1
&& pos.piece_count(BLACK, ROOK) == 1
&& pos.piece_count(BLACK, PAWN) >= 1)
mi->scalingFunction[WHITE] = &ScaleKQKRPs;
else if ( pos.piece_count(BLACK, PAWN) == 0
&& pos.non_pawn_material(BLACK) == QueenValueMidgame
&& pos.piece_count(BLACK, QUEEN) == 1
&& pos.piece_count(WHITE, ROOK) == 1
&& pos.piece_count(WHITE, PAWN) >= 1)
mi->scalingFunction[BLACK] = &ScaleKRPsKQ;
if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) == Value(0))
{
if (pos.piece_count(BLACK, PAWN) == 0)
{
assert(pos.piece_count(WHITE, PAWN) >= 2);
mi->scalingFunction[WHITE] = &ScaleKPsK; mi->scalingFunction[WHITE] = &ScaleKPsK;
} }
else if(pos.pawn_count(WHITE) == 0) { else if (pos.piece_count(WHITE, PAWN) == 0)
assert(pos.pawn_count(BLACK) >= 2); {
assert(pos.piece_count(BLACK, PAWN) >= 2);
mi->scalingFunction[BLACK] = &ScaleKKPs; mi->scalingFunction[BLACK] = &ScaleKKPs;
} }
else if(pos.pawn_count(WHITE) == 1 && pos.pawn_count(BLACK) == 1) { else if (pos.piece_count(WHITE, PAWN) == 1 && pos.piece_count(BLACK, PAWN) == 1)
{
// This is a special case because we set scaling functions
// for both colors instead of only one.
mi->scalingFunction[WHITE] = &ScaleKPKPw; mi->scalingFunction[WHITE] = &ScaleKPKPw;
mi->scalingFunction[BLACK] = &ScaleKPKPb; mi->scalingFunction[BLACK] = &ScaleKPKPb;
} }
} }
// Evaluate the material balance. // Compute the space weight
if (pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK) >=
2*QueenValueMidgame + 4*RookValueMidgame + 2*KnightValueMidgame)
{
int minorPieceCount = pos.piece_count(WHITE, KNIGHT)
+ pos.piece_count(BLACK, KNIGHT)
+ pos.piece_count(WHITE, BISHOP)
+ pos.piece_count(BLACK, BISHOP);
Color c; 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; int sign;
Value egValue = Value(0), mgValue = Value(0); int matValue = 0;
for(c = WHITE, sign = 1; c <= BLACK; c++, sign = -sign) { for (c = WHITE, sign = 1; c <= BLACK; c++, sign = -sign)
{
// No pawns makes it difficult to win, even with a material advantage: // No pawns makes it difficult to win, even with a material advantage
if(pos.pawn_count(c) == 0 && if ( pos.piece_count(c, PAWN) == 0
pos.non_pawn_material(c) - pos.non_pawn_material(opposite_color(c)) && pos.non_pawn_material(c) - pos.non_pawn_material(opposite_color(c)) <= BishopValueMidgame)
<= BishopValueMidgame) { {
if(pos.non_pawn_material(c) == pos.non_pawn_material(opposite_color(c))) if ( pos.non_pawn_material(c) == pos.non_pawn_material(opposite_color(c))
|| pos.non_pawn_material(c) < RookValueMidgame)
mi->factor[c] = 0; mi->factor[c] = 0;
else if(pos.non_pawn_material(c) < RookValueMidgame) else
mi->factor[c] = 0; {
else { switch (pos.piece_count(c, BISHOP)) {
switch(pos.bishop_count(c)) {
case 2: case 2:
mi->factor[c] = 32; break; mi->factor[c] = 32;
break;
case 1: case 1:
mi->factor[c] = 12; break; mi->factor[c] = 12;
break;
case 0: case 0:
mi->factor[c] = 6; break; mi->factor[c] = 6;
break;
} }
} }
} }
// Bishop pair: // Redundancy of major pieces, formula based on Kaufman's paper
if(pos.bishop_count(c) >= 2) { // "The Evaluation of Material Imbalances in Chess"
mgValue += sign * BishopPairMidgameBonus;
egValue += sign * BishopPairEndgameBonus;
}
// Knights are stronger when there are many pawns on the board. The
// formula is taken from Larry Kaufman's paper "The Evaluation of Material
// Imbalances in Chess":
// http://mywebpages.comcast.net/danheisman/Articles/evaluation_of_material_imbalance.htm // http://mywebpages.comcast.net/danheisman/Articles/evaluation_of_material_imbalance.htm
mgValue += sign * Value(pos.knight_count(c)*(pos.pawn_count(c)-5)*16); if (pieceCount[c][ROOK] >= 1)
egValue += sign * Value(pos.knight_count(c)*(pos.pawn_count(c)-5)*16); matValue -= sign * ((pieceCount[c][ROOK] - 1) * RedundantRookPenalty + pieceCount[c][QUEEN] * RedundantQueenPenalty);
// Redundancy of major pieces, again based on Kaufman's paper: them = opposite_color(c);
if(pos.rook_count(c) >= 1) {
Value v = Value((pos.rook_count(c) - 1) * 32 + pos.queen_count(c) * 16); // Second-degree polynomial material imbalance by Tord Romstad
mgValue -= sign * v; //
egValue -= sign * v; // 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 (int pt1 = NO_PIECE_TYPE; pt1 <= QUEEN; pt1++)
{
int c1 = sign * pieceCount[c][pt1];
if (!c1)
continue;
matValue += c1 * LinearCoefficients[pt1];
for (int pt2 = NO_PIECE_TYPE; pt2 <= pt1; pt2++)
{
matValue += c1 * pieceCount[c][pt2] * QuadraticCoefficientsSameColor[pt1][pt2];
matValue += c1 * pieceCount[them][pt2] * QuadraticCoefficientsOppositeColor[pt1][pt2];
} }
} }
}
mi->mgValue = int16_t(mgValue); mi->value = int16_t(matValue / 16);
mi->egValue = int16_t(egValue);
return mi; return mi;
} }
/// EndgameFunctions member definitions.
EndgameFunctions::EndgameFunctions() {
add<EvaluationFunction<KNNK> >("KNNK");
add<EvaluationFunction<KPK> >("KPK");
add<EvaluationFunction<KBNK> >("KBNK");
add<EvaluationFunction<KRKP> >("KRKP");
add<EvaluationFunction<KRKB> >("KRKB");
add<EvaluationFunction<KRKN> >("KRKN");
add<EvaluationFunction<KQKR> >("KQKR");
add<EvaluationFunction<KBBKN> >("KBBKN");
add<ScalingFunction<KNPK> >("KNPK");
add<ScalingFunction<KRPKR> >("KRPKR");
add<ScalingFunction<KBPKB> >("KBPKB");
add<ScalingFunction<KBPPKB> >("KBPPKB");
add<ScalingFunction<KBPKN> >("KBPKN");
add<ScalingFunction<KRPPKRP> >("KRPPKRP");
add<ScalingFunction<KRPPKRP> >("KRPPKRP");
}
EndgameFunctions::~EndgameFunctions() {
for (map<Key, EF*>::iterator it = maps.first.begin(); it != maps.first.end(); ++it)
delete (*it).second;
for (map<Key, SF*>::iterator it = maps.second.begin(); it != maps.second.end(); ++it)
delete (*it).second;
}
Key EndgameFunctions::buildKey(const string& keyCode) {
assert(keyCode.length() > 0 && keyCode[0] == 'K');
assert(keyCode.length() < 8);
stringstream s;
bool upcase = false;
// Build up a fen string with the given pieces, note that
// the fen string could be of an illegal position.
for (size_t i = 0; i < keyCode.length(); i++)
{
if (keyCode[i] == 'K')
upcase = !upcase;
s << char(upcase? toupper(keyCode[i]) : tolower(keyCode[i]));
}
s << 8 - keyCode.length() << "/8/8/8/8/8/8/8 w -";
return Position(s.str()).get_material_key();
}
const string EndgameFunctions::swapColors(const string& keyCode) {
// Build corresponding key for the opposite color: "KBPKN" -> "KNKBP"
size_t idx = keyCode.find("K", 1);
return keyCode.substr(idx) + keyCode.substr(0, idx);
}
template<class T>
void EndgameFunctions::add(const string& keyCode) {
typedef typename T::Base F;
get<F>().insert(pair<Key, F*>(buildKey(keyCode), new T(WHITE)));
get<F>().insert(pair<Key, F*>(buildKey(swapColors(keyCode)), new T(BLACK)));
}
template<class T>
T* EndgameFunctions::get(Key key) const {
typename map<Key, T*>::const_iterator it(get<T>().find(key));
return (it != get<T>().end() ? it->second : NULL);
}
+43 -31
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -48,42 +49,42 @@ class MaterialInfo {
friend class MaterialInfoTable; friend class MaterialInfoTable;
public: public:
Value mg_value() const; MaterialInfo() : key(0) { clear(); }
Value eg_value() const;
Value material_value() const;
ScaleFactor scale_factor(const Position& pos, Color c) const; ScaleFactor scale_factor(const Position& pos, Color c) const;
int space_weight() const;
bool specialized_eval_exists() const; bool specialized_eval_exists() const;
Value evaluate(const Position& pos) const; Value evaluate(const Position& pos) const;
static void init();
private: private:
void clear(); inline void clear();
Key key; Key key;
int16_t mgValue; int16_t value;
int16_t egValue;
uint8_t factor[2]; uint8_t factor[2];
EndgameEvaluationFunction *evaluationFunction; EndgameEvaluationFunctionBase* evaluationFunction;
ScalingFunction *scalingFunction[2]; EndgameScalingFunctionBase* scalingFunction[2];
int spaceWeight;
}; };
/// The MaterialInfoTable class represents a pawn hash table. It is basically /// The MaterialInfoTable class represents a pawn hash table. It is basically
/// just an array of MaterialInfo objects and a few methods for accessing these /// 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 /// 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. /// position in the table and returns a pointer to a MaterialInfo object.
class EndgameFunctions;
class MaterialInfoTable { class MaterialInfoTable {
public: public:
MaterialInfoTable(unsigned numOfEntries); MaterialInfoTable(unsigned numOfEntries);
~MaterialInfoTable(); ~MaterialInfoTable();
void clear();
MaterialInfo* get_material_info(const Position& pos); MaterialInfo* get_material_info(const Position& pos);
private: private:
unsigned size; unsigned size;
MaterialInfo* entries; MaterialInfo* entries;
EndgameFunctions* funcs;
}; };
@@ -91,39 +92,39 @@ private:
//// Inline functions //// Inline functions
//// ////
/// MaterialInfo::mg_value and MaterialInfo::eg_value simply returns the /// MaterialInfo::material_value simply returns the material balance
/// material balance evaluation for the middle game and the endgame. /// evaluation that is independent from game phase.
inline Value MaterialInfo::mg_value() const { inline Value MaterialInfo::material_value() const {
return Value(mgValue);
}
inline Value MaterialInfo::eg_value() const { return Value(value);
return Value(egValue);
} }
/// MaterialInfo::clear() resets a MaterialInfo object to an empty state, /// MaterialInfo::clear() resets a MaterialInfo object to an empty state,
/// with all slots at their default values. /// with all slots at their default values but the key.
inline void MaterialInfo::clear() { inline void MaterialInfo::clear() {
mgValue = egValue = 0;
value = 0;
factor[WHITE] = factor[BLACK] = uint8_t(SCALE_FACTOR_NORMAL); factor[WHITE] = factor[BLACK] = uint8_t(SCALE_FACTOR_NORMAL);
evaluationFunction = NULL; evaluationFunction = NULL;
scalingFunction[WHITE] = scalingFunction[BLACK] = NULL; scalingFunction[WHITE] = scalingFunction[BLACK] = NULL;
spaceWeight = 0;
} }
/// MaterialInfo::scale_factor takes a position and a color as input, and /// MaterialInfo::scale_factor takes a position and a color as input, and
/// returns a scale factor for the given color. We have to provide the /// returns a scale factor for the given color. We have to provide the
/// position in addition to the color, because the scale factor need not /// position in addition to the color, because the scale factor need not
/// be a constant: It can also be a function which should be applied to /// to be a constant: It can also be a function which should be applied to
/// the position. For instance, in KBP vs K endgames, a scaling function /// the position. For instance, in KBP vs K endgames, a scaling function
/// which checks for draws with rook pawns and wrong-colored bishops. /// which checks for draws with rook pawns and wrong-colored bishops.
inline ScaleFactor MaterialInfo::scale_factor(const Position &pos, Color c) inline ScaleFactor MaterialInfo::scale_factor(const Position& pos, Color c) const {
const {
if(scalingFunction[c] != NULL) { if (scalingFunction[c] != NULL)
{
ScaleFactor sf = scalingFunction[c]->apply(pos); ScaleFactor sf = scalingFunction[c]->apply(pos);
if (sf != SCALE_FACTOR_NONE) if (sf != SCALE_FACTOR_NONE)
return sf; return sf;
@@ -132,20 +133,31 @@ inline ScaleFactor MaterialInfo::scale_factor(const Position &pos, Color c)
} }
/// MaterialInfo::space_weight() simply returns the weight for the space
/// evaluation for this material configuration.
inline int MaterialInfo::space_weight() const {
return spaceWeight;
}
/// MaterialInfo::specialized_eval_exists decides whether there is a /// MaterialInfo::specialized_eval_exists decides whether there is a
/// specialized evaluation function for the current material configuration, /// specialized evaluation function for the current material configuration,
/// or if the normal evaluation function should be used. /// or if the normal evaluation function should be used.
inline bool MaterialInfo::specialized_eval_exists() const { inline bool MaterialInfo::specialized_eval_exists() const {
return evaluationFunction != NULL; return evaluationFunction != NULL;
} }
/// MaterialInfo::evaluate applies a specialized evaluation function to a /// MaterialInfo::evaluate applies a specialized evaluation function
/// given position object. It should only be called when /// to a given position object. It should only be called when
/// this->specialized_eval_exists() returns 'true'. /// specialized_eval_exists() returns 'true'.
inline Value MaterialInfo::evaluate(const Position& pos) const { inline Value MaterialInfo::evaluate(const Position& pos) const {
return evaluationFunction->apply(pos); return evaluationFunction->apply(pos);
} }
+3 -2
View File
@@ -42,6 +42,7 @@
*/ */
#include "types.h" #include "types.h"
#include "mersenne.h"
/* Period parameters */ /* Period parameters */
#define N 624 #define N 624
@@ -54,7 +55,7 @@ static unsigned long mt[N]; /* the array for the state vector */
static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */ static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */
/* initializes mt[N] with a seed */ /* initializes mt[N] with a seed */
void init_genrand(unsigned long s) static void init_genrand(unsigned long s)
{ {
mt[0]= s & 0xffffffffUL; mt[0]= s & 0xffffffffUL;
for (mti=1; mti<N; mti++) { for (mti=1; mti<N; mti++) {
@@ -73,7 +74,7 @@ void init_genrand(unsigned long s)
/* init_key is the array for initializing keys */ /* init_key is the array for initializing keys */
/* key_length is its length */ /* key_length is its length */
/* slight change for C++, 2004/2/26 */ /* slight change for C++, 2004/2/26 */
void init_by_array(unsigned long init_key[], int key_length) static void init_by_array(unsigned long init_key[], int key_length)
{ {
int i, j, k; int i, j, k;
init_genrand(19650218UL); init_genrand(19650218UL);
+5 -4
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
+137 -28
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -29,60 +30,152 @@
#else #else
#define _CRT_SECURE_NO_DEPRECATE
#include <windows.h> #include <windows.h>
# include <time.h> #include <sys/timeb.h>
# include "dos.h"
int gettimeofday(struct timeval * tp, struct timezone * tzp);
#endif #endif
#include <cassert>
#include <cstdio> #include <cstdio>
#include <iomanip> #include <iomanip>
#include <iostream>
#include <sstream> #include <sstream>
#include "bitcount.h"
#include "misc.h" #include "misc.h"
using namespace std;
/// Version number. If this is left empty, the current date (in the format
/// YYMMDD) is used as a version number.
static const string EngineVersion = "1.5";
static const string AppName = "Stockfish";
static const string AppTag = "";
////
//// Variables
////
bool Chess960;
uint64_t dbg_cnt0 = 0;
uint64_t dbg_cnt1 = 0;
bool dbg_show_mean = false;
bool dbg_show_hit_rate = false;
//// ////
//// Functions //// Functions
//// ////
/// engine_name() returns the full name of the current Glaurung version. void dbg_hit_on(bool b) {
/// This will be either "Glaurung YYMMDD" (where YYMMDD is the date when the
/// program was compiled) or "Glaurung <version number>", depending on whether 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. /// the constant EngineVersion (defined in misc.h) is empty.
const std::string engine_name() { const string engine_name() {
if(EngineVersion == "") {
static const char monthNames[12][4] = {
"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
};
const char *dateString = __DATE__;
std::stringstream s;
int month = 0, day = 0;
for(int i = 0; i < 12; i++) const string cpu64(CpuHas64BitPath ? " 64bit" : "");
if(strncmp(dateString, monthNames[i], 3) == 0)
month = i + 1;
day = atoi(dateString+4);
s << "Glaurung " << (dateString+9) << std::setfill('0') << std::setw(2) if (!EngineVersion.empty())
<< month << std::setfill('0') << std::setw(2) << day; return AppName+ " " + EngineVersion + cpu64;
string date(__DATE__); // From compiler, format is "Sep 21 2008"
string months("Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec");
size_t mon = 1 + months.find(date.substr(0, 3)) / 4;
stringstream s;
string day = (date[4] == ' ' ? date.substr(5, 1) : date.substr(4, 2));
string name = AppName + " " + AppTag + " ";
s << name << date.substr(date.length() - 2) << setfill('0')
<< setw(2) << mon << setw(2) << day << cpu64;
return s.str(); return s.str();
} }
else
return "Glaurung " + EngineVersion;
}
/// get_system_time() returns the current system time, measured in /// get_system_time() returns the current system time, measured in
/// milliseconds. /// milliseconds.
int get_system_time() { int get_system_time() {
#if defined(_MSC_VER)
struct _timeb t;
_ftime(&t);
return int(t.time*1000 + t.millitm);
#else
struct timeval t; struct timeval t;
gettimeofday(&t, NULL); gettimeofday(&t, NULL);
return t.tv_sec*1000 + t.tv_usec/1000; return t.tv_sec*1000 + t.tv_usec/1000;
#endif
} }
@@ -162,8 +255,24 @@ int Bioskey()
return 1; return 1;
return dw; return dw;
} else { } else {
// Count the number of unread input records, including keyboard,
// mouse, and window-resizing input records.
GetNumberOfConsoleInputEvents(inh, &dw); GetNumberOfConsoleInputEvents(inh, &dw);
return dw <= 1 ? 0 : 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 #endif
+35 -15
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -25,19 +26,11 @@
//// Includes //// Includes
//// ////
#include <fstream>
#include <string> #include <string>
#include "application.h"
//// #include "types.h"
//// Constants
////
/// Version number. If this is left empty, the current date (in the format
/// YYMMDD) is used as a version number.
const std::string EngineVersion = "2.1";
//// ////
//// Macros //// Macros
@@ -47,6 +40,13 @@ const std::string EngineVersion = "2.1";
#define Max(x, y) (((x) < (y))? (y) : (x)) #define Max(x, y) (((x) < (y))? (y) : (x))
////
//// Variables
////
extern bool Chess960;
//// ////
//// Prototypes //// Prototypes
//// ////
@@ -57,4 +57,24 @@ extern int cpu_count();
extern int Bioskey(); extern int Bioskey();
////
//// 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);
#endif // !defined(MISC_H_INCLUDED) #endif // !defined(MISC_H_INCLUDED)
+49 -44
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -26,7 +27,6 @@
#include "move.h" #include "move.h"
#include "piece.h" #include "piece.h"
#include "position.h" #include "position.h"
#include "ucioption.h"
//// ////
@@ -40,60 +40,65 @@
/// the input move is legal and correctly formatted. /// the input move is legal and correctly formatted.
Move move_from_string(const Position& pos, const std::string& str) { Move move_from_string(const Position& pos, const std::string& str) {
Square from, to; Square from, to;
Piece piece; Piece piece;
Color us = pos.side_to_move(); Color us = pos.side_to_move();
if(str.length() < 4) return MOVE_NONE; if (str.length() < 4)
return MOVE_NONE;
// Read the from and to squares: // Read the from and to squares
from = square_from_string(str.substr(0, 2)); from = square_from_string(str.substr(0, 2));
to = square_from_string(str.substr(2, 4)); to = square_from_string(str.substr(2, 4));
// Find the moving piece: // Find the moving piece
piece = pos.piece_on(from); piece = pos.piece_on(from);
// If the string has more than 4 characters, try to interpret the 5th // If the string has more than 4 characters, try to interpret the 5th
// character as a promotion: // character as a promotion
if(type_of_piece(piece) == PAWN && str.length() >= 5) { if (type_of_piece(piece) == PAWN && str.length() > 4)
switch(str[4]) { {
case 'n': case 'N': switch (tolower(str[4])) {
case 'n':
return make_promotion_move(from, to, KNIGHT); return make_promotion_move(from, to, KNIGHT);
case 'b': case 'B': case 'b':
return make_promotion_move(from, to, BISHOP); return make_promotion_move(from, to, BISHOP);
case 'r': case 'R': case 'r':
return make_promotion_move(from, to, ROOK); return make_promotion_move(from, to, ROOK);
case 'q': case 'Q': case 'q':
return make_promotion_move(from, to, QUEEN); return make_promotion_move(from, to, QUEEN);
} }
} }
if(piece == king_of_color(us)) { if (piece == piece_of_color_and_type(us, KING))
{
// Is this a castling move? A king move is assumed to be a castling // 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 // move if the destination square is occupied by a friendly rook, or
// if the distance between the source and destination squares is more // if the distance between the source and destination squares is more
// than 1. // than 1.
if(pos.piece_on(to) == rook_of_color(us)) if (pos.piece_on(to) == piece_of_color_and_type(us, ROOK))
return make_castle_move(from, to); return make_castle_move(from, to);
else if(square_distance(from, to) > 1) {
else if (square_distance(from, to) > 1)
{
// This is a castling move, but we have to translate it to the // This is a castling move, but we have to translate it to the
// internal "king captures rook" representation. // internal "king captures rook" representation.
SquareDelta delta = (to > from)? DELTA_E : DELTA_W; SquareDelta delta = (to > from ? DELTA_E : DELTA_W);
Square s; Square s = from + delta;
for(s = from + delta; while (relative_rank(us, s) == RANK_1 && pos.piece_on(s) != piece_of_color_and_type(us, ROOK))
pawn_rank(us, s) == RANK_1 && pos.piece_on(s) != rook_of_color(us); s += delta;
s += delta);
if(pawn_rank(us, s) == RANK_1 && pos.piece_on(s) == rook_of_color(us)) return (relative_rank(us, s) == RANK_1 ? make_castle_move(from, s) : MOVE_NONE);
return make_castle_move(from, s);
} }
} }
else if(piece == pawn_of_color(us)) { else if (piece == piece_of_color_and_type(us, PAWN))
{
// En passant move? We assume that a pawn move is an en passant move // En passant move? We assume that a pawn move is an en passant move
// without further testing if the destination square is epSquare. // without further testing if the destination square is epSquare.
if (to == pos.ep_square()) if (to == pos.ep_square())
return make_ep_move(from, to); return make_ep_move(from, to);
} }
return make_move(from, to); return make_move(from, to);
} }
@@ -104,30 +109,28 @@ Move move_from_string(const Position &pos, const std::string &str) {
/// Chess960 mode. /// Chess960 mode.
const std::string move_to_string(Move move) { const std::string move_to_string(Move move) {
std::string str; std::string str;
Square from = move_from(move);
Square to = move_to(move);
if (move == MOVE_NONE) if (move == MOVE_NONE)
str = "(none)"; str = "(none)";
else if (move == MOVE_NULL) else if (move == MOVE_NULL)
str = "0000"; str = "0000";
else { else
if(!Chess960) { {
if(move_from(move) == SQ_E1 && move_is_short_castle(move)) { if (!Chess960)
str = "e1g1"; return str; {
if (move_is_short_castle(move))
return (from == SQ_E1 ? "e1g1" : "e8g8");
if (move_is_long_castle(move))
return (from == SQ_E1 ? "e1c1" : "e8c8");
} }
else if(move_from(move) == SQ_E1 && move_is_long_castle(move)) { str = square_to_string(from) + square_to_string(to);
str = "e1c1"; return str; if (move_is_promotion(move))
} str += piece_type_to_char(move_promotion_piece(move), false);
if(move_from(move) == SQ_E8 && move_is_short_castle(move)) {
str = "e8g8"; return str;
}
else if(move_from(move) == SQ_E8 && move_is_long_castle(move)) {
str = "e8c8"; return str;
}
}
str = square_to_string(move_from(move)) + square_to_string(move_to(move));
if(move_promotion(move))
str += piece_type_to_char(move_promotion(move), false);
} }
return str; return str;
} }
@@ -136,6 +139,7 @@ const std::string move_to_string(Move move) {
/// Overload the << operator, to make it easier to print moves. /// Overload the << operator, to make it easier to print moves.
std::ostream &operator << (std::ostream& os, Move m) { std::ostream &operator << (std::ostream& os, Move m) {
return os << move_to_string(m); return os << move_to_string(m);
} }
@@ -143,5 +147,6 @@ std::ostream &operator << (std::ostream &os, Move m) {
/// move_is_ok(), for debugging. /// move_is_ok(), for debugging.
bool move_is_ok(Move m) { bool move_is_ok(Move m) {
return square_is_ok(move_from(m)) && square_is_ok(move_to(m)); return square_is_ok(move_from(m)) && square_is_ok(move_to(m));
} }
+33 -13
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -37,10 +38,22 @@
class Position; 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 { enum Move {
MOVE_NONE = 0, MOVE_NONE = 0,
MOVE_NULL = 65, MOVE_NULL = 65
MOVE_MAX = 0xFFFFFF
}; };
@@ -49,29 +62,36 @@ struct MoveStack {
int score; int score;
}; };
// Note that operator< is set up such that std::sort() will sort in descending order
inline bool operator<(const MoveStack& f, const MoveStack& s) { return s.score < f.score; }
//// ////
//// Inline functions //// Inline functions
//// ////
inline Square move_from(Move m) { inline Square move_from(Move m) {
return Square((int(m) >> 6) & 077); return Square((int(m) >> 6) & 0x3F);
} }
inline Square move_to(Move m) { inline Square move_to(Move m) {
return Square(m & 077); return Square(m & 0x3F);
} }
inline PieceType move_promotion(Move m) { inline PieceType move_promotion_piece(Move m) {
return PieceType((int(m) >> 12) & 7); return PieceType((int(m) >> 12) & 7);
} }
inline bool move_is_ep(Move m) { inline int move_is_promotion(Move m) {
return bool((int(m) >> 15) & 1); return m & (7 << 12);
} }
inline bool move_is_castle(Move m) { inline int move_is_ep(Move m) {
return bool((int(m) >> 16) & 1); return m & (1 << 15);
}
inline int move_is_castle(Move m) {
return m & (1 << 16);
} }
inline bool move_is_short_castle(Move m) { inline bool move_is_short_castle(Move m) {
+573 -1033
View File
File diff suppressed because it is too large Load Diff
+13 -11
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -31,12 +32,13 @@
//// Prototypes //// Prototypes
//// ////
extern int generate_captures(const Position &pos, MoveStack *mlist); extern MoveStack* generate_captures(const Position& pos, MoveStack* mlist);
extern int generate_noncaptures(const Position &pos, MoveStack *mlist); extern MoveStack* generate_noncaptures(const Position& pos, MoveStack* mlist);
extern int generate_checks(const Position &pos, MoveStack *mlist, Bitboard dc); extern MoveStack* generate_non_capture_checks(const Position& pos, MoveStack* mlist, Bitboard dc);
extern int generate_evasions(const Position &pos, MoveStack *mlist); extern MoveStack* generate_evasions(const Position& pos, MoveStack* mlist, Bitboard pinned);
extern int generate_legal_moves(const Position &pos, MoveStack *mlist); extern MoveStack* generate_moves(const Position& pos, MoveStack* mlist, bool pseudoLegal = false);
extern Move generate_move_if_legal(const Position &pos, Move m, extern bool move_is_legal(const Position& pos, const Move m, Bitboard pinned);
Bitboard pinned); extern bool move_is_legal(const Position& pos, const Move m);
#endif // !defined(MOVEGEN_H_INCLUDED) #endif // !defined(MOVEGEN_H_INCLUDED)
+217 -361
View File
@@ -1,13 +1,15 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful,
Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -21,6 +23,7 @@
//// Includes //// Includes
//// ////
#include <algorithm>
#include <cassert> #include <cassert>
#include "history.h" #include "history.h"
@@ -36,31 +39,23 @@
namespace { namespace {
/// Types
enum MovegenPhase { enum MovegenPhase {
PH_TT_MOVE, // Transposition table move PH_TT_MOVES, // Transposition table move and mate killer
PH_MATE_KILLER, // Mate killer from the current ply
PH_GOOD_CAPTURES, // Queen promotions and captures with SEE values >= 0 PH_GOOD_CAPTURES, // Queen promotions and captures with SEE values >= 0
PH_BAD_CAPTURES, // Queen promotions and captures with SEE valuse <= 0 PH_KILLERS, // Killer moves from the current ply
PH_KILLER_1, // Killer move 1 from the current ply (not used yet).
PH_KILLER_2, // Killer move 2 from the current ply (not used yet).
PH_NONCAPTURES, // Non-captures and underpromotions PH_NONCAPTURES, // Non-captures and underpromotions
PH_BAD_CAPTURES, // Queen promotions and captures with SEE values < 0
PH_EVASIONS, // Check evasions PH_EVASIONS, // Check evasions
PH_QCAPTURES, // Captures in quiescence search PH_QCAPTURES, // Captures in quiescence search
PH_QCHECKS, // Checks in quiescence search PH_QCHECKS, // Non-capture checks in quiescence search
PH_STOP PH_STOP
}; };
CACHE_LINE_ALIGNMENT
/// Variables const uint8_t MainSearchPhaseTable[] = { PH_TT_MOVES, PH_GOOD_CAPTURES, PH_KILLERS, PH_NONCAPTURES, PH_BAD_CAPTURES, PH_STOP};
const uint8_t EvasionsPhaseTable[] = { PH_EVASIONS, PH_STOP};
MovegenPhase PhaseTable[32]; const uint8_t QsearchWithChecksPhaseTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_QCHECKS, PH_STOP};
int MainSearchPhaseIndex; const uint8_t QsearchWithoutChecksPhaseTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_STOP};
int EvasionsPhaseIndex;
int QsearchWithChecksPhaseIndex;
int QsearchWithoutChecksPhaseIndex;
} }
@@ -76,164 +71,113 @@ namespace {
/// search captures, promotions and some checks) and about how important good /// search captures, promotions and some checks) and about how important good
/// move ordering is at the current node. /// move ordering is at the current node.
MovePicker::MovePicker(Position &p, bool pvnode, Move ttm, Move mk, MovePicker::MovePicker(const Position& p, Move ttm, Depth d,
Move k1, Move k2, Depth dpth) { const History& h, SearchStack* ss) : pos(p), H(h) {
pos = &p; int searchTT = ttm;
pvNode = pvnode; ttMoves[0].move = ttm;
ttMove = ttm; finished = false;
mateKiller = (mk == ttm)? MOVE_NONE : mk; lastBadCapture = badCaptures;
killer1 = k1;
killer2 = k2; if (ss)
depth = dpth; {
movesPicked = 0; ttMoves[1].move = (ss->mateKiller == ttm)? MOVE_NONE : ss->mateKiller;
numOfMoves = 0; searchTT |= ttMoves[1].move;
numOfBadCaptures = 0; killers[0].move = ss->killers[0];
dc = p.discovered_check_candidates(p.side_to_move()); killers[1].move = ss->killers[1];
} else
ttMoves[1].move = killers[0].move = killers[1].move = MOVE_NONE;
Color us = pos.side_to_move();
dc = p.discovered_check_candidates(us);
pinned = p.pinned_pieces(us);
if (p.is_check()) if (p.is_check())
phaseIndex = EvasionsPhaseIndex; phasePtr = EvasionsPhaseTable;
else if(depth > Depth(0)) else if (d > Depth(0))
phaseIndex = MainSearchPhaseIndex; phasePtr = MainSearchPhaseTable + !searchTT;
else if(depth == Depth(0)) else if (d == Depth(0))
phaseIndex = QsearchWithChecksPhaseIndex; phasePtr = QsearchWithChecksPhaseTable + !searchTT;
else else
phaseIndex = QsearchWithoutChecksPhaseIndex; phasePtr = QsearchWithoutChecksPhaseTable + !searchTT;
pinned = p.pinned_pieces(p.side_to_move()); phasePtr--;
go_next_phase();
finished = false;
} }
/// MovePicker::get_next_move() is the most important method of the MovePicker /// MovePicker::go_next_phase() generates, scores and sorts the next bunch
/// class. It returns a new legal move every time it is called, until there /// of moves when there are no more moves to try for the current phase.
/// are no more moves left of the types we are interested in.
Move MovePicker::get_next_move() { void MovePicker::go_next_phase() {
Move move;
while(true) { curMove = moves;
// If we already have a list of generated moves, pick the best move from phase = *(++phasePtr);
// the list, and return it: switch (phase) {
move = this->pick_move_from_list();
if(move != MOVE_NONE) {
assert(move_is_ok(move));
return move;
}
// Next phase: case PH_TT_MOVES:
phaseIndex++; curMove = ttMoves;
switch(PhaseTable[phaseIndex]) { lastMove = curMove + 2;
return;
case PH_TT_MOVE:
if(ttMove != MOVE_NONE) {
assert(move_is_ok(ttMove));
Move m = generate_move_if_legal(*pos, ttMove, pinned);
if(m != MOVE_NONE) {
assert(m == ttMove);
return m;
}
}
break;
case PH_MATE_KILLER:
if(mateKiller != MOVE_NONE) {
assert(move_is_ok(mateKiller));
Move m = generate_move_if_legal(*pos, mateKiller, pinned);
if(m != MOVE_NONE) {
assert(m == mateKiller);
return m;
}
}
break;
case PH_GOOD_CAPTURES: case PH_GOOD_CAPTURES:
// pinned = pos->pinned_pieces(pos->side_to_move()); lastMove = generate_captures(pos, moves);
numOfMoves = generate_captures(*pos, moves); score_captures();
this->score_captures(); std::sort(moves, lastMove);
movesPicked = 0; return;
break;
case PH_BAD_CAPTURES: case PH_KILLERS:
badCapturesPicked = 0; curMove = killers;
break; lastMove = curMove + 2;
return;
case PH_NONCAPTURES: case PH_NONCAPTURES:
numOfMoves = generate_noncaptures(*pos, moves); lastMove = generate_noncaptures(pos, moves);
this->score_noncaptures(); score_noncaptures();
movesPicked = 0; std::sort(moves, lastMove);
break; return;
case PH_BAD_CAPTURES:
// Bad captures SEE value is already calculated so just sort them
// to get SEE move ordering.
curMove = badCaptures;
lastMove = lastBadCapture;
std::sort(badCaptures, lastMove);
return;
case PH_EVASIONS: case PH_EVASIONS:
assert(pos->is_check()); assert(pos.is_check());
// pinned = pos->pinned_pieces(pos->side_to_move()); lastMove = generate_evasions(pos, moves, pinned);
numOfMoves = generate_evasions(*pos, moves); score_evasions();
this->score_evasions(); std::sort(moves, lastMove);
movesPicked = 0; return;
break;
case PH_QCAPTURES: case PH_QCAPTURES:
// pinned = pos->pinned_pieces(pos->side_to_move()); lastMove = generate_captures(pos, moves);
numOfMoves = generate_captures(*pos, moves); score_captures();
this->score_qcaptures(); std::sort(moves, lastMove);
movesPicked = 0; return;
break;
case PH_QCHECKS: case PH_QCHECKS:
numOfMoves = generate_checks(*pos, moves, dc); // Perhaps we should order moves move here? FIXME
movesPicked = 0; lastMove = generate_non_capture_checks(pos, moves, dc);
break; return;
case PH_STOP: case PH_STOP:
return MOVE_NONE; lastMove = curMove + 1; // hack to be friendly for get_next_move()
return;
default: default:
assert(false); assert(false);
return MOVE_NONE; return;
} }
} }
assert(false);
return MOVE_NONE; /// MovePicker::score_captures(), MovePicker::score_noncaptures() and
} /// MovePicker::score_evasions() assign a numerical move ordering score
/// to each move in a move list. The moves with highest scores will be
/// picked first by get_next_move().
/// A variant of get_next_move() which takes a lock as a parameter, used to
/// prevent multiple threads from picking the same move at a split point.
Move MovePicker::get_next_move(Lock &lock) {
Move m;
lock_grab(&lock);
if(finished) {
lock_release(&lock);
return MOVE_NONE;
}
m = this->get_next_move();
if(m == MOVE_NONE)
finished = true;
lock_release(&lock);
return m;
}
/// MovePicker::number_of_moves() simply returns the numOfMoves member
/// variable. 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.
int MovePicker::number_of_moves() const {
return numOfMoves;
}
/// MovePicker::score_captures(), MovePicker::score_noncaptures(),
/// MovePicker::score_evasions() and MovePicker::score_qcaptures() assign a
/// numerical move ordering score to each move in a move list. The moves
/// with highest scores will be picked first by
/// MovePicker::pick_move_from_list().
void MovePicker::score_captures() { void MovePicker::score_captures() {
// Winning and equal captures in the main search are ordered by MVV/LVA. // Winning and equal captures in the main search are ordered by MVV/LVA.
@@ -245,259 +189,171 @@ void MovePicker::score_captures() {
// where it is possible to recapture with the hanging piece). Exchanging // where it is possible to recapture with the hanging piece). Exchanging
// big pieces before capturing a hanging piece probably helps to reduce // big pieces before capturing a hanging piece probably helps to reduce
// the subtree size. // the subtree size.
for(int i = 0; i < numOfMoves; i++) { // In main search we want to push captures with negative SEE values to
int seeValue = pos->see(moves[i].move); // badCaptures[] array, but instead of doing it now we delay till when
if(seeValue >= 0) { // the move has been picked up in pick_move_from_list(), this way we save
if(move_promotion(moves[i].move)) // some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
moves[i].score = QueenValueMidgame; Move m;
else
moves[i].score =
int(pos->midgame_value_of_piece_on(move_to(moves[i].move))) -
int(pos->type_of_piece_on(move_from(moves[i].move)));
}
else
moves[i].score = seeValue;
// Use MVV/LVA ordering
for (MoveStack* cur = moves; cur != lastMove; cur++)
{
m = cur->move;
if (move_is_promotion(m))
cur->score = QueenValueMidgame;
else
cur->score = int(pos.midgame_value_of_piece_on(move_to(m)))
-int(pos.type_of_piece_on(move_from(m)));
} }
} }
void MovePicker::score_noncaptures() { void MovePicker::score_noncaptures() {
for(int i = 0; i < numOfMoves; i++) { // First score by history, when no history is available then use
Move m = moves[i].move; // piece/square tables values. This seems to be better then a
if(m == killer1) // random choice when we don't have an history for any move.
moves[i].score = HistoryMax + 2; Move m;
else if(m == killer2) Piece piece;
moves[i].score = HistoryMax + 1; Square from, to;
else int hs;
moves[i].score = H.move_ordering_score(pos->piece_on(move_from(m)), m);
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 is always preferred to pst
if (hs > 0)
hs += 1000;
// pst based scoring
cur->score = hs + pos.pst_delta<Position::MidGame>(piece, from, to);
} }
} }
void MovePicker::score_evasions() { void MovePicker::score_evasions() {
for(int i = 0; i < numOfMoves; i++) {
Move m = moves[i].move; Move m;
if(m == ttMove)
moves[i].score = 2*HistoryMax; for (MoveStack* cur = moves; cur != lastMove; cur++)
else if(!pos->square_is_empty(move_to(m))) { {
int seeScore = pos->see(m); m = cur->move;
moves[i].score = (seeScore >= 0)? seeScore + HistoryMax : seeScore; if (m == ttMoves[0].move)
} cur->score = 2 * HistoryMax;
else else if (!pos.square_is_empty(move_to(m)))
moves[i].score = H.move_ordering_score(pos->piece_on(move_from(m)), m); {
int seeScore = pos.see(m);
cur->score = seeScore + (seeScore >= 0 ? HistoryMax : 0);
} else
cur->score = H.move_ordering_score(pos.piece_on(move_from(m)), move_to(m));
} }
} }
void MovePicker::score_qcaptures() { /// MovePicker::get_next_move() is the most important method of the MovePicker
// Use MVV/LVA ordering. /// class. It returns a new legal move every time it is called, until there
for(int i = 0; i < numOfMoves; i++) { /// are no more moves left.
Move m = moves[i].move; /// It picks the move with the biggest score from a list of generated moves taking
if(move_promotion(m)) /// care not to return the tt move if has already been searched previously.
moves[i].score = QueenValueMidgame;
else
moves[i].score =
int(pos->midgame_value_of_piece_on(move_to(m))) -
int(pos->midgame_value_of_piece_on(move_to(m))) / 64;
}
}
Move MovePicker::get_next_move() {
/// MovePicker::pick_move_from_list() picks the move with the biggest score assert(!pos.is_check() || *phasePtr == PH_EVASIONS || *phasePtr == PH_STOP);
/// from a list of generated moves (moves[] or badCaptures[], depending on assert( pos.is_check() || *phasePtr != PH_EVASIONS);
/// the current move generation phase). It takes care not to return the
/// transposition table move if that has already been serched previously.
/// While picking captures in the PH_GOOD_CAPTURES phase (i.e. while picking
/// non-losing captures in the main search), it moves all captures with
/// negative SEE values to the badCaptures[] array.
Move MovePicker::pick_move_from_list() {
int bestScore = -10000000;
int bestIndex;
Move move; Move move;
switch(PhaseTable[phaseIndex]) { while (true)
{
while (curMove != lastMove)
{
move = (curMove++)->move;
switch (phase) {
case PH_TT_MOVES:
if ( move != MOVE_NONE
&& move_is_legal(pos, move, pinned))
return move;
break;
case PH_GOOD_CAPTURES: case PH_GOOD_CAPTURES:
assert(!pos->is_check()); if ( move != ttMoves[0].move
assert(movesPicked >= 0); && move != ttMoves[1].move
while(movesPicked < numOfMoves) { && pos.pl_move_is_legal(move, pinned))
bestScore = -10000000; {
bestIndex = -1; // Check for a non negative SEE now
for(int i = movesPicked; i < numOfMoves; i++) { int seeValue = pos.see_sign(move);
if(moves[i].score < 0) { if (seeValue >= 0)
// Losing capture, move it to the badCaptures[] array
assert(numOfBadCaptures < 63);
badCaptures[numOfBadCaptures++] = moves[i];
moves[i--] = moves[--numOfMoves];
}
else if(moves[i].score > bestScore) {
bestIndex = i;
bestScore = moves[i].score;
}
}
if(bestIndex != -1) { // Found a good capture
MoveStack tmp = moves[movesPicked];
moves[movesPicked] = moves[bestIndex];
moves[bestIndex] = tmp;
move = moves[movesPicked++].move;
if(move != ttMove && move != mateKiller &&
pos->move_is_legal(move, pinned))
return move; 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:
if ( move != MOVE_NONE
&& move != ttMoves[0].move
&& move != ttMoves[1].move
&& move_is_legal(pos, move, pinned)
&& !pos.move_is_capture(move))
return move;
break; break;
case PH_NONCAPTURES: case PH_NONCAPTURES:
assert(!pos->is_check()); if ( move != ttMoves[0].move
assert(movesPicked >= 0); && move != ttMoves[1].move
while(movesPicked < numOfMoves) { && move != killers[0].move
bestScore = -10000000; && move != killers[1].move
&& pos.pl_move_is_legal(move, pinned))
// If this is a PV node or we have only picked a few moves, scan
// the entire move list for the best move. If many moves have already
// been searched and it is not a PV node, we are probably failing low
// anyway, so we just pick the first move from the list.
if(pvNode || movesPicked < 12) {
bestIndex = -1;
for(int i = movesPicked; i < numOfMoves; i++)
if(moves[i].score > bestScore) {
bestIndex = i;
bestScore = moves[i].score;
}
}
else
bestIndex = movesPicked;
if(bestIndex != -1) {
MoveStack tmp = moves[movesPicked];
moves[movesPicked] = moves[bestIndex];
moves[bestIndex] = tmp;
move = moves[movesPicked++].move;
if(move != ttMove && move != mateKiller &&
pos->move_is_legal(move, pinned))
return move; return move;
}
}
break; break;
case PH_EVASIONS: case PH_EVASIONS:
assert(pos->is_check());
assert(movesPicked >= 0);
while(movesPicked < numOfMoves) {
bestScore = -10000000;
bestIndex = -1;
for(int i = movesPicked; i < numOfMoves; i++)
if(moves[i].score > bestScore) {
bestIndex = i;
bestScore = moves[i].score;
}
if(bestIndex != -1) {
MoveStack tmp = moves[movesPicked];
moves[movesPicked] = moves[bestIndex];
moves[bestIndex] = tmp;
move = moves[movesPicked++].move;
return move;
}
}
break;
case PH_BAD_CAPTURES: case PH_BAD_CAPTURES:
assert(!pos->is_check());
assert(badCapturesPicked >= 0);
// It's probably a good idea to use SEE move ordering here, instead
// of just picking the first move. FIXME
while(badCapturesPicked < numOfBadCaptures) {
move = badCaptures[badCapturesPicked++].move;
if(move != ttMove && move != mateKiller &&
pos->move_is_legal(move, pinned))
return move; return move;
}
break;
case PH_QCAPTURES: case PH_QCAPTURES:
assert(!pos->is_check());
assert(movesPicked >= 0);
while(movesPicked < numOfMoves) {
bestScore = -10000000;
if(movesPicked < 4) {
bestIndex = -1;
for(int i = movesPicked; i < numOfMoves; i++)
if(moves[i].score > bestScore) {
bestIndex = i;
bestScore = moves[i].score;
}
}
else
bestIndex = movesPicked;
if(bestIndex != -1) {
MoveStack tmp = moves[movesPicked];
moves[movesPicked] = moves[bestIndex];
moves[bestIndex] = tmp;
move = moves[movesPicked++].move;
// Remember to change the line below if we decide to hash the qsearch!
// Maybe also postpone the legality check until after futility pruning?
if(/* move != ttMove && */ pos->move_is_legal(move, pinned))
return move;
}
}
break;
case PH_QCHECKS: case PH_QCHECKS:
assert(!pos->is_check()); // Maybe postpone the legality check until after futility pruning?
assert(movesPicked >= 0); if ( move != ttMoves[0].move
// Perhaps we should do something better than just picking the first && pos.pl_move_is_legal(move, pinned))
// move here? FIXME
while(movesPicked < numOfMoves) {
move = moves[movesPicked++].move;
// Remember to change the line below if we decide to hash the qsearch!
if(/* move != ttMove && */ pos->move_is_legal(move, pinned))
return move; return move;
}
break; break;
case PH_STOP:
return MOVE_NONE;
default: default:
assert(false);
break; break;
} }
}
go_next_phase();
}
}
/// A variant of get_next_move() which takes a lock as a parameter, used to
/// prevent multiple threads from picking the same move at a split point.
Move MovePicker::get_next_move(Lock &lock) {
lock_grab(&lock);
if (finished)
{
lock_release(&lock);
return MOVE_NONE; return MOVE_NONE;
} }
Move m = get_next_move();
if (m == MOVE_NONE)
finished = true;
lock_release(&lock);
/// MovePicker::init_phase_table() initializes the PhaseTable[], return m;
/// MainSearchPhaseIndex, EvasionPhaseIndex, QsearchWithChecksPhaseIndex
/// and QsearchWithoutChecksPhaseIndex variables. It is only called once
/// during program startup, and never again while the program is running.
void MovePicker::init_phase_table() {
int i = 0;
// Main search
MainSearchPhaseIndex = i - 1;
PhaseTable[i++] = PH_TT_MOVE;
PhaseTable[i++] = PH_MATE_KILLER;
PhaseTable[i++] = PH_GOOD_CAPTURES;
// PH_KILLER_1 and PH_KILLER_2 are not yet used.
// PhaseTable[i++] = PH_KILLER_1;
// PhaseTable[i++] = PH_KILLER_2;
PhaseTable[i++] = PH_NONCAPTURES;
PhaseTable[i++] = PH_BAD_CAPTURES;
PhaseTable[i++] = PH_STOP;
// Check evasions
EvasionsPhaseIndex = i - 1;
PhaseTable[i++] = PH_EVASIONS;
PhaseTable[i++] = PH_STOP;
// Quiescence search with checks
QsearchWithChecksPhaseIndex = i - 1;
PhaseTable[i++] = PH_QCAPTURES;
PhaseTable[i++] = PH_QCHECKS;
PhaseTable[i++] = PH_STOP;
// Quiescence search without checks
QsearchWithoutChecksPhaseIndex = i - 1;
PhaseTable[i++] = PH_QCAPTURES;
PhaseTable[i++] = PH_STOP;
} }
+33 -23
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -25,6 +26,7 @@
//// ////
#include "depth.h" #include "depth.h"
#include "history.h"
#include "lock.h" #include "lock.h"
#include "position.h" #include "position.h"
@@ -33,6 +35,8 @@
//// Types //// Types
//// ////
struct SearchStack;
/// MovePicker is a class which is used to pick one legal move at a time from /// 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 /// 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 /// moves we have reason to believe are good. The most important method is
@@ -43,34 +47,30 @@
class MovePicker { class MovePicker {
MovePicker& operator=(const MovePicker&); // silence a warning under MSVC
public: public:
MovePicker(Position &p, bool pvnode, Move ttm, Move mk, Move k1, Move k2, MovePicker(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss = NULL);
Depth dpth);
Move get_next_move(); Move get_next_move();
Move get_next_move(Lock& lock); Move get_next_move(Lock& lock);
int number_of_moves() const; int number_of_evasions() const;
int current_move_score() const; Bitboard discovered_check_candidates() const;
Bitboard discovered_check_candidates();
static void init_phase_table();
private: private:
void score_captures(); void score_captures();
void score_noncaptures(); void score_noncaptures();
void score_evasions(); void score_evasions();
void score_qcaptures(); void go_next_phase();
Move pick_move_from_list();
Position *pos; const Position& pos;
Move ttMove, mateKiller, killer1, killer2; const History& H;
Bitboard pinned, dc; MoveStack ttMoves[2], killers[2];
MoveStack moves[256], badCaptures[64];
bool pvNode;
Depth depth;
int phaseIndex;
int numOfMoves, numOfBadCaptures;
int movesPicked, badCapturesPicked;
bool finished; bool finished;
int phase;
const uint8_t* phasePtr;
MoveStack *curMove, *lastMove, *lastBadCapture;
Bitboard dc, pinned;
MoveStack moves[256], badCaptures[64];
}; };
@@ -78,11 +78,21 @@ private:
//// Inline functions //// 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);
}
/// MovePicker::discovered_check_candidates() returns a bitboard containing /// MovePicker::discovered_check_candidates() returns a bitboard containing
/// all pieces which can possibly give discovered check. This bitboard is /// all pieces which can possibly give discovered check. This bitboard is
/// computed by the constructor function. /// computed by the constructor function.
inline Bitboard MovePicker::discovered_check_candidates() { inline Bitboard MovePicker::discovered_check_candidates() const {
return dc; return dc;
} }
+227 -203
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -22,8 +23,11 @@
//// ////
#include <cassert> #include <cassert>
#include <cstring>
#include "bitcount.h"
#include "pawns.h" #include "pawns.h"
#include "position.h"
//// ////
@@ -34,100 +38,95 @@ namespace {
/// Constants and variables /// Constants and variables
// Doubled pawn penalty by file, middle game. // Doubled pawn penalty by file, middle game
const Value DoubledPawnMidgamePenalty[8] = { const Value DoubledPawnMidgamePenalty[8] = {
Value(20), Value(30), Value(34), Value(34), Value(13), Value(20), Value(23), Value(23),
Value(34), Value(34), Value(30), Value(20) Value(23), Value(23), Value(20), Value(13)
}; };
// Doubled pawn penalty by file, endgame. // Doubled pawn penalty by file, endgame
const Value DoubledPawnEndgamePenalty[8] = { const Value DoubledPawnEndgamePenalty[8] = {
Value(35), Value(40), Value(40), Value(40), Value(43), Value(48), Value(48), Value(48),
Value(40), Value(40), Value(40), Value(35) Value(48), Value(48), Value(48), Value(43)
}; };
// Isolated pawn penalty by file, middle game. // Isolated pawn penalty by file, middle game
const Value IsolatedPawnMidgamePenalty[8] = { const Value IsolatedPawnMidgamePenalty[8] = {
Value(20), Value(30), Value(34), Value(34), Value(25), Value(36), Value(40), Value(40),
Value(34), Value(34), Value(30), Value(20) Value(40), Value(40), Value(36), Value(25)
}; };
// Isolated pawn penalty by file, endgame. // Isolated pawn penalty by file, endgame
const Value IsolatedPawnEndgamePenalty[8] = { const Value IsolatedPawnEndgamePenalty[8] = {
Value(35), Value(40), Value(40), Value(40), Value(30), Value(35), Value(35), Value(35),
Value(40), Value(40), Value(40), Value(35) Value(35), Value(35), Value(35), Value(30)
}; };
// Backward pawn penalty by file, middle game. // Backward pawn penalty by file, middle game
const Value BackwardPawnMidgamePenalty[8] = { const Value BackwardPawnMidgamePenalty[8] = {
Value(16), Value(24), Value(27), Value(27), Value(20), Value(29), Value(33), Value(33),
Value(27), Value(27), Value(24), Value(16) Value(33), Value(33), Value(29), Value(20)
}; };
// Backward pawn penalty by file, endgame. // Backward pawn penalty by file, endgame
const Value BackwardPawnEndgamePenalty[8] = { const Value BackwardPawnEndgamePenalty[8] = {
Value(28), Value(32), Value(32), Value(32), Value(28), Value(31), Value(31), Value(31),
Value(32), Value(32), Value(32), Value(28) Value(31), Value(31), Value(31), Value(28)
}; };
// Pawn chain membership bonus by file, middle game. // Pawn chain membership bonus by file, middle game
const Value ChainMidgameBonus[8] = { const Value ChainMidgameBonus[8] = {
Value(14), Value(16), Value(17), Value(18), Value(11), Value(13), Value(13), Value(14),
Value(18), Value(17), Value(16), Value(14) Value(14), Value(13), Value(13), Value(11)
}; };
// Pawn chain membership bonus by file, endgame. // Pawn chain membership bonus by file, endgame
const Value ChainEndgameBonus[8] = { const Value ChainEndgameBonus[8] = {
Value(16), Value(16), Value(16), Value(16), Value(-1), Value(-1), Value(-1), Value(-1),
Value(16), Value(16), Value(16), Value(16) Value(-1), Value(-1), Value(-1), Value(-1)
}; };
// Candidate passed pawn bonus by rank, middle game. // Candidate passed pawn bonus by rank, middle game
const Value CandidateMidgameBonus[8] = { const Value CandidateMidgameBonus[8] = {
Value(0), Value(12), Value(12), Value(20), Value( 0), Value( 6), Value(6), Value(14),
Value(40), Value(90), Value(0), Value(0) Value(34), Value(83), Value(0), Value( 0)
}; };
// Candidate passed pawn bonus by rank, endgame. // Candidate passed pawn bonus by rank, endgame
const Value CandidateEndgameBonus[8] = { const Value CandidateEndgameBonus[8] = {
Value(0), Value(24), Value(24), Value(40), Value( 0), Value( 13), Value(13), Value(29),
Value(80), Value(180), Value(0), Value(0) Value(68), Value(166), Value( 0), Value( 0)
}; };
// Evaluate pawn storms? // Pawn storm tables for positions with opposite castling
const bool EvaluatePawnStorms = true;
// Pawn storm tables for positions with opposite castling:
const int QStormTable[64] = { const int QStormTable[64] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-22, -22, -22, -13, -4, 0, 0, 0, -22,-22,-22,-14,-6, 0, 0, 0,
-4, -9, -9, -9, -4, 0, 0, 0, -6,-10,-10,-10,-6, 0, 0, 0,
9, 18, 22, 18, 9, 0, 0, 0, 4, 12, 16, 12, 4, 0, 0, 0,
22, 31, 31, 22, 0, 0, 0, 0, 16, 23, 23, 16, 0, 0, 0, 0,
31, 40, 40, 31, 0, 0, 0, 0, 23, 31, 31, 23, 0, 0, 0, 0,
31, 40, 40, 31, 0, 0, 0, 0, 23, 31, 31, 23, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0 0, 0, 0, 0, 0, 0, 0, 0
}; };
const int KStormTable[64] = { const int KStormTable[64] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, -4, -13, -22, -27, -27, 0, 0, 0,-10,-19,-28,-33,-33,
0, 0, 0, -4, -9, -13, -18, -18, 0, 0, 0,-10,-15,-19,-24,-24,
0, 0, 0, 0, 9, 9, 9, 9, 0, 0, 0, 0, 1, 1, 1, 1,
0, 0, 0, 0, 9, 18, 27, 27, 0, 0, 0, 0, 1, 10, 19, 19,
0, 0, 0, 0, 9, 27, 40, 36, 0, 0, 0, 0, 1, 19, 31, 27,
0, 0, 0, 0, 0, 31, 40, 31, 0, 0, 0, 0, 0, 22, 31, 22,
0, 0, 0, 0, 0, 0, 0, 0 0, 0, 0, 0, 0, 0, 0, 0
}; };
// Pawn storm open file bonuses by file: // Pawn storm open file bonuses by file
const int KStormOpenFileBonus[8] = { const int16_t KStormOpenFileBonus[8] = { 31, 31, 18, 0, 0, 0, 0, 0 };
45, 45, 30, 0, 0, 0, 0, 0 const int16_t QStormOpenFileBonus[8] = { 0, 0, 0, 0, 0, 26, 42, 26 };
};
const int QStormOpenFileBonus[8] = { // Pawn storm lever bonuses by file
0, 0, 0, 0, 0, 30, 45, 30 const int StormLeverBonus[8] = { -8, -8, -13, 0, 0, -13, -8, -8 };
};
} }
@@ -139,14 +138,15 @@ namespace {
/// Constructor /// Constructor
PawnInfoTable::PawnInfoTable(unsigned numOfEntries) { PawnInfoTable::PawnInfoTable(unsigned numOfEntries) {
size = numOfEntries; size = numOfEntries;
entries = new PawnInfo[size]; entries = new PawnInfo[size];
if(entries == NULL) { if (!entries)
{
std::cerr << "Failed to allocate " << (numOfEntries * sizeof(PawnInfo)) std::cerr << "Failed to allocate " << (numOfEntries * sizeof(PawnInfo))
<< " bytes for pawn hash table." << std::endl; << " bytes for pawn hash table." << std::endl;
exit(EXIT_FAILURE); Application::exit_with_failure();
} }
this->clear();
} }
@@ -157,11 +157,13 @@ PawnInfoTable::~PawnInfoTable() {
} }
/// PawnInfoTable::clear() clears the pawn hash table by setting all /// PawnInfo::clear() resets to zero the PawnInfo entry. Note that
/// entries to 0. /// kingSquares[] is initialized to SQ_NONE instead.
void PawnInfoTable::clear() { void PawnInfo::clear() {
memset(entries, 0, size * sizeof(PawnInfo));
memset(this, 0, sizeof(PawnInfo));
kingSquares[WHITE] = kingSquares[BLACK] = SQ_NONE;
} }
@@ -171,6 +173,7 @@ void PawnInfoTable::clear() {
/// the same pawn structure occurs again. /// the same pawn structure occurs again.
PawnInfo* PawnInfoTable::get_pawn_info(const Position& pos) { PawnInfo* PawnInfoTable::get_pawn_info(const Position& pos) {
assert(pos.is_ok()); assert(pos.is_ok());
Key key = pos.get_pawn_key(); Key key = pos.get_pawn_key();
@@ -178,208 +181,229 @@ PawnInfo *PawnInfoTable::get_pawn_info(const Position &pos) {
PawnInfo* pi = entries + index; PawnInfo* pi = entries + index;
// If pi->key matches the position's pawn hash key, it means that we // If pi->key matches the position's pawn hash key, it means that we
// have analysed this pawn structure before, and we can simply return the // have analysed this pawn structure before, and we can simply return
// information we found the last time instead of recomputing it: // the information we found the last time instead of recomputing it.
if (pi->key == key) if (pi->key == key)
return pi; return pi;
// Clear the PawnInfo object, and set the key: // Clear the PawnInfo object, and set the key
pi->clear(); pi->clear();
pi->key = key; pi->key = key;
Value mgValue[2] = {Value(0), Value(0)}; Value mgValue[2] = {Value(0), Value(0)};
Value egValue[2] = {Value(0), Value(0)}; Value egValue[2] = {Value(0), Value(0)};
// Loop through the pawns for both colors: // Calculate pawn attacks
for(Color us = WHITE; us <= BLACK; us++) { pi->pawnAttacks[WHITE] = ((pos.pieces(PAWN, WHITE) << 9) & ~FileABB) | ((pos.pieces(PAWN, WHITE) << 7) & ~FileHBB);
pi->pawnAttacks[BLACK] = ((pos.pieces(PAWN, BLACK) >> 7) & ~FileABB) | ((pos.pieces(PAWN, BLACK) >> 9) & ~FileHBB);
// Loop through the pawns for both colors
for (Color us = WHITE; us <= BLACK; us++)
{
Color them = opposite_color(us); Color them = opposite_color(us);
Bitboard ourPawns = pos.pawns(us); Bitboard ourPawns = pos.pieces(PAWN, us);
Bitboard theirPawns = pos.pawns(them); Bitboard theirPawns = pos.pieces(PAWN, them);
Bitboard pawns = ourPawns; Bitboard pawns = ourPawns;
// Initialize pawn storm scores by giving bonuses for open files: // Initialize pawn storm scores by giving bonuses for open files
if(EvaluatePawnStorms)
for (File f = FILE_A; f <= FILE_H; f++) for (File f = FILE_A; f <= FILE_H; f++)
if(pos.file_is_half_open(us, f)) { if (!(pawns & file_bb(f)))
{
pi->ksStormValue[us] += KStormOpenFileBonus[f]; pi->ksStormValue[us] += KStormOpenFileBonus[f];
pi->qsStormValue[us] += QStormOpenFileBonus[f]; pi->qsStormValue[us] += QStormOpenFileBonus[f];
pi->halfOpenFiles[us] |= (1 << f);
} }
// Loop through all pawns of the current color and score each pawn: // Loop through all pawns of the current color and score each pawn
while(pawns) { while (pawns)
{
Square s = pop_1st_bit(&pawns); Square s = pop_1st_bit(&pawns);
File f = square_file(s); File f = square_file(s);
Rank r = square_rank(s); Rank r = square_rank(s);
bool passed, doubled, isolated, backward, chain, candidate;
int bonus;
assert(pos.piece_on(s) == pawn_of_color(us)); assert(pos.piece_on(s) == piece_of_color_and_type(us, PAWN));
// The file containing the pawn is not half open:
pi->halfOpenFiles[us] &= ~(1 << f);
// Passed, isolated or doubled pawn? // Passed, isolated or doubled pawn?
passed = pos.pawn_is_passed(us, s); bool passed = Position::pawn_is_passed(theirPawns, us, s);
isolated = pos.pawn_is_isolated(us, s); bool isolated = Position::pawn_is_isolated(ourPawns, s);
doubled = pos.pawn_is_doubled(us, s); bool doubled = Position::pawn_is_doubled(ourPawns, us, s);
if(EvaluatePawnStorms) {
// We calculate kingside and queenside pawn storm // We calculate kingside and queenside pawn storm
// scores for both colors. These are used when evaluating // scores for both colors. These are used when evaluating
// middle game positions with opposite side castling. // middle game positions with opposite side castling.
// //
// Each pawn is given a base score given by a piece square table // Each pawn is given a base score given by a piece square table
// (KStormTable[] or QStormTable[]). This score is increased if // (KStormTable[] or QStormTable[]). Pawns which seem to have good
// there are enemy pawns on adjacent files in front of the pawn. // chances of creating an open file by exchanging itself against an
// This is because we want to be able to open files against the // enemy pawn on an adjacent file gets an additional bonus.
// enemy king, and to avoid blocking the pawn structure (e.g. white
// pawns on h6, g5, black pawns on h7, g6, f7).
// Kingside pawn storms: // Kingside pawn storms
bonus = KStormTable[relative_square(us, s)]; int bonus = KStormTable[relative_square(us, s)];
if(bonus > 0 && outpost_mask(us, s) & theirPawns) { if (f >= FILE_F)
switch(f) { {
Bitboard b = outpost_mask(us, s) & theirPawns & (FileFBB | FileGBB | FileHBB);
case FILE_F: while (b)
bonus += bonus / 4; {
break; Square s2 = pop_1st_bit(&b);
if (!(theirPawns & neighboring_files_bb(s2) & rank_bb(s2)))
case FILE_G: {
bonus += bonus / 2 + bonus / 4; // The enemy pawn has no pawn beside itself, which makes it
break; // particularly vulnerable. Big bonus, especially against a
// weakness on the rook file.
case FILE_H: if (square_file(s2) == FILE_H)
bonus += bonus / 2; bonus += 4*StormLeverBonus[f] - 8*square_distance(s, s2);
break; else
bonus += 2*StormLeverBonus[f] - 4*square_distance(s, s2);
default: } else
break; // There is at least one enemy pawn beside the enemy pawn we look
// at, which means that the pawn has somewhat better chances of
// defending itself by advancing. Smaller bonus.
bonus += StormLeverBonus[f] - 2*square_distance(s, s2);
} }
} }
pi->ksStormValue[us] += bonus; pi->ksStormValue[us] += bonus;
// Queenside pawn storms: // Queenside pawn storms
bonus = QStormTable[relative_square(us, s)]; bonus = QStormTable[relative_square(us, s)];
if(bonus > 0 && passed_pawn_mask(us, s) & theirPawns) { if (f <= FILE_C)
switch(f) { {
Bitboard b = outpost_mask(us, s) & theirPawns & (FileABB | FileBBB | FileCBB);
case FILE_A: while (b)
bonus += bonus / 2; {
break; Square s2 = pop_1st_bit(&b);
if (!(theirPawns & neighboring_files_bb(s2) & rank_bb(s2)))
case FILE_B: {
bonus += bonus / 2 + bonus / 4; // The enemy pawn has no pawn beside itself, which makes it
break; // particularly vulnerable. Big bonus, especially against a
// weakness on the rook file.
case FILE_C: if (square_file(s2) == FILE_A)
bonus += bonus / 2; bonus += 4*StormLeverBonus[f] - 16*square_distance(s, s2);
break; else
bonus += 2*StormLeverBonus[f] - 8*square_distance(s, s2);
default: } else
break; // There is at least one enemy pawn beside the enemy pawn we look
// at, which means that the pawn has somewhat better chances of
// defending itself by advancing. Smaller bonus.
bonus += StormLeverBonus[f] - 4*square_distance(s, s2);
} }
} }
pi->qsStormValue[us] += bonus; pi->qsStormValue[us] += bonus;
}
// Member of a pawn chain? We could speed up the test a little by // Member of a pawn chain (but not the backward one)? We could speed up
// introducing an array of masks indexed by color and square for doing // the test a little by introducing an array of masks indexed by color
// the test, but because everything is hashed, it probably won't make // and square for doing the test, but because everything is hashed,
// any noticable difference. // it probably won't make any noticable difference.
chain = (us == WHITE)? bool chain = ourPawns
(ourPawns & neighboring_files_bb(f) & (rank_bb(r) | rank_bb(r-1))) : & neighboring_files_bb(f)
(ourPawns & neighboring_files_bb(f) & (rank_bb(r) | rank_bb(r+1))); & (rank_bb(r) | rank_bb(r - (us == WHITE ? 1 : -1)));
// Test for backward pawn
// Test for backward pawn. //
// If the pawn is passed, isolated, or member of a pawn chain
// If the pawn is isolated, passed, or member of a pawn chain, it cannot // it cannot be backward. If can capture an enemy pawn or if
// be backward: // there are friendly pawns behind on neighboring files it cannot
if(passed || isolated || chain) // be backward either.
bool backward;
if ( passed
|| isolated
|| chain
|| (pos.attacks_from<PAWN>(s, us) & theirPawns)
|| (ourPawns & behind_bb(us, r) & neighboring_files_bb(f)))
backward = false; backward = false;
// If the pawn can capture an enemy pawn, it's not backward: else
else if(pos.pawn_attacks(us, s) & theirPawns) {
backward = false; // We now know that there are no friendly pawns beside or behind this
// Check for friendly pawns behind on neighboring files:
else if(ourPawns & in_front_bb(them, r) & neighboring_files_bb(f))
backward = false;
else {
// We now know that there is no friendly pawns beside or behind this
// pawn on neighboring files. We now check whether the pawn is // pawn on neighboring files. We now check whether the pawn is
// backward by looking in the forward direction on the neighboring // backward by looking in the forward direction on the neighboring
// files, and seeing whether we meet a friendly or an enemy pawn first. // files, and seeing whether we meet a friendly or an enemy pawn first.
Bitboard b; Bitboard b = pos.attacks_from<PAWN>(s, us);
if(us == WHITE) { if (us == WHITE)
for(b=pos.pawn_attacks(us, s); !(b&(ourPawns|theirPawns)); b<<=8); {
for ( ; !(b & (ourPawns | theirPawns)); b <<= 8);
backward = (b | (b << 8)) & theirPawns; backward = (b | (b << 8)) & theirPawns;
} }
else { else
for(b=pos.pawn_attacks(us, s); !(b&(ourPawns|theirPawns)); b>>=8); {
for ( ; !(b & (ourPawns | theirPawns)); b >>= 8);
backward = (b | (b >> 8)) & theirPawns; backward = (b | (b >> 8)) & theirPawns;
} }
} }
// Test for candidate passed pawn. // Test for candidate passed pawn
candidate = bool candidate;
(!passed && pos.file_is_half_open(them, f) && candidate = !passed
count_1s_max_15(neighboring_files_bb(f) && !(theirPawns & file_bb(f))
& (in_front_bb(them, r) | rank_bb(r)) && ( count_1s_max_15(neighboring_files_bb(f) & (behind_bb(us, r) | rank_bb(r)) & ourPawns)
& ourPawns) - count_1s_max_15(neighboring_files_bb(f) & in_front_bb(us, r) & theirPawns)
- count_1s_max_15(neighboring_files_bb(f) & in_front_bb(us, r)
& theirPawns)
>= 0); >= 0);
// In order to prevent doubled passed pawns from receiving a too big // In order to prevent doubled passed pawns from receiving a too big
// bonus, only the frontmost passed pawn on each file is considered as // bonus, only the frontmost passed pawn on each file is considered as
// a true passed pawn. // a true passed pawn.
if(passed && (ourPawns & squares_in_front_of(us, s))) { if (passed && (ourPawns & squares_in_front_of(us, s)))
// candidate = true;
passed = false; passed = false;
}
// Score this pawn: // Score this pawn
Value mv = Value(0), ev = Value(0);
if(isolated) {
mv -= IsolatedPawnMidgamePenalty[f];
ev -= IsolatedPawnEndgamePenalty[f];
if(pos.file_is_half_open(them, f)) {
mv -= IsolatedPawnMidgamePenalty[f] / 2;
ev -= IsolatedPawnEndgamePenalty[f] / 2;
}
}
if(doubled) {
mv -= DoubledPawnMidgamePenalty[f];
ev -= DoubledPawnEndgamePenalty[f];
}
if(backward) {
mv -= BackwardPawnMidgamePenalty[f];
ev -= BackwardPawnEndgamePenalty[f];
if(pos.file_is_half_open(them, f)) {
mv -= BackwardPawnMidgamePenalty[f] / 2;
ev -= BackwardPawnEndgamePenalty[f] / 2;
}
}
if(chain) {
mv += ChainMidgameBonus[f];
ev += ChainEndgameBonus[f];
}
if(candidate) {
mv += CandidateMidgameBonus[pawn_rank(us, s)];
ev += CandidateEndgameBonus[pawn_rank(us, s)];
}
mgValue[us] += mv;
egValue[us] += ev;
// If the pawn is passed, set the square of the pawn in the passedPawns
// bitboard:
if (passed) if (passed)
set_bit(&(pi->passedPawns), s); set_bit(&(pi->passedPawns), s);
if (isolated)
{
mgValue[us] -= IsolatedPawnMidgamePenalty[f];
egValue[us] -= IsolatedPawnEndgamePenalty[f];
if (!(theirPawns & file_bb(f)))
{
mgValue[us] -= IsolatedPawnMidgamePenalty[f] / 2;
egValue[us] -= IsolatedPawnEndgamePenalty[f] / 2;
} }
} }
if (doubled)
{
mgValue[us] -= DoubledPawnMidgamePenalty[f];
egValue[us] -= DoubledPawnEndgamePenalty[f];
}
if (backward)
{
mgValue[us] -= BackwardPawnMidgamePenalty[f];
egValue[us] -= BackwardPawnEndgamePenalty[f];
if (!(theirPawns & file_bb(f)))
{
mgValue[us] -= BackwardPawnMidgamePenalty[f] / 2;
egValue[us] -= BackwardPawnEndgamePenalty[f] / 2;
}
}
if (chain)
{
mgValue[us] += ChainMidgameBonus[f];
egValue[us] += ChainEndgameBonus[f];
}
if (candidate)
{
mgValue[us] += CandidateMidgameBonus[relative_rank(us, s)];
egValue[us] += CandidateEndgameBonus[relative_rank(us, s)];
}
} // while(pawns)
} // for(colors)
pi->mgValue = int16_t(mgValue[WHITE] - mgValue[BLACK]); pi->mgValue = int16_t(mgValue[WHITE] - mgValue[BLACK]);
pi->egValue = int16_t(egValue[WHITE] - egValue[BLACK]); pi->egValue = int16_t(egValue[WHITE] - egValue[BLACK]);
return pi; return pi;
} }
/// PawnInfo::updateShelter calculates and caches king shelter. It is called
/// only when king square changes, about 20% of total get_king_shelter() calls.
int PawnInfo::updateShelter(const Position& pos, Color c, Square ksq) {
unsigned shelter = 0;
Bitboard pawns = pos.pieces(PAWN, c) & this_and_neighboring_files_bb(ksq);
unsigned r = ksq & (7 << 3);
for (int i = 1, k = (c ? -8 : 8); i < 4; i++)
{
r += k;
shelter += BitCount8Bit[(pawns >> r) & 0xFF] * (128 >> i);
}
kingSquares[c] = ksq;
kingShelters[c] = shelter;
return shelter;
}
+29 -22
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -24,8 +25,8 @@
//// Includes //// Includes
//// ////
#include "position.h" #include "bitboard.h"
#include "value.h"
//// ////
//// Types //// Types
@@ -37,32 +38,40 @@
/// to add further information in the future. A lookup to the pawn hash table /// 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) /// (performed by calling the get_pawn_info method in a PawnInfoTable object)
/// returns a pointer to a PawnInfo object. /// returns a pointer to a PawnInfo object.
class Position;
class PawnInfo { class PawnInfo {
friend class PawnInfoTable; friend class PawnInfoTable;
public: public:
PawnInfo() : key(0) { clear(); }
Value mg_value() const; Value mg_value() const;
Value eg_value() const; Value eg_value() const;
Value kingside_storm_value(Color c) const; Value kingside_storm_value(Color c) const;
Value queenside_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() const;
bool file_is_half_open(Color c, File f) const; int file_is_half_open(Color c, File f) const;
bool has_open_file_to_left(Color c, File f) const; int has_open_file_to_left(Color c, File f) const;
bool has_open_file_to_right(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: private:
void clear(); void clear();
int updateShelter(const Position& pos, Color c, Square ksq);
Key key; Key key;
Bitboard passedPawns; Bitboard passedPawns;
Bitboard pawnAttacks[2];
int16_t mgValue, egValue; int16_t mgValue, egValue;
int8_t ksStormValue[2], qsStormValue[2]; int16_t ksStormValue[2], qsStormValue[2];
uint8_t halfOpenFiles[2]; uint8_t halfOpenFiles[2];
Square kingSquares[2];
uint8_t kingShelters[2];
}; };
/// The PawnInfoTable class represents a pawn hash table. It is basically /// The PawnInfoTable class represents a pawn hash table. It is basically
/// just an array of PawnInfo objects and a few methods for accessing these /// 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 /// objects. The most important method is get_pawn_info, which looks up a
@@ -73,7 +82,6 @@ class PawnInfoTable {
public: public:
PawnInfoTable(unsigned numOfEntries); PawnInfoTable(unsigned numOfEntries);
~PawnInfoTable(); ~PawnInfoTable();
void clear();
PawnInfo* get_pawn_info(const Position& pos); PawnInfo* get_pawn_info(const Position& pos);
private: private:
@@ -98,6 +106,10 @@ inline Bitboard PawnInfo::passed_pawns() const {
return passedPawns; return passedPawns;
} }
inline Bitboard PawnInfo::pawn_attacks(Color c) const {
return pawnAttacks[c];
}
inline Value PawnInfo::kingside_storm_value(Color c) const { inline Value PawnInfo::kingside_storm_value(Color c) const {
return Value(ksStormValue[c]); return Value(ksStormValue[c]);
} }
@@ -106,25 +118,20 @@ inline Value PawnInfo::queenside_storm_value(Color c) const {
return Value(qsStormValue[c]); return Value(qsStormValue[c]);
} }
inline bool PawnInfo::file_is_half_open(Color c, File f) const { 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 bool PawnInfo::has_open_file_to_left(Color c, File f) const { inline int PawnInfo::has_open_file_to_left(Color c, File f) const {
return halfOpenFiles[c] & ((1 << int(f)) - 1); return halfOpenFiles[c] & ((1 << int(f)) - 1);
} }
inline bool PawnInfo::has_open_file_to_right(Color c, File f) const { inline int PawnInfo::has_open_file_to_right(Color c, File f) const {
return halfOpenFiles[c] & ~((1 << int(f+1)) - 1); return halfOpenFiles[c] & ~((1 << int(f+1)) - 1);
} }
inline void PawnInfo::clear() { inline int PawnInfo::get_king_shelter(const Position& pos, Color c, Square ksq) {
mgValue = egValue = 0; return (kingSquares[c] == ksq ? kingShelters[c] : updateShelter(pos, c, ksq));
passedPawns = EmptyBoardBB;
ksStormValue[WHITE] = ksStormValue[BLACK] = 0;
qsStormValue[WHITE] = qsStormValue[BLACK] = 0;
halfOpenFiles[WHITE] = halfOpenFiles[BLACK] = 0xFF;
} }
#endif // !defined(PAWNS_H_INCLUDED) #endif // !defined(PAWNS_H_INCLUDED)
-33
View File
@@ -1,33 +0,0 @@
/*
Glaurung, a UCI chess playing engine.
Copyright (C) 2004-2008 Tord Romstad
Glaurung 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.
Glaurung 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(PHASE_H_INCLUDED)
#define PHASE_H_INCLUDED
////
//// Types
////
enum Phase {
PHASE_ENDGAME = 0,
PHASE_MIDGAME = 128
};
#endif // !defined(PHASE_H_INCLUDED)
+16 -61
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -21,74 +22,28 @@
//// Includes //// Includes
//// ////
#include <cstring> #include <string>
#include "piece.h" #include "piece.h"
using namespace std;
////
//// Constants and variables
////
const int SlidingArray[18] = {
0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0
};
const SquareDelta Directions[16][16] = {
{DELTA_ZERO},
{DELTA_NW, DELTA_NE, DELTA_ZERO},
{DELTA_SSW, DELTA_SSE, DELTA_SWW, DELTA_SEE,
DELTA_NWW, DELTA_NEE, DELTA_NNW, DELTA_NNE, DELTA_ZERO},
{DELTA_SE, DELTA_SW, DELTA_NE, DELTA_NW, DELTA_ZERO},
{DELTA_S, DELTA_E, DELTA_W, DELTA_N, DELTA_ZERO},
{DELTA_S, DELTA_E, DELTA_W, DELTA_N,
DELTA_SE, DELTA_SW, DELTA_NE, DELTA_NW, DELTA_ZERO},
{DELTA_S, DELTA_E, DELTA_W, DELTA_N,
DELTA_SE, DELTA_SW, DELTA_NE, DELTA_NW, DELTA_ZERO},
{DELTA_ZERO},
{DELTA_ZERO},
{DELTA_SW, DELTA_SE, DELTA_ZERO},
{DELTA_SSW, DELTA_SSE, DELTA_SWW, DELTA_SEE,
DELTA_NWW, DELTA_NEE, DELTA_NNW, DELTA_NNE, DELTA_ZERO},
{DELTA_SE, DELTA_SW, DELTA_NE, DELTA_NW, DELTA_ZERO},
{DELTA_S, DELTA_E, DELTA_W, DELTA_N, DELTA_ZERO},
{DELTA_S, DELTA_E, DELTA_W, DELTA_N,
DELTA_SE, DELTA_SW, DELTA_NE, DELTA_NW, DELTA_ZERO},
{DELTA_S, DELTA_E, DELTA_W, DELTA_N,
DELTA_SE, DELTA_SW, DELTA_NE, DELTA_NW, DELTA_ZERO},
};
const SquareDelta PawnPush[2] = {
DELTA_N, DELTA_S
};
//// ////
//// Functions //// Functions
//// ////
/// Translating piece types to/from English piece letters: /// Translating piece types to/from English piece letters
static const char PieceChars[] = " pnbrqk"; static const string PieceChars(" pnbrqk PNBRQK");
char piece_type_to_char(PieceType pt, bool upcase = false) { char piece_type_to_char(PieceType pt, bool upcase) {
return upcase? toupper(PieceChars[pt]) : PieceChars[pt];
return PieceChars[pt + upcase * 7];
} }
PieceType piece_type_from_char(char c) { PieceType piece_type_from_char(char c) {
const char *ch = strchr(PieceChars, tolower(c));
return ch? PieceType(ch - PieceChars) : NO_PIECE_TYPE; size_t idx = PieceChars.find(c);
}
return idx != string::npos ? PieceType(idx % 7) : NO_PIECE_TYPE;
/// piece_is_ok() and piece_type_is_ok(), for debugging:
bool piece_is_ok(Piece pc) {
return
piece_type_is_ok(type_of_piece(pc)) &&
color_is_ok(color_of_piece(pc));
}
bool piece_type_is_ok(PieceType pc) {
return pc >= PAWN && pc <= KING;
} }
+18 -43
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -25,7 +26,6 @@
//// ////
#include "color.h" #include "color.h"
#include "misc.h"
#include "square.h" #include "square.h"
@@ -46,15 +46,12 @@ enum Piece {
//// ////
//// Constants and variables //// Constants
//// ////
const PieceType PieceTypeMin = PAWN; const int SlidingArray[18] = {
const PieceType PieceTypeMax = KING; 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0
};
extern const int SlidingArray[18];
extern const SquareDelta Directions[16][16];
extern const SquareDelta PawnPush[2];
//// ////
@@ -82,40 +79,20 @@ inline Piece piece_of_color_and_type(Color c, PieceType pt) {
return Piece((int(c) << 3) | int(pt)); return Piece((int(c) << 3) | int(pt));
} }
inline Piece pawn_of_color(Color c) {
return piece_of_color_and_type(c, PAWN);
}
inline Piece knight_of_color(Color c) {
return piece_of_color_and_type(c, KNIGHT);
}
inline Piece bishop_of_color(Color c) {
return piece_of_color_and_type(c, BISHOP);
}
inline Piece rook_of_color(Color c) {
return piece_of_color_and_type(c, ROOK);
}
inline Piece queen_of_color(Color c) {
return piece_of_color_and_type(c, QUEEN);
}
inline Piece king_of_color(Color c) {
return piece_of_color_and_type(c, KING);
}
inline int piece_is_slider(Piece p) { inline int piece_is_slider(Piece p) {
return SlidingArray[int(p)]; return SlidingArray[int(p)];
} }
inline int piece_type_is_slider(PieceType pt) { inline SquareDelta pawn_push(Color c) {
return SlidingArray[int(pt)]; return (c == WHITE ? DELTA_N : DELTA_S);
} }
inline SquareDelta pawn_push(Color c) { inline bool piece_type_is_ok(PieceType pc) {
return PawnPush[c]; 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));
} }
@@ -123,10 +100,8 @@ inline SquareDelta pawn_push(Color c) {
//// Prototypes //// Prototypes
//// ////
extern char piece_type_to_char(PieceType pt, bool upcase); extern char piece_type_to_char(PieceType pt, bool upcase = false);
extern PieceType piece_type_from_char(char c); extern PieceType piece_type_from_char(char c);
extern bool piece_is_ok(Piece pc);
extern bool piece_type_is_ok(PieceType pt);
#endif // !defined(PIECE_H_INCLUDED) #endif // !defined(PIECE_H_INCLUDED)
+1139 -1359
View File
File diff suppressed because it is too large Load Diff
+184 -355
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -20,6 +21,18 @@
#if !defined(POSITION_H_INCLUDED) #if !defined(POSITION_H_INCLUDED)
#define 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 //// Includes
//// ////
@@ -29,7 +42,6 @@
#include "direction.h" #include "direction.h"
#include "move.h" #include "move.h"
#include "piece.h" #include "piece.h"
#include "phase.h"
#include "square.h" #include "square.h"
#include "value.h" #include "value.h"
@@ -38,13 +50,12 @@
//// Constants //// Constants
//// ////
/// FEN string for the initial position: /// FEN string for the initial position
const std::string StartPosition = const std::string StartPosition = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
"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 number of plies per game (220 should be enough, because the
/// maximum search depth is 100, and during position setup we reset the /// maximum search depth is 100, and during position setup we reset the
/// move counter for every non-reversible move): /// move counter for every non-reversible move).
const int MaxGameLength = 220; const int MaxGameLength = 220;
@@ -52,31 +63,39 @@ const int MaxGameLength = 220;
//// Types //// Types
//// ////
/// Castle rights, encoded as bit fields: /// Castle rights, encoded as bit fields
enum CastleRights { enum CastleRights {
NO_CASTLES = 0, NO_CASTLES = 0,
WHITE_OO = 1, BLACK_OO = 2, WHITE_OO = 1,
WHITE_OOO = 4, BLACK_OOO = 8, BLACK_OO = 2,
WHITE_OOO = 4,
BLACK_OOO = 8,
ALL_CASTLES = 15 ALL_CASTLES = 15
}; };
/// Game phase
enum Phase {
PHASE_ENDGAME = 0,
PHASE_MIDGAME = 128
};
/// The UndoInfo struct stores information we need to restore a Position
/// The StateInfo struct stores information we need to restore a Position
/// object to its previous state when we retract a move. Whenever a move /// object to its previous state when we retract a move. Whenever a move
/// is made on the board (by calling Position::do_move), an UndoInfo object /// is made on the board (by calling Position::do_move), an StateInfo object
/// must be passed as a parameter. When the move is unmade (by calling /// must be passed as a parameter.
/// Position::undo_move), the same UndoInfo object must be passed again.
struct UndoInfo { struct StateInfo {
int castleRights;
Square epSquare;
Bitboard checkersBB;
Key key, pawnKey, materialKey; Key key, pawnKey, materialKey;
int rule50; int castleRights, rule50;
Move lastMove; Square epSquare;
PieceType capture;
Value mgValue, egValue; Value mgValue, egValue;
Value npMaterial[2];
PieceType capture;
Bitboard checkersBB;
StateInfo* previous;
}; };
@@ -84,7 +103,7 @@ struct UndoInfo {
/// ///
/// * For each piece type, a bitboard representing the squares occupied /// * For each piece type, a bitboard representing the squares occupied
/// by pieces of that type. /// by pieces of that type.
/// * For each color, a bitboard representing the squares occupiecd by /// * For each color, a bitboard representing the squares occupied by
/// pieces of that color. /// pieces of that color.
/// * A bitboard of all occupied squares. /// * A bitboard of all occupied squares.
/// * A bitboard of all checking pieces. /// * A bitboard of all checking pieces.
@@ -96,27 +115,32 @@ struct UndoInfo {
/// * The en passant square (which is SQ_NONE if no en passant capture is /// * The en passant square (which is SQ_NONE if no en passant capture is
/// possible). /// possible).
/// * The squares of the kings for both sides. /// * The squares of the kings for both sides.
/// * The last move played.
/// * Hash keys for the position itself, the current pawn structure, and /// * Hash keys for the position itself, the current pawn structure, and
/// the current material situation. /// the current material situation.
/// * Hash keys for all previous positions in the game (for detecting /// * Hash keys for all previous positions in the game for detecting
/// repetition draws. /// repetition draws.
/// * A counter for detecting 50 move rule draws. /// * A counter for detecting 50 move rule draws.
class Position { class Position {
friend class MaterialInfo; friend class MaterialInfo;
friend class EndgameFunctions;
public: public:
enum GamePhase {
MidGame,
EndGame
};
// Constructors // Constructors
Position(); Position() {}
Position(const Position& pos); Position(const Position& pos);
Position(const std::string& fen); Position(const std::string& fen);
// Text input/output // Text input/output
void from_fen(const std::string& fen); void from_fen(const std::string& fen);
const std::string to_fen() const; const std::string to_fen() const;
void print() const; void print(Move m = MOVE_NONE) const;
// Copying // Copying
void copy(const Position& pos); void copy(const Position& pos);
@@ -138,124 +162,76 @@ public:
Bitboard empty_squares() const; Bitboard empty_squares() const;
Bitboard occupied_squares() const; Bitboard occupied_squares() const;
Bitboard pieces_of_color(Color c) const; Bitboard pieces_of_color(Color c) const;
Bitboard pieces_of_type(PieceType pt) const; Bitboard pieces(PieceType pt) const;
Bitboard pieces_of_color_and_type(Color c, PieceType pt) const; Bitboard pieces(PieceType pt, Color c) const;
Bitboard pawns() const; Bitboard pieces(PieceType pt1, PieceType pt2) const;
Bitboard knights() const; Bitboard pieces(PieceType pt1, PieceType pt2, Color c) const;
Bitboard bishops() const;
Bitboard rooks() const;
Bitboard queens() const;
Bitboard kings() const;
Bitboard rooks_and_queens() const;
Bitboard bishops_and_queens() const;
Bitboard sliders() const;
Bitboard pawns(Color c) const;
Bitboard knights(Color c) const;
Bitboard bishops(Color c) const;
Bitboard rooks(Color c) const;
Bitboard queens(Color c) const;
Bitboard kings(Color c) const;
Bitboard rooks_and_queens(Color c) const;
Bitboard bishops_and_queens(Color c) const;
Bitboard sliders_of_color(Color c) const;
// Number of pieces of each color and type // Number of pieces of each color and type
int piece_count(Color c, PieceType pt) const; int piece_count(Color c, PieceType pt) const;
int pawn_count(Color c) const;
int knight_count(Color c) const;
int bishop_count(Color c) const;
int rook_count(Color c) const;
int queen_count(Color c) const;
// The en passant square: // The en passant square
Square ep_square() const; Square ep_square() const;
// Current king position for each color // Current king position for each color
Square king_square(Color c) const; Square king_square(Color c) const;
// Castling rights. // Castling rights
bool can_castle_kingside(Color c) const; bool can_castle_kingside(Color c) const;
bool can_castle_queenside(Color c) const; bool can_castle_queenside(Color c) const;
bool can_castle(Color c) const; bool can_castle(Color c) const;
Square initial_kr_square(Color c) const; Square initial_kr_square(Color c) const;
Square initial_qr_square(Color c) const; Square initial_qr_square(Color c) const;
// Attack bitboards
Bitboard sliding_attacks(Square s, Direction d) const;
Bitboard ray_attacks(Square s, SignedDirection d) const;
Bitboard pawn_attacks(Color c, Square s) const;
Bitboard white_pawn_attacks(Square s) const;
Bitboard black_pawn_attacks(Square s) const;
Bitboard knight_attacks(Square s) const;
Bitboard bishop_attacks(Square s) const;
Bitboard rook_attacks(Square s) const;
Bitboard queen_attacks(Square s) const;
Bitboard king_attacks(Square s) const;
// Bitboards for pinned pieces and discovered check candidates // Bitboards for pinned pieces and discovered check candidates
Bitboard discovered_check_candidates(Color c) const; Bitboard discovered_check_candidates(Color c) const;
Bitboard pinned_pieces(Color c) const; Bitboard pinned_pieces(Color c) const;
// Checking pieces // Checking pieces and under check information
Bitboard checkers() const; Bitboard checkers() const;
// Piece lists:
Square piece_list(Color c, PieceType pt, int index) const;
Square pawn_list(Color c, int index) const;
Square knight_list(Color c, int index) const;
Square bishop_list(Color c, int index) const;
Square rook_list(Color c, int index) const;
Square queen_list(Color c, int index) const;
// Attack information for a given square
bool square_is_attacked(Square s, Color c) const;
Bitboard attacks_to(Square s) const;
Bitboard attacks_to(Square s, Color c) const;
bool is_check() const; bool is_check() const;
bool piece_attacks_square(Square f, Square t) const;
bool white_pawn_attacks_square(Square f, Square t) const; // Piece lists
bool black_pawn_attacks_square(Square f, Square t) const; Square piece_list(Color c, PieceType pt, int index) const;
bool knight_attacks_square(Square f, Square t) const; const Square* piece_list_begin(Color c, PieceType pt) const;
bool bishop_attacks_square(Square f, Square t) const;
bool rook_attacks_square(Square f, Square t) const; // Information about attacks to or from a given square
bool queen_attacks_square(Square f, Square t) const; Bitboard attackers_to(Square s) const;
bool king_attacks_square(Square f, Square t) const; Bitboard attacks_from(Piece p, Square s) const;
template<PieceType> Bitboard attacks_from(Square s) const;
template<PieceType> Bitboard attacks_from(Square s, Color c) const;
// Properties of moves // Properties of moves
bool move_is_legal(Move m) const; bool pl_move_is_legal(Move m) const;
bool move_is_legal(Move m, Bitboard pinned) const; bool pl_move_is_legal(Move m, Bitboard pinned) const;
bool move_is_check(Move m) const; bool move_is_check(Move m) const;
bool move_is_check(Move m, Bitboard dcCandidates) const; bool move_is_check(Move m, Bitboard dcCandidates) const;
bool move_is_capture(Move m) const; bool move_is_capture(Move m) const;
bool move_is_pawn_push_to_7th(Move m) const;
bool move_is_passed_pawn_push(Move m) const; bool move_is_passed_pawn_push(Move m) const;
bool move_was_passed_pawn_push(Move m) const;
bool move_attacks_square(Move m, Square s) const; bool move_attacks_square(Move m, Square s) const;
// Information about pawns // Information about pawns
bool pawn_is_passed(Color c, Square s) const; bool pawn_is_passed(Color c, Square s) const;
bool pawn_is_isolated(Color c, Square s) const; static bool pawn_is_passed(Bitboard theirPawns, Color c, Square s);
bool pawn_is_doubled(Color c, Square s) const; static bool pawn_is_isolated(Bitboard ourPawns, Square s);
static bool pawn_is_doubled(Bitboard ourPawns, Color c, Square s);
// Open and half-open files
bool file_is_open(File f) const;
bool file_is_half_open(Color c, File f) const;
// Weak squares // Weak squares
bool square_is_weak(Square s, Color c) const; bool square_is_weak(Square s, Color c) const;
// Doing and undoing moves // Doing and undoing moves
void backup(UndoInfo &u) const; void saveState();
void restore(const UndoInfo &u); void do_move(Move m, StateInfo& st);
void do_move(Move m, UndoInfo &u); void do_move(Move m, StateInfo& st, Bitboard dcCandidates);
void do_move(Move m, UndoInfo &u, Bitboard dcCandidates); void undo_move(Move m);
void undo_move(Move m, const UndoInfo &u); void do_null_move(StateInfo& st);
void do_null_move(UndoInfo &u); void undo_null_move();
void undo_null_move(const UndoInfo &u);
// Static exchange evaluation // Static exchange evaluation
int see(Square from, Square to) const; int see(Square from, Square to) const;
int see(Move m) const; int see(Move m) const;
int see(Square to) const;
int see_sign(Move m) const;
// Accessing hash keys // Accessing hash keys
Key get_key() const; Key get_key() const;
@@ -267,9 +243,10 @@ public:
Value eg_value() const; Value eg_value() const;
Value non_pawn_material(Color c) const; Value non_pawn_material(Color c) const;
Phase game_phase() const; Phase game_phase() const;
template<GamePhase> Value pst_delta(Piece piece, Square from, Square to) const;
// Game termination checks // Game termination checks
bool is_mate(); bool is_mate() const;
bool is_draw() const; bool is_draw() const;
// Check if one side threatens a mate in one // Check if one side threatens a mate in one
@@ -286,13 +263,14 @@ public:
void reset_game_ply(); void reset_game_ply();
// Position consistency check, for debugging // Position consistency check, for debugging
bool is_ok() const; bool is_ok(int* failedStep = NULL) const;
// Static member functions: // Static member functions
static void init_zobrist(); static void init_zobrist();
static void init_piece_square_tables(); static void init_piece_square_tables();
private: private:
// Initialization helper functions (used while setting up a position) // Initialization helper functions (used while setting up a position)
void clear(); void clear();
void put_piece(Piece p, Square s); void put_piece(Piece p, Square s);
@@ -300,51 +278,47 @@ private:
void allow_ooo(Color c); void allow_ooo(Color c);
// Helper functions for doing and undoing moves // Helper functions for doing and undoing moves
void do_capture_move(Bitboard& key, PieceType capture, Color them, Square to, bool ep);
void do_castle_move(Move m); void do_castle_move(Move m);
void do_promotion_move(Move m, UndoInfo &u);
void do_ep_move(Move m);
void undo_castle_move(Move m); void undo_castle_move(Move m);
void undo_promotion_move(Move m, const UndoInfo &u);
void undo_ep_move(Move m);
void find_checkers(); void find_checkers();
template<PieceType Piece>
void update_checkers(Bitboard* pCheckersBB, Square ksq, Square from, Square to, Bitboard dcCandidates);
template<bool FindPinned>
Bitboard hidden_checkers(Color c) const;
// Computing hash keys from scratch (for initialization and debugging) // Computing hash keys from scratch (for initialization and debugging)
Key compute_key() const; Key compute_key() const;
Key compute_pawn_key() const; Key compute_pawn_key() const;
Key compute_material_key() const; Key compute_material_key() const;
// Computing incremental evaluation scores and material counts // Computing incremental evaluation scores and material counts
Value mg_pst(Color c, PieceType pt, Square s) const; template<GamePhase> Value pst(Color c, PieceType pt, Square s) const;
Value eg_pst(Color c, PieceType pt, Square s) const; template<GamePhase> Value compute_value() const;
Value compute_mg_value() const;
Value compute_eg_value() const;
Value compute_non_pawn_material(Color c) const; Value compute_non_pawn_material(Color c) const;
// Bitboards
Bitboard byColorBB[2], byTypeBB[8];
Bitboard checkersBB;
// Board // Board
Piece board[64]; Piece board[64];
// Bitboards
Bitboard byTypeBB[8], byColorBB[2];
// Piece counts // Piece counts
int pieceCount[2][8]; // [color][pieceType] int pieceCount[2][8]; // [color][pieceType]
// Piece lists // Piece lists
Square pieceList[2][8][16]; // [color][pieceType][index] Square pieceList[2][8][16]; // [color][pieceType][index]
int index[64]; int index[64]; // [square]
// Other info // Other info
Color sideToMove; Color sideToMove;
int castleRights; int gamePly;
Key history[MaxGameLength];
File initialKFile, initialKRFile, initialQRFile; File initialKFile, initialKRFile, initialQRFile;
Square epSquare; StateInfo startState;
Square kingSquare[2]; StateInfo* st;
Move lastMove;
Key key, pawnKey, materialKey, history[MaxGameLength];
int rule50, gamePly;
Value mgValue, egValue;
Value npMaterial[2];
// Static variables // Static variables
static int castleRightsMask[64]; static int castleRightsMask[64];
@@ -367,27 +341,27 @@ inline Piece Position::piece_on(Square s) const {
} }
inline Color Position::color_of_piece_on(Square s) const { inline Color Position::color_of_piece_on(Square s) const {
return color_of_piece(this->piece_on(s)); return color_of_piece(piece_on(s));
} }
inline PieceType Position::type_of_piece_on(Square s) const { inline PieceType Position::type_of_piece_on(Square s) const {
return type_of_piece(this->piece_on(s)); return type_of_piece(piece_on(s));
} }
inline bool Position::square_is_empty(Square s) const { inline bool Position::square_is_empty(Square s) const {
return this->piece_on(s) == EMPTY; return piece_on(s) == EMPTY;
} }
inline bool Position::square_is_occupied(Square s) const { inline bool Position::square_is_occupied(Square s) const {
return !this->square_is_empty(s); return !square_is_empty(s);
} }
inline Value Position::midgame_value_of_piece_on(Square s) const { inline Value Position::midgame_value_of_piece_on(Square s) const {
return piece_value_midgame(this->piece_on(s)); return piece_value_midgame(piece_on(s));
} }
inline Value Position::endgame_value_of_piece_on(Square s) const { inline Value Position::endgame_value_of_piece_on(Square s) const {
return piece_value_endgame(this->piece_on(s)); return piece_value_endgame(piece_on(s));
} }
inline Color Position::side_to_move() const { inline Color Position::side_to_move() const {
@@ -399,156 +373,55 @@ inline Bitboard Position::occupied_squares() const {
} }
inline Bitboard Position::empty_squares() const { inline Bitboard Position::empty_squares() const {
return ~(this->occupied_squares()); return ~(occupied_squares());
} }
inline Bitboard Position::pieces_of_color(Color c) const { inline Bitboard Position::pieces_of_color(Color c) const {
return byColorBB[c]; return byColorBB[c];
} }
inline Bitboard Position::pieces_of_type(PieceType pt) const { inline Bitboard Position::pieces(PieceType pt) const {
return byTypeBB[pt]; return byTypeBB[pt];
} }
inline Bitboard Position::pieces_of_color_and_type(Color c, PieceType pt) inline Bitboard Position::pieces(PieceType pt, Color c) const {
const { return byTypeBB[pt] & byColorBB[c];
return this->pieces_of_color(c) & this->pieces_of_type(pt);
} }
inline Bitboard Position::pawns() const { inline Bitboard Position::pieces(PieceType pt1, PieceType pt2) const {
return this->pieces_of_type(PAWN); return byTypeBB[pt1] | byTypeBB[pt2];
} }
inline Bitboard Position::knights() const { inline Bitboard Position::pieces(PieceType pt1, PieceType pt2, Color c) const {
return this->pieces_of_type(KNIGHT); return (byTypeBB[pt1] | byTypeBB[pt2]) & byColorBB[c];
}
inline Bitboard Position::bishops() const {
return this->pieces_of_type(BISHOP);
}
inline Bitboard Position::rooks() const {
return this->pieces_of_type(ROOK);
}
inline Bitboard Position::queens() const {
return this->pieces_of_type(QUEEN);
}
inline Bitboard Position::kings() const {
return this->pieces_of_type(KING);
}
inline Bitboard Position::rooks_and_queens() const {
return this->rooks() | this->queens();
}
inline Bitboard Position::bishops_and_queens() const {
return this->bishops() | this->queens();
}
inline Bitboard Position::sliders() const {
return this->bishops() | this->queens() | this->rooks();
}
inline Bitboard Position::pawns(Color c) const {
return this->pieces_of_color_and_type(c, PAWN);
}
inline Bitboard Position::knights(Color c) const {
return this->pieces_of_color_and_type(c, KNIGHT);
}
inline Bitboard Position::bishops(Color c) const {
return this->pieces_of_color_and_type(c, BISHOP);
}
inline Bitboard Position::rooks(Color c) const {
return this->pieces_of_color_and_type(c, ROOK);
}
inline Bitboard Position::queens(Color c) const {
return this->pieces_of_color_and_type(c, QUEEN);
}
inline Bitboard Position::kings(Color c) const {
return this->pieces_of_color_and_type(c, KING);
}
inline Bitboard Position::rooks_and_queens(Color c) const {
return this->rooks_and_queens() & this->pieces_of_color(c);
}
inline Bitboard Position::bishops_and_queens(Color c) const {
return this->bishops_and_queens() & this->pieces_of_color(c);
}
inline Bitboard Position::sliders_of_color(Color c) const {
return this->sliders() & this->pieces_of_color(c);
} }
inline int Position::piece_count(Color c, PieceType pt) const { inline int Position::piece_count(Color c, PieceType pt) const {
return pieceCount[c][pt]; return pieceCount[c][pt];
} }
inline int Position::pawn_count(Color c) const {
return this->piece_count(c, PAWN);
}
inline int Position::knight_count(Color c) const {
return this->piece_count(c, KNIGHT);
}
inline int Position::bishop_count(Color c) const {
return this->piece_count(c, BISHOP);
}
inline int Position::rook_count(Color c) const {
return this->piece_count(c, ROOK);
}
inline int Position::queen_count(Color c) const {
return this->piece_count(c, QUEEN);
}
inline Square Position::piece_list(Color c, PieceType pt, int index) const { inline Square Position::piece_list(Color c, PieceType pt, int index) const {
return pieceList[c][pt][index]; return pieceList[c][pt][index];
} }
inline Square Position::pawn_list(Color c, int index) const { inline const Square* Position::piece_list_begin(Color c, PieceType pt) const {
return this->piece_list(c, PAWN, index); return pieceList[c][pt];
}
inline Square Position::knight_list(Color c, int index) const {
return this->piece_list(c, KNIGHT, index);
}
inline Square Position::bishop_list(Color c, int index) const {
return this->piece_list(c, BISHOP, index);
}
inline Square Position::rook_list(Color c, int index) const {
return this->piece_list(c, ROOK, index);
}
inline Square Position::queen_list(Color c, int index) const {
return this->piece_list(c, QUEEN, index);
} }
inline Square Position::ep_square() const { inline Square Position::ep_square() const {
return epSquare; return st->epSquare;
} }
inline Square Position::king_square(Color c) const { inline Square Position::king_square(Color c) const {
return kingSquare[c]; return pieceList[c][KING][0];
} }
inline bool Position::can_castle_kingside(Color side) const { inline bool Position::can_castle_kingside(Color side) const {
return castleRights & (1+int(side)); return st->castleRights & (1+int(side));
} }
inline bool Position::can_castle_queenside(Color side) const { inline bool Position::can_castle_queenside(Color side) const {
return castleRights & (4+4*int(side)); return st->castleRights & (4+4*int(side));
} }
inline bool Position::can_castle(Color side) const { inline bool Position::can_castle(Color side) const {
@@ -563,140 +436,102 @@ inline Square Position::initial_qr_square(Color c) const {
return relative_square(c, make_square(initialQRFile, RANK_1)); return relative_square(c, make_square(initialQRFile, RANK_1));
} }
inline Bitboard Position::pawn_attacks(Color c, Square s) const { template<>
return StepAttackBB[pawn_of_color(c)][s]; inline Bitboard Position::attacks_from<PAWN>(Square s, Color c) const {
return StepAttackBB[piece_of_color_and_type(c, PAWN)][s];
} }
inline Bitboard Position::white_pawn_attacks(Square s) const { template<PieceType Piece> // Knight and King and white pawns
return this->pawn_attacks(WHITE, s); inline Bitboard Position::attacks_from(Square s) const {
return StepAttackBB[Piece][s];
} }
inline Bitboard Position::black_pawn_attacks(Square s) const { template<>
return this->pawn_attacks(BLACK, s); inline Bitboard Position::attacks_from<BISHOP>(Square s) const {
return bishop_attacks_bb(s, occupied_squares());
} }
inline Bitboard Position::knight_attacks(Square s) const { template<>
return StepAttackBB[KNIGHT][s]; inline Bitboard Position::attacks_from<ROOK>(Square s) const {
return rook_attacks_bb(s, occupied_squares());
} }
inline Bitboard Position::rook_attacks(Square s) const { template<>
return rook_attacks_bb(s, this->occupied_squares()); inline Bitboard Position::attacks_from<QUEEN>(Square s) const {
} return attacks_from<ROOK>(s) | attacks_from<BISHOP>(s);
inline Bitboard Position::bishop_attacks(Square s) const {
return bishop_attacks_bb(s, this->occupied_squares());
}
inline Bitboard Position::queen_attacks(Square s) const {
return this->rook_attacks(s) | this->bishop_attacks(s);
}
inline Bitboard Position::king_attacks(Square s) const {
return StepAttackBB[KING][s];
} }
inline Bitboard Position::checkers() const { inline Bitboard Position::checkers() const {
return checkersBB; return st->checkersBB;
} }
inline bool Position::is_check() const { inline bool Position::is_check() const {
return this->checkers() != EmptyBoardBB; return st->checkersBB != EmptyBoardBB;
}
inline bool Position::white_pawn_attacks_square(Square f, Square t) const {
return bit_is_set(this->white_pawn_attacks(f), t);
}
inline bool Position::black_pawn_attacks_square(Square f, Square t) const {
return bit_is_set(this->black_pawn_attacks(f), t);
}
inline bool Position::knight_attacks_square(Square f, Square t) const {
return bit_is_set(this->knight_attacks(f), t);
}
inline bool Position::bishop_attacks_square(Square f, Square t) const {
return bit_is_set(this->bishop_attacks(f), t);
}
inline bool Position::rook_attacks_square(Square f, Square t) const {
return bit_is_set(this->rook_attacks(f), t);
}
inline bool Position::queen_attacks_square(Square f, Square t) const {
return bit_is_set(this->queen_attacks(f), t);
}
inline bool Position::king_attacks_square(Square f, Square t) const {
return bit_is_set(this->king_attacks(f), t);
} }
inline bool Position::pawn_is_passed(Color c, Square s) const { inline bool Position::pawn_is_passed(Color c, Square s) const {
return !(this->pawns(opposite_color(c)) & passed_pawn_mask(c, s)); return !(pieces(PAWN, opposite_color(c)) & passed_pawn_mask(c, s));
} }
inline bool Position::pawn_is_isolated(Color c, Square s) const { inline bool Position::pawn_is_passed(Bitboard theirPawns, Color c, Square s) {
return !(this->pawns(c) & neighboring_files_bb(s)); return !(theirPawns & passed_pawn_mask(c, s));
} }
inline bool Position::pawn_is_doubled(Color c, Square s) const { inline bool Position::pawn_is_isolated(Bitboard ourPawns, Square s) {
return this->pawns(c) & squares_behind(c, s); return !(ourPawns & neighboring_files_bb(s));
} }
inline bool Position::file_is_open(File f) const { inline bool Position::pawn_is_doubled(Bitboard ourPawns, Color c, Square s) {
return !(this->pawns() & file_bb(f)); return ourPawns & squares_behind(c, s);
}
inline bool Position::file_is_half_open(Color c, File f) const {
return !(this->pawns(c) & file_bb(f));
} }
inline bool Position::square_is_weak(Square s, Color c) const { inline bool Position::square_is_weak(Square s, Color c) const {
return !(this->pawns(c) & outpost_mask(opposite_color(c), s)); return !(pieces(PAWN, c) & outpost_mask(opposite_color(c), s));
} }
inline Key Position::get_key() const { inline Key Position::get_key() const {
return key; return st->key;
} }
inline Key Position::get_pawn_key() const { inline Key Position::get_pawn_key() const {
return pawnKey; return st->pawnKey;
} }
inline Key Position::get_material_key() const { inline Key Position::get_material_key() const {
return materialKey; return st->materialKey;
} }
inline Value Position::mg_pst(Color c, PieceType pt, Square s) const { template<Position::GamePhase Ph>
return MgPieceSquareTable[piece_of_color_and_type(c, pt)][s]; inline Value Position::pst(Color c, PieceType pt, Square s) const {
return (Ph == MidGame ? MgPieceSquareTable[piece_of_color_and_type(c, pt)][s]
: EgPieceSquareTable[piece_of_color_and_type(c, pt)][s]);
} }
inline Value Position::eg_pst(Color c, PieceType pt, Square s) const { template<Position::GamePhase Ph>
return EgPieceSquareTable[piece_of_color_and_type(c, pt)][s]; inline Value Position::pst_delta(Piece piece, Square from, Square to) const {
return (Ph == MidGame ? MgPieceSquareTable[piece][to] - MgPieceSquareTable[piece][from]
: EgPieceSquareTable[piece][to] - EgPieceSquareTable[piece][from]);
} }
inline Value Position::mg_value() const { inline Value Position::mg_value() const {
return mgValue; return st->mgValue;
} }
inline Value Position::eg_value() const { inline Value Position::eg_value() const {
return egValue; return st->egValue;
} }
inline Value Position::non_pawn_material(Color c) const { inline Value Position::non_pawn_material(Color c) const {
return npMaterial[c]; return st->npMaterial[c];
} }
inline Phase Position::game_phase() const { inline Phase Position::game_phase() const {
// The purpose of the Value(325) terms below is to make sure the difference // Values modified by Joona Kiiski
// between MidgameLimit and EndgameLimit is a power of 2, which should make static const Value MidgameLimit = Value(15581);
// the division at the end of the function a bit faster. static const Value EndgameLimit = Value(3998);
static const Value MidgameLimit = Value npm = non_pawn_material(WHITE) + non_pawn_material(BLACK);
2*QueenValueMidgame+2*RookValueMidgame+6*BishopValueMidgame+Value(325);
static const Value EndgameLimit = 4*RookValueMidgame-Value(325);
Value npm = this->non_pawn_material(WHITE) + this->non_pawn_material(BLACK);
if (npm >= MidgameLimit) if (npm >= MidgameLimit)
return PHASE_MIDGAME; return PHASE_MIDGAME;
@@ -706,41 +541,35 @@ inline Phase Position::game_phase() const {
return Phase(((npm - EndgameLimit) * 128) / (MidgameLimit - EndgameLimit)); return Phase(((npm - EndgameLimit) * 128) / (MidgameLimit - EndgameLimit));
} }
inline bool Position::move_is_pawn_push_to_7th(Move m) const {
Color c = this->side_to_move();
return
this->piece_on(move_from(m)) == pawn_of_color(c) &&
pawn_rank(c, move_to(m)) == RANK_7;
}
inline bool Position::move_is_passed_pawn_push(Move m) const { inline bool Position::move_is_passed_pawn_push(Move m) const {
Color c = this->side_to_move();
return
this->piece_on(move_from(m)) == pawn_of_color(c) &&
this->pawn_is_passed(c, move_to(m));
}
inline bool Position::move_was_passed_pawn_push(Move m) const { Color c = side_to_move();
Color c = opposite_color(this->side_to_move()); return piece_on(move_from(m)) == piece_of_color_and_type(c, PAWN)
return && pawn_is_passed(c, move_to(m));
this->piece_on(move_to(m)) == pawn_of_color(c) &&
this->pawn_is_passed(c, move_to(m));
} }
inline int Position::rule_50_counter() const { inline int Position::rule_50_counter() const {
return rule50;
return st->rule50;
} }
inline bool Position::opposite_colored_bishops() const { inline bool Position::opposite_colored_bishops() const {
return
this->bishop_count(WHITE) == 1 && this->bishop_count(BLACK) == 1 && return piece_count(WHITE, BISHOP) == 1
square_color(this->bishop_list(WHITE, 0)) != && piece_count(BLACK, BISHOP) == 1
square_color(this->bishop_list(BLACK, 0)); && square_color(piece_list(WHITE, BISHOP, 0)) != square_color(piece_list(BLACK, BISHOP, 0));
} }
inline bool Position::has_pawn_on_7th(Color c) const { inline bool Position::has_pawn_on_7th(Color c) const {
return this->pawns(c) & relative_rank_bb(c, RANK_7);
return pieces(PAWN, c) & relative_rank_bb(c, RANK_7);
} }
inline bool Position::move_is_capture(Move m) const {
// Move must not be MOVE_NONE !
return (!square_is_empty(move_to(m)) && !move_is_castle(m)) || move_is_ep(m);
}
#endif // !defined(POSITION_H_INCLUDED) #endif // !defined(POSITION_H_INCLUDED)
+122 -98
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -24,139 +25,162 @@
//// Includes //// Includes
//// ////
#include "position.h" #include "value.h"
//// ////
//// Variables //// Constants modified by Joona Kiiski
//// ////
static const Value MP = PawnValueMidgame;
static const Value MK = KnightValueMidgame;
static const Value MB = BishopValueMidgame;
static const Value MR = RookValueMidgame;
static const Value MQ = QueenValueMidgame;
static const int MgPST[][64] = { static const int MgPST[][64] = {
{ }, { },
{// Pawn {// Pawn
// A B C D E F G H
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
166, 192, 204, 216, 216, 204, 192, 166, MP-28, MP-6, MP+ 4, MP+14, MP+14, MP+ 4, MP-6, MP-28,
166, 192, 210, 242, 242, 210, 192, 166, MP-28, MP-6, MP+ 9, MP+36, MP+36, MP+ 9, MP-6, MP-28,
166, 192, 220, 268, 268, 220, 192, 166, MP-28, MP-6, MP+17, MP+58, MP+58, MP+17, MP-6, MP-28,
166, 192, 220, 242, 242, 220, 192, 166, MP-28, MP-6, MP+17, MP+36, MP+36, MP+17, MP-6, MP-28,
166, 192, 210, 216, 216, 210, 192, 166, MP-28, MP-6, MP+ 9, MP+14, MP+14, MP+ 9, MP-6, MP-28,
166, 192, 204, 216, 216, 204, 192, 166, MP-28, MP-6, MP+ 4, MP+14, MP+14, MP+ 4, MP-6, MP-28,
0, 0, 0, 0, 0, 0, 0, 0 0, 0, 0, 0, 0, 0, 0, 0
}, },
{// Knight {// Knight
704, 730, 756, 768, 768, 756, 730, 704, // A B C D E F G H
743, 768, 794, 807, 807, 794, 768, 743, MK-135, MK-107, MK-80, MK-67, MK-67, MK-80, MK-107, MK-135,
781, 807, 832, 844, 844, 832, 807, 781, MK- 93, MK- 67, MK-39, MK-25, MK-25, MK-39, MK- 67, MK- 93,
807, 832, 857, 870, 870, 857, 832, 807, MK- 53, MK- 25, MK+ 1, MK+13, MK+13, MK+ 1, MK- 25, MK- 53,
820, 844, 870, 883, 883, 870, 844, 820, MK- 25, MK+ 1, MK+27, MK+41, MK+41, MK+27, MK+ 1, MK- 25,
820, 844, 870, 883, 883, 870, 844, 820, MK- 11, MK+ 13, MK+41, MK+55, MK+55, MK+41, MK+ 13, MK- 11,
781, 807, 832, 844, 844, 832, 807, 781, MK- 11, MK+ 13, MK+41, MK+55, MK+55, MK+41, MK+ 13, MK- 11,
650, 768, 794, 807, 807, 794, 768, 650 MK- 53, MK- 25, MK+ 1, MK+13, MK+13, MK+ 1, MK- 25, MK- 53,
MK-193, MK- 67, MK-39, MK-25, MK-25, MK-39, MK- 67, MK-193
}, },
{// Bishop {// Bishop
786, 786, 792, 797, 797, 792, 786, 786, // A B C D E F G H
812, 832, 827, 832, 832, 827, 832, 812, MB-40, MB-40, MB-35, MB-30, MB-30, MB-35, MB-40, MB-40,
817, 827, 842, 837, 837, 842, 827, 817, MB-17, MB+ 0, MB- 4, MB+ 0, MB+ 0, MB- 4, MB+ 0, MB-17,
822, 832, 837, 852, 852, 837, 832, 822, MB-13, MB- 4, MB+ 8, MB+ 4, MB+ 4, MB+ 8, MB- 4, MB-13,
822, 832, 837, 852, 852, 837, 832, 822, MB- 8, MB+ 0, MB+ 4, MB+17, MB+17, MB+ 4, MB+ 0, MB- 8,
817, 827, 842, 837, 837, 842, 827, 817, MB- 8, MB+ 0, MB+ 4, MB+17, MB+17, MB+ 4, MB+ 0, MB- 8,
812, 832, 827, 832, 832, 827, 832, 812, MB-13, MB- 4, MB+ 8, MB+ 4, MB+ 4, MB+ 8, MB- 4, MB-13,
812, 812, 817, 822, 822, 817, 812, 812 MB-17, MB+ 0, MB- 4, MB+ 0, MB+ 0, MB- 4, MB+ 0, MB-17,
MB-17, MB-17, MB-13, MB- 8, MB- 8, MB-13, MB-17, MB-17
}, },
{// Rook {// Rook
1267, 1275, 1282, 1289, 1289, 1282, 1275, 1267, // A B C D E F G H
1267, 1275, 1282, 1289, 1289, 1282, 1275, 1267, MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
1267, 1275, 1282, 1289, 1289, 1282, 1275, 1267, MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
1267, 1275, 1282, 1289, 1289, 1282, 1275, 1267, MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
1267, 1275, 1282, 1289, 1289, 1282, 1275, 1267, MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
1267, 1275, 1282, 1289, 1289, 1282, 1275, 1267, MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
1267, 1275, 1282, 1289, 1289, 1282, 1275, 1267, MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
1267, 1275, 1282, 1289, 1289, 1282, 1275, 1267 MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12,
MR-12, MR-7, MR-2, MR+2, MR+2, MR-2, MR-7, MR-12
}, },
{// Queen {// Queen
2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, // A B C D E F G H
2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
2560, 2560, 2560, 2560, 2560, 2560, 2560, 2560 MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8,
MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8, MQ+8
}, },
{// King {// King
302, 328, 276, 225, 225, 276, 328, 302, //A B C D E F G H
276, 302, 251, 200, 200, 251, 302, 276, 287, 311, 262, 214, 214, 262, 311, 287,
225, 251, 200, 149, 149, 200, 251, 225, 262, 287, 238, 190, 190, 238, 287, 262,
200, 225, 175, 124, 124, 175, 225, 200, 214, 238, 190, 142, 142, 190, 238, 214,
175, 200, 149, 98, 98, 149, 200, 175, 190, 214, 167, 119, 119, 167, 214, 190,
149, 175, 124, 72, 72, 124, 175, 149, 167, 190, 142, 94, 94, 142, 190, 167,
124, 149, 98, 47, 47, 98, 149, 124, 142, 167, 119, 69, 69, 119, 167, 142,
98, 124, 72, 21, 21, 72, 124, 98, 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] = { static const int EgPST[][64] = {
{ }, { },
{// Pawn {// Pawn
// A B C D E F G H
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
256, 256, 256, 256, 256, 256, 256, 256, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
256, 256, 256, 256, 256, 256, 256, 256, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
256, 256, 256, 256, 256, 256, 256, 256, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
256, 256, 256, 256, 256, 256, 256, 256, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
256, 256, 256, 256, 256, 256, 256, 256, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
256, 256, 256, 256, 256, 256, 256, 256, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8, EP-8,
0, 0, 0, 0, 0, 0, 0, 0 0, 0, 0, 0, 0, 0, 0, 0
}, },
{// Knight {// Knight
730, 756, 781, 794, 794, 781, 756, 730, // A B C D E F G H
756, 781, 807, 820, 820, 807, 781, 756, EK-104, EK-79, EK-55, EK-42, EK-42, EK-55, EK-79, EK-104,
781, 807, 832, 844, 844, 832, 807, 781, EK- 79, EK-55, EK-30, EK-17, EK-17, EK-30, EK-55, EK- 79,
794, 820, 844, 857, 857, 844, 820, 794, EK- 55, EK-30, EK- 6, EK+ 5, EK+ 5, EK- 6, EK-30, EK- 55,
794, 820, 844, 857, 857, 844, 820, 794, EK- 42, EK-17, EK+ 5, EK+18, EK+18, EK+ 5, EK-17, EK- 42,
781, 807, 832, 844, 844, 832, 807, 781, EK- 42, EK-17, EK+ 5, EK+18, EK+18, EK+ 5, EK-17, EK- 42,
756, 781, 807, 820, 820, 807, 781, 756, EK- 55, EK-30, EK- 6, EK+ 5, EK+ 5, EK- 6, EK-30, EK- 55,
730, 756, 781, 794, 794, 781, 756, 730 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 {// Bishop
786, 802, 809, 817, 817, 809, 802, 786, // A B C D E F G H
802, 817, 825, 832, 832, 825, 817, 802, EB-59, EB-42, EB-35, EB-26, EB-26, EB-35, EB-42, EB-59,
809, 825, 832, 839, 839, 832, 825, 809, EB-42, EB-26, EB-18, EB-11, EB-11, EB-18, EB-26, EB-42,
817, 832, 839, 847, 847, 839, 832, 817, EB-35, EB-18, EB-11, EB- 4, EB- 4, EB-11, EB-18, EB-35,
817, 832, 839, 847, 847, 839, 832, 817, EB-26, EB-11, EB- 4, EB+ 4, EB+ 4, EB- 4, EB-11, EB-26,
809, 825, 832, 839, 839, 832, 825, 809, EB-26, EB-11, EB- 4, EB+ 4, EB+ 4, EB- 4, EB-11, EB-26,
802, 817, 825, 832, 832, 825, 817, 802, EB-35, EB-18, EB-11, EB- 4, EB- 4, EB-11, EB-18, EB-35,
786, 802, 809, 817, 817, 809, 802, 786 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 {// Rook
1282, 1282, 1282, 1282, 1282, 1282, 1282, 1282, // A B C D E F G H
1282, 1282, 1282, 1282, 1282, 1282, 1282, 1282, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
1282, 1282, 1282, 1282, 1282, 1282, 1282, 1282, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
1282, 1282, 1282, 1282, 1282, 1282, 1282, 1282, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
1282, 1282, 1282, 1282, 1282, 1282, 1282, 1282, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
1282, 1282, 1282, 1282, 1282, 1282, 1282, 1282, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
1282, 1282, 1282, 1282, 1282, 1282, 1282, 1282, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3, ER+3,
1282, 1282, 1282, 1282, 1282, 1282, 1282, 1282 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 {// Queen
2499, 2520, 2530, 2540, 2540, 2530, 2520, 2499, // A B C D E F G H
2520, 2540, 2550, 2560, 2560, 2550, 2540, 2520, EQ-80, EQ-54, EQ-42, EQ-30, EQ-30, EQ-42, EQ-54, EQ-80,
2530, 2550, 2560, 2570, 2570, 2560, 2550, 2530, EQ-54, EQ-30, EQ-18, EQ- 6, EQ- 6, EQ-18, EQ-30, EQ-54,
2540, 2560, 2570, 2580, 2580, 2570, 2560, 2540, EQ-42, EQ-18, EQ- 6, EQ+ 6, EQ+ 6, EQ- 6, EQ-18, EQ-42,
2540, 2560, 2570, 2580, 2580, 2570, 2560, 2540, EQ-30, EQ- 6, EQ+ 6, EQ+18, EQ+18, EQ+ 6, EQ- 6, EQ-30,
2530, 2550, 2560, 2570, 2570, 2560, 2550, 2530, EQ-30, EQ- 6, EQ+ 6, EQ+18, EQ+18, EQ+ 6, EQ- 6, EQ-30,
2520, 2540, 2550, 2560, 2560, 2550, 2540, 2520, EQ-42, EQ-18, EQ- 6, EQ+ 6, EQ+ 6, EQ- 6, EQ-18, EQ-42,
2499, 2520, 2530, 2540, 2540, 2530, 2520, 2499 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 {// King
16, 78, 108, 139, 139, 108, 78, 16, //A B C D E F G H
78, 139, 170, 200, 200, 170, 139, 78, 18, 77, 105, 135, 135, 105, 77, 18,
108, 170, 200, 230, 230, 200, 170, 108, 77, 135, 165, 193, 193, 165, 135, 77,
139, 200, 230, 261, 261, 230, 200, 139, 105, 165, 193, 222, 222, 193, 165, 105,
139, 200, 230, 261, 261, 230, 200, 139, 135, 193, 222, 251, 251, 222, 193, 135,
108, 170, 200, 230, 230, 200, 170, 108, 135, 193, 222, 251, 251, 222, 193, 135,
78, 139, 170, 200, 200, 170, 139, 78, 105, 165, 193, 222, 222, 193, 165, 105,
16, 78, 108, 139, 139, 108, 78, 16 77, 135, 165, 193, 193, 165, 135, 77,
18, 77, 105, 135, 135, 105, 77, 18
} }
}; };
+211 -195
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -27,9 +28,11 @@
#include <string> #include <string>
#include <sstream> #include <sstream>
#include "history.h"
#include "movepick.h" #include "movepick.h"
#include "san.h" #include "san.h"
using std::string;
//// ////
//// Local definitions //// Local definitions
@@ -37,8 +40,6 @@
namespace { namespace {
/// Types
enum Ambiguity { enum Ambiguity {
AMBIGUITY_NONE, AMBIGUITY_NONE,
AMBIGUITY_FILE, AMBIGUITY_FILE,
@@ -46,12 +47,11 @@ namespace {
AMBIGUITY_BOTH AMBIGUITY_BOTH
}; };
const History H; // used as dummy argument for MovePicker c'tor
/// Functions Ambiguity move_ambiguity(const Position& pos, Move m);
const string time_string(int milliseconds);
Ambiguity move_ambiguity(Position &pos, Move m); const string score_string(Value v);
const std::string time_string(int milliseconds);
const std::string score_string(Value v);
} }
@@ -63,85 +63,72 @@ namespace {
/// that the move is a legal move from the position. The return value is /// that the move is a legal move from the position. The return value is
/// a string containing the move in short algebraic notation. /// a string containing the move in short algebraic notation.
const std::string move_to_san(Position &pos, Move m) { const string move_to_san(const Position& pos, Move m) {
std::string str;
assert(pos.is_ok()); assert(pos.is_ok());
assert(move_is_ok(m)); assert(move_is_ok(m));
if(m == MOVE_NONE) {
str = "(none)";
return str;
}
else if(m == MOVE_NULL) {
str = "(null)";
return str;
}
else if(move_is_long_castle(m))
str = "O-O-O";
else if(move_is_short_castle(m))
str = "O-O";
else {
Square from, to; Square from, to;
Piece pc; PieceType pt;
from = move_from(m); from = move_from(m);
to = move_to(m); to = move_to(m);
pc = pos.piece_on(move_from(m)); pt = type_of_piece(pos.piece_on(move_from(m)));
str = ""; string san = "";
if(type_of_piece(pc) == PAWN) {
if(pos.move_is_capture(m))
str += file_to_char(square_file(move_from(m)));
}
else {
str += piece_type_to_char(type_of_piece(pc), true);
Ambiguity amb = move_ambiguity(pos, m);
switch(amb) {
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: case AMBIGUITY_NONE:
break; break;
case AMBIGUITY_FILE: case AMBIGUITY_FILE:
str += file_to_char(square_file(from)); san += file_to_char(square_file(from));
break; break;
case AMBIGUITY_RANK: case AMBIGUITY_RANK:
str += rank_to_char(square_rank(from)); san += rank_to_char(square_rank(from));
break; break;
case AMBIGUITY_BOTH: case AMBIGUITY_BOTH:
str += square_to_string(from); san += square_to_string(from);
break; break;
default: default:
assert(false); assert(false);
} }
} }
if (pos.move_is_capture(m)) if (pos.move_is_capture(m))
str += "x"; {
if (pt == PAWN)
str += square_to_string(move_to(m)); san += file_to_char(square_file(move_from(m)));
san += "x";
if(move_promotion(m)) { }
str += "="; san += square_to_string(move_to(m));
str += piece_type_to_char(move_promotion(m), true); if (move_is_promotion(m))
{
san += '=';
san += piece_type_to_char(move_promotion_piece(m), true);
} }
} }
// Is the move check? We don't use pos.move_is_check(m) here, because // Is the move check? We don't use pos.move_is_check(m) here, because
// Position::move_is_check doesn't detect all checks (not castling moves, // Position::move_is_check doesn't detect all checks (not castling moves,
// promotions and en passant captures). // promotions and en passant captures).
UndoInfo u; StateInfo st;
pos.do_move(m, u); Position p(pos);
if(pos.is_check()) p.do_move(m, st);
str += pos.is_mate()? "#" : "+"; if (p.is_check())
pos.undo_move(m, u); san += p.is_mate()? "#" : "+";
return str; return san;
} }
@@ -150,116 +137,150 @@ const std::string move_to_san(Position &pos, Move m) {
/// the move is returned. On failure (i.e. if the string is unparsable, or /// 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. /// if the move is illegal or ambiguous), MOVE_NONE is returned.
Move move_from_san(Position &pos, const std::string &movestr) { Move move_from_san(const Position& pos, const string& movestr) {
assert(pos.is_ok()); assert(pos.is_ok());
MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE, MovePicker mp = MovePicker(pos, MOVE_NONE, OnePly, H);
MOVE_NONE, OnePly);
// Castling moves // Castling moves
if(movestr == "O-O-O") { if (movestr == "O-O-O" || movestr == "O-O-O+")
{
Move m; Move m;
while ((m = mp.get_next_move()) != MOVE_NONE) while ((m = mp.get_next_move()) != MOVE_NONE)
if(move_is_long_castle(m) && pos.move_is_legal(m)) if (move_is_long_castle(m) && pos.pl_move_is_legal(m))
return m; return m;
return MOVE_NONE; return MOVE_NONE;
} }
else if(movestr == "O-O") { else if (movestr == "O-O" || movestr == "O-O+")
{
Move m; Move m;
while ((m = mp.get_next_move()) != MOVE_NONE) while ((m = mp.get_next_move()) != MOVE_NONE)
if(move_is_short_castle(m) && pos.move_is_legal(m)) if (move_is_short_castle(m) && pos.pl_move_is_legal(m))
return m; return m;
return MOVE_NONE; return MOVE_NONE;
} }
// Normal moves // Normal moves. We use a simple FSM to parse the san string.
const char *cstr = movestr.c_str(); enum { START, TO_FILE, TO_RANK, PROMOTION_OR_CHECK, PROMOTION, CHECK, END };
const char *c; static const string pieceLetters = "KQRBN";
char *cc; PieceType pt = NO_PIECE_TYPE, promotion = NO_PIECE_TYPE;
char str[10]; File fromFile = FILE_NONE, toFile = FILE_NONE;
int i; Rank fromRank = RANK_NONE, toRank = RANK_NONE;
// Initialize str[] by making a copy of movestr with the characters
// 'x', '=', '+' and '#' removed.
cc = str;
for(i=0, c=cstr; i<10 && *c!='\0' && *c!='\n' && *c!=' '; i++, c++)
if(!strchr("x=+#", *c)) {
*cc = strchr("nrq", *c)? toupper(*c) : *c;
cc++;
}
*cc = '\0';
int left = 0, right = strlen(str) - 1;
PieceType pt = NO_PIECE_TYPE, promotion;
Square to; Square to;
File fromFile = FILE_NONE; int state = START;
Rank fromRank = RANK_NONE;
// Promotion? for (size_t i = 0; i < movestr.length(); i++)
if(strchr("BNRQ", str[right])) { {
promotion = piece_type_from_char(str[right]); char type, c = movestr[i];
right--; if (pieceLetters.find(c) != string::npos)
} type = 'P';
else else if (c >= 'a' && c <= 'h')
promotion = NO_PIECE_TYPE; type = 'F';
else if (c >= '1' && c <= '8')
// Find the moving piece: type = 'R';
if(left < right) { else
if(strchr("BNRQK", str[left])) { type = c;
pt = piece_type_from_char(str[left]);
left++; 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 else
return MOVE_NONE;
break;
case 'F':
if (state == START)
{
pt = PAWN; pt = PAWN;
fromFile = toFile = file_from_char(c);
state = TO_RANK;
} }
else if (state == TO_FILE)
// Find the to square: {
if(left < right) { toFile = file_from_char(c);
if(str[right] < '1' || str[right] > '8' || state = TO_RANK;
str[right-1] < 'a' || str[right-1] > 'h') }
return MOVE_NONE; else if (state == TO_RANK && toFile != FILE_NONE)
to = make_square(file_from_char(str[right-1]), rank_from_char(str[right])); {
right -= 2; // Previous file was for disambiguation
fromFile = toFile;
toFile = file_from_char(c);
} }
else else
return MOVE_NONE; return MOVE_NONE;
break;
// Find the file and/or rank of the from square: case 'R':
if(left <= right) { if (state == TO_RANK)
if(strchr("abcdefgh", str[left])) { {
fromFile = file_from_char(str[left]); toRank = rank_from_char(c);
left++; 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(strchr("12345678", str[left]))
fromRank = rank_from_char(str[left]);
} }
// Look for a matching move: if (state != END)
return MOVE_NONE;
// Look for a matching move
Move m, move = MOVE_NONE; Move m, move = MOVE_NONE;
to = make_square(toFile, toRank);
int matches = 0; int matches = 0;
while((m = mp.get_next_move()) != MOVE_NONE) { while ((m = mp.get_next_move()) != MOVE_NONE)
bool match = true; if ( pos.type_of_piece_on(move_from(m)) == pt
if(pos.type_of_piece_on(move_from(m)) != pt) && move_to(m) == to
match = false; && move_promotion_piece(m) == promotion
else if(move_to(m) != to) && (fromFile == FILE_NONE || fromFile == square_file(move_from(m)))
match = false; && (fromRank == RANK_NONE || fromRank == square_rank(move_from(m))))
else if(move_promotion(m) != promotion) {
match = false;
else if(fromFile != FILE_NONE && fromFile != square_file(move_from(m)))
match = false;
else if(fromRank != RANK_NONE && fromRank != square_rank(move_from(m)))
match = false;
if(match) {
move = m; move = m;
matches++; matches++;
} }
} return (matches == 1 ? move : MOVE_NONE);
if(matches == 1)
return move;
else
return MOVE_NONE;
} }
@@ -270,34 +291,31 @@ Move move_from_san(Position &pos, const std::string &movestr) {
/// length of 80 characters. After a line break, 'startColumn' spaces are /// length of 80 characters. After a line break, 'startColumn' spaces are
/// inserted at the beginning of the new line. /// inserted at the beginning of the new line.
const std::string line_to_san(const Position &pos, Move line[], int startColumn, const string line_to_san(const Position& pos, Move line[], int startColumn, bool breakLines) {
bool breakLines) {
Position p = Position(pos); StateInfo st;
UndoInfo u;
std::stringstream s; std::stringstream s;
std::string moveStr; string moveStr;
int length, maxLength; size_t length = 0;
size_t maxLength = 80 - startColumn;
Position p(pos);
length = 0; for (int i = 0; line[i] != MOVE_NONE; i++)
maxLength = 80 - startColumn; {
for(int i = 0; line[i] != MOVE_NONE; i++) {
moveStr = move_to_san(p, line[i]); moveStr = move_to_san(p, line[i]);
length += moveStr.length() + 1; length += moveStr.length() + 1;
if(breakLines && length > maxLength) { if (breakLines && length > maxLength)
s << "\n"; {
for(int j = 0; j < startColumn; j++) s << '\n' << std::setw(startColumn) << ' ';
s << " ";
length = moveStr.length() + 1; length = moveStr.length() + 1;
} }
s << moveStr << " "; s << moveStr << ' ';
if (line[i] == MOVE_NULL) if (line[i] == MOVE_NULL)
p.do_null_move(u); p.do_null_move(st);
else else
p.do_move(line[i], u); p.do_move(line[i], st);
} }
return s.str(); return s.str();
} }
@@ -306,26 +324,26 @@ const std::string line_to_san(const Position &pos, Move line[], int startColumn,
/// It is used to write search information to the log file (which is created /// It is used to write search information to the log file (which is created
/// when the UCI parameter "Use Search Log" is "true"). /// when the UCI parameter "Use Search Log" is "true").
const std::string pretty_pv(const Position &pos, int time, int depth, const string pretty_pv(const Position& pos, int time, int depth,
uint64_t nodes, Value score, Move pv[]) { uint64_t nodes, Value score, Move pv[]) {
std::stringstream s; std::stringstream s;
// Depth // Depth
s << std::setw(2) << std::setfill(' ') << depth << " "; s << std::setw(2) << depth << " ";
// Score // Score
s << std::setw(8) << score_string(score); s << std::setw(8) << score_string(score);
// Time // Time
s << std::setw(8) << std::setfill(' ') << time_string(time) << " "; s << std::setw(8) << time_string(time) << " ";
// Nodes // Nodes
if (nodes < 1000000ULL) if (nodes < 1000000ULL)
s << std::setw(8) << std::setfill(' ') << nodes << " "; s << std::setw(8) << nodes << " ";
else if (nodes < 1000000000ULL) else if (nodes < 1000000000ULL)
s << std::setw(7) << std::setfill(' ') << nodes/1000ULL << 'k' << " "; s << std::setw(7) << nodes/1000ULL << 'k' << " ";
else else
s << std::setw(7) << std::setfill(' ') << nodes/1000000ULL << 'M' << " "; s << std::setw(7) << nodes/1000000ULL << 'M' << " ";
// PV // PV
s << line_to_san(pos, pv, 30, true); s << line_to_san(pos, pv, 30, true);
@@ -336,82 +354,80 @@ const std::string pretty_pv(const Position &pos, int time, int depth,
namespace { namespace {
Ambiguity move_ambiguity(Position &pos, Move m) { Ambiguity move_ambiguity(const Position& pos, Move m) {
Square from, to;
Piece pc;
from = move_from(m); Square from = move_from(m);
to = move_to(m); Square to = move_to(m);
pc = pos.piece_on(from); Piece pc = pos.piece_on(from);
// King moves are never ambiguous, because there is never two kings of // King moves are never ambiguous, because there is never two kings of
// the same color. // the same color.
if (type_of_piece(pc) == KING) if (type_of_piece(pc) == KING)
return AMBIGUITY_NONE; return AMBIGUITY_NONE;
MovePicker mp = MovePicker(pos, false, MOVE_NONE, MOVE_NONE, MOVE_NONE, MovePicker mp = MovePicker(pos, MOVE_NONE, OnePly, H);
MOVE_NONE, OnePly);
Move mv, moveList[8]; Move mv, moveList[8];
int i, j, n;
n = 0; int n = 0;
while ((mv = mp.get_next_move()) != MOVE_NONE) while ((mv = mp.get_next_move()) != MOVE_NONE)
if(move_to(mv) == to && pos.piece_on(move_from(mv)) == pc if (move_to(mv) == to && pos.piece_on(move_from(mv)) == pc && pos.pl_move_is_legal(mv))
&& pos.move_is_legal(mv))
moveList[n++] = mv; moveList[n++] = mv;
if (n == 1) if (n == 1)
return AMBIGUITY_NONE; return AMBIGUITY_NONE;
j = 0; int f = 0, r = 0;
for(i = 0; i < n; i++) for (int i = 0; i < n; i++)
{
if (square_file(move_from(moveList[i])) == square_file(from)) if (square_file(move_from(moveList[i])) == square_file(from))
j++; f++;
if(j == 1)
if (square_rank(move_from(moveList[i])) == square_rank(from))
r++;
}
if (f == 1)
return AMBIGUITY_FILE; return AMBIGUITY_FILE;
j = 0; if (r == 1)
for(i = 0; i < n; i++)
if(square_rank(move_from(moveList[i])) == square_rank(from))
j++;
if(j == 1)
return AMBIGUITY_RANK; return AMBIGUITY_RANK;
return AMBIGUITY_BOTH; return AMBIGUITY_BOTH;
} }
const std::string time_string(int milliseconds) { const string time_string(int milliseconds) {
std::stringstream s; std::stringstream s;
s << std::setfill('0');
int hours = milliseconds / (1000*60*60); int hours = milliseconds / (1000*60*60);
int minutes = (milliseconds - hours*1000*60*60) / (60*1000); int minutes = (milliseconds - hours*1000*60*60) / (1000*60);
int seconds = (milliseconds - hours*1000*60*60 - minutes*60*1000) / 1000; int seconds = (milliseconds - hours*1000*60*60 - minutes*1000*60) / 1000;
if (hours) if (hours)
s << hours << ':'; s << hours << ':';
s << std::setw(2) << std::setfill('0') << minutes << ':';
s << std::setw(2) << std::setfill('0') << seconds;
s << std::setw(2) << minutes << ':' << std::setw(2) << seconds;
return s.str(); return s.str();
} }
const std::string score_string(Value v) { const string score_string(Value v) {
std::stringstream s; std::stringstream s;
if(abs(v) >= VALUE_MATE - 200) { if (v >= VALUE_MATE - 200)
if(v < 0) s << "#" << (VALUE_MATE - v + 1) / 2;
else if(v <= -VALUE_MATE + 200)
s << "-#" << (VALUE_MATE + v) / 2; s << "-#" << (VALUE_MATE + v) / 2;
else else
s << "#" << (VALUE_MATE - v + 1) / 2; {
}
else {
float floatScore = float(v) / float(PawnValueMidgame); float floatScore = float(v) / float(PawnValueMidgame);
if (v >= 0) if (v >= 0)
s << '+'; s << '+';
s << std::setprecision(2) << std::fixed << floatScore; s << std::setprecision(2) << std::fixed << floatScore;
} }
return s.str(); return s.str();
} }
} }
+9 -11
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -35,12 +36,9 @@
//// Prototypes //// Prototypes
//// ////
extern const std::string move_to_san(Position &pos, Move m); extern const std::string move_to_san(const Position& pos, Move m);
extern Move move_from_san(Position &pos, const std::string &str); extern Move move_from_san(const Position& pos, const std::string& str);
extern const std::string line_to_san(const Position &pos, Move line[], extern const std::string line_to_san(const Position& pos, Move line[], int startColumn, bool breakLines);
int startColumn, bool breakLines); extern const std::string pretty_pv(const Position& pos, int time, int depth, uint64_t nodes, Value score, Move pv[]);
extern const std::string pretty_pv(const Position &pos, int time, int depth,
uint64_t nodes, Value score, Move pv[]);
#endif // !defined(SAN_H_INCLUDED) #endif // !defined(SAN_H_INCLUDED)
+5 -4
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
+1224 -780
View File
File diff suppressed because it is too large Load Diff
+15 -30
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -24,14 +25,8 @@
//// Includes //// Includes
//// ////
#include "types.h"
#include "depth.h" #include "depth.h"
#include "history.h" #include "move.h"
#include "lock.h"
#include "movegen.h"
#include "position.h"
#include "tt.h"
#include "value.h"
//// ////
@@ -40,6 +35,7 @@
const int PLY_MAX = 100; const int PLY_MAX = 100;
const int PLY_MAX_PLUS_2 = 102; const int PLY_MAX_PLUS_2 = 102;
const int KILLER_MAX = 2;
//// ////
@@ -54,36 +50,25 @@ const int PLY_MAX_PLUS_2 = 102;
struct SearchStack { struct SearchStack {
Move pv[PLY_MAX]; Move pv[PLY_MAX];
Move currentMove; Move currentMove;
Value currentMoveCaptureValue; Move mateKiller;
Move mateKiller, killer1, killer2;
Move threatMove; Move threatMove;
Move killers[KILLER_MAX];
Depth reduction; Depth reduction;
void init(int ply);
void initKillers();
}; };
////
//// Global variables
////
extern TranspositionTable TT;
extern int ActiveThreads;
extern Lock SMPLock;
// Perhaps better to make H local, and pass as parameter to MovePicker?
extern History H;
//// ////
//// Prototypes //// Prototypes
//// ////
extern void init_threads(); extern void init_threads();
extern void stop_threads(); extern void stop_threads();
extern void think(const Position &pos, bool infinite, bool ponder, int time, extern bool think(const Position &pos, bool infinite, bool ponder, int side_to_move,
int increment, int movesToGo, int maxDepth, int maxNodes, int time[], int increment[], int movesToGo, int maxDepth,
int maxTime, Move searchMoves[]); int maxNodes, int maxTime, Move searchMoves[]);
extern int64_t nodes_searched(); extern int64_t nodes_searched();
-85
View File
@@ -1,85 +0,0 @@
/*
Glaurung, a UCI chess playing engine.
Copyright (C) 2004-2008 Tord Romstad
Glaurung 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.
Glaurung 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 <cstdio>
#include <string>
#include "square.h"
////
//// Functions
////
/// Translating files, ranks and squares to/from characters and strings:
File file_from_char(char c) {
return File(c - 'a') + FILE_A;
}
char file_to_char(File f) {
return char(f - FILE_A) + 'a';
}
Rank rank_from_char(char c) {
return Rank(c - '1') + RANK_1;
}
char rank_to_char(Rank r) {
return char(r - RANK_1) + '1';
}
Square square_from_string(const std::string &str) {
return make_square(file_from_char(str[0]), rank_from_char(str[1]));
}
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;
}
/// file_is_ok(), rank_is_ok() and square_is_ok(), for debugging:
bool file_is_ok(File f) {
return f >= FILE_A && f <= FILE_H;
}
bool rank_is_ok(Rank r) {
return r >= RANK_1 && r <= RANK_8;
}
bool square_is_ok(Square s) {
return file_is_ok(square_file(s)) && rank_is_ok(square_rank(s));
}
+41 -17
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -24,6 +25,7 @@
//// Includes //// Includes
//// ////
#include <cstdlib> // for abs()
#include <string> #include <string>
#include "color.h" #include "color.h"
@@ -129,7 +131,7 @@ inline Square relative_square(Color c, Square s) {
return Square(int(s) ^ (int(c) * FlipMask)); return Square(int(s) ^ (int(c) * FlipMask));
} }
inline Rank pawn_rank(Color c, Square s) { inline Rank relative_rank(Color c, Square s) {
return square_rank(relative_square(c, s)); return square_rank(relative_square(c, s));
} }
@@ -157,21 +159,43 @@ inline int square_distance(Square s1, Square s2) {
return Max(file_distance(s1, s2), rank_distance(s1, 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) {
//// Prototypes return char(f - FILE_A + int('a'));
//// }
extern File file_from_char(char c); inline Rank rank_from_char(char c) {
extern char file_to_char(File f); return Rank(c - '1') + RANK_1;
extern Rank rank_from_char(char c); }
extern char rank_to_char(Rank r);
extern Square square_from_string(const std::string &str);
extern const std::string square_to_string(Square s);
extern bool file_is_ok(File f); inline char rank_to_char(Rank r) {
extern bool rank_is_ok(Rank r); return char(r - RANK_1 + int('1'));
extern bool square_is_ok(Square s); }
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) #endif // !defined(SQUARE_H_INCLUDED)
+7 -5
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -65,13 +66,14 @@ struct Thread {
SplitPoint *splitPoint; SplitPoint *splitPoint;
int activeSplitPoints; int activeSplitPoints;
uint64_t nodes; uint64_t nodes;
uint64_t betaCutOffs[2];
bool failHighPly1; bool failHighPly1;
volatile bool stop; volatile bool stop;
volatile bool running; volatile bool running;
volatile bool idle; volatile bool idle;
volatile bool workIsWaiting; volatile bool workIsWaiting;
volatile bool printCurrentLine; volatile bool printCurrentLine;
unsigned char pad[64]; unsigned char pad[64]; // set some distance among local data for each thread
}; };
-28
View File
@@ -1,28 +0,0 @@
/*
(c) Copyright 1992 Eric Backus
This software may be used freely so long as this copyright notice is
left intact. There is no warrantee on this software.
*/
#include <windows.h>
#include <time.h>
#include "dos.h"
int gettimeofday(struct timeval * tp, struct timezone * tzp)
{
SYSTEMTIME systime;
if (tp) {
struct tm tmrec;
time_t theTime = time(NULL);
tmrec = *localtime(&theTime);
tp->tv_sec = mktime(&tmrec);
GetLocalTime(&systime); /* system time */
tp->tv_usec = systime.wMilliseconds * 1000;
}
return 0;
}
+144 -117
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -23,28 +24,28 @@
#include <cassert> #include <cassert>
#include <cmath> #include <cmath>
#include <cstring>
#include <xmmintrin.h>
#include "movegen.h"
#include "tt.h" #include "tt.h"
// The main transposition table
TranspositionTable TT;
//// ////
//// Functions //// Functions
//// ////
/// Constructor TranspositionTable::TranspositionTable() {
TranspositionTable::TranspositionTable(unsigned mbSize) { size = writes = 0;
size = 0;
generation = 0;
writes = 0;
entries = 0; entries = 0;
this->set_size(mbSize); generation = 0;
} }
/// Destructor
TranspositionTable::~TranspositionTable() { TranspositionTable::~TranspositionTable() {
delete [] entries; delete [] entries;
} }
@@ -53,25 +54,28 @@ TranspositionTable::~TranspositionTable() {
/// measured in megabytes. /// measured in megabytes.
void TranspositionTable::set_size(unsigned mbSize) { void TranspositionTable::set_size(unsigned mbSize) {
unsigned newSize;
assert(mbSize >= 4 && mbSize <= 1024); assert(mbSize >= 4 && mbSize <= 4096);
for(newSize = 1024; newSize * 4 * (sizeof(TTEntry)) <= (mbSize << 20); unsigned newSize = 1024;
newSize *= 2);
newSize /= 2;
if(newSize != size) { // 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))
newSize *= 2;
if (newSize != size)
{
size = newSize; size = newSize;
delete [] entries; delete [] entries;
entries = new TTEntry[size * 4]; entries = new TTCluster[size];
if(entries == NULL) { if (!entries)
{
std::cerr << "Failed to allocate " << mbSize std::cerr << "Failed to allocate " << mbSize
<< " MB for transposition table." << " MB for transposition table." << std::endl;
<< std::endl; Application::exit_with_failure();
exit(EXIT_FAILURE);
} }
this->clear(); clear();
} }
} }
@@ -82,73 +86,101 @@ void TranspositionTable::set_size(unsigned mbSize) {
/// Perhaps we should also clear it when the "ucinewgame" command is recieved? /// Perhaps we should also clear it when the "ucinewgame" command is recieved?
void TranspositionTable::clear() { void TranspositionTable::clear() {
memset(entries, 0, size * 4 * sizeof(TTEntry));
memset(entries, 0, size * sizeof(TTCluster));
}
/// 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.
inline TTEntry* TranspositionTable::first_entry(const Key posKey) const {
return entries[uint32_t(posKey) & (size - 1)].data;
} }
/// TranspositionTable::store writes a new entry containing a position, /// TranspositionTable::store writes a new entry containing a position,
/// a value, a value type, a search depth, and a best move to the /// a value, a value type, a search depth, and a best move to the
/// transposition table. The transposition table is organized in clusters /// transposition table. Transposition table is organized in clusters of
/// of four TTEntry objects, and when a new entry is written, it replaces /// 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 /// 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 /// 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 /// current search and t2 is from a previous search, or if the depth of t1
/// is bigger than the depth of t2. /// is bigger than the depth of t2. A TTEntry of type VALUE_TYPE_EVAL
/// never replaces another entry for the same position.
void TranspositionTable::store(const Key posKey, Value v, ValueType t, Depth d, Move m) {
void TranspositionTable::store(const Position &pos, Value v, Depth d,
Move m, ValueType type) {
TTEntry *tte, *replace; TTEntry *tte, *replace;
uint32_t posKey32 = posKey >> 32; // Use the high 32 bits as key
tte = replace = first_entry(posKey);
for (int i = 0; i < ClusterSize; i++, tte++)
{
if (!tte->key() || tte->key() == posKey32) // empty or overwrite old
{
// Do not overwrite when new type is VALUE_TYPE_EV_LO
if (tte->key() && t == VALUE_TYPE_EV_LO)
return;
tte = replace = entries + int(pos.get_key() & (size - 1)) * 4;
for(int i = 0; i < 4; i++) {
if((tte+i)->key() == pos.get_key()) {
if (m == MOVE_NONE) if (m == MOVE_NONE)
m = (tte+i)->move(); m = tte->move();
*(tte+i) = TTEntry(pos.get_key(), v, type, d, m, generation);
*tte = TTEntry(posKey32, v, t, d, m, generation);
return; return;
} }
if(replace->generation() == generation) { else if (i == 0) // replace would be a no-op in this common case
if((tte+i)->generation() != generation || continue;
(tte+i)->depth() < replace->depth())
replace = tte+i; int c1 = (replace->generation() == generation ? 2 : 0);
int c2 = (tte->generation() == generation ? -2 : 0);
int c3 = (tte->depth() < replace->depth() ? 1 : 0);
if (c1 + c2 + c3 > 0)
replace = tte;
} }
else if((tte+i)->generation() != generation && *replace = TTEntry(posKey32, v, t, d, m, generation);
(tte+i)->depth() < replace->depth())
replace = tte+i;
}
*replace = TTEntry(pos.get_key(), v, type, d, m, generation);
writes++; writes++;
} }
/// TranspositionTable::retrieve looks up the current position in the /// TranspositionTable::retrieve looks up the current position in the
/// transposition table, and extracts the value, value type, depth and /// transposition table. Returns a pointer to the TTEntry or NULL
/// best move if the position is found. The return value is true if /// if position is not found.
/// the position is found, and false if it isn't.
bool TranspositionTable::retrieve(const Position &pos, Value *value, TTEntry* TranspositionTable::retrieve(const Key posKey) const {
Depth *d, Move *move,
ValueType *type) const {
TTEntry *tte;
bool found = false;
tte = entries + int(pos.get_key() & (size - 1)) * 4; uint32_t posKey32 = posKey >> 32;
for(int i = 0; i < 4 && !found ; i++) TTEntry* tte = first_entry(posKey);
if((tte+i)->key() == pos.get_key()) {
tte = tte + i; for (int i = 0; i < ClusterSize; i++, tte++)
found = true; if (tte->key() == posKey32)
} return tte;
if(!found) {
*move = MOVE_NONE; return NULL;
return false;
} }
*value = tte->value();
*type = tte->type();
*d = tte->depth();
*move = tte->move();
return true; /// TranspositionTable::prefetch looks up the current position in the
/// transposition table and load it 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. When we will
/// subsequently call retrieve() the TT data will be already
/// quickly accessible in L1/L2 CPU cache.
void TranspositionTable::prefetch(const Key posKey) const {
#if defined(__INTEL_COMPILER) || defined(__ICL)
// This hack prevents prefetches to be optimized away by the
// Intel compiler. Both MSVC and gcc seems not affected.
__asm__ ("");
#endif
char const* addr = (char*)first_entry(posKey);
_mm_prefetch(addr, _MM_HINT_T2);
_mm_prefetch(addr+64, _MM_HINT_T2); // 64 bytes ahead
} }
@@ -158,73 +190,68 @@ bool TranspositionTable::retrieve(const Position &pos, Value *value,
/// entries from the current search. /// entries from the current search.
void TranspositionTable::new_search() { void TranspositionTable::new_search() {
generation++; generation++;
writes = 0; writes = 0;
} }
/// TranspositionTable::insert_pv() is called at the end of a search /// TranspositionTable::insert_pv() is called at the end of a search
/// iteration, and inserts the PV back into the PV. This makes sure the /// iteration, and inserts the PV back into the PV. This makes sure
/// old PV moves are searched first, even if the old TT entries have been /// the old PV moves are searched first, even if the old TT entries
/// overwritten. /// have been overwritten.
void TranspositionTable::insert_pv(const Position& pos, Move pv[]) { void TranspositionTable::insert_pv(const Position& pos, Move pv[]) {
UndoInfo u;
StateInfo st;
Position p(pos); Position p(pos);
for(int i = 0; pv[i] != MOVE_NONE; i++) { for (int i = 0; pv[i] != MOVE_NONE; i++)
this->store(p, VALUE_NONE, Depth(0), pv[i], VALUE_TYPE_NONE); {
p.do_move(pv[i], u); store(p.get_key(), VALUE_NONE, VALUE_TYPE_NONE, Depth(-127*OnePly), pv[i]);
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 pv[]) {
int ply;
Position p(pos);
StateInfo st[100];
for (ply = 0; pv[ply] != MOVE_NONE; ply++)
p.do_move(pv[ply], st[ply]);
bool stop;
const TTEntry* tte;
for (stop = false, tte = retrieve(p.get_key());
tte && tte->move() != MOVE_NONE && !stop;
tte = retrieve(p.get_key()), ply++)
{
if (!move_is_legal(p, tte->move()))
break;
pv[ply] = tte->move();
p.do_move(pv[ply], st[ply]);
for (int j = 0; j < ply; j++)
if (st[j].key == p.get_key()) stop = true;
}
pv[ply] = MOVE_NONE;
}
/// TranspositionTable::full() returns the permill of all transposition table /// TranspositionTable::full() returns the permill of all transposition table
/// entries which have received at least one write during the current search. /// entries which have received at least one write during the current search.
/// It is used to display the "info hashfull ..." information in UCI. /// It is used to display the "info hashfull ..." information in UCI.
int TranspositionTable::full() { int TranspositionTable::full() const {
double N = double(size) * 4.0;
double N = double(size) * ClusterSize;
return int(1000 * (1 - exp(writes * log(1.0 - 1.0/N)))); return int(1000 * (1 - exp(writes * log(1.0 - 1.0/N))));
} }
/// Constructors
TTEntry::TTEntry() {
}
TTEntry::TTEntry(Key k, Value v, ValueType t, Depth d, Move m,
int generation) {
key_ = k;
data = (m & 0x7FFFF) | (t << 20) | (generation << 23);
value_ = v;
depth_ = int16_t(d);
}
/// Functions for extracting data from TTEntry objects.
Key TTEntry::key() const {
return key_;
}
Depth TTEntry::depth() const {
return Depth(depth_);
}
Move TTEntry::move() const {
return Move(data & 0x7FFFF);
}
Value TTEntry::value() const {
return Value(value_);
}
ValueType TTEntry::type() const {
return ValueType((data >> 20) & 3);
}
int TTEntry::generation() const {
return (data >> 23);
}
+61 -29
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -33,28 +34,58 @@
//// Types //// Types
//// ////
/// The TTEntry class is the class of transposition table entries. /// The TTEntry class is the class of transposition table entries
///
/// A TTEntry needs 96 bits to be stored
///
/// bit 0-31: key
/// bit 32-63: data
/// bit 64-79: value
/// bit 80-95: depth
///
/// 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 23-31: generation
class TTEntry { class TTEntry {
public: public:
TTEntry(); TTEntry() {}
TTEntry(Key k, Value v, ValueType t, Depth d, Move m, int generation); TTEntry(uint32_t k, Value v, ValueType t, Depth d, Move m, int generation)
Key key() const; : key_ (k), data((m & 0x1FFFF) | (t << 20) | (generation << 23)),
Depth depth() const; value_(int16_t(v)), depth_(int16_t(d)) {}
Move move() const;
Value value() const; uint32_t key() const { return key_; }
ValueType type() const; Depth depth() const { return Depth(depth_); }
int generation() const; Move move() const { return Move(data & 0x1FFFF); }
Value value() const { return Value(value_); }
ValueType type() const { return ValueType((data >> 20) & 7); }
int generation() const { return (data >> 23); }
private: private:
Key key_; uint32_t key_;
uint32_t data; uint32_t data;
int16_t value_; int16_t value_;
int16_t depth_; int16_t depth_;
}; };
/// This is the number of TTEntry slots for each position
const int ClusterSize = 5;
/// Each group of ClusterSize number of TTEntry form a TTCluster
/// that is indexed by a single position key. Cluster is padded
/// to a cache line size so to guarantee always aligned accesses.
struct TTCluster {
TTEntry data[ClusterSize];
char cache_line_padding[64 - sizeof(TTEntry[ClusterSize])];
};
/// The transposition table class. This is basically just a huge array /// The transposition table class. This is basically just a huge array
/// containing TTEntry objects, and a few methods for writing new entries /// containing TTEntry objects, and a few methods for writing new entries
/// and reading new ones. /// and reading new ones.
@@ -62,31 +93,32 @@ private:
class TranspositionTable { class TranspositionTable {
public: public:
TranspositionTable(unsigned mbSize); TranspositionTable();
~TranspositionTable(); ~TranspositionTable();
void set_size(unsigned mbSize); void set_size(unsigned mbSize);
void clear(); void clear();
void store(const Position &pos, Value v, Depth d, Move m, ValueType type); void store(const Key posKey, Value v, ValueType type, Depth d, Move m);
bool retrieve(const Position &pos, Value *value, Depth *d, Move *move, TTEntry* retrieve(const Key posKey) const;
ValueType *type) const; void prefetch(const Key posKey) const;
void new_search(); void new_search();
void insert_pv(const Position& pos, Move pv[]); void insert_pv(const Position& pos, Move pv[]);
int full(); void extract_pv(const Position& pos, Move pv[]);
int full() const;
private: private:
inline TTEntry* first_entry(const Key posKey) const;
// Be sure 'writes' is at least one cache line away
// from read only variables.
unsigned char pad_before[64 - sizeof(unsigned)];
unsigned writes; // heavy SMP read/write access here
unsigned char pad_after[64];
unsigned size; unsigned size;
int writes; TTCluster* entries;
TTEntry* entries;
uint8_t generation; uint8_t generation;
}; };
extern TranspositionTable TT;
////
//// Constants and variables
////
// Default transposition table size, in megabytes:
const int TTDefaultSize = 32;
#endif // !defined(TT_H_INCLUDED) #endif // !defined(TT_H_INCLUDED)
+36 -6
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -30,7 +31,7 @@ typedef __int8 int8_t;
typedef unsigned __int8 uint8_t; typedef unsigned __int8 uint8_t;
typedef __int16 int16; typedef __int16 int16;
typedef unsigned __int16 uint16_t; typedef unsigned __int16 uint16_t;
typedef __int32 int32; typedef __int32 int32_t;
typedef unsigned __int32 uint32_t; typedef unsigned __int32 uint32_t;
typedef __int64 int64; typedef __int64 int64;
typedef unsigned __int64 uint64_t; typedef unsigned __int64 uint64_t;
@@ -40,7 +41,36 @@ typedef __int64 int64_t;
#endif // !defined(_MSC_VER) #endif // !defined(_MSC_VER)
// Hash keys: // Hash keys
typedef uint64_t Key; typedef uint64_t Key;
// Bitboard type
typedef uint64_t Bitboard;
////
//// Compiler specific defines
////
// Quiet a warning on Intel compiler
#if !defined(__SIZEOF_INT__ )
#define __SIZEOF_INT__ 0
#endif
// Check for 64 bits for different compilers: Intel, MSVC and gcc
#if defined(__x86_64) || defined(_M_X64) || defined(_WIN64) || (__SIZEOF_INT__ > 4)
#define IS_64BIT
#endif
#if defined(IS_64BIT) && (defined(__GNUC__) || defined(__INTEL_COMPILER))
#define USE_BSFQ
#endif
// 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
#endif // !defined(TYPES_H_INCLUDED) #endif // !defined(TYPES_H_INCLUDED)
+155 -225
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -21,7 +22,9 @@
//// Includes //// Includes
//// ////
#include <cassert>
#include <iostream> #include <iostream>
#include <sstream>
#include <string> #include <string>
#include "book.h" #include "book.h"
@@ -35,6 +38,7 @@
#include "uci.h" #include "uci.h"
#include "ucioption.h" #include "ucioption.h"
using namespace std;
//// ////
//// Local definitions: //// Local definitions:
@@ -42,30 +46,10 @@
namespace { namespace {
// UCIInputParser is a class for parsing UCI input. The class is // UCIInputParser is a class for parsing UCI input. The class
// very simple, and basically just consist of a constant input // is actually a string stream built on a given input string.
// string and a current location in the string. There are methods
// for checking if we are at the end of the line, for getting the
// next token (defined as any whitespace-delimited sequence of
// characters), and for getting the rest of the line as a single
// string.
class UCIInputParser {
public:
UCIInputParser(const std::string &line);
std::string get_next_token();
std::string get_rest_of_line();
bool at_end_of_line();
private:
const std::string &inputLine;
int length, currentIndex;
void skip_whitespace();
};
typedef istringstream UCIInputParser;
// The root position. This is set up when the user (or in practice, the GUI) // 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() // sends the "position" UCI command. The root position is sent to the think()
@@ -73,11 +57,10 @@ namespace {
Position RootPosition; Position RootPosition;
// Local functions // Local functions
void wait_for_command(); bool handle_command(const string& command);
void handle_command(const std::string &command);
void set_option(UCIInputParser& uip); void set_option(UCIInputParser& uip);
void set_position(UCIInputParser& uip); void set_position(UCIInputParser& uip);
void go(UCIInputParser &uip); bool go(UCIInputParser& uip);
} }
@@ -88,11 +71,22 @@ namespace {
/// uci_main_loop() is the only global function in this file. It is /// uci_main_loop() is the only global function in this file. It is
/// called immediately after the program has finished initializing. /// called immediately after the program has finished initializing.
/// The program remains in this loop until it receives the "quit" UCI /// The program remains in this loop until it receives the "quit" UCI
/// command. /// 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_main_loop() { void uci_main_loop() {
RootPosition.from_fen(StartPosition); RootPosition.from_fen(StartPosition);
while(1) wait_for_command(); string command;
do {
// Wait for a command from stdin
if (!getline(cin, command))
command = "quit";
} while (handle_command(command));
} }
@@ -102,278 +96,213 @@ void uci_main_loop() {
namespace { namespace {
///
/// Implementation of the UCIInputParser class.
///
// Constructor for the UCIInputParser class. The constructor takes a
// text string containing a single UCI command as input.
UCIInputParser::UCIInputParser(const std::string &line) : inputLine(line) {
this->currentIndex = 0;
this->length = line.length();
}
// UCIInputParser::skip_whitspace() skips any number of whitespace
// characters from the current location in an input string.
void UCIInputParser::skip_whitespace() {
while(isspace((int)(unsigned char)this->inputLine[this->currentIndex]))
this->currentIndex++;
}
// UCIInputParser::get_next_token() gets the next token in an UCI
// command. A 'token' in an UCI command is simply any
// whitespace-delimited sequence of characters.
std::string UCIInputParser::get_next_token() {
int i, j;
this->skip_whitespace();
for(i = j = this->currentIndex;
j < this->length && !isspace(this->inputLine[j]);
j++);
this->currentIndex = j;
this->skip_whitespace();
std::string str = this->inputLine.substr(i, j - i);
return str;
}
// UCIInputParser::get_rest_of_line() returns the rest of the input
// line (from the current location) as a single string.
std::string UCIInputParser::get_rest_of_line() {
this->skip_whitespace();
return this->inputLine.substr(this->currentIndex, this->length);
}
// UCIInputParser::at_end_of_line() tests whether we have reached the
// end of the input string, i.e. if any more input remains to be
// parsed.
bool UCIInputParser::at_end_of_line() {
return this->currentIndex == this->length;
}
///
/// Other functions
///
// wait_for_command() waits for a command from the user, and passes
// this command to handle_command. wait_for_command also intercepts
// EOF from stdin, by translating EOF to the "quit" command. This
// ensures that Glaurung exits gracefully if the GUI dies
// unexpectedly.
void wait_for_command() {
std::string command;
if(!std::getline(std::cin, command)) command = "quit";
handle_command(command);
}
// handle_command() takes a text string as input, uses a // handle_command() takes a text string as input, uses a
// UCIInputParser object to parse this text string as a UCI command, // UCIInputParser object to parse this text string as a UCI command,
// and calls the appropriate functions. In addition to the UCI // and calls the appropriate functions. In addition to the UCI
// commands, the function also supports a few debug commands. // commands, the function also supports a few debug commands.
void handle_command(const std::string &command) { bool handle_command(const string& command) {
UCIInputParser uip(command);
std::string s = uip.get_next_token();
if(s == "quit") { UCIInputParser uip(command);
OpeningBook.close(); string token;
stop_threads();
quit_eval(); uip >> token; // operator>>() skips any whitespace
exit(0);
} if (token == "quit")
else if(s == "uci") { return false;
std::cout << "id name " << engine_name() << std::endl;
std::cout << "id author Tord Romstad" << std::endl; if (token == "go")
return go(uip);
if (token == "uci")
{
cout << "id name " << engine_name()
<< "\nid author Tord Romstad, Marco Costalba, Joona Kiiski\n";
print_uci_options(); print_uci_options();
std::cout << "uciok" << std::endl; cout << "uciok" << endl;
} }
else if(s == "ucinewgame") { else if (token == "ucinewgame")
TT.clear(); {
push_button("Clear Hash");
Position::init_piece_square_tables(); Position::init_piece_square_tables();
RootPosition.from_fen(StartPosition); RootPosition.from_fen(StartPosition);
} }
else if(s == "isready") else if (token == "isready")
std::cout << "readyok" << std::endl; cout << "readyok" << endl;
else if(s == "position") else if (token == "position")
set_position(uip); set_position(uip);
else if(s == "setoption") else if (token == "setoption")
set_option(uip); set_option(uip);
else if(s == "go")
go(uip);
// The remaining commands are for debugging purposes only. // The remaining commands are for debugging purposes only.
// Perhaps they should be removed later in order to reduce the // Perhaps they should be removed later in order to reduce the
// size of the program binary. // size of the program binary.
else if(s == "d") else if (token == "d")
RootPosition.print(); RootPosition.print();
else if(s == "flip") { else if (token == "flip")
{
Position p(RootPosition); Position p(RootPosition);
RootPosition.flipped_copy(p); RootPosition.flipped_copy(p);
} }
else if(s == "eval") { else if (token == "eval")
{
EvalInfo ei; EvalInfo ei;
std::cout << "Incremental mg: " << RootPosition.mg_value() cout << "Incremental mg: " << RootPosition.mg_value()
<< std::endl; << "\nIncremental eg: " << RootPosition.eg_value()
std::cout << "Incremental eg: " << RootPosition.eg_value() << "\nFull eval: " << evaluate(RootPosition, ei, 0) << endl;
<< std::endl;
std::cout << "Full eval: "
<< evaluate(RootPosition, ei, 0)
<< std::endl;
} }
else if(s == "key") { else if (token == "key")
std::cout << "key: " << RootPosition.get_key() cout << "key: " << hex << RootPosition.get_key()
<< " material key: " << RootPosition.get_material_key() << "\nmaterial key: " << RootPosition.get_material_key()
<< " pawn key: " << RootPosition.get_pawn_key() << "\npawn key: " << RootPosition.get_pawn_key() << endl;
<< std::endl; else
} {
else { cout << "Unknown command: " << command << endl;
std::cout << "Unknown command: " << command << std::endl; while (!uip.eof())
while(!uip.at_end_of_line()) { {
std::cout << uip.get_next_token() << std::endl; uip >> token;
cout << token << endl;
} }
} }
return true;
} }
// set_position() is called when Glaurung receives the "position" UCI // set_position() is called when Stockfish receives the "position" UCI
// command. The input parameter is a UCIInputParser. It is assumed // command. The input parameter is a UCIInputParser. It is assumed
// that this parser has consumed the first token of the UCI command // that this parser has consumed the first token of the UCI command
// ("position"), and is ready to read the second token ("startpos" // ("position"), and is ready to read the second token ("startpos"
// or "fen", if the input is well-formed). // or "fen", if the input is well-formed).
void set_position(UCIInputParser& uip) { void set_position(UCIInputParser& uip) {
std::string token;
token = uip.get_next_token(); string token;
uip >> token; // operator>>() skips any whitespace
if (token == "startpos") if (token == "startpos")
RootPosition.from_fen(StartPosition); RootPosition.from_fen(StartPosition);
else if(token == "fen") { else if (token == "fen")
std::string fen; {
while(token != "moves" && !uip.at_end_of_line()) { string fen;
token = uip.get_next_token(); while (token != "moves" && !uip.eof())
{
uip >> token;
fen += token; fen += token;
fen += ' '; fen += ' ';
} }
RootPosition.from_fen(fen); RootPosition.from_fen(fen);
} }
if(!uip.at_end_of_line()) { if (!uip.eof())
{
if (token != "moves") if (token != "moves")
token = uip.get_next_token(); uip >> token;
if(token == "moves") { if (token == "moves")
{
Move move; Move move;
UndoInfo u; StateInfo st;
while(!uip.at_end_of_line()) { while (!uip.eof())
token = uip.get_next_token(); {
uip >> token;
move = move_from_string(RootPosition, token); move = move_from_string(RootPosition, token);
RootPosition.do_move(move, u); RootPosition.do_move(move, st);
if (RootPosition.rule_50_counter() == 0) if (RootPosition.rule_50_counter() == 0)
RootPosition.reset_game_ply(); RootPosition.reset_game_ply();
} }
// Our StateInfo st is about going out of scope so copy
// its content inside RootPosition before they disappear.
RootPosition.saveState();
} }
} }
} }
// set_option() is called when Glaurung receives the "setoption" UCI // set_option() is called when Stockfish receives the "setoption" UCI
// command. The input parameter is a UCIInputParser. It is assumed // command. The input parameter is a UCIInputParser. It is assumed
// that this parser has consumed the first token of the UCI command // that this parser has consumed the first token of the UCI command
// ("setoption"), and is ready to read the second token ("name", if // ("setoption"), and is ready to read the second token ("name", if
// the input is well-formed). // the input is well-formed).
void set_option(UCIInputParser& uip) { void set_option(UCIInputParser& uip) {
std::string token;
if(!uip.at_end_of_line()) { string token, name;
token = uip.get_next_token();
if(token == "name" && !uip.at_end_of_line()) { uip >> token;
std::string name = uip.get_next_token(); if (token == "name")
std::string nextToken; {
while(!uip.at_end_of_line() uip >> name;
&& (nextToken = uip.get_next_token()) != "value") while (!uip.eof())
name += (" " + nextToken); {
if(nextToken == "value") uip >> token;
set_option_value(name, uip.get_rest_of_line()); if (token == "value")
else break;
name += (" " + token);
}
if (token == "value")
{
// Reads until end of line and left trim white space
getline(uip, token);
token.erase(0, token.find_first_not_of(" \n\r\t"));
set_option_value(name, token);
} else
push_button(name); push_button(name);
} }
} }
}
// go() is called when Glaurung receives the "go" UCI command. The // go() is called when Stockfish receives the "go" UCI command. The
// input parameter is a UCIInputParser. It is assumed that this // input parameter is a UCIInputParser. It is assumed that this
// parser has consumed the first token of the UCI command ("go"), // parser has consumed the first token of the UCI command ("go"),
// and is ready to read the second token. The function sets the // and is ready to read the second token. The function sets the
// thinking time and other parameters from the input string, and // thinking time and other parameters from the input string, and
// calls think() (defined in search.cpp) with the appropriate // calls think() (defined in search.cpp) with the appropriate
// parameters. // parameters. Returns false if a quit command is received while
// thinking, returns true otherwise.
void go(UCIInputParser &uip) { bool go(UCIInputParser& uip) {
std::string token;
int time[2] = {0, 0}, inc[2] = {0, 0}, movesToGo = 0, depth = 0, nodes = 0; string token;
int moveTime = 0;
int time[2] = {0, 0}, inc[2] = {0, 0};
int movesToGo = 0, depth = 0, nodes = 0, moveTime = 0;
bool infinite = false, ponder = false; bool infinite = false, ponder = false;
Move searchMoves[500]; Move searchMoves[500];
searchMoves[0] = MOVE_NONE; searchMoves[0] = MOVE_NONE;
while(!uip.at_end_of_line()) { while (!uip.eof())
token = uip.get_next_token(); {
uip >> token;
if (token == "infinite") if (token == "infinite")
infinite = true; infinite = true;
else if (token == "ponder") else if (token == "ponder")
ponder = true; ponder = true;
else if(token == "wtime") { else if (token == "wtime")
if(!uip.at_end_of_line()) uip >> time[0];
time[0] = atoi(uip.get_next_token().c_str()); else if (token == "btime")
} uip >> time[1];
else if(token == "btime") { else if (token == "winc")
if(!uip.at_end_of_line()) uip >> inc[0];
time[1] = atoi(uip.get_next_token().c_str()); else if (token == "binc")
} uip >> inc[1];
else if(token == "winc") { else if (token == "movestogo")
if(!uip.at_end_of_line()) uip >> movesToGo;
inc[0] = atoi(uip.get_next_token().c_str()); else if (token == "depth")
} uip >> depth;
else if(token == "binc") { else if (token == "nodes")
if(!uip.at_end_of_line()) uip >> nodes;
inc[1] = atoi(uip.get_next_token().c_str()); else if (token == "movetime")
} uip >> moveTime;
else if(token == "movestogo") { else if (token == "searchmoves")
if(!uip.at_end_of_line()) {
movesToGo = atoi(uip.get_next_token().c_str());
}
else if(token == "depth") {
if(!uip.at_end_of_line())
depth = atoi(uip.get_next_token().c_str());
}
else if(token == "nodes") {
if(!uip.at_end_of_line())
nodes = atoi(uip.get_next_token().c_str());
}
else if(token == "movetime") {
if(!uip.at_end_of_line())
moveTime = atoi(uip.get_next_token().c_str());
}
else if(token == "searchmoves" && !uip.at_end_of_line()) {
int numOfMoves = 0; int numOfMoves = 0;
while(!uip.at_end_of_line()) { while (!uip.eof())
token = uip.get_next_token(); {
uip >> token;
searchMoves[numOfMoves++] = move_from_string(RootPosition, token); searchMoves[numOfMoves++] = move_from_string(RootPosition, token);
} }
searchMoves[numOfMoves] = MOVE_NONE; searchMoves[numOfMoves] = MOVE_NONE;
@@ -383,9 +312,10 @@ namespace {
if (moveTime) if (moveTime)
infinite = true; // HACK infinite = true; // HACK
think(RootPosition, infinite, ponder, time[RootPosition.side_to_move()], assert(RootPosition.is_ok());
inc[RootPosition.side_to_move()], movesToGo, depth, nodes, moveTime,
searchMoves); return think(RootPosition, infinite, ponder, RootPosition.side_to_move(),
time, inc, movesToGo, depth, nodes, moveTime, searchMoves);
} }
} }
+5 -4
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
+203 -146
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -21,21 +22,18 @@
//// Includes //// Includes
//// ////
#include <algorithm>
#include <cassert> #include <cassert>
#include <cstdarg> #include <map>
#include <cstdio> #include <string>
#include <sstream>
#include <vector>
#include "misc.h" #include "misc.h"
#include "thread.h" #include "thread.h"
#include "ucioption.h" #include "ucioption.h"
using std::string;
////
//// Variables
////
bool Chess960 = false;
//// ////
//// Local definitions //// Local definitions
@@ -47,93 +45,132 @@ namespace {
/// Types /// Types
/// ///
enum OptionType { SPIN, COMBO, CHECK, STRING, BUTTON, OPTION_TYPE_NONE}; enum OptionType { SPIN, COMBO, CHECK, STRING, BUTTON };
typedef std::vector<string> ComboValues;
struct Option { struct Option {
char name[50], defaultValue[300], currentValue[300];
string name, defaultValue, currentValue;
OptionType type; OptionType type;
size_t idx;
int minValue, maxValue; int minValue, maxValue;
char comboValues[8][64]; 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["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["King Safety Curve"] = Option("Quadratic", COMBO);
o["King Safety Curve"].comboValues.push_back("Quadratic");
o["King Safety Curve"].comboValues.push_back("Linear"); /*, "From File"*/
o["King Safety Coefficient"] = Option(40, 1, 100);
o["King Safety X Intercept"] = Option(0, 0, 20);
o["King Safety Max Slope"] = Option(30, 10, 100);
o["King Safety Max Value"] = Option(500, 100, 1000);
o["Queen Contact Check Bonus"] = Option(3, 0, 8);
o["Queen Check Bonus"] = Option(2, 0, 4);
o["Rook Check Bonus"] = Option(1, 0, 4);
o["Bishop Check Bonus"] = Option(1, 0, 4);
o["Knight Check Bonus"] = Option(1, 0, 4);
o["Discovered Check Bonus"] = Option(3, 0, 8);
o["Mate Threat Bonus"] = Option(3, 0, 8);
o["Check Extension (PV nodes)"] = Option(2, 0, 2);
o["Check Extension (non-PV nodes)"] = Option(1, 0, 2);
o["Single Reply Extension (PV nodes)"] = Option(2, 0, 2);
o["Single Reply Extension (non-PV nodes)"] = Option(2, 0, 2);
o["Mate Threat Extension (PV nodes)"] = Option(0, 0, 2);
o["Mate Threat Extension (non-PV nodes)"] = Option(0, 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["Full Depth Moves (PV nodes)"] = Option(10, 1, 100);
o["Full Depth Moves (non-PV nodes)"] = Option(3, 1, 100);
o["Threat Depth"] = Option(5, 0, 100);
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, 8);
o["Hash"] = Option(32, 4, 4096);
o["Clear Hash"] = Option(false, BUTTON);
o["Ponder"] = Option(true);
o["OwnBook"] = Option(true);
o["MultiPV"] = Option(1, 1, 500);
o["UCI_ShowCurrLine"] = Option(false);
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 /// Variables
/// ///
Option Options[] = { Options options;
{ "Use Search Log", "false", "false", CHECK, 0, 0, {""} },
{ "Search Log Filename", "SearchLog.txt", "SearchLog.txt", STRING, 0, 0, {""} },
{ "Book File", "book.bin", "book.bin", STRING, 0, 0, {""} },
{ "Mobility (Middle Game)", "100", "100", SPIN, 0, 200, {""} },
{ "Mobility (Endgame)", "100", "100", SPIN, 0, 200, {""} },
{ "Pawn Structure (Middle Game)", "100", "100", SPIN, 0, 200, {""} },
{ "Pawn Structure (Endgame)", "100", "100", SPIN, 0, 200, {""} },
{ "Passed Pawns (Middle Game)", "100", "100", SPIN, 0, 200, {""} },
{ "Passed Pawns (Endgame)", "100", "100", SPIN, 0, 200, {""} },
{ "Aggressiveness", "100", "100", SPIN, 0, 200, {""} },
{ "Cowardice", "100", "100", SPIN, 0, 200, {""} },
{ "King Safety Curve", "Quadratic", "Quadratic", COMBO, 0, 0,
{ "Quadratic", "Linear" /*, "From File"*/ } },
{ "King Safety Coefficient", "40", "40", SPIN, 1, 100 , {""} },
{ "King Safety X Intercept", "0", "0", SPIN, 0, 20, {""} },
{ "King Safety Max Slope", "30", "30", SPIN, 10, 100, {""} },
{ "King Safety Max Value", "500", "500", SPIN, 100, 1000, {""} },
{ "Queen Contact Check Bonus", "4", "4", SPIN, 0, 8, {""} },
{ "Rook Contact Check Bonus", "2", "2", SPIN, 0, 4, {""} },
{ "Queen Check Bonus", "2", "2", SPIN, 0, 4, {""} },
{ "Rook Check Bonus", "1", "1", SPIN, 0, 4, {""} },
{ "Bishop Check Bonus", "1", "1", SPIN, 0, 4, {""} },
{ "Knight Check Bonus", "1", "1", SPIN, 0, 4, {""} },
{ "Discovered Check Bonus", "3", "3", SPIN, 0, 8, {""} },
{ "Mate Threat Bonus", "3", "3", SPIN, 0, 8, {""} },
{ "Check Extension (PV nodes)", "2", "2", SPIN, 0, 2, {""} },
{ "Check Extension (non-PV nodes)", "1", "1", SPIN, 0, 2, {""} },
{ "Single Reply Extension (PV nodes)", "2", "2", SPIN, 0, 2, {""} },
{ "Single Reply Extension (non-PV nodes)", "2", "2", SPIN, 0, 2, {""} },
{ "Mate Threat Extension (PV nodes)", "0", "0", SPIN, 0, 2, {""} },
{ "Mate Threat Extension (non-PV nodes)", "0", "0", SPIN, 0, 2, {""} },
{ "Pawn Push to 7th Extension (PV nodes)", "1", "1", SPIN, 0, 2, {""} },
{ "Pawn Push to 7th Extension (non-PV nodes)", "1", "1", SPIN, 0, 2, {""} },
{ "Passed Pawn Extension (PV nodes)", "1", "1", SPIN, 0, 2, {""} },
{ "Passed Pawn Extension (non-PV nodes)", "0", "0", SPIN, 0, 2, {""} },
{ "Pawn Endgame Extension (PV nodes)", "2", "2", SPIN, 0, 2, {""} },
{ "Pawn Endgame Extension (non-PV nodes)", "2", "2", SPIN, 0, 2, {""} },
{ "Full Depth Moves (PV nodes)", "14", "14", SPIN, 1, 100, {""} },
{ "Full Depth Moves (non-PV nodes)", "3", "3", SPIN, 1, 100, {""} },
{ "Threat Depth", "5", "5", SPIN, 0, 100, {""} },
{ "Selective Plies", "7", "7", SPIN, 0, 10, {""} },
{ "Futility Pruning (Main Search)", "true", "true", CHECK, 0, 0, {""} },
{ "Futility Pruning (Quiescence Search)", "true", "true", CHECK, 0, 0, {""} },
{ "Futility Margin 0", "50", "50", SPIN, 0, 1000, {""} },
{ "Futility Margin 1", "100", "100", SPIN, 0, 1000, {""} },
{ "Futility Margin 2", "300", "300", SPIN, 0, 1000, {""} },
{ "Maximum Razoring Depth", "3", "3", SPIN, 0, 4, {""} },
{ "Razoring Margin", "300", "300", SPIN, 150, 600, {""} },
{ "Randomness", "0", "0", SPIN, 0, 10, {""} },
{ "Minimum Split Depth", "4", "4", SPIN, 4, 7, {""} },
{ "Maximum Number of Threads per Split Point", "5", "5", SPIN, 4, 8, {""} },
{ "Threads", "1", "1", SPIN, 1, 8, {""} },
{ "Hash", "32", "32", SPIN, 4, 4096, {""} },
{ "Clear Hash", "false", "false", BUTTON, 0, 0, {""} },
{ "Ponder", "true", "true", CHECK, 0, 0, {""} },
{ "OwnBook", "true", "true", CHECK, 0, 0, {""} },
{ "MultiPV", "1", "1", SPIN, 1, 500, {""} },
{ "UCI_ShowCurrLine", "false", "false", CHECK, 0, 0, {""} },
{ "UCI_Chess960", "false", "false", CHECK, 0, 0, {""} },
{ "", "", "", OPTION_TYPE_NONE, 0, 0, {""}}
};
// stringify converts a value of type T to a std::string
template<typename T>
string stringify(const T& v) {
/// std::ostringstream ss;
/// Functions ss << v;
/// return ss.str();
Option *option_with_name(const char *optionName);
} }
// 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.
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;
}
}
//// ////
//// Functions //// Functions
//// ////
@@ -143,27 +180,18 @@ namespace {
/// "Threads" parameter to the number of available CPU cores. /// "Threads" parameter to the number of available CPU cores.
void init_uci_options() { void init_uci_options() {
Option *o;
o = option_with_name("Threads"); load_defaults(options);
assert(o != NULL);
// Limit the default value of "Threads" to 7 even if we have 8 CPU cores. // Limit the default value of "Threads" to 7 even if we have 8 CPU cores.
// According to Ken Dail's tests, Glaurung plays much better with 7 than // According to Ken Dail's tests, Glaurung plays much better with 7 than
// with 8 threads. This is weird, but it is probably difficult to find out // with 8 threads. This is weird, but it is probably difficult to find out
// why before I have a 8-core computer to experiment with myself. // why before I have a 8-core computer to experiment with myself.
sprintf(o->defaultValue, "%d", Min(cpu_count(), 7)); assert(options.find("Threads") != options.end());
sprintf(o->currentValue, "%d", Min(cpu_count(), 7)); assert(options.find("Minimum Split Depth") != options.end());
// Increase the minimum split depth when the number of CPUs is big. options["Threads"].defaultValue = stringify(Min(cpu_count(), 7));
// It would probably be better to let this depend on the number of threads options["Threads"].currentValue = stringify(Min(cpu_count(), 7));
// instead.
o = option_with_name("Minimum Split Depth");
assert(o != NULL);
if(cpu_count() > 4) {
sprintf(o->defaultValue, "%d", 6);
sprintf(o->defaultValue, "%d", 6);
}
} }
@@ -171,30 +199,49 @@ void init_uci_options() {
/// in the format defined by the UCI protocol. /// in the format defined by the UCI protocol.
void print_uci_options() { void print_uci_options() {
static const char optionTypeName[][16] = { static const char optionTypeName[][16] = {
"spin", "combo", "check", "string", "button" "spin", "combo", "check", "string", "button"
}; };
for(Option *o = Options; o->type != OPTION_TYPE_NONE; o++) {
printf("option name %s type %s", o->name, optionTypeName[o->type]); // Build up a vector out of the options map and sort it according to idx
if(o->type != BUTTON) { // field, that is the chronological insertion order in options map.
printf(" default %s", o->defaultValue); std::vector<Option> vec;
if(o->type == SPIN) for (Options::const_iterator it = options.begin(); it != options.end(); ++it)
printf(" min %d max %d", o->minValue, o->maxValue); vec.push_back(it->second);
else if(o->type == COMBO)
for(int i = 0; strlen(o->comboValues[i]) > 0; i++) std::sort(vec.begin(), vec.end());
printf(" var %s", o->comboValues[i]);
} for (std::vector<Option>::const_iterator it = vec.begin(); it != vec.end(); ++it)
printf("\n"); {
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;
} }
/// get_option_value_bool() returns the current value of a UCI parameter of /// get_option_value_bool() returns the current value of a UCI parameter of
/// type "check". /// type "check".
bool get_option_value_bool(const std::string &optionName) { bool get_option_value_bool(const string& optionName) {
Option *o = option_with_name(optionName.c_str());
return o != NULL && strcmp(o->currentValue, "true") == 0; return get_option_value<bool>(optionName);
} }
@@ -203,31 +250,18 @@ bool get_option_value_bool(const std::string &optionName) {
/// it could also be used with a "combo" parameter, where all the available /// it could also be used with a "combo" parameter, where all the available
/// values are integers. /// values are integers.
int get_option_value_int(const std::string &optionName) { int get_option_value_int(const string& optionName) {
Option *o = option_with_name(optionName.c_str());
return atoi(o->currentValue); return get_option_value<int>(optionName);
} }
/// get_option_value_string() returns the current value of a UCI parameter as /// 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". /// a string. It is used with parameters of type "combo" and "string".
const std::string get_option_value_string(const std::string &optionName) { string get_option_value_string(const string& optionName) {
Option *o = option_with_name(optionName.c_str());
return o->currentValue;
}
return get_option_value<string>(optionName);
/// button_was_pressed() tests whether a UCI parameter of type "button" has
/// been selected since the last time the function was called.
bool button_was_pressed(const std::string &buttonName) {
if(get_option_value_bool(buttonName)) {
set_option_value(buttonName, "false");
return true;
}
else
return false;
} }
@@ -235,36 +269,59 @@ bool button_was_pressed(const std::string &buttonName) {
/// the function does not check that the new value is legal for the given /// 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. /// parameter: This is assumed to be the responsibility of the GUI.
void set_option_value(const std::string &optionName, void set_option_value(const string& name, const string& value) {
const std::string &newValue) {
Option *o = option_with_name(optionName.c_str());
if(o != NULL) // UCI protocol uses "true" and "false" instead of "1" and "0", so convert
strcpy(o->currentValue, newValue.c_str()); // 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())
options[name].currentValue = v;
else else
std::cout << "No such option: " << optionName << std::endl; std::cout << "No such option: " << name << std::endl;
} }
/// push_button() is used to tell the engine that a UCI parameter of type /// push_button() is used to tell the engine that a UCI parameter of type
/// "button" has been selected: /// "button" has been selected:
void push_button(const std::string &buttonName) { void push_button(const string& buttonName) {
set_option_value(buttonName, "true"); 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 { namespace {
// option_with_name() tries to find a UCI option with a given // Define constructors of Option class.
// name. It returns a pointer to the UCI option or the null pointer,
// depending on whether an option with the given name exists.
Option *option_with_name(const char *optionName) { Option::Option() {} // To allow insertion in a std::map
for(Option *o = Options; o->type != OPTION_TYPE_NONE; o++)
if(strcmp(o->name, optionName) == 0) Option::Option(const char* def, OptionType t)
return o; : defaultValue(def), currentValue(def), type(t), idx(options.size()), minValue(0), maxValue(0) {}
return NULL;
} 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) {}
} }
+7 -15
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -26,14 +27,6 @@
#include <string> #include <string>
////
//// Variables
////
extern bool Chess960;
//// ////
//// Prototypes //// Prototypes
//// ////
@@ -42,10 +35,9 @@ extern void init_uci_options();
extern void print_uci_options(); extern void print_uci_options();
extern bool get_option_value_bool(const std::string& optionName); extern bool get_option_value_bool(const std::string& optionName);
extern int get_option_value_int(const std::string& optionName); extern int get_option_value_int(const std::string& optionName);
extern const std::string get_option_value_string(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 bool button_was_pressed(const std::string& buttonName);
extern void set_option_value(const std::string &optionName, extern void set_option_value(const std::string& optionName,const std::string& newValue);
const std::string &newValue);
extern void push_button(const std::string& buttonName); extern void push_button(const std::string& buttonName);
+7 -6
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -59,7 +60,7 @@ Value value_from_tt(Value v, int ply) {
} }
/// value_to_centipawns() converts a value from Glaurung's somewhat unusual /// value_to_centipawns() converts a value from Stockfish's somewhat unusual
/// scale of pawn = 256 to the more conventional pawn = 100. /// scale of pawn = 256 to the more conventional pawn = 100.
int value_to_centipawns(Value v) { int value_to_centipawns(Value v) {
@@ -67,7 +68,7 @@ int value_to_centipawns(Value v) {
} }
/// value_from_centipawns() converts a centipawn value to Glaurung's internal /// value_from_centipawns() converts a centipawn value to Stockfish's internal
/// evaluation scale. It's used when reading the values of UCI options /// evaluation scale. It's used when reading the values of UCI options
/// containing material values (e.g. futility pruning margins). /// containing material values (e.g. futility pruning margins).
+24 -18
View File
@@ -1,13 +1,14 @@
/* /*
Glaurung, a UCI chess playing engine. Stockfish, a UCI chess playing engine derived from Glaurung 2.1
Copyright (C) 2004-2008 Tord Romstad Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
Copyright (C) 2008-2009 Marco Costalba
Glaurung is free software: you can redistribute it and/or modify Stockfish is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
Glaurung is distributed in the hope that it will be useful, Stockfish is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
@@ -35,7 +36,10 @@ enum ValueType {
VALUE_TYPE_NONE = 0, VALUE_TYPE_NONE = 0,
VALUE_TYPE_UPPER = 1, // Upper bound VALUE_TYPE_UPPER = 1, // Upper bound
VALUE_TYPE_LOWER = 2, // Lower bound VALUE_TYPE_LOWER = 2, // Lower bound
VALUE_TYPE_EXACT = 3 // Exact score VALUE_TYPE_EXACT = 3, // Exact score
VALUE_TYPE_EVAL = 4, // Evaluation cache
VALUE_TYPE_EV_UP = 5, // Evaluation cache for upper bound
VALUE_TYPE_EV_LO = 6 // Evaluation cache for lower bound
}; };
@@ -57,17 +61,19 @@ enum Value {
/// Important: If the material values are changed, one must also /// Important: If the material values are changed, one must also
/// adjust the piece square tables, and the method game_phase() in the /// adjust the piece square tables, and the method game_phase() in the
/// Position class! /// Position class!
///
/// Values modified by Joona Kiiski
const Value PawnValueMidgame = Value(0xCC); const Value PawnValueMidgame = Value(0x0C6);
const Value PawnValueEndgame = Value(0x100); const Value PawnValueEndgame = Value(0x102);
const Value KnightValueMidgame = Value(0x340); const Value KnightValueMidgame = Value(0x331);
const Value KnightValueEndgame = Value(0x340); const Value KnightValueEndgame = Value(0x34E);
const Value BishopValueMidgame = Value(0x340); const Value BishopValueMidgame = Value(0x344);
const Value BishopValueEndgame = Value(0x340); const Value BishopValueEndgame = Value(0x359);
const Value RookValueMidgame = Value(0x505); const Value RookValueMidgame = Value(0x4F6);
const Value RookValueEndgame = Value(0x505); const Value RookValueEndgame = Value(0x4FE);
const Value QueenValueMidgame = Value(0xA00); const Value QueenValueMidgame = Value(0x9D9);
const Value QueenValueEndgame = Value(0xA00); const Value QueenValueEndgame = Value(0x9FE);
const Value PieceValueMidgame[17] = { const Value PieceValueMidgame[17] = {
Value(0), Value(0),
@@ -89,10 +95,10 @@ const Value PieceValueEndgame[17] = {
Value(0), Value(0), Value(0) Value(0), Value(0), Value(0)
}; };
/// Bonus for having the side to move /// Bonus for having the side to move (modified by Joona Kiiski)
const Value TempoValueMidgame = Value(50); const Value TempoValueMidgame = Value(48);
const Value TempoValueEndgame = Value(20); const Value TempoValueEndgame = Value(22);
//// ////