ezionoir

Untitled

Jul 28th, 2025
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.61 KB | None | 0 0
  1. pub fn init_sliding_piece_magics<'a>(
  2.    piece_type: PieceType,
  3.    attacks: &'a mut [Bitboard],
  4.     magics: &mut [Magic<'a>; Square::NB],
  5. ) {
  6.    debug_assert!(piece_type == Bishop || piece_type == Rook);
  7.  
  8.    let mut offsets = [0; Square::NB + 1];
  9.    let mut offset: usize = 0;
  10.    for &square in Square::ALL.iter() {
  11.        let magic = &mut magics[square as usize];
  12.        magic.mask = sliding_attacks(piece_type, square, Bitboard::EMPTY);
  13.  
  14.        let start = offset;
  15.        // Carry-Rippler trick (https://www.chessprogramming.org/Traversing_Subsets_of_a_Set)
  16.        let mut blockers = Bitboard::EMPTY;
  17.        loop {
  18.            let index = Bitboard::extract_bits(blockers, magic.mask);
  19.            attacks[start + index as usize] = sliding_attacks(piece_type, square, blockers);
  20.            offset += 1;
  21.            blockers = Bitboard((blockers.0.wrapping_sub(magic.mask.0)) & magic.mask.0);
  22.            if blockers.empty() {
  23.                break;
  24.            }
  25.        }
  26.        offsets[square as usize + 1] = offset;
  27.        // magic.attacks = &attacks[start..offset];
  28.    }
  29.  
  30.    for &square in Square::ALL.iter() {
  31.        magics[square as usize].attacks = &attacks[offsets[square as usize]..offsets[square as usize + 1]];
  32.    }
  33. }
  34.  
  35. static ROOK_MAGICS: LazyLock<SlidingPieceMagics<'static>> = LazyLock::new(|| {
  36.     let mut attacks = Box::leak(Box::new([Bitboard::EMPTY; ROOK_ATTACK_NB]));
  37.     let mut magics = [Magic::default(); Square::NB];
  38.  
  39.     init_sliding_piece_magics(Rook, attacks, &mut magics);
  40.  
  41.     SlidingPieceMagics {
  42.         attacks: &attacks[..],
  43.         magics,
  44.     }
  45. });
Advertisement
Add Comment
Please, Sign In to add comment