# core/graphic (vanilla.js 0.4.0)

> https://vanillapunch.com/docs/vanilla.js/0.4.0/api/core/graphic/

Graphics.

## GeometryKey extends Object

Geometry cache key. (where Component.writeGeometryKey writes its draw inputs)
- Compares the values written with add against the previous ones in order with ===. If any differs or the count differs, it counts as changed.
- Overwrites while comparing, so it does not create a new array every frame.

Example: Writing draw inputs and seeing whether they changed

```js
import { GeometryKey } from "./build/vanilla.js";

const geometryKey = new GeometryKey();
geometryKey.begin();
geometryKey.add(10);
geometryKey.add("#ff0000");
console.log(geometryKey.end());
geometryKey.begin();
geometryKey.add(10);
geometryKey.add("#ff0000");
console.log(geometryKey.end());
geometryKey.begin();
geometryKey.add(12);
geometryKey.add("#ff0000");
console.log(geometryKey.end());
```

- `constructor()` (constructor, since 0.4.0): Constructor.
- `begin()` (method, since 0.4.0): Starts writing. (Graphic calls it before writeGeometryKey)
- `add(value)` (method, since 0.4.0): Writes one value. (number, string, boolean, object reference, null)
  - `value` *: A value the draw reads. (objects are compared by reference, so write the fields of mutable values such as Color separately)
- `end()` (method, since 0.4.0): Ends writing. (true if same as last time)
  - returns boolean: True if every value written this time equals the previous ones. (false the first time)

## Graphic extends Object

Graphics.
- A renderer that outputs through the Canvas's WebGL2 rendering context.
- Reproduces the Canvas2D-era coordinate system (top-left origin, pixel units) and state model (transform/alpha stack)
  as is. All draws converge on the single point drawVertices().

Example: Draw shapes and text in a scene's draw

```js
import { Engine, EngineConfiguration, Scene, Vector2, Rect } from "./build/vanilla.js";

class MainScene extends Scene {
	draw(graphic) {
		super.draw(graphic);
		graphic.setFillColor("#203040");
		graphic.drawRoundRect(Rect.create(40, 40, 260, 160), 16);
		graphic.setStrokeColor("#ffcc00");
		graphic.drawStrokeCircle(Vector2.create(460, 120), 60, 4);
		graphic.setFillColor("#ffffff");
		graphic.setFontString("24px sans-serif");
		graphic.setTextAlign("center");
		graphic.setTextBaseline("middle");
		graphic.drawFillText("Graphic", 170, 120);
	}
}

const engineConfiguration = new EngineConfiguration();
engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
const engine = new Engine(engineConfiguration);
engine.run(new MainScene());
```

- `constructor(canvas, preserveDrawingBuffer, antialias = true, colorSpace = ColorSpace.gamma, trackGpuMemory = false)` (constructor, since 0.0.9): Constructor.
  - `canvas` HTMLCanvasElement: Canvas to draw on. (throws an error if a WebGL2 context is unavailable)
  - `preserveDrawingBuffer` boolean: Whether drawings stay on the canvas after the frame ends. (kept only when true)
  - `antialias` boolean: Whether to enable multisample anti-aliasing on the canvas. (default true, turned off only when false)
  - `colorSpace` string: 3D color space. (ColorSpace, default ColorSpace.gamma, the engine passes EngineConfiguration.colorSpace)
  - `trackGpuMemory` boolean: Whether to turn on GPU memory tracking from the start. (Default false, the engine passes EngineConfiguration.trackGpuMemory)
- `applySettings(engine)` (method, since 0.0.9): Applies settings. (called by the engine at the start of every frame)
  - Detects canvas size changes and updates the viewport/projection.
  - Resets to the frame-start baseline state.
  - `engine` Engine: Engine.
- `setImageSmoothingEnabled(value)` (method, since 0.2.1): Sets whether image smoothing is enabled.
  - Pixel-art (dot) sprite games set this to false to render crisply.
  - `value` boolean: Samples images smoothly (LINEAR) if true, crisply (NEAREST) if false.
- `isImageSmoothingEnabled()` (method, since 0.2.1): Returns whether image smoothing is enabled.
  - returns boolean: True if image smoothing is on.
- `setImageMipmapEnabled(value)` (method, since 0.3.2): Sets whether image mipmaps are enabled. (default false)
  - When on, builds mipmaps for image textures with smoothing on and sets the minification filter to LINEAR_MIPMAP_LINEAR.
  - Reduces stair-stepping and shimmering at the edges when large images (atlases, etc.) are drawn heavily scaled down.
  - An atlas needs generous padding (stretched edges) around each image so neighboring images do not bleed in at small mipmap levels.
  - `value` boolean: Whether to enable image mipmaps.
- `isImageMipmapEnabled()` (method, since 0.3.2): Returns whether image mipmaps are enabled.
  - returns boolean: True if image mipmaps are on.
- `setImageMipmapBias(value)` (method, since 0.3.2): Sets the image mipmap level bias. (default 0)
  - Value added when choosing the mipmap level. Negative picks the next larger image and looks sharper; too small and it shimmers again. (around -0.5)
  - Applies to the default shaders (single image, sprite batching, particles). A swapped-in shader receives it if it has a textureLodBias uniform.
  - `value` number: Value added to the mipmap level. (sharper if negative)
- `getImageMipmapBias()` (method, since 0.3.2): Returns the image mipmap level bias.
  - returns number: Mipmap level bias.
- `setImageSmoothingQuality(value)` (method, since 0.2.1): Sets the image smoothing quality. ("low", "medium", "high")
  - WebGL2 only has the LINEAR/NEAREST choice, so the value is only stored.
  - `value` string: One of "low", "medium", "high". (only stored)
- `getImageSmoothingQuality()` (method, since 0.4.0): Returns the image smoothing quality. ("low", "medium", "high", initially "high")
  - returns string: Image smoothing quality.
- `setForceGizmosVisible(isForceGizmosVisible)` (method, since 0.2.0): Sets forced display of all gizmos.
  - `isForceGizmosVisible` boolean: If true, draws all gizmos regardless of each node's setting.
- `isForceGizmosVisible()` (method, since 0.2.0): Returns whether all gizmos are force-displayed.
  - returns boolean: True if all gizmos are forced visible.
- `pushState()` (method, since 0.3.0): Saves the state. (transform/alpha/blend/color/font/tint, equivalent to Canvas2D save)

  Example: Save the state and draw rotated

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2, Rect } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		graphic.pushState();
  		graphic.translate(320, 180);
  		graphic.rotate(Math.PI / 6);
  		graphic.setGlobalAlpha(0.5);
  		graphic.setFillColor("#ff6600");
  		graphic.drawRect(Rect.create(-50, -50, 100, 100));
  		graphic.popState();
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `popState()` (method, since 0.3.0): Restores the state. (equivalent to Canvas2D restore)
- `translate(x, y)` (method, since 0.3.0): Accumulates a translation transform.
  - `x` number: X translation.
  - `y` number: Y translation.
- `rotate(radian)` (method, since 0.3.0): Accumulates a rotation transform.
  - `radian` number: Rotation angle. (radians, clockwise on screen if positive)
- `scale(x, y)` (method, since 0.3.0): Accumulates a scale transform.
  - `x` number: X scale.
  - `y` number: Y scale.
- `setTransform(a, b, c, d, e, f)` (method, since 0.3.0): Sets the transform matrix directly. (equivalent to Canvas2D setTransform(a, b, c, d, e, f))
  - `a` number: Horizontal scaling. (x' = a x + c y + e)
  - `b` number: Vertical skewing. (y' = b x + d y + f)
  - `c` number: Horizontal skewing. (x' = a x + c y + e)
  - `d` number: Vertical scaling. (y' = b x + d y + f)
  - `e` number: Horizontal translation. (x' = a x + c y + e)
  - `f` number: Vertical translation. (y' = b x + d y + f)
- `resetTransform()` (method, since 0.3.0): Resets the transform matrix.
- `getTransformMatrix()` (method, since 0.3.0): Returns the current transform matrix.
  - returns TransformMatrix: The current transform matrix. (held and reused by Graphic, so clone it to keep its values)
- `setGlobalAlpha(value)` (method, since 0.3.0): Sets the global alpha.
  - `value` number: Global alpha. (clamped to 0 ~ 1)
- `getGlobalAlpha()` (method, since 0.3.0): Returns the global alpha.
  - returns number: Global alpha. (0 ~ 1)
- `multiplyGlobalAlpha(value)` (method, since 0.3.0): Multiplies into the global alpha. (for alpha inheritance in the node tree)
  - `value` number: Alpha to multiply by. (the product is clamped to 0 ~ 1)
- `setBlendMode(blendMode)` (method, since 0.3.0): Sets the blend mode. (accepts SpriteBlendMode strings, the 26 Canvas2D globalCompositeOperation modes)
  - The 13 modes possible with fixed blending (Porter-Duff operators, lighter, multiply, screen) are set with blendFunc.
  - The other 13 (overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color, luminosity)
    copy the area beneath each draw and blend in the shader. In these modes sprite batching is not used, and each draw costs one area copy and one draw call.
    (when drawing with a swapped-in shader, it draws to an overlay buffer first and then transfers, so two draw calls)
  - multiply blends in the shader only when drawing to a render target (while a framebuffer is bound). (getDrawShaderBlendModeIndex)
  - Unknown names draw as source-over.
  - `blendMode` string: Blend mode. (a Canvas2D globalCompositeOperation name, an unknown name warns once and draws with source-over)

  Example: Overlap light with additive blending

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		graphic.setBlendMode("lighter");
  		graphic.setFillColor("rgba(255, 80, 80, 0.8)");
  		graphic.drawCircle(Vector2.create(280, 180), 80);
  		graphic.setFillColor("rgba(80, 80, 255, 0.8)");
  		graphic.drawCircle(Vector2.create(360, 180), 80);
  		graphic.setBlendMode("source-over");
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `getBlendMode()` (method, since 0.3.0): Returns the blend mode.
  - returns string: Blend mode. (reset to "source-over" every frame)
- `setImageTintColor(color)` (method, since 0.3.0): Sets the image tint color. (null clears it)
  - Covers color only inside the image silhouette (alpha), at the tint.alpha ratio.
  - `color` Color | null: Tint color. (a copy is kept, cleared if not a Color)
- `getImageTintColor()` (method, since 0.3.0): Returns the image tint color.
  - returns Color | null: Tint color. (null if none)
- `setFillColor(color)` (method, since 0.0.9): Sets the color.
  - `color` Color | string: Fill color. (a Color or a "#rrggbb(aa)" or "rgb(a)(...)" string, unchanged if falsy)
- `getFillColor()` (method, since 0.3.0): Returns the fill color.
  - returns Color: Fill color. (initially black)
- `setStrokeColor(color)` (method, since 0.0.9): Sets the color.
  - `color` Color | string: Stroke color. (a Color or a "#rrggbb(aa)" or "rgb(a)(...)" string, unchanged if falsy)
- `getStrokeColor()` (method, since 0.3.0): Returns the stroke color.
  - returns Color: Stroke color. (initially black)
- `writeQuad(offset, leftX, topY, rightX, bottomY, leftU, topV, rightU, bottomV)` (method, since 0.3.0): Writes a quad (2 triangles, 6 vertices) into the vertex data.
  - Returns the offset (in floats) after writing.
  - `offset` number: Position to start writing at. (in floats)
  - `leftX` number: Left X.
  - `topY` number: Top Y.
  - `rightX` number: Right X.
  - `bottomY` number: Bottom Y.
  - `leftU` number: Left U. (0 ~ 1)
  - `topV` number: Top V. (0 ~ 1)
  - `rightU` number: Right U. (0 ~ 1)
  - `bottomV` number: Bottom V. (0 ~ 1)
  - returns number: Position after writing. (in floats, offset plus 24)
- `drawVertices(vertexCount, texture, color)` (method, since 0.3.0): Outputs the recorded vertices. (the single point all draws converge on, the future batching insertion point)
  - `vertexCount` number: Number of vertices to draw. (written to getVertexData, nothing is drawn if 0 or less)
  - `texture` WebGLTexture: Texture to use.
  - `color` Color: Color to multiply by.

  Example: Write vertices directly and draw

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2, Color } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		const floatCount = graphic.writeQuad(0, 100, 100, 300, 200, 0, 0, 1, 1);
  		const whiteTexture = graphic.getWhiteTexture();
  		const color = Color.createFromHEX("#ff00ff");
  		graphic.drawVertices(floatCount / 4, whiteTexture, color);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `uploadDrawUniforms(shaderProgram, color)` (method, since 0.4.0): Uploads the uniforms for one draw call. (called by drawVertices)
  - Uniform locations are looked up again only when the shader program changes.
  - The default program's tint and global alpha are not re-uploaded if equal to the last uploaded values. (forgotten at frame start and when the program changes)
  - Always uploaded for a swapped-in shader program.
  - `shaderProgram` ShaderProgram: Shader program to upload to.
  - `color` Color: Color to upload as mainColor.
- `isContextLost()` (method, since 0.4.0): Whether the WebGL context is lost.
  - returns boolean: true if lost.

  Example: Skipping the game drawing while the context is lost

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  if (!engine.getGraphic().isContextLost()) {
  	console.log("draw");
  }
  ```

- `enableGpuMemoryTracking()` (method, since 0.4.0): Turning on GPU memory tracking

  Example: Turning on GPU memory tracking

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  engine.getGraphic().enableGpuMemoryTracking();
  console.log(engine.getGraphic().isGpuMemoryTrackingEnabled());
  ```

- `isGpuMemoryTrackingEnabled()` (method, since 0.4.0): Whether GPU memory tracking is on.
  - returns boolean: true if on.

  Example: Reading whether GPU memory tracking is on

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  engine.run(new Scene());
  console.log(engine.getGraphic().isGpuMemoryTrackingEnabled());
  ```

- `readGpuMemoryUsage()` (method, since 0.4.0): Reads GPU memory. (For development)
  - returns { totalBytes: number, canvasBytes: number, kindTable: object, ownerList: Array<{ owner: string, kind: string, count: number, bytes: number }> }: Total (including the default framebuffer share of the canvas), canvas share, per-kind { count, bytes }, per-owner shares (largest first, the owner is the top three frames of the call stack that created the object).

  Example: Reading the GPU memory total and the largest owner

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.trackGpuMemory = true;
  const engine = new Engine(engineConfiguration);
  engine.run(new Scene());
  const usage = engine.getGraphic().readGpuMemoryUsage();
  console.log(usage.totalBytes, usage.ownerList.length > 0 ? usage.ownerList[0].owner : "none");
  ```

- `beginFrameStatistics()` (method, since 0.3.2): Starts frame draw statistics.
  - The engine calls this every frame before drawing the scene. Keeps the last frame's draw call / vertex counts and clears this frame's values.
  - Counts only the 2D path (drawVertices, drawColoredQuads). The 3D renderer and screen effect passes are not counted.
- `getLastFrameDrawCallCount()` (method, since 0.3.2): Returns the last frame's draw call count.
  - returns number: The last frame's draw call count.
- `getLastFrameVertexCount()` (method, since 0.3.2): Returns the number of vertices drawn in the last frame.
  - returns number: Number of vertices drawn in the last frame.
- `getLastFrameTriangleCount()` (method, since 0.3.2): Returns the number of triangles drawn in the last frame. (every draw call is a triangle list)
  - returns number: Number of triangles drawn in the last frame.
- `setCullingEnabled(isCullingEnabled)` (method, since 0.4.0): Sets off-screen culling. (default true)
  - When on, before WorldNode draws its components, if all enabled components report that they draw only inside the content area (Component.isDrawnInsideContent),
    the node's component drawing is skipped when the content area is off screen. Children are each checked separately and drawn as usual.
  - The test uses the bounding box of the area moved by the current transform at draw time (parent position, scale, rotation and anything set with pushState).
  - If even one component that does not report (default, text, particle, user-made components) is enabled, the node is not culled. Nodes that override draw are not culled either.
  - With subtree culling (setSubtreeCullingEnabled, on by default), when a node's subtree draw bounds (TransformNode.readSubtreeDrawBounds) are off screen,
    the draw traversal of that node and its descendants is skipped entirely. (tick updates still run)
  - `isCullingEnabled` boolean: Whether to enable off screen culling. (enabled only when true)
- `isCullingEnabled()` (method, since 0.4.0): Returns whether off-screen culling is on.
  - returns boolean: True if off screen culling is on.
- `setSubtreeCullingEnabled(isSubtreeCullingEnabled)` (method, since 0.4.0): Sets off-screen subtree culling. (default true, culls only while off-screen culling setCullingEnabled is on)
  - When on, after drawNode applies a node's transform it moves that node's subtree draw bounds (TransformNode.readSubtreeDrawBounds) by the current transform,
    and if they are outside the screen and the active clips (beginClipRect) the draw traversal of that node and its descendants is skipped entirely. (invisible rows of a scroll list are not visited)
  - The bounds are recalculated only when a transform, content size, child, active state, visibility or component changes. A subtree that contains something whose drawing area is unknown is never skipped.
  - Updates (tick) still run. Nothing is skipped while all gizmos are forced visible (setForceGizmosVisible).
  - `isSubtreeCullingEnabled` boolean: Whether to turn on off-screen subtree culling. (turns on only when true)

  Example: Read how many rows were skipped in a scroll list

  ```js
  import { Engine, EngineConfiguration, Scene } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		graphic.setSubtreeCullingEnabled(true);
  		super.draw(graphic);
  		console.log(graphic.isSubtreeCullingEnabled(), graphic.getLastFrameCulledSubtreeCount());
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `isSubtreeCullingEnabled()` (method, since 0.4.0): Returns whether off-screen subtree culling is on.
  - returns boolean: True if on. (nothing is culled while off-screen culling is off, even if this is on)
- `getLastFrameCulledSubtreeCount()` (method, since 0.4.0): Returns the number of subtrees whose drawing was skipped entirely in the last frame because they were off screen.
  - returns number: The number of subtrees skipped in the last frame.
- `isInsideVisibleBounds()` (method, since 0.4.0): Returns whether a node whose subtree lies fully inside the visible rectangle is being drawn. (Decided by the draw traversal)
  - When subtree culling finds that a node's subtree bounds lie fully inside the visible rectangle (the screen and active clips shrunk by one device pixel), this is true while that node is drawn.
    Its descendants are drawn without off-screen tests (subtree bounds, component culling, visible child range). Only descendants that draw nothing (bounds of size 0) are skipped.
  - If a new clip (beginClipRect, masks and scroll views) is set below it, this is false until that clip ends. (Tested again inside the new clip)
  - False if off-screen culling or subtree culling is off, or all gizmos are drawn.
  - returns boolean: True if the node being drawn lies fully inside the visible rectangle.

  Example: A component of a node fully inside the visible rectangle skipping the test

  ```js
  import { Engine, EngineConfiguration, Scene, WorldNode, Component, Paint, Rect, Vector2, Pivot, Colors } from "./build/vanilla.js";
  
  class InsideProbe extends Component {
  	isDrawnInsideContent() {
  		return true;
  	}
  	draw(graphic) {
  		graphic.setFillColor(Colors.white);
  		graphic.drawRect(Rect.create(0, 0, 10, 10));
  		console.log(graphic.isInsideVisibleBounds());
  	}
  }
  
  class MainScene extends Scene {
  	initialize(engine) {
  		super.initialize(engine);
  		const node = new WorldNode();
  		node.setPivot(Pivot.topLeft);
  		node.setRect(100, 100, 40, 40);
  		node.addComponent(Paint);
  		node.addComponent(InsideProbe);
  		this.getRoot().addChild(node);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `readLocalVisibleBounds(rect)` (method, since 0.4.0): Reads the visible rectangle (the screen and active clips) moved back into the current transform's local coordinates as a bounding box. (Only while subtree culling is on; true if known)
  - With rotation or skew it is conservative (the bounding box of the four corners, grown by one device pixel). Anything drawn outside this rectangle is not visible.
  - Used by a node to find the visible range among many children (TransformNode.drawChildren). Not recalculated while the transform and clip stay the same.
  - False if off-screen culling or subtree culling is off, all gizmos are drawn, the viewport is not set yet, or the transform cannot be inverted (scale 0).
  - `rect` Rect: Where to write the bounding box. (In the current transform's local coordinates)
  - returns boolean: True if known. (Otherwise rect is left untouched)

  Example: Reading the visible rectangle under the current transform

  ```js
  import { Engine, EngineConfiguration, Scene, Rect } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		const visibleRect = Rect.zero();
  		graphic.pushState();
  		graphic.translate(100, 0);
  		console.log(graphic.readLocalVisibleBounds(visibleRect), visibleRect.position.x < -100);
  		graphic.popState();
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `addCulledSubtreeCount(culledSubtreeCount)` (method, since 0.4.0): Adds to the number of subtrees whose drawing was skipped entirely this frame because they were off screen. (TransformNode.drawChildren calls it after skipping the children outside the visible range at once)
  - `culledSubtreeCount` number: The number of subtrees to add.
- `isLocalRectVisible(rect)` (method, since 0.4.0): Returns whether a rectangle moved by the current transform overlaps the screen (drawing buffer) and the active clip. (judged by the bounding box of the four moved corners)
  - It works in the same device pixel coordinates as the projection, so it equals testing outside clip space. (correct even when drawing to a smaller viewport)
  - Outside the bounding box of the clips set with beginClipRect (all nested ones), it counts as not visible. (like Unity RectMask2D, rows outside a scroll view are not drawn)
  - Before the viewport is set (before applySettings), it counts as overlapping.
  - `rect` Rect: Rect before the current transform. (local coordinates)
  - returns boolean: True if it overlaps the screen.
- `addCulledNodeCount(culledNodeCount)` (method, since 0.4.0): Adds to this frame's count of nodes whose components were skipped for being off screen. (called by WorldNode)
  - `culledNodeCount` number: Number of nodes to add.
- `getLastFrameCulledNodeCount()` (method, since 0.4.0): Returns the last frame's count of nodes whose components were skipped for being off screen.
  - returns number: Number of nodes skipped in the last frame.
- `setBatchingEnabled(isBatchingEnabled)` (method, since 0.4.0): Turns batched drawing on and off. (the engine turns it on at the start, off means one draw call per draw)
  - When on, consecutive draws (images, shapes, text, vertex-color quads) are accumulated with transform and color carried in the vertices and drawn in one draw call.
  - One batch binds several textures (the smaller of the device texture unit count and 16), so the batch continues when the texture changes. (the same scheme as PixiJS)
  - Axis-aligned clips (beginClipRect) whose edges lie on pixel boundaries are clipped by the shader with a clip rectangle carried in the vertices, so they do not break the batch. (rotated or rounded clips use the stencil)
  - When the texture slots fill up, when the blend, a stencil clip or a swapped-in shader changes, or when the buffer is full, what has accumulated is drawn, and the engine draws the rest at the end of the frame.
  - Drawing outside the engine loop (a Graphic made without an engine, your own requestAnimationFrame, an input handler) is also drawn when that task ends (a microtask). That is before the browser presents the canvas, so it shows without an explicit flush, like a 2D canvas.
  - When inserting a pass that touches WebGL directly (an external renderer and the like) while it is on, call flushBatch() first.
  - `isBatchingEnabled` boolean: Whether to enable batching. (enabled only when true, turning it off draws what is queued first)
- `isBatchingEnabled()` (method, since 0.4.0): Returns whether batched drawing is on.
  - returns boolean: True if batching is on.
- `flushBatch()` (method, since 0.4.0): Draws the accumulated batch. (does nothing if nothing has accumulated)
  - Binds the batch textures to units from 0 up. Units of unused slots get the white texture, so a texture from an earlier draw never forms a feedback loop even if it is the current target (render target).
- `setGeometryCachingEnabled(isGeometryCachingEnabled)` (method, since 0.4.0): Turns the geometry cache on or off. (on by default)
  - When on, the vertices drawn by components that report their draw inputs through writeGeometryKey (Paint, UIView, Text, etc.) are cached per component.
    If the inputs, transform and opacity are unchanged, draw is not called and the cache is copied into the batch; if only the translation changes (scrolling etc.), only the new matrix is applied to the cached local vertices.
    (the same idea as Unity UGUI keeping each Graphic's mesh in local space and rebuilding only what changed, and Unreal Slate Invalidation)
  - When off, draw is called for every component every frame as in earlier versions. (the screen result is the same)
  - `isGeometryCachingEnabled` boolean: Whether to enable it.

  Example: Turning the geometry cache off and on and reading the reuse count

  ```js
  import { Engine, EngineConfiguration, Scene, WorldNode, Paint, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	initialize(engine) {
  		super.initialize(engine);
  		const boxNode = new WorldNode();
  		boxNode.setLocalPosition(Vector2.create(320, 180));
  		boxNode.setContentSize(Vector2.create(200, 100));
  		boxNode.addComponent(Paint).setColor("#3399ff");
  		this.getRoot().addChild(boxNode);
  	}
  	draw(graphic) {
  		graphic.setGeometryCachingEnabled(true);
  		super.draw(graphic);
  		console.log(graphic.isGeometryCachingEnabled(), graphic.getLastFrameGeometryCacheHitCount());
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `isGeometryCachingEnabled()` (method, since 0.4.0): Returns whether the geometry cache is on.
  - returns boolean: True if enabled.
- `getLastFrameGeometryCacheHitCount()` (method, since 0.4.0): Returns the number of components drawn from the geometry cache in the last frame. (draw was not called)
  - returns number: Number of components drawn by copying the cache as is or by applying only the new matrix.
- `getLastFrameGeometryRebuildCount()` (method, since 0.4.0): Returns the number of components whose geometry cache was rewritten in the last frame. (among caching components, those whose draw was called)
  - returns number: Number of components whose draw was called again because inputs, scale, rotation, etc. changed.
- `getLastFrameRetainedBatchCount()` (method, since 0.4.0): Returns the number of batches in the last frame drawn from buffers retained on the GPU without uploading vertices again.
  - When every segment put into a batch (geometry cache segments with their versions, and the vertex values of spans written directly without a cache) matches the batch at the same position in the previous frame, no vertices are copied or uploaded and only the draw call is issued.
  - A batch where only part changed uploads only the changed ranges with bufferSubData and is not counted here.
  - returns number: Number of batches drawn from retained buffers.

  Example: Checking that a still UI is drawn from retained batches

  ```js
  import { Engine, EngineConfiguration, Scene, WorldNode, Paint, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	initialize(engine) {
  		super.initialize(engine);
  		const boxNode = new WorldNode();
  		boxNode.setLocalPosition(Vector2.create(320, 180));
  		boxNode.setContentSize(Vector2.create(200, 100));
  		boxNode.addComponent(Paint).setColor("#3399ff");
  		this.getRoot().addChild(boxNode);
  	}
  	draw(graphic) {
  		super.draw(graphic);
  		console.log(graphic.getLastFrameRetainedBatchCount(), graphic.getLastFrameDrawCallCount());
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `drawComponent(component)` (method, since 0.4.0): Draws a component. (nodes call it for each component, it goes through the geometry cache)
  - If the component does not report its inputs through writeGeometryKey, the cache is off, or the state is not batched, draw is called as is.
  - If the inputs and the drawing state (scale, rotation, blend, tint, text direction) are the same as last time:
    if the translation and opacity are also the same, the cached device vertices are copied into the batch as is; otherwise the current matrix and opacity are applied again to the cached local vertices.
    (scrolling only changes the parent's translation, so child components only do a matrix multiply without draw; text recomputes pixel snapping identically)
  - Otherwise draw is called to rewrite the cache. If the draw does work outside the batch such as clipping, layers or changing the blend mode, that component is not cached.
  - `component` Component: Component to draw.
- `getParticleVertexData(minimumFloatCount)` (method, since 0.3.0): Returns the particle batch vertex array. (grows as needed, interleaved x, y, u, v, r, g, b, a)
  - `minimumFloatCount` number: Minimum number of floats needed. (doubled until large enough)
  - returns Float32Array: Particle vertex array. (x, y, u, v, r, g, b, a per vertex, a new array when grown)
- `drawColoredQuads(vertexCount, texture)` (method, since 0.3.0): Outputs the particle batch. (draws the vertices filled into getParticleVertexData at once)
  - `vertexCount` number: Number of vertices to draw. (nothing is drawn if 0 or less)
  - `texture` WebGLTexture: Texture to use. (such as getSoftDiscTexture)

  Example: Draw quads with per vertex colors at once

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  const COLOR_LIST = [[1, 0.3, 0.3], [0.3, 1, 0.3], [0.3, 0.5, 1]];
  const CORNER_LIST = [[0, 0], [1, 0], [0, 1], [0, 1], [1, 0], [1, 1]];
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		const quadCount = COLOR_LIST.length;
  		const vertexData = graphic.getParticleVertexData(quadCount * 6 * 8);
  		let offset = 0;
  		for (let quadIndex = 0; quadIndex < quadCount; ++quadIndex) {
  			const leftX = 120 + quadIndex * 150;
  			const topY = 140;
  			const size = 80;
  			const color = COLOR_LIST[quadIndex];
  			for (const corner of CORNER_LIST) {
  				vertexData[offset++] = leftX + corner[0] * size;
  				vertexData[offset++] = topY + corner[1] * size;
  				vertexData[offset++] = corner[0];
  				vertexData[offset++] = corner[1];
  				vertexData[offset++] = color[0];
  				vertexData[offset++] = color[1];
  				vertexData[offset++] = color[2];
  				vertexData[offset++] = 1;
  			}
  		}
  		const softDiscTexture = graphic.getSoftDiscTexture();
  		graphic.drawColoredQuads(quadCount * 6, softDiscTexture);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `getSoftDiscTexture()` (method, since 0.3.0): Returns the soft circle texture. (64x64 circle that fades out at the edge, the default particle sprite)
  - returns WebGLTexture: Soft disc texture. (created on the first call)
- `drawLine(positions, size = 1)` (method, since 0.0.9): Draws a line.
  - setStrokeColor()
  - `positions` Vector2[]: Points the line passes through. (nothing is drawn if fewer than 2)
  - `size` number: Line width. (default 1)
- `drawLineLoop(positions, size = 1)` (method, since 0.3.0): Draws a closed line. (a loop joining the last point to the first)
  - setStrokeColor()
  - `positions` Vector2[]: Points the line passes through. (nothing is drawn if fewer than 2)
  - `size` number: Line width. (default 1)
- `drawPolyline(positions, size, isClosed)` (method, since 0.3.0): Draws a polyline. (per-segment quads expanded by thickness)
  - Inner joints are filled by extending half the thickness.
  - When the vertex buffer fills, it draws what has accumulated, empties it and keeps writing. (segments are not dropped even with many points)
  - `positions` Vector2[]: Points the line passes through. (nothing is drawn if fewer than 2)
  - `size` number: Line width.
  - `isClosed` boolean: Connects the last point to the first if true.
- `drawRect(rect)` (method, since 0.0.9): Draws a rectangle.
  - setFillColor()
  - `rect` Rect: Rect to fill.
- `drawStrokeRect(rect, lineWidth = 1)` (method, since 0.3.0): Draws a rectangle outline. (equivalent to Canvas2D strokeRect, line center on the border)
  - setStrokeColor()
  - `rect` Rect: Rect to outline.
  - `lineWidth` number: Line width. (default 1)
- `buildRoundRectPositions(rect, roundSize)` (method, since 0.3.0): Creates the list of rounded rectangle path coordinates. (clockwise, convex polygon)
  - `rect` Rect: Rect.
  - `roundSize` number: Corner radius. (clamped to half of the shorter side)
  - returns Vector2[]: Points of the path. (a new array)
- `writeRoundRectPositionData(rect, roundSize)` (method, since 0.4.0): Writes the rounded rectangle path coordinates into ROUND_RECT_POSITION_DATA. (clockwise, convex polygon, x, y order)
  - The cos / sin for each point come from a table computed up front.
  - `rect` Rect: Rect.
  - `roundSize` number: Corner radius. (clamped to half of the shorter side)
- `drawConvexPolygon(positions, color)` (method, since 0.3.0): Draws a filled convex polygon. (fan split from the first point)
  - When the vertex buffer fills, it draws the accumulated triangles, empties it and keeps writing. (triangles are not dropped even with many points)
  - `positions` Vector2[]: Points of the convex polygon. (nothing is drawn if fewer than 3)
  - `color` Color: Color to fill with.
- `drawRoundRect(rect, roundSize)` (method, since 0.0.9): Draws a rounded rectangle.
  - setFillColor()
  - `rect` Rect: Rect to fill.
  - `roundSize` number: Corner radius. (a sharp rectangle if 0 or less, clamped to half of the shorter side)
- `drawRoundRectPositionData(color)` (method, since 0.4.0): Draws the filled rounded rectangle written in ROUND_RECT_POSITION_DATA. (fan split from the first point, same triangles as drawConvexPolygon)
  - `color` Color: Color to fill with.
- `drawStrokeRoundRect(rect, roundSize, lineWidth = 1)` (method, since 0.3.0): Draws a rounded rectangle outline.
  - setStrokeColor()
  - `rect` Rect: Rect to outline.
  - `roundSize` number: Corner radius. (a sharp rectangle if 0 or less, clamped to half of the shorter side)
  - `lineWidth` number: Line width. (default 1)
- `drawCircle(center, radius)` (method, since 0.0.9): Draws a circle.
  - setFillColor()
  - `center` Vector2: Center.
  - `radius` number: Radius. (nothing is drawn if 0 or less)
- `drawStrokeCircle(center, radius, lineWidth = 1)` (method, since 0.3.0): Draws a circle outline.
  - setStrokeColor()
  - `center` Vector2: Center.
  - `radius` number: Radius. (nothing is drawn if 0 or less)
  - `lineWidth` number: Line width. (default 1)
- `drawRing(center, innerRadius, outerRadius, startRadian = 0, endRadian = Math.PI * 2)` (method, since 0.4.0): Draws a ring (band). (fills between the inner and outer radius from startRadian to endRadian)
  - setFillColor()
  - Angles are in radians, 0 is to the right and increases clockwise on screen. (-PI / 2 to start at 12 o'clock)
  - Each segment is one quad joined without overlap and drawn at once, so the seams between segments do not darken even with a translucent color.
  - The segment count follows the on-screen outer radius like drawCircle (16 ~ 64 per full turn), and only the portion for the drawn angle is used.
  - `center` Vector2: Center.
  - `innerRadius` number: Inner radius.
  - `outerRadius` number: Outer radius. (nothing is drawn if 0 or less, or not greater than the inner radius)
  - `startRadian` number: Default 0.
  - `endRadian` number: Default PI * 2.

  Example: Fill a ring clockwise from 12 o'clock

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		const center = Vector2.create(320, 180);
  		const progress = 0.7;
  		const startRadian = -Math.PI / 2;
  		graphic.setFillColor("#44dd88");
  		graphic.drawRing(center, 50, 70, startRadian, startRadian + Math.PI * 2 * progress);
  		graphic.setStrokeColor("#ffffff");
  		graphic.drawArc(center, 90, startRadian, startRadian + Math.PI, 3);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `drawArc(center, radius, startRadian, endRadian, lineWidth = 1)` (method, since 0.4.0): Draws an arc. (a line of lineWidth thickness along the radius, from startRadian to endRadian)
  - setStrokeColor()
  - Angles and segment count are the same as drawRing. The middle of the line thickness lies on the radius.
  - `center` Vector2: Center.
  - `radius` number: Radius. (the middle of the line width)
  - `startRadian` number: Start angle. (radians)
  - `endRadian` number: End angle. (radians)
  - `lineWidth` number: Default 1.
- `drawRingWithColor(centerX, centerY, innerRadius, outerRadius, startRadian, endRadian, color)` (method, since 0.4.0): Ring drawing computation. (called by drawRing, drawArc)
  - `centerX` number: Center X.
  - `centerY` number: Center Y.
  - `innerRadius` number: Inner radius.
  - `outerRadius` number: Outer radius. (nothing is drawn if 0 or less, or not greater than the inner radius)
  - `startRadian` number: Start angle. (radians)
  - `endRadian` number: End angle. (radians, nothing is drawn if equal to the start angle, clamped to one full turn)
  - `color` Color: Color to fill with.
- `drawLineSegments(positionValues, size = 1)` (method, since 0.4.0): Draws multiple line segments. (one position array with four values x0, y0, x1, y1 per segment, drawn at once)
  - setStrokeColor()
  - Each segment is one quad widened by the thickness. (unlike drawLine, joints are not filled, meant for separate segments)
  - Reads number arrays (Array, Float32Array) directly without creating Vector2 arrays. Zero-length segments are skipped.
  - When the vertex buffer fills, draws up to there and continues filling. (with sprite batching on, it is the same texture so it continues as one draw call)
  - `positionValues` number[] | Float32Array: Number array with x0, y0, x1, y1 for each segment. (nothing is drawn if fewer than four)
  - `size` number: Default 1.

  Example: Draw grid lines at once

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		const positionValues = [];
  		for (let x = 0; x <= 640; x += 40) {
  			positionValues.push(x, 0, x, 360);
  		}
  		for (let y = 0; y <= 360; y += 40) {
  			positionValues.push(0, y, 640, y);
  		}
  		graphic.setStrokeColor("rgba(255, 255, 255, 0.3)");
  		graphic.drawLineSegments(positionValues, 1);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `prepareImage(image)` (method, since 0.4.0): Uploads an image to the GPU in advance. (Call it while loading so that decoding and uploading do not pile up on the first drawn frame)
  - Uploads with the current image smoothing and mipmap settings. (If the settings differ when drawing, only the filtering changes then)
  - Does nothing if the image is already uploaded. Does not upload an image that is not loaded yet (size 0).
  - Use it in a scene's load to upload images that were not loaded with ImageAsset, such as canvases made in code.
  - `image` HTMLImageElement | HTMLCanvasElement | OffscreenCanvas: The image to upload.
  - returns boolean: true if a texture exists. (false if null or the image is not loaded yet)

  Example: Upload an image made in code while the scene loads

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	async load(engine) {
  		await super.load(engine);
  		this.dotImage = new OffscreenCanvas(32, 32);
  		const context = this.dotImage.getContext("2d");
  		context.fillStyle = "#ff6600";
  		context.fillRect(0, 0, 32, 32);
  		const isPrepared = engine.getGraphic().prepareImage(this.dotImage);
  		console.log(isPrepared);
  	}
  
  	draw(graphic) {
  		super.draw(graphic);
  		graphic.drawImage(this.dotImage, Vector2.create(304, 164), Vector2.create(32, 32));
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `prepareLoadedImages(timeLimitMilliseconds = System.Infinity)` (method, since 0.4.0): Uploads images that were loaded but not uploaded yet. (Images loaded by ImageAsset, in loading order)
  - SceneManager calls it split across frames after a scene's load finishes (during the loading screen). A scene does not need to call it.
  - Given a time limit, it stops after exceeding that time and returns the remaining count. (Uploads at least one per call, same as Unity's asyncUploadTimeSlice)
  - A pre-decoded image (ImageBitmap) is closed after uploading. An image of a format that is not pre-decoded is uploaded from the image element as is.
  - `timeLimitMilliseconds` number: The time limit to use this time. (Milliseconds, the default Infinity means all)
  - returns number: The number of images still left to upload. (0 means all are uploaded)

  Example: Upload images right after loading them

  ```js
  import { Engine, EngineConfiguration, Scene, ImageAsset, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	async load(engine) {
  		await super.load(engine);
  		this.imageAsset = new ImageAsset();
  		await this.imageAsset.load("examples/assets/spritesheet.png");
  		const remainingCount = engine.getGraphic().prepareLoadedImages();
  		console.log(remainingCount);
  	}
  
  	draw(graphic) {
  		super.draw(graphic);
  		graphic.drawImage(this.imageAsset.getImage(), Vector2.create(170, 30), Vector2.create(300, 300));
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `drawImage(image, position, contentSize)` (method, since 0.0.9): Draws an image.
  - setFillColor() Not Supported.
  - `image` HTMLImageElement | HTMLCanvasElement: Image to draw. (throws an error if null or undefined)
  - `position` Vector2: Top left to draw at.
  - `contentSize` Vector2: Size to draw. (flipped if negative)
- `drawImageWithImageRect(image, position, contentSize, imageRect)` (method, since 0.0.9): Draws only part of an image.
  - setFillColor() Not Supported.
  - `image` HTMLImageElement | HTMLCanvasElement: Image to draw. (throws an error if null or undefined)
  - `position` Vector2: Top left to draw at.
  - `contentSize` Vector2: Size to draw. (flipped if negative)
  - `imageRect` Rect: Area of the image to draw. (pixels, the whole image if null or empty)
- `drawImageWithSourceAndDestination(image, sourceX, sourceY, sourceWidth, sourceHeight, destinationX, destinationY, destinationWidth, destinationHeight)` (method, since 0.3.0): Draws a source region of an image into a given region. (equivalent to the 9-argument Canvas2D drawImage)
  - `image` HTMLImageElement | HTMLCanvasElement: Image to draw. (nothing is drawn if its size is 0 because it is not loaded yet)
  - `sourceX` number: Left inside the image. (pixels)
  - `sourceY` number: Top inside the image. (pixels)
  - `sourceWidth` number: Width inside the image. (pixels)
  - `sourceHeight` number: Height inside the image. (pixels)
  - `destinationX` number: Left to draw at.
  - `destinationY` number: Top to draw at.
  - `destinationWidth` number: Width to draw. (flipped if negative)
  - `destinationHeight` number: Height to draw. (flipped if negative)

  Example: Draw a piece of an image

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2, ImageAsset } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	async load(engine) {
  		await super.load(engine);
  		this.imageAsset = new ImageAsset();
  		await this.imageAsset.load("examples/assets/spritesheet.png");
  	}
  
  	draw(graphic) {
  		super.draw(graphic);
  		const image = this.imageAsset.image;
  		graphic.drawImageWithSourceAndDestination(image, 200, 0, 200, 200, 220, 80, 200, 200);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `drawImageWithNineSlice(image, position, size, nineSlice)` (method, since 0.0.9): Draws an image as a nine-patch.
  - setFillColor() Not Supported.
  - `image` HTMLImageElement | HTMLCanvasElement: Image to draw.
  - `position` Vector2: Top left to draw at. (floored)
  - `size` Vector2: Size to draw. (ceiled, at least the sum of the border thicknesses)
  - `nineSlice` Rect: Nine slice borders. (position.x left, position.y top, size.x right, size.y bottom thickness, pixels)
- `setFontString(fontString)` (method, since 0.3.0): Sets the font string. (equivalent to Canvas2D font, e.g. "16px DOSGothic", the family name default is the engine default font chain)
  - `fontString` string: CSS font string. (e.g. "16px DOSGothic", the family name default is the engine default font chain SYSTEM_FONT_STRING, unchanged if empty)
- `getFontString()` (method, since 0.3.0): Returns the font string.
  - returns string: CSS font string. (initially "10px sans-serif")
- `setTextAlign(textAlign)` (method, since 0.3.0): Sets the horizontal text alignment. ("left" | "center" | "right" | "start" | "end")
  - `textAlign` string: Horizontal alignment. (unchanged if empty)
- `getTextAlign()` (method, since 0.3.0): Returns the horizontal text alignment.
  - returns string: Horizontal alignment. (initially "start")
- `setTextDirection(textDirection)` (method, since 0.3.2): Sets the text direction. ("inherit" | "ltr" | "rtl" | "auto", equivalent to Canvas2D direction)
  - This is the paragraph direction. The order within the text (bidirectional algorithm) and the left/right of alignment "start" / "end" follow it.
  - "inherit" is treated as "ltr". (default, same as before)
  - "auto" decides per string by the first strongly directional character. (HTML dir="auto", "ltr" if none) Used for user-written text (nicknames, etc.).
  - `textDirection` string: Text direction. (unchanged if empty)
- `getTextDirection()` (method, since 0.3.2): Returns the text direction.
  - returns string: Text direction. (initially "inherit")
- `resolveTextDirection(text)` (method, since 0.3.2): Computes the actual direction of a string. ("ltr" or "rtl", "auto" uses the first strongly directional character)
  - `text` string: Text that decides the direction. (inspected only for "auto")
  - returns string: "ltr" or "rtl".
- `resolveTextAlign(textAlign, textDirection)` (method, since 0.3.2): Computes the actual horizontal alignment. ("start" / "end" become "left" / "right" by direction)
  - `textAlign` string: Alignment. ("left", "center", "right", "start", "end", "left" for unknown values)
  - `textDirection` string: "ltr" or "rtl".
  - returns string: "left" | "center" | "right"
- `setTextBaseline(textBaseline)` (method, since 0.3.0): Sets the text baseline. ("top" | "hanging" | "middle" | "alphabetic" | "ideographic" | "bottom")
  - `textBaseline` string: Vertical baseline. (unchanged if empty)
- `getTextBaseline()` (method, since 0.3.0): Returns the text baseline.
  - returns string: Vertical baseline. (initially "alphabetic")
- `measureText(text)` (method, since 0.3.0): Measures a string. (based on the current font, equivalent to Canvas2D measureText)
  - `text` string: Text to measure.
  - returns TextMetrics: Metrics measured with the current font. (shared by the cache so do not modify)
- `measureTextWithFontString(fontString, text)` (method, since 0.4.0): Measures a string. (with the given font string, does not change the current font string)
  - `fontString` string: Font string to measure with. (Canvas2D font form)
  - `text` string: Text to measure.
  - returns TextMetrics: Metrics measured with that font. (shared by the cache so do not modify it, the current transform is not considered)

  Example: Measuring with a larger font without changing the current font

  ```js
  import { Engine, EngineConfiguration } from "./build/vanilla.js";
  
  const engine = new Engine(new EngineConfiguration());
  const graphic = engine.getGraphic();
  const metrics = graphic.measureTextWithFontString("32px sans-serif", "Vanilla");
  console.log(metrics.width > 0, graphic.getFontString());
  ```

- `setTextBakeScaleStep(textBakeScaleStep)` (method, since 0.3.2): Sets the text bake scale quantization step.
  - Default 0.25. Groups scales so text that is zoomed often is not re-baked for every scale.
  - 0 means no quantization, baked at the actual scale. (for drawing fixed-scale UI text 1:1 without stretching)
  - `textBakeScaleStep` number: Quantization step. (negative becomes 0, no quantization if 0)
- `getTextBakeScaleStep()` (method, since 0.3.2): Returns the text bake scale quantization step.
  - returns number: Quantization step.
- `setTextBakeMotionScaleStep(textBakeMotionScaleStep)` (method, since 0.4.0): Sets the text bake scale quantization step for nodes whose scale is changing. (default 0.25)
  - When the quantization step (setTextBakeScaleStep) is 0 and the drawn node's transform scale differs from the last frame (zoom motion, popup, tween, camera zoom),
    bakes at the scale grouped by this step. Does not re-bake at a different scale every frame.
  - When the scale stops (same as the last frame), re-bakes at the exact scale so it is crisp 1:1.
  - 0 means no grouping even while changing. (same as before)
  - `textBakeMotionScaleStep` number: Quantization step while moving. (negative becomes 0, no grouping if 0)
- `getTextBakeMotionScaleStep()` (method, since 0.4.0): Returns the text bake scale quantization step for nodes whose scale is changing.
  - returns number: Quantization step while moving.
- `setTextBakeScaleMoving(isTextBakeScaleMoving)` (method, since 0.4.0): Sets whether the scale of the node being drawn is changing. (set by drawNode, the caller can set it when drawing directly outside a node)
  - `isTextBakeScaleMoving` boolean: Whether the scale is moving. (treated as moving only when true)
- `isTextBakeScaleMoving()` (method, since 0.4.0): Returns whether the scale of the node being drawn is changing.
  - returns boolean: True if the scale is moving.
- `readNodeTextBakeScaleMoving(node)` (method, since 0.4.0): Computes and remembers whether a node's transform scale differs from the last frame, that is, is changing. (called by drawNode after pushTransform)
  - If the quantization step is not 0, baking is always grouped, so this is not computed.
  - A node drawn for the first time is treated as not changing. (to avoid baking twice on the first frame)
  - A node that was not drawn in the previous frame (hidden, or skipped because its subtree was off screen) is also treated like one drawn for the first time. (the screen matches the unskipped case even if the scale changed while it was skipped)
  - `node` TransformNode: Node being drawn. (the current scale is stored on the node)
  - returns boolean: True if the scale differs from the last frame and is moving.
- `setTextPixelSnapEnabled(isTextPixelSnapEnabled)` (method, since 0.3.2): Sets text pixel snapping.
  - When on, aligns the top-left of glyph quads to the device pixel grid under transforms without rotation / skew.
  - Sharpest when the bake scale equals the actual scale (setTextBakeScaleStep(0)), as texels and pixels match 1:1.
  - `isTextPixelSnapEnabled` boolean: Whether to snap text quads to the device pixel grid.

  Example: Keep UI text crisp at 1:1

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	initialize(engine) {
  		const graphic = engine.getGraphic();
  		graphic.setTextBakeScaleStep(0);
  		graphic.setTextPixelSnapEnabled(true);
  	}
  
  	draw(graphic) {
  		super.draw(graphic);
  		graphic.setFillColor("#ffffff");
  		graphic.setFontString("16px sans-serif");
  		graphic.setTextAlign("left");
  		graphic.setTextBaseline("top");
  		graphic.drawFillText("Score 12345", 20, 20);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `isTextPixelSnapEnabled()` (method, since 0.3.2): Returns whether text pixel snapping is on.
  - returns boolean: True if text pixel snapping is on.
- `setTextAntialiasEnabled(isTextAntialiasEnabled)` (method, since 0.4.0): Turns text antialiasing on or off. (Same as Rust Graphic::set_text_antialias_enabled)
  
  When off, baked glyph alpha is split into 0 and 255 at threshold 128 and the texture is sampled with NEAREST. (For pixel fonts)
  It applies only to this Graphic. Text drawn after the change uses the new form. (Text already made changes from its next draw too; baked text is kept per form, so switching back does not bake again. On by default)
  - `isTextAntialiasEnabled` boolean: True to enable.

  Example: Crisp text like a pixel font

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	initialize(engine) {
  		engine.getGraphic().setTextAntialiasEnabled(false);
  	}
  
  	draw(graphic) {
  		super.draw(graphic);
  		graphic.setFillColor("#ffffff");
  		graphic.setFontString("16px sans-serif");
  		graphic.setTextAlign("left");
  		graphic.setTextBaseline("top");
  		graphic.drawFillText("PIXEL 123", 20, 20);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `isTextAntialiasEnabled()` (method, since 0.4.0): Whether text antialiasing is on.
  - returns boolean: True if on.
- `calculateTextBakeScale()` (method, since 0.3.0): Computes the text bake scale. (based on the current transform matrix, quantization step from setTextBakeScaleStep)
  - returns number: Bake scale. (0.25 ~ 8)
- `drawTextEntry(entry, x, y, color = null, textDirection = "ltr")` (method, since 0.3.0): Draws a text layout entry as glyph quads aligned to the alignment/baseline.
  - Computes the rectangle the whole string would occupy if baked at once (pixel snap included) and draws the glyph rectangles inside it from the atlas.
  - `entry` object: Text layout entry. (TextStringTextureCache.getEntry)
  - `x` number: Anchor X. (the alignment anchor)
  - `y` number: Anchor Y. (the position of the vertical baseline)
  - `color` Color | null: Color to multiply text baked in white by. (null keeps it white)
  - `textDirection` string: Direction that resolves alignment "start" / "end". ("ltr" or "rtl", default "ltr")
- `drawFillText(text, x, y)` (method, since 0.3.0): Draws filled text. (equivalent to Canvas2D fillText)
  - setFillColor() / setFontString() / setTextAlign() / setTextBaseline()
  - `text` string: Text to draw. (nothing is drawn if empty)
  - `x` number: Anchor X. (the alignment anchor)
  - `y` number: Anchor Y. (the position of the vertical baseline)
- `drawStrokeText(text, x, y, lineWidth = 1)` (method, since 0.3.0): Draws outlined text. (equivalent to Canvas2D strokeText)
  - setStrokeColor() / setFontString() / setTextAlign() / setTextBaseline()
  - `text` string: Text to draw. (nothing is drawn if empty)
  - `x` number: Anchor X. (the alignment anchor)
  - `y` number: Anchor Y. (the position of the vertical baseline)
  - `lineWidth` number: Line width. (default 1)
- `drawNode(node)` (method, since 0.0.9): Draws a node.
  - `node` TransformNode: Node to draw. (nothing is drawn if null or inactive)
- `beginClipRect(rect, roundSize = 0)` (method, since 0.0.9): Begins clipping the output region.
  - Stencil buffer based, so rotated/scaled regions are clipped exactly too.
  - Given roundSize, clips to a rounded rectangle. (matches the background exactly when equal to Paint's roundSize)
  - `rect` Rect: Rect to clip to. (local coordinates before the current transform)
  - `roundSize` number: Corner radius. (default 0, a sharp rectangle if 0 or less)

  Example: Clip drawing to a rounded rectangle

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2, Rect } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		graphic.beginClipRect(Rect.create(100, 60, 200, 200), 24);
  		graphic.setFillColor("#3399ff");
  		graphic.drawCircle(Vector2.create(300, 160), 120);
  		graphic.endClipRect();
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `beginOpacityLayer()` (method, since 0.4.0): Begins an opacity layer. (Like CSS opacity or an Adobe transparency group, everything drawn until endOpacityLayer is gathered in a separate buffer and laid down at once with the current global alpha)
  - Drawings inside the layer do not show through each other where they overlap. (Multiplying opacity per node and laying each down separately lets the drawing below show through at overlaps)
  - Inside the layer the global alpha starts at 1. The layer buffer is RGBA8 at the screen size, its depth is cleared and its stencil is filled with the current clip depth, so clips and 3D passes (clearDepth: false) inside the layer still work.
    Outer clips apply when the layer is laid down. Layers can be nested. If the buffer cannot be made, drawing goes straight through without a layer.
  - A node with setOpacityLayer turned on and opacity below 1 is drawn with its descendants as a layer.

  Example: Make two overlapping rectangles translucent as a group (the lower rectangle does not show through where they overlap)

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2, Rect } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		graphic.pushState();
  		graphic.setGlobalAlpha(0.5);
  		graphic.beginOpacityLayer();
  		graphic.setFillColor("#ff0000");
  		graphic.drawRect(Rect.create(100, 100, 200, 100));
  		graphic.setFillColor("#0000ff");
  		graphic.drawRect(Rect.create(200, 150, 200, 100));
  		graphic.endOpacityLayer();
  		graphic.popState();
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `endOpacityLayer()` (method, since 0.4.0): Ends an opacity layer. (Lays what was drawn after beginOpacityLayer onto the previous framebuffer with the global alpha at the time the layer was opened)
- `endClipRect()` (method, since 0.0.9): Ends clipping the output region.
- `getCanvas()` (method, since 0.3.0): Returns the canvas.
  - returns HTMLCanvasElement: Canvas.
- `getColorSpace()` (method, since 0.4.0): Returns the 3D color space. (ColorSpace, the default the toon renderer and post process read from the engine, this batch's 2D composites in gamma space either way)
  - returns string: ColorSpace.gamma or ColorSpace.linear.

  Example: Color space of a Graphic built from a canvas

  ```js
  import { Graphic, ColorSpace } from "./vanilla.js";
  const graphic = new Graphic(document.createElement("canvas"), false, true, ColorSpace.linear);
  if (graphic.getColorSpace() !== ColorSpace.linear) {
  	throw new Error("color space is not linear");
  }
  ```

- `getWebGL2RenderingContext()` (method, since 0.3.0): Returns the WebGL2 rendering context.
  - returns WebGL2RenderingContext: WebGL2 rendering context.
- `getCurrentFramebuffer()` (method, since 0.4.0): Return the framebuffer being drawn to now. (null means the canvas, a remembered value read without asking GL)
  - returns WebGLFramebuffer | null: The draw framebuffer bound now. (null means the canvas default framebuffer)

  Example: Switch the render target in an external pass and switch it back

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		graphic.runExternalPass((webGL2RenderingContext) => {
  			const previousFramebuffer = graphic.getCurrentFramebuffer();
  			const framebuffer = webGL2RenderingContext.createFramebuffer();
  			webGL2RenderingContext.bindFramebuffer(webGL2RenderingContext.FRAMEBUFFER, framebuffer);
  			webGL2RenderingContext.bindFramebuffer(webGL2RenderingContext.FRAMEBUFFER, previousFramebuffer);
  			webGL2RenderingContext.deleteFramebuffer(framebuffer);
  		}, { clearDepth: false });
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `getCurrentViewport()` (method, since 0.4.0): Return the current viewport. (device pixels, origin at the bottom left like GL, a remembered value read without asking GL)
  - returns Rect: The current viewport. (position x, y and size width, height, a new Rect)

  Example: Read the current viewport size

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		const viewport = graphic.getCurrentViewport();
  		console.log(viewport.position.x, viewport.position.y, viewport.width, viewport.height);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `resetGLStateCache()` (method, since 0.4.0): Resynchronize the remembered GL state. (call it after outside GL code changed the state, like resetState in three.js)
  - The engine intercepts the context's state functions (bindFramebuffer, viewport, enable and so on) and remembers them, so calls made through the same context object need no notice.
  - Call it after changing state in a way that cannot be intercepted, such as calling a prototype function directly. It forgets everything and asks GL once for each value the next time it is read.
    Graphic keeps no binding or state memory of its own and compares against this memory, so the 2D draws after it also set their own program, textures and blending again.

  Example: Resynchronize after changing state in a way that cannot be intercepted

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2 } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		graphic.runExternalPass((webGL2RenderingContext) => {
  			WebGL2RenderingContext.prototype.viewport.call(webGL2RenderingContext, 0, 0, 64, 64);
  			graphic.resetGLStateCache();
  			console.log(graphic.getCurrentViewport().width);
  		}, { clearDepth: false });
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `getDrawingBufferWidth()` (method, since 0.4.0): Returns the drawing buffer width. (pixels, the last set viewport)
  - returns number: Drawing buffer width. (pixels)
- `getDrawingBufferHeight()` (method, since 0.4.0): Returns the drawing buffer height. (pixels, the last set viewport)
  - returns number: Drawing buffer height. (pixels)
- `readFramebufferPixels()` (method, since 0.4.0): Reads the screen drawn so far. (width, height, RGBA laid out top to bottom. Call before the frame is presented)
  - Treated as opaque like a canvas. (alpha 255)
  - returns { width: number, height: number, pixels: Uint8Array }: Screen pixels. ({ width, height, pixels }, pixels are RGBA from the top row, alpha 255)
- `getShaderProgram()` (method, since 0.3.0): Returns the shader program.
  - returns ShaderProgram: Shader program in use. (the override if any)
- `setShaderProgramOverride(shaderProgram)` (method, since 0.3.0): Swaps in a shader program. (null returns to the default program)
  - Must have the same attribute locations / uniform names as the default program (projectionMatrix, modelMatrix, mainColor, tintColor, globalAlpha, mainTexture).
  - `shaderProgram` ShaderProgram | null: Shader program to swap in. (the default program if null)
- `restoreRenderState()` (method, since 0.3.0): Restores the render state. (when continuing Graphic output after an external WebGL pass changed the program / vertex array / viewport)
- `useShaderProgram(shaderProgram)` (method, since 0.4.0): Puts a shader program in use. (does not set it again if the state cache remembers this program is already in use)
  - Graphic keeps no memory of its own of the program in use. Even if a game puts another program in use through the same context, the next draw sets its own program again.
  - `shaderProgram` ShaderProgram: Shader program to use.
- `bindTexture(texture)` (method, since 0.4.0): Binds a texture to texture unit 0. (does not bind it again if the state cache remembers it is already bound)
  - If the active unit is not 0, switches back to unit 0. (binds to unit 0 even when a game comes back leaving another unit active)
  - `texture` WebGLTexture: Texture to bind.
- `clearDepthBuffer()` (method, since 0.4.0): Clears the depth buffer. (before inserting 3D between 2D draws)
  - Clearing depth mid-draw after setting a clip (beginClipRect, stencil) once made the Galaxy Fold3 (Adreno 660) driver draw no 3D at all.
    Nodes that draw 3D inside a clip call this before beginClipRect, and pass clearDepth: false to runExternalPass.
- `runExternalPass(callback, options = {})` (method, since 0.4.0): Inserts a WebGL pass between 2D draws. (draws the preceding 2D batch, clears depth, then callback, and restoreRenderState when done)
  - callback receives the WebGL2 context and may freely change the program, vertex array, viewport, blending, depth and face culling. (the stencil clip stays applied, and the stencil state is not restored, so do not change it)
  - If callback throws, the state is restored and the error is rethrown.
  - Even when WebGL is used through the same context outside this function, the next 2D draw compares the program, vertex array, texture units, blending, depth, face culling, scissor and viewport against the state cache and sets them again.
    Two promises remain. 2D draws into the framebuffer bound now, so if the game bound its own framebuffer it puts back the one it found, and it does not change the stencil state.
  - `callback` Function: (webGL2RenderingContext) => any
  - `options` object: { clearDepth whether to clear depth (default true, inside a clip see the clearDepthBuffer header comment) }
  - returns any: The value returned by callback.

  Example: Insert direct WebGL drawing between 2D

  ```js
  import { Engine, EngineConfiguration, Scene, Vector2, Rect } from "./build/vanilla.js";
  
  class MainScene extends Scene {
  	draw(graphic) {
  		super.draw(graphic);
  		graphic.setFillColor("#888888");
  		graphic.drawRect(Rect.create(0, 0, 640, 360));
  		graphic.runExternalPass((webGL2RenderingContext) => {
  			webGL2RenderingContext.enable(webGL2RenderingContext.SCISSOR_TEST);
  			webGL2RenderingContext.scissor(20, 20, 100, 100);
  			webGL2RenderingContext.clearColor(0.2, 0.4, 0.8, 1);
  			webGL2RenderingContext.clear(webGL2RenderingContext.COLOR_BUFFER_BIT);
  			webGL2RenderingContext.disable(webGL2RenderingContext.SCISSOR_TEST);
  		}, { clearDepth: false });
  		graphic.setFillColor("#ffffff");
  		graphic.drawCircle(Vector2.create(320, 180), 40);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  engineConfiguration.referenceResolutionSize = Vector2.create(640, 360);
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

- `getVertexArray()` (method, since 0.3.0): Returns the vertex array.
  - returns WebGLVertexArrayObject: Vertex array.
- `getVertexBuffer()` (method, since 0.3.0): Returns the vertex buffer.
  - returns WebGLBuffer: Vertex buffer.
- `getVertexData()` (method, since 0.3.0): Returns the scratch vertex data.
  - returns Float32Array: Scratch vertex data. (x, y, u, v per vertex)
- `getWhiteTexture()` (method, since 0.3.0): Returns the white texture. (for solid-color shapes)
  - returns WebGLTexture: 1x1 white texture.
- `getWhiteColor()` (method, since 0.3.0): Returns the white color. (default color for image/text output)
  - returns Color: White. (shared so do not modify)
- `getImageTextureCache()` (method, since 0.3.0): Returns the image texture cache.
  - returns ImageTextureCache: Image texture cache.
- `getTextStringTextureCache()` (method, since 0.3.0): Returns the string texture cache.
  - returns TextStringTextureCache: String texture cache.
- `resolveShaderProgram(programGroupName, programName, createShaderSource)` (method, since 0.4.0): Return a cached program, swappable into drawing, by name. (if none is cached, build it from the sources createShaderSource gives and cache it)
  - Links with the attribute locations pinned to the default program, so the default vertex array is used as is.
  - If building fails it reports once and caches null so it is never built again.
  - `programGroupName` string: Group name. (such as an effect kind, the first half of the key)
  - `programName` string: Program name. (the second half of the key)
  - `createShaderSource` () => [string, string]: Function called only when nothing is cached. ([vertex source, fragment source], GLSL ES 3.00)
  - returns ShaderProgram | null: The cached program. null if building failed. (null afterwards too)

  Example: Drawing a shape with a swapped-in grayscale shader

  ```js
  import { Engine, EngineConfiguration, Scene, Color, Rect } from "./build/vanilla.js";
  
  const VERTEXSHADER_SOURCE = `#version 300 es
  in vec2 vertexPosition;
  in vec2 vertexTextureCoordinate;
  uniform mat3 projectionMatrix;
  uniform mat3 modelMatrix;
  out vec2 fragmentTextureCoordinate;
  void main() {
  	vec3 transformedPosition = projectionMatrix * (modelMatrix * vec3(vertexPosition, 1.0));
  	gl_Position = vec4(transformedPosition.xy, 0.0, 1.0);
  	fragmentTextureCoordinate = vertexTextureCoordinate;
  }
  `;
  const GRAY_FRAGMENTSHADER_SOURCE = `#version 300 es
  precision highp float;
  in vec2 fragmentTextureCoordinate;
  uniform sampler2D mainTexture;
  uniform vec4 mainColor;
  uniform float globalAlpha;
  out vec4 outputColor;
  void main() {
  	vec4 textureColor = texture(mainTexture, fragmentTextureCoordinate);
  	float gray = dot(textureColor.rgb * mainColor.rgb, vec3(0.299, 0.587, 0.114));
  	float alpha = textureColor.a * mainColor.a * globalAlpha;
  	outputColor = vec4(vec3(gray) * alpha, alpha);
  }
  `;
  
  class MainScene extends Scene {
  	preDraw(graphic) {
  		super.preDraw(graphic);
  		const shaderProgram = graphic.resolveShaderProgram("example", "gray", () => [VERTEXSHADER_SOURCE, GRAY_FRAGMENTSHADER_SOURCE]);
  		graphic.setShaderProgramOverride(shaderProgram);
  		graphic.setFillColor(new Color(1, 0.4, 0.2, 1));
  		graphic.drawRect(Rect.create(220, 100, 200, 160));
  		graphic.setShaderProgramOverride(null);
  	}
  }
  
  const engineConfiguration = new EngineConfiguration();
  const engine = new Engine(engineConfiguration);
  engine.run(new MainScene());
  ```

## Functions and constants

- `detectTextDirection(text)` (method, since 0.4.0): First strong direction of the text. ("ltr" or "rtl", the first among letter-class characters and LRM, RLM, ALM, "ltr" if none. Used by setTextDirection("auto"))
  - `text` string: Text to inspect. ("ltr" if empty)
  - returns string: "ltr" or "rtl".
