Skip to main content

uorustlibs/
color.rs

1//! Traits for easy conversion between packed color data and easy-to-manipulate tuples
2//!
3//! UO's colour palette is 16-bit 555, with the high bit unused
4
5pub trait Color {
6    //! A color that can be converted between an rgba tuple and back
7    fn to_rgba(&self) -> (u8, u8, u8, u8);
8    fn from_rgba(r: u8, g: u8, b: u8, a: u8) -> Self;
9}
10
11pub type Color16 = u16;
12pub type Color32 = u32;
13
14pub const BLACK_16: Color16 = 0;
15
16impl Color for Color16 {
17    fn to_rgba(&self) -> (u8, u8, u8, u8) {
18        let r = (((*self >> 10) & 0x1F) * 0xFF / 0x1F) as u8;
19        let g = (((*self >> 5) & 0x1F) * 0xFF / 0x1F) as u8;
20        let b = ((*self & 0x1F) * 0xFF / 0x1F) as u8;
21        (r, g, b, 255)
22    }
23
24    fn from_rgba(r: u8, g: u8, b: u8, _a: u8) -> Color16 {
25        ((r as u16 >> 3) << 10) + ((g as u16 >> 3) << 5) + (b as u16 >> 3)
26    }
27}
28
29impl Color for Color32 {
30    fn to_rgba(&self) -> (u8, u8, u8, u8) {
31        let r = ((*self >> 24) & 0xFF) as u8;
32        let g = ((*self >> 16) & 0xFF) as u8;
33        let b = ((*self >> 8) & 0xFF) as u8;
34        let a = (*self & 0xFF) as u8;
35        (r, g, b, a)
36    }
37
38    fn from_rgba(r: u8, g: u8, b: u8, a: u8) -> Color32 {
39        ((r as u32) << 24) + ((g as u32) << 16) + ((b as u32) << 8) + (a as u32)
40    }
41}