Skip to content

Commit

Permalink
Merge pull request #62 from lyonbeckers/sprite-additions-but-safe
Browse files Browse the repository at this point in the history
Sprite API - safe userdata, remove_sprites, and get_sprite_count
  • Loading branch information
boozook authored Sep 13, 2023
2 parents a1e9fb7 + dc13668 commit 05067d3
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions src/sprite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ pub struct SpriteInner {
pub raw_sprite: *mut crankstart_sys::LCDSprite,
playdate_sprite: *const playdate_sprite,
image: Option<Bitmap>,
userdata: Option<Rc<dyn core::any::Any>>,
}

pub type SpritePtr = Rc<RefCell<SpriteInner>>;
Expand Down Expand Up @@ -285,6 +286,32 @@ impl SpriteInner {
pub fn mark_dirty(&mut self) -> Result<(), Error> {
pd_func_caller!((*self.playdate_sprite).markDirty, self.raw_sprite,)
}

pub fn get_userdata<T>(&self) -> Result<Option<Rc<T>>, Error>
where
T: 'static,
{
self.userdata
.as_ref()
.map(
|userdata: &Rc<dyn core::any::Any>| -> Result<Rc<T>, Error> {
userdata.clone().downcast::<T>().map_err(|err| {
anyhow!(
"Failed to cast userdata type {}",
core::any::type_name::<T>(),
)
})
},
)
.transpose()
}

pub fn set_userdata<T>(&mut self, userdata: Rc<T>)
where
T: 'static,
{
self.userdata = Some(userdata);
}
}

impl Drop for SpriteInner {
Expand Down Expand Up @@ -424,6 +451,20 @@ impl Sprite {
.map_err(Error::msg)?
.mark_dirty()
}

pub fn get_userdata<T>(&self) -> Result<Option<Rc<T>>, Error>
where
T: 'static,
{
self.inner.borrow().get_userdata()
}

pub fn set_userdata<T>(&mut self, userdata: Rc<T>)
where
T: 'static,
{
self.inner.borrow_mut().set_userdata(userdata)
}
}

impl Hash for Sprite {
Expand Down Expand Up @@ -479,6 +520,7 @@ impl SpriteManager {
raw_sprite,
playdate_sprite: self.playdate_sprite,
image: None,
userdata: None,
};
sprite.set_update_function(unsafe { SPRITE_UPDATE.expect("SPRITE_UPDATE") })?;
let sprite_ptr = Rc::new(RefCell::new(sprite));
Expand All @@ -495,6 +537,17 @@ impl SpriteManager {
)
}

pub fn get_sprite_count(&self) -> Result<i32, Error> {
pd_func_caller!((*self.playdate_sprite).getSpriteCount)
}

pub fn remove_sprite(&mut self, sprite: &Sprite) -> Result<(), Error> {
pd_func_caller!(
(*self.playdate_sprite).removeSprite,
sprite.inner.borrow_mut().raw_sprite
)
}

pub fn add_dirty_rect(dirty_rect: LCDRect) -> Result<(), Error> {
pd_func_caller!((*Self::get_mut().playdate_sprite).addDirtyRect, dirty_rect)
}
Expand Down

0 comments on commit 05067d3

Please sign in to comment.