- kingShelters[Us] = make_score(shelter, 0);
- return kingShelters[Us];
+ castleRights[Us] = pos.can_castle(Us);
+ minKPdistance[Us] = 0;
+
+ Bitboard pawns = pos.pieces(Us, PAWN);
+ if (pawns)
+ while (!(DistanceRingsBB[ksq][minKPdistance[Us]++] & pawns)) {}
+
+ if (relative_rank(Us, ksq) > RANK_4)
+ return kingSafety[Us] = make_score(0, -16 * minKPdistance[Us]);
+
+ Value bonus = shelter_storm<Us>(pos, ksq);
+
+ // If we can castle use the bonus after the castle if is bigger
+ if (pos.can_castle(make_castle_right(Us, KING_SIDE)))
+ bonus = std::max(bonus, shelter_storm<Us>(pos, relative_square(Us, SQ_G1)));
+
+ if (pos.can_castle(make_castle_right(Us, QUEEN_SIDE)))
+ bonus = std::max(bonus, shelter_storm<Us>(pos, relative_square(Us, SQ_C1)));
+
+ return kingSafety[Us] = make_score(bonus, -16 * minKPdistance[Us]);