#[derive(Clone, Copy)]
pub(super) enum BlendMode {
Normal,
Additive,
Multiply,
Screen,
}
pub(super) struct Mesh<'a> {
pub vertices: &'a [f32],
pub uvs: &'a [f32],
pub indices: &'a [u16],
pub page: usize,
pub blend: BlendMode,
pub light: [f32; 4],
pub dark: [f32; 3],
}
pub(super) struct Texture {
width: usize,
height: usize,
pixels: Vec<[f32; 4]>,
}
impl Texture {
pub fn new(image: image::RgbaImage, premultiplied: bool) -> Self {
let pixels = image
.pixels()
.map(|pixel| {
let mut color = pixel.0.map(|v| v as f32 / 255.0);
if !premultiplied {
for channel in 0..3 {
color[channel] *= color[3];
}
}
color
})
.collect();
Self {
width: image.width() as usize,
height: image.height() as usize,
pixels,
}
}
#[inline(always)]
fn sample(&self, uv: [f32; 2]) -> [f32; 4] {
let x = (uv[0] * self.width as f32 - 0.5).clamp(0.0, (self.width - 1) as f32);
let y = (uv[1] * self.height as f32 - 0.5).clamp(0.0, (self.height - 1) as f32);
let (x0, y0) = (x as usize, y as usize);
let (x1, y1) = ((x0 + 1).min(self.width - 1), (y0 + 1).min(self.height - 1));
let (fx, fy) = (x - x0 as f32, y - y0 as f32);
let channel = |c: usize| {
let top = self.pixels[y0 * self.width + x0][c] * (1.0 - fx)
+ self.pixels[y0 * self.width + x1][c] * fx;
let bottom = self.pixels[y1 * self.width + x0][c] * (1.0 - fx)
+ self.pixels[y1 * self.width + x1][c] * fx;
top * (1.0 - fy) + bottom * fy
};
[channel(0), channel(1), channel(2), channel(3)]
}
}
#[derive(Clone, Copy)]
pub(super) struct View {
pub scale: f32,
pub offset: [f32; 2],
}
#[inline]
pub(super) fn draw(
pixels: &mut [[f32; 4]],
width: usize,
height: usize,
texture: &Texture,
mesh: Mesh<'_>,
view: View,
) {
draw_mapped::<false>(pixels, width, height, texture, mesh, |p| {
[
(p[0] * view.scale + view.offset[0]) as f64,
(-p[1] * view.scale + view.offset[1]) as f64,
]
});
}
pub(super) fn draw_transformed(
pixels: &mut [[f32; 4]],
width: usize,
height: usize,
texture: &Texture,
mesh: Mesh<'_>,
mapping: crate::RenderMapping,
) {
draw_mapped::<true>(pixels, width, height, texture, mesh, |p| {
mapping.map_point([p[0] as f64, -p[1] as f64])
});
}
fn draw_mapped<const TRANSFORMED: bool>(
pixels: &mut [[f32; 4]],
width: usize,
height: usize,
texture: &Texture,
mesh: Mesh<'_>,
map_point: impl Fn([f32; 2]) -> [f64; 2],
) {
let tinted = mesh.light != [1.0; 4] || mesh.dark != [0.0; 3];
for triangle in mesh.indices.chunks_exact(3) {
let mut indices = [
triangle[0] as usize,
triangle[1] as usize,
triangle[2] as usize,
];
let mut points =
indices.map(|i| map_point([mesh.vertices[i * 2], mesh.vertices[i * 2 + 1]]));
let mut area = edge(points[0], points[1], points[2]);
if area == 0.0 || !area.is_finite() {
continue;
}
if area < 0.0 {
points.swap(1, 2);
indices.swap(1, 2);
area = -area;
}
let min_x = points
.iter()
.map(|p| p[0])
.fold(f64::INFINITY, f64::min)
.floor()
.max(0.0) as usize;
let min_y = points
.iter()
.map(|p| p[1])
.fold(f64::INFINITY, f64::min)
.floor()
.max(0.0) as usize;
let max_x = points
.iter()
.map(|p| p[0])
.fold(f64::NEG_INFINITY, f64::max)
.ceil()
.clamp(0.0, width as f64) as usize;
let max_y = points
.iter()
.map(|p| p[1])
.fold(f64::NEG_INFINITY, f64::max)
.ceil()
.clamp(0.0, height as f64) as usize;
let inclusive = [
top_left(points[1], points[2]),
top_left(points[2], points[0]),
top_left(points[0], points[1]),
];
let edges_in_order = [
[points[1], points[2]],
[points[2], points[0]],
[points[0], points[1]],
]
.map(|[a, b]| if a < b { (a, b, 1.0) } else { (b, a, -1.0) });
let uvs = indices.map(|i| [mesh.uvs[i * 2] as f64, mesh.uvs[i * 2 + 1] as f64]);
let inv_area = 1.0 / area;
for y in min_y..max_y {
let mut entered = false;
for x in min_x..max_x {
let p = [x as f64 + 0.5, y as f64 + 0.5];
let edges = if TRANSFORMED {
edges_in_order.map(|(a, b, sign)| edge(a, b, p) * sign)
} else {
[
edge(points[1], points[2], p),
edge(points[2], points[0], p),
edge(points[0], points[1], p),
]
};
if edges
.iter()
.zip(inclusive)
.any(|(&e, include)| e < 0.0 || (e == 0.0 && !include))
{
if entered {
break;
}
continue;
}
entered = true;
let uv = std::array::from_fn(|axis| {
((uvs[0][axis] * edges[0] + uvs[1][axis] * edges[1] + uvs[2][axis] * edges[2])
* inv_area) as f32
});
let texel = texture.sample(uv);
let mut source = texel;
if tinted {
source[3] = texel[3] * mesh.light[3];
for c in 0..3 {
source[c] = (texel[c] * mesh.light[c]
+ (texel[3] - texel[c]) * mesh.dark[c])
* mesh.light[3];
}
}
blend(&mut pixels[y * width + x], source, mesh.blend);
}
}
}
}
fn edge(a: [f64; 2], b: [f64; 2], p: [f64; 2]) -> f64 {
(b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])
}
fn top_left(a: [f64; 2], b: [f64; 2]) -> bool {
b[1] < a[1] || (b[1] == a[1] && b[0] > a[0])
}
fn blend(dst: &mut [f32; 4], src: [f32; 4], mode: BlendMode) {
let alpha = src[3] + dst[3] * (1.0 - src[3]);
for c in 0..3 {
dst[c] = match mode {
BlendMode::Normal => src[c] + dst[c] * (1.0 - src[3]),
BlendMode::Additive => (src[c] + dst[c]).min(alpha),
BlendMode::Multiply => {
src[c] * (1.0 - dst[3]) + dst[c] * (1.0 - src[3]) + src[c] * dst[c]
}
BlendMode::Screen => src[c] + dst[c] - src[c] * dst[c],
};
}
dst[3] = alpha;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn pixel_center_edges_cover_once_for_either_winding() {
let texture = Texture::new(
image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 255, 255, 128])),
false,
);
let vertices = [0.00001, -0.00001, 250.3, 0.0, 250.3, -250.3, 0.0, -250.3];
let uvs = [0.5; 8];
let view = View {
scale: 1.0,
offset: [0.0; 2],
};
let color = [128.0 / 255.0; 4];
for indices in [[0, 1, 2, 0, 2, 3], [2, 1, 0, 3, 2, 0]] {
let mut pixels = vec![[0.0; 4]; 256 * 256];
for (half, triangle) in indices.chunks_exact(3).enumerate() {
draw(
&mut pixels,
256,
256,
&texture,
Mesh {
vertices: &vertices,
uvs: &uvs,
indices: triangle,
page: 0,
blend: BlendMode::Normal,
light: [1.0; 4],
dark: [0.0; 3],
},
view,
);
for (i, pixel) in pixels.iter().enumerate() {
let (x, y) = (i % 256, i / 256);
let covered = x < 250 && y < 250 && (half == 1 || x >= y);
assert_eq!(
*pixel,
if covered { color } else { [0.0; 4] },
"pixel ({x}, {y}), half {half}, indices {indices:?}",
);
}
}
}
let vertices = [0.0, 0.0, 8.0, 0.0, 8.0, -8.0, 0.0, -8.0];
for rotation in [
0.0,
0.3,
std::f64::consts::FRAC_PI_4,
std::f64::consts::FRAC_PI_2,
] {
for scale in [[1.5, 0.5], [-1.5, 0.5], [1.5, -0.5]] {
let options = crate::RenderOptions {
transform: crate::Transform {
rotation,
scale,
pivot: Some([24.0; 2]),
..Default::default()
},
..Default::default()
};
let mapping =
crate::RenderMapping::new([2.0; 2], [16.0; 2], 64, 64, &options).unwrap();
let mut forward = None;
for indices in [[0, 1, 2, 0, 2, 3], [2, 1, 0, 3, 2, 0]] {
let mut pixels = vec![[0.0; 4]; 64 * 64];
draw_transformed(
&mut pixels,
64,
64,
&texture,
Mesh {
vertices: &vertices,
uvs: &uvs,
indices: &indices,
page: 0,
blend: BlendMode::Normal,
light: [1.0; 4],
dark: [0.0; 3],
},
mapping,
);
assert!(pixels.contains(&color));
assert!(pixels.iter().all(|p| *p == color || *p == [0.0; 4]));
if let Some(expected) = &forward {
assert_eq!(&pixels, expected);
} else {
forward = Some(pixels);
}
}
}
}
}
#[test]
fn sampling_ignores_invisible_rgb_and_accepts_premultiplied_textures() {
let image = image::RgbaImage::from_raw(2, 1, vec![255, 0, 0, 255, 0, 255, 0, 0]).unwrap();
assert_eq!(
Texture::new(image, false).sample([0.5, 0.5]),
[0.5, 0.0, 0.0, 0.5]
);
let image = image::RgbaImage::from_pixel(1, 1, image::Rgba([128, 0, 0, 128]));
let sample = Texture::new(image, true).sample([0.5, 0.5]);
assert_eq!(sample[0], sample[3]); }
#[test]
fn blend_modes_composite_color_and_alpha_on_a_transparent_canvas() {
let source = [0.4, 0.1, 0.0, 0.5];
for (mode, expected) in [
(BlendMode::Normal, [0.4, 0.2, 0.15, 0.75]),
(BlendMode::Additive, [0.4, 0.3, 0.3, 0.75]),
(BlendMode::Multiply, [0.2, 0.17, 0.15, 0.75]),
(BlendMode::Screen, [0.4, 0.28, 0.3, 0.75]),
] {
let mut target = [0.0, 0.2, 0.3, 0.5];
blend(&mut target, source, mode);
for c in 0..4 {
assert!((target[c] - expected[c]).abs() < 1e-6);
}
let mut transparent = [0.0; 4];
blend(&mut transparent, source, mode);
assert_eq!(transparent, source);
}
}
}