use crate::core::{BufferGeometry, ObjectRef};
use crate::materials::MeshBasicNodeMaterial;
use crate::math::{Color, Vector2};
use crate::nodes::display::{viewport_safe_uv, viewport_shared_texture_at};
use crate::nodes::node::{CustomNode, SettableValue};
use crate::nodes::reflector_node::{reflector, ReflectorNode, ReflectorParameters};
use crate::nodes::tsl::{
abs, block, camera_position, custom, dot, float, max, mix, position_world, screen_uv, texture,
texture_with_uv, to_const, to_var, to_var_intent, uniform_settable, uv, vec2_join, vec3_join,
vec4_join,
};
use crate::nodes::{NodeBuilder, NodeRef, NodeUpdateType, Type};
use crate::objects::Mesh;
use crate::renderer::Renderer;
use crate::textures::Texture;
use std::rc::Rc;
const CYCLE: f64 = 0.15;
const HALF_CYCLE: f64 = CYCLE * 0.5;
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Water2MeshOptions {
pub color: Color,
pub flow_direction: Vector2,
pub flow_speed: f64,
pub reflectivity: f64,
pub scale: f64,
pub flow_map: Option<Texture>,
pub normal_map0: Texture,
pub normal_map1: Texture,
}
impl Water2MeshOptions {
pub fn new(normal_map0: Texture, normal_map1: Texture) -> Self {
Self {
color: Color::from_hex(0xffffff),
flow_direction: Vector2::new(1.0, 0.0),
flow_speed: 0.03,
reflectivity: 0.02,
scale: 1.0,
flow_map: None,
normal_map0,
normal_map1,
}
}
}
pub struct Water2Mesh {
pub mesh: ObjectRef,
pub normal_map0: Texture,
pub normal_map1: Texture,
pub flow_map: Option<Texture>,
pub color: SettableValue,
pub flow_direction: SettableValue,
pub flow_speed: SettableValue,
pub reflectivity: SettableValue,
pub scale: SettableValue,
pub flow_config: SettableValue,
pub reflection_sampler: ReflectorNode,
}
struct Uniforms {
color: NodeRef,
flow_direction: NodeRef,
reflectivity: NodeRef,
scale: NodeRef,
flow_config: NodeRef,
}
impl Water2Mesh {
pub fn new(geometry: Rc<BufferGeometry>, options: Water2MeshOptions) -> Self {
let c = options.color;
let d = options.flow_direction;
let (color, color_cell) = uniform_settable(Type::Vec3, vec![c.r, c.g, c.b]);
let (flow_direction, flow_direction_cell) = uniform_settable(Type::Vec2, vec![d.x, d.y]);
let (_flow_speed, flow_speed_cell) = uniform_settable(Type::F32, vec![options.flow_speed]);
let (reflectivity, reflectivity_cell) =
uniform_settable(Type::F32, vec![options.reflectivity]);
let (scale, scale_cell) = uniform_settable(Type::F32, vec![options.scale]);
let (flow_config, flow_config_cell) = uniform_settable(Type::Vec3, vec![0.0; 3]);
let uniforms = Uniforms {
color,
flow_direction,
reflectivity,
scale,
flow_config,
};
let mut reflection_sampler = reflector(ReflectorParameters::default());
let output = water_output(
&uniforms,
&options.normal_map0,
&options.normal_map1,
options.flow_map.as_ref(),
&mut reflection_sampler,
);
let water_node = custom(WaterNode {
flow_speed: flow_speed_cell.clone(),
flow_config: flow_config_cell.clone(),
output,
});
let mut material = MeshBasicNodeMaterial::new();
material.transparent = true;
material.color_node = Some(water_node);
let mesh = Mesh::new(geometry, material);
reflection_sampler.add_target_on_setup(&mesh);
Self {
mesh,
normal_map0: options.normal_map0,
normal_map1: options.normal_map1,
flow_map: options.flow_map,
color: color_cell,
flow_direction: flow_direction_cell,
flow_speed: flow_speed_cell,
reflectivity: reflectivity_cell,
scale: scale_cell,
flow_config: flow_config_cell,
reflection_sampler,
}
}
pub fn update_flow(&self, delta: f64) {
update_flow(&self.flow_config, self.flow_speed.get()[0], delta);
}
}
fn update_flow(flow_config: &SettableValue, flow_speed: f64, delta: f64) {
let mut config = flow_config.get();
config[0] += flow_speed * delta; config[1] = config[0] + HALF_CYCLE;
if config[0] >= CYCLE {
config[0] = 0.0;
config[1] = HALF_CYCLE;
} else if config[1] >= CYCLE {
config[1] -= CYCLE;
}
config[2] = HALF_CYCLE;
flow_config.set(config);
}
struct WaterNode {
flow_speed: SettableValue,
flow_config: SettableValue,
output: NodeRef,
}
impl CustomNode for WaterNode {
fn type_name(&self) -> &'static str {
"WaterNode"
}
fn node_type(&self) -> Type {
Type::Vec4
}
fn setup(&self, _builder: &NodeBuilder) -> NodeRef {
self.output.clone()
}
fn update_before_type(&self) -> NodeUpdateType {
NodeUpdateType::Render
}
fn update_before(&self, renderer: &mut Renderer) -> bool {
let delta = renderer.node_frame().delta_time;
update_flow(&self.flow_config, self.flow_speed.get()[0], delta);
true
}
}
fn water_output(
u: &Uniforms,
normal_map0: &Texture,
normal_map1: &Texture,
flow_map: Option<&Texture>,
reflection_sampler: &mut ReflectorNode,
) -> NodeRef {
let flow_map_offset0 = u.flow_config.x();
let flow_map_offset1 = u.flow_config.y();
let half_cycle = u.flow_config.z();
let to_eye = camera_position().sub(position_world()).normalize();
let flow = match flow_map {
Some(flow_map) => to_var_intent(texture(flow_map).xy().mul(2.0).sub(1.0)),
None => to_var_intent(vec2_join(vec![u.flow_direction.x(), u.flow_direction.y()])),
};
let flip = flow.x().mul_assign(-1.0);
let uvs = uv();
let normal_uv0 = uvs
.mul(u.scale.clone())
.add(flow.mul(flow_map_offset0.clone()));
let normal_uv1 = uvs.mul(u.scale.clone()).add(flow.mul(flow_map_offset1));
let normal_color0 = texture_with_uv(normal_map0, normal_uv0);
let normal_color1 = texture_with_uv(normal_map1, normal_uv1);
let flow_lerp = abs(half_cycle.clone().sub(flow_map_offset0)).div(half_cycle);
let normal_color = to_const(None, mix(normal_color0, normal_color1, flow_lerp));
let normal = to_const(
None,
vec3_join(vec![
normal_color.x().mul(2.0).sub(1.0),
normal_color.z(),
normal_color.y().mul(2.0).sub(1.0),
])
.normalize(),
);
let theta = max(dot(to_eye, normal.clone()), 0.0);
let reflectance = float(1.0)
.sub(theta)
.pow(5.0)
.mul(float(1.0).sub(u.reflectivity.clone()))
.add(u.reflectivity.clone());
let offset = to_var(None, normal.xz().mul(0.05));
reflection_sampler.uv_node = reflection_sampler.uv_node.add(offset.clone());
let refractor_uv = to_const(None, screen_uv().add(offset));
let refraction_sampler = viewport_shared_texture_at(viewport_safe_uv(refractor_uv));
let output = vec4_join(vec![u.color.clone(), float(1.0)]).mul(mix(
refraction_sampler,
reflection_sampler.node(),
reflectance,
));
block(vec![flip], output)
}
#[cfg(test)]
mod tests {
use super::*;
fn config(x: f64, y: f64, z: f64) -> SettableValue {
SettableValue::new(vec![x, y, z])
}
#[test]
fn update_flow_advances_offset0_and_keeps_offset1_half_a_cycle_ahead() {
let flow_config = config(0.0, 0.0, 0.0);
update_flow(&flow_config, 0.03, 1.0);
assert_eq!(flow_config.get(), vec![0.03, 0.03 + HALF_CYCLE, HALF_CYCLE]);
}
#[test]
fn update_flow_wraps_offset1() {
let flow_config = config(0.07, 0.0, 0.0);
update_flow(&flow_config, 0.03, 1.0);
let [x, y, z] = flow_config.get()[..] else {
unreachable!()
};
assert_eq!(x, 0.1);
assert_eq!(y, 0.1 + HALF_CYCLE - CYCLE);
assert_eq!(z, HALF_CYCLE);
}
#[test]
fn update_flow_resets_at_a_full_cycle() {
let flow_config = config(0.14, 0.0, 0.0);
update_flow(&flow_config, 0.03, 1.0);
assert_eq!(flow_config.get(), vec![0.0, HALF_CYCLE, HALF_CYCLE]);
}
#[test]
fn update_flow_with_no_time_sets_the_half_cycle() {
let flow_config = config(0.0, 0.0, 0.0);
update_flow(&flow_config, 0.03, 0.0);
assert_eq!(flow_config.get(), vec![0.0, HALF_CYCLE, HALF_CYCLE]);
}
}