# graphics3d/toon/toonview3d (vanilla-engine 0.4.0)

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

Component that draws toon 3D inside the node rectangle. (ToonView3D of vanilla.js graphics3d/toon/toonview3d.js)
- In draw: maps the node's content area (0, 0, content size) with the current transform to a rectangle in drawing buffer pixels (the bounding rectangle if rotated),
  flushes the preceding 2D batch with Graphic::run_external_pass, forgets the cached state and clears depth, then sets the renderer's screen rectangle (set_screen_rect) and calls the draw function.
  When done, releases the screen rectangle and restores the 2D state with restore_render_state. (Both are restored even if the draw function panics)
- The renderer is built on the first draw. On devices that cannot build the shaders, it is not rebuilt and 2D is drawn with the fallback draw function (set_fallback_draw_callback).
  To share one renderer across multiple nodes, pass it in with set_renderer.
- The aspect ratio of the camera (get_camera_mut) is matched to the rectangle's ratio on every draw. 2D markers over 3D points are computed with the same camera's project_to_view.
- Depth clearing: inside a parent Mask's clip there is the Adreno 660 pitfall (Graphic::clear_depth_buffer header). The side that applies the clip
  calls clear_depth_buffer before begin_clip_rect, and this component is set with set_depth_cleared(false).
- Draw function: (renderer, camera, screen rectangle, GL, output). The screen rectangle is the rectangle to draw in the current framebuffer (pixels, top-left origin).
  The output (ToonViewOutput) is the framebuffer bound now (None means the default framebuffer) and the GL viewport inside it ([x, y, width, height], integers, bottom-left origin).
  Usually queue into ToonDrawQueue and call queue.draw(gl, renderer, camera), or draw between begin_frame_with_camera and end_frame.
  When using ToonPostProcess, call renderer.clear_screen_rect(), draw into a float render target, then give end the framebuffer and viewport of the output.
  (That way it lands in the right place regardless of render scale or transparency layers)
- Render scale (set_render_scale, 0.05 ~ 4, default 1): if not 1, only 3D is cleared to transparent and drawn into a target of the content area screen size x scale (depth 24, 4 samples if the default framebuffer
  is multisampled), then stretched on through the 2D drawing path with linear filtering and source-over. (UI stays at device pixels,
  same meaning as Unity URP renderScale and Unreal screen percentage) The target uses its own depth, so continuing the earlier 3D depth with set_depth_cleared(false) only works at scale 1.
  The target is deleted when detached from the node (detach) and when dropped (Drop).
- Differences from the original:
  - The shared renderer is `Rc<RefCell<ToonRenderer>>`. The original shares object references. While drawing, the renderer is borrowed and passed to the draw function.
  - outputFramebuffer, outputViewport of the original screen rectangle object are output_framebuffer, output_viewport of the fifth argument ToonViewOutput.

## ToonViewDrawCallback (type)

Draw function. (renderer, camera, screen rectangle, GL, output)

```rust
pub type ToonViewDrawCallback = Box<dyn FnMut(&mut ToonRenderer, &Camera3D, Rect, &GlContext, ToonViewOutput)>
```

## ToonViewOutput (struct) (Clone, Copy, Debug, PartialEq, Eq)

Output of the draw function. (outputFramebuffer, outputViewport of the original screen rectangle object)
- Anything that outputs separately, such as ToonPostProcess::end, must output with these two to land in the right place regardless of render scale or transparency layers.

Example: Output drawn to the default framebuffer

```rust
use vanilla::ToonViewOutput;

let output = ToonViewOutput { output_framebuffer: None, output_viewport: [0, 0, 960, 540] };
assert!(output.output_framebuffer.is_none());
assert_eq!(output.output_viewport[2], 960);
```

- `pub output_framebuffer: Option<GlFramebuffer>` (field, since 0.4.0): The framebuffer bound now. (None means the default framebuffer)
  - returns Option<GlFramebuffer>
- `pub output_viewport: [i32; 4]` (field, since 0.4.0): The GL viewport inside it. ([x, y, width, height], integer pixels, bottom-left origin)
  - returns [i32; 4]

## ToonViewFallbackDrawCallback (type)

Fallback draw function. (2D on devices where the renderer could not be built, the Graphic with the node transform applied and the content size)

```rust
pub type ToonViewFallbackDrawCallback = Box<dyn FnMut(&mut Graphic, Vector2)>
```

## ToonView3D (struct) (Default, Component, Drop)

Component that draws toon 3D inside the node rectangle. (see the header comment)

Example: Draw a toon 3D scene inside a node rectangle

```rust
use vanilla::{create_sphere_geometry, Camera3D, GlContext, Matrix4, MeshBuilder, NodeTree, Rect, ToonDrawOptions, ToonDrawQueue, ToonMesh, ToonPartOptions, ToonRenderer, ToonView3D, ToonViewOutput, Vector3};

let mut node_tree = NodeTree::new();
let root_id = node_tree.get_root_id();
let view_id = node_tree.create_child(root_id, "view");
node_tree[view_id].set_content_size_xy(320.0, 240.0);
let view = node_tree[view_id].add_component(ToonView3D::new());
view.get_camera_mut().set_perspective(0.8, 0.1, 100.0);
view.get_camera_mut().look_at(Vector3::create(0.0, 1.5, 3.0), Vector3::create(0.0, 0.5, 0.0), Vector3::create(0.0, 1.0, 0.0));
let mut builder = MeshBuilder::new();
builder.add_part(&create_sphere_geometry(0.5, 24, 16, std::f64::consts::PI), &Matrix4::create_translation(0.0, 0.5, 0.0), "#f0b080", ToonPartOptions::default());
let arrays = builder.read_arrays();
let mut mesh: Option<ToonMesh> = None;
view.set_draw_callback(Some(Box::new(move |renderer: &mut ToonRenderer, camera: &Camera3D, _screen_rect: Rect, gl: &vanilla::GlContext, _output: ToonViewOutput| {
	if mesh.is_none() {
		mesh = renderer.create_mesh(gl, &arrays);
	}
	if let Some(mesh) = mesh.as_ref() {
		let mut queue = ToonDrawQueue::new();
		queue.add_mesh(mesh, &Matrix4::create_identity(), ToonDrawOptions::default());
		queue.draw(gl, renderer, camera);
	}
})));
assert!(view.get_renderer().is_none());
assert!(view.is_depth_cleared());
assert_eq!(view.get_render_scale(), 1.0);
```

- `pub fn new() -> ToonView3D` (constructor, since 0.4.0): Constructor. (clears depth)
  - returns ToonView3D: New component. (The renderer is built on the first draw)
- `pub fn set_render_scale(&mut self, render_scale: f64)` (method, since 0.4.0): Sets the render scale. (Only 3D is drawn into a target at this scale and stretched on with linear filtering; UI stays at device pixels. Same meaning as Unity URP renderScale and Unreal screen percentage)
  - At 1 (default) it draws directly to the screen. Otherwise it clears a target (content area screen size x scale, with depth, 4 samples if the default framebuffer is multisampled)
    to transparent, draws into it, and composites it with source-over through the 2D drawing path. (It follows 2D clipping, and the 2D below shows through where 3D does not cover)
  - The target uses its own depth, so continuing the earlier 3D depth with set_depth_cleared(false) only works at scale 1.
  - The draw function must output with the framebuffer and viewport of the output it receives (ToonViewOutput) to land in the right place regardless of scale. (Such as ToonPostProcess::end)
  - `render_scale` f64: Scale. (0.05 ~ 4, 1 draws directly to the screen, 1 if not a finite number)

  Example: Drawing only the 3D at half resolution

  ```rust
  use vanilla::{NodeTree, ToonView3D};
  
  let mut node_tree = NodeTree::new();
  let root_id = node_tree.get_root_id();
  let view_id = node_tree.create_child(root_id, "view");
  node_tree[view_id].set_content_size_xy(320.0, 240.0);
  let view = node_tree[view_id].add_component(ToonView3D::new());
  view.set_render_scale(0.5);
  assert_eq!(view.get_render_scale(), 0.5);
  ```

- `pub fn get_render_scale(&self) -> f64` (method, since 0.4.0): Returns the render scale.
  - returns f64: Scale. (1 draws directly to the screen)
- `pub fn set_draw_callback(&mut self, draw_callback: Option<ToonViewDrawCallback>)` (method, since 0.4.0): Sets the draw function. (nothing is drawn when None)
  - `draw_callback` Option<ToonViewDrawCallback>: Function that receives (renderer, camera, screen rectangle, GL, output). (Draws nothing if None)
The screen rectangle is the rectangle to draw in the current framebuffer (pixels, top-left origin), and the output is the framebuffer bound now and the GL viewport inside it (bottom-left origin).
- `pub fn set_fallback_draw_callback(&mut self, fallback_draw_callback: Option<ToonViewFallbackDrawCallback>)` (method, since 0.4.0): Sets the fallback draw function. (2D on devices where the renderer could not be built)
  - `fallback_draw_callback` Option<ToonViewFallbackDrawCallback>: Function that receives (graphic, content_size). Called on devices where the renderer could not be built. (Draws nothing if None)
- `pub fn set_depth_cleared(&mut self, is_depth_cleared: bool)` (method, since 0.4.0): Sets whether to clear depth before drawing. (default true)
  - `is_depth_cleared` bool: Whether to clear depth before drawing. (Inside a parent Mask clip, leave it false and let the clipping side clear)
- `pub fn is_depth_cleared(&self) -> bool` (method, since 0.4.0): Returns whether depth is cleared before drawing.
  - returns bool: true if depth is cleared before drawing.
- `pub fn set_renderer(&mut self, renderer: Option<Rc<RefCell<ToonRenderer>>>)` (method, since 0.4.0): Sets the renderer. (when multiple nodes share one, if None it is built on the first draw)
  - `renderer` Option<Rc<RefCell<ToonRenderer>>>: Renderer to share. (Built on the first draw if None)
- `pub fn get_renderer(&self) -> Option<&Rc<RefCell<ToonRenderer>>>` (method, since 0.4.0): Returns the renderer. (None if not yet built or could not be built)
  - returns Option<&Rc<RefCell<ToonRenderer>>>: Renderer. (None if not built yet or could not be built)
- `pub fn is_renderer_failed(&self) -> bool` (method, since 0.4.0): Whether the renderer could not be built.
  - returns bool: true if the renderer could not be built. (Then the fallback draw function draws)
- `pub fn get_camera(&self) -> &Camera3D` (method, since 0.4.0): Returns the camera.
  - returns &Camera3D: The camera of this component. (Its aspect ratio is matched to the rectangle on every draw)
- `pub fn get_camera_mut(&mut self) -> &mut Camera3D` (method, since 0.4.0): Returns the camera. (for setting the projection and view position)
  - returns &mut Camera3D: The camera of this component. (Its aspect ratio is matched to the rectangle on every draw)
- `pub fn get_screen_rect(&self) -> Rect` (method, since 0.4.0): Returns the screen rectangle of the last draw. (drawing buffer pixels)
  - returns Rect: Rectangle in drawing buffer pixels. (Top left is the origin, an empty rectangle if not drawn yet)
- `pub fn read_renderer(&mut self, graphic: &mut Graphic) -> Option<Rc<RefCell<ToonRenderer>>>` (method, since 0.4.0): Reads the renderer. (builds it the first time, None if it cannot be built, and it is not rebuilt)
  - `graphic` &mut Graphic: Graphic. (On the first call, builds the renderer with its GL)
  - returns Option<Rc<RefCell<ToonRenderer>>>: Renderer. (None if it could not be built)
- `pub fn refresh_screen_rect(&mut self, graphic: &Graphic, content_size: Vector2)` (method, since 0.4.0): Content area to a rectangle in drawing buffer pixels. (Bounding rectangle of the four corners mapped with the current transform)
  - `graphic` &Graphic: Graphic. (Reads the current transform)
  - `content_size` Vector2: Size of the content area.
