# effect/screeneffect (vanilla-engine 0.4.0)

> https://vanillapunch.com/docs/vanilla-engine/0.4.0/api/effect/screeneffect/

Screen effect. (scene post-processing chain)
- Ported from the original effect/screeneffect.js. Effect names, apply order, default parameters, parameter names, default colors and GLSL bodies are copied from the original tables as they are.
- The scene is drawn to the screen as is, and end() copies the screen (or the area set with set_region), applies the enabled effects in order and puts it back in the same place.
  The screen is copied into an RGB8 texture with copyTexSubImage2D, and effects are applied with FullscreenPass going back and forth between ping-pong / half size framebuffers. The last step draws to the default framebuffer.
- The area is in canvas pixel coordinates (top left origin), and with a rounded corner radius the outside of it keeps the original.
- Shaders are GLSL ES 3.00. On desktop (GL 3.3 core) ShaderProgram changes only the header to #version 330 core, and the web (WebGL2) uses them as they are.
- The engine is not modified. Like the original, the scene calls begin at the start of pre_draw, end at the end of post_draw, and tick in tick:
  ```text
    // in the scene load
    self.screen_effect = ScreenEffect::new();
    self.screen_effect.set_enabled(ScreenEffectType::Vignette, true);
    // at the start of pre_draw / at the end of post_draw
    self.screen_effect.begin(graphic);  ...  self.screen_effect.end(graphic);
    // in tick
    self.screen_effect.tick(time_delta);
  ```
- When building a pass shader fails, both engines report once and skip that step. (one failing effect does not stop the frame)
- Differences from the original:
  - The original takes a Graphic in the constructor and holds the GL context. The Rust version is made taking nothing, makes GL resources at the first end, and each function takes a Graphic.
    At that time it holds a weak handle to the GL context, so destroy() releases without arguments like the original, and it also releases by itself when dropped (Drop, when the scene is unloaded).
  - Effects are the ScreenEffectType enum instead of strings. (the original string names are get_name / from_name)

## ScreenEffectRegion (struct) (Clone, Copy, Debug, PartialEq)

Application area. (canvas pixels, top left origin)

Example: Set, read and clear the area

```rust
use vanilla::{ScreenEffect, ScreenEffectRegion};

let mut screen_effect = ScreenEffect::new();
assert_eq!(screen_effect.get_region(), None);
screen_effect.set_region(40.0, 30.0, 320.0, 180.0, -5.0);
let expected_region = ScreenEffectRegion { x: 40.0, y: 30.0, width: 320.0, height: 180.0, corner_radius: 0.0 };
assert_eq!(screen_effect.get_region(), Some(expected_region));
screen_effect.clear_region();
assert!(screen_effect.get_region().is_none());
```

- `pub x: f64` (field, since 0.3.2): Region left. (canvas pixels)
  - returns f64
- `pub y: f64` (field, since 0.3.2): Top of the area. (canvas pixels)
  - returns f64
- `pub width: f64` (field, since 0.3.2): Area width. (pixels, the part beyond the canvas is cut off)
  - returns f64
- `pub height: f64` (field, since 0.3.2): Area height. (pixels, the part beyond the canvas is cut off)
  - returns f64
- `pub corner_radius: f64` (field, since 0.3.2): Rounded corner radius. (pixels, a rectangle if 0)
  - returns f64

## ScreenEffect (struct) (TimelinePropertyTarget, Default, Drop)

Screen effect.
- Holds enabled, strength, four parameters and a color for each effect. When the scene calls begin at the start of pre_draw, end at the end of post_draw and tick in tick, the enabled effects are applied in application order.

Example: Enable the vignette and set its strength and parameters

```rust
use vanilla::{Color, ScreenEffect, ScreenEffectType};

let mut screen_effect = ScreenEffect::new();
assert!(!screen_effect.has_active_effect());
screen_effect.set_enabled(ScreenEffectType::Vignette, true);
screen_effect.set_strength(ScreenEffectType::Vignette, 0.8);
screen_effect.set_parameter(ScreenEffectType::Vignette, "outer", 0.9);
screen_effect.set_color(ScreenEffectType::Vignette, Color::create(0.0, 0.0, 0.2, 1.0));
assert!(screen_effect.has_active_effect());
assert_eq!(screen_effect.get_parameters(ScreenEffectType::Vignette), [0.45, 0.9, 0.0, 0.0]);
screen_effect.set_strength(ScreenEffectType::Vignette, 0.0);
assert!(!screen_effect.has_active_effect());
```

Example: Call begin, end and tick in a scene

```rust
use vanilla::{Engine, EngineConfiguration, Graphic, Scene, SceneBase, ScreenEffect, ScreenEffectType};

struct MainScene {
	scene_base: SceneBase,
	screen_effect: ScreenEffect,
}

impl Scene for MainScene {
	fn get_scene_base(&self) -> &SceneBase {
		&self.scene_base
	}

	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
		&mut self.scene_base
	}

	fn load(&mut self, _engine: &Engine) {
		self.screen_effect.set_enabled(ScreenEffectType::Vignette, true);
	}

	fn tick(&mut self, time_delta: f64) {
		self.scene_base.tick(time_delta);
		self.screen_effect.tick(time_delta);
	}

	fn pre_draw(&mut self, graphic: &mut Graphic) {
		self.screen_effect.begin(graphic);
		self.scene_base.draw_scene_background(graphic);
	}

	fn post_draw(&mut self, graphic: &mut Graphic) {
		self.screen_effect.end(graphic);
	}
}

let engine = Engine::new(EngineConfiguration::new());
let main_scene = MainScene {
	scene_base: SceneBase::new(),
	screen_effect: ScreenEffect::new(),
};
engine.run(Box::new(main_scene)).unwrap();
```

- `pub fn new() -> ScreenEffect` (constructor, since 0.3.2): Creates. (GL resources are made at the first end)
  - returns ScreenEffect: A screen effect with all effects off, strength 1, and each effect's default parameters and color. (no area, time 0)
- `pub fn reset_all(&mut self)` (method, since 0.3.2): Resets everything to defaults. (off, strength 1, default parameters / colors. So earlier settings do not linger when switching modes)
- `pub fn set_region(&mut self, x: f64, y: f64, width: f64, height: f64, corner_radius: f64)` (method, since 0.3.2): Sets the application area. (canvas pixels, top left origin. corner_radius is the rounded corner radius (pixels), a rectangle if 0)
  - `x` f64: Left of the area. (canvas pixels, rounded in end, below 0 becomes 0)
  - `y` f64: Top of the area. (canvas pixels)
  - `width` f64: Area width. (pixels, cut off beyond the canvas)
  - `height` f64: Area height. (pixels, cut off beyond the canvas)
  - `corner_radius` f64: Rounded corner radius. (pixels, negative becomes 0, the original screen is kept outside it)
- `pub fn clear_region(&mut self)` (method, since 0.3.2): Clears the region to apply to. (whole screen)
- `pub fn get_region(&self) -> Option<ScreenEffectRegion>` (method, since 0.3.2): Returns the application area. (the whole screen if None)
  - returns Option<ScreenEffectRegion>: The set area. None for the whole screen.
- `pub fn tick(&mut self, time_delta: f64)` (method, since 0.3.2): Update. (time for animated effects)
  - `time_delta` f64: Time elapsed since the last frame. (seconds, added to the effect time)
- `pub fn begin(&mut self, _graphic: &mut Graphic)` (method, since 0.3.2): Begins. (at the start of the scene's pre_draw. The scene draws straight to the screen. end only works when an effect is enabled)
  - `_graphic` &mut Graphic: Graphic. (not used now, an argument to pair with end)
- `pub fn end(&mut self, graphic: &mut Graphic)` (method, since 0.3.2): Applies the effects. (at the end of the scene's post_draw. Copies the screen area, applies the effects and puts it back in the same place)
  - Does nothing if no effect was enabled at begin. Render targets and passes are made the first time they are needed.
  - `graphic` &mut Graphic: Graphic that finished drawing the scene. (copies that screen after flushing the batch)
- `pub fn has_active_effect(&self) -> bool` (method, since 0.3.2): Whether any effect is enabled. (strength 0 counts as off)
  - returns bool: true if at least one effect is enabled with a strength above 0.
- `pub fn set_enabled(&mut self, effect_type: ScreenEffectType, is_enabled: bool)` (method, since 0.3.2): Turns an effect on / off.
  - `effect_type` ScreenEffectType: Effect.
  - `is_enabled` bool: Enables it if true.
- `pub fn is_enabled(&self, effect_type: ScreenEffectType) -> bool` (method, since 0.3.2): Returns whether an effect is on.
  - `effect_type` ScreenEffectType: Effect.
  - returns bool: true if enabled. (strength is not checked)
- `pub fn set_strength(&mut self, effect_type: ScreenEffectType, strength: f64)` (method, since 0.3.2): Sets the strength. (0 is the same as off)
  - `effect_type` ScreenEffectType: Effect.
  - `strength` f64: Strength. (usually 0 ~ 1, not applied if 0 or less. Coverage for transition effects, default 1)
- `pub fn get_strength(&self, effect_type: ScreenEffectType) -> f64` (method, since 0.3.2): Returns the strength.
  - `effect_type` ScreenEffectType: Effect.
  - returns f64: Strength. (default 1)
- `pub fn set_parameters(&mut self, effect_type: ScreenEffectType, x: f64, y: f64, z: f64, w: f64)` (method, since 0.3.2): Sets the parameters. (the meaning differs per effect. See the ScreenEffectType comments, pass the original's y / z / w default 0 explicitly)
  - `effect_type` ScreenEffectType: Effect.
  - `x` f64: First parameter.
  - `y` f64: Second parameter. (0 for effects that do not use it)
  - `z` f64: Third parameter. (0 for effects that do not use it)
  - `w` f64: Fourth parameter. (0 for effects that do not use it)
- `pub fn set_parameter(&mut self, effect_type: ScreenEffectType, parameter_name: &str, value: f64)` (method, since 0.3.2): Sets a single parameter. (names in SCREEN_EFFECT_PARAMETER_NAMES)
  - `effect_type` ScreenEffectType: Effect.
  - `parameter_name` &str: Parameter name. (one from get_parameter_names, does nothing for an unknown name)
  - `value` f64: Value.
- `pub fn get_parameters(&self, effect_type: ScreenEffectType) -> [f64; 4]` (method, since 0.3.2): Returns the parameters.
  - `effect_type` ScreenEffectType: Effect.
  - returns [f64; 4]: Parameters [x, y, z, w]. (each effect's defaults after reset_all)
- `pub fn set_color(&mut self, effect_type: ScreenEffectType, color: impl Into<Color>)` (method, since 0.3.2): Sets the color. (a Color or a string such as "#rrggbb")
  - `effect_type` ScreenEffectType: Effect.
  - `color` impl Into<Color>: Effect color. (the meaning differs per effect, like an edge color, a light color, or the color a transition covers with)
- `pub fn get_color(&self, effect_type: ScreenEffectType) -> Color` (method, since 0.3.2): Returns the color.
  - `effect_type` ScreenEffectType: Effect.
  - returns Color: Effect color. (each effect's default color after reset_all, white for effects without a default color)
- `pub fn disable_all(&mut self)` (method, since 0.3.2): Turns everything off.
- `pub fn set_timeline_property(&mut self, property_name: &str, value: &TimelineValue)` (method, since 0.3.2): Applies a timeline property. ("vignette" = strength (off if 0), "shockwave.radius" = parameter, "fade.color" = color, "fade.enabled" = enabled)
  - Values are numbers, strings or booleans (TimelineValue) as in the original. Numbers are read like the original Number() (booleans are 1 / 0, an empty string is 0, NaN if unreadable),
    colors change only for "#rrggbb" strings, and enabled is true or "true".
  - `property_name` &str: "effect" or "effect.member". (effect is the original name, member is color, enabled or a parameter name. Unknown effects or parameter names are ignored)
  - `value` &TimelineValue: Value to apply.

  Example: Apply strength, parameters, color and enabled by timeline property name

  ```rust
  use vanilla::{Color, ScreenEffect, ScreenEffectType, TimelineValue};
  
  let mut screen_effect = ScreenEffect::new();
  screen_effect.set_timeline_property("vignette", &TimelineValue::Number(0.5));
  assert!(screen_effect.is_enabled(ScreenEffectType::Vignette));
  assert_eq!(screen_effect.get_strength(ScreenEffectType::Vignette), 0.5);
  screen_effect.set_timeline_property("shockwave.radius", &TimelineValue::Number(0.75));
  assert_eq!(screen_effect.get_parameters(ScreenEffectType::Shockwave)[2], 0.75);
  screen_effect.set_timeline_property("fade.color", &TimelineValue::String(String::from("#ff0000")));
  screen_effect.set_timeline_property("fade.enabled", &TimelineValue::Boolean(true));
  assert_eq!(screen_effect.get_color(ScreenEffectType::Fade), Color::create(1.0, 0.0, 0.0, 1.0));
  assert!(screen_effect.is_enabled(ScreenEffectType::Fade));
  ```

- `pub fn get_time(&self) -> f64` (method, since 0.3.2): Returns the time.
  - returns f64: Effect time. (seconds, accumulated by tick)
- `pub fn get_scene_texture(&self) -> Option<GlTexture>` (method, since 0.3.2): Returns the scene texture. (after end, the original of the region captured in the last frame)
  - returns Option<GlTexture>: Original texture of the copied area. None before end makes the render targets or after destroy.
- `pub fn get_effect_order() -> Vec<ScreenEffectType>` (static, since 0.3.2): Returns the apply order. (static)
  - returns Vec<ScreenEffectType>: The 58 effects in application order. (same as the enum declaration order)
- `pub fn destroy(&mut self)` (method, since 0.3.2): Destroys. (releases GL resources: render targets and pass programs, the original destroy)
  - Also called by itself when dropped (Drop). Calling end again makes the resources anew.
  - If the GL context is already gone, those resources are gone with it, so it only empties the lists.

## Functions and constants

- `pub const SCREEN_EFFECT_PARAMETER_NAMES: [(ScreenEffectType, &[&str]); 59]` (field, since 0.3.2): Parameter names per effect. (accessed with the timeline property "effect.name", in application order)
  - returns [(ScreenEffectType, &[&str]); 59]

## ScreenEffectType (enum) (Clone, Copy, Debug, PartialEq, Eq, Hash)

Screen effect type. (declaration order is application order)

- `LensDistortion`: Barrel / pincushion lens distortion. (parameters = `[strength: negative for pincushion]`)
- `Bulge`: Bulge / pinch. (parameters = `[center x, center y, strength, radius]`)
- `Swirl`: Swirl. (parameters = `[center x, center y, turn count, radius]`)
- `Kaleidoscope`: Kaleidoscope. (parameters = `[segment count]`)
- `Mirror`: Symmetry. (parameters = `[0 horizontal / 1 vertical]`)
- `Ripple`: Water ripple. (parameters = `[center x, center y, frequency, speed]`)
- `HeatHaze`: Heat haze. (parameters = `[noise scale, speed]`)
- `Jitter`: Screen shake. (parameters = `[amplitude pixels, changes per second]`)
- `DoubleVision`: Double vision. (parameters = `[spacing, sway speed]`)
- `Pixelate`: Mosaic. (strength 0 → 1, parameters = `[largest block pixels]`)
- `Shockwave`: Shockwave ring distortion. (parameters = `[center x, center y, radius 0 ~ 1.5, width]`, color = ring light)
- `Wave`: Screen wave. (parameters = `[frequency, speed]`)
- `MotionBlur`: Directional blur. (parameters = `[angle radians, length pixels]`)
- `ZoomBlur`: Radial blur streaking toward the center. (parameters = `[center x, center y, length]`)
- `Blur`: Gaussian blur. (parameters = `[radius pixels]`)
- `GaussianBlur`: Standard-deviation Gaussian blur. (parameters = `[standard deviation in pixels]`, same meaning as CSS filter: blur(), separable linear sampling, up to 3 sigma)
- `TiltShift`: Tilt-shift. (parameters = `[focus y, focus width, radius pixels]`)
- `GodRays`: Light shafts. (parameters = `[center x, center y, threshold, decay]`, color = light color)
- `Bloom`: Bloom of bright areas. (parameters = `[threshold, strength scale, radius pixels]`)
- `Anamorphic`: Horizontal lens flare. (parameters = `[threshold, strength scale, width pixels]`, color = flare color)
- `Glitch`: Horizontal line offset + color split + block inversion. (parameters = `[line count, changes per second, offset width]`)
- `Vhs`: VHS tape. (shake + color bleeding + noise lines, parameters = `[shake, noise]`)
- `Chromatic`: Chromatic aberration. (parameters = `[scale]`)
- `WhiteBalance`: Color temperature / tint. (parameters = `[temperature -1 ~ 1, tint -1 ~ 1]`)
- `LiftGammaGain`: Lift / gamma / gain. (parameters = `[lift, gamma, gain]`)
- `ColorGrade`: Contrast / saturation / brightness + tint. (parameters = `[contrast, saturation, brightness]`, color = tint)
- `HueShift`: Hue rotation. (parameters = `[turn count: multiplied by strength]`)
- `SplitToning`: Split toning. (parameters.xyz = shadow color, color = highlight color, w = balance)
- `Tonemap`: ACES tone mapping. (parameters = `[exposure]`)
- `GradientMap`: Maps brightness between two colors. (parameters.xyz = dark color, color = bright color)
- `Sepia`: Sepia.
- `Grayscale`: Grayscale.
- `Posterize`: Posterize. (parameters = `[step count]`)
- `Dither`: Ordered dithering. (parameters = `[step count, pixel size]`)
- `Halftone`: Halftone dots. (parameters = `[grid pixels]`)
- `Sharpen`: Sharpen.
- `EdgeDetect`: Edge detection. (color = line color)
- `OldFilm`: Old film. (sepia + grain + scratches + flicker)
- `NightVision`: Night vision. (color = tint)
- `Invert`: Color inversion.
- `Scanline`: CRT curvature + scanlines + RGB mask. (parameters = `[curvature, scanline density]`)
- `Grain`: Film grain.
- `Rain`: Rain streaks. (parameters = `[line count, density, speed]`, color = streak color)
- `Fog`: Vertical fog. (parameters = `[start y, end y]`, color = fog color)
- `Vignette`: Vignette. (parameters = `[start distance, end distance]`, color = edge color)
- `Spotlight`: Darkening outside a spotlight. (parameters = `[center x, center y, radius, softness]`, color = outside color)
- `SpeedLines`: Focus lines. (parameters = `[center x, center y, density, speed]`, color = line color)
- `Letterbox`: Black bars at top and bottom / left and right. (parameters = `[vertical bar ratio, horizontal bar ratio]`, color = bar color)
- `PixelDissolve`: Block dissolve. (parameters = `[block count]`)
- `Wipe`: Directional wipe. (parameters = `[direction x, direction y, softness]`)
- `IrisWipe`: Circular iris. (parameters = `[center x, center y, softness]`)
- `DiamondWipe`: Diamond wipe. (parameters = `[softness]`)
- `ClockWipe`: Clock wipe. (parameters = `[softness]`)
- `Blinds`: Blinds. (parameters = `[line count, softness]`)
- `CheckerWipe`: Checkerboard. (parameters = `[cell count]`)
- `NoiseFade`: Noise fade. (parameters = `[noise scale, softness]`)
- `Burn`: As if burning. (parameters = `[noise scale, band width]`, color = cover color, the band is orange)
- `TvOff`: CRT turn-off. (squashes vertically into a bright line)
- `Fade`: Fade to a solid color. (color = target color)

- `pub fn get_name(&self) -> &'static str` (method, since 0.3.2): Returns the original name. (a string like "vignette")
  - returns &'static str: Original effect name. (camelCase, like "lensDistortion")
- `pub fn from_name(name: &str) -> Option<ScreenEffectType>` (static, since 0.3.2): Finds by the original name. (None for an unknown name)
  - `name` &str: Original effect name. (case-sensitive)
  - returns Option<ScreenEffectType>: The effect with that name. None for an unknown name.

  Example: Names, effects and parameter names

  ```rust
  use vanilla::ScreenEffectType;
  
  assert_eq!(ScreenEffectType::from_name("shockwave"), Some(ScreenEffectType::Shockwave));
  assert_eq!(ScreenEffectType::Shockwave.get_name(), "shockwave");
  assert_eq!(ScreenEffectType::Shockwave.get_parameter_names(), &["centerX", "centerY", "radius", "width"]);
  assert!(ScreenEffectType::Sepia.get_parameter_names().is_empty());
  assert_eq!(ScreenEffectType::from_name("unknown"), None);
  ```

- `pub fn get_parameter_names(&self) -> &'static [&'static str]` (method, since 0.3.2): Returns the list of parameter names. (SCREEN_EFFECT_PARAMETER_NAMES)
  - returns &'static [&'static str]: List of names in parameter x, y, z, w order. (0 ~ 4 of them, an empty list for effects without parameters)
