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

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

Toon draw queue. (ToonDrawQueue of vanilla.js graphics3d/toon/toondrawqueue.js)
- Holds the models to draw in a frame, then draws them in order with ToonRenderer.
- Order: (line target of the screen-space outline) → stage BeforeOpaque → opaque bodies → AfterOpaque → outline shells of opaque things → screen-space outline → AfterOutline
  → transparent things (farthest from the camera first, depth not written) → AfterTransparent.
  Outlines are drawn together after all bodies to switch programs less, and transparent things are blended last from the farthest so what is behind shows through.
- Transparent things: those whose options alpha or tint_color alpha is below 1, or whose blend_mode is not Alpha. Their outlines are drawn with them too (has_outline).
- Groups: transparent things with the same options group are sorted as one lump by the middle depth (average of the members) and drawn in the order they were added.
  If even one member of a group has is_depth_prepassed, that lump draws depth first and then paints color only on pixels with the same depth (LEQUAL).
  A hologram made of several overlapping parts shows through as one lump instead of being doubly bright. Lumps are drawn farthest first so they show through each other.
- Screen-space outline: if set_screen_outline(ToonScreenOutline) is given, draw draws opaque things into the line target before the bodies and blends it after the outline shells.
  The ID is the options line_id (the order added + 1 if None, for instances the line_id of ToonInstance, for instance buffers the instanceLineId slot of the layout comes first), and per model has_screen_outline and has_crease_line turn it off and on.
  Transparent things are not drawn into the line target. If there is a screen rectangle (ToonRenderer::set_screen_rect), that rectangle is used as the drawing area of the line target.
  The Rust version borrows the outline as &'a mut and keeps it in a RefCell. (Modified in draw(&self))
- Ambient occlusion: give set_post_process(ToonPostProcess) and turn on set_ambient_occlusion in the post process, and it is computed after the line target and before bodies, set on the renderer and cleared after end_frame. (without outlines, only the line target is drawn, with no lines)
- Stage callbacks: callback(gl, renderer) of add_pass(stage, callback) is called at that point. After the call, the renderer sets the frame's draw state again.
- Instance batches (add_mesh_instanced) draw body and outline at once if opaque, and if transparent are sorted as one lump by the center of the instance positions.
  It uploads every time it culls and draws per instance. (the body, the shadow and the line board upload the same array separately) For long-lived instances, share a buffer uploaded once with add_mesh_instance_buffer.
- An instance buffer (add_mesh_instance_buffer) is in the style of Unity Graphics.RenderMeshInstanced with GraphicsBuffer and Godot MultiMesh. It culls the whole buffer by its bounds and does not upload again.
- Shadows: draw_shadows(gl, renderer, shadow_map) draws only opaque things whose casts_shadow is true into the shadow depth. Call it before draw.
  For point light and spotlight shadows, draw_local_shadows(gl, renderer, shadow_atlas) draws the same things per atlas tile. (Set on the renderer with set_local_shadows)
  Follows the shadow target's set_update_mode(ShadowUpdateMode). The default OnChange does not redraw when the lights and casters are unchanged, bakes casters that stay unchanged for a long time, and draws only the moving ones over them. (The screen is the same as drawing every frame)
- Use: every frame clear() → add_mesh / add_mesh_instanced / add_mesh_instance_buffer / add_pass → (draw_shadows) → draw(gl, renderer, camera) or draw_with_matrices(gl, renderer, view matrix, projection matrix)
  draw calls renderer.begin_frame_with_camera and end_frame by itself. draw_with_matrices calls begin_frame_with_matrices. (Orthographic or raw matrix camera)
  The screen rectangle (ToonRenderer::set_screen_rect) is set before that. clear empties all added models and stage callbacks. (The screen-space outline is kept)
- The original holds what is added as object references. The Rust version borrows the models, instance lists and stage callbacks, so the queue has their lifetime 'a. (Build a new one every frame, or add again after clear)
  Stage callbacks are FnMut, so they are kept in a RefCell and called in draw(&self).

## ToonPassCallback (type)

Stage callback. (gl, renderer)

```rust
pub type ToonPassCallback<'a> = Box<dyn FnMut(&GlContext, &mut ToonRenderer) + 'a>
```

## ToonDrawQueue (struct) (Default)

Toon draw queue. (see the header comment)

Example: Decide the outline form per model

```rust
use vanilla::{create_box_geometry, create_faceted_chunk_geometry, Camera3D, Matrix4, MeshBuilder, ToonDrawOptions, ToonDrawQueue, ToonPartOptions, ToonRenderer, ToonScreenOutline, Vector3};

fn draw_scene(gl: &vanilla::GlContext) -> Result<(), String> {
	let mut renderer = ToonRenderer::new(gl)?;
	let mut floor_builder = MeshBuilder::new();
	floor_builder.add_part(&create_box_geometry(8.0, 0.2, 8.0), &Matrix4::create_translation(0.0, -0.1, 0.0), "#708090", ToonPartOptions { has_outline: false, ..ToonPartOptions::default() });
	let floor_mesh = renderer.create_mesh(gl, &floor_builder.read_arrays()).ok_or("floor mesh")?;
	let mut gem_builder = MeshBuilder::new();
	gem_builder.add_part(&create_faceted_chunk_geometry(0.5, &[1.0, 0.9, 1.1], [1.0, 1.0, 1.0]), &Matrix4::create_translation(0.0, 0.5, 0.0), "#a0c0ff", ToonPartOptions { has_outline: false, ..ToonPartOptions::default() });
	let gem_mesh = renderer.create_mesh(gl, &gem_builder.read_arrays()).ok_or("gem mesh")?;
	let mut camera = Camera3D::new();
	camera.set_perspective(0.8, 0.1, 100.0);
	camera.look_at(Vector3::create(0.0, 2.0, 4.0), Vector3::create(0.0, 0.4, 0.0), Vector3::create(0.0, 1.0, 0.0));
	let mut screen_outline = ToonScreenOutline::new(gl)?;
	let mut queue = ToonDrawQueue::new();
	queue.set_screen_outline(Some(&mut screen_outline));
	queue.add_mesh(&floor_mesh, &Matrix4::create_identity(), ToonDrawOptions { line_id: Some(1), has_screen_outline: false, ..ToonDrawOptions::default() });
	queue.add_mesh(&gem_mesh, &Matrix4::create_identity(), ToonDrawOptions { line_id: Some(2), has_crease_line: false, ..ToonDrawOptions::default() });
	queue.draw(gl, &mut renderer, &camera);
	Ok(())
}
```

- `pub fn new() -> ToonDrawQueue<'a>` (constructor, since 0.4.0): Constructor.
  - returns ToonDrawQueue<'a>: An empty draw queue. (With no screen-space outline handed over)
- `pub fn clear(&mut self)` (method, since 0.4.0): Clears. (stage callbacks are cleared too, the screen-space outline stays)
- `pub fn get_item_count(&self) -> usize` (method, since 0.4.0): Returns the queued count.
  - returns usize: Number of added models and instance batches.
- `pub fn set_screen_outline(&mut self, screen_outline: Option<&'a mut ToonScreenOutline>)` (method, since 0.4.0): Hands over a screen-space outline. (draw renders the line target and blends it after the outline shells, None hands over nothing)
  - `screen_outline` Option<&'a mut ToonScreenOutline>: ToonScreenOutline or None. (Borrowed for the lifetime of the queue)
- `pub fn has_screen_outline(&self) -> bool` (method, since 0.4.0): Whether a screen-space outline was handed over.
  - returns bool: true if one is handed over.
- `pub fn set_post_process(&mut self, post_process: Option<&'a mut ToonPostProcess>)` (method, since 0.4.0): Hands over the toon post process. (original setPostProcess; if ambient occlusion is on, draw computes it after the line target and before bodies, sets it on the renderer and clears it after end_frame, None hands over nothing)
  - With a screen-space outline it uses that line target; otherwise it draws only normals and depth with the post process prepass (get_ambient_occlusion_prepass).
  - `post_process` Option<&'a mut ToonPostProcess>: ToonPostProcess or None. (borrowed for the lifetime of the queue)
- `pub fn has_post_process(&self) -> bool` (method, since 0.4.0): Whether a toon post process is handed over. (whether the original getPostProcess is not null)
  - returns bool: true if one is handed over.
- `pub fn add_pass(&mut self, stage: ToonDrawStage, callback: impl FnMut(&GlContext, &mut ToonRenderer) + 'a)` (method, since 0.4.0): Adds a stage callback. (calls callback(gl, renderer) at the ToonDrawStage position, in the order added)
  - `stage` ToonDrawStage: ToonDrawStage.
  - `callback` impl FnMut(&GlContext, &mut ToonRenderer) + 'a: Receives (gl, renderer). After the call, the renderer sets the frame's draw state again.
- `pub fn add_mesh(&mut self, mesh: &'a ToonMesh, model_matrix: &Matrix4, options: ToonDrawOptions<'a>)` (method, since 0.4.0): Queues one model.
  - `mesh` &'a ToonMesh: Result of ToonRenderer::create_mesh.
  - `model_matrix` &Matrix4: Model matrix. (Copied when added)
  - `options` ToonDrawOptions<'a>: Draw options of ToonRenderer::draw_mesh. (This queue also reads casts_shadow, group, is_depth_prepassed, line_id, has_screen_outline, has_crease_line)
- `pub fn add_mesh_instanced(&mut self, mesh: &'a ToonMesh, instance_list: &'a [ToonInstance], options: ToonDrawOptions<'a>)` (method, since 0.4.0): Queues multiple instances of the same model. (GPU instancing, not queued if empty)
  - `mesh` &'a ToonMesh: Result of ToonRenderer::create_mesh.
  - `instance_list` &'a [ToonInstance]: List of ToonInstance. (Model matrix, tint color, line ID)
  - `options` ToonDrawOptions<'a>: Same as add_mesh.
- `pub fn add_mesh_instance_buffer(&mut self, mesh: &'a ToonMesh, instance_buffer: &'a ToonInstanceBuffer, instance_count: usize, options: ToonDrawOptions<'a>)` (method, since 0.4.0): Queue several of the same mesh with a persistent instance buffer. (the body, the outline shell, the shadow and the line board share one GPU buffer and do not upload again; the original addMeshInstanceBuffer)
  - Create the buffer with ToonRenderer::create_instance_buffer and change it with update_instance_buffer or update_instance_buffer_range. The whole buffer is culled by its bounds.
  - The line id of each instance is the instanceLineId slot of the layout, otherwise options.line_id (None means queue order + 1).
  - The shadow cache (ShadowUpdateMode::OnChange) notices changes through get_generation of the buffer.
  - `mesh` &'a ToonMesh: Result of ToonRenderer::create_mesh.
  - `instance_buffer` &'a ToonInstanceBuffer: The result of ToonRenderer::create_instance_buffer. (borrowed for the lifetime of the queue)
  - `instance_count` usize: Number of instances to draw. (clamped to the buffer, nothing is queued for 0)
  - `options` ToonDrawOptions<'a>: Same as add_mesh.

  Example: Draw the miner rock field from a buffer uploaded once and change just one

  ```rust
  use vanilla::{create_octahedron_geometry, Camera3D, Matrix4, MeshBuilder, ToonBufferUsage, ToonDrawOptions, ToonDrawQueue, ToonPartOptions, ToonRenderer, ToonScreenOutline, Vector3};
  
  fn draw_rocks(gl: &vanilla::GlContext) -> Result<(), String> {
  	let mut renderer = ToonRenderer::new(gl)?;
  	let mut builder = MeshBuilder::new();
  	builder.add_part(&create_octahedron_geometry(0.3), &Matrix4::create_identity(), "#a89880", ToonPartOptions { has_outline: true, ..ToonPartOptions::default() });
  	let rock_mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("mesh failed")?;
  	let instance_layout = renderer.create_instance_layout(&[("instanceMatrix", 16), ("instanceTint", 4), ("instanceLineId", 1)])?;
  	let float_count = instance_layout.get_float_count();
  	let mut data: Vec<f32> = Vec::new();
  	for index in 0..25 {
  		data.extend_from_slice(Matrix4::create_translation((index % 5) as f64 - 2.0, 0.0, (index / 5) as f64 - 2.0).get_elements());
  		data.extend_from_slice(&[1.0, 1.0, 1.0, 1.0, 1.0 + index as f32]);
  	}
  	let instance_buffer = renderer.create_instance_buffer(gl, &instance_layout, &data, ToonBufferUsage::Dynamic)?;
  	let mut camera = Camera3D::new();
  	camera.set_perspective(0.8, 0.1, 50.0);
  	camera.look_at(Vector3::create(0.0, 5.0, 6.0), Vector3::create(0.0, 0.0, 0.0), Vector3::create(0.0, 1.0, 0.0));
  	let mut outline = ToonScreenOutline::new(gl)?;
  	let mut queue = ToonDrawQueue::new();
  	queue.set_screen_outline(Some(&mut outline));
  	queue.add_mesh_instance_buffer(&rock_mesh, &instance_buffer, 25, ToonDrawOptions::default());
  	queue.draw(gl, &mut renderer, &camera);
  	let mut broken_rock = data[12 * float_count..13 * float_count].to_vec();
  	broken_rock[16..20].copy_from_slice(&[0.5, 0.5, 0.5, 1.0]);
  	renderer.update_instance_buffer_range(gl, &instance_buffer, 12, &broken_rock)?;
  	queue.draw(gl, &mut renderer, &camera);
  	Ok(())
  }
  ```

- `pub fn draw_shadows(&self, gl: &GlContext, renderer: &mut ToonRenderer, shadow_map: &ShadowMap)` (method, since 0.4.0): Draws shadow depth. (only opaque ones whose casts_shadow is true, restores the previous framebuffer and viewport)
  - Follows the update mode of shadow_map.set_update_mode. (The default OnChange does not draw when the lights and casters are unchanged)
  - `gl` &GlContext: GL context.
  - `renderer` &mut ToonRenderer: ToonRenderer.
  - `shadow_map` &ShadowMap: ShadowMap.
- `pub fn draw_local_shadows(&self, gl: &GlContext, renderer: &mut ToonRenderer, shadow_atlas: &ShadowAtlas)` (method, since 0.4.0): Draws point light and spotlight shadow depth. (Opaque ones with casts_shadow true, per atlas tile, the previous framebuffer and viewport are restored)
  - Follows the update mode of shadow_atlas.set_update_mode. (The default OnChange does not draw when the lights and casters are unchanged)
  - `gl` &GlContext: GL context.
  - `renderer` &mut ToonRenderer: ToonRenderer.
  - `shadow_atlas` &ShadowAtlas: ShadowAtlas. (One on which update_lights was called)
- `pub fn draw(&self, gl: &GlContext, renderer: &mut ToonRenderer, camera: &Camera3D)` (method, since 0.4.0): Draws the queued items. (starting with the line target if there is a screen-space outline, calls begin_frame_with_camera and end_frame itself)
  - `gl` &GlContext: GL context.
  - `renderer` &mut ToonRenderer: ToonRenderer.
  - `camera` &Camera3D: Camera3D.
- `pub fn draw_with_matrices(&self, gl: &GlContext, renderer: &mut ToonRenderer, view_matrix: &Matrix4, projection_matrix: &Matrix4)` (method, since 0.4.0): Draws the queued items with view and projection matrices. (without Camera3D, calls begin_frame_with_matrices and end_frame itself)
  - `gl` &GlContext: GL context.
  - `renderer` &mut ToonRenderer: ToonRenderer.
  - `view_matrix` &Matrix4: View matrix.
  - `projection_matrix` &Matrix4: Projection matrix.

## ToonDrawStage (enum) (Clone, Copy, Debug, PartialEq, Eq)

Stages of the draw queue. (positions where add_pass callbacks are called)
- BeforeOpaque: before opaque bodies. (planar mirror reflections, sky)
- AfterOpaque: after opaque bodies, before outline shells.
- AfterOutline: after outline shells and the screen-space outline, before translucent ones.
- AfterTransparent: after translucent ones. (effects)

- `BeforeOpaque`: Before opaque bodies. (Planar mirror reflections, sky)
- `AfterOpaque`: After opaque bodies, before outline shells.
- `AfterOutline`: After outline shells and the screen-space outline, before transparent things.
- `AfterTransparent`: After transparent things. (Effects)
