Make everything accept a Vec2Int and add docs

This commit is contained in:
Yash Karandikar 2022-05-28 09:51:46 -05:00
parent 26d6746065
commit f5a040680c
4 changed files with 71 additions and 52 deletions

View file

@ -35,7 +35,7 @@
//! ) //! )
//! .unwrap(); //! .unwrap();
//! //!
//! let (start_x, start_y) = s.position(); //! let (start_x, start_y) = s.position().into();
//! let m = get_mouse_state(ctx); //! let m = get_mouse_state(ctx);
//! let x_diff = m.x - start_x; //! let x_diff = m.x - start_x;
//! let y_diff = m.y - start_y; //! let y_diff = m.y - start_y;
@ -44,7 +44,7 @@
//! s.set_angle(angle.to_degrees()); //! s.set_angle(angle.to_degrees());
//! //!
//! for spr in coll.iter() { //! for spr in coll.iter() {
//! let (start_x, start_y) = spr.position(); //! let (start_x, start_y) = spr.position().into();
//! let m = get_mouse_state(ctx); //! let m = get_mouse_state(ctx);
//! let x_diff = m.x - start_x; //! let x_diff = m.x - start_x;
//! let y_diff = m.y - start_y; //! let y_diff = m.y - start_y;
@ -105,6 +105,8 @@ use sdl2::{
EventPump, IntegerOrSdlError, EventPump, IntegerOrSdlError,
}; };
use vec2::Vec2Int;
#[doc(no_inline)] #[doc(no_inline)]
pub use sdl2::{self, event::Event, keyboard::Scancode, pixels::Color}; pub use sdl2::{self, event::Event, keyboard::Scancode, pixels::Color};
@ -188,7 +190,6 @@ pub struct Sprite {
pub rect: Rect, pub rect: Rect,
surf: Surface<'static>, surf: Surface<'static>,
angle: f64, angle: f64,
} }
impl Sprite { impl Sprite {
@ -210,7 +211,6 @@ impl Sprite {
rect: dest_rect, rect: dest_rect,
surf, surf,
angle: 0.0, angle: 0.0,
}) })
} }
@ -233,7 +233,6 @@ impl Sprite {
rect: dest_rect, rect: dest_rect,
surf, surf,
angle: 0.0, angle: 0.0,
}) })
} }
@ -263,9 +262,10 @@ impl Sprite {
/// # let mut s = Sprite::new("duck.png", 500, 400).unwrap(); /// # let mut s = Sprite::new("duck.png", 500, 400).unwrap();
/// s.translate((5, 10)); /// s.translate((5, 10));
/// ``` /// ```
pub fn translate(&mut self, position: (i32, i32)) { pub fn translate<I: Into<Vec2Int>>(&mut self, position: I) {
let new_x = self.rect.x() + position.0; let position = position.into();
let new_y = self.rect.y() - position.1; let new_x = self.rect.x() + position.x;
let new_y = self.rect.y() - position.y;
self.rect.set_x(new_x); self.rect.set_x(new_x);
self.rect.set_y(new_y); self.rect.set_y(new_y);
@ -278,8 +278,9 @@ impl Sprite {
/// # let mut s = Sprite::new("duck.png", 500, 400).unwrap(); /// # let mut s = Sprite::new("duck.png", 500, 400).unwrap();
/// s.set_position((5, 10)); /// s.set_position((5, 10));
/// ``` /// ```
pub fn set_position(&mut self, position: (i32, i32)) { pub fn set_position<I: Into<Vec2Int>>(&mut self, position: I) {
self.rect.center_on(position); let position = position.into();
self.rect.center_on((position.x, position.y));
} }
/// Set the angle of the sprite, in degrees of clockwise rotation. /// Set the angle of the sprite, in degrees of clockwise rotation.
@ -309,9 +310,9 @@ impl Sprite {
/// ``` /// ```
/// # use cat_box::*; /// # use cat_box::*;
/// # let s = Sprite::new("duck.png", 500, 400).unwrap(); /// # let s = Sprite::new("duck.png", 500, 400).unwrap();
/// let (x, y) = s.position(); /// let (x, y) = s.position().into();
/// ``` /// ```
pub fn position(&self) -> (i32, i32) { pub fn position(&self) -> Vec2Int {
self.rect.center().into() self.rect.center().into()
} }
} }
@ -579,12 +580,12 @@ pub enum TextMode {
/// }; /// };
/// draw_text(ctx, "text to draw", "arial.ttf", 72, (300, 300), mode); /// draw_text(ctx, "text to draw", "arial.ttf", 72, (300, 300), mode);
/// # }); /// # });
pub fn draw_text<S: AsRef<str>>( pub fn draw_text<S: AsRef<str>, I: Into<Vec2Int>>(
ctx: &mut Context, ctx: &mut Context,
text: S, text: S,
font: &str, font: &str,
size: u16, size: u16,
pos: (i32, i32), pos: I,
mode: TextMode, mode: TextMode,
) -> Result<()> { ) -> Result<()> {
let font = ctx.ttf_subsystem.load_font(font, size)?; let font = ctx.ttf_subsystem.load_font(font, size)?;
@ -602,8 +603,10 @@ pub fn draw_text<S: AsRef<str>>(
let (creator, canvas, _) = ctx.inner(); let (creator, canvas, _) = ctx.inner();
let texture = creator.create_texture_from_surface(&surf)?; let texture = creator.create_texture_from_surface(&surf)?;
let pos = pos.into();
let srect = surf.rect(); let srect = surf.rect();
let dest_rect: Rect = Rect::from_center(pos, srect.width(), srect.height()); let dest_rect: Rect = Rect::from_center((pos.x, pos.y), srect.width(), srect.height());
canvas.copy_ex(&texture, None, dest_rect, 0.0, None, false, false)?; canvas.copy_ex(&texture, None, dest_rect, 0.0, None, false, false)?;

View file

@ -34,7 +34,7 @@ fn main() {
) )
.unwrap(); .unwrap();
let (start_x, start_y) = s.position(); let (start_x, start_y) = s.position().into();
let m = get_mouse_state(ctx); let m = get_mouse_state(ctx);
let x_diff = m.x - start_x; let x_diff = m.x - start_x;
let y_diff = m.y - start_y; let y_diff = m.y - start_y;
@ -43,7 +43,7 @@ fn main() {
s.set_angle(angle.to_degrees()); s.set_angle(angle.to_degrees());
for spr in coll.iter() { for spr in coll.iter() {
let (start_x, start_y) = spr.position(); let (start_x, start_y) = spr.position().into();
let m = get_mouse_state(ctx); let m = get_mouse_state(ctx);
let x_diff = m.x - start_x; let x_diff = m.x - start_x;
let y_diff = m.y - start_y; let y_diff = m.y - start_y;

View file

@ -1,3 +1,7 @@
//! Basic physics utilities for cat-box.
//!
//! Still ***very much work-in-progress***
use crate::{Sprite, SpriteCollection}; use crate::{Sprite, SpriteCollection};
use std::cmp::max; use std::cmp::max;
@ -10,14 +14,14 @@ fn collided(sprite1: &Sprite, sprite2: &Sprite) -> bool {
let collision_radius = coll_rad1 + coll_rad2; let collision_radius = coll_rad1 + coll_rad2;
let collision_diameter = collision_radius * collision_radius; let collision_diameter = collision_radius * collision_radius;
let diff_x = sprite1.position().0 - sprite2.position().0; let diff_x = sprite1.position().x - sprite2.position().x;
let diff_x2 = diff_x * diff_x; let diff_x2 = diff_x * diff_x;
if diff_x2 > collision_diameter { if diff_x2 > collision_diameter {
return false; return false;
} }
let diff_y = sprite1.position().1 - sprite2.position().1; let diff_y = sprite1.position().y - sprite2.position().y;
let diff_y2 = diff_y * diff_y; let diff_y2 = diff_y * diff_y;
if diff_y2 > collision_diameter { if diff_y2 > collision_diameter {

View file

@ -1,31 +1,26 @@
//! Types representing directions and locations in 2d and 3d space. //! Types representing directions and locations in 2d and 3d space.
//! //!
//! NOTE: `Vec3`, `Vec3Int`, and `Direction3` don't exist yet. Coming soon! //!
//! //! This module contains 6 major types:
//! This crate contains 6 major types:
//! - [`Vec2`], a 2d float vector //! - [`Vec2`], a 2d float vector
//! - [`Vec2Int`], a 2d integer vector //! - [`Vec2Int`], a 2d integer vector
//! - [`Direction2`], a 2d cardinal direction //! - [`Direction`], a 2d cardinal direction
//! - [`Vec3`], a 3d float vector (TODO) //!
//! - [`Vec3Int`], a 3d integer vector (TODO)
//! - [`Direction3`], a 3d cardinal direction (TODO)
//!
//! All the types implement the expected [`From`]s and all the relevant operator traits. //! All the types implement the expected [`From`]s and all the relevant operator traits.
#![warn(clippy::pedantic)] use std::{
#![warn(missing_docs)] fmt::Debug,
#![allow(clippy::must_use_candidate)] ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign},
};
use sdl2::rect::Point;
use std::{ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign}, fmt::Debug};
// Direction // Direction
/// A cardinal direction in a 2d plane. /// A cardinal direction in a 2d plane.
/// ///
/// Conversions to a [`Vec2`] or [`Vec2Int`] assume that East is positive-x and South is positive-y. /// Conversions to a [`Vec2`] or [`Vec2Int`] assume that East is positive-x and South is positive-y.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Direction2 { pub enum Direction {
/// North, or Vec2::from((0, -1)) /// North, or Vec2::from((0, -1))
North, North,
/// North, or Vec2::from((0, 1)) /// North, or Vec2::from((0, 1))
@ -37,7 +32,7 @@ pub enum Direction2 {
} }
#[allow(clippy::enum_glob_use)] #[allow(clippy::enum_glob_use)]
impl Direction2 { impl Direction {
/// Flips this `Direction` around both the x- and y-axes. /// Flips this `Direction` around both the x- and y-axes.
pub fn flipped(self) -> Self { pub fn flipped(self) -> Self {
self.flip_x().flip_y() self.flip_x().flip_y()
@ -45,7 +40,7 @@ impl Direction2 {
/// Flips this `Direction` around the x-axis. /// Flips this `Direction` around the x-axis.
pub fn flip_x(self) -> Self { pub fn flip_x(self) -> Self {
use Direction2::*; use Direction::*;
match self { match self {
East => West, East => West,
West => East, West => East,
@ -55,7 +50,7 @@ impl Direction2 {
/// Flips this `Direction` around the y-axis. /// Flips this `Direction` around the y-axis.
pub fn flip_y(self) -> Self { pub fn flip_y(self) -> Self {
use Direction2::*; use Direction::*;
match self { match self {
North => South, North => South,
South => North, South => North,
@ -65,7 +60,7 @@ impl Direction2 {
} }
// ...and related op impls // ...and related op impls
impl Neg for Direction2 { impl Neg for Direction {
type Output = Self; type Output = Self;
fn neg(self) -> Self::Output { fn neg(self) -> Self::Output {
@ -74,9 +69,9 @@ impl Neg for Direction2 {
} }
#[allow(clippy::enum_glob_use)] #[allow(clippy::enum_glob_use)]
impl From<Direction2> for Vec2 { impl From<Direction> for Vec2 {
fn from(v: Direction2) -> Self { fn from(v: Direction) -> Self {
use Direction2::*; use Direction::*;
match v { match v {
North => (0.0, -1.0).into(), North => (0.0, -1.0).into(),
South => (0.0, 1.0).into(), South => (0.0, 1.0).into(),
@ -87,9 +82,9 @@ impl From<Direction2> for Vec2 {
} }
#[allow(clippy::enum_glob_use)] #[allow(clippy::enum_glob_use)]
impl From<Direction2> for Vec2Int { impl From<Direction> for Vec2Int {
fn from(v: Direction2) -> Self { fn from(v: Direction) -> Self {
use Direction2::*; use Direction::*;
match v { match v {
North => (0, -1).into(), North => (0, -1).into(),
South => (0, 1).into(), South => (0, 1).into(),
@ -99,7 +94,21 @@ impl From<Direction2> for Vec2Int {
} }
} }
impl Mul<f32> for Direction2 { impl From<Point> for Vec2 {
fn from(p: Point) -> Self {
let x: (i32, i32) = p.into();
x.into()
}
}
impl From<Point> for Vec2Int {
fn from(p: Point) -> Self {
let x: (i32, i32) = p.into();
x.into()
}
}
impl Mul<f32> for Direction {
type Output = Vec2; type Output = Vec2;
fn mul(self, rhs: f32) -> Self::Output { fn mul(self, rhs: f32) -> Self::Output {
@ -107,7 +116,7 @@ impl Mul<f32> for Direction2 {
} }
} }
impl Mul<i32> for Direction2 { impl Mul<i32> for Direction {
type Output = Vec2Int; type Output = Vec2Int;
fn mul(self, rhs: i32) -> Self::Output { fn mul(self, rhs: i32) -> Self::Output {
@ -230,10 +239,10 @@ impl Add for Vec2 {
} }
} }
impl Add<Direction2> for Vec2 { impl Add<Direction> for Vec2 {
type Output = Self; type Output = Self;
fn add(self, rhs: Direction2) -> Self::Output { fn add(self, rhs: Direction) -> Self::Output {
self + Self::from(rhs) self + Self::from(rhs)
} }
} }
@ -313,7 +322,10 @@ pub struct Vec2Int {
impl Debug for Vec2Int { impl Debug for Vec2Int {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("Vec2Int").field(&self.x).field(&self.y).finish() f.debug_tuple("Vec2Int")
.field(&self.x)
.field(&self.y)
.finish()
} }
} }
@ -400,10 +412,10 @@ impl Add for Vec2Int {
} }
} }
impl Add<Direction2> for Vec2Int { impl Add<Direction> for Vec2Int {
type Output = Self; type Output = Self;
fn add(self, rhs: Direction2) -> Self::Output { fn add(self, rhs: Direction) -> Self::Output {
self + Self::from(rhs) self + Self::from(rhs)
} }
} }