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

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

Toon material and instance layout. (vanilla.js graphics3d/toon/toonmaterial.js)
- ToonMaterial: shader chunks inserted into ToonRenderer's body shader, the per-game extension point.
  Only patterns and effects that the engine's standard features (textures, light, tint, blending) cannot do go into chunks. Slots without a chunk get the engine's empty functions.
  - uniform_chunk: goes into the top slot of the fragment shader. Write uniforms, constants, functions and the ins exported by the vertex chunk.
  - surface_chunk: defines void applySurface(inout ToonSurface surface). The engine calls it after computing the vertex color, textures and decal, before tint and light.
    ToonSurface { vec3 baseColor (sRGB in the gamma color space, linear in the linear color space; convert sRGB colors with toSurfaceColor before mixing them in), float alpha, vec3 emission (linear), vec3 normal (world, unit), float glow (vertex glow), bool isUnlit,
                  vec4 detail (vertex pattern number and pattern color), vec2 uv, vec2 uv1 (second UV, (0, 1) if none), vec3 localPosition (model coordinates), vec3 worldPosition, vec3 viewDirection (from the surface toward the camera, unit),
                float shadeOffset (value added to the received light amount, moves the shade boundary), float specularMask (highlight multiplier), float rimMask (rim light multiplier) }
  - light_chunk: defines void applyLight(ToonSurface surface, inout ToonLighting lighting). The engine calls it after gathering the sun, ambient light, fill, point lights and spotlights, highlight and rim, before combining.
    ToonLighting { vec3 irradiance (light multiplied into the base color, after the shade ramp), vec3 specular (highlight to add), vec3 rim (rim light to add), float shadow (0 ~ 1), float sunLevel (brightness level of the received sun 0 ~ 1) }
  Combining is base color x irradiance + specular x specularMask + rim x rimMask + glow.
  - vertex_chunk: goes into the top slot of the vertex shaders (all three: body, outline, shadow depth) and defines void applyVertex(inout ToonVertex vertex). Called before moving into world space.
    ToonVertex { vec3 localPosition, vec3 localNormal, vec3 color, vec2 material, vec4 detail, vec2 uv, vec2 uv1, vec4 tint, vec4 emissive, mat4 modelMatrix }
    User attributes of the instance layout (ToonInstanceLayout) are read as ins of that name. Since it goes into all three, do not use outs that exist only in the body. (Use the fields of vertex instead of vertex attribute names)
    Normals are moved by mat3(modelMatrix). If the scale is not uniform, divide localNormal by the square of that scale beforehand.
  - The shader has the engine's toLinear(vec3) (sRGB to linear: pow 2.2 in the gamma color space, the standard sRGB curve in the linear color space), toSurfaceColor(vec3) (sRGB into the space of baseColor) and RECIPROCAL_PI.
    In the linear color space (ColorSpace::Linear), the source has #define VANILLA_COLOR_SPACE_LINEAR 1 and the color textures the engine binds are decoded to linear by the GPU. (is_color_data in ToonTextureOptions)
  - Textures are passed with the draw's textures ([(uniform name, texture)]). The engine binds them in order to units it does not use (from 8, up to TOON_MAXIMUM_MATERIAL_TEXTURES) and puts the unit into the sampler2D uniform of that name.
  - Uniforms that differ per draw are written in on_before_draw(program, gl, ToonProgramKind). The engine rewrites its own uniforms, so write only the material's.
- ToonInstanceLayout: the attribute order of one instance. (used by ToonRenderer::create_instance_buffer and draw_mesh_instance_buffer)
  Each attribute is (name, size). The engine reads instanceMatrix (16) as the model matrix and instanceTint (4) as the multiplied color.
  instanceMatrix is read as an affine 3x4, and the four values of its bottom row (elements 3, 7, 11, 15) are the emission of that instance (sRGB r, g, b and linear intensity, vertex.emissive). Storing Matrix4 elements as they are gives no emission.
  instanceLineId (1) is the per-instance line id of the screen-space outline. (ToonScreenOutline::draw_mesh_instance_buffer, ToonDrawQueue::add_mesh_instance_buffer)
  It uses the last user attribute location (TOON_INSTANCE_LINE_ID_LOCATION), so with it one fewer user attribute fits. A vertex chunk can read it by that name too.
  Other names are user attributes. Up to TOON_MAXIMUM_INSTANCE_ATTRIBUTES, size 1 ~ 4. The vertex chunk reads them as ins of that name. (locations from 13)
  Without instanceMatrix the model matrix is the identity matrix. The vertex chunk builds vertex.modelMatrix. Without instanceTint the tint is 1.
- The original builds a material from an options object ({ uniformChunk, ... }). The Rust version passes ToonMaterialChunks.

Example: Put stripes in with a surface chunk and pass a texture and uniforms per draw

```rust
use vanilla::{create_box_geometry, GlContext, Matrix4, MeshBuilder, ShaderProgram, ToonDrawOptions, ToonMaterialChunks, ToonPartOptions, ToonProgramKind, ToonRenderer, ToonTextureOptions, Vector3};

fn draw_stripe(gl: &vanilla::GlContext) -> Result<(), String> {
	let mut renderer = ToonRenderer::new(gl)?;
	let material = renderer.create_material(ToonMaterialChunks {
		name: String::from("stripe"),
		uniform_chunk: String::from("uniform sampler2D stripeTexture;\nuniform float stripeShift;\n"),
		surface_chunk: String::from("void applySurface(inout ToonSurface surface) {
			float stripe = texture(stripeTexture, vec2(surface.localPosition.y * 4.0 + stripeShift, 0.5)).r;
			surface.baseColor *= mix(0.5, 1.0, stripe);
		}"),
		..ToonMaterialChunks::default()
	});
	let stripe_texture = renderer.create_texture(gl, 2, 1, &[255, 255, 255, 255, 0, 0, 0, 255], ToonTextureOptions { is_mipmapped: false, ..ToonTextureOptions::default() })?;
	let mut builder = MeshBuilder::new();
	builder.add_part(&create_box_geometry(1.0, 1.0, 1.0), &Matrix4::create_identity(), "#80c0e0", ToonPartOptions::default());
	let mesh = renderer.create_mesh(gl, &builder.read_arrays()).ok_or("mesh failed")?;
	let view_matrix = Matrix4::create_look_at(Vector3::create(2.0, 2.0, 3.0), Vector3::create(0.0, 0.0, 0.0), Vector3::create(0.0, 1.0, 0.0));
	renderer.begin_frame_with_matrices(gl, &view_matrix, &Matrix4::create_perspective(0.8, 1.0, 0.1, 20.0));
	let set_shift = |program: &ShaderProgram, gl: &vanilla::GlContext, _kind: ToonProgramKind| unsafe {
		gl.uniform_1_f32(program.get_uniform_location(gl, "stripeShift").as_ref(), 0.25);
	};
	renderer.draw_mesh(gl, &mesh, &Matrix4::create_identity(), ToonDrawOptions {
		material: Some(&material),
		textures: &[("stripeTexture", stripe_texture)],
		on_before_draw: Some(&set_shift),
		..ToonDrawOptions::default()
	});
	renderer.end_frame(gl);
	Ok(())
}
```

## ToonMaterialChunks (struct) (Clone, Debug, Default)

Shader snippets of the material. (the engine's empty functions for empty text)

Example: Material with only a surface chunk

```rust
use vanilla::{ToonMaterial, ToonMaterialChunks};

let material = ToonMaterial::new(ToonMaterialChunks {
	name: String::from("darken"),
	surface_chunk: String::from("void applySurface(inout ToonSurface surface) { surface.baseColor *= 0.5; }"),
	..ToonMaterialChunks::default()
});
assert_eq!(material.get_name(), "darken");
assert!(material.get_light_chunk().is_empty());
```

- `pub name: String` (field, since 0.4.0): Name. (used in notice messages)
  - returns String
- `pub uniform_chunk: String` (field, since 0.4.0): Uniform chunk. (top slot of the fragment shader, uniforms, constants, functions and the ins exported by the vertex chunk)
  - returns String
- `pub surface_chunk: String` (field, since 0.4.0): Surface chunk. (defines void applySurface(inout ToonSurface surface))
  - returns String
- `pub light_chunk: String` (field, since 0.4.0): Light chunk. (defines void applyLight(ToonSurface surface, inout ToonLighting lighting))
  - returns String
- `pub vertex_chunk: String` (field, since 0.4.0): Vertex chunk. (top slot of the three vertex shaders, defines void applyVertex(inout ToonVertex vertex))
  - returns String

## ToonMaterial (struct) (Clone, Debug)

Toon material. (see the header comment, shader snippets and an ID)

Example: Grow the rim with a light chunk and tilt with a vertex chunk

```rust
use vanilla::{ToonMaterialChunks, ToonRenderer};

fn prepare_lean_rim(gl: &vanilla::GlContext, renderer: &mut ToonRenderer) -> Result<(), String> {
	let material = renderer.create_material(ToonMaterialChunks {
		name: String::from("leanRim"),
		light_chunk: String::from("void applyLight(ToonSurface surface, inout ToonLighting lighting) { lighting.rim *= 2.0; }"),
		vertex_chunk: String::from("void applyVertex(inout ToonVertex vertex) { vertex.localPosition.x += vertex.localPosition.y * 0.2; }"),
		..ToonMaterialChunks::default()
	});
	if !renderer.prepare_material(gl, Some(&material), None) {
		return Err(format!("shader failed: {}", material.get_name()));
	}
	Ok(())
}
```

- `pub fn new(chunks: ToonMaterialChunks) -> ToonMaterial` (constructor, since 0.4.0): Constructor.
  - `chunks` ToonMaterialChunks: Name and shader chunks. (slots with empty text get the engine's empty functions)
  - returns ToonMaterial: New material. (the ID differs per material)
- `pub fn get_id(&self) -> u32` (method, since 0.4.0): Returns the ID. (different per material)
  - returns u32: Material number.
- `pub fn get_name(&self) -> &str` (method, since 0.4.0): Returns the name. (used in notification messages)
  - returns &str: Name. (Empty text if not given)
- `pub fn get_uniform_chunk(&self) -> &str` (method, since 0.4.0): Returns the uniform chunk.
  - returns &str: Uniform chunk. (Empty text if none)
- `pub fn get_surface_chunk(&self) -> &str` (method, since 0.4.0): Returns the surface chunk.
  - returns &str: Surface chunk. (Empty text if none)
- `pub fn get_light_chunk(&self) -> &str` (method, since 0.4.0): Returns the light chunk.
  - returns &str: Light chunk. (Empty text if none)
- `pub fn get_vertex_chunk(&self) -> &str` (method, since 0.4.0): Returns the vertex chunk.
  - returns &str: Vertex chunk. (Empty text if none)

## ToonInstanceAttribute (struct) (Clone, Debug, PartialEq, Eq)

One instance attribute. (offset is in values, location is Some only for user attributes)

Example: Read the locations of user attributes

```rust
use vanilla::ToonInstanceLayout;

let layout = ToonInstanceLayout::new(&[("instanceMatrix", 16), ("instanceShape", 4)]).unwrap();
let attributes = layout.get_attributes();
assert_eq!(attributes[0].location, None);
assert_eq!((attributes[1].offset, attributes[1].location), (16, Some(13)));
```

- `pub name: String` (field, since 0.4.0): Name. (the in name in the shader, the engine reads instanceMatrix and instanceTint)
  - returns String
- `pub size: usize` (field, since 0.4.0): Number of floats. (instanceMatrix 16, instanceTint 4, user attributes 1 ~ 4)
  - returns usize
- `pub offset: usize` (field, since 0.4.0): Position within one instance. (in floats)
  - returns usize
- `pub location: Option<u32>` (field, since 0.4.0): Attribute location. (Some only for user attributes and instanceLineId; user attributes go in order from TOON_FIRST_INSTANCE_ATTRIBUTE_LOCATION)
  - returns Option<u32>

## ToonInstanceLayout (struct) (Clone, Debug)

Instance layout. (see the header comment, order of attribute names and sizes)

Example: A layout holding only position and size without a matrix

```rust
use vanilla::{ToonBufferUsage, ToonInstanceBuffer, ToonInstanceLayout, ToonMaterialChunks, ToonRenderer};

fn create_scatter(gl: &vanilla::GlContext, renderer: &mut ToonRenderer) -> Result<ToonInstanceBuffer, String> {
	let instance_layout = ToonInstanceLayout::new(&[("instanceOffset", 3), ("instanceScale", 1), ("instanceTint", 4)])?;
	let material = renderer.create_material(ToonMaterialChunks {
		name: String::from("scatter"),
		vertex_chunk: String::from("void applyVertex(inout ToonVertex vertex) { vertex.localPosition = vertex.localPosition * instanceScale + instanceOffset; }"),
		..ToonMaterialChunks::default()
	});
	renderer.prepare_material(gl, Some(&material), Some(&instance_layout));
	let data = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 0.0, 0.0, 0.5, 1.0, 0.6, 0.6, 1.0];
	renderer.create_instance_buffer(gl, &instance_layout, &data, ToonBufferUsage::Static)
}
```

- `pub fn new(attributes: &[(&str, usize)]) -> Result<ToonInstanceLayout, String>` (constructor, since 0.4.0): Constructor. ((name, size) list, Err if names overlap, sizes do not fit, or there are too many user attributes)
  - `attributes` &[(&str, usize)]: Array of (name, size).
  - returns Result<ToonInstanceLayout, String>: The built layout. Err(reason) if a name is not a shader name or is repeated, a size does not fit, or there are more than TOON_MAXIMUM_INSTANCE_ATTRIBUTES user attributes.
- `pub fn get_id(&self) -> u32` (method, since 0.4.0): Returns the ID. (different per layout)
  - returns u32: Layout number.
- `pub fn get_attributes(&self) -> &[ToonInstanceAttribute]` (method, since 0.4.0): Returns the attribute list.
  - returns &[ToonInstanceAttribute]: Attribute list. (offset is in floats, location is Some only for user attributes)
- `pub fn get_float_count(&self) -> usize` (method, since 0.4.0): Number of values per instance.
  - returns usize: Number of values per instance.
- `pub fn has_matrix(&self) -> bool` (method, since 0.4.0): Whether it has a model matrix.
  - returns bool: true if there is an instanceMatrix.
- `pub fn has_tint(&self) -> bool` (method, since 0.4.0): Whether it has a tint.
  - returns bool: true if there is an instanceTint.
- `pub fn has_line_id(&self) -> bool` (method, since 0.4.0): Whether there is a per-instance line id.
  - returns bool: true when instanceLineId is present.
- `pub fn read_declaration_source(&self) -> String` (method, since 0.4.0): Shader declarations of the user attributes. (in float / vec2 / vec3 / vec4 name;)
  - returns String: in declarations, one line per user attribute. (Empty text if none)

## Functions and constants

- `pub const TOON_MAXIMUM_INSTANCE_ATTRIBUTES: usize = 3` (field, since 0.4.0): Upper limit on the number of user attributes in an instance layout. (attribute locations 13, 14, 15)
  - returns usize
- `pub const TOON_FIRST_INSTANCE_ATTRIBUTE_LOCATION: u32 = 13` (field, since 0.4.0): First location of the user instance attributes.
  - returns u32
- `pub const TOON_INSTANCE_MATRIX_NAME: &str = "instanceMatrix"` (field, since 0.4.0): Name the engine reads as the model matrix in an instance layout. (16 floats)
  - returns &str
- `pub const TOON_INSTANCE_TINT_NAME: &str = "instanceTint"` (field, since 0.4.0): Name the engine reads as the multiplied color in an instance layout. (4 floats)
  - returns &str
- `pub const TOON_INSTANCE_LINE_ID_NAME: &str = "instanceLineId"` (field, since 0.4.0): Name the screen-space outline reads as the per-instance line id in an instance layout. (1 float, 1 to TOON_SCREEN_OUTLINE_MAXIMUM_LINE_ID)
  - returns &str
- `pub const TOON_INSTANCE_LINE_ID_LOCATION: u32` (field, since 0.4.0): Location of the line id attribute. (the last user attribute location; the line board shader reads from it)
  - returns u32

## ToonBlendMode (enum) (Clone, Copy, Debug, Default, PartialEq, Eq)

Blend mode. (Alpha is straight alpha SRC_ALPHA, Premultiplied is premultiplied alpha ONE, Additive is additive ONE, ONE)

- `Alpha`: Straight alpha. (SRC_ALPHA, ONE_MINUS_SRC_ALPHA)
- `Premultiplied`: Premultiplied alpha. (ONE, ONE_MINUS_SRC_ALPHA)
- `Additive`: Additive. (ONE, ONE)

## ToonMatcapBlend (enum) (Clone, Copy, Debug, Default, PartialEq, Eq)

How matcaps are blended. (Multiply multiplies the color, Add adds to the color, same as the MatCap blending of Unity Toon Shader)

- `Multiply`: Multiplies into the color.
- `Add`: Adds to the color.

## ToonBufferUsage (enum) (Clone, Copy, Debug, Default, PartialEq, Eq)

Usage of the instance buffer. (Static is uploaded once and drawn for a long time, Dynamic is modified often)

- `Static`: Uploaded once and used for a long time. (STATIC_DRAW)
- `Dynamic`: Changed often. (DYNAMIC_DRAW)
