#![doc = include_str!("../README.md")]
#![deny(missing_docs)]
use std::{
collections::VecDeque,
sync::atomic::{AtomicU64, Ordering},
};
use anyhow::{Result, anyhow, bail};
const MAX_GRAPH_RESOURCES: usize = 100_000;
const MAX_GRAPH_PASSES: usize = 100_000;
const MAX_GRAPH_REFERENCES: usize = 1_000_000;
const MAX_GRAPH_NAME_BYTES: usize = 16 * 1024 * 1024;
const MAX_GRAPH_NAME_LENGTH: usize = 4 * 1024;
static NEXT_GRAPH_ID: AtomicU64 = AtomicU64::new(1);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ResourceId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PassId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CacheKey(u128);
impl CacheKey {
pub const fn as_u128(self) -> u128 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResourceKind {
Texture,
Buffer,
}
#[derive(Debug, Clone)]
pub struct ResourceDesc {
pub name: String,
pub kind: ResourceKind,
pub imported: bool,
pub allocation_class: u64,
}
impl ResourceDesc {
pub fn transient_texture(name: impl Into<String>) -> Self {
Self {
name: name.into(),
kind: ResourceKind::Texture,
imported: false,
allocation_class: 0,
}
}
pub fn imported_texture(name: impl Into<String>) -> Self {
Self {
name: name.into(),
kind: ResourceKind::Texture,
imported: true,
allocation_class: 0,
}
}
pub fn allocation_class(mut self, allocation_class: u64) -> Self {
self.allocation_class = allocation_class;
self
}
}
#[derive(Debug, Clone)]
pub struct PassDesc {
pub name: String,
pub reads: Vec<ResourceId>,
pub writes: Vec<ResourceId>,
pub param_hash: u64,
pub frame_pts: Option<i64>,
}
impl PassDesc {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
reads: Vec::new(),
writes: Vec::new(),
param_hash: 0,
frame_pts: None,
}
}
pub fn read(mut self, resource: ResourceId) -> Self {
self.reads.push(resource);
self
}
pub fn write(mut self, resource: ResourceId) -> Self {
self.writes.push(resource);
self
}
pub fn param_hash(mut self, hash: u64) -> Self {
self.param_hash = hash;
self
}
pub fn frame_pts(mut self, pts: i64) -> Self {
self.frame_pts = Some(pts);
self
}
}
#[derive(Debug)]
pub struct RenderGraph {
graph_id: u64,
revision: u64,
name_bytes: usize,
reference_count: usize,
resources: Vec<ResourceDesc>,
passes: Vec<PassDesc>,
}
impl Default for RenderGraph {
fn default() -> Self {
Self {
graph_id: NEXT_GRAPH_ID.fetch_add(1, Ordering::Relaxed),
revision: 0,
name_bytes: 0,
reference_count: 0,
resources: Vec::new(),
passes: Vec::new(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResourceLifetime {
pub resource: ResourceId,
pub first_pass_order: usize,
pub last_pass_order: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Barrier {
pub resource: ResourceId,
pub after: PassId,
pub before: PassId,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransientAllocation {
pub slot_of: Vec<Option<usize>>,
pub slot_count: usize,
}
#[derive(Debug, Clone)]
pub struct CompiledGraph {
graph_id: u64,
graph_revision: u64,
order: Vec<PassId>,
cache_keys: Vec<CacheKey>,
lifetimes: Vec<Option<ResourceLifetime>>,
transient: Vec<bool>,
resource_classes: Vec<(ResourceKind, u64)>,
barriers: Vec<Barrier>,
}
impl RenderGraph {
pub fn new() -> Self {
Self::default()
}
pub fn add_resource(&mut self, desc: ResourceDesc) -> ResourceId {
self.try_add_resource(desc)
.expect("render graph resource bounds exceeded")
}
pub fn try_add_resource(&mut self, desc: ResourceDesc) -> Result<ResourceId> {
if self.resources.len() >= MAX_GRAPH_RESOURCES {
bail!("render graph exceeds the {MAX_GRAPH_RESOURCES} resource limit");
}
self.validate_name_budget(&desc.name)?;
let next_revision = self.next_revision()?;
self.resources
.try_reserve(1)
.map_err(|error| anyhow!("cannot grow render graph resources: {error}"))?;
let id = ResourceId(self.resources.len() as u32);
self.name_bytes += desc.name.len();
self.resources.push(desc);
self.revision = next_revision;
Ok(id)
}
pub fn add_pass(&mut self, desc: PassDesc) -> PassId {
self.try_add_pass(desc)
.expect("render graph pass bounds exceeded")
}
pub fn try_add_pass(&mut self, desc: PassDesc) -> Result<PassId> {
if self.passes.len() >= MAX_GRAPH_PASSES {
bail!("render graph exceeds the {MAX_GRAPH_PASSES} pass limit");
}
self.validate_name_budget(&desc.name)?;
let added_references = desc
.reads
.len()
.checked_add(desc.writes.len())
.ok_or_else(|| anyhow!("render graph reference count overflow"))?;
let reference_count = self
.reference_count
.checked_add(added_references)
.ok_or_else(|| anyhow!("render graph reference count overflow"))?;
if reference_count > MAX_GRAPH_REFERENCES {
bail!("render graph exceeds the {MAX_GRAPH_REFERENCES} reference limit");
}
let next_revision = self.next_revision()?;
self.passes
.try_reserve(1)
.map_err(|error| anyhow!("cannot grow render graph passes: {error}"))?;
let id = PassId(self.passes.len() as u32);
self.name_bytes += desc.name.len();
self.reference_count = reference_count;
self.passes.push(desc);
self.revision = next_revision;
Ok(id)
}
pub fn pass(&self, pass: PassId) -> Option<&PassDesc> {
self.passes.get(pass.0 as usize)
}
pub fn resource(&self, resource: ResourceId) -> Option<&ResourceDesc> {
self.resources.get(resource.0 as usize)
}
fn validate_name_budget(&self, name: &str) -> Result<()> {
if name.len() > MAX_GRAPH_NAME_LENGTH {
bail!("render graph name exceeds the {MAX_GRAPH_NAME_LENGTH} byte limit");
}
let name_bytes = self
.name_bytes
.checked_add(name.len())
.ok_or_else(|| anyhow!("render graph name byte count overflow"))?;
if name_bytes > MAX_GRAPH_NAME_BYTES {
bail!("render graph names exceed the {MAX_GRAPH_NAME_BYTES} byte limit");
}
Ok(())
}
fn next_revision(&self) -> Result<u64> {
self.revision
.checked_add(1)
.ok_or_else(|| anyhow!("render graph revision is exhausted"))
}
pub fn compile(&self) -> Result<CompiledGraph> {
let resource_count = self.resources.len();
let pass_count = self.passes.len();
let mut writer: Vec<Option<PassId>> = vec![None; resource_count];
for (index, pass) in self.passes.iter().enumerate() {
let pass_id = PassId(index as u32);
for &resource in pass.reads.iter().chain(pass.writes.iter()) {
if resource.0 as usize >= resource_count {
bail!(
"pass '{}' references unknown resource {:?}",
pass.name,
resource
);
}
}
for &resource in &pass.writes {
if let Some(existing) = writer[resource.0 as usize] {
bail!(
"resource {:?} is written by multiple passes ({:?} and {:?}); each resource must have a single writer",
resource,
existing,
pass_id
);
}
writer[resource.0 as usize] = Some(pass_id);
}
}
for (reader_index, pass) in self.passes.iter().enumerate() {
for &resource in &pass.reads {
let resource_index = resource.0 as usize;
if !self.resources[resource_index].imported
&& writer[resource_index]
.is_none_or(|producer| producer.0 as usize == reader_index)
{
bail!(
"pass '{}' reads transient resource '{}' before any pass produces it",
pass.name,
self.resources[resource_index].name
);
}
}
}
let order = self.topological_order(&writer)?;
let cache_keys = self.compute_cache_keys(&order, &writer);
let lifetimes = self.compute_lifetimes(&order, resource_count);
let mut keys_by_pass = vec![CacheKey(0); pass_count];
for (position, &pass_id) in order.iter().enumerate() {
keys_by_pass[pass_id.0 as usize] = cache_keys[position];
}
let mut barriers = Vec::new();
for (reader_index, pass) in self.passes.iter().enumerate() {
let mut reads = pass.reads.clone();
reads.sort_unstable();
reads.dedup();
for resource in reads {
if let Some(producer) = writer[resource.0 as usize] {
if producer.0 as usize != reader_index {
barriers.push(Barrier {
resource,
after: producer,
before: PassId(reader_index as u32),
});
}
}
}
}
let transient = self
.resources
.iter()
.map(|resource| !resource.imported)
.collect();
let resource_classes = self
.resources
.iter()
.map(|resource| (resource.kind, resource.allocation_class))
.collect();
Ok(CompiledGraph {
graph_id: self.graph_id,
graph_revision: self.revision,
order,
cache_keys: keys_by_pass,
lifetimes,
transient,
resource_classes,
barriers,
})
}
fn topological_order(&self, writer: &[Option<PassId>]) -> Result<Vec<PassId>> {
let pass_count = self.passes.len();
let mut in_degree = vec![0usize; pass_count];
let mut edges: Vec<Vec<usize>> = vec![Vec::new(); pass_count];
for (reader_index, pass) in self.passes.iter().enumerate() {
let mut reads = pass.reads.clone();
reads.sort_unstable();
reads.dedup();
for resource in reads {
if let Some(producer) = writer[resource.0 as usize] {
let producer_index = producer.0 as usize;
if producer_index == reader_index {
continue;
}
edges[producer_index].push(reader_index);
in_degree[reader_index] += 1;
}
}
}
let mut ready: VecDeque<usize> = (0..pass_count)
.filter(|&index| in_degree[index] == 0)
.collect();
let mut order = Vec::with_capacity(pass_count);
while let Some(index) = ready.pop_front() {
order.push(PassId(index as u32));
for &next in &edges[index] {
in_degree[next] -= 1;
if in_degree[next] == 0 {
ready.push_back(next);
}
}
}
if order.len() != pass_count {
bail!("render graph contains a cycle");
}
Ok(order)
}
fn compute_cache_keys(&self, order: &[PassId], writer: &[Option<PassId>]) -> Vec<CacheKey> {
let mut keys_by_pass = vec![CacheKey(0); self.passes.len()];
let mut keys_in_order = Vec::with_capacity(order.len());
for &pass_id in order {
let pass = &self.passes[pass_id.0 as usize];
let mut key = FNV_OFFSET;
key = fnv_mix(key, u128::from(pass_id.0));
key = fnv_mix(key, u128::from(pass.param_hash));
match pass.frame_pts {
Some(pts) => {
key = fnv_mix(key, 1);
key = fnv_mix(key, pts as u64 as u128);
}
None => key = fnv_mix(key, 0),
}
key = fnv_mix(key, pass.reads.len() as u128);
for &resource in &pass.reads {
key = fnv_mix(key, u128::from(resource.0));
let desc = &self.resources[resource.0 as usize];
key = fnv_mix(key, resource_kind_tag(desc.kind));
key = fnv_mix(key, u128::from(desc.allocation_class));
key = fnv_mix(key, u128::from(desc.imported));
if let Some(producer) = writer[resource.0 as usize] {
key = fnv_mix(key, keys_by_pass[producer.0 as usize].0);
}
}
key = fnv_mix(key, pass.writes.len() as u128);
for &resource in &pass.writes {
key = fnv_mix(key, u128::from(resource.0));
let desc = &self.resources[resource.0 as usize];
key = fnv_mix(key, resource_kind_tag(desc.kind));
key = fnv_mix(key, u128::from(desc.allocation_class));
key = fnv_mix(key, u128::from(desc.imported));
}
keys_by_pass[pass_id.0 as usize] = key;
keys_in_order.push(key);
}
keys_in_order
}
fn compute_lifetimes(
&self,
order: &[PassId],
resource_count: usize,
) -> Vec<Option<ResourceLifetime>> {
let mut order_position = vec![0usize; self.passes.len()];
for (position, &pass_id) in order.iter().enumerate() {
order_position[pass_id.0 as usize] = position;
}
let mut lifetimes: Vec<Option<ResourceLifetime>> = vec![None; resource_count];
for (pass_index, pass) in self.passes.iter().enumerate() {
let position = order_position[pass_index];
for &resource in pass.reads.iter().chain(pass.writes.iter()) {
let slot = &mut lifetimes[resource.0 as usize];
match slot {
None => {
*slot = Some(ResourceLifetime {
resource,
first_pass_order: position,
last_pass_order: position,
});
}
Some(lifetime) => {
lifetime.first_pass_order = lifetime.first_pass_order.min(position);
lifetime.last_pass_order = lifetime.last_pass_order.max(position);
}
}
}
}
lifetimes
}
}
impl CompiledGraph {
pub fn is_current_for(&self, graph: &RenderGraph) -> bool {
self.graph_id == graph.graph_id && self.graph_revision == graph.revision
}
pub fn execution_order(&self) -> &[PassId] {
&self.order
}
pub fn cache_key(&self, pass: PassId) -> Option<CacheKey> {
self.cache_keys.get(pass.0 as usize).copied()
}
pub fn lifetime(&self, resource: ResourceId) -> Option<ResourceLifetime> {
self.lifetimes.get(resource.0 as usize).copied().flatten()
}
pub fn non_overlapping(&self, resource: ResourceId) -> Vec<ResourceId> {
if !self
.transient
.get(resource.0 as usize)
.copied()
.unwrap_or(false)
{
return Vec::new();
}
let Some(target) = self.lifetime(resource) else {
return Vec::new();
};
let Some(target_class) = self.resource_classes.get(resource.0 as usize) else {
return Vec::new();
};
self.lifetimes
.iter()
.enumerate()
.filter(|(index, _)| self.transient.get(*index).copied().unwrap_or(false))
.filter(|(index, _)| self.resource_classes.get(*index) == Some(target_class))
.filter_map(|(_, entry)| *entry)
.filter(|other| other.resource != resource)
.filter(|other| {
other.last_pass_order < target.first_pass_order
|| other.first_pass_order > target.last_pass_order
})
.map(|other| other.resource)
.collect()
}
pub fn changed_passes(&self, previous: &CompiledGraph) -> Vec<PassId> {
let mut changed = Vec::new();
for (index, &key) in self.cache_keys.iter().enumerate() {
let pass = PassId(index as u32);
if previous.cache_key(pass) != Some(key) {
changed.push(pass);
}
}
changed
}
pub fn barriers(&self) -> &[Barrier] {
&self.barriers
}
pub fn assign_transient_memory(&self) -> TransientAllocation {
let mut items: Vec<ResourceLifetime> = self
.lifetimes
.iter()
.enumerate()
.filter_map(|(index, lifetime)| {
let lifetime = (*lifetime)?;
if *self.transient.get(index).unwrap_or(&false) {
Some(lifetime)
} else {
None
}
})
.collect();
items.sort_by_key(|lifetime| (lifetime.first_pass_order, lifetime.last_pass_order));
let mut slot_of = vec![None; self.lifetimes.len()];
let mut slots: Vec<((ResourceKind, u64), usize)> = Vec::new();
for lifetime in items {
let class = self.resource_classes[lifetime.resource.0 as usize];
let free_slot = slots.iter().position(|&(slot_class, last)| {
slot_class == class && last < lifetime.first_pass_order
});
let slot = match free_slot {
Some(slot) => {
slots[slot].1 = lifetime.last_pass_order;
slot
}
None => {
slots.push((class, lifetime.last_pass_order));
slots.len() - 1
}
};
slot_of[lifetime.resource.0 as usize] = Some(slot);
}
TransientAllocation {
slot_of,
slot_count: slots.len(),
}
}
}
const fn resource_kind_tag(kind: ResourceKind) -> u128 {
match kind {
ResourceKind::Texture => 0,
ResourceKind::Buffer => 1,
}
}
const FNV_OFFSET: CacheKey = CacheKey(0x6c62_272e_07bb_0142_62b8_2175_6295_c58d);
const FNV_PRIME: u128 = 0x0000_0000_0100_0000_0000_0000_0000_013b;
fn fnv_mix(mut hash: CacheKey, value: u128) -> CacheKey {
for byte in value.to_le_bytes() {
hash.0 ^= u128::from(byte);
hash.0 = hash.0.wrapping_mul(FNV_PRIME);
}
hash
}
#[cfg(test)]
mod tests {
use super::*;
struct Chain {
graph: RenderGraph,
decode: PassId,
effect: PassId,
present: PassId,
frame: ResourceId,
composited: ResourceId,
}
fn build_chain(decode_pts: i64, effect_param: u64) -> Chain {
let mut graph = RenderGraph::new();
let frame = graph.add_resource(ResourceDesc::transient_texture("frame"));
let composited = graph.add_resource(ResourceDesc::transient_texture("composited"));
let backbuffer = graph.add_resource(ResourceDesc::imported_texture("backbuffer"));
let decode = graph.add_pass(PassDesc::new("decode").write(frame).frame_pts(decode_pts));
let effect = graph.add_pass(
PassDesc::new("effect")
.read(frame)
.write(composited)
.param_hash(effect_param),
);
let present = graph.add_pass(PassDesc::new("present").read(composited).write(backbuffer));
Chain {
graph,
decode,
effect,
present,
frame,
composited,
}
}
#[test]
fn schedules_in_dependency_order() {
let chain = build_chain(0, 0);
let compiled = chain.graph.compile().unwrap();
let order = compiled.execution_order();
let pos = |p: PassId| order.iter().position(|&q| q == p).unwrap();
assert!(pos(chain.decode) < pos(chain.effect));
assert!(pos(chain.effect) < pos(chain.present));
}
#[test]
fn cache_keys_stay_attached_to_pass_ids_after_reordering() {
let mut graph = RenderGraph::new();
let intermediate = graph.add_resource(ResourceDesc::transient_texture("intermediate"));
let output = graph.add_resource(ResourceDesc::transient_texture("output"));
let consumer = graph.add_pass(PassDesc::new("consumer").read(intermediate).write(output));
let producer = graph.add_pass(PassDesc::new("producer").write(intermediate).param_hash(7));
let compiled = graph.compile().unwrap();
assert_eq!(compiled.execution_order(), &[producer, consumer]);
let mut expected_producer_key = FNV_OFFSET;
for value in [1, 7, 0, 0, 1, 0, 0, 0, 0] {
expected_producer_key = fnv_mix(expected_producer_key, value);
}
assert_eq!(
compiled.cache_key(producer),
Some(expected_producer_key),
"topological scheduling must not remap the key to the consumer's pass id"
);
}
#[test]
fn detects_cycles() {
let mut graph = RenderGraph::new();
let a = graph.add_resource(ResourceDesc::transient_texture("a"));
let b = graph.add_resource(ResourceDesc::transient_texture("b"));
graph.add_pass(PassDesc::new("p").read(b).write(a));
graph.add_pass(PassDesc::new("q").read(a).write(b));
assert!(graph.compile().is_err());
}
#[test]
fn rejects_multiple_writers() {
let mut graph = RenderGraph::new();
let r = graph.add_resource(ResourceDesc::transient_texture("r"));
graph.add_pass(PassDesc::new("p").write(r));
graph.add_pass(PassDesc::new("q").write(r));
assert!(graph.compile().is_err());
}
#[test]
fn rejects_unknown_resource() {
let mut graph = RenderGraph::new();
graph.add_pass(PassDesc::new("p").write(ResourceId(99)));
assert!(graph.compile().is_err());
}
#[test]
fn rejects_unproduced_transient_read() {
let mut graph = RenderGraph::new();
let transient = graph.add_resource(ResourceDesc::transient_texture("scratch"));
graph.add_pass(PassDesc::new("consumer").read(transient));
let error = graph.compile().unwrap_err().to_string();
assert!(error.contains("consumer"));
assert!(error.contains("scratch"));
}
#[test]
fn allows_imported_resource_without_writer() {
let mut graph = RenderGraph::new();
let imported = graph.add_resource(ResourceDesc::imported_texture("source"));
graph.add_pass(PassDesc::new("consumer").read(imported));
graph.compile().unwrap();
}
#[test]
fn identical_graphs_produce_identical_keys() {
let a = build_chain(100, 7).graph.compile().unwrap();
let b = build_chain(100, 7).graph.compile().unwrap();
assert_eq!(a.cache_keys, b.cache_keys);
}
#[test]
fn changing_effect_param_invalidates_only_it_and_dependents() {
let base = build_chain(100, 7);
let base_compiled = base.graph.compile().unwrap();
let changed = build_chain(100, 8);
let changed_compiled = changed.graph.compile().unwrap();
assert_eq!(
base_compiled.cache_key(base.decode),
changed_compiled.cache_key(changed.decode),
"decode is upstream of the effect and must not change"
);
assert_ne!(
base_compiled.cache_key(base.effect),
changed_compiled.cache_key(changed.effect)
);
assert_ne!(
base_compiled.cache_key(base.present),
changed_compiled.cache_key(changed.present),
"present depends on the effect and must be invalidated"
);
let changed_ids = changed_compiled.changed_passes(&base_compiled);
assert!(changed_ids.contains(&changed.effect));
assert!(changed_ids.contains(&changed.present));
assert!(!changed_ids.contains(&changed.decode));
}
#[test]
fn changing_frame_pts_invalidates_whole_downstream() {
let base = build_chain(100, 7).graph.compile().unwrap();
let next = build_chain(101, 7).graph.compile().unwrap();
assert_eq!(next.changed_passes(&base).len(), 3);
}
#[test]
fn absent_pts_does_not_collide_with_minimum_pts() {
let mut without_pts = RenderGraph::new();
let output = without_pts.add_resource(ResourceDesc::transient_texture("output"));
let pass = without_pts.add_pass(PassDesc::new("producer").write(output));
let mut with_pts = RenderGraph::new();
let output2 = with_pts.add_resource(ResourceDesc::transient_texture("output"));
with_pts.add_pass(PassDesc::new("producer").write(output2).frame_pts(i64::MIN));
assert_ne!(
without_pts.compile().unwrap().cache_key(pass),
with_pts.compile().unwrap().cache_key(pass)
);
}
#[test]
fn input_order_is_part_of_cache_topology() {
let make = |reverse: bool| {
let mut graph = RenderGraph::new();
let left = graph.add_resource(ResourceDesc::imported_texture("left"));
let right = graph.add_resource(ResourceDesc::imported_texture("right"));
let output = graph.add_resource(ResourceDesc::transient_texture("output"));
let pass = if reverse {
PassDesc::new("blend").read(right).read(left).write(output)
} else {
PassDesc::new("blend").read(left).read(right).write(output)
};
let pass = graph.add_pass(pass);
(graph, pass)
};
let (forward_graph, forward_pass) = make(false);
let (reverse_graph, reverse_pass) = make(true);
assert_ne!(
forward_graph.compile().unwrap().cache_key(forward_pass),
reverse_graph.compile().unwrap().cache_key(reverse_pass)
);
}
#[test]
fn output_topology_is_part_of_cache_key() {
let mut texture_graph = RenderGraph::new();
let texture = texture_graph.add_resource(ResourceDesc::transient_texture("output"));
let pass = texture_graph.add_pass(PassDesc::new("producer").write(texture));
let mut buffer_graph = RenderGraph::new();
let buffer = buffer_graph.add_resource(ResourceDesc {
name: "output".into(),
kind: ResourceKind::Buffer,
imported: false,
allocation_class: 0,
});
buffer_graph.add_pass(PassDesc::new("producer").write(buffer));
assert_ne!(
texture_graph.compile().unwrap().cache_key(pass),
buffer_graph.compile().unwrap().cache_key(pass)
);
}
#[test]
fn independent_branches_are_isolated() {
let mut graph = RenderGraph::new();
let in_a = graph.add_resource(ResourceDesc::imported_texture("in_a"));
let in_b = graph.add_resource(ResourceDesc::imported_texture("in_b"));
let out_a = graph.add_resource(ResourceDesc::transient_texture("out_a"));
let out_b = graph.add_resource(ResourceDesc::transient_texture("out_b"));
let pass_a = graph.add_pass(PassDesc::new("a").read(in_a).write(out_a).param_hash(1));
let pass_b = graph.add_pass(PassDesc::new("b").read(in_b).write(out_b).param_hash(2));
let base = graph.compile().unwrap();
let mut graph2 = RenderGraph::new();
let in_a2 = graph2.add_resource(ResourceDesc::imported_texture("in_a"));
let in_b2 = graph2.add_resource(ResourceDesc::imported_texture("in_b"));
let out_a2 = graph2.add_resource(ResourceDesc::transient_texture("out_a"));
let out_b2 = graph2.add_resource(ResourceDesc::transient_texture("out_b"));
let _ = graph2.add_pass(PassDesc::new("a").read(in_a2).write(out_a2).param_hash(1));
let _ = graph2.add_pass(PassDesc::new("b").read(in_b2).write(out_b2).param_hash(99));
let changed = graph2.compile().unwrap();
assert_eq!(base.cache_key(pass_a), changed.cache_key(pass_a));
assert_ne!(base.cache_key(pass_b), changed.cache_key(pass_b));
}
#[test]
fn computes_resource_lifetimes() {
let chain = build_chain(0, 0);
let compiled = chain.graph.compile().unwrap();
let frame = compiled.lifetime(chain.frame).unwrap();
assert_eq!(frame.first_pass_order, 0);
assert_eq!(frame.last_pass_order, 1);
assert!(
!compiled
.non_overlapping(chain.frame)
.contains(&chain.composited)
);
}
#[test]
fn barriers_track_read_after_write() {
let chain = build_chain(0, 0);
let compiled = chain.graph.compile().unwrap();
let barriers = compiled.barriers();
assert!(
barriers
.iter()
.any(|barrier| barrier.resource == chain.frame
&& barrier.after == chain.decode
&& barrier.before == chain.effect)
);
assert!(
barriers
.iter()
.any(|barrier| barrier.resource == chain.composited
&& barrier.after == chain.effect
&& barrier.before == chain.present)
);
}
#[test]
fn imported_resource_gets_no_transient_slot() {
let mut graph = RenderGraph::new();
let frame = graph.add_resource(ResourceDesc::transient_texture("frame"));
let backbuffer = graph.add_resource(ResourceDesc::imported_texture("backbuffer"));
graph.add_pass(PassDesc::new("decode").write(frame));
graph.add_pass(PassDesc::new("present").read(frame).write(backbuffer));
let allocation = graph.compile().unwrap().assign_transient_memory();
assert!(allocation.slot_of[frame.0 as usize].is_some());
assert!(allocation.slot_of[backbuffer.0 as usize].is_none());
}
#[test]
fn imported_resources_are_not_alias_candidates() {
let mut graph = RenderGraph::new();
let imported = graph.add_resource(ResourceDesc::imported_texture("input"));
let first = graph.add_resource(ResourceDesc::transient_texture("first"));
let second = graph.add_resource(ResourceDesc::transient_texture("second"));
graph.add_pass(PassDesc::new("read input").read(imported).write(first));
graph.add_pass(PassDesc::new("read first").read(first));
graph.add_pass(PassDesc::new("write second").write(second));
let compiled = graph.compile().unwrap();
assert!(compiled.non_overlapping(imported).is_empty());
assert!(!compiled.non_overlapping(second).contains(&imported));
}
#[test]
fn disjoint_transients_share_a_slot() {
let mut graph = RenderGraph::new();
let t1 = graph.add_resource(ResourceDesc::transient_texture("t1"));
let t2 = graph.add_resource(ResourceDesc::transient_texture("t2"));
let t3 = graph.add_resource(ResourceDesc::transient_texture("t3"));
graph.add_pass(PassDesc::new("a").write(t1));
graph.add_pass(PassDesc::new("b").read(t1).write(t2));
graph.add_pass(PassDesc::new("c").read(t2).write(t3));
graph.add_pass(PassDesc::new("d").read(t3));
let allocation = graph.compile().unwrap().assign_transient_memory();
assert_eq!(allocation.slot_count, 2);
assert_eq!(
allocation.slot_of[t1.0 as usize],
allocation.slot_of[t3.0 as usize]
);
assert_ne!(
allocation.slot_of[t1.0 as usize],
allocation.slot_of[t2.0 as usize]
);
}
#[test]
fn incompatible_resource_kinds_do_not_share_a_slot() {
let mut graph = RenderGraph::new();
let texture = graph.add_resource(ResourceDesc::transient_texture("texture"));
let buffer = graph.add_resource(ResourceDesc {
name: "buffer".into(),
kind: ResourceKind::Buffer,
imported: false,
allocation_class: 0,
});
graph.add_pass(PassDesc::new("texture pass").write(texture));
graph.add_pass(PassDesc::new("buffer pass").write(buffer));
let allocation = graph.compile().unwrap().assign_transient_memory();
assert_eq!(allocation.slot_count, 2);
assert_ne!(
allocation.slot_of[texture.0 as usize],
allocation.slot_of[buffer.0 as usize]
);
}
#[test]
fn incompatible_allocation_classes_do_not_alias() {
let mut graph = RenderGraph::new();
let first =
graph.add_resource(ResourceDesc::transient_texture("first").allocation_class(1));
let second =
graph.add_resource(ResourceDesc::transient_texture("second").allocation_class(2));
graph.add_pass(PassDesc::new("first pass").write(first));
graph.add_pass(PassDesc::new("second pass").write(second));
let compiled = graph.compile().unwrap();
let allocation = compiled.assign_transient_memory();
assert_eq!(allocation.slot_count, 2);
assert!(!compiled.non_overlapping(first).contains(&second));
}
#[test]
fn compiled_graph_tracks_the_source_revision() {
let mut graph = RenderGraph::new();
let output = graph.add_resource(ResourceDesc::transient_texture("output"));
graph.add_pass(PassDesc::new("render").write(output));
let compiled = graph.compile().unwrap();
assert!(compiled.is_current_for(&graph));
graph.add_resource(ResourceDesc::transient_texture("new resource"));
assert!(!compiled.is_current_for(&graph));
}
#[test]
fn fallible_graph_construction_enforces_name_and_reference_budgets() {
let mut graph = RenderGraph::new();
assert!(
graph
.try_add_resource(ResourceDesc::transient_texture(
"x".repeat(MAX_GRAPH_NAME_LENGTH + 1)
))
.is_err()
);
let resource = graph
.try_add_resource(ResourceDesc::transient_texture("resource"))
.unwrap();
graph.reference_count = MAX_GRAPH_REFERENCES;
assert!(
graph
.try_add_pass(PassDesc::new("pass").read(resource))
.is_err()
);
}
}
pub mod reference {
use std::collections::{HashMap, VecDeque};
use std::mem;
use anyhow::{Result, anyhow, bail};
use super::{CacheKey, CompiledGraph, PassId, RenderGraph, ResourceId, ResourceKind};
const MAX_REFERENCE_IMAGE_BYTES: usize = 256 * 1024 * 1024;
const MAX_REFERENCE_RESULT_BYTES: usize = 1024 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq)]
pub struct Image {
pub width: u32,
pub height: u32,
pub pixels: Vec<[f32; 4]>,
}
impl Image {
pub fn new(width: u32, height: u32) -> Self {
Self::try_new(width, height).expect("image dimensions exceed addressable memory")
}
pub fn try_new(width: u32, height: u32) -> Result<Self> {
let pixel_count = pixel_count(width, height)?;
Ok(Self {
width,
height,
pixels: allocate_pixels(pixel_count, [0.0; 4], width, height)?,
})
}
pub fn filled(width: u32, height: u32, color: [f32; 4]) -> Self {
Self::try_filled(width, height, color)
.expect("image dimensions exceed addressable memory")
}
pub fn try_filled(width: u32, height: u32, color: [f32; 4]) -> Result<Self> {
let pixel_count = pixel_count(width, height)?;
Ok(Self {
width,
height,
pixels: allocate_pixels(pixel_count, color, width, height)?,
})
}
pub fn from_pixels(width: u32, height: u32, pixels: Vec<[f32; 4]>) -> Result<Self> {
let expected = pixel_count(width, height)?;
if pixels.len() != expected {
bail!(
"image dimensions {width}x{height} require {expected} pixels, got {}",
pixels.len()
);
}
Ok(Self {
width,
height,
pixels,
})
}
pub const fn width(&self) -> u32 {
self.width
}
pub const fn height(&self) -> u32 {
self.height
}
pub fn pixels(&self) -> &[[f32; 4]] {
&self.pixels
}
pub fn pixels_mut(&mut self) -> &mut [[f32; 4]] {
&mut self.pixels
}
pub fn get_pixel(&self, x: u32, y: u32) -> Option<[f32; 4]> {
if x >= self.width || y >= self.height {
return None;
}
self.pixels
.get((y as usize) * (self.width as usize) + (x as usize))
.copied()
}
pub fn pixel(&self, x: u32, y: u32) -> [f32; 4] {
self.get_pixel(x, y)
.expect("pixel coordinates out of bounds")
}
fn byte_len(&self) -> usize {
self.pixels.len().saturating_mul(mem::size_of::<[f32; 4]>())
}
}
fn pixel_count(width: u32, height: u32) -> Result<usize> {
let count = u64::from(width)
.checked_mul(u64::from(height))
.ok_or_else(|| anyhow!("image dimensions {width}x{height} overflow"))?;
let count = usize::try_from(count)
.map_err(|_| anyhow!("image dimensions {width}x{height} exceed addressable memory"))?;
let bytes = count
.checked_mul(mem::size_of::<[f32; 4]>())
.ok_or_else(|| anyhow!("image dimensions {width}x{height} overflow byte length"))?;
if bytes > MAX_REFERENCE_IMAGE_BYTES {
bail!(
"image dimensions {width}x{height} require {bytes} bytes, exceeding the {MAX_REFERENCE_IMAGE_BYTES} byte reference-image limit"
);
}
Ok(count)
}
fn allocate_pixels(
pixel_count: usize,
color: [f32; 4],
width: u32,
height: u32,
) -> Result<Vec<[f32; 4]>> {
let mut pixels = Vec::new();
pixels.try_reserve_exact(pixel_count).map_err(|error| {
anyhow!("cannot allocate image storage for {width}x{height} pixels: {error}")
})?;
pixels.resize(pixel_count, color);
Ok(pixels)
}
pub type PassOp<'a> = Box<dyn Fn(&[&Image], &mut Image) + 'a>;
#[derive(Debug)]
pub struct ExecutionCache {
entries: HashMap<CacheKey, Image>,
recency: VecDeque<CacheKey>,
max_entries: usize,
max_bytes: usize,
used_bytes: usize,
}
impl ExecutionCache {
pub fn new(max_entries: usize, max_bytes: usize) -> Self {
Self {
entries: HashMap::new(),
recency: VecDeque::new(),
max_entries,
max_bytes,
used_bytes: 0,
}
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub const fn used_bytes(&self) -> usize {
self.used_bytes
}
pub fn clear(&mut self) {
self.entries.clear();
self.recency.clear();
self.used_bytes = 0;
}
fn get(&mut self, key: CacheKey, width: u32, height: u32) -> Option<Image> {
if self
.entries
.get(&key)
.is_some_and(|image| image.width != width || image.height != height)
{
if let Some(stale) = self.entries.remove(&key) {
self.used_bytes = self.used_bytes.saturating_sub(stale.byte_len());
}
self.recency.retain(|candidate| *candidate != key);
return None;
}
let image = self.entries.get(&key)?.clone();
self.recency.retain(|candidate| *candidate != key);
self.recency.push_back(key);
Some(image)
}
fn insert(&mut self, key: CacheKey, image: Image) {
let image_bytes = image.byte_len();
if self.max_entries == 0 || self.max_bytes == 0 || image_bytes > self.max_bytes {
return;
}
if let Some(previous) = self.entries.remove(&key) {
self.used_bytes = self.used_bytes.saturating_sub(previous.byte_len());
self.recency.retain(|candidate| *candidate != key);
}
while self.entries.len() >= self.max_entries
|| self.used_bytes.saturating_add(image_bytes) > self.max_bytes
{
let Some(oldest) = self.recency.pop_front() else {
break;
};
if let Some(evicted) = self.entries.remove(&oldest) {
self.used_bytes = self.used_bytes.saturating_sub(evicted.byte_len());
}
}
self.used_bytes = self.used_bytes.saturating_add(image_bytes);
self.recency.push_back(key);
self.entries.insert(key, image);
}
}
pub fn execute<'ops>(
graph: &RenderGraph,
compiled: &CompiledGraph,
width: u32,
height: u32,
imported: &HashMap<ResourceId, Image>,
ops: &HashMap<PassId, PassOp<'ops>>,
) -> Result<HashMap<ResourceId, Image>> {
validate_execution(graph, compiled, width, height, imported)?;
let mut images: HashMap<ResourceId, Image> = imported.clone();
for &pass_id in compiled.execution_order() {
let pass = graph
.pass(pass_id)
.ok_or_else(|| anyhow!("compiled graph references unknown {pass_id:?}"))?;
let mut inputs = Vec::with_capacity(pass.reads.len());
for resource in &pass.reads {
let image = images.get(resource).ok_or_else(|| {
anyhow!("pass '{}' reads unproduced {:?}", pass.name, resource)
})?;
inputs.push(image);
}
let mut output = Image::try_new(width, height)?;
if let Some(op) = ops.get(&pass_id) {
op(&inputs, &mut output);
}
validate_produced_image(pass.name.as_str(), width, height, &output)?;
store_outputs(&mut images, &pass.writes, output);
}
Ok(images)
}
pub fn execute_cached<'ops>(
graph: &RenderGraph,
compiled: &CompiledGraph,
width: u32,
height: u32,
imported: &HashMap<ResourceId, Image>,
ops: &HashMap<PassId, PassOp<'ops>>,
cache: &mut ExecutionCache,
) -> Result<(HashMap<ResourceId, Image>, Vec<PassId>)> {
validate_execution(graph, compiled, width, height, imported)?;
let mut images: HashMap<ResourceId, Image> = imported.clone();
let mut executed = Vec::new();
for &pass_id in compiled.execution_order() {
let pass = graph
.pass(pass_id)
.ok_or_else(|| anyhow!("compiled graph references unknown {pass_id:?}"))?;
let key = compiled
.cache_key(pass_id)
.ok_or_else(|| anyhow!("compiled graph has no cache key for {pass_id:?}"))?;
let output = if let Some(cached) = cache.get(key, width, height) {
cached
} else {
let mut inputs = Vec::with_capacity(pass.reads.len());
for resource in &pass.reads {
let image = images.get(resource).ok_or_else(|| {
anyhow!("pass '{}' reads unproduced {:?}", pass.name, resource)
})?;
inputs.push(image);
}
let mut produced = Image::try_new(width, height)?;
if let Some(op) = ops.get(&pass_id) {
op(&inputs, &mut produced);
}
validate_produced_image(pass.name.as_str(), width, height, &produced)?;
executed.push(pass_id);
cache.insert(key, produced.clone());
produced
};
store_outputs(&mut images, &pass.writes, output);
}
Ok((images, executed))
}
fn store_outputs(
images: &mut HashMap<ResourceId, Image>,
writes: &[ResourceId],
output: Image,
) {
let Some((last, preceding)) = writes.split_last() else {
return;
};
for &resource in preceding {
images.insert(resource, output.clone());
}
images.insert(*last, output);
}
fn validate_execution(
graph: &RenderGraph,
compiled: &CompiledGraph,
width: u32,
height: u32,
imported: &HashMap<ResourceId, Image>,
) -> Result<()> {
if !compiled.is_current_for(graph) {
bail!("compiled render graph is stale or belongs to a different graph");
}
if graph
.resources
.iter()
.any(|resource| resource.kind != ResourceKind::Texture)
{
bail!("CPU reference execution supports texture resources only");
}
validate_imported_images(graph, width, height, imported)?;
let image_bytes = pixel_count(width, height)?
.checked_mul(mem::size_of::<[f32; 4]>())
.ok_or_else(|| anyhow!("reference image byte length overflow"))?;
let mut retained = vec![false; graph.resources.len()];
for resource in imported.keys() {
retained[resource.0 as usize] = true;
}
for pass in &graph.passes {
for resource in &pass.writes {
retained[resource.0 as usize] = true;
}
}
let retained_count = retained.into_iter().filter(|retained| *retained).count();
let result_bytes = image_bytes
.checked_mul(retained_count)
.ok_or_else(|| anyhow!("reference execution result byte length overflow"))?;
if result_bytes > MAX_REFERENCE_RESULT_BYTES {
bail!(
"reference execution would retain {result_bytes} image bytes, exceeding the {MAX_REFERENCE_RESULT_BYTES} byte result limit"
);
}
Ok(())
}
fn validate_produced_image(
pass_name: &str,
width: u32,
height: u32,
image: &Image,
) -> Result<()> {
let expected_pixels = pixel_count(width, height)?;
if image.width != width || image.height != height || image.pixels.len() != expected_pixels {
bail!(
"pass '{pass_name}' produced an invalid {}x{} image with {} pixels; expected {width}x{height} with {expected_pixels} pixels",
image.width,
image.height,
image.pixels.len()
);
}
Ok(())
}
fn validate_imported_images(
graph: &RenderGraph,
width: u32,
height: u32,
imported: &HashMap<ResourceId, Image>,
) -> Result<()> {
let expected_pixels = pixel_count(width, height)?;
for (&resource, image) in imported {
let Some(desc) = graph.resources.get(resource.0 as usize) else {
return Err(anyhow!("imported image references unknown {resource:?}"));
};
if !desc.imported {
return Err(anyhow!(
"resource '{}' is transient and cannot be supplied as an imported image",
desc.name
));
}
if image.width != width || image.height != height {
return Err(anyhow!(
"imported image '{}' is {}x{}, expected {width}x{height}",
desc.name,
image.width,
image.height
));
}
if image.pixels.len() != expected_pixels {
return Err(anyhow!(
"imported image '{}' has {} pixels, expected {expected_pixels}",
desc.name,
image.pixels.len()
));
}
}
Ok(())
}
pub fn fill(color: [f32; 4]) -> PassOp<'static> {
Box::new(move |_inputs, output| {
for pixel in output.pixels.iter_mut() {
*pixel = color;
}
})
}
pub fn blend_over() -> PassOp<'static> {
Box::new(|inputs, output| {
if inputs.len() < 2 {
return;
}
let (top, bottom) = (inputs[0], inputs[1]);
for (index, pixel) in output.pixels.iter_mut().enumerate() {
let t = top.pixels[index];
let b = bottom.pixels[index];
let out_a = t[3] + b[3] * (1.0 - t[3]);
let mut out = [0.0f32; 4];
out[3] = out_a;
for channel in 0..3 {
out[channel] = if out_a <= f32::EPSILON {
0.0
} else {
(t[channel] * t[3] + b[channel] * b[3] * (1.0 - t[3])) / out_a
};
}
*pixel = out;
}
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlendMode {
Normal,
Multiply,
Screen,
Add,
Darken,
Lighten,
Overlay,
HardLight,
SoftLight,
ColorDodge,
ColorBurn,
Difference,
Exclusion,
}
impl BlendMode {
fn apply(self, backdrop: f32, source: f32) -> f32 {
match self {
Self::Normal => source,
Self::Multiply => backdrop * source,
Self::Screen => backdrop + source - backdrop * source,
Self::Add => (backdrop + source).min(1.0),
Self::Darken => backdrop.min(source),
Self::Lighten => backdrop.max(source),
Self::Overlay => hard_light(source, backdrop),
Self::HardLight => hard_light(backdrop, source),
Self::SoftLight => soft_light(backdrop, source),
Self::ColorDodge => {
if backdrop == 0.0 {
0.0
} else if source >= 1.0 {
1.0
} else {
(backdrop / (1.0 - source)).min(1.0)
}
}
Self::ColorBurn => {
if backdrop >= 1.0 {
1.0
} else if source == 0.0 {
0.0
} else {
1.0 - ((1.0 - backdrop) / source).min(1.0)
}
}
Self::Difference => (backdrop - source).abs(),
Self::Exclusion => backdrop + source - 2.0 * backdrop * source,
}
}
}
fn hard_light(backdrop: f32, source: f32) -> f32 {
if source <= 0.5 {
2.0 * backdrop * source
} else {
1.0 - 2.0 * (1.0 - backdrop) * (1.0 - source)
}
}
fn soft_light(backdrop: f32, source: f32) -> f32 {
if source <= 0.5 {
backdrop - (1.0 - 2.0 * source) * backdrop * (1.0 - backdrop)
} else {
let d = if backdrop <= 0.25 {
((16.0 * backdrop - 12.0) * backdrop + 4.0) * backdrop
} else {
backdrop.sqrt()
};
backdrop + (2.0 * source - 1.0) * (d - backdrop)
}
}
pub fn blend(mode: BlendMode) -> PassOp<'static> {
Box::new(move |inputs, output| {
if inputs.len() < 2 {
return;
}
let (top, bottom) = (inputs[0], inputs[1]);
for (index, pixel) in output.pixels.iter_mut().enumerate() {
let s = top.pixels[index];
let b = bottom.pixels[index];
let (a_s, a_b) = (s[3], b[3]);
let out_a = a_s + a_b * (1.0 - a_s);
let mut out = [0.0f32; 4];
out[3] = out_a;
for channel in 0..3 {
let blended = mode.apply(b[channel], s[channel]);
let premultiplied = a_s * (1.0 - a_b) * s[channel]
+ a_s * a_b * blended
+ a_b * (1.0 - a_s) * b[channel];
out[channel] = if out_a <= f32::EPSILON {
0.0
} else {
premultiplied / out_a
};
}
*pixel = out;
}
})
}
pub fn translate(dx: i32, dy: i32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
let (width, height) = (output.width as i32, output.height as i32);
for y in 0..height {
for x in 0..width {
let (sx, sy) = (x - dx, y - dy);
let value = if sx >= 0
&& sx < source.width as i32
&& sy >= 0
&& sy < source.height as i32
{
source.pixels[(sy as u32 * source.width + sx as u32) as usize]
} else {
[0.0; 4]
};
output.pixels[(y as u32 * output.width + x as u32) as usize] = value;
}
}
})
}
pub fn crossfade(mix: f32) -> PassOp<'static> {
let mix = mix.clamp(0.0, 1.0);
Box::new(move |inputs, output| {
if inputs.len() < 2 {
return;
}
let (from, to) = (inputs[0], inputs[1]);
for (index, pixel) in output.pixels.iter_mut().enumerate() {
let a = from.pixels[index];
let b = to.pixels[index];
let mut out = [0.0f32; 4];
for channel in 0..4 {
out[channel] = a[channel] * (1.0 - mix) + b[channel] * mix;
}
*pixel = out;
}
})
}
pub fn wipe_horizontal(progress: f32) -> PassOp<'static> {
let progress = progress.clamp(0.0, 1.0);
Box::new(move |inputs, output| {
if inputs.len() < 2 {
return;
}
let (from, to) = (inputs[0], inputs[1]);
let boundary = (progress * output.width as f32) as u32;
for y in 0..output.height {
for x in 0..output.width {
let index = (y * output.width + x) as usize;
output.pixels[index] = if x < boundary {
to.pixels[index]
} else {
from.pixels[index]
};
}
}
})
}
pub fn wipe_vertical(progress: f32) -> PassOp<'static> {
let progress = progress.clamp(0.0, 1.0);
Box::new(move |inputs, output| {
if inputs.len() < 2 {
return;
}
let (from, to) = (inputs[0], inputs[1]);
let boundary = (progress * output.height as f32) as u32;
for y in 0..output.height {
for x in 0..output.width {
let index = (y * output.width + x) as usize;
output.pixels[index] = if y < boundary {
to.pixels[index]
} else {
from.pixels[index]
};
}
}
})
}
pub fn dip_to_color(color: [f32; 4], progress: f32) -> PassOp<'static> {
let progress = progress.clamp(0.0, 1.0);
Box::new(move |inputs, output| {
if inputs.len() < 2 {
return;
}
let (from, to) = (inputs[0], inputs[1]);
let (source, mix) = if progress < 0.5 {
(from, 1.0 - progress * 2.0)
} else {
(to, progress * 2.0 - 1.0)
};
for (index, pixel) in output.pixels.iter_mut().enumerate() {
let edge = source.pixels[index];
let mut out = [0.0f32; 4];
for channel in 0..4 {
out[channel] = edge[channel] * mix + color[channel] * (1.0 - mix);
}
*pixel = out;
}
})
}
pub fn iris(progress: f32) -> PassOp<'static> {
let progress = progress.clamp(0.0, 1.0);
Box::new(move |inputs, output| {
if inputs.len() < 2 {
return;
}
let (from, to) = (inputs[0], inputs[1]);
let (cx, cy) = (output.width as f32 / 2.0, output.height as f32 / 2.0);
let max_radius = (cx * cx + cy * cy).sqrt();
let radius = progress * max_radius;
for y in 0..output.height {
for x in 0..output.width {
let index = (y * output.width + x) as usize;
let (dx, dy) = (x as f32 + 0.5 - cx, y as f32 + 0.5 - cy);
output.pixels[index] = if (dx * dx + dy * dy).sqrt() < radius {
to.pixels[index]
} else {
from.pixels[index]
};
}
}
})
}
pub fn push_horizontal(progress: f32) -> PassOp<'static> {
let progress = progress.clamp(0.0, 1.0);
Box::new(move |inputs, output| {
if inputs.len() < 2 {
return;
}
let (from, to) = (inputs[0], inputs[1]);
let width = output.width;
let shift = (progress * width as f32) as u32;
let split = width - shift;
for y in 0..output.height {
let row = y * width;
for x in 0..width {
let index = (row + x) as usize;
output.pixels[index] = if x < split {
from.pixels[(row + x + shift) as usize]
} else {
to.pixels[(row + (x - split)) as usize]
};
}
}
})
}
fn sample_bilinear(image: &Image, u: f32, v: f32) -> [f32; 4] {
let max_x = image.width as i32 - 1;
let max_y = image.height as i32 - 1;
let x0 = u.floor() as i32;
let y0 = v.floor() as i32;
let (fx, fy) = (u - x0 as f32, v - y0 as f32);
let get = |x: i32, y: i32| {
let cx = x.clamp(0, max_x) as u32;
let cy = y.clamp(0, max_y) as u32;
image.pixels[(cy * image.width + cx) as usize]
};
let (c00, c10, c01, c11) = (
get(x0, y0),
get(x0 + 1, y0),
get(x0, y0 + 1),
get(x0 + 1, y0 + 1),
);
let mut out = [0.0f32; 4];
for channel in 0..4 {
let top = c00[channel] * (1.0 - fx) + c10[channel] * fx;
let bottom = c01[channel] * (1.0 - fx) + c11[channel] * fx;
out[channel] = top * (1.0 - fy) + bottom * fy;
}
out
}
fn bounded_radius(radius: u32, width: u32, height: u32) -> i32 {
radius
.min(width.max(height).saturating_sub(1))
.min(i32::MAX as u32) as i32
}
pub fn resample() -> PassOp<'static> {
Box::new(|inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width == 0 || source.height == 0 {
return;
}
for oy in 0..output.height {
for ox in 0..output.width {
let u = (ox as f32 + 0.5) / output.width as f32 * source.width as f32 - 0.5;
let v = (oy as f32 + 0.5) / output.height as f32 * source.height as f32 - 0.5;
output.pixels[(oy * output.width + ox) as usize] =
sample_bilinear(source, u, v);
}
}
})
}
pub fn place(dst_x: i32, dst_y: i32, dst_width: u32, dst_height: u32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
for oy in 0..output.height {
for ox in 0..output.width {
let index = (oy * output.width + ox) as usize;
let rel_x = ox as i32 - dst_x;
let rel_y = oy as i32 - dst_y;
let inside = dst_width > 0
&& dst_height > 0
&& source.width > 0
&& source.height > 0
&& rel_x >= 0
&& (rel_x as u32) < dst_width
&& rel_y >= 0
&& (rel_y as u32) < dst_height;
output.pixels[index] = if inside {
let u = (rel_x as f32 + 0.5) / dst_width as f32 * source.width as f32 - 0.5;
let v =
(rel_y as f32 + 0.5) / dst_height as f32 * source.height as f32 - 0.5;
sample_bilinear(source, u, v)
} else {
[0.0; 4]
};
}
}
})
}
pub fn box_blur(radius: u32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
let radius = bounded_radius(radius, source.width, source.height);
let (width, height) = (output.width as i32, output.height as i32);
for y in 0..height {
for x in 0..width {
let mut sum = [0.0f32; 4];
let mut count = 0.0f32;
for dy in -radius..=radius {
for dx in -radius..=radius {
let sx = (x + dx).clamp(0, width - 1);
let sy = (y + dy).clamp(0, height - 1);
let pixel = source.pixels[(sy * width + sx) as usize];
for channel in 0..4 {
sum[channel] += pixel[channel];
}
count += 1.0;
}
}
let index = (y * width + x) as usize;
output.pixels[index] = [
sum[0] / count,
sum[1] / count,
sum[2] / count,
sum[3] / count,
];
}
}
})
}
pub fn gaussian_blur(sigma: f32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
if !sigma.is_finite() || sigma <= 0.0 || source.pixels.is_empty() {
output.pixels.copy_from_slice(&source.pixels);
return;
}
let max_radius = bounded_radius(u32::MAX, source.width, source.height);
let radius = ((f64::from(sigma) * 3.0).ceil().min(f64::from(max_radius))) as i32;
let denom = 2.0 * sigma * sigma;
let mut kernel = Vec::with_capacity((radius * 2 + 1) as usize);
let mut total = 0.0f32;
for offset in -radius..=radius {
let coordinate = offset as f32;
let weight = (-(coordinate * coordinate) / denom).exp();
kernel.push(weight);
total += weight;
}
for weight in &mut kernel {
*weight /= total;
}
let (width, height) = (output.width as i32, output.height as i32);
let mut horizontal = vec![[0.0f32; 4]; source.pixels.len()];
for y in 0..height {
for x in 0..width {
let mut sum = [0.0f32; 4];
for (tap, &weight) in kernel.iter().enumerate() {
let sx = (x + tap as i32 - radius).clamp(0, width - 1);
let pixel = source.pixels[(y * width + sx) as usize];
for channel in 0..4 {
sum[channel] += pixel[channel] * weight;
}
}
horizontal[(y * width + x) as usize] = sum;
}
}
for y in 0..height {
for x in 0..width {
let mut sum = [0.0f32; 4];
for (tap, &weight) in kernel.iter().enumerate() {
let sy = (y + tap as i32 - radius).clamp(0, height - 1);
let pixel = horizontal[(sy * width + x) as usize];
for channel in 0..4 {
sum[channel] += pixel[channel] * weight;
}
}
output.pixels[(y * width + x) as usize] = sum;
}
}
})
}
pub fn unsharp_mask(sigma: f32, amount: f32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
let mut blurred = Image::new(source.width, source.height);
gaussian_blur(sigma)(inputs, &mut blurred);
for ((out_pixel, source_pixel), blur_pixel) in output
.pixels
.iter_mut()
.zip(&source.pixels)
.zip(&blurred.pixels)
{
for channel in 0..3 {
let high_pass = source_pixel[channel] - blur_pixel[channel];
out_pixel[channel] =
(source_pixel[channel] + amount * high_pass).clamp(0.0, 1.0);
}
out_pixel[3] = source_pixel[3];
}
})
}
pub fn directional_blur(dx: f32, dy: f32, radius: u32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
let length = (dx * dx + dy * dy).sqrt();
if radius == 0 || !length.is_finite() || length <= f32::EPSILON {
output.pixels.copy_from_slice(&source.pixels);
return;
}
let (step_x, step_y) = (dx / length, dy / length);
let radius = bounded_radius(radius, source.width, source.height);
let tap_count = (radius * 2 + 1) as f32;
let (width, height) = (output.width, output.height);
for y in 0..height {
for x in 0..width {
let mut sum = [0.0f32; 4];
for tap in -radius..=radius {
let u = x as f32 + tap as f32 * step_x;
let v = y as f32 + tap as f32 * step_y;
let sample = sample_bilinear(source, u, v);
for channel in 0..4 {
sum[channel] += sample[channel];
}
}
output.pixels[(y * width + x) as usize] = [
sum[0] / tap_count,
sum[1] / tap_count,
sum[2] / tap_count,
sum[3] / tap_count,
];
}
}
})
}
pub fn drop_shadow(
offset_x: i32,
offset_y: i32,
sigma: f32,
color: [f32; 3],
opacity: f32,
) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
let (width, height) = (source.width, source.height);
let mut shadow = Image::new(width, height);
for y in 0..height as i64 {
for x in 0..width as i64 {
let sx = x - offset_x as i64;
let sy = y - offset_y as i64;
let alpha = if sx >= 0 && sx < width as i64 && sy >= 0 && sy < height as i64 {
source.pixels[(sy as u32 * width + sx as u32) as usize][3]
} else {
0.0
};
shadow.pixels[(y as u32 * width + x as u32) as usize] =
[alpha, alpha, alpha, alpha];
}
}
let mut blurred = Image::new(width, height);
gaussian_blur(sigma)(&[&shadow], &mut blurred);
for ((out_pixel, source_pixel), blur_pixel) in output
.pixels
.iter_mut()
.zip(&source.pixels)
.zip(&blurred.pixels)
{
let source_alpha = source_pixel[3];
let shadow_alpha = (blur_pixel[3] * opacity).clamp(0.0, 1.0);
let out_alpha = source_alpha + shadow_alpha * (1.0 - source_alpha);
if out_alpha > 0.0 {
let over = |source_channel: f32, shadow_channel: f32| {
(source_channel * source_alpha
+ shadow_channel * shadow_alpha * (1.0 - source_alpha))
/ out_alpha
};
*out_pixel = [
over(source_pixel[0], color[0]),
over(source_pixel[1], color[1]),
over(source_pixel[2], color[2]),
out_alpha,
];
} else {
*out_pixel = [0.0, 0.0, 0.0, 0.0];
}
}
})
}
pub fn bloom(threshold: f32, sigma: f32, intensity: f32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
let mut bright = Image::new(source.width, source.height);
for (bright_pixel, source_pixel) in bright.pixels.iter_mut().zip(&source.pixels) {
*bright_pixel = [
(source_pixel[0] - threshold).max(0.0),
(source_pixel[1] - threshold).max(0.0),
(source_pixel[2] - threshold).max(0.0),
1.0,
];
}
let mut blurred = Image::new(source.width, source.height);
gaussian_blur(sigma)(&[&bright], &mut blurred);
for ((out_pixel, source_pixel), blur_pixel) in output
.pixels
.iter_mut()
.zip(&source.pixels)
.zip(&blurred.pixels)
{
*out_pixel = [
(source_pixel[0] + intensity * blur_pixel[0]).clamp(0.0, 1.0),
(source_pixel[1] + intensity * blur_pixel[1]).clamp(0.0, 1.0),
(source_pixel[2] + intensity * blur_pixel[2]).clamp(0.0, 1.0),
source_pixel[3],
];
}
})
}
pub fn vignette(amount: f32, radius: f32, softness: f32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
let (width, height) = (source.width, source.height);
if width == 0 || height == 0 {
return;
}
let corner_distance = 0.5f32.sqrt();
let falloff = softness.max(f32::EPSILON);
for y in 0..height {
for x in 0..width {
let dx = (x as f32 + 0.5) / width as f32 - 0.5;
let dy = (y as f32 + 0.5) / height as f32 - 0.5;
let distance = (dx * dx + dy * dy).sqrt() / corner_distance;
let t = ((distance - radius) / falloff).clamp(0.0, 1.0);
let smooth = t * t * (3.0 - 2.0 * t);
let factor = (1.0 - amount * smooth).max(0.0);
let pixel = source.pixels[(y * width + x) as usize];
output.pixels[(y * width + x) as usize] = [
pixel[0] * factor,
pixel[1] * factor,
pixel[2] * factor,
pixel[3],
];
}
}
})
}
pub fn sobel_edges(scale: f32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
let (width, height) = (source.width as i32, source.height as i32);
let luma = |x: i32, y: i32| -> f32 {
let cx = x.clamp(0, width - 1) as u32;
let cy = y.clamp(0, height - 1) as u32;
let pixel = source.pixels[(cy * source.width + cx) as usize];
0.2126 * pixel[0] + 0.7152 * pixel[1] + 0.0722 * pixel[2]
};
for y in 0..height {
for x in 0..width {
let gx = -luma(x - 1, y - 1) + luma(x + 1, y - 1) - 2.0 * luma(x - 1, y)
+ 2.0 * luma(x + 1, y)
- luma(x - 1, y + 1)
+ luma(x + 1, y + 1);
let gy = -luma(x - 1, y - 1) - 2.0 * luma(x, y - 1) - luma(x + 1, y - 1)
+ luma(x - 1, y + 1)
+ 2.0 * luma(x, y + 1)
+ luma(x + 1, y + 1);
let magnitude = ((gx * gx + gy * gy).sqrt() * scale).clamp(0.0, 1.0);
let index = (y as u32 * source.width + x as u32) as usize;
output.pixels[index] =
[magnitude, magnitude, magnitude, source.pixels[index][3]];
}
}
})
}
pub fn pixelate(block_size: u32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
if block_size <= 1 {
output.pixels.copy_from_slice(&source.pixels);
return;
}
let (width, height) = (source.width, source.height);
let mut block_y = 0;
while block_y < height {
let y_end = block_y.saturating_add(block_size).min(height);
let mut block_x = 0;
while block_x < width {
let x_end = block_x.saturating_add(block_size).min(width);
let mut sum = [0.0f32; 4];
let mut count = 0.0f32;
for y in block_y..y_end {
for x in block_x..x_end {
let pixel = source.pixels[(y * width + x) as usize];
for channel in 0..4 {
sum[channel] += pixel[channel];
}
count += 1.0;
}
}
let average = [
sum[0] / count,
sum[1] / count,
sum[2] / count,
sum[3] / count,
];
for y in block_y..y_end {
for x in block_x..x_end {
output.pixels[(y * width + x) as usize] = average;
}
}
block_x = x_end;
}
block_y = y_end;
}
})
}
pub fn median_filter(radius: u32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
if radius == 0 {
output.pixels.copy_from_slice(&source.pixels);
return;
}
let radius = bounded_radius(radius, source.width, source.height);
let (width, height) = (source.width as i32, source.height as i32);
for y in 0..height {
for x in 0..width {
let mut channels: [Vec<f32>; 3] = [Vec::new(), Vec::new(), Vec::new()];
for dy in -radius..=radius {
for dx in -radius..=radius {
let sx = (x + dx).clamp(0, width - 1);
let sy = (y + dy).clamp(0, height - 1);
let pixel = source.pixels[(sy * width + sx) as usize];
for (channel, samples) in channels.iter_mut().enumerate() {
samples.push(pixel[channel]);
}
}
}
let index = (y * width + x) as usize;
let mut result = source.pixels[index];
for (channel, samples) in channels.iter_mut().enumerate() {
samples.sort_by(f32::total_cmp);
result[channel] = samples[samples.len() / 2];
}
output.pixels[index] = result;
}
}
})
}
fn morphology(radius: u32, take_max: bool) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
if radius == 0 {
output.pixels.copy_from_slice(&source.pixels);
return;
}
let radius = bounded_radius(radius, source.width, source.height);
let (width, height) = (source.width as i32, source.height as i32);
for y in 0..height {
for x in 0..width {
let mut accumulator = if take_max {
[f32::NEG_INFINITY; 4]
} else {
[f32::INFINITY; 4]
};
for dy in -radius..=radius {
for dx in -radius..=radius {
let sx = (x + dx).clamp(0, width - 1);
let sy = (y + dy).clamp(0, height - 1);
let pixel = source.pixels[(sy * width + sx) as usize];
for channel in 0..4 {
accumulator[channel] = if take_max {
accumulator[channel].max(pixel[channel])
} else {
accumulator[channel].min(pixel[channel])
};
}
}
}
output.pixels[(y * width + x) as usize] = accumulator;
}
}
})
}
pub fn dilate(radius: u32) -> PassOp<'static> {
morphology(radius, true)
}
pub fn erode(radius: u32) -> PassOp<'static> {
morphology(radius, false)
}
pub fn luma_key(threshold: f32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
let luma =
0.2126 * source_pixel[0] + 0.7152 * source_pixel[1] + 0.0722 * source_pixel[2];
let alpha = if luma < threshold {
0.0
} else {
source_pixel[3]
};
*output_pixel = [source_pixel[0], source_pixel[1], source_pixel[2], alpha];
}
})
}
pub fn chroma_key(color: [f32; 3], tolerance: f32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
let distance = ((source_pixel[0] - color[0]).powi(2)
+ (source_pixel[1] - color[1]).powi(2)
+ (source_pixel[2] - color[2]).powi(2))
.sqrt();
let alpha = if distance <= tolerance {
0.0
} else {
source_pixel[3]
};
*output_pixel = [source_pixel[0], source_pixel[1], source_pixel[2], alpha];
}
})
}
pub fn luma_matte() -> PassOp<'static> {
Box::new(|inputs, output| {
let (Some(source), Some(matte)) = (inputs.first(), inputs.get(1)) else {
return;
};
if source.width != output.width
|| source.height != output.height
|| matte.width != source.width
|| matte.height != source.height
{
return;
}
for ((output_pixel, source_pixel), matte_pixel) in output
.pixels
.iter_mut()
.zip(&source.pixels)
.zip(&matte.pixels)
{
let luma =
(0.2126 * matte_pixel[0] + 0.7152 * matte_pixel[1] + 0.0722 * matte_pixel[2])
.clamp(0.0, 1.0);
*output_pixel = [
source_pixel[0],
source_pixel[1],
source_pixel[2],
source_pixel[3] * luma,
];
}
})
}
pub fn alpha_matte() -> PassOp<'static> {
Box::new(|inputs, output| {
let (Some(source), Some(matte)) = (inputs.first(), inputs.get(1)) else {
return;
};
if source.width != output.width
|| source.height != output.height
|| matte.width != source.width
|| matte.height != source.height
{
return;
}
for ((output_pixel, source_pixel), matte_pixel) in output
.pixels
.iter_mut()
.zip(&source.pixels)
.zip(&matte.pixels)
{
*output_pixel = [
source_pixel[0],
source_pixel[1],
source_pixel[2],
source_pixel[3] * matte_pixel[3].clamp(0.0, 1.0),
];
}
})
}
pub fn premultiply() -> PassOp<'static> {
Box::new(|inputs, output| {
let Some(source) = inputs.first() else {
return;
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
let alpha = source_pixel[3];
*output_pixel = [
source_pixel[0] * alpha,
source_pixel[1] * alpha,
source_pixel[2] * alpha,
alpha,
];
}
})
}
pub fn unpremultiply() -> PassOp<'static> {
Box::new(|inputs, output| {
let Some(source) = inputs.first() else {
return;
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
let alpha = source_pixel[3];
*output_pixel = if alpha <= f32::EPSILON {
[0.0, 0.0, 0.0, alpha]
} else {
[
source_pixel[0] / alpha,
source_pixel[1] / alpha,
source_pixel[2] / alpha,
alpha,
]
};
}
})
}
pub fn convolve_3x3(kernel: [[f32; 3]; 3]) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
let (width, height) = (output.width as i32, output.height as i32);
for y in 0..height {
for x in 0..width {
let mut acc = [0.0f32; 3];
for (ky, row) in kernel.iter().enumerate() {
for (kx, weight) in row.iter().enumerate() {
let sx = (x + kx as i32 - 1).clamp(0, width - 1);
let sy = (y + ky as i32 - 1).clamp(0, height - 1);
let pixel = source.pixels[(sy * width + sx) as usize];
for channel in 0..3 {
acc[channel] += weight * pixel[channel];
}
}
}
let index = (y * width + x) as usize;
let alpha = source.pixels[index][3];
output.pixels[index] = [
acc[0].clamp(0.0, 1.0),
acc[1].clamp(0.0, 1.0),
acc[2].clamp(0.0, 1.0),
alpha,
];
}
}
})
}
pub fn despill_green() -> PassOp<'static> {
Box::new(|inputs, output| {
let Some(source) = inputs.first() else {
return;
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
let limit = source_pixel[0].max(source_pixel[2]);
*output_pixel = [
source_pixel[0],
source_pixel[1].min(limit),
source_pixel[2],
source_pixel[3],
];
}
})
}
pub fn exposure(stops: f32) -> PassOp<'static> {
let gain = 2.0f32.powf(stops);
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
*output_pixel = [
(source_pixel[0] * gain).clamp(0.0, 1.0),
(source_pixel[1] * gain).clamp(0.0, 1.0),
(source_pixel[2] * gain).clamp(0.0, 1.0),
source_pixel[3],
];
}
})
}
pub fn gamma(power: f32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
let curve = |value: f32| {
if power > 0.0 {
value.clamp(0.0, 1.0).powf(power)
} else {
value
}
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
*output_pixel = [
curve(source_pixel[0]),
curve(source_pixel[1]),
curve(source_pixel[2]),
source_pixel[3],
];
}
})
}
pub fn lift_gamma_gain(lift: [f32; 3], gamma: [f32; 3], gain: [f32; 3]) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
let grade = |value: f32, lift: f32, gamma: f32, gain: f32| {
let scaled = (value * gain + lift).clamp(0.0, 1.0);
if gamma > 0.0 {
scaled.powf(1.0 / gamma)
} else {
scaled
}
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
*output_pixel = [
grade(source_pixel[0], lift[0], gamma[0], gain[0]),
grade(source_pixel[1], lift[1], gamma[1], gain[1]),
grade(source_pixel[2], lift[2], gamma[2], gain[2]),
source_pixel[3],
];
}
})
}
pub fn temperature_tint(temperature: f32, tint: f32) -> PassOp<'static> {
let red_gain = 1.0 + temperature;
let green_gain = 1.0 - tint;
let blue_gain = 1.0 - temperature;
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
*output_pixel = [
(source_pixel[0] * red_gain).clamp(0.0, 1.0),
(source_pixel[1] * green_gain).clamp(0.0, 1.0),
(source_pixel[2] * blue_gain).clamp(0.0, 1.0),
source_pixel[3],
];
}
})
}
pub fn flip_horizontal() -> PassOp<'static> {
Box::new(|inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
let width = output.width;
for y in 0..output.height {
for x in 0..width {
output.pixels[(y * width + x) as usize] =
source.pixels[(y * width + (width - 1 - x)) as usize];
}
}
})
}
pub fn flip_vertical() -> PassOp<'static> {
Box::new(|inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
let (width, height) = (output.width, output.height);
for y in 0..height {
for x in 0..width {
output.pixels[(y * width + x) as usize] =
source.pixels[((height - 1 - y) * width + x) as usize];
}
}
})
}
pub fn rotate(radians: f32) -> PassOp<'static> {
let (sin, cos) = radians.sin_cos();
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width != output.width || source.height != output.height {
return;
}
let (width, height) = (output.width, output.height);
let (center_x, center_y) = (width as f32 / 2.0, height as f32 / 2.0);
for y in 0..height {
for x in 0..width {
let dx = x as f32 + 0.5 - center_x;
let dy = y as f32 + 0.5 - center_y;
let source_x = center_x + dx * cos + dy * sin - 0.5;
let source_y = center_y - dx * sin + dy * cos - 0.5;
let pixel = if source_x >= -0.5
&& source_x <= width as f32 - 0.5
&& source_y >= -0.5
&& source_y <= height as f32 - 0.5
{
sample_bilinear(source, source_x, source_y)
} else {
[0.0; 4]
};
output.pixels[(y * width + x) as usize] = pixel;
}
}
})
}
pub fn letterbox() -> PassOp<'static> {
Box::new(|inputs, output| {
let Some(source) = inputs.first() else {
return;
};
if source.width == 0 || source.height == 0 {
return;
}
let (out_w, out_h) = (output.width as f32, output.height as f32);
let (src_w, src_h) = (source.width as f32, source.height as f32);
let scale = (out_w / src_w).min(out_h / src_h);
let fit_w = src_w * scale;
let fit_h = src_h * scale;
let offset_x = (out_w - fit_w) / 2.0;
let offset_y = (out_h - fit_h) / 2.0;
for y in 0..output.height {
for x in 0..output.width {
let fit_x = x as f32 + 0.5 - offset_x;
let fit_y = y as f32 + 0.5 - offset_y;
let index = (y * output.width + x) as usize;
output.pixels[index] =
if fit_x >= 0.0 && fit_x < fit_w && fit_y >= 0.0 && fit_y < fit_h {
let u = fit_x / fit_w * src_w - 0.5;
let v = fit_y / fit_h * src_h - 0.5;
sample_bilinear(source, u, v)
} else {
[0.0; 4]
};
}
}
})
}
pub fn saturation(amount: f32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
let luma =
0.2126 * source_pixel[0] + 0.7152 * source_pixel[1] + 0.0722 * source_pixel[2];
let mix = |channel: f32| (luma + amount * (channel - luma)).clamp(0.0, 1.0);
*output_pixel = [
mix(source_pixel[0]),
mix(source_pixel[1]),
mix(source_pixel[2]),
source_pixel[3],
];
}
})
}
pub fn tone_curve(control_points: Vec<[f32; 2]>) -> PassOp<'static> {
let mut points: Vec<[f32; 2]> = control_points
.into_iter()
.filter(|point| point[0].is_finite() && point[1].is_finite())
.map(|point| [point[0].clamp(0.0, 1.0), point[1].clamp(0.0, 1.0)])
.collect();
points.sort_by(|a, b| a[0].total_cmp(&b[0]));
points.dedup_by(|a, b| a[0] == b[0]);
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
let apply = |value: f32| -> f32 {
if points.len() < 2 {
return value;
}
let clamped = value.clamp(0.0, 1.0);
if clamped <= points[0][0] {
return points[0][1];
}
let last = points[points.len() - 1];
if clamped >= last[0] {
return last[1];
}
let upper = points.partition_point(|point| point[0] <= clamped);
let [x0, y0] = points[upper - 1];
let [x1, y1] = points[upper];
let t = (clamped - x0) / (x1 - x0);
y0 + t * (y1 - y0)
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
*output_pixel = [
apply(source_pixel[0]),
apply(source_pixel[1]),
apply(source_pixel[2]),
source_pixel[3],
];
}
})
}
pub fn channel_mixer(matrix: [[f32; 3]; 3]) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
let mix = |row: [f32; 3]| {
(row[0] * source_pixel[0] + row[1] * source_pixel[1] + row[2] * source_pixel[2])
.clamp(0.0, 1.0)
};
*output_pixel = [
mix(matrix[0]),
mix(matrix[1]),
mix(matrix[2]),
source_pixel[3],
];
}
})
}
pub fn levels(
in_black: f32,
in_white: f32,
gamma: f32,
out_black: f32,
out_white: f32,
) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
let span = in_white - in_black;
let remap = |value: f32| {
let mut normalized = if span > 0.0 {
((value - in_black) / span).clamp(0.0, 1.0)
} else {
value.clamp(0.0, 1.0)
};
if gamma > 0.0 {
normalized = normalized.powf(1.0 / gamma);
}
out_black + normalized * (out_white - out_black)
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
*output_pixel = [
remap(source_pixel[0]),
remap(source_pixel[1]),
remap(source_pixel[2]),
source_pixel[3],
];
}
})
}
pub fn solarize(threshold: f32) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
let fold = |value: f32| {
if value >= threshold {
1.0 - value
} else {
value
}
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
*output_pixel = [
fold(source_pixel[0]),
fold(source_pixel[1]),
fold(source_pixel[2]),
source_pixel[3],
];
}
})
}
pub fn posterize(levels: u32) -> PassOp<'static> {
let steps = levels.max(2) as f32 - 1.0;
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
let quantize = |value: f32| (value.clamp(0.0, 1.0) * steps).round() / steps;
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
*output_pixel = [
quantize(source_pixel[0]),
quantize(source_pixel[1]),
quantize(source_pixel[2]),
source_pixel[3],
];
}
})
}
pub fn invert() -> PassOp<'static> {
Box::new(|inputs, output| {
let Some(source) = inputs.first() else {
return;
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
*output_pixel = [
1.0 - source_pixel[0],
1.0 - source_pixel[1],
1.0 - source_pixel[2],
source_pixel[3],
];
}
})
}
pub fn duotone(shadow: [f32; 3], highlight: [f32; 3]) -> PassOp<'static> {
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
let luma = (0.2126 * source_pixel[0]
+ 0.7152 * source_pixel[1]
+ 0.0722 * source_pixel[2])
.clamp(0.0, 1.0);
*output_pixel = [
shadow[0] + (highlight[0] - shadow[0]) * luma,
shadow[1] + (highlight[1] - shadow[1]) * luma,
shadow[2] + (highlight[2] - shadow[2]) * luma,
source_pixel[3],
];
}
})
}
pub fn hue_rotate(radians: f32) -> PassOp<'static> {
let (sin, cos) = radians.sin_cos();
let matrix = [
[
0.213 + cos * 0.787 - sin * 0.213,
0.715 - cos * 0.715 - sin * 0.715,
0.072 - cos * 0.072 + sin * 0.928,
],
[
0.213 - cos * 0.213 + sin * 0.143,
0.715 + cos * 0.285 + sin * 0.140,
0.072 - cos * 0.072 - sin * 0.283,
],
[
0.213 - cos * 0.213 - sin * 0.787,
0.715 - cos * 0.715 + sin * 0.715,
0.072 + cos * 0.928 + sin * 0.072,
],
];
Box::new(move |inputs, output| {
let Some(source) = inputs.first() else {
return;
};
for (output_pixel, source_pixel) in output.pixels.iter_mut().zip(&source.pixels) {
let (r, g, b) = (source_pixel[0], source_pixel[1], source_pixel[2]);
let channel =
|row: [f32; 3]| (row[0] * r + row[1] * g + row[2] * b).clamp(0.0, 1.0);
*output_pixel = [
channel(matrix[0]),
channel(matrix[1]),
channel(matrix[2]),
source_pixel[3],
];
}
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{PassDesc, ResourceDesc};
fn cache_chain(effect_param: u64) -> (RenderGraph, [PassId; 3], ResourceId) {
let mut graph = RenderGraph::new();
let frame = graph.add_resource(ResourceDesc::transient_texture("frame"));
let composited = graph.add_resource(ResourceDesc::transient_texture("composited"));
let backbuffer = graph.add_resource(ResourceDesc::imported_texture("backbuffer"));
let decode = graph.add_pass(PassDesc::new("decode").write(frame).frame_pts(0));
let effect = graph.add_pass(
PassDesc::new("effect")
.read(frame)
.write(composited)
.param_hash(effect_param),
);
let present =
graph.add_pass(PassDesc::new("present").read(composited).write(backbuffer));
(graph, [decode, effect, present], backbuffer)
}
fn chain_ops(ids: [PassId; 3]) -> HashMap<PassId, PassOp<'static>> {
let mut ops = HashMap::new();
ops.insert(ids[0], fill([1.0, 0.0, 0.0, 1.0]));
ops.insert(ids[1], fill([0.0, 1.0, 0.0, 1.0]));
ops.insert(ids[2], fill([0.0, 0.0, 1.0, 1.0]));
ops
}
#[test]
fn execute_cached_skips_unchanged_passes_on_replay() {
let (graph, ids, backbuffer) = cache_chain(7);
let compiled = graph.compile().unwrap();
let ops = chain_ops(ids);
let imported = HashMap::new();
let mut cache = ExecutionCache::new(16, 1024 * 1024);
let (first, ran_first) =
execute_cached(&graph, &compiled, 2, 2, &imported, &ops, &mut cache).unwrap();
assert_eq!(ran_first.len(), 3, "every pass runs on the cold cache");
let (second, ran_second) =
execute_cached(&graph, &compiled, 2, 2, &imported, &ops, &mut cache).unwrap();
assert!(
ran_second.is_empty(),
"an identical replay is all cache hits"
);
assert_eq!(first[&backbuffer].pixels, second[&backbuffer].pixels);
}
#[test]
fn execute_cached_reruns_only_the_dirty_subtree() {
let (graph_a, ids_a, _) = cache_chain(7);
let compiled_a = graph_a.compile().unwrap();
let ops_a = chain_ops(ids_a);
let imported = HashMap::new();
let mut cache = ExecutionCache::new(16, 1024 * 1024);
execute_cached(&graph_a, &compiled_a, 2, 2, &imported, &ops_a, &mut cache).unwrap();
let (graph_b, ids_b, _) = cache_chain(8);
let [decode_b, effect_b, present_b] = ids_b;
let compiled_b = graph_b.compile().unwrap();
let ops_b = chain_ops(ids_b);
let (_, ran) =
execute_cached(&graph_b, &compiled_b, 2, 2, &imported, &ops_b, &mut cache).unwrap();
assert!(
!ran.contains(&decode_b),
"decode is unaffected and stays cached"
);
assert!(ran.contains(&effect_b), "the changed effect re-runs");
assert!(
ran.contains(&present_b),
"present depends on the effect and re-runs"
);
assert_eq!(ran.len(), 2);
}
#[test]
fn execute_cached_matches_uncached_execute() {
let (graph, ids, _) = cache_chain(7);
let compiled = graph.compile().unwrap();
let ops = chain_ops(ids);
let imported = HashMap::new();
let plain = execute(&graph, &compiled, 2, 2, &imported, &ops).unwrap();
let mut cache = ExecutionCache::new(16, 1024 * 1024);
let (cached, _) =
execute_cached(&graph, &compiled, 2, 2, &imported, &ops, &mut cache).unwrap();
assert_eq!(plain.len(), cached.len());
for (resource, image) in &plain {
assert_eq!(cached[resource].pixels, image.pixels, "{resource:?}");
}
}
#[test]
fn execute_cached_recomputes_at_a_new_resolution() {
let (graph, ids, backbuffer) = cache_chain(7);
let compiled = graph.compile().unwrap();
let ops = chain_ops(ids);
let imported = HashMap::new();
let mut cache = ExecutionCache::new(16, 1024 * 1024);
execute_cached(&graph, &compiled, 2, 2, &imported, &ops, &mut cache).unwrap();
let (images, ran) =
execute_cached(&graph, &compiled, 3, 3, &imported, &ops, &mut cache).unwrap();
assert_eq!(ran.len(), 3);
assert_eq!(
(images[&backbuffer].width, images[&backbuffer].height),
(3, 3)
);
assert_eq!(images[&backbuffer].pixels.len(), 9);
}
#[test]
fn execution_cache_evicts_by_recency_and_size() {
let mut cache = ExecutionCache::new(2, 128);
cache.insert(crate::CacheKey(1), Image::new(2, 2));
cache.insert(crate::CacheKey(2), Image::new(2, 2));
assert!(cache.get(crate::CacheKey(1), 2, 2).is_some());
cache.insert(crate::CacheKey(3), Image::new(2, 2));
assert!(cache.get(crate::CacheKey(2), 2, 2).is_none());
assert_eq!(cache.len(), 2);
assert_eq!(cache.used_bytes(), 128);
cache.insert(crate::CacheKey(4), Image::new(3, 3));
assert_eq!(cache.len(), 2, "an oversized entry is not retained");
cache.clear();
assert!(cache.is_empty());
assert_eq!(cache.used_bytes(), 0);
}
#[test]
fn executor_rejects_malformed_pass_output() {
let mut graph = RenderGraph::new();
let out = graph.add_resource(ResourceDesc::transient_texture("out"));
let pass = graph.add_pass(PassDesc::new("malformed").write(out));
let compiled = graph.compile().unwrap();
let mut ops: HashMap<PassId, PassOp<'static>> = HashMap::new();
ops.insert(
pass,
Box::new(|_inputs, output| {
output.pixels.pop();
}),
);
let error = execute(&graph, &compiled, 2, 2, &HashMap::new(), &ops)
.unwrap_err()
.to_string();
assert!(error.contains("malformed"));
assert!(error.contains("expected 2x2 with 4 pixels"));
}
#[test]
fn image_construction_and_checked_access_validate_shape() {
assert!(Image::from_pixels(2, 2, vec![[0.0; 4]; 3]).is_err());
let image = Image::from_pixels(2, 1, vec![[0.1; 4], [0.2; 4]]).unwrap();
assert_eq!(image.get_pixel(1, 0), Some([0.2; 4]));
assert_eq!(image.get_pixel(2, 0), None);
}
#[test]
fn executes_a_composite() {
let mut graph = RenderGraph::new();
let overlay = graph.add_resource(ResourceDesc::transient_texture("overlay"));
let bg = graph.add_resource(ResourceDesc::imported_texture("bg"));
let out = graph.add_resource(ResourceDesc::transient_texture("out"));
let paint = graph.add_pass(PassDesc::new("paint").write(overlay));
let comp = graph.add_pass(PassDesc::new("comp").read(overlay).read(bg).write(out));
let compiled = graph.compile().unwrap();
let mut imported = HashMap::new();
imported.insert(bg, Image::filled(2, 2, [0.0, 0.0, 1.0, 1.0]));
let mut ops: HashMap<PassId, PassOp<'static>> = HashMap::new();
ops.insert(paint, fill([1.0, 0.0, 0.0, 0.5]));
ops.insert(comp, blend_over());
let result = execute(&graph, &compiled, 2, 2, &imported, &ops).unwrap();
let pixel = result[&out].pixel(1, 1);
assert!((pixel[0] - 0.5).abs() < 1e-6, "{pixel:?}");
assert!((pixel[1] - 0.0).abs() < 1e-6, "{pixel:?}");
assert!((pixel[2] - 0.5).abs() < 1e-6, "{pixel:?}");
assert!((pixel[3] - 1.0).abs() < 1e-6, "{pixel:?}");
}
#[test]
fn errors_on_unproduced_input() {
let mut graph = RenderGraph::new();
let missing = graph.add_resource(ResourceDesc::imported_texture("missing"));
let out = graph.add_resource(ResourceDesc::transient_texture("out"));
graph.add_pass(PassDesc::new("p").read(missing).write(out));
let compiled = graph.compile().unwrap();
let result = execute(&graph, &compiled, 1, 1, &HashMap::new(), &HashMap::new());
assert!(result.is_err());
}
#[test]
fn rejects_malformed_or_mismatched_imported_images() {
let mut graph = RenderGraph::new();
let input = graph.add_resource(ResourceDesc::imported_texture("input"));
let output = graph.add_resource(ResourceDesc::transient_texture("output"));
graph.add_pass(PassDesc::new("copy").read(input).write(output));
let compiled = graph.compile().unwrap();
let mut imported = HashMap::new();
imported.insert(input, Image::new(2, 1));
assert!(execute(&graph, &compiled, 1, 1, &imported, &HashMap::new()).is_err());
imported.insert(
input,
Image {
width: 1,
height: 1,
pixels: Vec::new(),
},
);
assert!(execute(&graph, &compiled, 1, 1, &imported, &HashMap::new()).is_err());
}
#[test]
fn oversized_images_fail_allocation_cleanly() {
assert!(Image::try_new(u32::MAX, u32::MAX).is_err());
assert!(Image::try_filled(u32::MAX, u32::MAX, [1.0; 4]).is_err());
assert!(Image::try_new(4_097, 4_096).is_err());
}
#[test]
fn executor_rejects_stale_foreign_and_non_texture_graphs() {
let mut graph = RenderGraph::new();
let output = graph.add_resource(ResourceDesc::transient_texture("output"));
graph.add_pass(PassDesc::new("render").write(output));
let compiled = graph.compile().unwrap();
graph.add_resource(ResourceDesc::transient_texture("later"));
assert!(execute(&graph, &compiled, 1, 1, &HashMap::new(), &HashMap::new()).is_err());
let mut other = RenderGraph::new();
let output = other.add_resource(ResourceDesc::transient_texture("output"));
other.add_pass(PassDesc::new("render").write(output));
assert!(execute(&other, &compiled, 1, 1, &HashMap::new(), &HashMap::new()).is_err());
let mut buffers = RenderGraph::new();
let output = buffers.add_resource(ResourceDesc {
name: "buffer".into(),
kind: ResourceKind::Buffer,
imported: false,
allocation_class: 0,
});
buffers.add_pass(PassDesc::new("render").write(output));
let compiled = buffers.compile().unwrap();
assert!(execute(&buffers, &compiled, 1, 1, &HashMap::new(), &HashMap::new()).is_err());
}
#[test]
fn executor_rejects_results_over_the_resident_byte_limit() {
let mut graph = RenderGraph::new();
let mut pass = PassDesc::new("wide output");
for index in 0..5 {
let resource =
graph.add_resource(ResourceDesc::transient_texture(format!("output {index}")));
pass = pass.write(resource);
}
graph.add_pass(pass);
let compiled = graph.compile().unwrap();
let error = execute(
&graph,
&compiled,
4_096,
4_096,
&HashMap::new(),
&HashMap::new(),
)
.unwrap_err()
.to_string();
assert!(error.contains("result limit"));
}
#[test]
fn blend_over_with_missing_inputs_is_a_noop() {
let mut output = Image::filled(1, 1, [0.25; 4]);
blend_over()(&[], &mut output);
assert_eq!(output.pixel(0, 0), [0.25; 4]);
}
#[test]
fn blend_modes_combine_layers() {
let gray = Image::filled(1, 1, [0.5, 0.5, 0.5, 1.0]);
let run = |mode| {
let mut out = Image::new(1, 1);
blend(mode)(&[&gray, &gray], &mut out);
out.pixel(0, 0)[0]
};
assert!((run(BlendMode::Normal) - 0.5).abs() < 1e-6);
assert!((run(BlendMode::Multiply) - 0.25).abs() < 1e-6);
assert!((run(BlendMode::Screen) - 0.75).abs() < 1e-6);
assert!((run(BlendMode::Add) - 1.0).abs() < 1e-6);
}
#[test]
fn separable_blend_modes_match_w3c() {
let backdrop = Image::filled(1, 1, [0.6, 0.6, 0.6, 1.0]);
let source = Image::filled(1, 1, [0.25, 0.25, 0.25, 1.0]);
let run = |mode| {
let mut out = Image::new(1, 1);
blend(mode)(&[&source, &backdrop], &mut out);
out.pixel(0, 0)[0]
};
let approx = |actual: f32, expected: f32| (actual - expected).abs() < 1e-5;
assert!(approx(run(BlendMode::Darken), 0.25));
assert!(approx(run(BlendMode::Lighten), 0.6));
assert!(approx(run(BlendMode::HardLight), 0.30));
assert!(approx(run(BlendMode::Overlay), 0.40));
assert!(approx(run(BlendMode::Difference), 0.35));
assert!(approx(run(BlendMode::Exclusion), 0.55));
assert!(approx(run(BlendMode::ColorDodge), 0.8));
assert!(approx(run(BlendMode::ColorBurn), 0.0));
assert!(approx(run(BlendMode::SoftLight), 0.48));
}
#[test]
fn blend_mode_boundary_cases_are_defined() {
let white = Image::filled(1, 1, [1.0, 1.0, 1.0, 1.0]);
let black = Image::filled(1, 1, [0.0, 0.0, 0.0, 1.0]);
let gray = Image::filled(1, 1, [0.5, 0.5, 0.5, 1.0]);
let channel = |mode, top: &Image, bottom: &Image| {
let mut out = Image::new(1, 1);
blend(mode)(&[top, bottom], &mut out);
out.pixel(0, 0)[0]
};
assert!((channel(BlendMode::ColorDodge, &white, &gray) - 1.0).abs() < 1e-6);
assert!((channel(BlendMode::ColorBurn, &black, &gray) - 0.0).abs() < 1e-6);
}
#[test]
fn translate_shifts_pixels() {
let source = Image::filled(2, 2, [1.0, 0.0, 0.0, 1.0]);
let mut out = Image::new(2, 2);
translate(1, 0)(&[&source], &mut out);
assert_eq!(out.pixel(0, 0), [0.0, 0.0, 0.0, 0.0]);
assert_eq!(out.pixel(1, 0), [1.0, 0.0, 0.0, 1.0]);
}
#[test]
fn crossfade_dissolves_between_inputs() {
let red = Image::filled(1, 1, [1.0, 0.0, 0.0, 1.0]);
let blue = Image::filled(1, 1, [0.0, 0.0, 1.0, 1.0]);
let mut out = Image::new(1, 1);
crossfade(0.0)(&[&red, &blue], &mut out);
assert_eq!(out.pixel(0, 0), [1.0, 0.0, 0.0, 1.0]);
crossfade(1.0)(&[&red, &blue], &mut out);
assert_eq!(out.pixel(0, 0), [0.0, 0.0, 1.0, 1.0]);
crossfade(0.5)(&[&red, &blue], &mut out);
let mid = out.pixel(0, 0);
assert!((mid[0] - 0.5).abs() < 1e-6 && (mid[2] - 0.5).abs() < 1e-6);
}
#[test]
fn wipe_reveals_second_input_from_left() {
let red = Image::filled(4, 1, [1.0, 0.0, 0.0, 1.0]);
let blue = Image::filled(4, 1, [0.0, 0.0, 1.0, 1.0]);
let mut out = Image::new(4, 1);
wipe_horizontal(0.5)(&[&red, &blue], &mut out);
assert_eq!(out.pixel(0, 0), [0.0, 0.0, 1.0, 1.0]);
assert_eq!(out.pixel(1, 0), [0.0, 0.0, 1.0, 1.0]);
assert_eq!(out.pixel(2, 0), [1.0, 0.0, 0.0, 1.0]);
assert_eq!(out.pixel(3, 0), [1.0, 0.0, 0.0, 1.0]);
}
#[test]
fn wipe_vertical_reveals_from_top() {
let red = Image::filled(1, 4, [1.0, 0.0, 0.0, 1.0]);
let blue = Image::filled(1, 4, [0.0, 0.0, 1.0, 1.0]);
let mut out = Image::new(1, 4);
wipe_vertical(0.5)(&[&red, &blue], &mut out);
assert_eq!(out.pixel(0, 0), [0.0, 0.0, 1.0, 1.0]);
assert_eq!(out.pixel(0, 1), [0.0, 0.0, 1.0, 1.0]);
assert_eq!(out.pixel(0, 2), [1.0, 0.0, 0.0, 1.0]);
assert_eq!(out.pixel(0, 3), [1.0, 0.0, 0.0, 1.0]);
}
#[test]
fn dip_to_color_passes_through_color_at_midpoint() {
let red = Image::filled(1, 1, [1.0, 0.0, 0.0, 1.0]);
let blue = Image::filled(1, 1, [0.0, 0.0, 1.0, 1.0]);
let black = [0.0, 0.0, 0.0, 1.0];
let run = |progress| {
let mut out = Image::new(1, 1);
dip_to_color(black, progress)(&[&red, &blue], &mut out);
out.pixel(0, 0)
};
assert_eq!(run(0.0), [1.0, 0.0, 0.0, 1.0]);
assert_eq!(run(1.0), [0.0, 0.0, 1.0, 1.0]);
let mid = run(0.5);
assert!(
mid.iter().zip(black).all(|(a, b)| (a - b).abs() < 1e-6),
"midpoint should be the dip color: {mid:?}"
);
}
#[test]
fn iris_expands_from_center() {
let red = Image::filled(3, 3, [1.0, 0.0, 0.0, 1.0]);
let blue = Image::filled(3, 3, [0.0, 0.0, 1.0, 1.0]);
let mut out0 = Image::new(3, 3);
iris(0.0)(&[&red, &blue], &mut out0);
assert!(out0.pixels.iter().all(|p| *p == [1.0, 0.0, 0.0, 1.0]));
let mut out1 = Image::new(3, 3);
iris(1.0)(&[&red, &blue], &mut out1);
assert!(out1.pixels.iter().all(|p| *p == [0.0, 0.0, 1.0, 1.0]));
let mut mid = Image::new(3, 3);
iris(0.2)(&[&red, &blue], &mut mid);
assert_eq!(mid.pixel(1, 1), [0.0, 0.0, 1.0, 1.0]);
assert_eq!(mid.pixel(0, 0), [1.0, 0.0, 0.0, 1.0]);
}
#[test]
fn push_horizontal_slides_in_from_right() {
let red = Image::filled(4, 1, [1.0, 0.0, 0.0, 1.0]);
let blue = Image::filled(4, 1, [0.0, 0.0, 1.0, 1.0]);
let run = |progress| {
let mut out = Image::new(4, 1);
push_horizontal(progress)(&[&red, &blue], &mut out);
out
};
assert!(run(0.0).pixels.iter().all(|p| *p == [1.0, 0.0, 0.0, 1.0]));
assert!(run(1.0).pixels.iter().all(|p| *p == [0.0, 0.0, 1.0, 1.0]));
let half = run(0.5);
assert_eq!(half.pixel(0, 0), [1.0, 0.0, 0.0, 1.0]);
assert_eq!(half.pixel(3, 0), [0.0, 0.0, 1.0, 1.0]);
}
#[test]
fn resample_is_identity_at_same_size() {
let mut source = Image::new(2, 2);
source.pixels = vec![
[1.0, 0.0, 0.0, 1.0],
[0.0, 1.0, 0.0, 1.0],
[0.0, 0.0, 1.0, 1.0],
[1.0, 1.0, 0.0, 1.0],
];
let mut out = Image::new(2, 2);
resample()(&[&source], &mut out);
assert_eq!(out.pixels, source.pixels);
}
#[test]
fn resample_upscales_solid_color() {
let source = Image::filled(2, 2, [0.4, 0.6, 0.8, 1.0]);
let mut out = Image::new(8, 8);
resample()(&[&source], &mut out);
assert!(out.pixels.iter().all(|pixel| {
pixel
.iter()
.zip([0.4, 0.6, 0.8, 1.0])
.all(|(a, b)| (a - b).abs() < 1e-5)
}));
}
#[test]
fn place_fills_destination_rect_and_clears_outside() {
let source = Image::filled(1, 1, [1.0, 0.0, 0.0, 1.0]);
let mut out = Image::new(4, 4);
place(0, 0, 2, 2)(&[&source], &mut out);
assert_eq!(out.pixel(0, 0), [1.0, 0.0, 0.0, 1.0]);
assert_eq!(out.pixel(1, 1), [1.0, 0.0, 0.0, 1.0]);
assert_eq!(out.pixel(2, 2), [0.0, 0.0, 0.0, 0.0]);
assert_eq!(out.pixel(3, 0), [0.0, 0.0, 0.0, 0.0]);
}
#[test]
fn place_respects_offset_position() {
let source = Image::filled(1, 1, [0.0, 1.0, 0.0, 1.0]);
let mut out = Image::new(4, 4);
place(2, 1, 1, 1)(&[&source], &mut out);
assert_eq!(out.pixel(2, 1), [0.0, 1.0, 0.0, 1.0]);
assert_eq!(out.pixel(0, 0), [0.0, 0.0, 0.0, 0.0]);
}
#[test]
fn box_blur_radius_zero_is_passthrough() {
let mut source = Image::new(2, 2);
source.pixels = vec![
[1.0, 0.0, 0.0, 1.0],
[0.0, 1.0, 0.0, 1.0],
[0.0, 0.0, 1.0, 1.0],
[1.0, 1.0, 0.0, 1.0],
];
let mut out = Image::new(2, 2);
box_blur(0)(&[&source], &mut out);
assert_eq!(out.pixels, source.pixels);
}
#[test]
fn extreme_filter_parameters_are_bounded() {
let source = Image::filled(1, 1, [0.25, 0.5, 0.75, 1.0]);
let filters = [
box_blur(u32::MAX),
directional_blur(1.0, 0.0, u32::MAX),
median_filter(u32::MAX),
dilate(u32::MAX),
erode(u32::MAX),
gaussian_blur(f32::NAN),
];
for filter in filters {
let mut output = Image::new(1, 1);
filter(&[&source], &mut output);
assert_eq!(output, source);
}
}
#[test]
fn box_blur_preserves_solids_and_smooths_edges() {
let solid = Image::filled(3, 3, [0.5, 0.5, 0.5, 1.0]);
let mut out = Image::new(3, 3);
box_blur(1)(&[&solid], &mut out);
assert!(out.pixels.iter().all(|p| (p[0] - 0.5).abs() < 1e-6));
let mut edge = Image::new(4, 1);
edge.pixels = vec![
[0.0, 0.0, 0.0, 1.0],
[0.0, 0.0, 0.0, 1.0],
[1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0],
];
let mut blurred = Image::new(4, 1);
box_blur(1)(&[&edge], &mut blurred);
let red: Vec<f32> = blurred.pixels.iter().map(|p| p[0]).collect();
assert!((red[0]).abs() < 1e-6 && (red[3] - 1.0).abs() < 1e-6);
assert!(
red[1] > red[0] && red[2] > red[1] && red[3] > red[2],
"{red:?}"
);
}
#[test]
fn luma_key_masks_dark_pixels_and_keeps_color() {
let mut source = Image::new(3, 1);
source.pixels = vec![
[0.0, 0.0, 0.0, 1.0], [0.25, 0.25, 0.25, 1.0], [1.0, 1.0, 1.0, 1.0], ];
let mut out = Image::new(3, 1);
luma_key(0.5)(&[&source], &mut out);
assert_eq!(out.pixel(0, 0)[3], 0.0);
assert_eq!(out.pixel(1, 0)[3], 0.0);
assert_eq!(out.pixel(2, 0)[3], 1.0);
assert_eq!(out.pixel(2, 0), [1.0, 1.0, 1.0, 1.0]);
assert_eq!(&out.pixel(0, 0)[0..3], &[0.0, 0.0, 0.0]);
}
#[test]
fn chroma_key_removes_key_color_and_keeps_others() {
let mut source = Image::new(3, 1);
source.pixels = vec![
[0.0, 1.0, 0.0, 1.0], [0.1, 0.9, 0.1, 1.0], [1.0, 0.0, 0.0, 1.0], ];
let mut out = Image::new(3, 1);
chroma_key([0.0, 1.0, 0.0], 0.2)(&[&source], &mut out);
assert_eq!(out.pixel(0, 0)[3], 0.0);
assert_eq!(out.pixel(1, 0)[3], 0.0);
assert_eq!(out.pixel(2, 0)[3], 1.0);
assert_eq!(&out.pixel(2, 0)[0..3], &[1.0, 0.0, 0.0]);
}
#[test]
fn luma_matte_scales_alpha_by_matte_luminance() {
let source = Image::filled(2, 2, [0.2, 0.4, 0.8, 1.0]);
let apply = |matte: &Image| {
let mut out = Image::new(2, 2);
luma_matte()(&[&source, matte], &mut out);
out.pixel(0, 0)
};
assert!((apply(&Image::filled(2, 2, [1.0, 1.0, 1.0, 1.0]))[3] - 1.0).abs() < 1e-6);
assert!(apply(&Image::filled(2, 2, [0.0, 0.0, 0.0, 1.0]))[3] < 1e-6);
let masked = apply(&Image::filled(2, 2, [0.5, 0.5, 0.5, 1.0]));
assert!((masked[3] - 0.5).abs() < 1e-6);
assert!((masked[0] - 0.2).abs() < 1e-6 && (masked[2] - 0.8).abs() < 1e-6);
}
#[test]
fn alpha_matte_scales_alpha_by_matte_alpha() {
let source = Image::filled(1, 1, [0.5, 0.5, 0.5, 0.8]);
let matte = Image::filled(1, 1, [0.0, 0.0, 0.0, 0.5]);
let mut out = Image::new(1, 1);
alpha_matte()(&[&source, &matte], &mut out);
assert!((out.pixel(0, 0)[3] - 0.4).abs() < 1e-6);
assert!((out.pixel(0, 0)[0] - 0.5).abs() < 1e-6);
}
#[test]
fn matte_size_mismatch_is_a_noop() {
let source = Image::filled(2, 2, [1.0, 1.0, 1.0, 1.0]);
let matte = Image::filled(1, 1, [1.0, 1.0, 1.0, 1.0]);
let mut out = Image::new(2, 2);
luma_matte()(&[&source, &matte], &mut out);
assert!(out.pixels.iter().all(|pixel| pixel[3] == 0.0));
}
#[test]
fn premultiply_unpremultiply_round_trip() {
let mut source = Image::new(2, 1);
source.pixels = vec![[1.0, 0.5, 0.0, 0.5], [0.0, 0.0, 0.0, 0.0]];
let mut premultiplied = Image::new(2, 1);
premultiply()(&[&source], &mut premultiplied);
assert_eq!(premultiplied.pixel(0, 0), [0.5, 0.25, 0.0, 0.5]);
assert_eq!(premultiplied.pixel(1, 0), [0.0, 0.0, 0.0, 0.0]);
let mut restored = Image::new(2, 1);
unpremultiply()(&[&premultiplied], &mut restored);
assert_eq!(restored.pixel(0, 0), [1.0, 0.5, 0.0, 0.5]);
assert_eq!(restored.pixel(1, 0), [0.0, 0.0, 0.0, 0.0]);
}
#[test]
fn convolve_identity_is_passthrough() {
let identity = [[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]];
let mut source = Image::new(2, 2);
source.pixels = vec![
[0.2, 0.4, 0.6, 1.0],
[0.1, 0.2, 0.3, 1.0],
[0.9, 0.8, 0.7, 1.0],
[0.5, 0.5, 0.5, 1.0],
];
let mut out = Image::new(2, 2);
convolve_3x3(identity)(&[&source], &mut out);
for (got, want) in out.pixels.iter().zip(&source.pixels) {
for channel in 0..3 {
assert!(
(got[channel] - want[channel]).abs() < 1e-6,
"{got:?} vs {want:?}"
);
}
}
}
#[test]
fn convolve_sharpen_preserves_solids() {
let sharpen = [[0.0, -1.0, 0.0], [-1.0, 5.0, -1.0], [0.0, -1.0, 0.0]];
let solid = Image::filled(3, 3, [0.5, 0.5, 0.5, 1.0]);
let mut out = Image::new(3, 3);
convolve_3x3(sharpen)(&[&solid], &mut out);
assert!(out.pixels.iter().all(|p| (p[0] - 0.5).abs() < 1e-6));
}
#[test]
fn gaussian_blur_preserves_a_flat_region() {
let solid = Image::filled(8, 8, [0.3, 0.6, 0.9, 1.0]);
let mut out = Image::new(8, 8);
gaussian_blur(2.0)(&[&solid], &mut out);
for pixel in &out.pixels {
for channel in 0..4 {
assert!((pixel[channel] - solid.pixels[0][channel]).abs() < 1e-5);
}
}
}
#[test]
fn gaussian_blur_zero_sigma_is_identity() {
let mut source = Image::new(3, 3);
source.pixels[4] = [1.0, 0.5, 0.25, 1.0];
let mut out = Image::new(3, 3);
gaussian_blur(0.0)(&[&source], &mut out);
assert_eq!(out.pixels, source.pixels);
}
#[test]
fn gaussian_blur_spreads_an_impulse_symmetrically() {
let mut source = Image::new(5, 5);
source.pixels[2 * 5 + 2] = [1.0, 0.0, 0.0, 0.0];
let mut out = Image::new(5, 5);
gaussian_blur(1.0)(&[&source], &mut out);
let center = out.pixel(2, 2)[0];
assert!(center > 0.0 && center < 1.0);
assert!((out.pixel(1, 2)[0] - out.pixel(3, 2)[0]).abs() < 1e-6);
assert!((out.pixel(2, 1)[0] - out.pixel(2, 3)[0]).abs() < 1e-6);
assert!((out.pixel(1, 1)[0] - out.pixel(3, 3)[0]).abs() < 1e-6);
assert!((out.pixel(1, 1)[0] - out.pixel(1, 3)[0]).abs() < 1e-6);
assert!(out.pixel(1, 2)[0] > 0.0);
assert!(center > out.pixel(1, 2)[0]);
assert!(out.pixel(1, 2)[0] > out.pixel(0, 2)[0]);
}
#[test]
fn unsharp_mask_zero_amount_is_identity() {
let mut source = Image::new(4, 4);
source.pixels[5] = [0.8, 0.2, 0.5, 1.0];
source.pixels[10] = [0.1, 0.9, 0.3, 0.5];
let mut out = Image::new(4, 4);
unsharp_mask(2.0, 0.0)(&[&source], &mut out);
for (got, want) in out.pixels.iter().zip(&source.pixels) {
for channel in 0..4 {
assert!(
(got[channel] - want[channel]).abs() < 1e-6,
"{got:?} vs {want:?}"
);
}
}
}
#[test]
fn unsharp_mask_preserves_a_flat_region() {
let solid = Image::filled(6, 6, [0.4, 0.5, 0.6, 1.0]);
let mut out = Image::new(6, 6);
unsharp_mask(1.5, 1.5)(&[&solid], &mut out);
for pixel in &out.pixels {
for channel in 0..4 {
assert!((pixel[channel] - solid.pixels[0][channel]).abs() < 1e-5);
}
}
}
#[test]
fn unsharp_mask_overshoots_at_an_edge() {
let mut source = Image::new(6, 1);
for x in 0..3 {
source.pixels[x] = [0.3, 0.3, 0.3, 1.0];
}
for x in 3..6 {
source.pixels[x] = [0.7, 0.7, 0.7, 1.0];
}
let mut out = Image::new(6, 1);
unsharp_mask(1.0, 1.0)(&[&source], &mut out);
assert!(out.pixel(2, 0)[0] < 0.3, "{:?}", out.pixel(2, 0));
assert!(out.pixel(3, 0)[0] > 0.7, "{:?}", out.pixel(3, 0));
assert!((out.pixel(2, 0)[3] - 1.0).abs() < 1e-6);
}
#[test]
fn directional_blur_zero_radius_is_identity() {
let mut source = Image::new(3, 3);
source.pixels[4] = [0.9, 0.1, 0.4, 1.0];
let mut out = Image::new(3, 3);
directional_blur(1.0, 1.0, 0)(&[&source], &mut out);
assert_eq!(out.pixels, source.pixels);
let mut out2 = Image::new(3, 3);
directional_blur(0.0, 0.0, 4)(&[&source], &mut out2);
assert_eq!(out2.pixels, source.pixels);
}
#[test]
fn directional_blur_preserves_a_flat_region() {
let solid = Image::filled(5, 5, [0.2, 0.4, 0.6, 1.0]);
let mut out = Image::new(5, 5);
directional_blur(1.0, 0.0, 2)(&[&solid], &mut out);
for pixel in &out.pixels {
for channel in 0..4 {
assert!((pixel[channel] - solid.pixels[0][channel]).abs() < 1e-6);
}
}
}
#[test]
fn directional_blur_smears_only_along_its_axis() {
let mut column = Image::new(5, 5);
for y in 0..5 {
column.pixels[y * 5 + 2] = [1.0, 1.0, 1.0, 1.0];
}
let mut blurred_column = Image::new(5, 5);
directional_blur(1.0, 0.0, 1)(&[&column], &mut blurred_column);
assert!(blurred_column.pixel(2, 2)[0] < 1.0);
assert!(blurred_column.pixel(1, 2)[0] > 0.0);
assert!(blurred_column.pixel(3, 2)[0] > 0.0);
let mut row = Image::new(5, 5);
for x in 0..5 {
row.pixels[2 * 5 + x] = [1.0, 1.0, 1.0, 1.0];
}
let mut blurred_row = Image::new(5, 5);
directional_blur(1.0, 0.0, 1)(&[&row], &mut blurred_row);
assert!((blurred_row.pixel(2, 2)[0] - 1.0).abs() < 1e-6);
assert!(blurred_row.pixel(2, 1)[0] < 1e-6);
}
#[test]
fn drop_shadow_leaves_a_fully_opaque_source_unchanged() {
let source = Image::filled(5, 5, [0.3, 0.6, 0.9, 1.0]);
let mut out = Image::new(5, 5);
drop_shadow(2, 2, 1.5, [0.0, 0.0, 0.0], 1.0)(&[&source], &mut out);
for (got, want) in out.pixels.iter().zip(&source.pixels) {
for channel in 0..4 {
assert!(
(got[channel] - want[channel]).abs() < 1e-6,
"{got:?} vs {want:?}"
);
}
}
}
#[test]
fn drop_shadow_casts_into_transparent_areas() {
let mut source = Image::new(5, 5);
source.pixels[2 * 5 + 2] = [1.0, 1.0, 1.0, 1.0];
let mut out = Image::new(5, 5);
drop_shadow(1, 1, 0.0, [0.0, 0.0, 0.0], 1.0)(&[&source], &mut out);
let shadow = out.pixel(3, 3);
assert!(shadow[0] < 1e-6 && shadow[1] < 1e-6 && shadow[2] < 1e-6);
assert!((shadow[3] - 1.0).abs() < 1e-6);
let center = out.pixel(2, 2);
assert!((center[0] - 1.0).abs() < 1e-6 && (center[3] - 1.0).abs() < 1e-6);
}
#[test]
fn drop_shadow_zero_opacity_returns_source() {
let mut source = Image::new(4, 4);
source.pixels[5] = [0.8, 0.2, 0.5, 1.0];
source.pixels[10] = [0.1, 0.9, 0.3, 0.6];
let mut out = Image::new(4, 4);
drop_shadow(1, 1, 2.0, [0.0, 0.0, 0.0], 0.0)(&[&source], &mut out);
for (got, want) in out.pixels.iter().zip(&source.pixels) {
for channel in 0..4 {
assert!(
(got[channel] - want[channel]).abs() < 1e-6,
"{got:?} vs {want:?}"
);
}
}
}
#[test]
fn bloom_below_threshold_or_zero_intensity_is_identity() {
let source = Image::filled(4, 4, [0.4, 0.5, 0.6, 1.0]);
let mut gated = Image::new(4, 4);
bloom(1.0, 2.0, 1.0)(&[&source], &mut gated);
let mut dark = Image::new(4, 4);
bloom(0.0, 2.0, 0.0)(&[&source], &mut dark);
for out in [&gated, &dark] {
for (got, want) in out.pixels.iter().zip(&source.pixels) {
for channel in 0..4 {
assert!(
(got[channel] - want[channel]).abs() < 1e-6,
"{got:?} vs {want:?}"
);
}
}
}
}
#[test]
fn bloom_spreads_bright_regions_into_neighbors() {
let mut source = Image::filled(5, 5, [0.0, 0.0, 0.0, 1.0]);
source.pixels[2 * 5 + 2] = [1.0, 1.0, 1.0, 1.0];
let mut out = Image::new(5, 5);
bloom(0.5, 1.0, 1.0)(&[&source], &mut out);
assert!(out.pixel(1, 2)[0] > 0.0);
assert!(out.pixel(2, 1)[0] > 0.0);
assert!(out.pixel(2, 2)[0] >= 1.0 - 1e-6);
assert_eq!(out.pixel(1, 2)[3], 1.0);
assert_eq!(out.pixel(2, 2)[3], 1.0);
}
#[test]
fn vignette_zero_amount_is_identity() {
let mut source = Image::new(4, 4);
source.pixels[5] = [0.8, 0.4, 0.2, 1.0];
source.pixels[10] = [0.3, 0.7, 0.9, 0.5];
let mut out = Image::new(4, 4);
vignette(0.0, 0.5, 0.5)(&[&source], &mut out);
assert_eq!(out.pixels, source.pixels);
}
#[test]
fn vignette_darkens_monotonically_outward() {
let source = Image::filled(5, 5, [0.8, 0.8, 0.8, 1.0]);
let mut out = Image::new(5, 5);
vignette(1.0, 0.0, 1.0)(&[&source], &mut out);
let center = out.pixel(2, 2)[0];
let edge = out.pixel(0, 2)[0];
let corner = out.pixel(0, 0)[0];
assert!((center - 0.8).abs() < 1e-6);
assert!(edge < center);
assert!(corner < edge);
assert_eq!(out.pixel(0, 0)[3], 1.0);
}
#[test]
fn sobel_edges_flat_region_is_black() {
let source = Image::filled(4, 4, [0.5, 0.5, 0.5, 1.0]);
let mut out = Image::new(4, 4);
sobel_edges(1.0)(&[&source], &mut out);
for pixel in &out.pixels {
assert!(
pixel[0] < 1e-6 && pixel[1] < 1e-6 && pixel[2] < 1e-6,
"{pixel:?}"
);
assert_eq!(pixel[3], 1.0);
}
}
#[test]
fn sobel_edges_fire_at_a_vertical_boundary() {
let mut source = Image::filled(5, 5, [0.0, 0.0, 0.0, 1.0]);
for y in 0..5 {
for x in 2..5 {
source.pixels[y * 5 + x] = [1.0, 1.0, 1.0, 1.0];
}
}
let mut out = Image::new(5, 5);
sobel_edges(1.0)(&[&source], &mut out);
assert!(out.pixel(0, 2)[0] < 1e-6);
assert!(out.pixel(2, 2)[0] > 0.5);
assert!(out.pixel(4, 2)[0] < 1e-6);
assert_eq!(out.pixel(2, 2)[3], 1.0);
let mut zeroed = Image::new(5, 5);
sobel_edges(0.0)(&[&source], &mut zeroed);
assert!(zeroed.pixel(2, 2)[0] < 1e-6);
}
#[test]
fn pixelate_block_size_one_or_flat_is_unchanged() {
let mut varied = Image::new(3, 3);
varied.pixels[4] = [0.8, 0.2, 0.5, 1.0];
varied.pixels[7] = [0.1, 0.9, 0.3, 0.6];
let mut out = Image::new(3, 3);
pixelate(1)(&[&varied], &mut out);
assert_eq!(out.pixels, varied.pixels);
let flat = Image::filled(4, 4, [0.3, 0.6, 0.9, 1.0]);
let mut flat_out = Image::new(4, 4);
pixelate(2)(&[&flat], &mut flat_out);
assert_eq!(flat_out.pixels, flat.pixels);
}
#[test]
fn pixelate_replaces_each_block_with_its_average() {
let mut source = Image::new(2, 2);
source.pixels = vec![
[1.0, 1.0, 1.0, 1.0],
[0.0, 0.0, 0.0, 1.0],
[0.0, 0.0, 0.0, 1.0],
[0.0, 0.0, 0.0, 1.0],
];
let mut out = Image::new(2, 2);
pixelate(2)(&[&source], &mut out);
for pixel in &out.pixels {
assert!((pixel[0] - 0.25).abs() < 1e-6);
assert!((pixel[1] - 0.25).abs() < 1e-6);
assert!((pixel[2] - 0.25).abs() < 1e-6);
assert!((pixel[3] - 1.0).abs() < 1e-6);
}
}
#[test]
fn pixelate_handles_partial_edge_blocks() {
let mut source = Image::new(3, 1);
source.pixels = vec![
[0.0, 0.0, 0.0, 1.0],
[0.4, 0.4, 0.4, 1.0],
[0.9, 0.9, 0.9, 1.0],
];
let mut out = Image::new(3, 1);
pixelate(2)(&[&source], &mut out);
assert!((out.pixel(0, 0)[0] - 0.2).abs() < 1e-6);
assert!((out.pixel(1, 0)[0] - 0.2).abs() < 1e-6);
assert!((out.pixel(2, 0)[0] - 0.9).abs() < 1e-6);
}
#[test]
fn median_filter_radius_zero_or_flat_is_unchanged() {
let mut varied = Image::new(3, 3);
varied.pixels[4] = [0.8, 0.2, 0.5, 1.0];
let mut out = Image::new(3, 3);
median_filter(0)(&[&varied], &mut out);
assert_eq!(out.pixels, varied.pixels);
let flat = Image::filled(5, 5, [0.3, 0.6, 0.9, 1.0]);
let mut flat_out = Image::new(5, 5);
median_filter(1)(&[&flat], &mut flat_out);
assert_eq!(flat_out.pixels, flat.pixels);
}
#[test]
fn median_filter_removes_isolated_outliers() {
let mut source = Image::filled(5, 5, [0.2, 0.2, 0.2, 1.0]);
source.pixels[2 * 5 + 2] = [1.0, 1.0, 1.0, 1.0];
let mut out = Image::new(5, 5);
median_filter(1)(&[&source], &mut out);
assert!((out.pixel(2, 2)[0] - 0.2).abs() < 1e-6);
assert!((out.pixel(0, 0)[0] - 0.2).abs() < 1e-6);
}
#[test]
fn median_filter_preserves_edges_without_blurring() {
let mut source = Image::filled(5, 5, [0.0, 0.0, 0.0, 1.0]);
for y in 0..5 {
for x in 2..5 {
source.pixels[y * 5 + x] = [1.0, 1.0, 1.0, 1.0];
}
}
let mut out = Image::new(5, 5);
median_filter(1)(&[&source], &mut out);
assert!((out.pixel(0, 2)[0] - 0.0).abs() < 1e-6);
assert!((out.pixel(4, 2)[0] - 1.0).abs() < 1e-6);
assert!((out.pixel(2, 2)[0] - 1.0).abs() < 1e-6);
for pixel in &out.pixels {
assert!(
pixel[0] < 1e-6 || (pixel[0] - 1.0).abs() < 1e-6,
"{pixel:?}"
);
}
}
#[test]
fn dilate_and_erode_radius_zero_is_identity() {
let mut source = Image::new(3, 3);
source.pixels[4] = [0.8, 0.2, 0.5, 0.7];
let mut grown = Image::new(3, 3);
dilate(0)(&[&source], &mut grown);
assert_eq!(grown.pixels, source.pixels);
let mut shrunk = Image::new(3, 3);
erode(0)(&[&source], &mut shrunk);
assert_eq!(shrunk.pixels, source.pixels);
}
#[test]
fn dilate_grows_a_bright_speck() {
let mut source = Image::filled(5, 5, [0.0, 0.0, 0.0, 1.0]);
source.pixels[2 * 5 + 2] = [1.0, 1.0, 1.0, 1.0];
let mut out = Image::new(5, 5);
dilate(1)(&[&source], &mut out);
assert!((out.pixel(2, 2)[0] - 1.0).abs() < 1e-6);
assert!((out.pixel(1, 1)[0] - 1.0).abs() < 1e-6);
assert!((out.pixel(3, 3)[0] - 1.0).abs() < 1e-6);
assert!(out.pixel(0, 0)[0] < 1e-6);
}
#[test]
fn erode_shrinks_a_bright_block() {
let mut source = Image::filled(5, 5, [0.0, 0.0, 0.0, 1.0]);
for y in 1..4 {
for x in 1..4 {
source.pixels[y * 5 + x] = [1.0, 1.0, 1.0, 1.0];
}
}
let mut out = Image::new(5, 5);
erode(1)(&[&source], &mut out);
assert!((out.pixel(2, 2)[0] - 1.0).abs() < 1e-6);
assert!(out.pixel(1, 1)[0] < 1e-6);
assert!(out.pixel(3, 3)[0] < 1e-6);
}
#[test]
fn convolve_box_kernel_averages_neighborhood() {
let box_kernel = [[1.0 / 9.0; 3]; 3];
let mut source = Image::new(3, 1);
source.pixels = vec![
[0.0, 0.0, 0.0, 1.0],
[0.9, 0.9, 0.9, 1.0],
[0.0, 0.0, 0.0, 1.0],
];
let mut out = Image::new(3, 1);
convolve_3x3(box_kernel)(&[&source], &mut out);
assert!(
(out.pixel(1, 0)[0] - 0.3).abs() < 1e-6,
"{:?}",
out.pixel(1, 0)
);
}
#[test]
fn despill_green_limits_green_to_red_blue_maximum() {
let mut source = Image::new(3, 1);
source.pixels = vec![
[0.3, 0.9, 0.4, 1.0], [0.8, 0.2, 0.1, 1.0], [1.0, 1.0, 1.0, 1.0], ];
let mut out = Image::new(3, 1);
despill_green()(&[&source], &mut out);
assert_eq!(out.pixel(0, 0), [0.3, 0.4, 0.4, 1.0]);
assert_eq!(out.pixel(1, 0), [0.8, 0.2, 0.1, 1.0]);
assert_eq!(out.pixel(2, 0), [1.0, 1.0, 1.0, 1.0]);
}
#[test]
fn exposure_and_gamma_adjust_channels() {
let mut source = Image::new(1, 1);
source.pixels = vec![[0.25, 0.5, 1.0, 0.5]];
let mut brighter = Image::new(1, 1);
exposure(1.0)(&[&source], &mut brighter);
assert_eq!(brighter.pixel(0, 0), [0.5, 1.0, 1.0, 0.5]);
let mut same = Image::new(1, 1);
exposure(0.0)(&[&source], &mut same);
assert_eq!(same.pixel(0, 0), source.pixels[0]);
let mut squared = Image::new(1, 1);
gamma(2.0)(&[&source], &mut squared);
assert!((squared.pixel(0, 0)[0] - 0.0625).abs() < 1e-6);
assert!((squared.pixel(0, 0)[1] - 0.25).abs() < 1e-6);
assert_eq!(squared.pixel(0, 0)[3], 0.5);
let mut rooted = Image::new(1, 1);
gamma(0.5)(&[&source], &mut rooted);
assert!((rooted.pixel(0, 0)[0] - 0.5).abs() < 1e-6);
}
#[test]
fn lift_gamma_gain_identity_passes_through() {
let mut source = Image::new(2, 1);
source.pixels = vec![[0.2, 0.5, 0.8, 1.0], [0.0, 0.4, 1.0, 0.25]];
let mut out = Image::new(2, 1);
lift_gamma_gain([0.0; 3], [1.0; 3], [1.0; 3])(&[&source], &mut out);
for (got, want) in out.pixels.iter().zip(&source.pixels) {
for channel in 0..4 {
assert!(
(got[channel] - want[channel]).abs() < 1e-6,
"{got:?} vs {want:?}"
);
}
}
}
#[test]
fn lift_gamma_gain_lift_raises_shadows_gain_scales_highlights() {
let mut source = Image::new(2, 1);
source.pixels = vec![[0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0]];
let mut lifted = Image::new(2, 1);
lift_gamma_gain([0.2; 3], [1.0; 3], [1.0; 3])(&[&source], &mut lifted);
assert!((lifted.pixel(0, 0)[0] - 0.2).abs() < 1e-6);
assert!((lifted.pixel(1, 0)[0] - 1.0).abs() < 1e-6);
let mut gained = Image::new(2, 1);
lift_gamma_gain([0.0; 3], [1.0; 3], [0.5; 3])(&[&source], &mut gained);
assert!((gained.pixel(0, 0)[0] - 0.0).abs() < 1e-6);
assert!((gained.pixel(1, 0)[0] - 0.5).abs() < 1e-6);
let mut mid = Image::new(1, 1);
let gray = Image::filled(1, 1, [0.25, 0.25, 0.25, 1.0]);
lift_gamma_gain([0.0; 3], [2.0; 3], [1.0; 3])(&[&gray], &mut mid);
assert!((mid.pixel(0, 0)[0] - 0.5).abs() < 1e-6);
}
#[test]
fn lift_gamma_gain_is_per_channel_and_clamped() {
let gray = Image::filled(1, 1, [0.4, 0.4, 0.4, 0.5]);
let mut out = Image::new(1, 1);
lift_gamma_gain([0.0; 3], [1.0; 3], [1.0, 1.0, 3.0])(&[&gray], &mut out);
assert!((out.pixel(0, 0)[0] - 0.4).abs() < 1e-6);
assert!((out.pixel(0, 0)[1] - 0.4).abs() < 1e-6);
assert!((out.pixel(0, 0)[2] - 1.0).abs() < 1e-6);
assert_eq!(out.pixel(0, 0)[3], 0.5);
}
#[test]
fn temperature_tint_neutral_is_identity() {
let source = Image::filled(2, 2, [0.3, 0.5, 0.7, 0.8]);
let mut out = Image::new(2, 2);
temperature_tint(0.0, 0.0)(&[&source], &mut out);
assert_eq!(out.pixels, source.pixels);
}
#[test]
fn temperature_warms_and_cools_red_blue_axis() {
let gray = Image::filled(1, 1, [0.5, 0.5, 0.5, 1.0]);
let mut warm = Image::new(1, 1);
temperature_tint(0.5, 0.0)(&[&gray], &mut warm);
assert!((warm.pixel(0, 0)[0] - 0.75).abs() < 1e-6);
assert!((warm.pixel(0, 0)[1] - 0.5).abs() < 1e-6);
assert!((warm.pixel(0, 0)[2] - 0.25).abs() < 1e-6);
assert_eq!(warm.pixel(0, 0)[3], 1.0);
let mut cool = Image::new(1, 1);
temperature_tint(-0.5, 0.0)(&[&gray], &mut cool);
assert!((cool.pixel(0, 0)[0] - 0.25).abs() < 1e-6);
assert!((cool.pixel(0, 0)[2] - 0.75).abs() < 1e-6);
}
#[test]
fn tint_shifts_green_magenta_axis_and_clamps() {
let gray = Image::filled(1, 1, [0.5, 0.5, 0.5, 1.0]);
let mut magenta = Image::new(1, 1);
temperature_tint(0.0, 0.5)(&[&gray], &mut magenta);
assert!((magenta.pixel(0, 0)[1] - 0.25).abs() < 1e-6);
assert!((magenta.pixel(0, 0)[0] - 0.5).abs() < 1e-6);
let mut green = Image::new(1, 1);
temperature_tint(0.0, -2.0)(&[&gray], &mut green);
assert!((green.pixel(0, 0)[1] - 1.0).abs() < 1e-6);
}
#[test]
fn tone_curve_identity_and_degenerate_inputs_pass_through() {
let source = Image::filled(2, 2, [0.2, 0.55, 0.9, 0.5]);
for curve in [vec![[0.0, 0.0], [1.0, 1.0]], vec![], vec![[0.3, 0.9]]] {
let mut out = Image::new(2, 2);
tone_curve(curve)(&[&source], &mut out);
for (got, want) in out.pixels.iter().zip(&source.pixels) {
for channel in 0..4 {
assert!(
(got[channel] - want[channel]).abs() < 1e-6,
"{got:?} vs {want:?}"
);
}
}
}
}
#[test]
fn tone_curve_inverts_and_interpolates_linearly() {
let mut source = Image::new(4, 1);
source.pixels = vec![
[0.0, 0.0, 0.0, 1.0],
[0.25, 0.25, 0.25, 1.0],
[0.5, 0.5, 0.5, 1.0],
[1.0, 1.0, 1.0, 1.0],
];
let mut out = Image::new(4, 1);
tone_curve(vec![[0.0, 1.0], [1.0, 0.0]])(&[&source], &mut out);
let expected = [1.0, 0.75, 0.5, 0.0];
for (x, want) in expected.iter().enumerate() {
assert!(
(out.pixel(x as u32, 0)[0] - want).abs() < 1e-6,
"{}",
out.pixel(x as u32, 0)[0]
);
}
}
#[test]
fn tone_curve_sorts_points_and_clamps_to_endpoints() {
let mut source = Image::new(3, 1);
source.pixels = vec![
[0.1, 0.1, 0.1, 0.5],
[0.5, 0.5, 0.5, 0.5],
[0.9, 0.9, 0.9, 0.5],
];
let mut out = Image::new(3, 1);
tone_curve(vec![[0.75, 1.0], [0.25, 0.0]])(&[&source], &mut out);
assert!((out.pixel(0, 0)[0] - 0.0).abs() < 1e-6);
assert!((out.pixel(1, 0)[0] - 0.5).abs() < 1e-6);
assert!((out.pixel(2, 0)[0] - 1.0).abs() < 1e-6);
assert_eq!(out.pixel(1, 0)[3], 0.5);
}
#[test]
fn channel_mixer_identity_passes_through() {
let source = Image::filled(2, 2, [0.8, 0.5, 0.2, 0.6]);
let mut out = Image::new(2, 2);
channel_mixer([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])(
&[&source],
&mut out,
);
assert_eq!(out.pixels, source.pixels);
}
#[test]
fn channel_mixer_to_grayscale_equalizes_channels() {
let source = Image::filled(1, 1, [0.8, 0.5, 0.2, 1.0]);
let luma_row = [0.2126, 0.7152, 0.0722];
let mut out = Image::new(1, 1);
channel_mixer([luma_row, luma_row, luma_row])(&[&source], &mut out);
let expected = 0.2126 * 0.8 + 0.7152 * 0.5 + 0.0722 * 0.2;
let pixel = out.pixel(0, 0);
assert!((pixel[0] - expected).abs() < 1e-6);
assert!((pixel[0] - pixel[1]).abs() < 1e-6 && (pixel[1] - pixel[2]).abs() < 1e-6);
}
#[test]
fn channel_mixer_swaps_channels_and_clamps() {
let source = Image::filled(1, 1, [0.8, 0.5, 0.2, 0.4]);
let mut swapped = Image::new(1, 1);
channel_mixer([[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]])(
&[&source],
&mut swapped,
);
assert!((swapped.pixel(0, 0)[0] - 0.5).abs() < 1e-6);
assert!((swapped.pixel(0, 0)[1] - 0.8).abs() < 1e-6);
assert!((swapped.pixel(0, 0)[2] - 0.2).abs() < 1e-6);
assert_eq!(swapped.pixel(0, 0)[3], 0.4);
let mut hot = Image::new(1, 1);
channel_mixer([[2.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])(
&[&source],
&mut hot,
);
assert!((hot.pixel(0, 0)[0] - 1.0).abs() < 1e-6);
}
#[test]
fn levels_identity_passes_through() {
let source = Image::filled(2, 2, [0.2, 0.55, 0.9, 0.7]);
let mut out = Image::new(2, 2);
levels(0.0, 1.0, 1.0, 0.0, 1.0)(&[&source], &mut out);
for (got, want) in out.pixels.iter().zip(&source.pixels) {
for channel in 0..4 {
assert!(
(got[channel] - want[channel]).abs() < 1e-6,
"{got:?} vs {want:?}"
);
}
}
}
#[test]
fn levels_input_range_clips_and_expands_contrast() {
let mut source = Image::new(5, 1);
source.pixels = vec![
[0.1, 0.1, 0.1, 1.0],
[0.25, 0.25, 0.25, 1.0],
[0.5, 0.5, 0.5, 1.0],
[0.75, 0.75, 0.75, 1.0],
[0.9, 0.9, 0.9, 1.0],
];
let mut out = Image::new(5, 1);
levels(0.25, 0.75, 1.0, 0.0, 1.0)(&[&source], &mut out);
let expected = [0.0, 0.0, 0.5, 1.0, 1.0];
for (x, want) in expected.iter().enumerate() {
assert!(
(out.pixel(x as u32, 0)[0] - want).abs() < 1e-6,
"{}",
out.pixel(x as u32, 0)[0]
);
}
}
#[test]
fn levels_output_range_and_gamma_apply() {
let gray = Image::filled(1, 1, [0.25, 0.25, 0.25, 0.5]);
let mut out = Image::new(1, 1);
levels(0.0, 1.0, 2.0, 0.2, 0.8)(&[&gray], &mut out);
assert!((out.pixel(0, 0)[0] - 0.5).abs() < 1e-6);
assert_eq!(out.pixel(0, 0)[3], 0.5);
let mut ramp = Image::new(2, 1);
let mut ends = Image::new(2, 1);
ramp.pixels = vec![[0.0, 0.0, 0.0, 1.0], [1.0, 1.0, 1.0, 1.0]];
levels(0.0, 1.0, 1.0, 0.2, 0.8)(&[&ramp], &mut ends);
assert!((ends.pixel(0, 0)[0] - 0.2).abs() < 1e-6);
assert!((ends.pixel(1, 0)[0] - 0.8).abs() < 1e-6);
}
#[test]
fn solarize_high_threshold_passes_through() {
let source = Image::filled(2, 2, [0.2, 0.55, 0.95, 0.6]);
let mut out = Image::new(2, 2);
solarize(1.5)(&[&source], &mut out);
assert_eq!(out.pixels, source.pixels);
}
#[test]
fn solarize_zero_threshold_fully_inverts() {
let source = Image::filled(1, 1, [0.2, 0.6, 0.9, 1.0]);
let mut out = Image::new(1, 1);
solarize(0.0)(&[&source], &mut out);
assert!((out.pixel(0, 0)[0] - 0.8).abs() < 1e-6);
assert!((out.pixel(0, 0)[1] - 0.4).abs() < 1e-6);
assert!((out.pixel(0, 0)[2] - 0.1).abs() < 1e-6);
assert_eq!(out.pixel(0, 0)[3], 1.0);
}
#[test]
fn solarize_folds_values_above_the_threshold() {
let source = Image::filled(1, 1, [0.3, 0.5, 0.8, 0.4]);
let mut out = Image::new(1, 1);
solarize(0.5)(&[&source], &mut out);
assert!((out.pixel(0, 0)[0] - 0.3).abs() < 1e-6);
assert!((out.pixel(0, 0)[1] - 0.5).abs() < 1e-6);
assert!((out.pixel(0, 0)[2] - 0.2).abs() < 1e-6);
assert_eq!(out.pixel(0, 0)[3], 0.4);
}
#[test]
fn flips_mirror_the_image() {
let red = [1.0, 0.0, 0.0, 1.0];
let green = [0.0, 1.0, 0.0, 1.0];
let blue = [0.0, 0.0, 1.0, 1.0];
let mut source = Image::new(3, 1);
source.pixels = vec![red, green, blue];
let mut flipped = Image::new(3, 1);
flip_horizontal()(&[&source], &mut flipped);
assert_eq!(flipped.pixels, vec![blue, green, red]);
let mut twice = Image::new(3, 1);
flip_horizontal()(&[&flipped], &mut twice);
assert_eq!(twice.pixels, source.pixels);
let mut column = Image::new(1, 3);
column.pixels = vec![red, green, blue];
let mut flipped_v = Image::new(1, 3);
flip_vertical()(&[&column], &mut flipped_v);
assert_eq!(flipped_v.pixels, vec![blue, green, red]);
}
#[test]
fn rotate_zero_is_identity() {
let mut source = Image::new(3, 3);
source.pixels[4] = [0.8, 0.2, 0.5, 1.0];
let mut out = Image::new(3, 3);
rotate(0.0)(&[&source], &mut out);
for (got, want) in out.pixels.iter().zip(&source.pixels) {
for channel in 0..4 {
assert!(
(got[channel] - want[channel]).abs() < 1e-6,
"{got:?} vs {want:?}"
);
}
}
}
#[test]
fn rotate_180_swaps_opposite_corners() {
let mut source = Image::filled(3, 3, [0.0, 0.0, 0.0, 1.0]);
source.pixels[0] = [1.0, 0.0, 0.0, 1.0]; source.pixels[4] = [0.0, 1.0, 0.0, 1.0]; let mut out = Image::new(3, 3);
rotate(std::f32::consts::PI)(&[&source], &mut out);
assert!((out.pixel(2, 2)[0] - 1.0).abs() < 1e-5);
assert!((out.pixel(1, 1)[1] - 1.0).abs() < 1e-5);
assert!(out.pixel(0, 0)[0] < 1e-5);
}
#[test]
fn rotate_preserves_a_solid_center() {
let solid = Image::filled(5, 5, [0.3, 0.6, 0.9, 1.0]);
let mut out = Image::new(5, 5);
rotate(0.5)(&[&solid], &mut out);
let center = out.pixel(2, 2);
assert!((center[0] - 0.3).abs() < 1e-5 && (center[2] - 0.9).abs() < 1e-5);
}
#[test]
fn letterbox_pillarboxes_a_square_into_a_wide_frame() {
let source = Image::filled(2, 2, [1.0, 1.0, 1.0, 1.0]);
let mut out = Image::new(4, 2);
letterbox()(&[&source], &mut out);
assert_eq!(out.pixel(0, 0), [0.0, 0.0, 0.0, 0.0]);
assert_eq!(out.pixel(3, 0), [0.0, 0.0, 0.0, 0.0]);
assert_eq!(out.pixel(1, 0), [1.0, 1.0, 1.0, 1.0]);
assert_eq!(out.pixel(2, 1), [1.0, 1.0, 1.0, 1.0]);
}
#[test]
fn saturation_unchanged_at_one_grayscale_at_zero() {
let color = [0.8, 0.4, 0.2, 1.0];
let luma = 0.2126 * 0.8 + 0.7152 * 0.4 + 0.0722 * 0.2;
let mut source = Image::new(1, 1);
source.pixels = vec![color];
let mut same = Image::new(1, 1);
saturation(1.0)(&[&source], &mut same);
for channel in 0..3 {
assert!((same.pixel(0, 0)[channel] - color[channel]).abs() < 1e-6);
}
let mut gray = Image::new(1, 1);
saturation(0.0)(&[&source], &mut gray);
for channel in 0..3 {
assert!((gray.pixel(0, 0)[channel] - luma).abs() < 1e-5);
}
assert_eq!(gray.pixel(0, 0)[3], 1.0);
}
#[test]
fn posterize_quantizes_channels() {
let mut source = Image::new(1, 1);
source.pixels = vec![[0.3, 0.6, 0.9, 0.5]];
let mut two = Image::new(1, 1);
posterize(2)(&[&source], &mut two);
assert_eq!(two.pixel(0, 0), [0.0, 1.0, 1.0, 0.5]);
let mut four = Image::new(1, 1);
posterize(4)(&[&source], &mut four);
let close = |a: f32, b: f32| (a - b).abs() < 1e-5;
assert!(close(four.pixel(0, 0)[0], 1.0 / 3.0));
assert!(close(four.pixel(0, 0)[1], 2.0 / 3.0));
assert!(close(four.pixel(0, 0)[2], 1.0));
let mut one = Image::new(1, 1);
posterize(1)(&[&source], &mut one);
assert_eq!(one.pixel(0, 0), two.pixel(0, 0));
}
#[test]
fn invert_negates_color_keeps_alpha() {
let mut source = Image::new(1, 1);
source.pixels = vec![[0.2, 0.5, 0.8, 0.5]];
let mut out = Image::new(1, 1);
invert()(&[&source], &mut out);
let pixel = out.pixel(0, 0);
assert!(
(pixel[0] - 0.8).abs() < 1e-6
&& (pixel[1] - 0.5).abs() < 1e-6
&& (pixel[2] - 0.2).abs() < 1e-6
);
assert_eq!(pixel[3], 0.5);
let mut back = Image::new(1, 1);
invert()(&[&out], &mut back);
for channel in 0..3 {
assert!((back.pixel(0, 0)[channel] - source.pixels[0][channel]).abs() < 1e-6);
}
}
#[test]
fn duotone_maps_luma_across_the_two_tones() {
let mut source = Image::new(3, 1);
source.pixels = vec![
[0.0, 0.0, 0.0, 1.0],
[0.5, 0.5, 0.5, 0.5],
[1.0, 1.0, 1.0, 1.0],
];
let shadow = [0.0, 0.0, 1.0];
let highlight = [1.0, 1.0, 0.0];
let mut out = Image::new(3, 1);
duotone(shadow, highlight)(&[&source], &mut out);
assert_eq!(&out.pixel(0, 0)[0..3], &shadow);
assert_eq!(&out.pixel(2, 0)[0..3], &highlight);
let mid = out.pixel(1, 0);
assert!(
(mid[0] - 0.5).abs() < 1e-6
&& (mid[1] - 0.5).abs() < 1e-6
&& (mid[2] - 0.5).abs() < 1e-6
);
assert_eq!(mid[3], 0.5);
}
#[test]
fn hue_rotate_identity_at_zero_and_preserves_gray() {
let close = |a: f32, b: f32| (a - b).abs() < 1e-5;
let color = [0.8, 0.4, 0.2, 1.0];
let mut source = Image::new(1, 1);
source.pixels = vec![color];
let mut at_zero = Image::new(1, 1);
hue_rotate(0.0)(&[&source], &mut at_zero);
for channel in 0..3 {
assert!(close(at_zero.pixel(0, 0)[channel], color[channel]));
}
assert_eq!(at_zero.pixel(0, 0)[3], 1.0);
let gray = Image::filled(1, 1, [0.5, 0.5, 0.5, 1.0]);
let mut rotated_gray = Image::new(1, 1);
hue_rotate(2.0)(&[&gray], &mut rotated_gray);
for channel in 0..3 {
assert!(close(rotated_gray.pixel(0, 0)[channel], 0.5));
}
let mut shifted = Image::new(1, 1);
hue_rotate(2.0)(&[&source], &mut shifted);
assert!(
(shifted.pixel(0, 0)[0] - color[0]).abs() > 1e-3
|| (shifted.pixel(0, 0)[1] - color[1]).abs() > 1e-3
);
}
}
}