Skip to content

Commit

Permalink
Color math: properly clip colors
Browse files Browse the repository at this point in the history
  • Loading branch information
twvd committed Nov 28, 2023
1 parent eaf6199 commit 66a5c94
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
14 changes: 12 additions & 2 deletions src/snes/ppu/color.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::cmp::min;

use num_traits::int::PrimInt;
use num_traits::AsPrimitive;

Expand All @@ -18,6 +20,14 @@ impl SnesColor {
Self((r as u16 & 0x1F) | (g as u16 & 0x1F) << 5 | (b as u16 & 0x1F) << 10)
}

pub fn from_rgb5_clip(r: u8, g: u8, b: u8) -> SnesColor {
Self(
(min(r, 0x1F) as u16 & 0x1F)
| (min(g, 0x1F) as u16 & 0x1F) << 5
| (min(b, 0x1F) as u16 & 0x1F) << 10,
)
}

/// Convert to a (host)-native color (RGB888)
pub fn to_native(&self) -> Color {
// TODO better put this in the frontend? I'm not sure..
Expand Down Expand Up @@ -77,7 +87,7 @@ impl SnesColor {
/// Color math add
pub fn cm_add(&self, other: &SnesColor, div2: bool) -> SnesColor {
let div = if div2 { 2 } else { 1 };
Self::from_rgb5(
Self::from_rgb5_clip(
(self.r() + other.r()) / div,
(self.g() + other.g()) / div,
(self.b() + other.b()) / div,
Expand All @@ -87,7 +97,7 @@ impl SnesColor {
/// Color math subtract
pub fn cm_sub(&self, other: &SnesColor, div2: bool) -> SnesColor {
let div = if div2 { 2 } else { 1 };
Self::from_rgb5(
Self::from_rgb5_clip(
(self.r().saturating_sub(other.r())) / div,
(self.g().saturating_sub(other.g())) / div,
(self.b().saturating_sub(other.b())) / div,
Expand Down
4 changes: 3 additions & 1 deletion src/snes/ppu/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,9 @@ where
return pixel;
}

let div2 = self.cgadsub & (1 << 6) != 0 && sublayer != LAYER_BACKDROP;
let div2 = self.cgadsub & (1 << 6) != 0
&& sublayer != LAYER_BACKDROP
&& mainlayer != LAYER_BACKDROP;
if self.cgadsub & (1 << 7) == 0 {
// Add mode
pixel = pixel.cm_add(&subclr, div2);
Expand Down

0 comments on commit 66a5c94

Please sign in to comment.