use std::fmt;
use crate::engine::common::Result;
use crate::engine::{Exceptions, Point, point, point_i};
use super::BitArray;
type BaseType = super::BitFieldBaseType;
const BASE_BITS: usize = super::BIT_FIELD_BASE_BITS;
const BASE_SHIFT: usize = super::BIT_FIELD_SHIFT_BITS;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BitMatrix {
width: u32,
height: u32,
row_size: usize,
bits: Vec<BaseType>,
}
impl BitMatrix {
pub fn with_single_dimension(dimension: u32) -> Result<Self> {
Self::new(dimension, dimension)
}
pub fn new(width: u32, height: u32) -> Result<Self> {
if width < 1 || height < 1 {
return Err(Exceptions::illegal_argument_with("Both dimensions must be greater than 0"));
}
Ok(Self {
width,
height,
row_size: (width as usize).div_ceil(BASE_BITS),
bits: vec![0; (width as usize).div_ceil(BASE_BITS) * height as usize],
})
}
#[inline(always)]
pub fn get(&self, x: u32, y: u32) -> bool {
if x >= self.width || y >= self.height {
return false;
}
let offset = self.get_offset(y, x);
if offset >= self.bits.len() { false } else { ((self.bits[offset] >> (x as usize & BASE_SHIFT)) & 1) != 0 }
}
#[inline(always)]
pub fn get_point(&self, point: Point) -> bool {
if !point.x.is_finite() || !point.y.is_finite() || point.x < 0.0 || point.y < 0.0 {
return false;
}
self.get(point.x as u32, point.y as u32)
}
#[inline(always)]
pub fn get_index<T: Into<usize>>(&self, index: T) -> bool {
self.get_point(self.calculate_pointrom_index(index.into()))
}
#[inline(always)]
fn calculate_pointrom_index(&self, index: usize) -> Point {
let row = index / (self.getWidth() as usize);
let column = index % (self.getWidth() as usize);
point_i(column as u32, row as u32)
}
#[inline(always)]
fn get_offset(&self, y: u32, x: u32) -> usize {
y as usize * self.row_size + (x as usize / BASE_BITS)
}
pub fn try_get(&self, x: u32, y: u32) -> Option<bool> {
if x >= self.width || y >= self.height {
return None;
}
let offset = self.get_offset(y, x);
if offset >= self.bits.len() { None } else { Some(((self.bits[offset] >> (x as usize & BASE_SHIFT)) & 1) != 0) }
}
#[inline(always)]
pub fn try_get_point(&self, point: Point) -> Option<bool> {
if !point.x.is_finite() || !point.y.is_finite() || point.x < 0.0 || point.y < 0.0 {
return None;
}
self.try_get(point.x as u32, point.y as u32)
}
pub fn try_get_area(&self, x: u32, y: u32, box_size: u32) -> Option<bool> {
let mut matrix = Vec::with_capacity((box_size * box_size) as usize);
let start_x = (x as i32 - box_size as i32 / 2).max(0) as u32;
let end_x = x + box_size / 2;
let start_y = (y as i32 - box_size as i32 / 2).max(0) as u32;
let end_y = y + box_size / 2;
for get_x in start_x..=end_x {
for get_y in start_y..=end_y {
matrix.push(self.try_get(get_x, get_y)?);
}
}
let total_set = matrix.iter().filter(|bit| **bit).count();
if (total_set as f32 / matrix.len() as f32) >= 0.5 { Some(true) } else { Some(false) }
}
#[inline(always)]
pub fn check_in_bounds(&self, x: u32, y: u32) -> bool {
(self.get_offset(y, x)) >= self.bits.len()
}
#[inline(always)]
pub fn check_point_in_bounds(&self, point: Point) -> bool {
self.check_in_bounds(point.x as u32, point.y as u32)
}
#[inline(always)]
pub fn set(&mut self, x: u32, y: u32) {
let offset = self.get_offset(y, x);
self.bits[offset] |= 1 << (x as usize & BASE_SHIFT);
}
#[inline(always)]
pub fn set_bool(&mut self, x: u32, y: u32, value: bool) {
if value { self.set(x, y) } else { self.unset(x, y) }
}
#[inline(always)]
pub fn unset(&mut self, x: u32, y: u32) {
let offset = self.get_offset(y, x);
self.bits[offset] &= !(1 << (x as usize & BASE_SHIFT));
}
#[inline(always)]
pub fn flip_coords(&mut self, x: u32, y: u32) {
let offset = self.get_offset(y, x);
self.bits[offset] ^= 1 << (x as usize & BASE_SHIFT);
}
pub fn flip_self(&mut self) {
for bit_set in self.bits.iter_mut() {
*bit_set = !*bit_set;
}
let used = self.width as usize % BASE_BITS;
if used != 0 {
let mask: BaseType = ((1 as BaseType) << used) - 1;
for y in 0..self.height as usize {
let last = y * self.row_size + self.row_size - 1;
self.bits[last] &= mask;
}
}
}
pub fn xor(&mut self, mask: &BitMatrix) -> Result<()> {
if self.width != mask.width || self.height != mask.height || self.row_size != mask.row_size {
return Err(Exceptions::illegal_argument_with("input matrix dimensions do not match"));
}
for y in 0..self.height {
let offset = y as usize * self.row_size;
let rowArray = mask.getRow(y);
let row = rowArray.getBitArray();
for (x, row_x) in row.iter().enumerate().take(self.row_size) {
self.bits[offset + x] ^= *row_x;
}
}
Ok(())
}
#[inline(always)]
pub fn clear(&mut self) {
self.bits.fill(0);
}
pub fn setRegion(&mut self, left: u32, top: u32, width: u32, height: u32) -> Result<()> {
if height < 1 || width < 1 {
return Err(Exceptions::illegal_argument_with("height and width must be at least 1"));
}
let right = left + width;
let bottom = top + height;
if bottom > self.height || right > self.width {
return Err(Exceptions::illegal_argument_with("the region must fit inside the matrix"));
}
for y in top..bottom {
let offset = y as usize * self.row_size;
for x in left..right {
self.bits[offset + (x as usize / BASE_BITS)] |= 1 << (x as usize & BASE_SHIFT);
}
}
Ok(())
}
pub fn getRow(&self, y: u32) -> BitArray {
let mut rw = BitArray::with_size(self.width as usize);
let offset = y as usize * self.row_size;
for x in 0..self.row_size {
rw.setBulk(x * BASE_BITS, self.bits[offset + x]);
}
rw
}
pub fn getCol(&self, x: u32) -> BitArray {
let mut cw = BitArray::with_size(self.height as usize);
for y in 0..self.height {
if self.get(x, y) {
cw.set(y as usize)
}
}
cw
}
pub fn setRow(&mut self, y: u32, row: &BitArray) {
self.bits[y as usize * self.row_size..y as usize * self.row_size + self.row_size]
.clone_from_slice(&row.getBitArray()[0..self.row_size])
}
pub fn rotate(&mut self, degrees: u32) -> Result<()> {
match degrees % 360 {
0 => Ok(()),
90 => {
self.rotate90();
Ok(())
}
180 => {
self.rotate180();
Ok(())
}
270 => {
self.rotate90();
self.rotate180();
Ok(())
}
_ => Err(Exceptions::illegal_argument_with("degrees must be a multiple of 0, 90, 180, or 270")),
}
}
pub fn rotate180(&mut self) {
let maxHeight = self.height.div_ceil(2);
for i in 0..maxHeight {
let mut topRow = self.getRow(i);
let bottomRowIndex = self.height - 1 - i;
let mut bottomRow = self.getRow(bottomRowIndex);
topRow.reverse();
bottomRow.reverse();
self.setRow(i, &bottomRow);
self.setRow(bottomRowIndex, &topRow);
}
}
pub fn rotate90(&mut self) {
let newWidth = self.height;
let newHeight = self.width;
let newRowSize = newWidth.div_ceil(BASE_BITS as u32);
let mut newBits = vec![0; (newRowSize * newHeight) as usize];
for y in 0..self.height {
for x in 0..self.width {
let offset = self.get_offset(y, x);
if ((self.bits[offset] >> (x as usize & BASE_SHIFT)) & 1) != 0 {
let newOffset: usize = ((newHeight - 1 - x) * newRowSize + (y / BASE_BITS as u32)) as usize;
newBits[newOffset] |= 1 << (y as usize & BASE_SHIFT);
}
}
}
self.width = newWidth;
self.height = newHeight;
self.row_size = newRowSize as usize;
self.bits = newBits;
}
pub fn getEnclosingRectangle(&self) -> Option<[u32; 4]> {
let mut left = self.width;
let mut top = self.height;
let mut right: u32 = 0;
let mut bottom = 0;
for y in 0..self.height {
for x32 in 0..self.row_size {
let theBits = self.bits[y as usize * self.row_size + x32];
if theBits != 0 {
top = top.min(y);
bottom = bottom.max(y);
let bit_lo: usize = theBits.trailing_zeros() as usize;
left = left.min(((x32 * BASE_BITS) + bit_lo) as u32);
let bit_hi: usize = (BASE_BITS - 1) - (theBits.leading_zeros() as usize);
right = right.max(((x32 * BASE_BITS) + bit_hi) as u32);
}
}
}
if right < left || bottom < top {
return None;
}
Some([left, top, right - left + 1, bottom - top + 1])
}
pub fn getTopLeftOnBit(&self) -> Option<Point> {
let mut bitsOffset = 0;
while bitsOffset < self.bits.len() && self.bits[bitsOffset] == 0 {
bitsOffset += 1;
}
if bitsOffset == self.bits.len() {
return None;
}
let y = bitsOffset / self.row_size;
let mut x = (bitsOffset % self.row_size) * BASE_BITS;
let theBits = self.bits[bitsOffset];
let mut bit = 0;
while (theBits << (BASE_SHIFT - bit)) == 0 {
bit += 1;
}
x += bit;
Some(point(x as f32, y as f32))
}
pub fn getBottomRightOnBit(&self) -> Option<Point> {
let mut bitsOffset = self.bits.len() as i64 - 1;
while bitsOffset >= 0 && self.bits[bitsOffset as usize] == 0 {
bitsOffset -= 1;
}
if bitsOffset < 0 {
return None;
}
let y = bitsOffset as usize / self.row_size;
let mut x = (bitsOffset as usize % self.row_size) * BASE_BITS;
let theBits = self.bits[bitsOffset as usize];
let mut bit = BASE_BITS - 1;
while (theBits >> bit) == 0 {
bit -= 1;
}
x += bit;
Some(point(x as f32, y as f32))
}
#[inline(always)]
pub const fn getWidth(&self) -> u32 {
self.width()
}
#[inline(always)]
pub const fn width(&self) -> u32 {
self.width
}
#[inline(always)]
pub const fn getHeight(&self) -> u32 {
self.height()
}
#[inline(always)]
pub const fn height(&self) -> u32 {
self.height
}
#[inline(always)]
pub fn getRowSize(&self) -> usize {
self.row_size
}
pub fn toString(&self, setString: &str, unsetString: &str) -> String {
self.buildToString(setString, unsetString, "\n")
}
fn buildToString(&self, setString: &str, unsetString: &str, lineSeparator: &str) -> String {
let mut result = String::with_capacity((self.height * (self.width + 1)).try_into().unwrap());
for y in 0..self.height {
for x in 0..self.width {
result.push_str(if self.get(x, y) { setString } else { unsetString });
}
result.push_str(lineSeparator);
}
result
}
#[inline(always)]
pub fn is_in(&self, p: Point) -> bool {
self.isIn(p, 0)
}
#[inline(always)]
pub fn isIn(&self, p: Point, b: i32) -> bool {
b as f32 <= p.x
&& p.x < self.getWidth() as f32 - b as f32
&& b as f32 <= p.y
&& p.y < self.getHeight() as f32 - b as f32
}
}
impl fmt::Display for BitMatrix {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.toString("X ", " "))
}
}
impl From<&BitMatrix> for Vec<bool> {
fn from(value: &BitMatrix) -> Self {
let mut arr = vec![false; (value.width * value.height) as usize];
for x in 0..value.width {
for y in 0..value.height {
let insert_pos = ((y * value.width) + x) as usize;
arr[insert_pos] = value.get(x, y);
}
}
arr
}
}
#[cfg(test)]
mod boundary_tests {
use super::*;
#[test]
fn reads_reject_invalid_coordinates_before_offset_calculation() {
let mut matrix = BitMatrix::new(1, 2).unwrap();
matrix.set(0, 1);
assert!(matrix.get(0, 1));
assert_eq!(matrix.try_get(0, 1), Some(true));
for (x, y) in [(BASE_BITS as u32, 0), (0, 2), (u32::MAX, u32::MAX)] {
assert!(!matrix.get(x, y));
assert_eq!(matrix.try_get(x, y), None);
}
}
#[test]
fn point_reads_reject_nonfinite_and_negative_coordinates() {
let mut matrix = BitMatrix::new(2, 2).unwrap();
matrix.set(0, 0);
assert!(matrix.get_point(point(0.5, 0.5)));
assert_eq!(matrix.try_get_point(point(0.5, 0.5)), Some(true));
for p in [
point(-0.5, 0.0),
point(0.0, -0.5),
point(f32::NAN, 0.0),
point(0.0, f32::NAN),
point(f32::INFINITY, 0.0),
point(0.0, f32::INFINITY),
] {
assert!(!matrix.get_point(p));
assert_eq!(matrix.try_get_point(p), None);
}
}
}