# graphics3d/ambientocclusioneffect (vanilla-engine 0.4.0)

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

Screen space ambient occlusion. (the original graphics3d/ambientocclusioneffect.js)
- Depth + normal buffers → hemisphere sample occlusion → depth aware blur. The result is the visibility (1 = no occlusion) in the r channel of get_result_texture().
- The render() inputs are the main pass's depth texture and world normal texture (alpha = coverage), and the camera's view rotation / projection parameters.
- The GLSL, kernel and defaults (radius 0.03, intensity 1, bias 0.002, scale 0.5) are the same as the original. The original ${SAMPLE_COUNT} became the number 16.
- Functions that use GL take gl, and creation and resizing return an error (Result) if GL objects cannot be made.

## AmbientOcclusionEffect (struct)

Screen space ambient occlusion.
- The three buffers (occlusion, ping, pong) are RGBA16F. The occlusion buffer's r is visibility and g is linear depth.

Example: Make visibility from a scene that drew normals to attachment 1 and depth to a depth texture

```rust
use vanilla::{AmbientOcclusionEffect, Camera3D, RenderTarget, RenderTargetOptions};

fn create_resources(gl: &vanilla::GlContext) -> Result<(RenderTarget, AmbientOcclusionEffect), String> {
	let options = RenderTargetOptions { color_attachment_count: 2, use_float_color: true, use_depth_texture: true, ..RenderTargetOptions::default() };
	let scene_render_target = RenderTarget::new(gl, 1280, 720, true, Some(options))?;
	let mut ambient_occlusion_effect = AmbientOcclusionEffect::new(gl)?;
	ambient_occlusion_effect.set_parameters(0.05, 1.2, 0.002);
	ambient_occlusion_effect.set_scale(0.5);
	ambient_occlusion_effect.resize(gl, 1280, 720)?;
	Ok((scene_render_target, ambient_occlusion_effect))
}

fn render_occlusion(gl: &vanilla::GlContext, ambient_occlusion_effect: &AmbientOcclusionEffect, scene_render_target: &RenderTarget, camera: &Camera3D) {
	let view_matrix = camera.get_view_matrix();
	ambient_occlusion_effect.render(gl, scene_render_target.get_depth_texture(), scene_render_target.get_color_texture(1), view_matrix.get_elements(), camera.get_field_of_view(), camera.get_aspect_ratio(), camera.get_near_distance(), camera.get_far_distance());
	let visibility_texture = ambient_occlusion_effect.get_result_texture();
	assert!(visibility_texture.is_some());
}
```

- `pub fn new(gl: &GlContext) -> Result<AmbientOcclusionEffect, String>` (constructor, since 0.3.2): Creates. (2 passes + 3 half float targets, sized with resize)
  - `gl` &GlContext: GL context. (taken out with Graphic::get_gl)
  - returns Result<AmbientOcclusionEffect, String>: New effect. (radius 0.03, intensity 1, bias 0.002, scale 0.5, with the kernel computed) Err(error text) if shader compilation or buffer creation fails.
- `pub fn compute_kernel(&mut self)` (method, since 0.3.2): Computes the sample kernel. (evenly within the hemisphere, denser toward the center)
- `pub fn build_sample_kernel() -> [f32; SAMPLE_COUNT * 3]` (static, since 0.3.2): Makes the sample kernel. (GL independent, golden angle spiral, even heights, sizes in a squared 0.15 ~ 1 distribution)
  - returns [f32; SAMPLE_COUNT * 3]: Array of the x, y, z of SAMPLE_COUNT (16) samples in sequence. (inside the hemisphere with positive z, sample lengths 0.15 ~ 1)

  Example: All samples fall inside the upper hemisphere of radius 1

  ```rust
  use vanilla::graphics3d::ambientocclusioneffect::SAMPLE_COUNT;
  use vanilla::AmbientOcclusionEffect;
  
  let sample_kernel = AmbientOcclusionEffect::build_sample_kernel();
  assert_eq!(sample_kernel.len(), SAMPLE_COUNT * 3);
  for sample_index in 0..SAMPLE_COUNT {
  	let x = sample_kernel[sample_index * 3];
  	let y = sample_kernel[sample_index * 3 + 1];
  	let z = sample_kernel[sample_index * 3 + 2];
  	assert!(z > 0.0);
  	assert!((x * x + y * y + z * z).sqrt() <= 1.0 + 1.0e-5);
  }
  ```

- `pub fn resize(&mut self, gl: &GlContext, width: i32, height: i32) -> Result<(), String>` (method, since 0.3.2): Resizes. (main pass resolution, the downscale factor is applied internally)
  - `gl` &GlContext: GL context.
  - `width` i32: Width of the main pass. (pixels, the buffers are multiplied by the scale and floored, at least 1)
  - `height` i32: Height of the main pass. (pixels, the buffers are multiplied by the scale and floored, at least 1)
  - 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, depth_texture: Option<GlTexture>, normal_texture: Option<GlTexture>, view_matrix_elements: &[f32; 16], field_of_view_radian: f64, aspect_ratio: f64, near_distance: f64, far_distance: f64)` (method, since 0.3.2): Renders occlusion. (occlusion → horizontal blur → vertical blur, the result is get_result_texture())
  - view_matrix_elements is the view matrix elements (column major 4x4), field_of_view_radian is the vertical field of view.
  - Side effects: depth/blend disabled, TEXTURE0 active, the framebuffer binding changes.
  - Depth is bound to unit 0 and normals to unit 2, and unit 2 is unbound at the end.
  - `gl` &GlContext: GL context.
  - `depth_texture` Option<GlTexture>: Depth texture of the main pass. (hardware depth 0 ~ 1, 1 is treated as sky with no occlusion)
  - `normal_texture` Option<GlTexture>: World normal texture. (-1 ~ 1 normals as is in rgb, alpha below 0.5 is treated as empty with no occlusion)
  - `view_matrix_elements` &[f32; 16]: View matrix elements. (column major 4x4, only the rotation part is used)
  - `field_of_view_radian` f64: Vertical field of view. (radians)
  - `aspect_ratio` f64: Aspect ratio. (width / height)
  - `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(), r visibility)
  - returns Option<GlTexture>: Visibility texture after blurring. (the pong buffer, r of 1 means no occlusion, g is linear depth) None after destroy.
- `pub fn set_parameters(&mut self, radius: f64, intensity: f64, bias: f64)` (method, since 0.3.2): Sets the parameters. (sample radius (world) / strength / depth bias)
  - `radius` f64: Sample radius. (world units, default 0.03)
  - `intensity` f64: Occlusion intensity. (multiplied by the occluded amount, default 1)
  - `bias` f64: Depth bias. (world units, prevents self occlusion, default 0.002)
- `pub fn set_scale(&mut self, scale: f64)` (method, since 0.3.2): Sets the internal resolution scale. (call before resize)
  - `scale` f64: Resolution scale of the buffers. (multiplied by the main pass size, default 0.5, used from the next resize)
- `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_occlusion_pass(&self) -> &FullscreenPass` (method, since 0.3.2): Returns the occlusion pass.
  - returns &FullscreenPass: Occlusion pass. (shader that computes hemisphere sample occlusion from depth and normals)
- `pub fn get_blur_pass(&self) -> &FullscreenPass` (method, since 0.3.2): Returns the blur pass.
  - returns &FullscreenPass: Depth aware blur pass. (both horizontal and vertical use this pass)
- `pub fn get_occlusion_render_target(&self) -> &RenderTarget` (method, since 0.3.2): Returns the occlusion render target.
  - returns &RenderTarget: Occlusion render target. (visibility before blur)
- `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 blur 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 blur result, owner of the result texture)
- `pub fn get_radius(&self) -> f64` (method, since 0.3.2): Returns the sample radius.
  - returns f64: Sample radius. (world units)
- `pub fn get_intensity(&self) -> f64` (method, since 0.3.2): Returns the strength.
  - returns f64: Occlusion intensity.
- `pub fn get_bias(&self) -> f64` (method, since 0.3.2): Returns the depth bias.
  - returns f64: Depth bias. (world units)
- `pub fn get_scale(&self) -> f64` (method, since 0.3.2): Returns the internal resolution scale.
  - returns f64: Resolution scale of the buffers.

## Functions and constants

- `pub const SAMPLE_COUNT: usize = 16` (field, since 0.3.2): Hemisphere sample count. (scattered per fragment with rotation noise, must match the 16 in the shader)
  - returns usize
