# graphics3d/subsurfacescatteringeffect (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/graphics3d/subsurfacescatteringeffect/

Screen-space subsurface scattering. (the original graphics3d/subsurfacescatteringeffect.js)
- Separable, depth-aware horizontal/vertical blur of the diffuse irradiance buffer. Builds per-channel kernels from the skin diffusion profile (sum of Gaussians),
  and projects the scattering width (world units) onto the screen according to depth.
- The render() input is an irradiance texture with the scattering mask in alpha and the depth texture of the same pass. The result is get_result_texture().
- The GLSL, kernel formula and defaults (scattering width 0.2, falloff (1, 0.37, 0.3), strength (0.48, 0.41, 0.28)) are the same as the original.
  The original ${KERNEL_SAMPLE_COUNT} / ${KERNEL_RANGE} became the numbers 17 / 3.
- Functions that use GL take gl, and construction and resizing return an error (Result) if GL objects cannot be created.

## SubsurfaceScatteringEffect (struct)

Screen-space subsurface scattering.

Example: Scatter the irradiance of the skin MRT pass (attachment 0) according to depth

```rust
use vanilla::{Camera3D, RenderTarget, SubsurfaceScatteringEffect};

fn create_scattering(gl: &vanilla::GlContext) -> Result<SubsurfaceScatteringEffect, String> {
	let mut subsurface_scattering_effect = SubsurfaceScatteringEffect::new(gl)?;
	subsurface_scattering_effect.set_scatter_width(0.015);
	Ok(subsurface_scattering_effect)
}

fn render_scattering(gl: &vanilla::GlContext, subsurface_scattering_effect: &mut SubsurfaceScatteringEffect, scene_render_target: &RenderTarget, camera: &Camera3D) -> Result<(), String> {
	subsurface_scattering_effect.resize(gl, scene_render_target.get_width(), scene_render_target.get_height())?;
	subsurface_scattering_effect.render(gl, scene_render_target.get_color_texture(0), scene_render_target.get_depth_texture(), camera.get_field_of_view(), camera.get_aspect_ratio(), camera.get_near_distance(), camera.get_far_distance());
	let scattered_irradiance_texture = subsurface_scattering_effect.get_result_texture();
	assert!(scattered_irradiance_texture.is_some());
	Ok(())
}
```

- `pub fn new(gl: &GlContext) -> Result<SubsurfaceScatteringEffect, String>` (constructor, since 0.3.2): Constructor. (1 pass + 2 half-float targets, match the size with resize)
  - `gl` &GlContext: GL context. (taken out with Graphic::get_gl)
  - returns Result<SubsurfaceScatteringEffect, String>: New effect. (scattering width 0.2, falloff (1, 0.37, 0.3), strength (0.48, 0.41, 0.28), with the kernel computed) Err(error message) if shader compilation or target creation fails.
- `pub fn compute_kernel(&mut self)` (method, since 0.3.2): Computes the kernel. (integrates the skin diffusion profile over the offset interval areas, center sample at index 0)
- `pub fn build_kernel(falloff_color: [f64; 3], strength_color: [f64; 3]) -> [f32; KERNEL_SAMPLE_COUNT * 4]` (static, since 0.3.2): Builds the kernel. (GL independent, rgb weight + w offset per sample)
  - `falloff_color` [f64; 3]: Per-channel falloff. (r, g, b, larger values spread that channel farther)
  - `strength_color` [f64; 3]: Per-channel strength. (r, g, b, at 0 that channel does not scatter and only the center is 1)
  - returns [f32; KERNEL_SAMPLE_COUNT * 4]: Array of r weight, g weight, b weight and offset for KERNEL_SAMPLE_COUNT (17) samples in order. (sample 0 is the center with offset 0, the weights sum to 1 per channel, offsets are -3 ~ 3)

  Example: The kernel of the default skin profile sums to 1 per channel, and at strength 0 only the center remains

  ```rust
  use vanilla::graphics3d::subsurfacescatteringeffect::KERNEL_SAMPLE_COUNT;
  use vanilla::SubsurfaceScatteringEffect;
  
  let kernel = SubsurfaceScatteringEffect::build_kernel([1.0, 0.37, 0.3], [0.48, 0.41, 0.28]);
  for channel_index in 0..3 {
  	let weight_sum: f64 = (0..KERNEL_SAMPLE_COUNT).map(|sample_index| kernel[sample_index * 4 + channel_index] as f64).sum();
  	assert!((weight_sum - 1.0).abs() < 1.0e-5);
  }
  assert_eq!(kernel[3], 0.0);
  
  let identity_kernel = SubsurfaceScatteringEffect::build_kernel([1.0, 0.37, 0.3], [0.0, 0.0, 0.0]);
  assert_eq!(identity_kernel[0], 1.0);
  assert_eq!(identity_kernel[4], 0.0);
  ```

- `pub fn resize(&mut self, gl: &GlContext, width: i32, height: i32) -> Result<(), String>` (method, since 0.3.2): Resizes. (based on the irradiance buffer resolution, 2 full-resolution float targets)
  - `gl` &GlContext: GL context.
  - `width` i32: Irradiance buffer width. (pixels, the targets are the same size)
  - `height` i32: Irradiance buffer height. (pixels, the targets are the same size)
  - returns Result<(), String>: Ok if the buffers were fitted. Err(GL error text) if GL objects cannot be made while rebuilding.
- `pub fn render(&self, gl: &GlContext, irradiance_texture: Option<GlTexture>, depth_texture: Option<GlTexture>, field_of_view_radian: f64, aspect_ratio: f64, near_distance: f64, far_distance: f64)` (method, since 0.3.2): Renders the scattering. (horizontal → ping, vertical → pong, the result is get_result_texture())
  - Side effects: depth/blend disabled, TEXTURE0 active, framebuffer binding changed.
  - The depth texture is bound to unit 1 and unbound at the end. (unit 1 is the shadow sampler slot)
  - `gl` &GlContext: GL context.
  - `irradiance_texture` Option<GlTexture>: Diffuse irradiance texture. (rgb irradiance, a scattering mask, areas where the mask is below 0.001 are left as is)
  - `depth_texture` Option<GlTexture>: Depth texture of the same pass. (hardware depth 0 ~ 1)
  - `field_of_view_radian` f64: Vertical field of view. (radians, for projecting the scattering width onto the screen)
  - `aspect_ratio` f64: Aspect ratio. (width / height, corrects the horizontal step)
  - `near_distance` f64: Near distance of the projection. (for linearizing depth)
  - `far_distance` f64: Far distance of the projection.
- `pub fn get_result_texture(&self) -> Option<GlTexture>` (method, since 0.3.2): Returns the result texture. (after render())
  - returns Option<GlTexture>: Scattered irradiance texture. (the pong target, scattering mask in a) None after destroy.
- `pub fn set_scatter_width(&mut self, scatter_width: f64)` (method, since 0.3.2): Sets the scattering width. (world units, full kernel radius)
  - `scatter_width` f64: Scattering width. (world units, default 0.2, the shader clamps the projected width to at most 0.05 of the screen height)
- `pub fn get_scatter_width(&self) -> f64` (method, since 0.3.2): Returns the scattering width.
  - returns f64: Scatter width. (world units)
- `pub fn set_profile(&mut self, falloff_color: [f64; 3], strength_color: [f64; 3])` (method, since 0.3.2): Sets the diffusion profile. (per-channel falloff / strength, skin default (1, 0.37, 0.3) / (0.48, 0.41, 0.28))
  - Recomputes the kernel right away.
  - `falloff_color` [f64; 3]: Per-channel falloff. (r, g, b, larger values spread that channel farther)
  - `strength_color` [f64; 3]: Per-channel strength. (r, g, b, at 0 that channel does not scatter)
- `pub fn get_falloff_color(&self) -> [f64; 3]` (method, since 0.3.2): Returns the falloff color.
  - returns [f64; 3]: Per-channel falloff. (r, g, b)
- `pub fn get_strength_color(&self) -> [f64; 3]` (method, since 0.3.2): Returns the strength color.
  - returns [f64; 3]: Per-channel strength. (r, g, b)
- `pub fn destroy(&mut self, gl: &GlContext)` (method, since 0.3.2): Destroy. (Releases GL resources)
  - `gl` &GlContext: GL context used at creation.
- `pub fn get_scatter_pass(&self) -> &FullscreenPass` (method, since 0.3.2): Returns the scattering pass.
  - returns &FullscreenPass: Scattering pass. (used for both horizontal and vertical)
- `pub fn get_ping_render_target(&self) -> &RenderTarget` (method, since 0.3.2): Returns the ping render target. (horizontal blur result)
  - returns &RenderTarget: Ping render target. (horizontal scattering result)
- `pub fn get_pong_render_target(&self) -> &RenderTarget` (method, since 0.3.2): Returns the pong render target. (holds the final result)
  - returns &RenderTarget: Pong render target. (vertical scattering result, owner of the result texture)

## Functions and constants

- `pub const KERNEL_SAMPLE_COUNT: usize = 17` (field, since 0.3.2): Kernel sample count. (center 1 + both sides, odd, must match the 17 in the shader)
  - returns usize
- `pub const KERNEL_RANGE: f64 = 3.0` (field, since 0.3.2): Kernel offset range. (in diffusion profile units, normalized by the scattering width in the shader, must match the 3 in the shader)
  - returns f64
