# graphics3d/toon/toonrenderer (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/graphics3d/toon/toonrenderer/

Toon renderer. (draws MeshBuilder and readGlbArrays arrays with single-color material and outline)

Example: Draw one frame with shade, rim, highlight, point light and spotlight set

```js
import { ToonRenderer, MeshBuilder, createSphereGeometry, createBoxGeometry, Matrix4, Vector3 } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
const builder = new MeshBuilder();
builder.addPart(createSphereGeometry(0.5, 32, 20), Matrix4.createTranslation(0, 0.5, 0), "#f0c8a0", { hasOutline: true });
builder.addPart(createBoxGeometry(3, 0.1, 3), Matrix4.createTranslation(0, -0.05, 0), "#708090", { hasOutline: false });
const mesh = renderer.createMesh(builder.readArrays());
renderer.setShade({ step: 0.5, feather: 0.02, color: [0.6, 0.55, 0.75], secondStep: 0.2, secondFeather: 0.02, secondColor: [0.4, 0.36, 0.55], isHalfLambert: true });
renderer.setRimLight([0.5, 0.55, 0.7], 3, 0.2, 1);
renderer.setSpecular(0.6, 64, 0, [1, 1, 1]);
renderer.setPointLights([
	{ position: [1.5, 1.5, 1], color: [1, 0.7, 0.4], intensity: 2, range: 5 },
	{ position: [0, 3, 0], color: [0.6, 0.8, 1], intensity: 3, range: 6, direction: [0, -1, 0], innerConeAngle: 0.3, outerConeAngle: 0.6 },
]);
const matcapTexture = renderer.createTexture({ width: 2, height: 2, data: new Uint8Array([60, 60, 70, 255, 255, 255, 255, 255, 60, 60, 70, 255, 160, 160, 180, 255]) }, { isMipmapped: false, isRepeated: false });
const viewMatrix = Matrix4.createLookAt(Vector3.create(2, 2, 3), Vector3.create(0, 0.4, 0), Vector3.create(0, 1, 0));
const projectionMatrix = Matrix4.createPerspective(Math.PI / 4, 1, 0.1, 100);
renderer.beginFrameWithMatrices(viewMatrix, projectionMatrix);
renderer.drawMesh(mesh, Matrix4.createIdentity(), { receivesShadow: false, specularScale: 1.5, matcapTexture: matcapTexture, matcapStrength: 0.5 });
renderer.endFrame();
```

## ToonRenderer

Toon renderer. (draws MeshBuilder and readGlbArrays arrays with single-color material and outline)
- Light: holds one ToonLightSet as the default. Sun (direction and color, shadow), ambient light of sky color and ground color, fill light, point lights and spotlights (up to TOON_MAXIMUM_POINT_LIGHTS), rim light, highlight, light model (÷π).
  Cel shading is a shade ramp. (Base, 1st shade, 2nd shade with Step and Feather of the Unity Toon Shader, shadows enter as the shade color, boundaries without stairs by fwidth, a ramp texture also works)
  The sun receives the whole ramp color, while the fill light, point lights and spotlights receive the ramp's brightness level. Highlight and rim range from the hard toon form to the soft form. The math is in the ToonLightSet header.
  setLight, setSunDirection, setFillLight, setShade, setShadeRamp, clearShadeRamp, setBandCount, setBandRamp, setRampTexture, setRimLight, setSpecular, setPointLights, setPointLightLimit,
  setLightModel change the default set. Another set (createLightSet) can be given per draw with options.lightSet. (When the shade color differs per material)
- Normals: transformed by the transpose of the inverse of the upper left 3x3 of the model matrix and the joint matrix. (Light stays correct on stretched and squashed models, the same goes for matrices changed by the vertex chunk)
- Material: vertex color (sRGB), glow (multiplied by the base color and added), unlit. If vertex UVs (arrays.uvData, 2 each) exist, textures are sampled.
- Draw options (options, defaults give the same image as before):
  tintColor [r, g, b, a] sRGB and alpha. If tintAmount (0 ~ 1) is given, the tint is mixed in sRGB instead of multiplied. (Hit flash, broken red, mixed in linear in the linear color space)
  glowScale multiplier for vertex glow (default 1), colorScale multiplier for the final linear color (default 1, darkens mirrored reflections), emissiveColor [r, g, b] sRGB and emissiveIntensity (linear multiplier, default 1, color default black).
  baseColorTexture (multiplied into base color, alpha into opacity), emissiveTexture (multiplied into glow color), uvTransform [u offset, v offset, u scale, v scale] (offset, scale of KHR_texture_transform).
  decalTexture overlays the base color by alpha (color = texture x decalColor). Glows in that color by decalEmission. decalUvTransform is for picking one cell of an atlas.
  alphaCutoff discards pixels whose opacity is below it. (0 disables, glTF MASK)
  blendMode: ToonBlendMode.alpha (default, straight alpha), premultiplied (premultiplied alpha), additive (additive). If not alpha, drawn as translucent.
  softEdge multiplies opacity by pow(|dot(N, V)|, softEdge) to fade the edges. (0 disables, Fresnel style)
  isMirrored draws with flipped winding. If not given, flips automatically when the model matrix determinant is negative. If the view matrix is mirrored, that is added to the flip as well.
  indexStart, indexCount draw only that span of the body vertex indices. (GLB material range, hidden parts) outlineIndexStart, outlineIndexCount are for the outline shell.
  material (ToonMaterial), textures ({ uniform name: texture }), onBeforeDraw(program, webGL2RenderingContext, ToonProgramKind) are extension points. (toonmaterial.js header comment)
  lightSet (ToonLightSet) is the light set for that draw.
  If receivesShadow (default true) is false, the sun's shadow is not looked up. shadeOffset is added to the received light amount to move the shade boundary. (Vertex color threshold of Guilty Gear Xrd, Shading Grade Map form of the Unity Toon Shader)
  specularScale, rimScale (default 1) are the highlight and rim multipliers of that draw. (0 means none, strength per material)
  matcapTexture is a matcap read with the view-space normal. matcapStrength (default 1), matcapBlend (ToonMatcapBlend.multiply default, add)
  outlineColor [r, g, b, a] sRGB is the shell outline color of that draw (setOutlineColor if not given), outlineWidthScale (default 1) is the multiplier of the built thickness.
  outlineOffsetZ (default 0) is the world length the shell is pushed away from the camera. (So it does not show in front of the body, Offset Z of the Unity Toon Shader)
  angelRingTexture is the angel ring texture. u is the x of the view-space normal, v is the y of the second UV mixed with the y of the view normal by angelRingOffsetV (default 0.3). (Angel Ring of the Unity Toon Shader)
  angelRingColor [r, g, b] (linear multiplier, default white), angelRingOffsetU (0 ~ 0.5, default 0), isAngelRingAlpha (default false adds, true covers with the texture alpha)
  The angel ring UV is rotated back by the camera roll. (readCameraRoll, Camera Rolling Stabilizer of the Unity Toon Shader, the ring stays on the head even when the camera is tilted)
  lineId, hasScreenOutline, hasCreaseLine are values ToonDrawQueue passes to the screen-space outline. (The renderer does not read them)
- Outline shell (inverted hull): uploads the base position and push direction (built thickness, the averaged normal of the same position) of the shell MeshBuilder built, and the shader pushes it by outlineWidthScale and draws only back faces.
  If setOutlineDistanceScale(reference distance, minimum scale, maximum scale) is given, distance to the camera / reference distance is multiplied into the thickness to keep the screen thickness. (Perspective only)
  If setOutlineFadeDistance(near distance, far distance) is given, the thickness goes to 0 as the distance from the model position to the camera approaches the far distance. (smoothstep, Nearest and Farthest Distance of the Unity Toon Shader)
  The shell color is multiplied by the sun color when the outline light color usage of the light set is on (default). (Divided by its intensity when the intensity is 1 or more, same as the Unity Toon Shader outline)
- Skeleton: passes the bone matrices computed by writeSkinPose to drawMesh. (up to TOON_MAXIMUM_JOINTS)
- GPU instancing: drawMeshInstanced draws many copies of the same model at once with a matrix and tint per instance. (both body and outline, culled and uploaded on every draw)
  Long-lived instances build a persistent buffer with createInstanceLayout and createInstanceBuffer and are drawn with drawMeshInstanceBuffer. (Culled as a whole by the bounds of the entire buffer, the material vertex chunk reads user attributes)
  To change it use updateInstanceBuffer (whole) or updateInstanceBufferRange (part, bufferSubData). The body, outline shell, shadows and the screen-space outline's line target share the same GPU buffer.
- Off-screen culling: tests the model's bounding sphere against the view-projection frustum and skips drawing if outside. (instances are culled one by one and only the rest are uploaded)
- Shadows: cast into a ShadowMap with beginShadowPass and drawMesh, received with setShadow. (3x3 PCF, the bias is the texel-unit value of ShadowMap.setBias multiplied by the texel size and slope)
  Point light and spotlight shadows are cast into a ShadowAtlas with beginShadowAtlasPass and, per tile, setShadowAtlasTile and drawMesh, and received with setLocalShadows. (A point light uses six cube tiles, a spotlight one perspective tile)
  The shadow is multiplied into that light's received amount and goes into the shade ramp. (Same form as the sun) Only point lights with castsShadow true get tiles. (Up to SHADOW_ATLAS_MAXIMUM_LIGHTS)
  Even when shadows are not received, a 1x1 comparison depth texture is bound to both shadow units. (Without a depth texture on a sampler2DShadow unit the Mac driver reports it, and if a color texture is bound WebGL refuses to draw)
- HDR: setHdrOutput(true) outputs linear color without gamma. Draw into a float render target (ToonPostProcess) and finish with bloom and tone mapping.
- Usage: createMesh(arrays) → every frame beginFrame(view and projection) → drawMesh / drawMeshInstanced → endFrame() → deleteMesh when done.
  beginFrame records the previous draw state (blending, depth, face culling, program, vertex array) and enables depth testing and face culling, and endFrame restores the recorded state.
  (When inserted between engine 2D drawing, call Graphic.flushBatch before it)
  beginFrameWithMatrices(view, projection) starts with two matrices. (Orthographic or raw matrix camera) The camera position and view rotation (highlight, rim, soft edge, matcap) are read from the view and projection.
- Per program, frame values (view and projection, camera, shadow, HDR) and the light set are uploaded only when they change. Only per-draw values (model matrix, tint, textures) are uploaded every time.
- readProgramSources(material, instanceLayout) provides the sources to pass to ShaderWarmer.
- Drawing inside a node rectangle: given setScreenRect(x, y, width, height), beginFrame moves the view-projection clip space into that rectangle and scissors out the rest.
  The rectangle is in pixels within the viewport at beginFrame time (usually the whole drawing buffer), with the origin at the top left. (position computed with graphic.getTransformMatrix in a 2D node's draw)
  Off-screen culling uses the frustum before the move. endFrame releases the scissor. The camera's aspect ratio is matched to the rectangle's ratio. (Camera3D.setAspectRatio)
- beginFrameWithCamera(Camera3D) calls beginFrame with the camera's view and projection. Uses the same camera as 2D display (Camera3D.projectToView).
- drawMeshOutline draws only the outline shell. (when ToonDrawQueue draws all outlines together after drawing every opaque body, draws are not counted)
- Textures: createTexture(image or { width, height, data }, { isMipmapped, isRepeated, isFiltered, isColorData }) builds an RGBA texture. UV (0, 0) is the top left of the image. (Same as glTF)
- Color space: set by the constructor's options.colorSpace (default is the engine's EngineConfiguration.colorSpace, gamma without an engine) and never changes. (getColorSpace)
  gamma (default): passed colors (vertex color, tint, glow color, decal color, outline color) and color textures are sRGB; base color, tint and decal are multiplied and mixed in sRGB, then converted to linear with pow(color, 2.2) for lighting.
    pow(1 / 2.2) is applied for screen output. (Linear as is for HDR output)
  linear: color textures are uploaded in an sRGB format and the GPU decodes them to linear; passed colors are converted to linear with the sRGB standard curve (IEC 61966-2-1) before multiplying and mixing. Screen output is converted back to sRGB with the same curve.
    Every shader source gets #define VANILLA_COLOR_SPACE_LINEAR 1. (Build ToonPostProcess and ToonScreenOutline with the same value)
- Texture units: point light shadow atlas 0, ramp 1, matcap 2, sun shadow 3, base color 4, glow 5, decal 6, angel ring 7, material 8 ~ 15. beginFrame notes the binding of unit 0 and endFrame restores it.
  A unit is not rebound when it already holds the same texture, and draws do not switch the active unit back to 0. (endFrame restores the active unit; stage callbacks and onBeforeDraw are called with unit 0 active)
- Second UV: if the arrays have uv1Data, vertexUv is four values (UV, second UV). Shader chunks read it as ToonSurface.uv1. ((0, 1) if none)
- Light color usage (setLightColorUsage), shade-side rim (setShadeRimLight) and light intensity limit (setLightIntensityLimited) live in the light set (ToonLightSet).

Example: Draw after setting the sun and outline color, then read statistics and clean up

```js
import { ToonRenderer, MeshBuilder, createCapsuleGeometry, Matrix4, Vector3 } from "./vanilla.js";
const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
const renderer = new ToonRenderer(webGL2RenderingContext);
renderer.setLight([-0.4, -1, -0.3], [1, 0.96, 0.9], [0.45, 0.5, 0.6], [0.25, 0.22, 0.2]);
renderer.setOutlineColor([0.1, 0.06, 0.08, 1]);
const builder = new MeshBuilder();
builder.addPart(createCapsuleGeometry(0.3, 0.6, 8, 16), Matrix4.createIdentity(), "#a0d0a0", { outlineWidth: 0.02 });
const mesh = renderer.createMesh(builder.readArrays());
webGL2RenderingContext.clearColor(0.9, 0.9, 0.95, 1);
webGL2RenderingContext.clear(webGL2RenderingContext.COLOR_BUFFER_BIT | webGL2RenderingContext.DEPTH_BUFFER_BIT);
renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 1, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 20));
renderer.drawMesh(mesh, Matrix4.createIdentity());
renderer.drawMesh(mesh, Matrix4.createTranslation(0, 0, 50));
renderer.endFrame();
const statistics = renderer.getFrameStatistics();
if (statistics.drawnObjectCount !== 1 || statistics.culledObjectCount !== 1) {
	throw new Error("unexpected statistics");
}
renderer.deleteMesh(mesh);
renderer.destroy();
```

- `constructor(webGL2RenderingContext, options = null)` (constructor, since 0.4.0): Constructor.
  - `webGL2RenderingContext` WebGL2RenderingContext: WebGL2 rendering context to draw with.
  - `options` object | null: { colorSpace (ColorSpace, default is the engine's color space EngineConfiguration.colorSpace, gamma without an engine) }
- `static readProgramSources(material = null, instanceLayout = null, isAmbientOcclusion = false, colorSpace = readEngineColorSpace())` (static, since 0.4.0): Returns shader sources. (for pre-linking with ShaderWarmer, default programs if no material or instance layout)
  - `material` ToonMaterial | null: Material to insert shader chunks with. (Default null)
  - `instanceLayout` ToonInstanceLayout | null: Instance layout. (Default null)
  - `isAmbientOcclusion` boolean: Whether this is the body program for frames with ambient occlusion on. (default false, frames with a texture set by setAmbientOcclusionTexture use this body program)
  - `colorSpace` string: Color space. (ColorSpace, default is the engine's color space, give the same value the renderer builds with)
  - returns Array<object>: Array of { vertexShader, fragmentShader, attributeLocationTable }. (body, outline, shadow depth)

  Example: Link the default and material programs in the background while loading

  ```js
  import { ToonRenderer, ToonMaterial, ShaderWarmer } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const material = new ToonMaterial({ name: "warm", surfaceChunk: "void applySurface(inout ToonSurface surface) { surface.baseColor *= vec3(1.1, 1.0, 0.9); }" });
  const shaderWarmer = new ShaderWarmer(webGL2RenderingContext, ToonRenderer.readProgramSources().concat(ToonRenderer.readProgramSources(material)));
  shaderWarmer.update();
  const renderer = new ToonRenderer(webGL2RenderingContext);
  renderer.prepareMaterial(material);
  ```

- `createMaterial(chunks)` (method, since 0.4.0): Creates a material. (shader snippets, toonmaterial.js header comment)
  - `chunks` object: { name, uniformChunk, surfaceChunk, lightChunk, vertexChunk } (missing slots are empty strings)
  - returns ToonMaterial: The built material.
- `prepareMaterial(material, instanceLayout = null)` (method, since 0.4.0): Prebuilds a material's programs. (to avoid a stall on first draw, false on failure)
  - `material` ToonMaterial | null: Material to build in advance. (Default program if null)
  - `instanceLayout` ToonInstanceLayout | null: Instance layout to use with it. (Default null)
  - returns boolean: false if it could not be built.

  Example: Build material programs in advance while loading

  ```js
  import { ToonRenderer } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const material = renderer.createMaterial({
  	name: "checker",
  	surfaceChunk: "void applySurface(inout ToonSurface surface) { vec3 cell = floor(surface.worldPosition * 4.0); surface.baseColor *= mod(cell.x + cell.y + cell.z, 2.0) < 1.0 ? 0.7 : 1.0; }",
  });
  const instanceLayout = renderer.createInstanceLayout([{ name: "instanceMatrix", size: 16 }, { name: "instanceTint", size: 4 }]);
  const isReady = renderer.prepareMaterial(material) && renderer.prepareMaterial(material, instanceLayout);
  if (!isReady) {
  	renderer.deleteMaterial(material);
  }
  ```

- `setAsyncProgramBuild(isAsync)` (method, since 0.4.0): Whether to hand off a body variant first seen and draw with the default body meanwhile. (Default true; without KHR_parallel_shader_compile it is built on the spot regardless of this value)
  - `isAsync` boolean: If true, a body variant first seen mid-scene is not built on the spot; it is drawn with the default body with every feature on (same picture) until it finishes building. If false, it is built on the spot and waited for.

  Example

  ```js
  import { ToonRenderer } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  renderer.setAsyncProgramBuild(false);
  if (renderer.isAsyncProgramBuild() !== false) {
  	throw new Error("async program build must be off");
  }
  ```

- `isAsyncProgramBuild()` (method, since 0.4.0): Reads whether a body variant first seen is handed off and the default body is drawn meanwhile.
  - returns boolean: True if a body variant first seen is handed off and the default body is drawn meanwhile.

  Example

  ```js
  import { ToonRenderer } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  if (typeof renderer.isAsyncProgramBuild() !== "boolean") {
  	throw new Error("not boolean");
  }
  ```

- `prewarmDrawQueue(queue, options = {})` (method, since 0.4.0): Prewarms, without drawing, the program variants that the items in a draw queue will use. (Same idea as Unity ShaderVariantCollection.WarmUp and Unreal PSO caches)
  - Builds the material, instance layout, body feature bits (decided by the light set and draw options), ambient occlusion body, outline and shadow depth programs with the same keys the draw queue uses when drawing.
  - Moves the one-frame hitch of building a program for a combination first seen in the first draw into loading time. Call it once after adding the scene and before the first frame.
  - With KHR_parallel_shader_compile it only hands off compiling and polls for completion each frame so the main thread is not blocked. Without it, programs are built inside this call.
  - Drawing before the prewarm finishes is fine. A variant not built yet is built on the spot. (Same behavior)
  - `queue` ToonDrawQueue: Draw queue to read the variants from. (Only reads what was added; does not draw)
  - `options` object: List of combinations the game will use mid-scene. (Like Unity ShaderVariantCollection; default is an empty object)
  - returns ToonProgramPrewarm: Progress of the prewarm. (isReady, wait)

  Example: Prewarming variants after adding the scene and before the first frame

  ```js
  import { ToonRenderer, ToonDrawQueue, MeshBuilder, createSphereGeometry, Matrix4 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const builder = new MeshBuilder();
  builder.addPart(createSphereGeometry(0.5, 16, 10), Matrix4.createIdentity(), "#f0e8e0");
  const mesh = renderer.createMesh(builder.readArrays());
  const queue = new ToonDrawQueue();
  queue.addMesh(mesh, Matrix4.createIdentity(), { castsShadow: false });
  const prewarm = renderer.prewarmDrawQueue(queue);
  prewarm.wait().then(() => {
  	if (!prewarm.isReady()) {
  		throw new Error("prewarm is not ready");
  	}
  });
  ```

  Example: Prewarming up to the rim light combinations that turn on mid-scene

  ```js
  import { ToonRenderer, ToonDrawQueue, MeshBuilder, createSphereGeometry, Matrix4 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const builder = new MeshBuilder();
  builder.addPart(createSphereGeometry(0.5, 16, 10), Matrix4.createIdentity(), "#f0e8e0");
  const mesh = renderer.createMesh(builder.readArrays());
  const queue = new ToonDrawQueue();
  queue.addMesh(mesh, Matrix4.createIdentity(), { castsShadow: false });
  const prewarm = renderer.prewarmDrawQueue(queue, { lightFeatureList: [["rim"], ["rim", "shadeRim"]] });
  prewarm.wait().then(() => {
  	if (!prewarm.isReady()) {
  		throw new Error("prewarm is not ready");
  	}
  });
  ```

- `deleteMaterial(material)` (method, since 0.4.0): Deletes a material's programs. (for all instance layouts, rebuilt when drawn again)
  - `material` ToonMaterial: Material whose programs to delete.
- `createLightSet()` (method, since 0.4.0): Creates a light set. (to pass per draw via options.lightSet, starts with the same values as the default lighting)
  - returns ToonLightSet: A new light set starting with the same values as the default light.
- `getLightSet()` (method, since 0.4.0): Returns the default light set.
  - returns ToonLightSet: The default light set.
- `createInstanceLayout(attributes)` (method, since 0.4.0): Creates an instance layout. ([{ name, size }], ToonInstanceLayout in toonmaterial.js)
  - `attributes` Array<object>: Array of { name, size }.
  - returns ToonInstanceLayout: The built instance layout.

  Example: Pair a layout holding only position and color with a vertex chunk

  ```js
  import { ToonRenderer } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const instanceLayout = renderer.createInstanceLayout([{ name: "instanceOffset", size: 3 }, { name: "instanceTint", size: 4 }]);
  const material = renderer.createMaterial({
  	name: "offset",
  	vertexChunk: "void applyVertex(inout ToonVertex vertex) { vertex.modelMatrix[3].xyz += instanceOffset; }",
  });
  if (!renderer.prepareMaterial(material, instanceLayout) || instanceLayout.getFloatCount() !== 7) {
  	throw new Error("layout failed");
  }
  ```

- `createInstanceBuffer(instanceLayout, data, usage = ToonBufferUsage.static)` (method, since 0.4.0): Creates a persistent instance buffer. (data holding the layout's value count per instance, with ToonBufferUsage.static it is uploaded once and drawn for a long time)
  - `instanceLayout` ToonInstanceLayout: Layout of one instance.
  - `data` Float32Array: Numbers of instances stored one after another, layout float count each.
  - `usage` string: Value of ToonBufferUsage. (Default static)
  - returns object: Instance buffer. ({ layout, buffer, usage, floatCount, vertexArrays, generation, bounds, data, renderer })
generation grows by 1 each time it is changed or deleted. (The shadow cache learns the buffer changed) bounds is the bounds of the entire buffer. (Only when the layout has a matrix, otherwise null)
data is a copy for recomputing the bounds. (Only when there is a matrix, do not change it) All drawing paths (drawMeshInstanceBuffer, ToonScreenOutline.drawMeshInstanceBuffer, ToonDrawQueue.addMeshInstanceBuffer) share this one GPU buffer and do not upload it again.

  Example: Upload the matrices and tints of nine trees once

  ```js
  import { ToonRenderer, Matrix4 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const instanceLayout = renderer.createInstanceLayout([{ name: "instanceMatrix", size: 16 }, { name: "instanceTint", size: 4 }]);
  const floatCount = instanceLayout.getFloatCount();
  const data = new Float32Array(floatCount * 9);
  for (let index = 0; index < 9; ++index) {
  	data.set(Matrix4.createTranslation(index % 3 - 1, 0, Math.floor(index / 3) - 1).getElements(), index * floatCount);
  	data.set([1, 1 - index * 0.05, 1, 1], index * floatCount + 16);
  }
  const instanceBuffer = renderer.createInstanceBuffer(instanceLayout, data);
  ```

- `updateInstanceBuffer(instanceBuffer, data)` (method, since 0.4.0): Updates an instance buffer. (re-uploads the whole thing)
  - `instanceBuffer` object: Result of createInstanceBuffer.
  - `data` Float32Array: New numbers. (The instance count may change)
- `updateInstanceBufferRange(instanceBuffer, firstInstance, data)` (method, since 0.4.0): Changes part of an instance buffer. (Uploads only as many instances as data holds, starting at the firstInstance-th, bufferSubData)
  - `instanceBuffer` object: Result of createInstanceBuffer.
  - `firstInstance` number: Number of the first instance to change. (From 0)
  - `data` Float32Array: Values holding the instances to change one after another, the layout's value count each. (Throws if it goes past the number of instances in the buffer, use updateInstanceBuffer to grow it)

  Example: Move only one rock and draw without uploading again

  ```js
  import { ToonRenderer, MeshBuilder, createOctahedronGeometry, Matrix4, Vector3 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const builder = new MeshBuilder();
  builder.addPart(createOctahedronGeometry(0.3), Matrix4.createIdentity(), "#909098");
  const rockMesh = renderer.createMesh(builder.readArrays());
  const instanceLayout = renderer.createInstanceLayout([{ name: "instanceMatrix", size: 16 }, { name: "instanceTint", size: 4 }]);
  const data = new Float32Array(20 * 3);
  for (let index = 0; index < 3; ++index) {
  	data.set(Matrix4.createTranslation(index - 1, 0, 0).getElements(), index * 20);
  	data.set([1, 1, 1, 1], index * 20 + 16);
  }
  const instanceBuffer = renderer.createInstanceBuffer(instanceLayout, data, "dynamic");
  const moved = new Float32Array(20);
  moved.set(Matrix4.createTranslation(0, 0.5, 0).getElements(), 0);
  moved.set([1, 0.6, 0.6, 1], 16);
  renderer.updateInstanceBufferRange(instanceBuffer, 1, moved);
  renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 2, 4), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 30));
  renderer.drawMeshInstanceBuffer(rockMesh, instanceBuffer, 3);
  renderer.endFrame();
  if (instanceBuffer.generation !== 1) {
  	throw new Error("generation failed");
  }
  ```

- `deleteInstanceBuffer(instanceBuffer)` (method, since 0.4.0): Deletes an instance buffer. (also the vertex arrays built with it, delete before the model, drawing with a deleted buffer draws nothing)
  - `instanceBuffer` object: Result of createInstanceBuffer.
- `createTexture(source, options = {})` (method, since 0.4.0): Builds a texture. (ImageBitmap, canvas, image, ImageData or { width, height, data: Uint8Array RGBA })
  - In the linear color space (ColorSpace.linear), color textures (base color, glow, decal, matcap, angel ring, ramp) are uploaded in an sRGB format (SRGB8_ALPHA8).
    The GPU decodes them to linear when reading, so filtering and mipmaps happen in linear space, and the shader uses the received value as a linear color as is. (Same as sRGB textures in Unity and Unreal)
    Data textures such as normals, masks and IDs are uploaded as is to RGBA8 with isColorData: false. (Data read by material chunks)
  - The gamma color space (default) uploads as RGBA regardless of isColorData, and the shader converts color textures to linear with pow 2.2. (Same as before)
  - `source` object: ImageBitmap, canvas, image, ImageData or { width, height, data }.
  - `options` object: { isMipmapped (default true), isRepeated (default true, false clamps to the edge), isFiltered (default true, false uses the nearest pixel), isColorData (default true is color, false is data such as normals or masks, only distinguished in the linear color space) }
  - returns WebGLTexture: The built RGBA texture.

  Example: Use a pattern drawn on a canvas as the base color texture

  ```js
  import { ToonRenderer, MeshBuilder, createBoxGeometry, Matrix4, Vector3 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const canvas = document.createElement("canvas");
  canvas.width = 64;
  canvas.height = 64;
  const context = canvas.getContext("2d");
  context.fillStyle = "#f0e0c0";
  context.fillRect(0, 0, 64, 64);
  context.fillStyle = "#c04040";
  context.fillRect(0, 0, 32, 32);
  const baseColorTexture = renderer.createTexture(canvas, { isRepeated: true });
  const builder = new MeshBuilder();
  builder.addPart(createBoxGeometry(1, 1, 1), Matrix4.createIdentity(), "#ffffff", { hasOutline: true });
  const mesh = renderer.createMesh(builder.readArrays());
  renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(2, 2, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 20));
  renderer.drawMesh(mesh, Matrix4.createIdentity(), { baseColorTexture: baseColorTexture, uvTransform: [0, 0, 2, 2] });
  renderer.endFrame();
  renderer.deleteTexture(baseColorTexture);
  ```

- `deleteTexture(texture)` (method, since 0.4.0): Deletes a texture.
  - `texture` WebGLTexture | null: Texture to delete. (Does nothing if null)
- `createMesh(arrays)` (method, since 0.4.0): Uploads a model. (result of MeshBuilder.readArrays or readGlbArrays, null if the body is empty)
  - `arrays` object: Result of MeshBuilder.readArrays or readGlbArrays.
  - returns object | null: Model uploaded to the GPU. (null if the body has no vertex indices)

  Example: Upload two parts as one model and delete it when done

  ```js
  import { ToonRenderer, MeshBuilder, createBoxGeometry, createSphereGeometry, Matrix4 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const builder = new MeshBuilder();
  builder.addPart(createBoxGeometry(0.8, 1, 0.5), Matrix4.createTranslation(0, 0.5, 0), "#6080c0", { hasOutline: true });
  builder.addPart(createSphereGeometry(0.3, 20, 14), Matrix4.createTranslation(0, 1.3, 0), "#f0d0b0", { hasOutline: true });
  const mesh = renderer.createMesh(builder.readArrays());
  if (mesh === null) {
  	throw new Error("empty mesh");
  }
  renderer.deleteMesh(mesh);
  ```

- `createEmptyShadowTexture()` (method, since 0.4.0): Creates the empty shadow texture. (1x1 depth 1, comparison sampling)
  - returns WebGLTexture: 1x1 comparison depth texture.
- `destroy()` (method, since 0.4.0): Deletes the renderer. (all programs and the empty texture, models, instance buffers and textures are deleted separately)
- `deleteMesh(mesh)` (method, since 0.4.0): Deletes a model.
  - `mesh` object | null: Result of createMesh. (Does nothing if null)
- `saveState()` (method, since 0.4.0): Records the state before drawing.
- `restoreState(isFramebufferRestored)` (method, since 0.4.0): Restores the recorded state.
  - `isFramebufferRestored` boolean: Whether to restore the framebuffer and viewport too.
- `applyFrameState()` (method, since 0.4.0): Applies the frame's draw state. (blending off, depth test LEQUAL and depth write, back-face culling, front face CCW, ToonDrawQueue reapplies it after stage callbacks)
- `beginFrame(viewProjectionMatrix)` (method, since 0.4.0): Begins a frame. (sets view, projection and frustum, records the previous state, then enables depth testing and face culling, the caller decides whether to clear depth)
  - `viewProjectionMatrix` Matrix4: View and projection matrix. (Projection x view)
- `endFrame()` (method, since 0.4.0): Ends a frame. (restores the recorded state)
- `beginFrameWithCamera(camera)` (method, since 0.4.0): Begins a frame with a camera. (beginFrame with the Camera3D's view and projection)
  - `camera` object: Camera3D. (Reads view and projection)

  Example: Start a frame with a Camera3D

  ```js
  import { ToonRenderer, MeshBuilder, createCylinderGeometry, Camera3D, Matrix4, Vector3 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const builder = new MeshBuilder();
  builder.addPart(createCylinderGeometry(0.4, 0.4, 1, 24), Matrix4.createIdentity(), "#c0a0e0", { hasOutline: true });
  const mesh = renderer.createMesh(builder.readArrays());
  const camera = new Camera3D();
  camera.setPerspective(0.8, 0.1, 100);
  camera.lookAt(Vector3.create(0, 1.5, 4), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0));
  renderer.beginFrameWithCamera(camera);
  renderer.drawMesh(mesh, Matrix4.createIdentity());
  renderer.endFrame();
  ```

- `beginFrameWithMatrices(viewMatrix, projectionMatrix)` (method, since 0.4.0): Begins a frame with view and projection matrices. (without Camera3D, beginFrame with projection x view)
  - `viewMatrix` Matrix4: View matrix.
  - `projectionMatrix` Matrix4: Projection matrix.
- `getFrameCamera()` (method, since 0.4.0): Returns this frame's camera. (read from view and projection)
  - returns object: Camera of this frame. ({ position [x, y, z, w (1 perspective, 0 orthographic)], forward, isMirrored })
- `setScreenRect(x, y, width, height)` (method, since 0.4.0): Sets the screen rectangle to draw into. (viewport pixels, top-left origin, from the next beginFrame)
  - `x` number: Left edge. (Viewport pixels)
  - `y` number: Top edge. (Viewport pixels, top is 0)
  - `width` number: Width. (pixels)
  - `height` number: Height. (pixels)

  Example: Draw a preview only in the top right rectangle of the drawing buffer

  ```js
  import { ToonRenderer, MeshBuilder, createOctahedronGeometry, Matrix4, Vector3 } from "./vanilla.js";
  const canvas = document.createElement("canvas");
  canvas.width = 320;
  canvas.height = 240;
  const renderer = new ToonRenderer(canvas.getContext("webgl2"));
  const builder = new MeshBuilder();
  builder.addPart(createOctahedronGeometry(0.6), Matrix4.createIdentity(), "#60c0a0", { hasOutline: true });
  const mesh = renderer.createMesh(builder.readArrays());
  renderer.setScreenRect(200, 16, 104, 78);
  renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 1, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 104 / 78, 0.1, 20));
  renderer.drawMesh(mesh, Matrix4.createIdentity());
  renderer.endFrame();
  renderer.clearScreenRect();
  ```

- `clearScreenRect()` (method, since 0.4.0): Clears the screen rectangle to draw into. (draws to the whole viewport)
- `getScreenRect()` (method, since 0.4.0): Returns the screen rectangle to draw into. (null if none)
  - returns object | null: Screen rectangle to draw in. ({ x, y, width, height }, null if none)
- `beginShadowPass(shadowMap)` (method, since 0.4.0): Begins the shadow depth pass. (into the ShadowMap's framebuffer with the light's view and projection, endShadowPass restores the previous framebuffer and viewport)
  - `shadowMap` object: ShadowMap. (Where depth is drawn, the light matrix is set beforehand with updateLightMatrix)

  Example: Cast the sun's shadow into a ShadowMap and receive it

  ```js
  import { ToonRenderer, MeshBuilder, createBoxGeometry, ShadowMap, Matrix4, Vector3 } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const renderer = new ToonRenderer(webGL2RenderingContext);
  const builder = new MeshBuilder();
  builder.addPart(createBoxGeometry(0.6, 0.6, 0.6), Matrix4.createTranslation(0, 0.6, 0), "#e0b080", { hasOutline: true });
  builder.addPart(createBoxGeometry(4, 0.1, 4), Matrix4.createTranslation(0, -0.05, 0), "#a0b0a0", { hasOutline: false });
  const mesh = renderer.createMesh(builder.readArrays());
  const shadowMap = new ShadowMap(webGL2RenderingContext, 1024);
  const sunDirection = renderer.getSunDirection();
  shadowMap.updateLightMatrix(Vector3.create(0, 0, 0), Vector3.create(sunDirection[0], sunDirection[1], sunDirection[2]), 3, 0.5, 20);
  renderer.beginShadowPass(shadowMap);
  renderer.drawMesh(mesh, Matrix4.createIdentity());
  renderer.endShadowPass();
  renderer.setShadow(shadowMap, 0.7);
  renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(2, 3, 4), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 30));
  renderer.drawMesh(mesh, Matrix4.createIdentity());
  renderer.endFrame();
  ```

- `beginShadowAtlasPass(shadowAtlas)` (method, since 0.4.0): Start the shadow atlas depth pass. (Binds and clears the atlas and notes the previous state, after setShadowAtlasTile per tile drawMesh draws only depth, end with endShadowPass)
  - `shadowAtlas` object: ShadowAtlas.

  Example: Draw depth for each tile of the point light shadow atlas

  ```js
  import { ToonRenderer, MeshBuilder, createBoxGeometry, ShadowAtlas, Matrix4 } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const renderer = new ToonRenderer(webGL2RenderingContext);
  const builder = new MeshBuilder();
  builder.addPart(createBoxGeometry(1, 1, 1), Matrix4.createTranslation(0, 0.5, 0), "#c0a080", { hasOutline: false });
  const mesh = renderer.createMesh(builder.readArrays());
  renderer.setPointLights([{ position: [0, 2.5, 1], color: [1, 0.8, 0.6], intensity: 3, range: 8, castsShadow: true }]);
  const shadowAtlas = new ShadowAtlas(webGL2RenderingContext, 1024);
  shadowAtlas.updateLights(renderer.getLightSet().getPointLights());
  renderer.beginShadowAtlasPass(shadowAtlas);
  for (let tileIndex = 0; tileIndex < shadowAtlas.getTileCount(); ++tileIndex) {
  	renderer.setShadowAtlasTile(shadowAtlas, tileIndex);
  	renderer.drawMesh(mesh, Matrix4.createIdentity());
  }
  renderer.endShadowPass();
  renderer.setLocalShadows(shadowAtlas, 1);
  ```

- `setShadowAtlasTile(shadowAtlas, tileIndex)` (method, since 0.4.0): Select a tile of the shadow atlas. (Sets that tile's view, projection, frustum and viewport, between beginShadowAtlasPass and endShadowPass)
  - `shadowAtlas` object: ShadowAtlas.
  - `tileIndex` number: Tile number.
- `endShadowPass()` (method, since 0.4.0): Ends the shadow depth pass. (restores the framebuffer, viewport and state)
- `isVisible(mesh, modelElements)` (method, since 0.4.0): Whether the bounding sphere is inside the frustum. (center transformed by the model matrix, radius multiplied by the largest scale)
  - `mesh` object: Result of createMesh.
  - `modelElements` Float32Array: The 16 numbers of the model matrix.
  - returns boolean: true if inside the frustum.
- `drawMesh(mesh, modelMatrix, options = EMPTY_OPTIONS)` (method, since 0.4.0): Draws one model. (depth only in the shadow pass, skipped if off-screen)
  - `mesh` object: Result of createMesh.
  - `modelMatrix` Matrix4: Model matrix.
  - `options` object: Draw options from the class header comment plus jointMatrices Float32Array, hasOutline (default true), isCulled (default true)

  Example: Change tint, outline color and thickness, and translucency per draw

  ```js
  import { ToonRenderer, MeshBuilder, createRoundedBoxGeometry, Matrix4, Vector3 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const builder = new MeshBuilder();
  builder.addPart(createRoundedBoxGeometry(0.8, 0.8, 0.8, 4, 0.1), Matrix4.createIdentity(), "#e0e0e0", { hasOutline: true });
  const mesh = renderer.createMesh(builder.readArrays());
  renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 1.5, 4), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 20));
  renderer.drawMesh(mesh, Matrix4.createTranslation(-1, 0, 0), { tintColor: [1, 0.6, 0.6, 1], outlineColor: [0.4, 0.05, 0.05, 1], outlineWidthScale: 1.5 });
  renderer.drawMesh(mesh, Matrix4.createTranslation(0, 0, 0), { tintColor: [1, 0.2, 0.2, 1], tintAmount: 0.7, shadeOffset: 0.2 });
  renderer.drawMesh(mesh, Matrix4.createTranslation(1, 0, 0), { alpha: 0.5, softEdge: 1.5, hasOutline: false });
  renderer.endFrame();
  ```

- `drawMeshInstanced(mesh, instances, options = EMPTY_OPTIONS)` (method, since 0.4.0): Draws many copies of the same model at once. (GPU instancing, off-screen instances are culled and only the rest are uploaded, skinned models share the same pose)
  - `mesh` object: Result of createMesh.
  - `instances` Array<object>: Array of { modelMatrix: Matrix4, tintColor: [r, g, b, a], emissiveColor: [r, g, b], emissiveIntensity: number }.
The tint is the multiplying sRGB and alpha (default 1), emissiveColor is the emission sRGB added to that instance (default none, added on top of the shading and pattern so only that instance brightens), and emissiveIntensity is the linear multiplier of the emission (default 1).
The model matrix is read as affine. (See the TOON_INSTANCE_FLOAT_COUNT header)
  - `options` object: Same as drawMesh. (Applied the same to all instances)

  Example: Twenty identical rocks with a different tint per instance

  ```js
  import { ToonRenderer, MeshBuilder, createOctahedronGeometry, Matrix4, Vector3 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const builder = new MeshBuilder();
  builder.addPart(createOctahedronGeometry(0.3), Matrix4.createIdentity(), "#909098", { hasOutline: true });
  const rockMesh = renderer.createMesh(builder.readArrays());
  const instances = [];
  for (let index = 0; index < 20; ++index) {
  	const shade = 0.7 + (index % 4) * 0.1;
  	instances.push({ modelMatrix: Matrix4.createTranslation(index % 5 - 2, 0, Math.floor(index / 5) - 2), tintColor: [shade, shade, shade, 1] });
  }
  renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 4, 6), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 30));
  renderer.drawMeshInstanced(rockMesh, instances, { specularScale: 0 });
  renderer.endFrame();
  ```

  Example: Brighten only one instance by adding emission

  ```js
  import { ToonRenderer, MeshBuilder, createOctahedronGeometry, Matrix4, Vector3 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const builder = new MeshBuilder();
  builder.addPart(createOctahedronGeometry(0.3), Matrix4.createIdentity(), "#909098", { hasOutline: true });
  const rockMesh = renderer.createMesh(builder.readArrays());
  const instances = [0, 1, 2].map((index) => ({ modelMatrix: Matrix4.createTranslation(index - 1, 0, 0) }));
  instances[1].emissiveColor = [1, 0.85, 0.3];
  instances[1].emissiveIntensity = 0.35;
  renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 2, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 30));
  renderer.drawMeshInstanced(rockMesh, instances);
  renderer.endFrame();
  ```

- `drawMeshInstanceBuffer(mesh, instanceBuffer, instanceCount, options = EMPTY_OPTIONS)` (method, since 0.4.0): Draws with a persistent instance buffer. (Culled as a whole by the bounds of the entire buffer, instanceCount instances, if the layout has no matrix the vertex chunk sets the position and it is not culled)
  - `mesh` object: Result of createMesh.
  - `instanceBuffer` object: Result of createInstanceBuffer.
  - `instanceCount` number: Number of instances to draw. (Clamped if more than the buffer holds)
  - `options` object: Same as drawMesh. (The material's vertex chunk reads user attributes, not culled if isCulled is false)

  Example: Draw a bush with a persistent buffer holding only positions

  ```js
  import { ToonRenderer, MeshBuilder, createCylinderGeometry, Matrix4, Vector3 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const builder = new MeshBuilder();
  builder.addPart(createCylinderGeometry(0.02, 0.15, 0.6, 6), Matrix4.createTranslation(0, 0.3, 0), "#60a050", { hasOutline: true });
  const grassMesh = renderer.createMesh(builder.readArrays());
  const instanceLayout = renderer.createInstanceLayout([{ name: "instanceOffset", size: 3 }]);
  const material = renderer.createMaterial({ name: "grass", vertexChunk: "void applyVertex(inout ToonVertex vertex) { vertex.modelMatrix[3].xyz += instanceOffset; }" });
  const data = new Float32Array(3 * 50);
  for (let index = 0; index < 50; ++index) {
  	data.set([(index % 10) * 0.4 - 2, 0, Math.floor(index / 10) * 0.4 - 1], index * 3);
  }
  const instanceBuffer = renderer.createInstanceBuffer(instanceLayout, data);
  renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 3, 5), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 30));
  renderer.drawMeshInstanceBuffer(grassMesh, instanceBuffer, 50, { material: material });
  renderer.endFrame();
  renderer.deleteInstanceBuffer(instanceBuffer);
  ```

- `drawMeshOutline(mesh, modelMatrix, options = EMPTY_OPTIONS)` (method, since 0.4.0): Draws only the outline of one model. (neither culled nor counted, not drawn if there is no shell or hasOutline is false)
  - `mesh` object: Result of createMesh.
  - `modelMatrix` Matrix4: Model matrix.
  - `options` object: Same as drawMesh.
- `uploadDrawUniforms(shaderProgram, modelElements, isSkinned, instancedMode, jointMatrices)` (method, since 0.4.0): Uploads the common per-draw uniforms. (model matrix, skeleton, instancing)
  - `shaderProgram` ShaderProgram: The program in use.
  - `modelElements` ArrayLike<number>: The 16 numbers of the model matrix.
  - `isSkinned` boolean: Whether to move by skeleton.
  - `instancedMode` number: 0 none, 1 instance matrix and tint, 2 instance tint only
  - `jointMatrices` Float32Array | null: Numbers of the joint matrices. (null if not skeletal)
- `drawWithCount(mesh, modelElements, instanceCount, options, instanceBuffer, parts = DRAW_PART_ALL, vertexArrays = null)` (method, since 0.4.0): Core draw. (normal draw if instanceCount is 0, otherwise instanced, using its layout if instanceBuffer is given)
  - `mesh` object: Result of createMesh.
  - `modelElements` ArrayLike<number>: The 16 numbers of the model matrix. (For instances, the first matrix that decides the winding)
  - `instanceCount` number: Instance count. (0 means an ordinary draw)
  - `options` object: Draw options of drawMesh.
  - `instanceBuffer` object | null: Result of createInstanceBuffer. (null if none)
  - `parts` number: What to draw. (DRAW_PART_OUTLINE the outline shell, DRAW_PART_BODY the body, both by default, hasOutline and isBodyDrawn false in the options also leave that out)
  - `vertexArrays` object | null: Vertex arrays to use instead of the mesh's. ({ body, outline }, the batch slot of auto-instancing, null by default)
- `setLight(sunDirection, sunColor, skyColor, groundColor)` (method, since 0.4.0): Sets the lighting. (sun direction, sun color, sky color, ground color, all linear colors 0 ~, may exceed 1 with HDR, default light set)
  - `sunDirection` Array<number>: Direction the sun shines. ([x, y, z], the way the light travels)
  - `sunColor` Array<number>: Linear color of the sun.
  - `skyColor` Array<number>: Linear color of the ambient light from above.
  - `groundColor` Array<number>: Linear color of the ambient light from below.
- `setSunDirection(sunDirection)` (method, since 0.4.0): Sets the sun direction. (the direction light travels, ToonLightSet header comment)
  - `sunDirection` Array<number>: Direction the light travels. ([x, y, z])
- `getSunDirection()` (method, since 0.4.0): Returns the sun direction. (passed to ShadowMap.updateLightMatrix)
  - returns Array<number>: Direction the sun shines. ([x, y, z])
- `setFillLight(fillDirection, fillColor)` (method, since 0.4.0): Sets the fill light. (direction light travels and linear color)
  - `fillDirection` Array<number>: Direction the light travels. ([x, y, z])
  - `fillColor` Array<number>: Linear color. (0 means none)
- `setRimLight(rimColor, rimPower, rimFeather = 1, rimLightMask = 0)` (method, since 0.4.0): Set the rim light. (ToonLightSet.setRimLight)
  - `rimColor` Array<number>: Linear color to add.
  - `rimPower` number: Power. (0 means none)
  - `rimFeather` number: 0 hard rim ~ 1 soft rim. (Default 1)
  - `rimLightMask` number: 1 means only on the side facing the sun. (Default 0)
- `setSpecular(specularStrength, specularExponent = 48, specularFeather = 0, specularColor = [1, 1, 1])` (method, since 0.4.0): Set the highlight. (ToonLightSet.setSpecular)
  - `specularStrength` number: Strength. (0 means none)
  - `specularExponent` number: Blinn-Phong exponent. (Default 48)
  - `specularFeather` number: 0 hard spot ~ 1 soft light. (Default 0)
  - `specularColor` Array<number>: Linear color. (Default white)
- `setPointLights(pointLights)` (method, since 0.4.0): Set point lights and spotlights. (ToonLightSet.setPointLights)
  - `pointLights` Array<object>: Form of ToonLightSet.setPointLights.
- `setPointLightLimit(pointLightLimit)` (method, since 0.4.0): Set the point light count limit. (ToonLightSet.setPointLightLimit)
  - `pointLightLimit` number: Number of point lights to receive. (0 ~ TOON_MAXIMUM_POINT_LIGHTS)
- `setShade(shade)` (method, since 0.4.0): Set the three shades. (ToonLightSet.setShade, base, 1st shade and 2nd shade of the Unity Toon Shader)
  - `shade` object: Thresholds, softness and colors from base to 1st and 2nd shade. ({ step, feather, color, secondStep, secondFeather, secondColor, isHalfLambert })

  Example: Split bright skin and two shade levels hard

  ```js
  import { ToonRenderer, MeshBuilder, createSphereGeometry, Matrix4, Vector3 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  renderer.setShade({ step: 0.55, feather: 0.01, color: [0.85, 0.62, 0.6], secondStep: 0.25, secondFeather: 0.01, secondColor: [0.6, 0.42, 0.45], isHalfLambert: true });
  const builder = new MeshBuilder();
  builder.addPart(createSphereGeometry(0.5, 32, 20), Matrix4.createIdentity(), "#f8e0d0", { hasOutline: true });
  const mesh = renderer.createMesh(builder.readArrays());
  renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 0, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 20));
  renderer.drawMesh(mesh, Matrix4.createIdentity());
  renderer.endFrame();
  ```

- `setShadeRamp(positions, colors, feathers, isHalfLambert)` (method, since 0.4.0): Set the shade ramp. (ToonLightSet.setShadeRamp)
  - `positions` Array<number>: Position per cell.
  - `colors` Array<Array<number>>: Linear multiplier per cell.
  - `feathers` Array<number>: Softness per cell.
  - `isHalfLambert` boolean: Whether to count with half Lambert.

  Example: Give the default light set a three-cell shade ramp

  ```js
  import { ToonRenderer } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  renderer.setShadeRamp([0, 0.4, 0.62], [[0.3, 0.3, 0.45], [0.62, 0.6, 0.75], [1, 1, 1]], [0, 0.05, 0.02], true);
  const shadeRamp = renderer.getLightSet().getShadeRamp();
  if (shadeRamp.positions.length !== 3) {
  	throw new Error("ramp not set");
  }
  ```

- `clearShadeRamp()` (method, since 0.4.0): Turn off the shade ramp. (Smooth Lambert)
- `setBandCount(bandCount)` (method, since 0.4.0): Set even cells. (ToonLightSet.setBandCount, 0 means smooth)
  - `bandCount` number: Number of cells.
- `setBandRamp(thresholds, values, isHalfLambert)` (method, since 0.4.0): Set a gray cell ramp. (ToonLightSet.setBandRamp)
  - `thresholds` Array<number>: Ascending thresholds.
  - `values` Array<number>: Received amount per cell.
  - `isHalfLambert` boolean: Whether to count with half Lambert.

  Example: Gray ramp with three cells: shade, middle, light

  ```js
  import { ToonRenderer } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  renderer.setBandRamp([0.3, 0.7], [0.35, 0.7, 1], false);
  renderer.setRimLight([0.4, 0.4, 0.5], 4, 0, 1);
  renderer.setSpecular(0.5, 32, 0);
  ```

- `setRampTexture(rampTexture, isHalfLambert = true)` (method, since 0.4.0): Set the ramp texture. (ToonLightSet.setRampTexture, back to cells if null)
  - `rampTexture` WebGLTexture | null: A ramp texture built with createTexture, or null.
  - `isHalfLambert` boolean: Whether to count with half Lambert. (Default true)

  Example: Give the shade color with a four-cell ramp texture and then return to cells

  ```js
  import { ToonRenderer, MeshBuilder, createTorusGeometry, Matrix4, Vector3 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const rampData = new Uint8Array([60, 50, 110, 255, 110, 100, 160, 255, 200, 185, 215, 255, 255, 255, 255, 255]);
  const rampTexture = renderer.createTexture({ width: 4, height: 1, data: rampData }, { isMipmapped: false, isRepeated: false, isFiltered: false });
  renderer.setRampTexture(rampTexture, true);
  const builder = new MeshBuilder();
  builder.addPart(createTorusGeometry(0.4, 0.15, 16, 32), Matrix4.createIdentity(), "#ffffff", { hasOutline: true });
  const mesh = renderer.createMesh(builder.readArrays());
  renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 1, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 20));
  renderer.drawMesh(mesh, Matrix4.createIdentity());
  renderer.endFrame();
  renderer.setRampTexture(null);
  renderer.deleteTexture(rampTexture);
  ```

- `setLightModel(lightModel)` (method, since 0.4.0): Sets the light model. ({ isEnergyNormalized })
  - `lightModel` object: { isEnergyNormalized } (if true, base color x light is divided by π)

  Example: Give the sun and point lights physical light intensities

  ```js
  import { ToonRenderer } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  renderer.setLightModel({ isEnergyNormalized: true });
  renderer.setLight([-0.3, -1, -0.4], [3.14, 3.0, 2.8], [0.4, 0.45, 0.55], [0.2, 0.18, 0.16]);
  renderer.setPointLights([{ position: [0, 2, 1], color: [1, 0.8, 0.6], intensity: 30, range: 8 }]);
  ```

- `setOutlineColor(outlineColor)` (method, since 0.4.0): Sets the outline color. (sRGB 0 ~ 1 and alpha)
  - `outlineColor` Array<number>: [r, g, b, a] (sRGB 0 ~ 1 and alpha)
- `setOutlineDistanceScale(referenceDistance, minimumScale = 0.5, maximumScale = 4)` (method, since 0.4.0): Set the distance scale of the shell outline. (Built thickness at the reference distance, pushed thicker by that much when far to keep the screen thickness, the scale lies between minimum and maximum, reference distance 0 turns it off)
  - Applied only with a perspective camera. Distance to the camera / reference distance per vertex is multiplied into the thickness. (Similar screen thickness regardless of distance, like Guilty Gear Xrd)
  - `referenceDistance` number: Distance at which the built thickness is kept. (0 turns it off)
  - `minimumScale` number: Minimum scale. (Default 0.5)
  - `maximumScale` number: Maximum scale. (Default 4)

  Example: Keep the screen thickness with the built thickness at 6 meters

  ```js
  import { ToonRenderer } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  renderer.setOutlineDistanceScale(6, 0.4, 3);
  ```

- `setOutlineFadeDistance(nearDistance, farDistance)` (method, since 0.4.0): Set the distance at which the shell outline fades when far. (Built thickness up to the near distance, 0 from the far distance, smoothstep in between, off if the far distance is not above the near distance)
  - Same form as Nearest Distance and Farthest Distance of the Unity Toon Shader. Uses the distance from the model matrix position to the camera. (Perspective only)
  - `nearDistance` number: Distance at which the built thickness is kept.
  - `farDistance` number: Distance at which the thickness becomes 0.

  Example: Make the shell outline fade beyond 20 meters

  ```js
  import { ToonRenderer } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  renderer.setOutlineFadeDistance(8, 20);
  ```

- `getOutlineFadeDistance()` (method, since 0.4.0): Return the distance at which the shell outline fades.
  - returns Array<number>: [near distance, far distance]
- `setLocalShadows(shadowAtlas, strength = 1)` (method, since 0.4.0): Set the point light and spotlight shadows to receive. (ShadowAtlas or null, strength 0 ~ 1, the atlas is the one built from the point light list of the default light set)
  - `shadowAtlas` object | null: ShadowAtlas or null.
  - `strength` number: Shadow strength. (Default 1)

  Example: Receive spotlight shadows through the atlas

  ```js
  import { ToonRenderer, ShadowAtlas } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const renderer = new ToonRenderer(webGL2RenderingContext);
  renderer.setPointLights([{ position: [0, 3, 0], color: [1, 0.9, 0.8], intensity: 4, range: 8, direction: [0, -1, 0], innerConeAngle: 0.3, outerConeAngle: 0.6, castsShadow: true }]);
  const shadowAtlas = new ShadowAtlas(webGL2RenderingContext, 1024);
  shadowAtlas.updateLights(renderer.getLightSet().getPointLights());
  renderer.setLocalShadows(shadowAtlas, 0.8);
  renderer.setLocalShadows(null);
  ```

- `setLightColorUsage(lightColorUsage)` (method, since 0.4.0): Set the light color usage. (ToonLightSet.setLightColorUsage)
  - `lightColorUsage` object: { base, shade, highlight, rim, shadeRim, matcap, angelRing, outline } (Ones not given stay as they are)

  Example: Keep the rim and shell outline from taking on the sun's color

  ```js
  import { ToonRenderer } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  renderer.setLightColorUsage({ rim: false, outline: false });
  ```

- `setLightIntensityLimited(isLimited)` (method, since 0.4.0): Set the light intensity limit. (ToonLightSet.setLightIntensityLimited)
  - `isLimited` boolean: If true, limits what each light gives to 1. (Default true)

  Example: Leave a strong sun unlimited for HDR bloom

  ```js
  import { ToonRenderer } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  renderer.setLight([-0.4, -1, -0.3], [3, 2.8, 2.6], [0.4, 0.45, 0.55], [0.2, 0.18, 0.16]);
  renderer.setLightIntensityLimited(false);
  ```

- `setShadeRimLight(shadeRimColor, shadeRimPower)` (method, since 0.4.0): Set the shade-side rim light. (ToonLightSet.setShadeRimLight)
  - `shadeRimColor` Array<number>: Linear color to add.
  - `shadeRimPower` number: Power. (0 means none)

  Example: A blue rim on the side facing away from the sun

  ```js
  import { ToonRenderer } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  renderer.setShadeRimLight([0.18, 0.3, 0.62], 2.2);
  ```

- `getOutlineDistanceScale()` (method, since 0.4.0): Return the distance scale of the shell outline.
  - returns Array<number>: [reference distance, minimum scale, maximum scale]
- `setHdrOutput(isHdrOutput)` (method, since 0.4.0): Sets HDR output. (if true, outputs linear color without gamma)
  - `isHdrOutput` boolean: If true, outputs linear color without gamma.
- `setShadow(shadowMap, strength = 0.6)` (method, since 0.4.0): Sets the shadow to receive. (ShadowMap or null, strength 0 ~ 1)
  - `shadowMap` object | null: ShadowMap to receive. (Shadows are not received if null)
  - `strength` number: Shadow strength 0 ~ 1. (Default 0.6)

  Example: Receive shadows but keep the floating light orb from receiving them

  ```js
  import { ToonRenderer, MeshBuilder, createSphereGeometry, ShadowMap, Matrix4, Vector3 } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const renderer = new ToonRenderer(webGL2RenderingContext);
  const builder = new MeshBuilder();
  builder.addPart(createSphereGeometry(0.3, 20, 14), Matrix4.createIdentity(), "#ffe080", { glow: 1, hasOutline: false });
  const mesh = renderer.createMesh(builder.readArrays());
  const shadowMap = new ShadowMap(webGL2RenderingContext, 512);
  shadowMap.updateLightMatrix(Vector3.create(0, 0, 0), Vector3.create(-0.3, -1, -0.2), 4, 0.5, 20);
  renderer.setShadow(shadowMap, 0.8);
  renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 1, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 20));
  renderer.drawMesh(mesh, Matrix4.createTranslation(0, 1, 0), { receivesShadow: false });
  renderer.endFrame();
  renderer.setShadow(null);
  ```

- `setAmbientOcclusionTexture(texture, directLightingStrength = 0)` (method, since 0.4.0): Sets the ambient occlusion texture. (the result of ToonPostProcess.drawAmbientOcclusion or null, from the next beginFrame)
  - While a texture is set, bodies are drawn with the ambient occlusion body program (TOON_AMBIENT_OCCLUSION), and the visibility at the screen position multiplies the ambient light (sky and ground light).
  - When the direct lighting strength (directLightingStrength, 0 to 1) is above 0, the diffuse and specular of the sun, fill light, point lights and spotlights are also multiplied by 1 - strength x (1 - visibility). (the form of Direct Lighting Strength in Unity URP SSAO)
    It is applied after the band (brightness step) is chosen, so band edges do not move. Rim light, glow, matcap and angel ring stay as they are. With strength 0 only the ambient light is multiplied.
  - Transparent things (alpha or tint alpha below 1) and surfaces whose depth differs from the texture (not in the line target) are not multiplied.
  - null returns to the default body program, which does not read the texture. (the screen with it off is the same as when it was never set)
  - Materials that use all 8 material textures are drawn without ambient occlusion on devices with 16 fragment shader texture units.
  - `texture` WebGLTexture | null: RGBA8 the size of the line target. (r visibility, gba 24-bit depth, null turns it off)
  - `directLightingStrength` number: How much it affects direct lighting, 0 to 1. (default 0, multiplies only the ambient light)

  Example: Setting ambient occlusion, drawing, then clearing it

  ```js
  import { ToonRenderer } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const renderer = new ToonRenderer(webGL2RenderingContext);
  const texture = webGL2RenderingContext.createTexture();
  webGL2RenderingContext.bindTexture(webGL2RenderingContext.TEXTURE_2D, texture);
  webGL2RenderingContext.texStorage2D(webGL2RenderingContext.TEXTURE_2D, 1, webGL2RenderingContext.RGBA8, 300, 150);
  renderer.setAmbientOcclusionTexture(texture, 0.5);
  if (renderer.getAmbientOcclusionTexture() !== texture || renderer.getAmbientOcclusionDirectLightingStrength() !== 0.5) {
  	throw new Error("ambient occlusion texture is not set");
  }
  renderer.setAmbientOcclusionTexture(null);
  ```

- `getAmbientOcclusionDirectLightingStrength()` (method, since 0.4.0): Returns how much ambient occlusion affects direct lighting. (the second argument of setAmbientOcclusionTexture, 0 when not set)
  - returns number: 0 ~ 1.
- `getAmbientOcclusionTexture()` (method, since 0.4.0): Returns the ambient occlusion texture. (null if not set)
  - returns WebGLTexture | null: The texture set by setAmbientOcclusionTexture.
- `getFrameStatistics()` (method, since 0.4.0): This frame's drawn count, culled count and draw calls.
  - returns object: Counts of this frame. ({ drawCallCount, drawnObjectCount, culledObjectCount })
- `getWebGL2RenderingContext()` (method, since 0.4.0): Returns the rendering context.
  - returns WebGL2RenderingContext: Context to draw with.
- `getColorSpace()` (method, since 0.4.0): Returns the color space. (Set at construction, never changes)
  - returns string: ColorSpace.gamma or ColorSpace.linear.

  Example: Build a linear color space renderer and build the post process and screen outline with the same value

  ```js
  import { ToonRenderer, ToonPostProcess, ToonScreenOutline, ColorSpace } from "./vanilla.js";
  const webGL2RenderingContext = document.createElement("canvas").getContext("webgl2");
  const renderer = new ToonRenderer(webGL2RenderingContext, { colorSpace: ColorSpace.linear });
  const postProcess = new ToonPostProcess(webGL2RenderingContext, 320, 180, { colorSpace: renderer.getColorSpace() });
  const screenOutline = new ToonScreenOutline(webGL2RenderingContext, { colorSpace: renderer.getColorSpace() });
  if (renderer.getColorSpace() !== ColorSpace.linear || postProcess.getColorSpace() !== ColorSpace.linear || screenOutline.getColorSpace() !== ColorSpace.linear) {
  	throw new Error("color space is not linear");
  }
  ```

- `getSolidProgram(material = null)` (method, since 0.4.0): Returns the body program. (that material's if a material is given, null if it failed to build)
  - `material` ToonMaterial | null: Material. (Default program if null, the default)
  - returns ShaderProgram | null: Body program. (null if it could not be built)
- `getOutlineProgram(material = null)` (method, since 0.4.0): Returns the outline program.
  - `material` ToonMaterial | null: Material. (Default program if null, the default)
  - returns ShaderProgram | null: Outline program. (null if it could not be built)
- `getDepthProgram(material = null)` (method, since 0.4.0): Returns the shadow depth program.
  - `material` ToonMaterial | null: Material. (Default program if null, the default)
  - returns ShaderProgram | null: Shadow depth program. (null if it could not be built)

## ToonProgramPrewarm

Progress of prewarming program variants. (The result of ToonRenderer.prewarmDrawQueue)
- Finishes compiled programs a few per frame. (requestAnimationFrame; without the parallel compile extension it is already finished when created)

Example: Prewarming while loading and starting once done

```js
import { ToonRenderer, ToonDrawQueue, MeshBuilder, createSphereGeometry, Matrix4 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const builder = new MeshBuilder();
builder.addPart(createSphereGeometry(0.5, 16, 10), Matrix4.createIdentity(), "#c0d0ff");
const mesh = renderer.createMesh(builder.readArrays());
const queue = new ToonDrawQueue();
queue.addMesh(mesh, Matrix4.createIdentity(), { castsShadow: false });
const prewarm = renderer.prewarmDrawQueue(queue);
await prewarm.wait();
console.log(prewarm.isReady());
```

- `isReady()` (method, since 0.4.0): Whether everything is built.
  - returns boolean: True if everything is built. (Drawing is allowed anyway; anything not built is built on the spot)
- `wait()` (method, since 0.4.0): Waiting until everything is built.
  - returns Promise<void>: Promise that resolves when everything is built.

## Functions and constants

- `TOON_MAXIMUM_JOINTS` (field, since 0.4.0): Upper limit on the number of joints one model uses. (shader uniform array size, 96, same as the engine's SkinnedModelRenderer)
- `TOON_INSTANCE_FLOAT_COUNT = 20` (field, since 0.4.0): Number of values per instance. (matrix 16, tint 4)
  - The matrix is read as an affine 3x4. The four values of the bottom row (elements 3, 7, 11, 15) are the instance emission (sRGB r, g, b and a linear intensity). (The 3x4 matrix form of Godot MultiMesh and Unity BatchRendererGroup)
    Storing Matrix4 elements as they are leaves the bottom row 0, 0, 0, 1, so there is no emission.
  - returns number
- `TOON_MAXIMUM_MATERIAL_TEXTURES = 8` (field, since 0.4.0): Upper limit of textures a material can bind per draw. (Units 8 ~ 15)
  - returns number
- `TOON_ATTRIBUTE_LOCATIONS` (field, since 0.4.0): Attribute locations. (all programs use the same locations, instance layout user attributes start at 13)
- `composeToonProgramSources(material, instanceLayout, isAmbientOcclusion = false, colorSpace = readEngineColorSpace(), disabledFeatures = [])` (method, since 0.4.0): Builds the sources of the three programs from a material and instance layout. (default programs if both are null)
  - `material` ToonMaterial | null: Material to insert shader chunks with. (Empty chunks if null)
  - `instanceLayout` ToonInstanceLayout | null: Instance layout that declares user attributes. (None if null)
  - `isAmbientOcclusion` boolean: Whether to define TOON_AMBIENT_OCCLUSION in the body fragment shader so the ambient occlusion texture multiplies the ambient light. (default false)
  - `colorSpace` string: Color space. (ColorSpace, default is the engine's color space, in linear every source gets #define VANILLA_COLOR_SPACE_LINEAR 1)
  - `disabledFeatures` Array<string>: Feature branches to remove from the body fragment shader at compile time. (Any of baseTexture, emissiveTexture, decalTexture, matcap, angelRing, rampTexture, shadeStops, rim, shadeRim, shadow, intensityLimit, default none; a removed branch is not drawn if a draw turns it on. The renderer finds the branches a draw does not use and passes them itself)
  - returns object: Sources and attribute locations of the three programs. ({ solidVertexShader, solidFragmentShader, outlineVertexShader, outlineFragmentShader, depthVertexShader, depthFragmentShader, attributeLocationTable })

  Example: Compile the body program built from a material and instance layout directly

  ```js
  import { composeToonProgramSources, ToonMaterial, ToonInstanceLayout } from "./vanilla.js";
  const material = new ToonMaterial({ name: "sway", vertexChunk: "void applyVertex(inout ToonVertex vertex) { vertex.localPosition.x += instanceSway * vertex.localPosition.y; }" });
  const instanceLayout = new ToonInstanceLayout([{ name: "instanceMatrix", size: 16 }, { name: "instanceSway", size: 1 }]);
  const sources = composeToonProgramSources(material, instanceLayout);
  const context = document.createElement("canvas").getContext("webgl2");
  const shader = context.createShader(context.VERTEX_SHADER);
  context.shaderSource(shader, sources.solidVertexShader);
  context.compileShader(shader);
  if (!context.getShaderParameter(shader, context.COMPILE_STATUS) || sources.attributeLocationTable.instanceSway !== 13) {
  	throw new Error(context.getShaderInfoLog(shader));
  }
  context.deleteShader(shader);
  ```

- `extractFrustumPlanes(matrix)` (method, since 0.4.0): The six frustum planes from a view-projection matrix. (ax + by + cz + d >= 0 is inside, normalized)
  - `matrix` Matrix4: View and projection matrix. (Projection x view)
  - returns Array<Array<number>>: [a, b, c, d] of the six planes. (Left, right, bottom, top, near, far)

  Example: Check whether a sphere is inside the frustum

  ```js
  import { extractFrustumPlanes, Matrix4, Vector3 } from "./vanilla.js";
  const viewProjectionMatrix = Matrix4.createPerspective(0.8, 16 / 9, 0.1, 50);
  viewProjectionMatrix.multiply(Matrix4.createLookAt(Vector3.create(0, 2, 6), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)));
  const planes = extractFrustumPlanes(viewProjectionMatrix);
  const isSphereVisible = (center, radius) => planes.every((plane) => plane[0] * center[0] + plane[1] * center[1] + plane[2] * center[2] + plane[3] >= -radius);
  if (!isSphereVisible([0, 0, 0], 1) || isSphereVisible([0, 0, 80], 1)) {
  	throw new Error("unexpected culling");
  }
  ```

- `readMatrixDeterminant(elements)` (method, since 0.4.0): Determinant of the model matrix's upper-left 3x3. (negative means a mirrored matrix, winding is flipped)
  - `elements` ArrayLike<number>: Elements of a Matrix4. (column order)
  - returns number: Determinant of the upper left 3x3. (Negative means a mirrored matrix)

  Example: Detect a model matrix flipped by a negative scale

  ```js
  import { readMatrixDeterminant, Matrix4 } from "./vanilla.js";
  const modelMatrix = Matrix4.createTranslation(1, 0, 0);
  modelMatrix.multiply(Matrix4.createScale(-1, 1, 1));
  const isMirrored = readMatrixDeterminant(modelMatrix.getElements()) < 0;
  if (!isMirrored) {
  	throw new Error("expected a mirrored matrix");
  }
  ```

- `readFrameCamera(elements)` (method, since 0.4.0): Reads the camera from view and projection matrices. (eye position if perspective, view direction if orthographic, whether the matrix is mirrored)
  - Perspective: the eye is the point where clip x, y, w are all 0. (system of equations from rows 0, 1, 3)
  - Orthographic: xyz of row 3 is 0, so the eye is infinitely far. The view direction is the cross product of rows 0, 1, oriented toward increasing depth.
  - A normal projection (near plane < far plane) has a negative determinant in its upper-left 3x3. If positive, the view matrix is mirrored.
  - `elements` ArrayLike<number>: The 16 numbers of the view and projection matrices. (Column order)
  - returns object: The camera read. ({ position [x, y, z, w (1 perspective, 0 orthographic)], forward [x, y, z], isMirrored })

  Example: Read the eye position and view direction from the view and projection matrices

  ```js
  import { readFrameCamera, Matrix4, Vector3 } from "./vanilla.js";
  const viewProjectionMatrix = Matrix4.createPerspective(0.8, 16 / 9, 0.1, 100);
  viewProjectionMatrix.multiply(Matrix4.createLookAt(Vector3.create(0, 2, 5), Vector3.create(0, 2, 0), Vector3.create(0, 1, 0)));
  const frameCamera = readFrameCamera(viewProjectionMatrix.getElements());
  const isPerspective = frameCamera.position[3] === 1;
  if (!isPerspective || Math.abs(frameCamera.position[2] - 5) > 0.001 || frameCamera.forward[2] > -0.999 || frameCamera.isMirrored) {
  	throw new Error("unexpected camera");
  }
  ```

- `readViewRotation(elements, forward)` (method, since 0.4.0): Read the 3x3 view rotation from the view and projection matrices. (Column order, rows are right, up, back, for computing the view-space normal of the matcap)
  - Right is the xyz of row 0 minus its share along the view direction. (Works for symmetric perspective, orthographic and projections moved into a screen rectangle)
  - `elements` ArrayLike<number>: The 16 numbers of the view and projection matrices.
  - `forward` Array<number>: View direction. (forward of readFrameCamera)
  - returns Array<number>: The 9 numbers of a mat3. (Column order)

  Example: Move a world normal into view space

  ```js
  import { readFrameCamera, readViewRotation, Matrix4, Vector3 } from "./vanilla.js";
  const viewProjectionMatrix = Matrix4.createPerspective(0.8, 1, 0.1, 100);
  viewProjectionMatrix.multiply(Matrix4.createLookAt(Vector3.create(3, 1, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)));
  const elements = viewProjectionMatrix.getElements();
  const rotation = readViewRotation(elements, readFrameCamera(elements).forward);
  const normal = [0, 1, 0];
  const viewNormal = [0, 1, 2].map((row) => rotation[row] * normal[0] + rotation[3 + row] * normal[1] + rotation[6 + row] * normal[2]);
  const matcapUv = [viewNormal[0] * 0.5 + 0.5, viewNormal[1] * 0.5 + 0.5];
  ```

- `readCameraRoll(viewRotationElements, isMirrored)` (method, since 0.4.0): Read the angle that undoes the camera roll. (Same math as the angel ring Camera Rolling Stabilizer of the Unity Toon Shader)
  - roll is the angle between the camera right (row 0 of the view rotation) and the horizontal right axis, the direction dir is -1 if the y of the right is negative, and the returned angle is -(dir x roll).
  - Unity uses left-handed coordinates so the horizontal right axis is cross(back, up), and the engine uses right-handed coordinates so the same axis is cross(forward, up). In a mirrored frame the axis is flipped. (mirrorFlag of the Unity Toon Shader)
  - When looking straight up or down there is no horizontal axis, so it is 0.
  - `viewRotationElements` Float32Array | Array<number>: The 9 numbers of a mat3. (Result of readViewRotation, column order)
  - `isMirrored` boolean: Whether the view matrix is mirrored. (isMirrored of readFrameCamera)
  - returns number: Angle to rotate the angel ring UV around (0.5, 0.5). (Radians)

  Example: Undo angle of a camera tilted 0.3 radians to the right

  ```js
  import { readCameraRoll } from "./vanilla.js";
  const roll = 0.3;
  const rotation = [Math.cos(roll), -Math.sin(roll), 0, Math.sin(roll), Math.cos(roll), 0, 0, 0, 1];
  const angle = readCameraRoll(rotation, false);
  if (Math.abs(angle + roll) > 0.0001) {
  	throw new Error("unexpected camera roll");
  }
  ```

- `readUvData(uvData, uv1Data, vertexCount)` (method, since 0.4.0): Build the UV vertex array. (UV 2 per point without a second UV, UV and second UV interleaved as 4 with one)
  - vertexUv in the shader is a vec4. If only 2 are uploaded, zw is read as (0, 1).
  - `uvData` Float32Array: UV. (2 per point)
  - `uv1Data` Float32Array | null: Second UV. (2 per point, null if none)
  - `vertexCount` number: Number of points.
  - returns Float32Array: 2 or 4 per point.

  Example: Interleave UV and second UV into one array

  ```js
  import { readUvData } from "./vanilla.js";
  const uvData = new Float32Array([0, 0, 1, 0, 1, 1]);
  const uv1Data = new Float32Array([0.5, 0.5, 0.6, 0.5, 0.6, 0.6]);
  const data = readUvData(uvData, uv1Data, 3);
  if (data.length !== 12 || data[2] !== 0.5 || data[7] !== 0.5) {
  	throw new Error("unexpected uv data");
  }
  ```

- `readOutlineVertexData(outlineVertexData, outlineBaseData)` (method, since 0.4.0): Build the shell vertex array. (Per point base position 3 and push direction 3, the push direction is copy position - base position)
  - If there are no base positions or the length differs (a shell prebuilt in the GLB), the copy position becomes the base and the push direction is 0. (The thickness scale does not apply)
  - `outlineVertexData` Float32Array: Copy positions pushed by the built thickness. (3 each)
  - `outlineBaseData` Float32Array | undefined | null: Base positions before pushing. (3 each)
  - returns Float32Array: 6 per point.

  Example: Unpack MeshBuilder's shell into base positions and push directions

  ```js
  import { readOutlineVertexData, MeshBuilder, createBoxGeometry, Matrix4 } from "./vanilla.js";
  const builder = new MeshBuilder();
  builder.addPart(createBoxGeometry(1, 1, 1), Matrix4.createIdentity(), "#a0a0a0", { outlineWidth: 0.02 });
  const arrays = builder.readArrays();
  const outlineData = readOutlineVertexData(arrays.outlineVertexData, arrays.outlineBaseData);
  const firstPush = Math.hypot(outlineData[3], outlineData[4], outlineData[5]);
  if (outlineData.length !== arrays.outlineVertexData.length * 2 || firstPush <= 0) {
  	throw new Error("unexpected outline data");
  }
  ```

- `createReflectionMatrix(planePoint, planeNormal)` (method, since 0.4.0): Builds a reflection matrix across a plane. (a point on the plane and its normal, multiplied into the model or view matrix for a planar mirror)
  - Drawing with a reflected matrix flips the winding. ToonRenderer flips the front face itself if the model matrix determinant is negative. (can also be set with options.isMirrored)
  - `planePoint` Array<number>: A point on the plane. ([x, y, z])
  - `planeNormal` Array<number>: Normal of the plane. ([x, y, z], length does not matter)
  - returns Matrix4: Matrix reflected across the plane.

  Example: Draw the reflection in the floor mirror darker

  ```js
  import { ToonRenderer, MeshBuilder, createSphereGeometry, createReflectionMatrix, Matrix4, Vector3 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const builder = new MeshBuilder();
  builder.addPart(createSphereGeometry(0.4, 24, 16), Matrix4.createIdentity(), "#e0a060", { hasOutline: true });
  const mesh = renderer.createMesh(builder.readArrays());
  const modelMatrix = Matrix4.createTranslation(0, 0.6, 0);
  const mirroredMatrix = createReflectionMatrix([0, 0, 0], [0, 1, 0]);
  mirroredMatrix.multiply(modelMatrix);
  renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(0, 1.5, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 20));
  renderer.drawMesh(mesh, mirroredMatrix, { colorScale: 0.4, hasOutline: false });
  renderer.drawMesh(mesh, modelMatrix);
  renderer.endFrame();
  ```

- `readInstanceBufferSphere(mesh, instanceBuffer)` (method, since 0.4.0): The world bounding sphere when drawing a model with an instance buffer. (The buffer's bounds plus the model's bounding sphere at the largest scale, culling with it drops no pixels)
  - `mesh` object: Result of ToonRenderer.createMesh.
  - `instanceBuffer` object: The result of ToonRenderer.createInstanceBuffer.
  - returns Array<number> | null: [x, y, z, radius]. (null if the layout has no matrix and the bounds are unknown)

  Example: See whether a whole tree buffer is on screen

  ```js
  import { ToonRenderer, MeshBuilder, createCylinderGeometry, readInstanceBufferSphere, Matrix4 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const builder = new MeshBuilder();
  builder.addPart(createCylinderGeometry(0.02, 0.4, 1, 8), Matrix4.createTranslation(0, 0.5, 0), "#4a8040");
  const treeMesh = renderer.createMesh(builder.readArrays());
  const instanceLayout = renderer.createInstanceLayout([{ name: "instanceMatrix", size: 16 }]);
  const data = new Float32Array(16 * 2);
  data.set(Matrix4.createTranslation(-3, 0, 0).getElements(), 0);
  data.set(Matrix4.createTranslation(3, 0, 0).getElements(), 16);
  const sphere = readInstanceBufferSphere(treeMesh, renderer.createInstanceBuffer(instanceLayout, data));
  if (sphere === null || sphere[0] !== 0 || sphere[3] < 3) {
  	throw new Error("bounds failed");
  }
  ```

- `writeInstanceBufferSphere(sphere, mesh, instanceBuffer)` (method, since 0.4.0): Writes the bounding sphere of an instance buffer drawn with a mesh into a given array. (Same value as readInstanceBufferSphere, no new array)
  - `sphere` Array<number> | Float32Array | Float64Array: Array to write. ([x, y, z, radius], four or more)
  - `mesh` object: Result of createMesh.
  - `instanceBuffer` object: Result of createInstanceBuffer.
  - returns boolean: false when there is no bounds because there are no matrices. (sphere is left unchanged then)

  Example: Write the bounding sphere into the same array every frame

  ```js
  import { ToonRenderer, MeshBuilder, createBoxGeometry, writeInstanceBufferSphere, Matrix4 } from "./vanilla.js";
  const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
  const builder = new MeshBuilder();
  builder.addPart(createBoxGeometry(1, 1, 1), Matrix4.createIdentity(), "#808080");
  const boxMesh = renderer.createMesh(builder.readArrays());
  const instanceLayout = renderer.createInstanceLayout([{ name: "instanceMatrix", size: 16 }]);
  const data = new Float32Array(16 * 2);
  data.set(Matrix4.createTranslation(-2, 0, 0).getElements(), 0);
  data.set(Matrix4.createTranslation(2, 0, 0).getElements(), 16);
  const sphere = [0, 0, 0, 0];
  if (!writeInstanceBufferSphere(sphere, boxMesh, renderer.createInstanceBuffer(instanceLayout, data)) || sphere[3] < 2) {
  	throw new Error("bounds failed");
  }
  ```

- `isSphereInFrustum(frustumPlanes, sphere)` (method, since 0.4.0): Whether a sphere is inside the frustum. (The six planes of extractFrustumPlanes)
  - `frustumPlanes` Array<Array<number>>: The result of extractFrustumPlanes.
  - `sphere` Array<number>: [x, y, z, radius].
  - returns boolean: true if inside or straddling the frustum.

  Example: Tell spheres in front of and behind the camera apart

  ```js
  import { extractFrustumPlanes, isSphereInFrustum, Matrix4, Vector3 } from "./vanilla.js";
  const viewProjectionMatrix = Matrix4.createPerspective(0.8, 1, 0.1, 50);
  viewProjectionMatrix.multiply(Matrix4.createLookAt(Vector3.create(0, 0, 5), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)));
  const planes = extractFrustumPlanes(viewProjectionMatrix);
  if (!isSphereInFrustum(planes, [0, 0, 0, 1]) || isSphereInFrustum(planes, [0, 0, 20, 1])) {
  	throw new Error("unexpected culling");
  }
  ```

## ToonProgramKind (enum)

Program kind of a draw. (third argument of onBeforeDraw)

Example: Write material uniforms only for the body program

```js
import { ToonRenderer, ToonMaterial, ToonProgramKind, MeshBuilder, createBoxGeometry, Matrix4, Vector3 } from "./vanilla.js";
const renderer = new ToonRenderer(document.createElement("canvas").getContext("webgl2"));
const material = new ToonMaterial({ name: "pulse", uniformChunk: "uniform float pulse;", surfaceChunk: "void applySurface(inout ToonSurface surface) { surface.emission += vec3(pulse); }" });
const builder = new MeshBuilder();
builder.addPart(createBoxGeometry(1, 1, 1), Matrix4.createIdentity(), "#d06060", { hasOutline: true });
const mesh = renderer.createMesh(builder.readArrays());
renderer.beginFrameWithMatrices(Matrix4.createLookAt(Vector3.create(2, 2, 3), Vector3.create(0, 0, 0), Vector3.create(0, 1, 0)), Matrix4.createPerspective(0.8, 1, 0.1, 20));
renderer.drawMesh(mesh, Matrix4.createIdentity(), {
	material: material,
	onBeforeDraw: (program, context, kind) => {
		if (kind === ToonProgramKind.solid) {
			context.uniform1f(program.getUniformLocation("pulse"), 0.3);
		}
	},
});
renderer.endFrame();
```

- `solid` = `solid`: Body.
- `outline` = `outline`: Outline shell.
- `depth` = `depth`: Shadow depth.
