1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
use std::fmt;
use std::sync::atomic::{AtomicBool, Ordering};

use num_traits::Float;
use specs::{Component, VecStorage};

pub struct Sprite<T, I> {
    pub image: I,
    pub x: T,
    pub y: T,
    pub w: T,
    pub h: T,
    pub width: T,
    pub height: T,
    z: usize,
    layer: usize,
    dirty: AtomicBool,
}

impl<T, I> fmt::Debug for Sprite<T, I>
where
    T: fmt::Debug,
    I: fmt::Debug,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Sprite")
            .field("image", &self.image)
            .field("x", &self.x)
            .field("y", &self.y)
            .field("w", &self.w)
            .field("h", &self.h)
            .field("width", &self.width)
            .field("height", &self.height)
            .field("z", &self.z)
            .field("layer", &self.layer)
            .finish()
    }
}

impl<T, I> Component for Sprite<T, I>
where
    T: 'static + Send + Sync,
    I: 'static + Send + Sync,
{
    type Storage = VecStorage<Self>;
}

impl<T, I> Sprite<T, I>
where
    T: 'static + Float + Send + Sync,
    I: 'static + Send + Sync,
{
    #[inline]
    pub fn new(image: I) -> Self {
        Sprite {
            image: image,
            x: T::zero(),
            y: T::zero(),
            w: T::one(),
            h: T::one(),
            width: T::one(),
            height: T::one(),
            z: 0,
            layer: 0,
            dirty: AtomicBool::new(true),
        }
    }

    #[inline(always)]
    pub fn z(&self) -> &usize {
        &self.z
    }
    #[inline(always)]
    pub fn layer(&self) -> &usize {
        &self.layer
    }

    #[inline]
    pub fn set_z(&mut self, z: usize) -> &mut Self {
        self.z = z;
        self.flag(true);
        self
    }
    #[inline]
    pub fn set_layer(&mut self, layer: usize) -> &mut Self {
        self.layer = layer;
        self.flag(true);
        self
    }
    #[inline]
    pub fn set_z_and_layer(&mut self, z: usize, layer: usize) -> &mut Self {
        self.z = z;
        self.layer = layer;
        self.flag(true);
        self
    }

    #[inline]
    pub(crate) fn flag(&self, dirty: bool) {
        self.dirty.store(dirty, Ordering::SeqCst)
    }

    #[inline]
    pub fn is_dirty(&self) -> bool {
        self.dirty.load(Ordering::SeqCst)
    }
}