use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use super::builder::{current_context, push_context};
use super::node::{
BufferNode, BufferSource, Builtin, ContextValue, CustomNode, FnDef, InstanceBuffer, Lazy, Node,
NodeRef, SampleMode, SettableValue, Type, UniformGroup, UniformNode, UniformSource, VarDef,
VaryingDef,
};
use crate::materials::Side;
use crate::math::{Color, Matrix3};
use crate::textures::{
CubeDepthTexture, CubeTexture, DataArrayTexture, DataTexture, DepthTexture, Texture,
};
pub use super::node::TextureSource;
mod wrappers;
pub use wrappers::*;
type NormalViewKey = (
Option<&'static str>,
Option<usize>,
bool,
Side,
bool,
Option<usize>,
);
#[derive(Clone, Debug, Default)]
#[non_exhaustive]
pub struct OverrideNodes {
pub position_view: Option<NodeRef>,
pub position_view_direction: Option<NodeRef>,
pub normal_view: Option<NodeRef>,
}
impl std::hash::Hash for OverrideNodes {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
for node in [
&self.position_view,
&self.position_view_direction,
&self.normal_view,
] {
node.as_ref().map(|n| n.key()).hash(state);
}
}
}
pub(crate) fn with_override_nodes<R>(
overrides: Option<&OverrideNodes>,
f: impl FnOnce() -> R,
) -> R {
let _overrides = push_context(|cx| cx.override_nodes = overrides.cloned());
f()
}
fn override_node(pick: fn(&OverrideNodes) -> &Option<NodeRef>) -> Option<NodeRef> {
current_context(|cx| cx.override_nodes.as_ref().and_then(|o| pick(o).clone()))
}
thread_local! {
static NORMAL_VIEW_GEOMETRY: RefCell<HashMap<bool, NodeRef>> = RefCell::new(HashMap::new());
static NORMAL_VIEW: RefCell<HashMap<NormalViewKey, NodeRef>> =
RefCell::new(HashMap::new());
static TANGENT_VIEW: RefCell<HashMap<NormalViewKey, (NodeRef, NodeRef)>> =
RefCell::new(HashMap::new());
static NORMAL_WORLD: RefCell<HashMap<NormalViewKey, NodeRef>> =
RefCell::new(HashMap::new());
static POSITION_VIEW: RefCell<HashMap<Option<usize>, (NodeRef, NodeRef)>> =
RefCell::new(HashMap::new());
}
fn sub_build_name(name: &str) -> String {
match current_context(|cx| cx.sub_build) {
Some(layer) => format!("{layer}_{name}"),
None => name.to_string(),
}
}
pub fn context(node: impl Into<NodeRef>, value: ContextValue) -> NodeRef {
NodeRef::new(Node::Context {
node: node.into(),
value: Rc::new(value),
})
}
pub fn isolate(node: impl Into<NodeRef>) -> NodeRef {
NodeRef::new(Node::Isolate { node: node.into() })
}
pub fn custom(node: impl CustomNode + 'static) -> NodeRef {
NodeRef::new(Node::Custom(Rc::new(node)))
}
fn in_sub_build<R>(layer: &'static str, f: impl FnOnce() -> R) -> R {
let _layer = push_context(|cx| cx.sub_build = Some(layer));
f()
}
pub(crate) fn with_material_normal<R>(
normal: Option<NodeRef>,
flat_shading: bool,
side: Side,
f: impl FnOnce() -> R,
) -> R {
let _material = push_context(|cx| {
cx.setup_normal = normal;
cx.flat_shading = flat_shading;
cx.material_side = side;
});
f()
}
pub(crate) fn with_tangent_attribute<R>(has_tangent: bool, f: impl FnOnce() -> R) -> R {
let _tangent = push_context(|cx| cx.has_tangent = has_tangent);
f()
}
pub(crate) fn with_material_side<R>(side: Side, f: impl FnOnce() -> R) -> R {
let _side = push_context(|cx| cx.material_side = side);
f()
}
fn negate_on_back_side(vector: NodeRef) -> NodeRef {
match current_context(|cx| cx.material_side) {
Side::Front => vector,
Side::Back => vector.mul(float(-1.0)),
Side::Double => vector.mul(face_direction()),
}
}
pub(crate) fn with_material_position_view<R>(value: Option<NodeRef>, f: impl FnOnce() -> R) -> R {
let _position_view = push_context(|cx| cx.setup_position_view = value);
f()
}
fn position_view_pair() -> (NodeRef, NodeRef) {
let value = current_context(|cx| cx.setup_position_view.clone());
let key = value.as_ref().map(|v| v.key());
if let Some(pair) = POSITION_VIEW.with(|m| m.borrow().get(&key).cloned()) {
return pair;
}
let view = value.unwrap_or_else(|| {
model_view_matrix()
.mul(vec4_join(vec![position_local(), float(1.0)]))
.xyz()
});
let view = to_varying(Some("v_positionView"), view);
let mvp = to_varying(
Some("v_modelViewProjection"),
camera_projection_matrix().mul(view.clone()),
);
let pair = (view, mvp);
POSITION_VIEW.with(|m| m.borrow_mut().insert(key, pair.clone()));
pair
}
fn constant(ty: Type, values: Vec<f64>) -> NodeRef {
NodeRef::new(Node::Const { ty, values })
}
pub fn float(v: impl Into<f64>) -> NodeRef {
constant(Type::F32, vec![v.into()])
}
pub fn int(v: i64) -> NodeRef {
constant(Type::I32, vec![v as f64])
}
pub fn boolean(v: bool) -> NodeRef {
constant(Type::Bool, vec![f64::from(u8::from(v))])
}
pub fn vec2(x: impl Into<f64>, y: impl Into<f64>) -> NodeRef {
constant(Type::Vec2, vec![x.into(), y.into()])
}
pub fn vec3(x: impl Into<f64>, y: impl Into<f64>, z: impl Into<f64>) -> NodeRef {
constant(Type::Vec3, vec![x.into(), y.into(), z.into()])
}
pub fn vec3s(x: impl Into<f64>) -> NodeRef {
let x = x.into();
constant(Type::Vec3, vec![x, x, x])
}
pub fn vec4(x: impl Into<f64>, y: impl Into<f64>, z: impl Into<f64>, w: impl Into<f64>) -> NodeRef {
constant(Type::Vec4, vec![x.into(), y.into(), z.into(), w.into()])
}
pub fn join(ty: Type, args: Vec<NodeRef>) -> NodeRef {
NodeRef::new(Node::Join { args, ty })
}
pub fn vec2_join(args: Vec<NodeRef>) -> NodeRef {
join(Type::Vec2, args)
}
pub fn vec3_join(args: Vec<NodeRef>) -> NodeRef {
join(Type::Vec3, args)
}
pub fn vec4_join(args: Vec<NodeRef>) -> NodeRef {
join(Type::Vec4, args)
}
pub fn const_array(values: Vec<f64>) -> NodeRef {
NodeRef::new(Node::ConstArray {
element_ty: Type::F32,
values,
})
}
pub fn array_var(values: Vec<f64>) -> NodeRef {
NodeRef::new(Node::ArrayVar {
element_ty: Type::F32,
values,
})
}
pub fn attribute(name: &'static str, ty: Type) -> NodeRef {
NodeRef::new(Node::Attribute { name, ty })
}
pub fn uniform_value(ty: Type, values: Vec<f64>) -> NodeRef {
uniform(UniformSource::Value(values), ty, UniformGroup::Object, None)
}
pub fn uniform_settable(ty: Type, values: Vec<f64>) -> (NodeRef, SettableValue) {
let cell = SettableValue::new(values);
let node = uniform(
UniformSource::Settable(cell.clone()),
ty,
UniformGroup::Object,
None,
);
(node, cell)
}
pub fn uniform_object(
ty: Type,
update: impl Fn(&crate::core::Object3D) -> Vec<f64> + 'static,
) -> NodeRef {
uniform(
UniformSource::ObjectUpdate(crate::nodes::node::ObjectUpdate::new(update)),
ty,
UniformGroup::Object,
None,
)
}
pub fn uniform_frame(
ty: Type,
update: impl Fn(&crate::nodes::NodeFrame) -> Vec<f64> + 'static,
) -> NodeRef {
uniform(
UniformSource::ObjectUpdate(crate::nodes::node::ObjectUpdate::with_frame(update)),
ty,
UniformGroup::Object,
None,
)
}
pub fn user_data(name: &str, ty: Type) -> NodeRef {
let name = name.to_owned();
let length = ty.components();
uniform_object(ty, move |object| {
let mut values = match object.user_data.get(&name) {
Some(serde_json::Value::Number(n)) => vec![n.as_f64().unwrap_or(0.0)],
Some(serde_json::Value::Array(items)) => {
items.iter().map(|v| v.as_f64().unwrap_or(0.0)).collect()
}
_ => Vec::new(),
};
values.resize(length, 0.0);
values
})
}
pub fn uniform(
source: UniformSource,
ty: Type,
group: UniformGroup,
name: Option<&'static str>,
) -> NodeRef {
NodeRef::new(Node::Uniform(Rc::new(UniformNode {
source,
ty,
group,
name,
})))
}
pub fn to_var(name: Option<&'static str>, value: NodeRef) -> NodeRef {
let ty = value.ty();
NodeRef::new(Node::Var(Rc::new(VarDef {
name: name.map(sub_build_name),
value,
ty,
})))
}
pub fn to_const(name: Option<&'static str>, value: NodeRef) -> NodeRef {
let ty = value.ty();
NodeRef::new(Node::Let(Rc::new(VarDef {
name: name.map(sub_build_name),
value,
ty,
})))
}
fn to_var_untagged(name: &'static str, value: NodeRef) -> NodeRef {
let ty = value.ty();
NodeRef::new(Node::Var(Rc::new(VarDef {
name: Some(name.to_string()),
value,
ty,
})))
}
pub fn to_varying(name: Option<&'static str>, value: NodeRef) -> NodeRef {
let ty = value.ty();
NodeRef::new(Node::Varying(Rc::new(VaryingDef {
name,
value,
ty,
flat: matches!(ty, Type::U32 | Type::I32),
})))
}
pub fn property(name: &'static str, ty: Type) -> NodeRef {
NodeRef::new(Node::Property { name, ty })
}
const COMPARISONS: [&str; 6] = ["==", "!=", "<", "<=", ">", ">="];
const LOGICAL: [&str; 2] = ["&&", "||"];
fn binary(op: &'static str, a: NodeRef, b: NodeRef) -> NodeRef {
let (ta, tb) = (a.ty(), b.ty());
if LOGICAL.contains(&op) {
return NodeRef::new(Node::Op {
op,
a,
b,
ty: Type::Bool,
});
}
if COMPARISONS.contains(&op) {
let n = ta.components().max(tb.components());
let ty = if n == 1 {
Type::Bool
} else {
Type::vector_of(Type::Bool, n)
};
return NodeRef::new(Node::Op { op, a, b, ty });
}
if ta.is_matrix() && !tb.is_matrix() && tb.components() > 1 {
let want = match ta {
Type::Mat4 => 4,
Type::Mat2 => 2,
_ => 3,
};
let ty = Type::vector_of(Type::F32, want);
let b = pad(b, want);
return NodeRef::new(Node::Op { op, a, b, ty });
}
if tb.is_matrix() && !ta.is_matrix() && ta.components() > 1 {
let want = match tb {
Type::Mat4 => 4,
Type::Mat2 => 2,
_ => 3,
};
let ty = Type::vector_of(Type::F32, want);
let a = pad(a, want);
return NodeRef::new(Node::Op { op, a, b, ty });
}
let ty = if ta.is_matrix() {
ta
} else if tb.is_matrix() || tb.components() > ta.components() {
tb
} else {
ta
};
NodeRef::new(Node::Op { op, a, b, ty })
}
fn pad(node: NodeRef, want: usize) -> NodeRef {
let have = node.ty().components();
if have >= want {
return node;
}
let mut args = vec![node];
for _ in have..want - 1 {
args.push(float(0.0));
}
args.push(float(1.0));
join(Type::vector_of(Type::F32, want), args)
}
fn math(name: &'static str, args: Vec<NodeRef>, ty: Type) -> NodeRef {
NodeRef::new(Node::Math { name, args, ty })
}
pub fn mix(a: impl Into<NodeRef>, b: impl Into<NodeRef>, t: impl Into<NodeRef>) -> NodeRef {
let (a, b, t) = (a.into(), b.into(), t.into());
let ty = if b.ty().components() > a.ty().components() {
b.ty()
} else {
a.ty()
};
math("mix", vec![a, b, t], ty)
}
pub fn dot(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
math("dot", vec![a.into(), b.into()], Type::F32)
}
pub fn cross(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
let a = a.into();
let ty = a.ty();
math("cross", vec![a, b.into()], ty)
}
pub fn refract(i: impl Into<NodeRef>, n: impl Into<NodeRef>, eta: impl Into<NodeRef>) -> NodeRef {
let i = i.into();
let ty = i.ty();
math("refract", vec![i, n.into(), eta.into()], ty)
}
pub fn ceil(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("ceil", vec![x], ty)
}
pub fn reflect(i: impl Into<NodeRef>, n: impl Into<NodeRef>) -> NodeRef {
let i = i.into();
let ty = i.ty();
math("reflect", vec![i, n.into()], ty)
}
pub fn floor(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("floor", vec![x], ty)
}
pub fn fract(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("fract", vec![x], ty)
}
pub fn sign(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("sign", vec![x], ty)
}
pub fn exp2(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("exp2", vec![x], ty)
}
pub fn log2(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("log2", vec![x], ty)
}
pub fn log(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("log", vec![x], ty)
}
pub fn exp(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("exp", vec![x], ty)
}
pub fn min_of(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
let a = a.into();
let ty = a.ty();
math("min", vec![a, b.into()], ty)
}
pub fn length(v: impl Into<NodeRef>) -> NodeRef {
math("length", vec![v.into()], Type::F32)
}
pub fn distance(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
math("distance", vec![a.into(), b.into()], Type::F32)
}
pub fn two_pi() -> NodeRef {
float(std::f64::consts::TAU)
}
pub fn rotate(position: impl Into<NodeRef>, rotation: impl Into<NodeRef>) -> NodeRef {
let (position, rotation) = (position.into(), rotation.into());
match position.ty() {
Type::Vec2 => {
let cos_angle = rotation.cos();
let sin_angle = rotation.sin();
join(
Type::Mat2,
vec![
cos_angle.clone(),
sin_angle.clone(),
sin_angle.negate(),
cos_angle,
],
)
.mul(position)
}
Type::Vec3 => {
let r = &rotation;
let row = |args: Vec<NodeRef>| join(Type::Vec4, args);
let mat4 = |rows: Vec<NodeRef>| join(Type::Mat4, rows);
let zero = || float(0.0);
let rotation_x = mat4(vec![
vec4(1.0, 0.0, 0.0, 0.0),
row(vec![zero(), r.x().cos(), r.x().sin(), zero()]),
row(vec![zero(), r.x().sin().negate(), r.x().cos(), zero()]),
vec4(0.0, 0.0, 0.0, 1.0),
]);
let rotation_y = mat4(vec![
row(vec![r.y().cos(), zero(), r.y().sin().negate(), zero()]),
vec4(0.0, 1.0, 0.0, 0.0),
row(vec![r.y().sin(), zero(), r.y().cos(), zero()]),
vec4(0.0, 0.0, 0.0, 1.0),
]);
let rotation_z = mat4(vec![
row(vec![r.z().cos(), r.z().sin(), zero(), zero()]),
row(vec![r.z().sin().negate(), r.z().cos(), zero(), zero()]),
vec4(0.0, 0.0, 1.0, 0.0),
vec4(0.0, 0.0, 0.0, 1.0),
]);
rotation_x
.mul(rotation_y)
.mul(rotation_z)
.mul(vec4_join(vec![position, float(1.0)]))
.xyz()
}
ty => panic!("three-rs: rotate() of a {ty:?}"),
}
}
pub fn abs(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("abs", vec![x], ty)
}
pub fn fwidth(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("fwidth", vec![x], ty)
}
pub fn mod_float(x: impl Into<NodeRef>, y: impl Into<NodeRef>) -> NodeRef {
math("tsl_mod_float", vec![x.into(), y.into()], Type::F32)
}
pub fn smoothstep(
low: impl Into<NodeRef>,
high: impl Into<NodeRef>,
x: impl Into<NodeRef>,
) -> NodeRef {
let (low, high, x) = (low.into(), high.into(), x.into());
let ty = wrappers::math_input_type(&[&low, &high, &x]);
math("smoothstep", vec![low, high, x], ty)
}
pub fn dpdx(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("dpdx", vec![x], ty)
}
pub fn dpdy(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("- dpdy", vec![x], ty)
}
pub fn checker(coord: impl Into<NodeRef>) -> NodeRef {
let uv = coord.into().mul(2.0);
let cx = floor(uv.x());
let cy = floor(uv.y());
sign(mod_float(cx.add(cy), 2.0))
}
pub fn perspective_depth_to_view_z(
depth: impl Into<NodeRef>,
near: impl Into<NodeRef>,
far: impl Into<NodeRef>,
) -> NodeRef {
let (depth, near, far) = (depth.into(), near.into(), far.into());
near.clone()
.mul(far.clone())
.div(far.clone().sub(near).mul(depth).sub(far))
}
fn fog_view_z() -> NodeRef {
current_context(|cx| cx.extra.get("getViewZ").cloned()).unwrap_or_else(|| position_view().z())
}
pub fn range_fog_factor(near: impl Into<NodeRef>, far: impl Into<NodeRef>) -> NodeRef {
let (near, far) = (near.into(), far.into());
fog_factor_fn(move || range_fog_factor_with_view_z(near.clone(), far.clone(), fog_view_z()))
}
fn fog_factor_fn(body: impl Fn() -> NodeRef + 'static) -> NodeRef {
call(&inline_fn(0, Type::F32, move |_| body()), Vec::new())
}
pub(crate) fn resolve_fog_factor(factor: &NodeRef) -> NodeRef {
resolve_fn_call(factor)
}
pub(crate) fn resolve_fn_call(node: &NodeRef) -> NodeRef {
match node.node() {
Node::Call { def, args } if !def.layout && args.is_empty() => (def.body)(&[]),
_ => node.clone(),
}
}
pub fn range_fog_factor_with_view_z(
near: impl Into<NodeRef>,
far: impl Into<NodeRef>,
view_z: impl Into<NodeRef>,
) -> NodeRef {
smoothstep(near, far, view_z.into().negate())
}
pub fn density_fog_factor(density: impl Into<NodeRef>) -> NodeRef {
let density = density.into();
fog_factor_fn(move || density_fog_factor_with_view_z(density.clone(), fog_view_z()))
}
pub fn density_fog_factor_with_view_z(
density: impl Into<NodeRef>,
view_z: impl Into<NodeRef>,
) -> NodeRef {
let density = density.into();
let view_z = to_const(None, view_z.into().negate());
exp(density
.clone()
.mul(density)
.mul(view_z.clone())
.mul(view_z)
.negate())
.one_minus()
}
pub fn exponential_height_fog_factor(
density: impl Into<NodeRef>,
height: impl Into<NodeRef>,
) -> NodeRef {
let (density, height) = (density.into(), height.into());
fog_factor_fn(move || {
exponential_height_fog_factor_with_view_z(density.clone(), height.clone(), fog_view_z())
})
}
pub fn exponential_height_fog_factor_with_view_z(
density: impl Into<NodeRef>,
height: impl Into<NodeRef>,
view_z: impl Into<NodeRef>,
) -> NodeRef {
let density = density.into();
let view_z = view_z.into().negate();
let distance = to_const(None, height.into().sub(position_world().y()).max(0.0));
let m = to_const(None, distance.mul(view_z));
exp(density.clone().mul(density).mul(m.clone()).mul(m).negate()).one_minus()
}
pub fn fog(color: impl Into<NodeRef>, factor: impl Into<NodeRef>) -> FogNode {
FogNode {
color: color.into(),
factor: factor.into(),
}
}
#[derive(Clone)]
pub struct FogNode {
pub color: NodeRef,
pub factor: NodeRef,
}
impl std::hash::Hash for FogNode {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.color.key().hash(state);
self.factor.key().hash(state);
}
}
pub(crate) fn light_color_intensity(index: usize) -> NodeRef {
uniform(
UniformSource::LightColorIntensity(index),
Type::Vec3,
UniformGroup::Render,
None,
)
}
pub(crate) fn light_cutoff_distance(index: usize) -> NodeRef {
uniform(
UniformSource::LightCutoffDistance(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn light_decay(index: usize) -> NodeRef {
uniform(
UniformSource::LightDecay(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub fn light_view_position(index: usize) -> NodeRef {
uniform(
UniformSource::LightViewPosition(index),
Type::Vec3,
UniformGroup::Render,
None,
)
}
pub(crate) fn light_ground_color(index: usize) -> NodeRef {
uniform(
UniformSource::LightGroundColor(index),
Type::Vec3,
UniformGroup::Render,
None,
)
}
pub fn light_world_position(index: usize) -> NodeRef {
uniform(
UniformSource::LightWorldPosition(index),
Type::Vec3,
UniformGroup::Render,
None,
)
}
pub fn light_target_position(index: usize) -> NodeRef {
uniform(
UniformSource::LightTargetPosition(index),
Type::Vec3,
UniformGroup::Render,
None,
)
}
pub(crate) fn light_cone_cos(index: usize) -> NodeRef {
uniform(
UniformSource::LightConeCos(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn light_penumbra_cos(index: usize) -> NodeRef {
uniform(
UniformSource::LightPenumbraCos(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub fn shadow_matrix(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowMatrix(index),
Type::Mat4,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_camera_near(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowCameraNear(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_camera_far(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowCameraFar(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_bias(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowBias(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_normal_bias(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowNormalBias(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_radius(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowRadius(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_blur_samples(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowBlurSamples(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_map_size(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowMapSize(index),
Type::Vec2,
UniformGroup::Render,
None,
)
}
pub(crate) fn shadow_intensity(index: usize) -> NodeRef {
uniform(
UniformSource::ShadowIntensity(index),
Type::F32,
UniformGroup::Render,
None,
)
}
pub fn material_metalness() -> NodeRef {
uniform(
UniformSource::MaterialMetalness,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_ior() -> NodeRef {
uniform(
UniformSource::MaterialIor,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_specular_intensity() -> NodeRef {
uniform(
UniformSource::MaterialSpecularIntensity,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_specular_color() -> NodeRef {
uniform(
UniformSource::MaterialSpecularColor,
Type::Vec3,
UniformGroup::Object,
None,
)
}
pub fn material_sheen() -> NodeRef {
uniform(
UniformSource::MaterialSheen,
Type::F32,
UniformGroup::Object,
None,
)
}
pub(crate) fn material_sheen_color() -> NodeRef {
uniform(
UniformSource::MaterialSheenColor,
Type::Vec3,
UniformGroup::Object,
None,
)
}
pub fn material_sheen_roughness() -> NodeRef {
uniform(
UniformSource::MaterialSheenRoughness,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_diffuse_roughness() -> NodeRef {
uniform(
UniformSource::MaterialDiffuseRoughness,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_anisotropy_vector() -> NodeRef {
uniform(
UniformSource::MaterialAnisotropyVector,
Type::Vec2,
UniformGroup::Object,
None,
)
}
pub fn material_clearcoat() -> NodeRef {
uniform(
UniformSource::MaterialClearcoat,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_clearcoat_roughness() -> NodeRef {
uniform(
UniformSource::MaterialClearcoatRoughness,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_transmission() -> NodeRef {
uniform(
UniformSource::MaterialTransmission,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_thickness() -> NodeRef {
uniform(
UniformSource::MaterialThickness,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_attenuation_distance() -> NodeRef {
uniform(
UniformSource::MaterialAttenuationDistance,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn material_attenuation_color() -> NodeRef {
uniform(
UniformSource::MaterialAttenuationColor,
Type::Vec3,
UniformGroup::Object,
None,
)
}
pub(crate) fn material_clearcoat_normal_scale() -> NodeRef {
uniform(
UniformSource::MaterialClearcoatNormalScale,
Type::Vec2,
UniformGroup::Object,
None,
)
}
pub(crate) fn material_normal_scale() -> NodeRef {
uniform(
UniformSource::MaterialNormalScale,
Type::Vec2,
UniformGroup::Object,
None,
)
}
pub fn material_roughness() -> NodeRef {
uniform(
UniformSource::MaterialRoughness,
Type::F32,
UniformGroup::Object,
None,
)
}
pub(crate) fn material_bump_scale() -> NodeRef {
uniform(
UniformSource::MaterialBumpScale,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn tone_mapping_exposure() -> NodeRef {
uniform(
UniformSource::ToneMappingExposure,
Type::F32,
UniformGroup::Render,
None,
)
}
pub fn inverse_sqrt(x: impl Into<NodeRef>) -> NodeRef {
math("inverseSqrt", vec![x.into()], Type::F32)
}
pub fn tbn_view_matrix() -> NodeRef {
thread_local! {
static CELL: RefCell<HashMap<NormalViewKey, NodeRef>> = RefCell::new(HashMap::new());
}
let key = normal_key();
if let Some(node) = CELL.with(|m| m.borrow().get(&key).cloned()) {
return node;
}
let node = to_var(
Some("TBNViewMatrix"),
join(
Type::Mat3,
vec![tangent_view(), bitangent_view(), normal_view()],
),
);
CELL.with(|m| m.borrow_mut().insert(key, node.clone()));
node
}
pub fn normal_map(node: impl Into<NodeRef>) -> NodeRef {
let texel = node.into();
in_sub_build("NORMAL", || {
tbn_view_matrix()
.mul(texel.mul(2.0).sub(1.0).xyz())
.normalize()
})
}
pub fn normal_map_scaled(node: impl Into<NodeRef>, scale: NodeRef) -> NodeRef {
let texel = node.into();
in_sub_build("NORMAL", || {
let unpacked = to_var(None, texel.mul(2.0).sub(1.0));
tbn_view_matrix()
.mul(vec3_join(vec![
unpacked.xy().mul(scale.clone()),
unpacked.z(),
]))
.normalize()
})
}
pub fn sqrt(x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("sqrt", vec![x], ty)
}
pub fn max(a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
let a = a.into();
let ty = a.ty();
math("max", vec![a, b.into()], ty)
}
fn whole(ty: Type) -> &'static str {
match ty.components() {
1 => "x",
2 => "xy",
3 => "xyz",
_ => "xyzw",
}
}
fn swizzle(node: NodeRef, components: &'static str) -> NodeRef {
if components == whole(node.ty()) {
return node;
}
let ty = Type::vector_of(node.ty().component_type(), components.len());
NodeRef::new(Node::Swizzle {
node,
components,
ty,
})
}
impl NodeRef {
pub fn add(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("+", self.clone(), other.into())
}
pub fn sub(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("-", self.clone(), other.into())
}
pub fn mul(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("*", self.clone(), other.into())
}
pub fn div(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("/", self.clone(), other.into())
}
pub fn modulo(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("%", self.clone(), other.into())
}
pub fn equal(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("==", self.clone(), other.into())
}
pub fn not_equal(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("!=", self.clone(), other.into())
}
pub fn less_than_equal(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("<=", self.clone(), other.into())
}
pub fn greater_than(&self, other: impl Into<NodeRef>) -> NodeRef {
binary(">", self.clone(), other.into())
}
pub fn greater_than_equal(&self, other: impl Into<NodeRef>) -> NodeRef {
binary(">=", self.clone(), other.into())
}
pub fn less_than(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("<", self.clone(), other.into())
}
pub fn and(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("&&", self.clone(), other.into())
}
pub fn or(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("||", self.clone(), other.into())
}
pub fn not(&self) -> NodeRef {
NodeRef::new(Node::Not { node: self.clone() })
}
pub fn shift_left(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("<<", self.clone(), other.into())
}
pub fn shift_right(&self, other: impl Into<NodeRef>) -> NodeRef {
binary(">>", self.clone(), other.into())
}
pub fn bit_and(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("&", self.clone(), other.into())
}
pub fn bit_or(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("|", self.clone(), other.into())
}
pub fn bit_xor(&self, other: impl Into<NodeRef>) -> NodeRef {
binary("^", self.clone(), other.into())
}
pub fn one_minus(&self) -> NodeRef {
binary("-", float(1.0), self.clone())
}
pub fn negate(&self) -> NodeRef {
NodeRef::new(Node::Neg {
node: self.clone(),
ty: self.ty(),
})
}
pub fn normalize(&self) -> NodeRef {
math("normalize", vec![self.clone()], self.ty())
}
pub fn cos(&self) -> NodeRef {
math("cos", vec![self.clone()], self.ty())
}
pub fn sin(&self) -> NodeRef {
math("sin", vec![self.clone()], self.ty())
}
pub fn asin(&self) -> NodeRef {
math("asin", vec![self.clone()], self.ty())
}
pub fn atan2(&self, x: impl Into<NodeRef>) -> NodeRef {
math("atan2", vec![self.clone(), x.into()], self.ty())
}
pub fn floor(&self) -> NodeRef {
math("floor", vec![self.clone()], self.ty())
}
pub fn fract(&self) -> NodeRef {
math("fract", vec![self.clone()], self.ty())
}
pub fn sqrt(&self) -> NodeRef {
math("sqrt", vec![self.clone()], self.ty())
}
pub fn abs(&self) -> NodeRef {
math("abs", vec![self.clone()], self.ty())
}
pub fn saturate(&self) -> NodeRef {
let ty = self.ty();
let lo = if ty.components() > 1 {
constant(ty, vec![0.0; ty.components()])
} else {
float(0.0)
};
let hi = if ty.components() > 1 {
constant(ty, vec![1.0; ty.components()])
} else {
float(1.0)
};
math("clamp", vec![self.clone(), lo, hi], ty)
}
pub fn pow(&self, other: impl Into<NodeRef>) -> NodeRef {
math("pow", vec![self.clone(), other.into()], self.ty())
}
pub fn pow3(&self) -> NodeRef {
self.mul(self.clone()).mul(self.clone())
}
pub fn reciprocal(&self) -> NodeRef {
float(1.0).div(self.clone())
}
pub fn exp2(&self) -> NodeRef {
exp2(self.clone())
}
pub fn max(&self, other: impl Into<NodeRef>) -> NodeRef {
math("max", vec![self.clone(), other.into()], self.ty())
}
pub fn min(&self, other: impl Into<NodeRef>) -> NodeRef {
math("min", vec![self.clone(), other.into()], self.ty())
}
pub fn clamp(&self, lo: impl Into<NodeRef>, hi: impl Into<NodeRef>) -> NodeRef {
math("clamp", vec![self.clone(), lo.into(), hi.into()], self.ty())
}
pub fn dot(&self, other: impl Into<NodeRef>) -> NodeRef {
dot(self.clone(), other)
}
pub fn cross(&self, other: impl Into<NodeRef>) -> NodeRef {
cross(self.clone(), other)
}
pub fn mix(&self, a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
mix(a, b, self.clone())
}
pub fn swizzle(&self, components: &'static str) -> NodeRef {
swizzle(self.clone(), components)
}
pub fn x(&self) -> NodeRef {
swizzle(self.clone(), "x")
}
pub fn y(&self) -> NodeRef {
swizzle(self.clone(), "y")
}
pub fn z(&self) -> NodeRef {
swizzle(self.clone(), "z")
}
pub fn w(&self) -> NodeRef {
swizzle(self.clone(), "w")
}
pub fn xy(&self) -> NodeRef {
swizzle(self.clone(), "xy")
}
pub fn yz(&self) -> NodeRef {
swizzle(self.clone(), "yz")
}
pub fn zw(&self) -> NodeRef {
swizzle(self.clone(), "zw")
}
pub fn zx(&self) -> NodeRef {
swizzle(self.clone(), "zx")
}
pub fn xyz(&self) -> NodeRef {
swizzle(self.clone(), "xyz")
}
pub fn xz(&self) -> NodeRef {
swizzle(self.clone(), "xz")
}
pub fn zzz(&self) -> NodeRef {
swizzle(self.clone(), "zzz")
}
pub fn rgb(&self) -> NodeRef {
swizzle(self.clone(), "xyz")
}
pub fn a(&self) -> NodeRef {
swizzle(self.clone(), "w")
}
pub fn set_z(&self, z: impl Into<NodeRef>) -> NodeRef {
join(Type::Vec4, vec![self.x(), self.y(), z.into(), self.w()])
}
pub fn to(&self, ty: Type) -> NodeRef {
if self.ty() == ty {
return self.clone();
}
NodeRef::new(Node::Cast {
node: self.clone(),
ty,
})
}
pub fn element(&self, index: usize) -> NodeRef {
let ty = match self.ty() {
Type::Mat4 => Type::Vec4,
Type::Mat3 => Type::Vec3,
Type::Mat2 => Type::Vec2,
other => other.component_type(),
};
NodeRef::new(Node::Element {
node: self.clone(),
index: constant(Type::U32, vec![index as f64]),
ty,
})
}
pub fn element_node(&self, index: NodeRef) -> NodeRef {
let ty = match self.ty() {
Type::Mat4 => Type::Vec4,
Type::Mat3 => Type::Vec3,
Type::Mat2 => Type::Vec2,
other if matches!(self.node(), Node::ConstArray { .. } | Node::ArrayVar { .. }) => {
other
}
other => other.component_type(),
};
NodeRef::new(Node::Element {
node: self.clone(),
index,
ty,
})
}
pub fn select(&self, a: impl Into<NodeRef>, b: impl Into<NodeRef>) -> NodeRef {
let a = a.into();
let ty = a.ty();
NodeRef::new(Node::Select {
cond: self.clone(),
a,
b: b.into(),
ty,
})
}
pub fn flip_y(&self) -> NodeRef {
let source = to_var(None, self.clone());
match self.ty() {
Type::Vec2 => vec2_join(vec![source.x(), float(1.0).sub(source.y())]),
Type::Vec3 => vec3_join(vec![source.x(), float(1.0).sub(source.y()), source.z()]),
Type::Vec4 => vec4_join(vec![
source.x(),
float(1.0).sub(source.y()),
source.z(),
source.w(),
]),
ty => panic!("flipY() on a {ty:?}"),
}
}
pub fn flip_x(&self) -> NodeRef {
let source = to_var(None, self.clone());
match self.ty() {
Type::Vec2 => vec2_join(vec![float(1.0).sub(source.x()), source.y()]),
Type::Vec3 => vec3_join(vec![float(1.0).sub(source.x()), source.y(), source.z()]),
Type::Vec4 => vec4_join(vec![
float(1.0).sub(source.x()),
source.y(),
source.z(),
source.w(),
]),
ty => panic!("flipX() on a {ty:?}"),
}
}
pub fn to_var(&self, name: &'static str) -> NodeRef {
to_var(Some(name), self.clone())
}
pub fn context(&self, value: ContextValue) -> NodeRef {
context(self.clone(), value)
}
pub fn isolate(&self) -> NodeRef {
isolate(self.clone())
}
pub fn to_varying(&self, name: &'static str) -> NodeRef {
to_varying(Some(name), self.clone())
}
pub fn add_assign(&self, value: impl Into<NodeRef>) -> NodeRef {
self.assign(self.add(value))
}
pub fn sub_assign(&self, value: impl Into<NodeRef>) -> NodeRef {
self.assign(self.sub(value))
}
pub fn mul_assign(&self, value: impl Into<NodeRef>) -> NodeRef {
self.assign(self.mul(value))
}
pub fn div_assign(&self, value: impl Into<NodeRef>) -> NodeRef {
self.assign(self.div(value))
}
pub fn assign(&self, value: impl Into<NodeRef>) -> NodeRef {
NodeRef::new(Node::Assign {
target: self.clone(),
value: value.into(),
})
}
}
macro_rules! accessor {
($(#[$m:meta])* pub(crate) $name:ident, $body:expr) => {
$(#[$m])*
pub(crate) fn $name() -> NodeRef {
thread_local! {
static CELL: Lazy<NodeRef> = const { Lazy::new() };
}
CELL.with(|c| c.get(|| $body))
}
};
($(#[$m:meta])* $name:ident, $body:expr) => {
$(#[$m])*
pub fn $name() -> NodeRef {
thread_local! {
static CELL: Lazy<NodeRef> = const { Lazy::new() };
}
CELL.with(|c| c.get(|| $body))
}
};
}
accessor!(
position_geometry,
attribute("position", Type::Vec3)
);
accessor!(
normal_geometry,
attribute("normal", Type::Vec3)
);
accessor!(
uv,
to_varying(None, attribute("uv", Type::Vec2))
);
accessor!(
uv1,
to_varying(None, attribute("uv1", Type::Vec2))
);
accessor!(
pub(crate) vertex_color_rgb,
to_varying(
None,
vec4_join(vec![attribute("color", Type::Vec3), float(1.0)])
)
);
accessor!(
pub(crate) vertex_color_rgba,
to_varying(None, attribute("color", Type::Vec4))
);
pub fn vertex_color(item_size: usize) -> NodeRef {
match item_size {
4 => vertex_color_rgba(),
_ => vertex_color_rgb(),
}
}
accessor!(
vertex_index,
NodeRef::new(Node::Builtin(Builtin::VertexIndex))
);
accessor!(
instance_index,
NodeRef::new(Node::Builtin(Builtin::InstanceIndex))
);
accessor!(
invocation_local_index,
NodeRef::new(Node::Builtin(Builtin::InvocationLocalIndex))
);
accessor!(
workgroup_id,
NodeRef::new(Node::Builtin(Builtin::WorkgroupId))
);
accessor!(
local_id,
NodeRef::new(Node::Builtin(Builtin::LocalId))
);
accessor!(
global_id,
NodeRef::new(Node::Builtin(Builtin::GlobalId))
);
accessor!(
num_workgroups,
NodeRef::new(Node::Builtin(Builtin::NumWorkgroups))
);
accessor!(
front_facing,
NodeRef::new(Node::Builtin(Builtin::FrontFacing))
);
accessor!(
face_direction,
front_facing().to(Type::F32).mul(2.0).sub(1.0)
);
accessor!(
frag_coord,
NodeRef::new(Node::Builtin(Builtin::FragCoord))
);
accessor!(
camera_projection_matrix,
uniform(
UniformSource::CameraProjectionMatrix,
Type::Mat4,
UniformGroup::Render,
Some("cameraProjectionMatrix")
)
);
accessor!(
camera_view_matrix,
uniform(
UniformSource::CameraViewMatrix,
Type::Mat4,
UniformGroup::Render,
Some("cameraViewMatrix")
)
);
accessor!(
camera_world_matrix,
uniform(
UniformSource::CameraWorldMatrix,
Type::Mat4,
UniformGroup::Render,
Some("cameraWorldMatrix")
)
);
accessor!(
camera_position,
uniform(
UniformSource::CameraPosition,
Type::Vec3,
UniformGroup::Render,
Some("cameraPosition")
)
);
accessor!(
model_world_matrix,
uniform(
UniformSource::ModelWorldMatrix,
Type::Mat4,
UniformGroup::Object,
None
)
);
accessor!(
model_normal_matrix,
uniform(
UniformSource::ModelNormalMatrix,
Type::Mat3,
UniformGroup::Object,
None
)
);
accessor!(
material_color,
uniform(
UniformSource::MaterialColor,
Type::Vec3,
UniformGroup::Object,
None
)
);
accessor!(
material_opacity,
uniform(
UniformSource::MaterialOpacity,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
material_alpha_test,
uniform(
UniformSource::MaterialAlphaTest,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
material_rotation,
uniform(
UniformSource::MaterialRotation,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
material_shininess,
uniform(
UniformSource::MaterialShininess,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
material_specular,
uniform(
UniformSource::MaterialSpecular,
Type::Vec3,
UniformGroup::Object,
None
)
);
accessor!(
material_emissive,
uniform(
UniformSource::MaterialEmissive,
Type::Vec3,
UniformGroup::Object,
None
)
);
accessor!(
pub(crate) material_emissive_intensity,
uniform(
UniformSource::MaterialEmissiveIntensity,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
pub(crate) material_ao_map_intensity,
uniform(
UniformSource::MaterialAoMapIntensity,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
material_env_intensity,
uniform(
UniformSource::MaterialEnvIntensity,
Type::F32,
UniformGroup::Object,
None,
)
);
accessor!(
material_reflectivity,
uniform(
UniformSource::MaterialReflectivity,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
material_env_rotation,
uniform(
UniformSource::EnvRotationMatrix,
Type::Mat4,
UniformGroup::Object,
None
)
);
accessor!(
background_rotation,
uniform(
UniformSource::BackgroundRotation,
Type::Mat4,
UniformGroup::Render,
None
)
);
accessor!(
background_blurriness,
uniform(
UniformSource::BackgroundBlurriness,
Type::F32,
UniformGroup::Render,
None
)
);
accessor!(
background_intensity,
uniform(
UniformSource::BackgroundIntensity,
Type::F32,
UniformGroup::Render,
None
)
);
accessor!(
time,
uniform(UniformSource::Time, Type::F32, UniformGroup::Render, None)
);
accessor!(
viewport_size,
uniform(
UniformSource::ViewportSize,
Type::Vec2,
UniformGroup::Render,
None
)
);
accessor!(
viewport,
uniform(UniformSource::Viewport, Type::Vec4, UniformGroup::Render, None)
);
accessor!(
screen_dpr,
uniform(UniformSource::ScreenDpr, Type::F32, UniformGroup::Render, None)
);
accessor!(
camera_projection_matrix_inverse,
uniform(
UniformSource::CameraProjectionMatrixInverse,
Type::Mat4,
UniformGroup::Render,
Some("cameraProjectionMatrixInverse")
)
);
accessor!(
model_world_matrix_inverse,
uniform(
UniformSource::ModelWorldMatrixInverse,
Type::Mat4,
UniformGroup::Object,
None
)
);
accessor!(
material_line_width,
uniform(
UniformSource::MaterialLineWidth,
Type::F32,
UniformGroup::Object,
None
)
);
accessor!(
screen_uv,
frag_coord().xy().div(viewport_size())
);
accessor!(
position_local,
to_varying(Some("positionLocal"), position_geometry())
);
accessor!(
normal_local,
to_var(Some("normalLocal"), normal_geometry())
);
accessor!(
model_view_matrix,
to_var(
Some("modelViewMatrix"),
camera_view_matrix().mul(model_world_matrix())
)
);
pub fn position_view() -> NodeRef {
if let Some(node) = override_node(|o| &o.position_view) {
return node;
}
position_view_pair().0
}
accessor!(
position_world,
to_varying(
Some("v_positionWorld"),
model_world_matrix()
.mul(vec4_join(vec![position_local(), float(1.0)]))
.xyz()
)
);
accessor!(
position_world_direction,
to_var(
Some("positionWorldDirection"),
to_varying(
Some("v_positionWorldDirection"),
model_world_matrix()
.mul(vec4_join(vec![position_local(), float(0.0)]))
.xyz()
.normalize()
)
.normalize()
)
);
pub fn position_view_direction() -> NodeRef {
if let Some(node) = override_node(|o| &o.position_view_direction) {
return node;
}
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| {
c.get(|| {
to_var(
Some("positionViewDirection"),
to_varying(Some("v_positionViewDirection"), position_view().negate()).normalize(),
)
})
})
}
pub fn normal_flat() -> NodeRef {
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| {
c.get(|| {
to_var(
Some("normalFlat"),
cross(dpdx(position_view()), dpdy(position_view())).normalize(),
)
})
})
}
pub fn normal_view_geometry() -> NodeRef {
let flat = current_context(|cx| cx.flat_shading);
if let Some(node) = NORMAL_VIEW_GEOMETRY.with(|m| m.borrow().get(&flat).cloned()) {
return node;
}
let value = if flat {
normal_flat()
} else {
to_varying(
Some("v_normalViewGeometry"),
camera_view_matrix()
.mul(vec4_join(vec![
model_normal_matrix().mul(normal_local()),
float(0.0),
]))
.xyz()
.normalize(),
)
.normalize()
};
let node = to_var(Some("normalViewGeometry"), value);
NORMAL_VIEW_GEOMETRY.with(|m| m.borrow_mut().insert(flat, node.clone()));
node
}
fn normal_key() -> NormalViewKey {
let layer = current_context(|cx| cx.sub_build);
let value = if layer.is_some() {
None
} else {
current_context(|cx| cx.setup_normal.clone())
};
(
layer,
value.as_ref().map(|v| v.key()),
current_context(|cx| cx.flat_shading),
current_context(|cx| cx.material_side),
current_context(|cx| cx.has_tangent),
override_node(|o| &o.normal_view).map(|n| n.key()),
)
}
fn normal_value() -> Option<NodeRef> {
let layer = current_context(|cx| cx.sub_build);
if layer.is_some() {
None
} else {
current_context(|cx| cx.setup_normal.clone())
}
}
pub fn normal_view() -> NodeRef {
if let Some(node) = override_node(|o| &o.normal_view) {
return node;
}
let key = normal_key();
let flat = current_context(|cx| cx.flat_shading);
if let Some(node) = NORMAL_VIEW.with(|m| m.borrow().get(&key).cloned()) {
return node;
}
let node = to_var(
Some("normalView"),
match normal_value() {
Some(value) => value,
None if flat => normal_view_geometry(),
None => negate_on_back_side(normal_view_geometry()),
},
);
NORMAL_VIEW.with(|m| m.borrow_mut().insert(key, node.clone()));
node
}
fn tangent_frame() -> (NodeRef, NodeRef) {
let key = normal_key();
if let Some(pair) = TANGENT_VIEW.with(|m| m.borrow().get(&key).cloned()) {
return pair;
}
if current_context(|cx| cx.has_tangent) {
let pair = tangent_attribute_frame();
TANGENT_VIEW.with(|m| m.borrow_mut().insert(key, pair.clone()));
return pair;
}
let n = normal_view();
let q1perp = cross(dpdy(position_view()), n.clone());
let q0perp = cross(n, dpdx(position_view()));
let st0 = dpdx(uv());
let st1 = dpdy(uv());
let t = q1perp
.clone()
.mul(st0.clone().x())
.add(q0perp.clone().mul(st1.clone().x()));
let b = q1perp.mul(st0.y()).add(q0perp.mul(st1.y()));
let det = max(t.clone().dot(t.clone()), b.clone().dot(b.clone()));
let scale = det
.clone()
.equal(float(0.0))
.select(float(0.0), inverse_sqrt(det));
let flat = current_context(|cx| cx.flat_shading);
let frame = |name, value| {
if flat {
value
} else {
let _ = name;
negate_on_back_side(value)
}
};
let pair = (
to_var(
Some("tangentView"),
frame(
"tangentView",
to_var_untagged("tangentViewFrame", t.mul(scale.clone())),
),
),
to_var(
Some("bitangentView"),
frame(
"bitangentView",
to_var_untagged("bitangentViewFrame", b.mul(scale)),
),
),
);
TANGENT_VIEW.with(|m| m.borrow_mut().insert(key, pair.clone()));
pair
}
fn tangent_attribute_frame() -> (NodeRef, NodeRef) {
let tangent_geometry = attribute("tangent", Type::Vec4);
let tangent_local = to_var(Some("tangentLocal"), tangent_geometry.clone().xyz());
let flat = current_context(|cx| cx.flat_shading);
let front_side = |value: NodeRef| {
if flat {
value
} else {
negate_on_back_side(value)
}
};
thread_local! { static TANGENT_VARYING: Lazy<NodeRef> = const { Lazy::new() }; }
let tangent = TANGENT_VARYING
.with(|c| {
c.get(|| {
to_varying(
Some("v_tangentView"),
model_view_matrix()
.mul(vec4_join(vec![tangent_local, float(0.0)]))
.xyz(),
)
})
})
.normalize();
let tangent_view = to_var(Some("tangentView"), front_side(tangent));
let cross_normal_tangent = cross(normal_view(), tangent_view.clone()).mul(tangent_geometry.w());
let in_normal_layer = current_context(|cx| cx.sub_build) == Some("NORMAL");
let bitangent = if in_normal_layer && !flat {
to_varying(Some("NORMAL_v_bitangentView"), cross_normal_tangent)
} else {
cross_normal_tangent
}
.normalize();
let bitangent_view = to_var(Some("bitangentView"), front_side(bitangent));
(tangent_view, bitangent_view)
}
pub fn tangent_view() -> NodeRef {
tangent_frame().0
}
pub fn bitangent_view() -> NodeRef {
tangent_frame().1
}
pub fn normal_world() -> NodeRef {
let key = normal_key();
if let Some(node) = NORMAL_WORLD.with(|m| m.borrow().get(&key).cloned()) {
return node;
}
let node = to_var(
Some("normalWorld"),
vec4_join(vec![normal_view(), float(0.0)])
.mul(camera_view_matrix())
.xyz()
.normalize(),
);
NORMAL_WORLD.with(|m| m.borrow_mut().insert(key, node.clone()));
node
}
accessor!(
normal_world_geometry,
to_var(
Some("normalWorldGeometry"),
to_varying(
Some("v_normalWorldGeometry"),
vec4_join(vec![normal_view_geometry(), float(0.0)])
.mul(camera_view_matrix())
.xyz()
.normalize()
)
.normalize()
)
);
pub fn model_view_projection() -> NodeRef {
position_view_pair().1
}
accessor!(
reflect_vector,
to_var(
Some("reflectVector"),
camera_world_matrix()
.mul(vec4_join(vec![
reflect(position_view_direction().negate(), normal_view()),
float(0.0)
]))
.xyz()
.normalize()
)
);
pub fn diffuse_color() -> NodeRef {
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| c.get(|| property("DiffuseColor", Type::Vec4)))
}
macro_rules! prop {
($(#[$meta:meta])* pub(crate) $name:ident, $wgsl:literal, $ty:expr) => {
$(#[$meta])*
pub(crate) fn $name() -> NodeRef {
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| c.get(|| property($wgsl, $ty)))
}
};
($(#[$meta:meta])* $name:ident, $wgsl:literal, $ty:expr) => {
$(#[$meta])*
pub fn $name() -> NodeRef {
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| c.get(|| property($wgsl, $ty)))
}
};
}
prop!(
output_property, "Output", Type::Vec4);
prop!(pub(crate) total_diffuse, "totalDiffuse", Type::Vec3);
prop!(pub(crate) total_specular, "totalSpecular", Type::Vec3);
prop!(pub(crate) outgoing_light, "outgoingLight", Type::Vec3);
prop!(
shininess, "Shininess", Type::F32);
prop!(
specular_color, "SpecularColor", Type::Vec3);
prop!(
emissive_color, "EmissiveColor", Type::Vec3);
pub(crate) fn ambient_occlusion_property() -> NodeRef {
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| c.get(|| property("AmbientOcclusion", Type::F32)))
}
macro_rules! lighting_var {
($(#[$meta:meta])* pub(crate) $name:ident, $wgsl:literal, $init:expr) => {
$(#[$meta])*
pub(crate) fn $name() -> NodeRef {
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| c.get(|| to_var_untagged($wgsl, $init)))
}
};
($(#[$meta:meta])* $name:ident, $wgsl:literal, $init:expr) => {
$(#[$meta])*
pub fn $name() -> NodeRef {
thread_local! { static CELL: Lazy<NodeRef> = const { Lazy::new() }; }
CELL.with(|c| c.get(|| to_var_untagged($wgsl, $init)))
}
};
}
lighting_var!(pub(crate) direct_diffuse, "directDiffuse", vec3(0.0, 0.0, 0.0));
lighting_var!(pub(crate) direct_specular, "directSpecular", vec3(0.0, 0.0, 0.0));
lighting_var!(pub(crate) indirect_diffuse, "indirectDiffuse", vec3(0.0, 0.0, 0.0));
lighting_var!(pub(crate) indirect_specular, "indirectSpecular", vec3(0.0, 0.0, 0.0));
lighting_var!(
irradiance, "irradiance", vec3(0.0, 0.0, 0.0));
lighting_var!(
ambient_occlusion, "ambientOcclusion", float(1.0));
lighting_var!(
radiance, "radiance", vec3(0.0, 0.0, 0.0));
lighting_var!(
ibl_irradiance, "iblIrradiance", vec3(0.0, 0.0, 0.0));
prop!(
metalness, "Metalness", Type::F32);
prop!(pub(crate) single_scattering, "singleScattering", Type::Vec3);
prop!(pub(crate) multi_scattering, "multiScattering", Type::Vec3);
prop!(
roughness, "Roughness", Type::F32);
prop!(
specular_color_blended, "SpecularColorBlended", Type::Vec3);
prop!(
specular_f90, "SpecularF90", Type::F32);
prop!(
ior, "IOR", Type::F32);
prop!(
diffuse_contribution, "DiffuseContribution", Type::Vec3);
prop!(
sheen, "Sheen", Type::Vec3);
prop!(
sheen_roughness, "SheenRoughness", Type::F32);
prop!(pub(crate) sheen_specular_direct, "sheenSpecularDirect", Type::Vec3);
prop!(pub(crate) sheen_specular_indirect, "sheenSpecularIndirect", Type::Vec3);
prop!(
diffuse_roughness, "DiffuseRoughness", Type::F32);
prop!(
pub(crate) single_scattering_dielectric,
"singleScatteringDielectric",
Type::Vec3
);
prop!(
pub(crate) multi_scattering_dielectric,
"multiScatteringDielectric",
Type::Vec3
);
prop!(
pub(crate) single_scattering_metallic,
"singleScatteringMetallic",
Type::Vec3
);
prop!(
pub(crate) multi_scattering_metallic,
"multiScatteringMetallic",
Type::Vec3
);
prop!(
anisotropy, "Anisotropy", Type::F32);
prop!(
alpha_t, "AlphaT", Type::F32);
prop!(
anisotropy_t, "AnisotropyT", Type::Vec3);
prop!(
anisotropy_b, "AnisotropyB", Type::Vec3);
prop!(
clearcoat, "Clearcoat", Type::F32);
prop!(
clearcoat_roughness, "ClearcoatRoughness", Type::F32);
prop!(
transmission, "Transmission", Type::F32);
prop!(
thickness, "Thickness", Type::F32);
prop!(
attenuation_distance, "AttenuationDistance", Type::F32);
prop!(
attenuation_color, "AttenuationColor", Type::Vec3);
lighting_var!(pub(crate) clearcoat_radiance, "clearcoatRadiance", vec3(0.0, 0.0, 0.0));
lighting_var!(
pub(crate) clearcoat_specular_direct,
"clearcoatSpecularDirect",
vec3(0.0, 0.0, 0.0)
);
lighting_var!(
pub(crate) clearcoat_specular_indirect,
"clearcoatSpecularIndirect",
vec3(0.0, 0.0, 0.0)
);
thread_local! {
static CLEARCOAT_NORMAL_VIEW: RefCell<HashMap<Option<usize>, NodeRef>> =
RefCell::new(HashMap::new());
}
pub(crate) fn with_clearcoat_normal<R>(normal: Option<NodeRef>, f: impl FnOnce() -> R) -> R {
let _clearcoat = push_context(|cx| cx.setup_clearcoat_normal = normal);
f()
}
pub fn clearcoat_normal_view() -> NodeRef {
let value = current_context(|cx| cx.setup_clearcoat_normal.clone());
let key = value.as_ref().map(|v| v.key());
if let Some(node) = CLEARCOAT_NORMAL_VIEW.with(|m| m.borrow().get(&key).cloned()) {
return node;
}
let node = to_var(
Some("clearcoatNormalView"),
value.unwrap_or_else(|| in_sub_build("NORMAL", normal_view)),
);
CLEARCOAT_NORMAL_VIEW.with(|m| m.borrow_mut().insert(key, node.clone()));
node
}
pub fn bent_normal_view() -> NodeRef {
let bent = cross(
cross(anisotropy_b(), position_view_direction()),
anisotropy_b(),
)
.normalize();
let base = to_var(None, anisotropy().mul(roughness().one_minus()).one_minus());
let squared = to_var(None, base.clone().mul(base));
mix(bent, normal_view(), squared.clone().mul(squared)).normalize()
}
fn texture_node(source: TextureSource, uv: NodeRef, mode: SampleMode, ty: Type) -> NodeRef {
NodeRef::new(Node::Texture {
texture: Rc::new(source),
uv,
mode,
ty,
})
}
fn transformed_uv(uv: NodeRef, key: (u8, usize), matrix: Matrix3) -> NodeRef {
thread_local! {
static CACHE: RefCell<HashMap<(u8, usize), NodeRef>> = RefCell::new(HashMap::new());
}
let matrix_uniform = CACHE.with(|c| {
c.borrow_mut()
.entry(key)
.or_insert_with(|| {
uniform(
UniformSource::Value(
matrix
.to_padded_f32_array()
.iter()
.map(|&v| v as f64)
.collect(),
),
Type::Mat3,
UniformGroup::Object,
None,
)
})
.clone()
});
matrix_uniform.mul(vec3_join(vec![uv, float(1.0)])).xy()
}
fn default_uv(map: &Texture) -> NodeRef {
match map.channel() {
0 => uv(),
_ => uv1(),
}
}
pub fn texture(map: &Texture) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
transformed_uv(default_uv(map), (0, map.id()), map.matrix()),
sample_mode_for(map),
texture_type_for(map),
)
}
pub fn texture_with_uv(map: &Texture, coord: NodeRef) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
transformed_uv(coord, (0, map.id()), map.matrix()),
sample_mode_for(map),
texture_type_for(map),
)
}
#[derive(Clone, Debug)]
pub struct Texture3DNode {
source: Rc<TextureSource>,
level: NodeRef,
}
pub fn texture_3d(texture: &crate::textures::Data3DTexture, level: NodeRef) -> Texture3DNode {
Texture3DNode {
source: Rc::new(TextureSource::Texture3D(texture.clone())),
level,
}
}
impl Texture3DNode {
pub fn sample(&self, uv: impl Into<NodeRef>) -> NodeRef {
NodeRef::new(Node::Texture {
texture: self.source.clone(),
uv: uv.into(),
mode: SampleMode::Level(self.level.clone()),
ty: Type::Vec4,
})
}
pub fn sample_r(&self, uv: impl Into<NodeRef>) -> NodeRef {
NodeRef::new(Node::Texture {
texture: self.source.clone(),
uv: uv.into(),
mode: SampleMode::Level(self.level.clone()),
ty: Type::F32,
})
}
pub fn normal(&self, uv: NodeRef) -> NodeRef {
let epsilon = 0.0001;
let ret = to_var(None, vec3(0.0, 0.0, 0.0));
let step = 0.01;
let x = self
.sample_r(uv.add(vec3(-step, 0.0, 0.0)))
.sub(self.sample_r(uv.add(vec3(step, 0.0, 0.0))));
let y = self
.sample_r(uv.add(vec3(0.0, -step, 0.0)))
.sub(self.sample_r(uv.add(vec3(0.0, step, 0.0))));
let z = self
.sample_r(uv.add(vec3(0.0, 0.0, -step)))
.sub(self.sample_r(uv.add(vec3(0.0, 0.0, step))));
let arms = [
(uv.x().less_than(epsilon), vec3(1.0, 0.0, 0.0)),
(uv.y().less_than(epsilon), vec3(0.0, 1.0, 0.0)),
(uv.z().less_than(epsilon), vec3(0.0, 0.0, 1.0)),
(uv.x().greater_than(1.0 - epsilon), vec3(-1.0, 0.0, 0.0)),
(uv.y().greater_than(1.0 - epsilon), vec3(0.0, -1.0, 0.0)),
(uv.z().greater_than(1.0 - epsilon), vec3(0.0, 0.0, -1.0)),
];
let mut chain = vec![ret.assign(vec3_join(vec![x, y, z]))];
for (cond, axis) in arms.into_iter().rev() {
chain = vec![if_else(cond, vec![ret.assign(axis)], chain)];
}
let mut statements = vec![ret.clone()];
statements.extend(chain);
block(statements, ret.normalize())
}
}
#[derive(Clone, Debug)]
pub struct StorageTextureNode {
source: Rc<TextureSource>,
}
pub fn storage_texture(texture: &Texture) -> StorageTextureNode {
assert!(
texture.is_storage(),
"three-rs: storageTexture() needs a Texture::storage()"
);
StorageTextureNode {
source: Rc::new(TextureSource::Storage(
texture.clone(),
crate::nodes::node::StorageAccess::WriteOnly,
)),
}
}
pub fn storage_texture_3d(texture: &crate::textures::Data3DTexture) -> StorageTextureNode {
assert!(
texture.is_storage(),
"three-rs: storageTexture() needs a Data3DTexture::storage()"
);
StorageTextureNode {
source: Rc::new(TextureSource::Storage3D(
texture.clone(),
crate::nodes::node::StorageAccess::WriteOnly,
)),
}
}
impl StorageTextureNode {
pub fn set_access(self, access: crate::nodes::node::StorageAccess) -> Self {
let source = match &*self.source {
TextureSource::Storage(t, _) => TextureSource::Storage(t.clone(), access),
TextureSource::Storage3D(t, _) => TextureSource::Storage3D(t.clone(), access),
_ => unreachable!("three-rs: a StorageTextureNode holds a storage source"),
};
Self {
source: Rc::new(source),
}
}
pub fn load(&self, coord: impl Into<NodeRef>) -> NodeRef {
NodeRef::new(Node::Texture {
texture: self.source.clone(),
uv: coord.into(),
mode: SampleMode::StorageLoad,
ty: Type::Vec4,
})
}
}
pub fn texture_store(
texture: &StorageTextureNode,
coord: impl Into<NodeRef>,
value: impl Into<NodeRef>,
) -> NodeRef {
NodeRef::new(Node::TextureStore {
texture: texture.source.clone(),
coord: coord.into(),
value: value.into(),
})
}
fn texture_type_for(map: &Texture) -> Type {
match map.format().components() {
2 => Type::Vec2,
_ => Type::Vec4,
}
}
fn sample_mode_for(map: &Texture) -> SampleMode {
if map.is_unfilterable() {
SampleMode::Load
} else {
SampleMode::Sample
}
}
pub fn triplanar_texture(
map_x: &Texture,
map_y: Option<&Texture>,
map_z: Option<&Texture>,
scale: NodeRef,
) -> NodeRef {
let map_y = map_y.unwrap_or(map_x);
let map_z = map_z.unwrap_or(map_x);
let bf = normal_local().abs().normalize();
let bf = bf.clone().div(bf.dot(vec3(1.0, 1.0, 1.0)));
let tx = position_local().yz().mul(scale.clone());
let ty = position_local().zx().mul(scale.clone());
let tz = position_local().xy().mul(scale);
let cx = texture_uv(map_x, tx).mul(bf.clone().x());
let cy = texture_uv(map_y, ty).mul(bf.clone().y());
let cz = texture_uv(map_z, tz).mul(bf.z());
cx.add(cy).add(cz)
}
pub fn bump_map(map: &Texture, scale: NodeRef) -> NodeRef {
bump_map_with(|texture| texture(map).x(), scale)
}
pub fn bump_map_with(
height: impl Fn(&dyn Fn(&Texture) -> NodeRef) -> NodeRef,
scale: NodeRef,
) -> NodeRef {
in_sub_build("NORMAL", || {
let tap = |coord: NodeRef| {
height(&|map: &Texture| {
texture_uv(
map,
transformed_uv(coord.clone(), (0, map.id()), map.matrix()),
)
})
};
let hll = tap(uv());
let dhdxy = join(
Type::Vec2,
vec![
tap(uv().add(dpdx(uv()))).sub(hll.clone()),
tap(uv().add(dpdy(uv()))).sub(hll),
],
)
.mul(scale);
let surf_norm = normal_view();
let v_sigma_x = dpdx(position_view()).normalize();
let v_sigma_y = dpdy(position_view()).normalize();
let r1 = cross(v_sigma_y, surf_norm.clone());
let r2 = cross(surf_norm.clone(), v_sigma_x.clone());
let f_det = v_sigma_x.dot(r1.clone()).mul(face_direction());
let v_grad = sign(f_det.clone()).mul(dhdxy.clone().x().mul(r1).add(dhdxy.y().mul(r2)));
abs(f_det).mul(surf_norm).sub(v_grad).normalize()
})
}
pub fn texture_grad(map: &Texture, coord: NodeRef, grad_x: NodeRef, grad_y: NodeRef) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
coord,
SampleMode::Grad(grad_x, grad_y),
Type::Vec4,
)
}
pub fn texture_gather(
map: &Texture,
coord: NodeRef,
component: NodeRef,
offset: Option<NodeRef>,
) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
coord,
SampleMode::Gather { component, offset },
Type::Vec4,
)
}
pub fn depth_texture_gather_compare(
map: &DepthTexture,
coord: NodeRef,
compare: NodeRef,
offset: Option<NodeRef>,
) -> NodeRef {
texture_node(
TextureSource::ShadowMap(map.clone()),
coord,
SampleMode::GatherCompare { compare, offset },
Type::Vec4,
)
}
pub fn texture_level(map: &Texture, coord: NodeRef, level: NodeRef) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
coord,
SampleMode::Level(level),
Type::Vec4,
)
}
pub fn texture_bias(map: &Texture, coord: NodeRef, bias: NodeRef) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
coord,
SampleMode::Bias(bias),
Type::Vec4,
)
}
pub fn texture_array(map: &Texture, coord: NodeRef, layer: NodeRef) -> NodeRef {
assert!(
map.is_array(),
"three-rs: texture_array needs a texture with array layers"
);
texture_node(
TextureSource::Texture2D(map.clone()),
coord,
SampleMode::SampleLayer(layer),
Type::Vec4,
)
}
pub fn equirect_uv(direction: NodeRef) -> NodeRef {
let u = direction
.z()
.atan2(direction.x())
.mul(float(1.0 / (std::f64::consts::PI * 2.0)))
.add(float(0.5));
let v = direction
.y()
.clamp(float(-1.0), float(1.0))
.asin()
.mul(float(1.0 / std::f64::consts::PI))
.add(float(0.5));
vec2_join(vec![u, v])
}
pub fn texture_sample(map: &Texture, coord: NodeRef) -> NodeRef {
let matrix = uniform(
UniformSource::Value(
map.matrix()
.to_padded_f32_array()
.iter()
.map(|&v| v as f64)
.collect(),
),
Type::Mat3,
UniformGroup::Object,
None,
);
texture_uv(map, matrix.mul(vec3_join(vec![coord, float(1.0)])).xy())
}
pub fn texture_uv(map: &Texture, coord: NodeRef) -> NodeRef {
texture_node(
TextureSource::Texture2D(map.clone()),
coord,
sample_mode_for(map),
texture_type_for(map),
)
}
pub fn depth_texture(map: &DepthTexture) -> NodeRef {
texture_node(
TextureSource::Depth(map.clone()),
transformed_uv(uv(), (1, map.id()), Matrix3::identity()),
SampleMode::Load,
Type::F32,
)
}
pub fn depth_texture_sample(map: &DepthTexture, coord: NodeRef) -> NodeRef {
let matrix = uniform(
UniformSource::Value(
Matrix3::identity()
.to_padded_f32_array()
.iter()
.map(|&v| v as f64)
.collect(),
),
Type::Mat3,
UniformGroup::Object,
None,
);
texture_node(
TextureSource::Depth(map.clone()),
matrix.mul(vec3_join(vec![coord, float(1.0)])).xy(),
SampleMode::Load,
Type::F32,
)
}
pub fn pass_depth_texture(map: &DepthTexture) -> NodeRef {
pass_depth_texture_uv(map, uv())
}
pub fn pass_depth_texture_uv(map: &DepthTexture, coord: NodeRef) -> NodeRef {
texture_node(
TextureSource::Depth(map.clone()),
coord,
SampleMode::Load,
Type::F32,
)
}
pub fn cube_texture(map: &CubeTexture, dir: NodeRef) -> NodeRef {
let dir = vec3_join(vec![dir.x().negate(), dir.yz()]);
texture_node(
TextureSource::Cube(map.clone()),
dir,
SampleMode::Sample,
Type::Vec4,
)
}
pub fn cube_depth_texture_compare(map: &CubeDepthTexture, dir: NodeRef, dp: NodeRef) -> NodeRef {
let dir = vec3_join(vec![dir.x(), dir.y().negate(), dir.z()]);
texture_node(
TextureSource::CubeDepth(map.clone()),
dir,
SampleMode::Compare(dp),
Type::F32,
)
}
pub fn cube_texture_level(map: &CubeTexture, dir: NodeRef, level: NodeRef) -> NodeRef {
let dir = vec3_join(vec![dir.x().negate(), dir.yz()]);
texture_node(
TextureSource::Cube(map.clone()),
dir,
SampleMode::Level(level),
Type::Vec4,
)
}
#[derive(Clone)]
pub struct StorageArray(Rc<BufferNode>);
pub fn instanced_array(count: usize, element_ty: Type) -> StorageArray {
StorageArray(Rc::new(BufferNode {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::Storage,
element_ty,
count,
}))
}
impl StorageArray {
pub fn element(&self, index: impl Into<NodeRef>) -> NodeRef {
NodeRef::new(Node::BufferElement {
buffer: self.0.clone(),
index: index.into(),
})
}
pub fn id(&self) -> crate::nodes::node::BufferId {
self.0.id
}
pub fn count(&self) -> usize {
self.0.count
}
pub fn element_ty(&self) -> Type {
self.0.element_ty
}
}
impl StorageArray {
pub fn to_atomic(&self) -> StorageArray {
assert!(
matches!(self.0.element_ty, Type::U32 | Type::I32),
"three-rs: an atomic storage array holds u32 or i32 (WGSL atomic<T>)"
);
StorageArray(Rc::new(BufferNode {
id: self.0.id,
source: BufferSource::AtomicStorage,
element_ty: self.0.element_ty,
count: self.0.count,
}))
}
}
fn storage_item_size(element_ty: Type) -> usize {
match element_ty.components() {
3 => 4,
n => n,
}
}
pub fn storage_data(words: &[u32], element_ty: Type) -> StorageArray {
let item_size = element_ty.components();
let stride = storage_item_size(element_ty);
let count = words.len() / item_size;
let mut init = vec![0u32; count * stride];
for (i, element) in words.chunks_exact(item_size).enumerate() {
init[i * stride..i * stride + item_size].copy_from_slice(element);
}
StorageArray(Rc::new(BufferNode {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::StorageData {
init: Rc::new(init),
read_only: false,
},
element_ty,
count,
}))
}
pub fn storage_f32(array: &[f32], element_ty: Type) -> StorageArray {
let words: Vec<u32> = array.iter().map(|v| v.to_bits()).collect();
storage_data(&words, element_ty)
}
impl StorageArray {
pub fn to_read_only(&self) -> StorageArray {
let source = match &self.0.source {
BufferSource::StorageData { init, .. } => BufferSource::StorageData {
init: init.clone(),
read_only: true,
},
_ => panic!("three-rs: to_read_only() is ported for storage over a CPU array"),
};
StorageArray(Rc::new(BufferNode {
id: self.0.id,
source,
element_ty: self.0.element_ty,
count: self.0.count,
}))
}
pub fn to_attribute(&self) -> NodeRef {
let buffer = Rc::new(InstanceBuffer {
id: self.0.id,
source: self.0.source.clone(),
count: self.0.count,
item_size: storage_item_size(self.0.element_ty),
});
instanced_attribute(&buffer, 0, self.0.element_ty)
}
}
pub fn compute_node(flow: crate::nodes::ComputeFlow, output: NodeRef) -> NodeRef {
NodeRef::new(Node::Compute {
flow: Rc::new(flow),
output,
})
}
pub fn object_world_matrix(object: &crate::core::Node) -> NodeRef {
let object = object.downgrade();
uniform(
UniformSource::Live(crate::nodes::node::LiveValue::new(move || {
let object = object
.upgrade()
.expect("three-rs: objectWorldMatrix( object ) outlived its object");
let world = object.borrow().matrix_world;
world.elements.to_vec()
})),
Type::Mat4,
UniformGroup::Object,
None,
)
}
pub fn shape_circle() -> NodeRef {
thread_local! {
static DEF: Rc<FnDef> = inline_fn(1, Type::F32, |args| {
let coord = args[0].clone();
let len2 = length_sq(coord.mul(2.0).sub(1.0));
let smooth = crate::nodes::builder::current_context(|cx| cx.alpha_to_coverage_samples);
if smooth {
let dlen = to_var(None, fwidth(len2.clone()));
smoothstep(dlen.one_minus(), dlen.add(1.0), len2).one_minus()
} else {
len2.greater_than(1.0).select(float(0.0), float(1.0))
}
});
}
DEF.with(|def| call(def, vec![uv()]))
}
pub use super::node::StructLayout;
pub use super::node::StructMember;
pub fn struct_type(name: &'static str, members: Vec<StructMember>) -> Rc<StructLayout> {
Rc::new(StructLayout { name, members })
}
impl StructMember {
pub fn new(name: &'static str, ty: Type) -> Self {
Self {
name,
ty,
atomic: false,
}
}
pub fn atomic(name: &'static str, ty: Type) -> Self {
Self {
name,
ty,
atomic: true,
}
}
}
#[derive(Clone)]
pub struct StorageStruct(Rc<BufferNode>);
pub fn storage_struct(
attribute: &crate::core::IndirectStorageBufferAttribute,
layout: Rc<StructLayout>,
) -> StorageStruct {
assert!(
layout
.members
.iter()
.all(|m| matches!(m.ty, Type::U32 | Type::I32 | Type::F32)),
"three-rs: storage_struct() lays out 4-byte scalar members only"
);
assert_eq!(
layout.members.len(),
attribute.array().len(),
"three-rs: struct {} does not cover the indirect attribute's words",
layout.name
);
StorageStruct(Rc::new(BufferNode {
id: attribute.id(),
source: BufferSource::Struct {
layout,
init: attribute.array(),
},
element_ty: Type::U32,
count: attribute.count(),
}))
}
impl StorageStruct {
pub fn get(&self, member: &str) -> NodeRef {
let BufferSource::Struct { layout, .. } = &self.0.source else {
unreachable!("three-rs: a StorageStruct is always a struct buffer")
};
NodeRef::new(Node::StructMember {
buffer: self.0.clone(),
member: layout.member(member),
})
}
}
fn atomic_function(method: &'static str, pointer: NodeRef, value: Option<NodeRef>) -> NodeRef {
NodeRef::new(Node::Atomic {
method,
pointer,
value,
})
}
macro_rules! atomic_fns {
($($(#[$m:meta])* $name:ident => $method:literal;)*) => {
$(
$(#[$m])*
pub fn $name(pointer: impl Into<NodeRef>, value: impl Into<NodeRef>) -> NodeRef {
atomic_function($method, pointer.into(), Some(value.into()))
}
)*
};
}
atomic_fns! {
atomic_store => "atomicStore";
atomic_add => "atomicAdd";
atomic_sub => "atomicSub";
atomic_max => "atomicMax";
atomic_min => "atomicMin";
atomic_and => "atomicAnd";
atomic_or => "atomicOr";
atomic_xor => "atomicXor";
}
pub fn atomic_load(pointer: impl Into<NodeRef>) -> NodeRef {
atomic_function("atomicLoad", pointer.into(), None)
}
#[derive(Clone)]
pub struct WorkgroupArray(Rc<super::node::WorkgroupArrayDef>);
pub fn workgroup_array(element_ty: Type, count: usize) -> WorkgroupArray {
WorkgroupArray(Rc::new(super::node::WorkgroupArrayDef {
element_ty,
count,
atomic: false,
}))
}
impl WorkgroupArray {
pub fn element(&self, index: impl Into<NodeRef>) -> NodeRef {
NodeRef::new(Node::Element {
node: NodeRef::new(Node::Workgroup(self.0.clone())),
index: index.into(),
ty: self.0.element_ty,
})
}
pub fn to_atomic(&self) -> WorkgroupArray {
WorkgroupArray(Rc::new(super::node::WorkgroupArrayDef {
atomic: true,
..*self.0
}))
}
}
pub fn workgroup_barrier() -> NodeRef {
NodeRef::new(Node::Barrier { scope: "workgroup" })
}
pub fn storage_barrier() -> NodeRef {
NodeRef::new(Node::Barrier { scope: "storage" })
}
#[derive(Clone)]
pub struct UniformArray(Rc<BufferNode>);
pub fn uniform_array_vec3(values: &[[f64; 3]]) -> UniformArray {
let mut padded = Vec::with_capacity(values.len() * 4);
for v in values {
padded.extend([v[0] as f32, v[1] as f32, v[2] as f32, 0.0]);
}
UniformArray(Rc::new(BufferNode {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::UniformArray(Rc::new(padded)),
element_ty: Type::Vec4,
count: values.len(),
}))
}
pub fn uniform_array_f32(values: &[f64]) -> UniformArray {
let mut padded = Vec::with_capacity(values.len() * 4);
for &v in values {
padded.extend([v as f32, 0.0, 0.0, 0.0]);
}
UniformArray(Rc::new(BufferNode {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::UniformArray(Rc::new(padded)),
element_ty: Type::Vec4,
count: values.len(),
}))
}
impl UniformArray {
pub fn element(&self, index: usize) -> NodeRef {
NodeRef::new(Node::BufferElement {
buffer: self.0.clone(),
index: constant(Type::U32, vec![index as f64]),
})
.xyz()
}
pub fn element_x(&self, index: NodeRef) -> NodeRef {
NodeRef::new(Node::BufferElement {
buffer: self.0.clone(),
index,
})
.x()
}
}
fn buffer_element(source: BufferSource, element_ty: Type, count: usize, index: NodeRef) -> NodeRef {
NodeRef::new(Node::BufferElement {
buffer: Rc::new(BufferNode {
id: crate::nodes::node::BufferId::next(),
source,
element_ty,
count,
}),
index,
})
}
fn instanced_attribute(buffer: &Rc<InstanceBuffer>, offset: usize, ty: Type) -> NodeRef {
NodeRef::new(Node::InstancedAttribute {
buffer: buffer.clone(),
offset,
ty,
})
}
pub(crate) fn instance_matrix(count: usize) -> NodeRef {
let matrix_count = count.max(1);
let uniform_buffer_size = matrix_count * 16 * 4;
if uniform_buffer_size <= crate::nodes::builder::uniform_buffer_limit() {
return buffer_element(
BufferSource::InstanceMatrix,
Type::Mat4,
count,
instance_index(),
);
}
let interleaved = Rc::new(InstanceBuffer {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::InstanceMatrix,
count: matrix_count,
item_size: 16,
});
join(
Type::Mat4,
(0..4)
.map(|i| instanced_attribute(&interleaved, i * 4, Type::Vec4))
.collect(),
)
}
pub fn instance_color(count: usize) -> NodeRef {
let buffer = Rc::new(InstanceBuffer {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::InstanceColor,
count: count.max(1),
item_size: 3,
});
to_varying(
Some("vInstanceColor"),
instanced_attribute(&buffer, 0, Type::Vec3),
)
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RangeValue {
Scalar(f64),
Color(Color),
Vec3([f64; 3]),
}
impl From<f64> for RangeValue {
fn from(v: f64) -> Self {
RangeValue::Scalar(v)
}
}
impl From<Color> for RangeValue {
fn from(v: Color) -> Self {
RangeValue::Color(v)
}
}
impl From<crate::math::Vector3> for RangeValue {
fn from(v: crate::math::Vector3) -> Self {
RangeValue::Vec3([v.x, v.y, v.z])
}
}
impl RangeValue {
fn vector4(self) -> [f64; 4] {
match self {
RangeValue::Scalar(v) => [v, v, v, v],
RangeValue::Color(c) => [c.r, c.g, c.b, 1.0],
RangeValue::Vec3([x, y, z]) => [x, y, z, 0.0],
}
}
fn ty(self) -> Type {
match self {
RangeValue::Scalar(_) => Type::F32,
RangeValue::Color(_) | RangeValue::Vec3(_) => Type::Vec3,
}
}
}
pub fn range(min: [f64; 4], max: [f64; 4], count: usize, index: NodeRef) -> NodeRef {
buffer_element(BufferSource::Range { min, max }, Type::Vec4, count, index)
}
pub(crate) fn instanced_range(
min: impl Into<RangeValue>,
max: impl Into<RangeValue>,
count: usize,
) -> NodeRef {
let (min, max) = (min.into(), max.into());
let ty = min.ty();
let uniform_buffer_size = count * 4 * 4;
let vec4 = if uniform_buffer_size <= crate::nodes::builder::uniform_buffer_limit() {
range(
min.vector4(),
max.vector4(),
count,
to_varying(None, instance_index()),
)
} else {
let buffer = Rc::new(InstanceBuffer {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::Range {
min: min.vector4(),
max: max.vector4(),
},
count,
item_size: 4,
});
instanced_attribute(&buffer, 0, Type::Vec4)
};
match ty {
Type::F32 => vec4.x(),
Type::Vec2 => vec4.xy(),
Type::Vec3 => vec4.xyz(),
_ => vec4,
}
}
pub fn loop_index() -> NodeRef {
NodeRef::new(Node::Param {
name: "i",
ty: Type::I32,
})
}
pub fn loop_statement(count: usize, index: NodeRef, body: Vec<NodeRef>) -> NodeRef {
let count = int(count as i64);
NodeRef::new(Node::Loop {
start: None,
index,
count,
condition: "<",
update: None,
body,
})
}
pub(crate) fn if_statement(cond: NodeRef, body: Vec<NodeRef>) -> NodeRef {
NodeRef::new(Node::If {
cond,
body,
else_body: Vec::new(),
})
}
pub fn ivec2(x: impl Into<NodeRef>, y: impl Into<NodeRef>) -> NodeRef {
join(Type::IVec2, vec![x.into(), y.into()])
}
pub fn texture_size(source: TextureSource, level: NodeRef) -> NodeRef {
NodeRef::new(Node::TextureSize {
texture: Rc::new(source),
level,
})
}
pub fn texture_load_texel(map: &DataTexture, coord: NodeRef, ty: Type) -> NodeRef {
texture_node(
TextureSource::Data(map.clone()),
coord,
SampleMode::LoadTexel,
ty,
)
}
pub fn varying_property(name: &'static str, ty: Type, flat: bool) -> NodeRef {
NodeRef::new(Node::VaryingProperty { name, ty, flat })
}
pub fn texture_load_array(map: &DataArrayTexture, coord: NodeRef, layer: NodeRef) -> NodeRef {
texture_node(
TextureSource::DataArray(map.clone()),
coord,
SampleMode::LoadLayer(layer),
Type::Vec4,
)
}
pub(crate) fn morph_influences(count: usize, index: NodeRef) -> NodeRef {
buffer_element(BufferSource::MorphInfluences, Type::Vec4, count, index)
}
pub(crate) fn morph_base() -> NodeRef {
uniform(
UniformSource::MorphBase,
Type::F32,
UniformGroup::Object,
None,
)
}
pub fn instanced_data_attribute(
data: &Rc<Vec<f32>>,
item_size: usize,
offset: usize,
ty: Type,
) -> NodeRef {
instanced_buffer_attribute(&instanced_data_buffer(data, item_size), offset, ty)
}
pub fn instanced_data_buffer(data: &Rc<Vec<f32>>, item_size: usize) -> Rc<InstanceBuffer> {
let count = data.len().checked_div(item_size).unwrap_or(0);
Rc::new(InstanceBuffer {
id: crate::nodes::node::BufferId::next(),
source: BufferSource::Attribute(data.clone()),
count,
item_size,
})
}
pub fn instanced_buffer_attribute(buffer: &Rc<InstanceBuffer>, offset: usize, ty: Type) -> NodeRef {
assert!(
offset + ty.components() <= buffer.item_size,
"three-rs: instanced attribute reads past the instance stride"
);
instanced_attribute(buffer, offset, ty)
}
pub fn inline_fn(
params: usize,
ret: Type,
body: impl Fn(&[NodeRef]) -> NodeRef + 'static,
) -> Rc<FnDef> {
Rc::new(FnDef {
name: None,
params: vec![("", Type::Void); params],
ret,
layout: false,
body: Box::new(body),
})
}
pub use crate::nodes::code::wgsl_fn;
pub fn code(def: &Rc<crate::nodes::code::CodeDef>) -> NodeRef {
NodeRef::new(Node::Code(def.clone()))
}
pub fn call_wgsl(def: &Rc<crate::nodes::code::CodeDef>, args: Vec<(&str, NodeRef)>) -> NodeRef {
let ordered = def
.params
.iter()
.map(|(name, _)| {
args.iter()
.find(|(given, _)| given == name)
.map(|(_, node)| node.clone())
.unwrap_or_else(|| {
panic!(
"three-rs: wgslFn `{}` has no argument for `{name}`",
def.name
)
})
})
.collect();
for (given, _) in &args {
assert!(
def.params.iter().any(|(name, _)| name == given),
"three-rs: wgslFn `{}` has no parameter `{given}`",
def.name
);
}
NodeRef::new(Node::CodeCall {
def: def.clone(),
args: ordered,
})
}
pub fn shader_fn(
name: Option<&'static str>,
params: Vec<(&'static str, Type)>,
ret: Type,
body: impl Fn(&[NodeRef]) -> NodeRef + 'static,
) -> Rc<FnDef> {
Rc::new(FnDef {
name,
params,
ret,
layout: true,
body: Box::new(body),
})
}
pub(crate) fn if_node(
pre: Vec<NodeRef>,
result: NodeRef,
cond: NodeRef,
body: Vec<NodeRef>,
) -> NodeRef {
NodeRef::new(Node::IfVar {
pre,
result,
cond,
body,
})
}
pub fn call(def: &Rc<FnDef>, args: Vec<NodeRef>) -> NodeRef {
NodeRef::new(Node::Call {
def: def.clone(),
args,
})
}
pub fn luminance(color: NodeRef) -> NodeRef {
dot(color, vec3(0.2126, 0.7152, 0.0722))
}
pub fn saturation(color: NodeRef, adjustment: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
inline_fn(2, Type::Vec3, |args| {
let (color, adjustment) = (args[0].clone(), args[1].clone());
adjustment
.mix(luminance(color.rgb()), color.rgb())
.max(float(0.0))
})
})
});
call(&def, vec![color, adjustment])
}
pub fn hue(color: NodeRef, adjustment: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
inline_fn(2, Type::Vec3, |args| {
let (color, adjustment) = (args[0].clone(), args[1].clone());
let k = vec3(0.57735, 0.57735, 0.57735);
let cos_angle = adjustment.cos();
color
.rgb()
.mul(cos_angle.clone())
.add(
k.cross(color.rgb())
.mul(adjustment.sin())
.add(k.mul(dot(k.clone(), color.rgb()).mul(cos_angle.one_minus()))),
)
.max(float(0.0))
})
})
});
call(&def, vec![color, adjustment])
}
pub fn osc_sine(t: NodeRef) -> NodeRef {
t.add(float(0.75))
.mul(float(std::f64::consts::TAU))
.sin()
.mul(float(0.5))
.add(float(0.5))
}
pub fn srgb_transfer_oetf(color: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("sRGBTransferOETF"),
vec![("color", Type::Vec3)],
Type::Vec3,
|args| {
let color = args[0].clone();
mix(
color
.pow(float(0.41666))
.mul(float(1.055))
.sub(float(0.055)),
color.mul(float(12.92)),
color.less_than_equal(float(0.0031308)).to(Type::Vec3),
)
},
)
})
});
call(&def, vec![color])
}
pub fn linear_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("linearToneMapping"),
vec![("color", Type::Vec3), ("exposure", Type::F32)],
Type::Vec3,
|args| {
args[0]
.clone()
.mul(args[1].clone())
.clamp(float(0.0), float(1.0))
},
)
})
});
call(&def, vec![color, exposure])
}
pub fn srgb_transfer_eotf(color: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("sRGBTransferEOTF"),
vec![("color", Type::Vec3)],
Type::Vec3,
|args| {
let color = args[0].clone();
mix(
color
.mul(float(0.9478672986))
.add(float(0.0521327014))
.pow(float(2.4)),
color.mul(float(0.0773993808)),
color.less_than_equal(float(0.04045)).to(Type::Vec3),
)
},
)
})
});
call(&def, vec![color])
}
pub fn srgb_to_working(color: NodeRef) -> NodeRef {
vec4_join(vec![srgb_transfer_eotf(color.rgb()), color.a()])
}
pub fn pack_normal_to_rgb(node: NodeRef) -> NodeRef {
node.mul(float(0.5)).add(float(0.5))
}
pub fn reinhard_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("reinhardToneMapping"),
vec![("color", Type::Vec3), ("exposure", Type::F32)],
Type::Vec3,
|args| {
let color = args[0].clone().mul(args[1].clone());
color
.clone()
.div(color.add(float(1.0)))
.clamp(float(0.0), float(1.0))
},
)
})
});
call(&def, vec![color, exposure])
}
pub fn premultiply_alpha(color: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(None, vec![("color", Type::Vec4)], Type::Vec4, |args| {
let color = args[0].clone();
vec4_join(vec![color.rgb().mul(color.a()), color.a()])
})
})
});
call(&def, vec![color])
}
pub fn unpremultiply_alpha(color: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(None, vec![("color", Type::Vec4)], Type::Vec4, |args| {
let color = args[0].clone();
color.a().equal(float(0.0)).select(
vec4(0.0, 0.0, 0.0, 0.0),
vec4_join(vec![color.rgb().div(color.a().to(Type::Vec3)), color.a()]),
)
})
})
});
call(&def, vec![color])
}
pub fn block(statements: Vec<NodeRef>, result: NodeRef) -> NodeRef {
NodeRef::new(Node::Block { statements, result })
}
pub fn loop_n(
name: &'static str,
count: NodeRef,
body: impl FnOnce(&NodeRef) -> Vec<NodeRef>,
) -> NodeRef {
let index = NodeRef::new(Node::Param {
name,
ty: Type::I32,
});
let body = body(&index);
NodeRef::new(Node::Loop {
start: None,
count,
index,
condition: "<",
update: None,
body,
})
}
pub fn loop_range(
name: &'static str,
start: NodeRef,
end: NodeRef,
body: impl FnOnce(&NodeRef) -> Vec<NodeRef>,
) -> NodeRef {
let index = NodeRef::new(Node::Param {
name,
ty: Type::I32,
});
let body = body(&index);
NodeRef::new(Node::Loop {
start: Some(start),
count: end,
condition: "<",
update: None,
index,
body,
})
}
pub fn loop_options(
name: &'static str,
ty: Type,
start: NodeRef,
end: NodeRef,
condition: &'static str,
body: impl FnOnce(&NodeRef) -> Vec<NodeRef>,
) -> NodeRef {
let index = NodeRef::new(Node::Param { name, ty });
let body = body(&index);
NodeRef::new(Node::Loop {
start: Some(start),
count: end,
index,
condition,
update: None,
body,
})
}
pub fn loop_float(
name: &'static str,
start: NodeRef,
end: NodeRef,
update: NodeRef,
body: impl FnOnce(&NodeRef) -> Vec<NodeRef>,
) -> NodeRef {
let index = NodeRef::new(Node::Param {
name,
ty: Type::F32,
});
let body = body(&index);
NodeRef::new(Node::Loop {
start: Some(start),
count: end,
index,
condition: "<",
update: Some(update),
body,
})
}
pub fn break_loop() -> NodeRef {
NodeRef::new(Node::Break)
}
pub fn if_then(cond: NodeRef, body: Vec<NodeRef>) -> NodeRef {
NodeRef::new(Node::If {
cond,
body,
else_body: Vec::new(),
})
}
pub fn if_else(cond: NodeRef, body: Vec<NodeRef>, else_body: Vec<NodeRef>) -> NodeRef {
NodeRef::new(Node::If {
cond,
body,
else_body,
})
}
pub fn if_else_if(
cond: NodeRef,
body: Vec<NodeRef>,
other: NodeRef,
other_body: Vec<NodeRef>,
) -> NodeRef {
if_else(cond, body, vec![if_then(other, other_body)])
}
pub fn return_statement(value: NodeRef) -> NodeRef {
NodeRef::new(Node::Return { value })
}
pub fn discard() -> NodeRef {
NodeRef::new(Node::Discard)
}
pub fn discard_if(cond: NodeRef) -> NodeRef {
if_then(cond.not(), vec![discard()])
}
pub fn wgsl_select(f: NodeRef, t: NodeRef, cond: NodeRef) -> NodeRef {
let ty = t.ty();
math("select", vec![f, t, cond], ty)
}
pub fn step(edge: impl Into<NodeRef>, x: impl Into<NodeRef>) -> NodeRef {
let x = x.into();
let ty = x.ty();
math("step", vec![edge.into(), x], ty)
}
pub fn uint(v: u32) -> NodeRef {
constant(Type::U32, vec![v as f64])
}
prop!(
shadow_position_world,
"shadowPositionWorld",
Type::Vec3
);
pub fn transform_direction(matrix: NodeRef, dir: NodeRef) -> NodeRef {
matrix
.mul(vec4_join(vec![dir, float(0.0)]))
.xyz()
.normalize()
}
pub fn light_target_direction(index: usize) -> NodeRef {
transform_direction(
camera_view_matrix(),
light_world_position(index).sub(light_target_position(index)),
)
}
pub fn shadow_map_compare(map: &DepthTexture, coord: NodeRef, z: NodeRef) -> NodeRef {
texture_node(
TextureSource::ShadowMap(map.clone()),
coord,
SampleMode::Compare(z),
Type::F32,
)
}
pub fn interleaved_gradient_noise(position: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("interleavedGradientNoise"),
vec![("position", Type::Vec2)],
Type::F32,
|args| {
float(52.9829189)
.mul(dot(args[0].clone(), vec2(0.06711056, 0.00583715)).fract())
.fract()
},
)
})
});
call(&def, vec![position])
}
pub fn vogel_disk_sample(sample_index: NodeRef, samples_count: NodeRef, phi: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("vogelDiskSample"),
vec![
("sampleIndex", Type::I32),
("samplesCount", Type::I32),
("phi", Type::F32),
],
Type::Vec2,
|args| {
let (index, count, phi) = (args[0].clone(), args[1].clone(), args[2].clone());
let theta = index
.clone()
.to(Type::F32)
.mul(float(2.399963229728653))
.add(phi);
let r = index
.to(Type::F32)
.add(float(0.5))
.div(count.to(Type::F32))
.sqrt();
vec2_join(vec![theta.cos(), theta.sin()]).mul(r)
},
)
})
});
call(&def, vec![sample_index, samples_count, phi])
}
pub fn aces_filmic_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("acesFilmicToneMapping"),
vec![("color", Type::Vec3), ("exposure", Type::F32)],
Type::Vec3,
|args| {
let (color, exposure) = (args[0].clone(), args[1].clone());
let input = constant(
Type::Mat3,
vec![
0.59719, 0.076, 0.0284, 0.35458, 0.90834, 0.13383, 0.04823, 0.01566, 0.83777,
],
);
let output = constant(
Type::Mat3,
vec![
1.60475, -0.10208, -0.00327, -0.53108, 1.10813, -0.07276, -0.07367, -0.00605, 1.07602,
],
);
let c = input.mul(color.mul(exposure).div(float(0.6)));
let a = c
.clone()
.mul(c.clone().add(float(0.0245786)))
.sub(float(0.000090537));
let b = c
.clone()
.mul(c.add(float(0.432951)).mul(float(0.983729)))
.add(float(0.238081));
output.mul(a.div(b)).saturate()
},
)
})
});
call(&def, vec![color, exposure])
}
pub fn agx_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("agxToneMapping"),
vec![("color", Type::Vec3), ("exposure", Type::F32)],
Type::Vec3,
|args| {
let (color, exposure) = (args[0].clone(), args[1].clone());
let srgb_to_rec2020 = constant(
Type::Mat3,
vec![
0.6274, 0.0691, 0.0164, 0.3293, 0.9195, 0.088, 0.0433, 0.0113, 0.8956,
],
);
let inset = constant(
Type::Mat3,
vec![
0.856627153315983,
0.137318972929847,
0.11189821299995,
0.0951212405381588,
0.761241990602591,
0.0767994186031903,
0.0482516061458583,
0.101439036467562,
0.811302368396859,
],
);
let outset = constant(
Type::Mat3,
vec![
1.1271005818144368,
-0.1413297634984383,
-0.14132976349843826,
-0.11060664309660323,
1.157823702216272,
-0.11060664309660294,
-0.016493938717834573,
-0.016493938717834257,
1.2519364065950405,
],
);
let rec2020_to_srgb = constant(
Type::Mat3,
vec![
1.6605, -0.1246, -0.0182, -0.5876, 1.1329, -0.1006, -0.0728, -0.0083, 1.1187,
],
);
let min_ev = || float(-12.47393);
let max_ev = float(4.026069);
let colortone = to_var(None, color);
let x = to_var(None, colortone.clone());
let x2 = to_var(None, x.clone().mul(x.clone()));
let x4 = to_var(None, x2.clone().mul(x2.clone()));
let contrast = float(15.5)
.mul(x4.clone().mul(x2.clone()))
.sub(float(40.14).mul(x4.clone().mul(x.clone())))
.add(
float(31.96)
.mul(x4)
.sub(float(6.868).mul(x2.clone().mul(x.clone())))
.add(
float(0.4298)
.mul(x2)
.add(float(0.1191).mul(x).sub(float(0.00232))),
),
);
block(
vec![
colortone.assign(colortone.mul(exposure)),
colortone.assign(srgb_to_rec2020.mul(colortone.clone())),
colortone.assign(inset.mul(colortone.clone())),
colortone.assign(max(colortone.clone(), float(1e-10))),
colortone.assign(log2(colortone.clone())),
colortone.assign(colortone.sub(min_ev()).div(max_ev.sub(min_ev()))),
colortone.assign(colortone.clamp(0.0, 1.0)),
colortone.assign(contrast),
colortone.assign(outset.mul(colortone.clone())),
colortone.assign(
max(vec3(0.0, 0.0, 0.0), colortone.clone())
.pow(vec3(2.2, 2.2, 2.2)),
),
colortone.assign(rec2020_to_srgb.mul(colortone.clone())),
colortone.assign(colortone.clamp(0.0, 1.0)),
],
colortone,
)
},
)
})
});
call(&def, vec![color, exposure])
}
pub fn neutral_tone_mapping(color: NodeRef, exposure: NodeRef) -> NodeRef {
thread_local! { static CELL: Lazy<Rc<FnDef>> = const { Lazy::new() }; }
let def = CELL.with(|c| {
c.get(|| {
shader_fn(
Some("neutralToneMapping"),
vec![("color", Type::Vec3), ("exposure", Type::F32)],
Type::Vec3,
|args| {
let start_compression = || float(0.76);
let desaturation = float(0.15);
let color = to_var(None, args[0].clone().mul(args[1].clone()));
let x = color.x().min(color.y().min(color.z()));
let offset = x
.less_than(float(0.08))
.select(x.sub(float(6.25).mul(x.mul(x.clone()))), float(0.04));
let peak = color.x().max(color.y().max(color.z()));
let d = float(1.0).sub(start_compression());
let new_peak =
float(1.0).sub(d.mul(d.clone()).div(peak.add(d.sub(start_compression()))));
let g = float(1.0).sub(
float(1.0)
.div(desaturation.mul(peak.sub(new_peak.clone())).add(float(1.0))),
);
block(
vec![
color.assign(color.sub(offset)),
if_statement(
peak.less_than(start_compression()),
vec![return_statement(color.clone())],
),
color.assign(color.mul(new_peak.div(peak))),
],
mix(color, new_peak.to(Type::Vec3), g),
)
},
)
})
});
call(&def, vec![color, exposure])
}