#![allow(dead_code)]
use crate::lights::{
point_shadow, point_shadow_filtered, LightKind, ShadowFilter, ShadowFilterInputs,
ShadowFilterMap,
};
use crate::nodes::tsl::*;
use crate::nodes::{NodeRef, Type};
use crate::textures::{CubeDepthTexture, DepthTexture};
pub(crate) const RECIPROCAL_PI: f64 = std::f64::consts::FRAC_1_PI;
pub fn distance_attenuation(
light_distance: NodeRef,
cutoff_distance: NodeRef,
decay: NodeRef,
) -> NodeRef {
cutoff_distance.greater_than(0.0).select(
distance_attenuation_with_cutoff(
light_distance.clone(),
cutoff_distance.clone(),
decay.clone(),
),
distance_attenuation_no_cutoff(light_distance, decay),
)
}
pub(crate) fn distance_attenuation_with_cutoff(
light_distance: NodeRef,
cutoff_distance: NodeRef,
decay: NodeRef,
) -> NodeRef {
let t = light_distance.clone().div(cutoff_distance);
let f = float(1.0)
.sub(t.clone().mul(t.clone()).mul(t.clone()).mul(t))
.clamp(0.0, 1.0);
float(1.0)
.div(max(light_distance.pow(decay), float(0.01)))
.mul(f.clone().mul(f))
}
pub(crate) fn distance_attenuation_no_cutoff(light_distance: NodeRef, decay: NodeRef) -> NodeRef {
float(1.0).div(max(light_distance.pow(decay), float(0.01)))
}
pub fn brdf_lambert(diffuse: NodeRef) -> NodeRef {
diffuse.mul(RECIPROCAL_PI)
}
pub fn f_schlick(f0: NodeRef, f90: NodeRef, dot_vh: NodeRef) -> NodeRef {
let fresnel = exp2(dot_vh.clone().mul(-5.55473).sub(6.98316).mul(dot_vh));
f0.mul(float(1.0).sub(fresnel.clone()))
.add(f90.mul(fresnel))
}
pub(crate) fn d_blinn_phong(shininess_value: NodeRef, dot_nh: NodeRef) -> NodeRef {
shininess_value
.clone()
.mul(0.5)
.add(1.0)
.mul(RECIPROCAL_PI)
.mul(dot_nh.pow(shininess_value))
}
pub(crate) fn brdf_blinn_phong(light_direction: NodeRef) -> NodeRef {
let half_dir = light_direction.add(position_view_direction()).normalize();
let dot_nh = normal_view().dot(half_dir.clone()).clamp(0.0, 1.0);
let dot_vh = position_view_direction().dot(half_dir).clamp(0.0, 1.0);
let f = f_schlick(specular_color(), float(1.0), dot_vh);
f.mul(0.25).mul(d_blinn_phong(shininess(), dot_nh))
}
#[derive(Clone, Debug)]
#[doc(hidden)]
pub enum ShadowMap {
Planar(DepthTexture),
Cube(CubeDepthTexture),
Filtered {
map: ShadowFilterMap,
filter: ShadowFilter,
},
Node(NodeRef),
Transmitted {
map: Box<ShadowMap>,
color: crate::textures::Texture,
},
Context {
map: Box<ShadowMap>,
shadow: NodeRef,
},
}
impl std::hash::Hash for ShadowMap {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::mem::discriminant(self).hash(state);
match self {
ShadowMap::Planar(texture) => texture.id().hash(state),
ShadowMap::Cube(texture) => texture.id().hash(state),
ShadowMap::Filtered { map, filter } => {
map.hash(state);
filter.hash(state);
}
ShadowMap::Node(node) => node.key().hash(state),
ShadowMap::Transmitted { map, color } => {
map.hash(state);
color.id().hash(state);
}
ShadowMap::Context { map, shadow } => {
map.hash(state);
shadow.key().hash(state);
}
}
}
}
#[derive(Clone, Debug, Hash)]
#[doc(hidden)]
pub struct LightDesc {
pub index: usize,
pub kind: LightKind,
pub shadow_map: Option<ShadowMap>,
}
pub(crate) fn shadow_node(
index: usize,
map: &ShadowMap,
received_shadow_position: Option<&NodeRef>,
out: &mut Vec<NodeRef>,
) -> NodeRef {
if let ShadowMap::Node(node) = map {
return node.clone();
}
let position = match received_shadow_position {
Some(node) => node.clone(),
None => position_world(),
};
out.push(shadow_position_world().assign(position));
match map {
ShadowMap::Planar(map) => shadow_factor(index, map),
ShadowMap::Cube(map) => point_shadow(index, map),
ShadowMap::Filtered {
map: ShadowFilterMap::Cube(map),
filter,
} => point_shadow_filtered(index, map, filter),
ShadowMap::Filtered { map, filter } => shadow_factor_filtered(index, map, filter),
ShadowMap::Transmitted { map, color } => match &**map {
ShadowMap::Planar(depth) => shadow_factor_transmitted(
index,
&ShadowFilterMap::Depth(depth.clone()),
&ShadowFilter::Pcf,
Some(color),
),
ShadowMap::Filtered { map, filter } if !matches!(map, ShadowFilterMap::Cube(_)) => {
shadow_factor_transmitted(index, map, filter, Some(color))
}
_ => unreachable!("three-rs: only a planar shadow map carries a colour target"),
},
ShadowMap::Node(_) => unreachable!("three-rs: returned above"),
ShadowMap::Context { .. } => {
unreachable!("three-rs: `setup_light` unwraps the shadow context")
}
}
}
pub(crate) fn setup_light(
light: &LightDesc,
received_shadow_position: Option<&NodeRef>,
out: &mut Vec<NodeRef>,
) -> Option<(NodeRef, NodeRef)> {
let index = light.index;
match light.kind {
LightKind::Ambient => {
out.push(irradiance().assign(irradiance().add(light_color_intensity(index))));
return None;
}
LightKind::Hemisphere => {
let light_direction = light_world_position(index).normalize();
let dot_nl = normal_world().dot(light_direction);
let hemi_diffuse_weight = dot_nl.mul(0.5).add(0.5);
let value = mix(
light_ground_color(index),
light_color_intensity(index),
hemi_diffuse_weight,
);
out.push(irradiance().assign(irradiance().add(value)));
return None;
}
LightKind::Probe => {
let value = get_sh_irradiance_at(normal_world(), &light_probe_sh(index));
out.push(irradiance().assign(irradiance().add(value)));
return None;
}
_ => {}
}
let mut color = light_color_intensity(index);
if let Some(map) = &light.shadow_map {
let (map, context) = match map {
ShadowMap::Context { map, shadow } => (&**map, Some(shadow)),
map => (map, None),
};
color = color.mul(shadow_node(index, map, received_shadow_position, out));
if let Some(shadow) = context {
color = color.mul(shadow.clone());
}
}
Some(match light.kind {
LightKind::Ambient | LightKind::Hemisphere | LightKind::Probe => {
unreachable!("three-rs: the irradiance-only lights are summed above")
}
LightKind::Point => {
let l_vector = light_view_position(index).sub(position_view());
let attenuation = distance_attenuation(
length(l_vector.clone()),
light_cutoff_distance(index),
light_decay(index),
);
(l_vector.normalize(), color.mul(attenuation))
}
LightKind::Spot => {
let l_vector = light_view_position(index).sub(position_view());
let light_direction = l_vector.clone().normalize();
let angle_cos = light_direction.clone().dot(light_target_direction(index));
let spot_attenuation =
smoothstep(light_cone_cos(index), light_penumbra_cos(index), angle_cos);
let attenuation = distance_attenuation(
length(l_vector),
light_cutoff_distance(index),
light_decay(index),
);
(
light_direction,
color.mul(spot_attenuation).mul(attenuation),
)
}
LightKind::Directional => (light_target_direction(index), color),
})
}
pub(crate) fn shadow_factor(index: usize, map: &DepthTexture) -> NodeRef {
shadow_factor_filtered(
index,
&ShadowFilterMap::Depth(map.clone()),
&ShadowFilter::Pcf,
)
}
pub(crate) fn shadow_factor_filtered(
index: usize,
map: &ShadowFilterMap,
filter: &ShadowFilter,
) -> NodeRef {
shadow_factor_transmitted(index, map, filter, None)
}
pub(crate) fn shadow_factor_transmitted(
index: usize,
map: &ShadowFilterMap,
filter: &ShadowFilter,
color: Option<&crate::textures::Texture>,
) -> NodeRef {
let position = shadow_matrix(index).mul(vec4_join(vec![
shadow_position_world().add(normal_world().mul(shadow_normal_bias(index))),
float(1.0),
]));
let divided = position.clone().xyz().div(position.w());
let coord = vec3_join(vec![
divided.clone().x(),
float(1.0).sub(divided.clone().y()),
divided.z().add(shadow_bias(index)),
]);
let frustum_test = coord
.clone()
.x()
.greater_than_equal(float(0.0))
.and(coord.clone().x().less_than_equal(float(1.0)))
.and(coord.clone().y().greater_than_equal(float(0.0)))
.and(coord.clone().y().less_than_equal(float(1.0)))
.and(coord.clone().z().less_than_equal(float(1.0)));
let filtered = filter.apply(&ShadowFilterInputs {
index,
map: map.clone(),
shadow_coord: coord.clone(),
dp: None,
});
let shadow = frustum_test.select(filtered, float(1.0));
match color {
None => mix(float(1.0), shadow, shadow_intensity(index)),
Some(color) => {
let shadow_color = texture_uv(color, coord.xy());
let tinted = mix(
shadow_color.clone(),
vec4(1.0, 1.0, 1.0, 1.0),
shadow.to(Type::Vec4),
);
mix(
vec4(1.0, 1.0, 1.0, 1.0),
tinted,
shadow_intensity(index).mul(shadow_color.w()),
)
.xyz()
}
}
}
pub(crate) fn ambient_lights(indices: &[usize], out: &mut Vec<NodeRef>) {
for index in indices {
out.push(irradiance().assign(irradiance().add(light_color_intensity(*index))));
}
}
pub(crate) fn direct_light(
light: &LightDesc,
received_shadow_position: Option<&NodeRef>,
specular: bool,
out: &mut Vec<NodeRef>,
) {
let Some((light_direction, light_color)) = setup_light(light, received_shadow_position, out)
else {
return;
};
let dot_nl = normal_view().dot(light_direction.clone()).clamp(0.0, 1.0);
let irr = dot_nl.mul(light_color);
out.push(
direct_diffuse()
.assign(direct_diffuse().add(irr.clone().mul(brdf_lambert(diffuse_color().xyz())))),
);
if specular {
out.push(
direct_specular()
.assign(direct_specular().add(irr.mul(brdf_blinn_phong(light_direction)).mul(1.0))),
);
}
}