+
+
+/// PawnEntry::shelter_storm() calculates shelter and storm penalties for the file
+/// the king is on, as well as the two adjacent files.
+
+template<Color Us>
+Value PawnEntry::shelter_storm(const Position& pos, Square ksq) {
+
+ const Color Them = (Us == WHITE ? BLACK : WHITE);
+
+ Value safety = MaxSafetyBonus;
+ Bitboard b = pos.pieces(PAWN) & (in_front_bb(Us, ksq) | rank_bb(ksq));
+ Bitboard ourPawns = b & pos.pieces(Us) & ~rank_bb(ksq);
+ Bitboard theirPawns = b & pos.pieces(Them);
+ Rank rkUs, rkThem;
+ File kf = file_of(ksq);
+
+ kf = (kf == FILE_A) ? kf++ : (kf == FILE_H) ? kf-- : kf;
+
+ for (int f = kf - 1; f <= kf + 1; f++)
+ {
+ // Shelter penalty is higher for the pawn in front of the king
+ b = ourPawns & FileBB[f];
+ rkUs = b ? rank_of(Us == WHITE ? first_1(b) : ~last_1(b)) : RANK_1;
+ safety -= ShelterWeakness[f != kf][rkUs];
+
+ // Storm danger is smaller if enemy pawn is blocked
+ b = theirPawns & FileBB[f];
+ rkThem = b ? rank_of(Us == WHITE ? first_1(b) : ~last_1(b)) : RANK_1;
+ safety -= StormDanger[rkThem == rkUs + 1][rkThem];
+ }
+
+ return safety;
+}
+
+
+/// PawnEntry::update_safety() calculates and caches a bonus for king safety. It is
+/// called only when king square changes, about 20% of total king_safety() calls.
+
+template<Color Us>
+Score PawnEntry::update_safety(const Position& pos, Square ksq) {
+
+ kingSquares[Us] = ksq;
+ castleRights[Us] = pos.can_castle(Us);
+
+ if (relative_rank(Us, ksq) > RANK_4)
+ return kingSafety[Us] = SCORE_ZERO;
+
+ Value bonus = shelter_storm<Us>(pos, ksq);
+
+ // If we can castle use the bonus after the castle if is bigger
+ if (pos.can_castle(make_castle_right(Us, KING_SIDE)))
+ bonus = std::max(bonus, shelter_storm<Us>(pos, relative_square(Us, SQ_G1)));
+
+ if (pos.can_castle(make_castle_right(Us, QUEEN_SIDE)))
+ bonus = std::max(bonus, shelter_storm<Us>(pos, relative_square(Us, SQ_C1)));
+
+ return kingSafety[Us] = make_score(bonus, 0);
+}
+
+// Explicit template instantiation
+template Score PawnEntry::update_safety<WHITE>(const Position& pos, Square ksq);
+template Score PawnEntry::update_safety<BLACK>(const Position& pos, Square ksq);