#![allow(dead_code, reason = "each reader uses its share")]
#![allow(clippy::float_cmp, reason = "defaults are compared exactly")]
use crate::material::{Alpha, Factor, Full, Specular};
use crate::mesh::{Extensions, GRAY, Material, srgb_to_linear};
pub(crate) const ROUGHNESS: f32 = 0.85;
pub(crate) const DEFAULT_NAME: &str = "default";
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Rgb {
Srgb([f32; 3]),
Linear([f32; 3]),
}
impl Rgb {
pub(crate) const BLACK: Self = Self::Linear([0.0; 3]);
pub(crate) const WHITE: Self = Self::Linear([1.0; 3]);
pub(crate) fn of(c: [f32; 3], linear: bool) -> Self {
if linear { Self::Linear(c) } else { Self::Srgb(c) }
}
pub(crate) fn linear(self) -> [f32; 3] {
self.scaled(1.0)
}
fn glow(self) -> [f32; 3] {
let clean = |v: f32| if v.is_finite() { v.max(0.0) } else { 0.0 };
match self {
Self::Srgb(c) => c.map(|v| srgb_to_linear(clean(v))),
Self::Linear(c) => c.map(clean),
}
}
fn scaled(self, k: f32) -> [f32; 3] {
let clean = |v: f32| if v.is_finite() { (v * k).max(0.0) } else { 0.0 };
match self {
Self::Srgb(c) => c.map(|v| srgb_to_linear(clean(v).min(1.0))),
Self::Linear(c) => c.map(clean),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Phong {
pub diffuse: Rgb,
pub opacity: f32,
pub emissive: Rgb,
pub specular: Option<Rgb>,
pub strength: f32,
pub exponent: Option<f32>,
pub highlight: bool,
}
impl Phong {
pub(crate) fn new(diffuse: Rgb) -> Self {
Self {
diffuse,
opacity: 1.0,
emissive: Rgb::BLACK,
specular: None,
strength: 1.0,
exponent: None,
highlight: true,
}
}
pub(crate) fn pbr(&self) -> Pbr {
let [r, g, b] = self.diffuse.linear().map(|v| v.min(1.0));
let opacity = if self.opacity.is_finite() {
self.opacity.clamp(0.0, 1.0)
} else {
1.0
};
let strength = if self.strength.is_finite() {
self.strength.clamp(0.0, 1.0)
} else {
1.0
};
let level = self.specular.map(|s| s.scaled(strength));
let top = level.map(|s| s[0].max(s[1]).max(s[2]));
let dark = !self.highlight || top.is_some_and(|t| t <= 0.0) || strength <= 0.0;
let (roughness, specular) = if dark {
(1.0, Some(Highlight::NONE))
} else {
let roughness = self.exponent.map_or(ROUGHNESS, roughness_of_exponent);
let specular = level.zip(top).and_then(|(s, top)| {
let h = Highlight {
factor: top.min(1.0),
color: s.map(|v| v / top),
};
let plain = h.factor >= 0.998 && h.color.iter().all(|&c| c >= 0.998);
(!plain).then_some(h)
});
(roughness, specular)
};
Pbr {
base_color: [r, g, b, opacity],
roughness,
emissive: self.emissive.glow(),
specular,
}
}
}
pub(crate) fn roughness_of_exponent(n: f32) -> f32 {
let n = if n.is_nan() { 0.0 } else { n.max(0.0) };
(2.0 / (n + 2.0)).sqrt().sqrt().clamp(0.0, 1.0)
}
pub(crate) fn exponent_of_roughness(roughness: f64) -> f64 {
let r = if roughness.is_nan() {
1.0
} else {
roughness.clamp(0.03, 1.0)
};
(2.0 / r.powi(4) - 2.0).max(0.0)
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Highlight {
pub factor: f32,
pub color: [f32; 3],
}
impl Highlight {
pub(crate) const NONE: Self = Self {
factor: 0.0,
color: [1.0; 3],
};
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Pbr {
pub base_color: [f32; 4],
pub roughness: f32,
pub emissive: [f32; 3],
pub specular: Option<Highlight>,
}
impl Pbr {
pub(crate) fn set(&self, m: &mut Material) {
m.color = self.base_color;
m.emissive = self.emissive;
m.metallic = 0.0;
m.roughness = self.roughness;
match self.specular {
Some(h) => {
m.extensions.get_or_insert_with(Box::<Extensions>::default).specular = Some(Specular {
factor: Factor::of(h.factor),
color: h.color,
color_tex: None,
});
}
None => {
if let Some(x) = m.extensions.as_deref_mut() {
x.specular = None;
}
}
}
}
pub(crate) fn material(&self, name: &str) -> Material {
let mut m = Material::plain(name, self.base_color);
self.set(&mut m);
m
}
pub(crate) fn set_full(&self, m: &mut Full) {
m.base_color = self.base_color;
m.alpha = Transparency::of(self.base_color[3]).mode();
m.emissive = self.emissive;
m.metallic = 0.0;
m.roughness = self.roughness;
m.specular = self.specular.map(|h| Specular {
factor: Factor::of(h.factor),
color: h.color,
color_tex: None,
});
}
pub(crate) fn full(&self, name: &str) -> Full {
let mut m = Full::from(Material::plain(name, self.base_color));
self.set_full(&mut m);
m
}
}
pub(crate) fn default_material(colored: bool) -> Material {
Material::plain(DEFAULT_NAME, if colored { [1.0; 4] } else { GRAY })
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Transparency {
pub opacity: f32,
pub texture_alpha: bool,
pub vertex_alpha: bool,
pub cutout: Option<f32>,
}
impl Transparency {
pub(crate) fn of(opacity: f32) -> Self {
Self {
opacity,
texture_alpha: false,
vertex_alpha: false,
cutout: None,
}
}
pub(crate) fn mode(self) -> Alpha {
if let Some(c) = self.cutout {
return Alpha::Mask(if c.is_finite() { c.clamp(0.0, 1.0) } else { 0.5 });
}
if self.opacity < 1.0 || self.texture_alpha || self.vertex_alpha {
Alpha::Blend
} else {
Alpha::Opaque
}
}
}
#[cfg(test)]
#[allow(clippy::float_cmp_const, reason = "defaults are compared exactly")]
mod tests {
use super::*;
fn close(a: f32, b: f32) -> bool {
(a - b).abs() < 1e-4
}
#[test]
fn an_exponent_is_the_ggx_roughness_of_its_lobe() {
assert_eq!(roughness_of_exponent(0.0), 1.0);
assert!(close(roughness_of_exponent(20.0), 0.549_100));
assert!(close(roughness_of_exponent(30.0), 0.5));
assert!(close(roughness_of_exponent(1000.0), 0.211_368));
assert_eq!(roughness_of_exponent(-5.0), 1.0);
assert_eq!(roughness_of_exponent(f32::NAN), 1.0);
for r in [0.05f32, 0.2, 0.5, 0.85, 1.0] {
#[allow(clippy::cast_possible_truncation, reason = "a test value")]
let n = exponent_of_roughness(f64::from(r)) as f32;
assert!(close(roughness_of_exponent(n), r), "{r}");
}
}
#[test]
fn a_phong_material_becomes_a_rough_dielectric() {
let mut p = Phong::new(Rgb::Srgb([0.8, 0.2, 0.1]));
p.specular = Some(Rgb::Srgb([0.5; 3]));
p.exponent = Some(20.0);
let pbr = p.pbr();
for (got, want) in pbr.base_color.iter().zip([0.603_827, 0.033_105, 0.010_023, 1.0]) {
assert!(close(*got, want), "{:?}", pbr.base_color);
}
assert!(close(pbr.roughness, 0.549_100));
let h = pbr.specular.unwrap();
assert!(close(h.factor, 0.214_041), "{h:?}");
assert_eq!(h.color, [1.0; 3]);
let m = pbr.material("m");
assert_eq!((m.metallic, m.roughness), (0.0, pbr.roughness));
assert!(m.extensions.unwrap().specular.is_some());
let f = pbr.full("m");
assert_eq!((f.metallic, f.roughness), (0.0, pbr.roughness));
}
#[test]
fn a_full_white_highlight_is_gltfs_default_and_none_is_no_reflection() {
let mut p = Phong::new(Rgb::Srgb([0.5; 3]));
p.exponent = Some(30.0);
p.specular = Some(Rgb::Srgb([1.0; 3]));
assert_eq!(p.pbr().specular, None);
p.specular = Some(Rgb::Linear([0.5, 0.25, 0.0]));
let h = p.pbr().specular.unwrap();
assert!(close(h.factor, 0.5));
assert_eq!(h.color, [1.0, 0.5, 0.0]);
p.strength = 0.5;
assert!(close(p.pbr().specular.unwrap().factor, 0.25));
p.specular = Some(Rgb::Srgb([1.0; 3]));
assert!(close(p.pbr().specular.unwrap().factor, 0.214_041));
p.specular = Some(Rgb::Linear([0.5, 0.25, 0.0]));
p.strength = 0.0;
assert_eq!((p.pbr().roughness, p.pbr().specular), (1.0, Some(Highlight::NONE)));
p.strength = 1.0;
p.specular = Some(Rgb::Srgb([0.0; 3]));
assert_eq!((p.pbr().roughness, p.pbr().specular), (1.0, Some(Highlight::NONE)));
p.specular = Some(Rgb::Srgb([1.0; 3]));
p.highlight = false;
assert_eq!((p.pbr().roughness, p.pbr().specular), (1.0, Some(Highlight::NONE)));
let mut bright = Phong::new(Rgb::Linear([2.0, 0.5, 0.0]));
bright.emissive = Rgb::Linear([4.0, 0.0, 0.0]);
assert_eq!(
(bright.pbr().base_color, bright.pbr().emissive),
([1.0, 0.5, 0.0, 1.0], [4.0, 0.0, 0.0])
);
let quiet = Phong::new(Rgb::Srgb([0.5; 3])).pbr();
assert_eq!((quiet.roughness, quiet.specular), (ROUGHNESS, None));
}
#[test]
fn the_default_material_is_one_gray() {
let m = default_material(false);
assert_eq!(
(m.name.as_str(), m.color, m.roughness, m.metallic),
("default", GRAY, 0.85, 0.0)
);
assert_eq!(default_material(true).color, [1.0; 4]);
assert_eq!(ROUGHNESS, Material::plain("", GRAY).roughness);
}
#[test]
fn transparency_is_cut_out_when_asked_and_blended_otherwise() {
let opaque = Transparency::of(1.0);
assert_eq!(opaque.mode(), Alpha::Opaque);
assert_eq!(Transparency::of(0.5).mode(), Alpha::Blend);
let texture = Transparency {
texture_alpha: true,
..opaque
};
assert_eq!(texture.mode(), Alpha::Blend);
let vertex = Transparency {
vertex_alpha: true,
..opaque
};
assert_eq!(vertex.mode(), Alpha::Blend);
let cut = Transparency {
cutout: Some(0.3),
..Transparency::of(0.5)
};
assert_eq!(cut.mode(), Alpha::Mask(0.3));
}
}