# core/graphic (vanilla-engine 0.4.0)

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

Graphics.
- A renderer that draws to a GL context. Uses the same shaders and the same state model as the original (WebGL2).
- Reproduces the coordinate system (top-left origin, pixel units) and state model (transform/alpha stack) of the Canvas2D days as is.
- All draws converge on one point, draw_vertices(). Solid shapes also use a 1x1 white texture to unify with the texture path.
- Clipping is based on the stencil buffer. Text is baked into string textures and drawn.
- Batching (on by default): consecutive draws with the same texture have their vertices transformed on the CPU, gathered, and drawn at once.
  With the same batch shader as the original, color and tint go with each vertex, so tinted draws are batched too. Clip region recording is not batched.
  Blends, clips, particle draws and the end of the frame flush what has been gathered first (flush_batch). The original also turns it on by default. (setSpriteBatchingEnabled)
- Offscreen culling (on by default): NodeTree asks is_local_rect_visible before drawing a node. The original also turns it on by default and WorldNode asks with the same function. (setCullingEnabled)
- Shader override (set_shader_program_override): effects such as ShaderSprite draw with their own program instead of the default one. No batching while overridden.
  resolve_shader_program keeps the override programs by name and fixes their attribute locations to match the default program so they share the default vertex array.
- Remembers the last bound shader program and the texture of texture unit 0, and skips GL calls that bind the same thing again. (same as the original)
  When GL can be touched from outside (when handing out the context with get_gl, restore_render_state, frame start and end), it forgets them and binds again next time.
- The mipmap level bias (set_image_mipmap_bias) is applied through the textureLodBias uniform of the default, batch and particle shaders. An override shader receives it if it has that uniform. (same as the original)
- Text direction (set_text_direction, the original setTextDirection) is held in the state, and baked strings are shaped in that paragraph direction. (bidirectional ordering and shaping in textshaping.rs)
- 26 blend modes (same as the original): 13 use fixed blending, and 13 grab what is under the draw area from the current framebuffer with blit_framebuffer and mix it in a shader following the W3C formulas.
  Multiply uses fixed blending on the default framebuffer and shader mixing when drawing to a render target. (fixed blending differs from the W3C formula when the backdrop is translucent, same as the original)
  The shader text does not differ from the original by a single character. Override shaders are drawn first into an overlay slot (always RGBA16F on desktop, RGBA16F on the web when EXT_color_buffer_float is available like the original) and then mixed over.
- Alpha is not written when drawing to the default framebuffer (apply_color_mask). In the original and on the web the canvas is alpha: false so screen alpha is always 1, but the desktop default framebuffer has alpha,
  so modes using DST_ALPHA and shader mixing after a mode that lowers alpha differed from the web. Alpha is written to render targets.

## GlTexture (type)

GL object types. (glow::Native* on desktop, WebGL objects on the web. Uses whatever the glow context defines)

```rust
pub type GlTexture = <glow::Context as glow::HasContext>::Texture
```

## GlBuffer (type)

GL buffer object. (such as a vertex buffer)

```rust
pub type GlBuffer = <glow::Context as glow::HasContext>::Buffer
```

## GlVertexArray (type)

GL vertex array object.

```rust
pub type GlVertexArray = <glow::Context as glow::HasContext>::VertexArray
```

## GlProgram (type)

GL shader program object.

```rust
pub type GlProgram = <glow::Context as glow::HasContext>::Program
```

## GlShader (type)

GL shader object. (one vertex or fragment shader)

```rust
pub type GlShader = <glow::Context as glow::HasContext>::Shader
```

## GlUniformLocation (type)

GL uniform location. (a value wrapping one integer on desktop, a WebGL location object on the web)

```rust
pub type GlUniformLocation = <glow::Context as glow::HasContext>::UniformLocation
```

## GlFramebuffer (type)

GL framebuffer object. (render target)

```rust
pub type GlFramebuffer = <glow::Context as glow::HasContext>::Framebuffer
```

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

Geometry cache key. (Where Component::write_geometry_key writes the drawing inputs, original GeometryKey)
- Values written with add are compared in order with the values written last time. If any differs or the count differs, it counts as changed.
- It overwrites while comparing, so no array is created every frame. (Text is stored again only when it changed)

Example: Write the drawing inputs and see whether they changed

```rust
use vanilla::GeometryKey;

let mut geometry_key = GeometryKey::new();
geometry_key.begin();
geometry_key.add(10.0);
geometry_key.add("#ff0000");
println!("{}", geometry_key.end());
geometry_key.begin();
geometry_key.add(10.0);
geometry_key.add("#ff0000");
println!("{}", geometry_key.end());
geometry_key.begin();
geometry_key.add(12.0);
geometry_key.add("#ff0000");
println!("{}", geometry_key.end());
```

- `pub fn new() -> GeometryKey` (constructor, since 0.4.0): Constructor.
  - returns GeometryKey: An empty key. (The first end is false)
- `pub fn begin(&mut self)` (method, since 0.4.0): Starts writing. (Graphic calls it before write_geometry_key)
- `pub fn add(&mut self, value: impl GeometryKeyValue)` (method, since 0.4.0): Writes one value. (number, bool, text, color, vector, rectangle, shared object (Rc), Option)
  - `value` impl GeometryKeyValue: A value that drawing reads. (Rc is compared by the address it points to, like the original's object reference comparison)
- `pub fn end(&mut self) -> bool` (method, since 0.4.0): Ends writing. (true if the same as last time)
  - returns bool: true if everything written this time equals what was written last time. (false the first time)

## GeometryKeyValue (trait)

A value that can be written with GeometryKey::add. (a number, text, bool, object reference or null, as the original add accepts)

Example: Recording counts and booleans to compare with the last time

```rust
use vanilla::GeometryKey;

let mut geometry_key = GeometryKey::new();
geometry_key.begin();
geometry_key.add(1.5_f64);
geometry_key.add(true);
geometry_key.end();
geometry_key.begin();
geometry_key.add(1.5_f64);
geometry_key.add(true);
assert!(geometry_key.end());
```

- `fn add_to_geometry_key(self, geometry_key: &mut GeometryKey)` (method, since 0.4.0): Writes this value into the key.
  - `geometry_key` &mut GeometryKey: The key to write into.

## Graphic (struct)

Graphics. (the original Graphic, a 2D renderer that draws to a GL context like Canvas2D)
- The engine holds one and passes it as `&mut Graphic` to the draw functions of scenes and nodes, and outside drawing it is taken with `engine.get_graphic()` and `get_graphic_mut()`. Coordinates have a top-left origin, in pixels.
- State (transform, global alpha, blend mode, color, font, alignment, text direction) is pushed and restored with push_state, pop_state. At the start of a frame (apply_settings) the transform, global alpha, tint and blend mode return to their initial values.

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

```rust
use vanilla::{Colors, Engine, EngineConfiguration, Graphic, Rect, Scene, SceneBase, TextAlign, TextBaseline, Vector2};

struct MainScene {
	scene_base: SceneBase,
}

impl Scene for MainScene {
	fn get_scene_base(&self) -> &SceneBase {
		&self.scene_base
	}

	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
		&mut self.scene_base
	}

	fn draw(&mut self, graphic: &mut Graphic) {
		graphic.push_state();
		graphic.translate(640.0, 360.0);
		graphic.rotate(0.25);
		graphic.set_fill_color(Colors::WHITE);
		graphic.draw_rect(Rect::create(-100.0, -60.0, 200.0, 120.0));
		graphic.pop_state();
		graphic.set_stroke_color("#ff8800");
		graphic.draw_stroke_circle(Vector2::create(200.0, 200.0), 50.0, 4.0);
		graphic.set_font_string("24px sans-serif");
		graphic.set_text_align(TextAlign::Center);
		graphic.set_text_baseline(TextBaseline::Middle);
		graphic.set_fill_color(Colors::VANILLA);
		graphic.draw_fill_text("Hello", 640.0, 620.0);
	}
}

fn main() {
	let mut engine_configuration = EngineConfiguration::new();
	engine_configuration.reference_resolution_size = Vector2::create(1280.0, 720.0);
	let engine = Engine::new(engine_configuration);
	let main_scene = MainScene {
		scene_base: SceneBase::new(),
	};
	if let Err(error) = engine.run(Box::new(main_scene)) {
		eprintln!("{}", error);
	}
}
```

- `pub fn new(gl: glow::Context, preserve_drawing_buffer: bool, color_space: crate::core::colorspace::ColorSpace) -> Result<Graphic, String>` (constructor, since 0.3.2): Constructor. (preserve_drawing_buffer is the original constructor argument preserveDrawingBuffer, pass the value of the same name from the engine settings)
  - `gl` glow::Context: GL context to draw to. (owned by Graphic)
  - `preserve_drawing_buffer` bool: Whether to keep what was drawn after the frame ends. (when on, the color is not cleared at the start of a frame)
  - `color_space` crate::core::colorspace::ColorSpace: 3D color space. (original constructor argument colorSpace, pass color_space from the engine configuration, 2D is in gamma space either way)
  - returns Result<Graphic, String>: The created graphics. Err holding the error text if compiling or linking the default shaders, or creating GL objects (vertex arrays, buffers, textures) fails.
- `pub fn is_drawing_buffer_preserved(&self) -> bool` (method, since 0.4.0): Whether what was drawn is kept after the frame ends. (the original preserveDrawingBuffer)
  - returns bool: Value of the constructor argument preserve_drawing_buffer.
- `pub fn apply_settings(&mut self, drawing_buffer_width: i32, drawing_buffer_height: i32)` (method, since 0.3.2): Applies settings. (called by the engine at the start of every frame)
  - Detects drawing buffer size changes and updates the viewport/projection.
  - Resets to the frame-start state.
  - The browser clears the drawing buffer after presenting when preserveDrawingBuffer is off. A window's back buffer after presenting is undefined, so it is cleared directly here.
    When on, the color is not cleared like the original. (the original applySettings clears only the stencil. It draws over the last frame's picture, and on desktop the platform restores the last frame's picture)
  - `drawing_buffer_width` i32: Drawing buffer width. (pixels, used for the viewport and projection)
  - `drawing_buffer_height` i32: Drawing buffer height. (pixels)
- `pub fn end_frame(&mut self)` (method, since 0.3.2): Finishes the frame. (called by the engine before presenting)
- `pub fn clear_depth_buffer(&mut self)` (method, since 0.4.0): Clears the depth buffer. (the original clearDepthBuffer, before inserting 3D between 2D draws)
  - Clearing depth in the middle of drawing after setting a clip (begin_clip_rect, stencil) once made the Galaxy Fold3 (Adreno 660) driver draw no 3D at all. (the original game)
    Nodes that draw 3D inside a clip call this before begin_clip_rect, and give is_depth_cleared false to run_external_pass.
- `pub fn run_external_pass<R>(&mut self, is_depth_cleared: bool, pass: impl FnOnce(&GlContext) -> R) -> R` (method, since 0.4.0): Inserts a GL pass between 2D draws. (the original runExternalPass)
  - Flushes the preceding 2D batch, clears depth if is_depth_cleared, calls pass, and calls restore_render_state when done.
  - pass receives the GL context and may change the program, vertex array, viewport, blending, depth, and face culling. (The stencil clip stays set, and the stencil clip state is restored at the end)
  - The state functions of the received context (GlContext) go through the GL state cache, so the engine knows the changed state even if engine drawing continues after changing state inside pass.
  - Even if GL is used with the same context outside this function, the next 2D draw compares the program, vertex array, vertex buffer, texture units, blending, depth, face culling, scissor, and viewport against the state cache and sets them again.
    Two promises remain. 2D draws into the currently bound framebuffer, so if you bound a game framebuffer, put back the one bound on entry, and do not change the stencil state.
  - Returns what pass returned as is. Even if pass panics, a guard calls restore_render_state while unwinding. (the original restores even when it throws)
  - `is_depth_cleared` bool: Whether to clear the depth buffer before pass. (when drawing 3D inside a clip, give false and call clear_depth_buffer before begin_clip_rect)
  - `pass` impl FnOnce(&GlContext) -> R: Function that receives the GL context and draws.
  - returns R: Value pass returned.

  Example: Drawing directly with GL and getting a value back

  ```rust
  use vanilla::Graphic;
  
  fn draw(graphic: &mut Graphic) {
  	let maximum_texture_size = graphic.run_external_pass(true, |gl| {
  		unsafe {
  			gl.enable(glow::DEPTH_TEST);
  			gl.get_parameter_i32(glow::MAX_TEXTURE_SIZE)
  		}
  	});
  	assert!(maximum_texture_size > 0);
  }
  ```

- `pub fn set_image_smoothing_enabled(&mut self, value: bool)` (method, since 0.3.2): Sets whether image smoothing is enabled.
  - Pixel-art (dot) sprite games set this to false to render crisply.
  - `value` bool: true for smooth LINEAR, false for NEAREST keeping pixels as is. (initially true)
- `pub fn is_image_smoothing_enabled(&self) -> bool` (method, since 0.3.2): Returns whether image smoothing is enabled.
  - returns bool: true if smoothing is on.
- `pub fn set_image_smoothing_quality(&mut self, value: ImageSmoothingQuality)` (method, since 0.4.0): Sets the image smoothing quality. (GL only has LINEAR / NEAREST, so it is only stored, initially High)
  - `value` ImageSmoothingQuality: Smoothing quality. (only stored, not used for drawing)
- `pub fn get_image_smoothing_quality(&self) -> ImageSmoothingQuality` (method, since 0.4.0): Returns the image smoothing quality.
  - returns ImageSmoothingQuality: The set quality. (initially High)
- `pub fn set_image_mipmap_enabled(&mut self, value: bool)` (method, since 0.3.2): Sets whether image mipmaps are used. (reduces the shimmering of images drawn much smaller)
  - `value` bool: true to use a mipmap filter when image textures are minified. (initially false)
- `pub fn is_image_mipmap_enabled(&self) -> bool` (method, since 0.3.2): Returns whether image mipmaps are used.
  - returns bool: true if mipmaps are used.
- `pub fn set_image_mipmap_bias(&mut self, value: f64)` (method, since 0.4.0): Sets the image mipmap level bias. (default 0, the original setImageMipmapBias)
  - A value added when picking the mipmap level. Negative picks one level larger and looks sharper, but too small shimmers again. (around -0.5)
  - Applied to the default shaders (single, batched, particle). Override shaders receive it if they have the textureLodBias uniform.
  - `value` f64: Value to add to the mipmap level. (negative is sharper, 0 means no bias)
- `pub fn get_image_mipmap_bias(&self) -> f64` (method, since 0.4.0): Returns the image mipmap level bias.
  - returns f64: The set bias value. (initially 0)
- `pub fn set_force_gizmos_visible(&mut self, is_force_gizmos_visible: bool)` (method, since 0.3.2): Sets whether to force the gizmos of all nodes to show.
  - `is_force_gizmos_visible` bool: true draws them regardless of each node's gizmo visibility setting. (initially false)
- `pub fn is_force_gizmos_visible(&self) -> bool` (method, since 0.3.2): Returns whether the gizmos of all nodes are forced to show.
  - returns bool: true if forced to show.
- `pub fn push_state(&mut self)` (method, since 0.3.2): Saves the state. (corresponds to Canvas2D save)
  - A slot used once is kept and reused. The font string is copied into the slot's storage so it is not allocated anew every time.
- `pub fn pop_state(&mut self)` (method, since 0.3.2): Restores the state. (corresponds to Canvas2D restore)
  - The font string is swapped with the slot's storage.
- `pub fn translate(&mut self, x: f64, y: f64)` (method, since 0.3.2): Accumulates a translation transform.
  - `x` f64: Horizontal translation. (in current coordinate system units, pixels)
  - `y` f64: Vertical translation. (down is +)
- `pub fn rotate(&mut self, radian: f64)` (method, since 0.3.2): Accumulates a rotation transform.
  - `radian` f64: Rotation angle. (radians, clockwise on screen is +)
- `pub fn scale(&mut self, x: f64, y: f64)` (method, since 0.3.2): Accumulates a scale transform.
  - `x` f64: Horizontal scale. (1 keeps it as is, negative flips it)
  - `y` f64: Vertical scale.
- `pub fn set_transform(&mut self, a: f64, b: f64, c: f64, d: f64, e: f64, f: f64)` (method, since 0.3.2): Sets the transform matrix directly. (equivalent to Canvas2D setTransform(a, b, c, d, e, f))
  - Replaces the current matrix instead of multiplying it. A point (x, y) is moved to (a x + c y + e, b x + d y + f).
  - `a` f64: Horizontal scale. (multiplied by x and added to the new x)
  - `b` f64: Vertical skew. (multiplied by x and added to the new y)
  - `c` f64: Horizontal skew. (multiplied by y and added to the new x)
  - `d` f64: Vertical scale. (multiplied by y and added to the new y)
  - `e` f64: Horizontal translation. (pixels)
  - `f` f64: Vertical translation. (pixels)
- `pub fn reset_transform(&mut self)` (method, since 0.3.2): Resets the transform matrix.
- `pub fn get_transform_matrix(&self) -> TransformMatrix` (method, since 0.3.2): Returns the current transform matrix.
  - returns TransformMatrix: Copy of the current transform matrix.
- `pub fn set_global_alpha(&mut self, value: f64)` (method, since 0.3.2): Sets the global alpha.
  - `value` f64: Global alpha. (clamped to 0 ~ 1, initially 1)
- `pub fn get_global_alpha(&self) -> f64` (method, since 0.3.2): Returns the global alpha.
  - returns f64: Current global alpha. (0 ~ 1)
- `pub fn multiply_global_alpha(&mut self, value: f64)` (method, since 0.3.2): Multiplies into the global alpha. (for alpha inheritance in the node tree)
  - `value` f64: Value to multiply the current global alpha by. (the product is clamped to 0 ~ 1)
- `pub fn set_blend_mode(&mut self, blend_mode: BlendMode)` (method, since 0.3.2): Sets the blend mode. (the original setBlendMode)
  - The 13 modes that fixed blending can do are set with blend_func.
  - The remaining 13 (Overlay, Darken, Lighten, ColorDodge, ColorBurn, HardLight, SoftLight, Difference, Exclusion, Hue, Saturation, Color, Luminosity)
    grab what is under the draw area on every draw and mix it in a shader. These modes are not batched, and each draw takes one region copy and one draw call.
    (when drawing with an override shader it is drawn into the overlay slot first and then moved, so two draw calls)
  - Multiply is mixed in a shader only when drawing to a render target (not the default framebuffer). (get_draw_shader_blend_mode_index)
  - `blend_mode` BlendMode: Blend mode to use from the next draw. (does nothing if it is the same as now, flushes the gathered batch first if it changes)
- `pub fn get_blend_mode(&self) -> BlendMode` (method, since 0.3.2): Returns the blend mode.
  - returns BlendMode: Current blend mode. (Normal at the start of a frame)
- `pub fn set_image_tint_color(&mut self, color: Option<Color>)` (method, since 0.3.2): Sets the image tint color. (cleared if None)
  - Covers with the color at the tint.alpha ratio only inside the image silhouette (alpha).
  - `color` Option<Color>: Color to cover with. (alpha is the cover ratio, None turns the tint off, None at the start of a frame)
- `pub fn get_image_tint_color(&self) -> Option<Color>` (method, since 0.3.2): Returns the image tint color.
  - returns Option<Color>: Current tint color. None if not set.
- `pub fn set_fill_color(&mut self, color: impl Into<Color>)` (method, since 0.3.2): Sets the fill color. (Color or a string like "#rrggbb")
  - `color` impl Into<Color>: Fill color. (Color or text like "#rrggbb", initially black)
- `pub fn get_fill_color(&self) -> Color` (method, since 0.3.2): Returns the fill color.
  - returns Color: Current fill color.
- `pub fn set_stroke_color(&mut self, color: impl Into<Color>)` (method, since 0.3.2): Sets the stroke color. (Color or a string like "#rrggbb")
  - `color` impl Into<Color>: Stroke color. (Color or text like "#rrggbb", initially black)
- `pub fn get_stroke_color(&self) -> Color` (method, since 0.3.2): Returns the stroke color.
  - returns Color: Current stroke color.
- `pub fn write_quad(&mut self, offset: usize, left_x: f64, top_y: f64, right_x: f64, bottom_y: f64, left_u: f64, top_v: f64, right_u: f64, bottom_v: f64) -> usize` (method, since 0.3.2): Writes a quad (2 triangles, 6 vertices) into the vertex data.
  - Returns the offset (in floats) after writing.
  - Panics if it writes past the scratch array (get_vertex_data, 4096 vertices, 16384 floats).
  - `offset` usize: Position to start writing at. (float index into the scratch array, 4 floats x, y, u, v per vertex)
  - `left_x` f64: Left x. (coordinates before the current transform, pixels)
  - `top_y` f64: Top y. (pixels)
  - `right_x` f64: Right x. (pixels)
  - `bottom_y` f64: Bottom y. (pixels)
  - `left_u` f64: Left texture coordinate. (0 ~ 1)
  - `top_v` f64: Top texture coordinate. (0 ~ 1, 0 is the top of the image)
  - `right_u` f64: Right texture coordinate. (0 ~ 1)
  - `bottom_v` f64: Bottom texture coordinate. (0 ~ 1)
  - returns usize: Offset after writing. (offset + 24, divided by 4 it is the vertex count so far)
- `pub fn draw_vertices(&mut self, vertex_count: usize, texture: GlTexture, color: Color)` (method, since 0.3.2): Draws the written vertices. (the single point all draws converge on)
  - `vertex_count` usize: Number of vertices to draw. (from the start of the scratch array, 3 per triangle, does nothing if 0)
  - `texture` GlTexture: Texture to apply. (get_white_texture for solid colors)
  - `color` Color: Color to multiply the texture color by. (get_white_color to keep the image as is)

  Example: Writing two quads and drawing them at once

  ```rust
  use vanilla::core::graphic::FLOATS_PER_VERTEX;
  use vanilla::{Color, Graphic};
  
  fn draw(graphic: &mut Graphic) {
  	let mut offset = graphic.write_quad(0, 10.0, 10.0, 110.0, 60.0, 0.0, 0.0, 1.0, 1.0);
  	offset = graphic.write_quad(offset, 10.0, 80.0, 110.0, 130.0, 0.0, 0.0, 1.0, 1.0);
  	let white_texture = graphic.get_white_texture();
  	graphic.draw_vertices(offset / FLOATS_PER_VERTEX, white_texture, Color::create(1.0, 0.5, 0.0, 1.0));
  }
  ```

- `pub fn set_geometry_caching_enabled(&mut self, is_geometry_caching_enabled: bool)` (method, since 0.4.0): Turns the geometry cache on or off. (On by default, original setGeometryCachingEnabled)
  - While on, components that report their drawing inputs with write_geometry_key (Paint, UIView, Text, Sprite and so on) have the vertices they drew cached per component.
    If the inputs, transform and opacity are unchanged, draw is not called and the cache is moved into the batch; if only the translation changed (scrolling and so on), only the new matrix is applied to the cached local vertices.
  - A batch filled only with cache pieces is kept in a GPU buffer per draw order in the frame, and when nothing changed only the draw call is issued without uploading vertices.
  - When off, draw is always called. (The picture is the same)
  - `is_geometry_caching_enabled` bool: Whether to turn it on.

  Example: Turn the geometry cache on and see how many were drawn from the cache last frame

  ```rust
  use vanilla::Graphic;
  
  fn draw(graphic: &mut Graphic) {
  	graphic.set_geometry_caching_enabled(true);
  	println!("{} {}", graphic.is_geometry_caching_enabled(), graphic.get_last_frame_geometry_cache_hit_count());
  }
  ```

- `pub fn is_geometry_caching_enabled(&self) -> bool` (method, since 0.4.0): Whether the geometry cache is on.
  - returns bool: true if on. (true at first)
- `pub fn get_last_frame_geometry_cache_hit_count(&self) -> u32` (method, since 0.4.0): The number of components drawn from the geometry cache last frame. (draw was not called)
  - returns u32: The number of components drawn by moving the cached vertices or only re-applying the matrix.
- `pub fn get_last_frame_geometry_rebuild_count(&self) -> u32` (method, since 0.4.0): The number of components whose geometry cache was written again last frame. (those among cached components that called draw)
  - returns u32: The number of components whose draw was called again because the input, scale, rotation and so on changed.
- `pub fn get_last_frame_retained_batch_count(&self) -> u32` (method, since 0.4.0): The number of batches drawn last frame from a buffer left on the GPU, without uploading vertices again.
  - A batch whose pieces (geometry cache pieces and the vertex values of directly written spans) are all the same as the batch of the same order last frame issues only the draw call, without moving or uploading vertices.
  - A batch with only part changed has just the changed ranges updated with buffer_sub_data and is not counted here.
  - returns u32: The number of batches drawn from the kept buffer.

  Example: See whether a still UI is drawn from kept batches

  ```rust
  use vanilla::Graphic;
  
  fn draw(graphic: &mut Graphic) {
  	println!("{} {}", graphic.get_last_frame_retained_batch_count(), graphic.get_last_frame_draw_call_count());
  }
  ```

- `pub fn draw_component(&mut self, component: &mut dyn Component, transform: &NodeTransform)` (method, since 0.4.0): Draws a component. (A node calls it per component, goes through the geometry cache, original drawComponent)
  - If the component does not report its inputs with write_geometry_key, the cache is off, or the state is not batched drawing, draw is called as is.
  - If the inputs and the drawing state (scale, rotation, blend, tint, text direction) equal last time:
    if translation and opacity are also the same, the cached device vertices are moved into the batch as they are; otherwise the current matrix and opacity are applied again to the cached local vertices.
    (When scrolling only the parent's translation changes, so child components only multiply the matrix without calling draw; text recomputes even the pixel snap the same way)
  - Otherwise draw is called and the cache is written again. If something outside the batch such as clipping, layers or blend changes happens during drawing, that component is not cached.
  - `component` &mut dyn Component: The component to draw. (the component holds the cache)
  - `transform` &NodeTransform: The transform of the node the component is attached to.
- `pub fn flush_batch(&mut self)` (method, since 0.3.2): Flushes the gathered batch. (called before changing GL state, at the end of a frame, and before using GL directly)
  - 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). (same as the original)
- `pub fn set_batching_enabled(&mut self, is_batching_enabled: bool)` (method, since 0.3.2): Turns batching on or off. (on by default. When off, one draw call per draw, like the original)
  - 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 (begin_clip_rect) 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.
  - `is_batching_enabled` bool: If true, consecutive draws are gathered and drawn at once. (turning it off flushes what has been gathered first)
- `pub fn is_batching_enabled(&self) -> bool` (method, since 0.3.2): Whether batching is on.
  - returns bool: true if batching is on. (initially true)
- `pub fn set_culling_enabled(&mut self, is_culling_enabled: bool)` (method, since 0.3.2): Turns offscreen culling on and off. (on by default)
  - `is_culling_enabled` bool: true skips drawing offscreen nodes.
- `pub fn is_culling_enabled(&self) -> bool` (method, since 0.3.2): Whether offscreen culling is on.
  - returns bool: true if offscreen culling is on. (initially true)
- `pub fn is_local_rect_visible(&self, rect: Rect) -> bool` (method, since 0.3.2): Whether a rectangle in the current transform overlaps the screen (drawing buffer) and the active clip. (judged by the bounding box of the four transformed corners)
  - Outside the bounding box of the clips set with begin_clip_rect (all nested ones), it counts as not visible. (like Unity RectMask2D, rows outside a scroll view are not drawn)
  - `rect` Rect: Rectangle in the current transform. (local coordinates, pixels)
  - returns bool: true if the bounding box of the four transformed corners overlaps the drawing buffer (from 0, 0 to width, height) and the bounding box of the active clip. (touching the edge counts as true)
- `pub fn set_subtree_culling_enabled(&mut self, is_subtree_culling_enabled: bool)` (method, since 0.4.0): Turns subtree draw skipping on or off. (on by default, original setSubtreeCullingEnabled)
  - When on, if the subtree draw bounds that hold everything a node and its descendants draw (NodeTree::read_subtree_draw_bounds) are outside the screen and the active clip, drawing of the node and its descendants is skipped as a whole. tick still runs.
  - Does nothing while off-screen culling (set_culling_enabled) is off. Never skips while all gizmos are drawn.
  - `is_subtree_culling_enabled` bool: true skips off-screen subtrees as a whole.

  Example: Turn off and on

  ```rust
  use vanilla::Graphic;
  
  fn compare_culling(graphic: &mut Graphic) {
  	assert!(graphic.is_subtree_culling_enabled());
  	graphic.set_subtree_culling_enabled(false);
  	assert!(!graphic.is_subtree_culling_enabled());
  	let culled_subtree_count = graphic.get_last_frame_culled_subtree_count();
  	assert!(culled_subtree_count < u32::MAX);
  }
  ```

- `pub fn is_subtree_culling_enabled(&self) -> bool` (method, since 0.4.0): Whether subtree draw skipping is on. (original isSubtreeCullingEnabled)
  - returns bool: true if on. (true at first)
- `pub fn get_last_frame_culled_subtree_count(&self) -> u32` (method, since 0.4.0): Number of subtrees whose drawing was skipped as a whole last frame because they were off screen. (original getLastFrameCulledSubtreeCount)
  - returns u32: Number of subtrees skipped last frame. (the value begin_frame_statistics carried over, descendants of a skipped node are not counted)
- `pub fn add_culled_subtree_count(&mut self, culled_subtree_count: u32)` (method, since 0.4.0): Adds to the number of subtrees skipped as a whole this frame because they were off screen. (original addCulledSubtreeCount, NodeTree::draw_children calls it after skipping the children outside the visible range at once)
  - `culled_subtree_count` u32: Number of subtrees to add.
- `pub fn read_local_visible_bounds(&mut self) -> Option<Rect>` (method, since 0.4.0): Reads the visible rect (the screen and the active clip, the same as is_local_rect_visible) moved back into the local coordinates of the current transform as a bounding box. (original readLocalVisibleBounds)
  - Generous with rotation or skew (bounding box of the four corners, the device rect is widened by one pixel before moving). Anything drawn outside this rect is not visible.
  - Used to find the visible range among a node's many children (NodeTree::draw_children). Not recomputed while the transform and the clip stay the same.
  - returns Option<Rect>: Visible bounding box in local coordinates. None 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).

  Example: Under a transform scaled twice the visible rect is half

  ```rust
  use vanilla::Graphic;
  
  fn read_scaled(graphic: &mut Graphic) {
  	if let Some(visible_rect) = graphic.read_local_visible_bounds() {
  		graphic.push_state();
  		graphic.scale(2.0, 2.0);
  		let scaled_rect = graphic.read_local_visible_bounds().expect("visible");
  		assert!((scaled_rect.size.x * 2.0 - visible_rect.size.x).abs() < 1e-9);
  		graphic.pop_state();
  	}
  }
  ```

- `pub fn is_inside_visible_bounds(&self) -> bool` (method, since 0.4.0): Whether a node whose subtree lies fully inside the visible rect (the screen and the applied clip) is being drawn. (original Graphic.isInsideVisibleBounds)
  - When true, the descendants of that node may be drawn without the off screen check. Under a clip begun below it, it is false inside that clip (checked again).
  - False when off screen culling or subtree culling is off, or when all gizmos are drawn.
  - returns bool: true when fully inside.

  Example: Checking whether a drawing component is fully inside

  ```rust
  use vanilla::Graphic;
  
  fn draw_marker(graphic: &mut Graphic) {
  	if graphic.is_inside_visible_bounds() {
  		assert!(graphic.is_subtree_culling_enabled());
  	}
  }
  ```

- `pub fn add_culled_node_count(&mut self, culled_node_count: u32)` (method, since 0.3.2): Adds to the number of nodes culled this frame. (called by NodeTree)
  - `culled_node_count` u32: Number of nodes to add.
- `pub fn get_last_frame_culled_node_count(&self) -> u32` (method, since 0.3.2): Number of nodes culled as offscreen last frame.
  - returns u32: Number of nodes culled last frame. (the value handed over by begin_frame_statistics)
- `pub fn begin_frame_statistics(&mut self)` (method, since 0.3.2): Starts the frame drawing statistics.
  - The engine calls it every frame before drawing the scene. Hands over the last frame's draw call / vertex counts and clears this frame's values.
- `pub fn get_last_frame_draw_call_count(&self) -> u32` (method, since 0.3.2): The last frame's draw call count.
  - returns u32: Number of draw calls last frame. (the value handed over by begin_frame_statistics)
- `pub fn get_last_frame_vertex_count(&self) -> u32` (method, since 0.3.2): Number of vertices drawn in the last frame.
  - returns u32: Number of vertices drawn in the last frame.
- `pub fn get_last_frame_triangle_count(&self) -> u32` (method, since 0.3.2): Number of triangles drawn in the last frame.
  - returns u32: Number of vertices last frame divided by 3.
- `pub fn get_particle_vertex_data(&mut self, minimum_float_count: usize) -> &mut [f32]` (method, since 0.3.2): Returns the array for writing particle vertices. (at least minimum_float_count, up to the capacity if it exceeds the capacity)
  - `minimum_float_count` usize: Number of floats to use. (PARTICLE_FLOATS_PER_VERTEX per vertex: x, y, u, v, r, g, b, a)
  - returns &mut [f32]: Array of minimum_float_count from the start. (up to the capacity if asked for more than the 8192 vertex capacity, previous values may remain)
- `pub fn draw_colored_quads(&mut self, vertex_count: usize, texture: GlTexture)` (method, since 0.3.2): Draws quads with a color per vertex. (what was written to get_particle_vertex_data)
  - `vertex_count` usize: Number of vertices to draw. (6 per quad, draws only up to the capacity and the length received from get_particle_vertex_data, does nothing if 0)
  - `texture` GlTexture: Texture to apply. (such as get_soft_disc_texture, get_image_texture)

  Example: Two soft discs with a color per vertex

  ```rust
  use vanilla::core::graphic::PARTICLE_FLOATS_PER_VERTEX;
  use vanilla::Graphic;
  
  fn draw(graphic: &mut Graphic) {
  	let soft_disc_texture = graphic.get_soft_disc_texture();
  	let particle_list: [(f64, f64, [f64; 4]); 2] = [(100.0, 100.0, [1.0, 0.5, 0.0, 1.0]), (140.0, 120.0, [0.2, 0.6, 1.0, 0.5])];
  	let half_size = 24.0;
  	let corner_list: [[f64; 4]; 6] = [[-half_size, -half_size, 0.0, 0.0], [half_size, -half_size, 1.0, 0.0], [half_size, half_size, 1.0, 1.0], [-half_size, -half_size, 0.0, 0.0], [half_size, half_size, 1.0, 1.0], [-half_size, half_size, 0.0, 1.0]];
  	let vertex_data = graphic.get_particle_vertex_data(particle_list.len() * 6 * PARTICLE_FLOATS_PER_VERTEX);
  	let mut offset = 0;
  	for (center_x, center_y, color) in particle_list {
  		for corner in corner_list {
  			let vertex = [center_x + corner[0], center_y + corner[1], corner[2], corner[3], color[0], color[1], color[2], color[3]];
  			vertex_data[offset..offset + PARTICLE_FLOATS_PER_VERTEX].copy_from_slice(&vertex.map(|value| value as f32));
  			offset += PARTICLE_FLOATS_PER_VERTEX;
  		}
  	}
  	graphic.draw_colored_quads(offset / PARTICLE_FLOATS_PER_VERTEX, soft_disc_texture);
  }
  ```

- `pub fn get_soft_disc_texture(&mut self) -> GlTexture` (method, since 0.3.2): Returns the soft disc texture. (a 64x64 disc whose edge fades out, the default particle sprite. Created lazily)
  - Panics if the GL texture cannot be created.
  - returns GlTexture: 64 x 64 pixel texture. (a white disc that is full up to radius 0.7 and fades out with smoothstep from 0.7 to 1, premultiplied)
- `pub fn prepare_image(&mut self, image: &Rc<Image>) -> bool` (method, since 0.4.0): Uploads an image to the GPU in advance. (the original prepareImage, called while the scene loads so uploads do not pile up on the first drawing frame)
  - Uploads with the current image smoothing and mipmap settings. (If the settings differ when drawing, only the filtering is changed then)
  - Does nothing if the image is already uploaded. Does not upload an image of size 0.
  - Used to upload in the scene's load an image not read through ImageAsset, such as an image built in code (Image::create_from_pixels and the like).
  - `image` &Rc<Image>: The image to upload.
  - returns bool: true if there is a texture. (false if the size is 0 or the GL texture cannot be created)

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

  ```rust
  use std::rc::Rc;
  use vanilla::{Engine, Image};
  
  fn load(engine: &Engine) -> Rc<Image> {
  	let dot_image = Image::create_from_pixels(32, 32, [255u8, 102, 0, 255].repeat(32 * 32));
  	if let Some(mut graphic) = engine.get_graphic_mut() {
  		let is_prepared = graphic.prepare_image(&dot_image);
  		println!("{}", is_prepared);
  	}
  	dot_image
  }
  ```

- `pub fn prepare_loaded_images(&mut self, time_limit_milliseconds: f64) -> usize` (method, since 0.4.0): Uploads images read but not uploaded yet. (the original prepareLoadedImages, images read and decoded by ImageAsset and AssetLoader, in decode order)
  - The engine calls it split across frames after the scene's tracked assets are read (during the loading screen). The scene has no need to call it itself.
  - Given a time limit, stops after exceeding that time and returns the remaining count. (Uploads at least one at a time, same as Unity's asyncUploadTimeSlice)
  - Uploads only its own (images read with the engine holding this Graphic). Images with an unknown owner are uploaded only when there is a single Graphic. (same as the original)
  - `time_limit_milliseconds` f64: The time limit to use this time. (milliseconds, f64::INFINITY for all)
  - returns usize: The number of images left not uploaded yet. (0 when all are uploaded)

  Example: Upload right after reading an image

  ```rust
  use vanilla::{Engine, ImageAsset};
  
  async fn load(engine: &Engine, image_asset: &mut ImageAsset) {
  	let _ = image_asset.load(engine, "examples/assets/spritesheet.png").await;
  	if let Some(mut graphic) = engine.get_graphic_mut() {
  		let remaining_count = graphic.prepare_loaded_images(f64::INFINITY);
  		println!("{}", remaining_count);
  	}
  }
  ```

- `pub fn get_image_texture(&mut self, image: &Rc<Image>) -> Option<GlTexture>` (method, since 0.3.2): Returns the texture of an image. (for places that write quads directly, like particles)
  - `image` &Rc<Image>: Image to get the texture for. (uploads it the first time and releases the CPU pixels)
  - returns Option<GlTexture>: Texture with the current smoothing and mipmap settings applied. None if the GL texture cannot be created.
- `pub fn draw_line(&mut self, positions: &[Vector2], size: f64)` (method, since 0.3.2): Draws lines.
  - set_stroke_color()
  - `positions` &[Vector2]: Points to connect. (not drawn if fewer than 2)
  - `size` f64: Line thickness. (pixels)
- `pub fn draw_line_loop(&mut self, positions: &[Vector2], size: f64)` (method, since 0.3.2): Draws a closed line. (a loop connecting the last point to the first)
  - set_stroke_color()
  - `positions` &[Vector2]: Points to connect. (not drawn if fewer than 2)
  - `size` f64: Line thickness. (pixels)
- `pub fn draw_polyline(&mut self, positions: &[Vector2], size: f64, is_closed: bool)` (method, since 0.3.2): Draws a polyline. (per-segment quads expanded by thickness)
  - Inner joints are filled by extending half the thickness.
  - `positions` &[Vector2]: Points to connect. (not drawn if fewer than 2, draws only up to the 682 segments that fit in the scratch array)
  - `size` f64: Line thickness. (pixels)
  - `is_closed` bool: true also connects the last point to the first.
- `pub fn draw_rect(&mut self, rect: Rect)` (method, since 0.3.2): Draws a rectangle.
  - set_fill_color()
  - `rect` Rect: Rectangle to fill. (coordinates before the current transform, pixels)
- `pub fn draw_stroke_rect(&mut self, rect: Rect, line_width: f64)` (method, since 0.3.2): Draws a rectangle outline. (corresponds to Canvas2D strokeRect, the line center is on the border)
  - set_stroke_color()
  - `rect` Rect: Rectangle to outline. (pixels)
  - `line_width` f64: Line thickness. (pixels, half on each side of the border)
- `pub fn build_round_rect_positions(&self, rect: Rect, round_size: f64) -> [Vector2; ROUND_RECT_POSITION_COUNT]` (method, since 0.3.2): Creates the list of rounded rectangle path coordinates. (clockwise, convex polygon)
  - `rect` Rect: Rectangle. (pixels)
  - `round_size` f64: Corner radius. (reduced to half of the shorter side if it exceeds that)
  - returns [Vector2; ROUND_RECT_POSITION_COUNT]: 36 points, 9 per corner. (in top-right, bottom-right, bottom-left, top-left corner order)
- `pub fn draw_convex_polygon(&mut self, positions: &[Vector2], color: Color)` (method, since 0.3.2): 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]: Vertices of a convex polygon. (not drawn if fewer than 3)
  - `color` Color: Color to fill with. (the fill color is not used)
- `pub fn draw_round_rect(&mut self, rect: Rect, round_size: f64)` (method, since 0.3.2): Draws a rounded rectangle.
  - set_fill_color()
  - `rect` Rect: Rectangle to fill. (pixels)
  - `round_size` f64: Corner radius. (same as draw_rect if 0 or less)
- `pub fn draw_stroke_round_rect(&mut self, rect: Rect, round_size: f64, line_width: f64)` (method, since 0.3.2): Draws a rounded rectangle outline.
  - set_stroke_color()
  - `rect` Rect: Rectangle to outline. (pixels)
  - `round_size` f64: Corner radius. (same as draw_stroke_rect if 0 or less)
  - `line_width` f64: Line thickness. (pixels)
- `pub fn draw_circle(&mut self, center: Vector2, radius: f64)` (method, since 0.3.2): Draws a circle.
  - set_fill_color()
  - `center` Vector2: Center. (pixels)
  - `radius` f64: Radius. (pixels, not drawn if 0 or less)
- `pub fn draw_stroke_circle(&mut self, center: Vector2, radius: f64, line_width: f64)` (method, since 0.3.2): Draws a circle outline.
  - set_stroke_color()
  - `center` Vector2: Center. (pixels)
  - `radius` f64: Radius. (pixels, not drawn if 0 or less)
  - `line_width` f64: Line thickness. (pixels, half on each side of the radius)
- `pub fn draw_ring(&mut self, center: Vector2, inner_radius: f64, outer_radius: f64, start_radian: f64, end_radian: f64)` (method, since 0.4.0): Draws a ring (band). (fills between the inner and outer radius from start_radian to end_radian)
  - set_fill_color()
  - Angles are in radians, 0 is to the right and they increase clockwise on screen. (-PI / 2 to start at 12 o'clock, a full turn is 0 to PI * 2)
  - 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 draw_circle (16 ~ 64 per full turn), and only as many as the drawn angle needs are used.
  - `center` Vector2: Center. (pixels)
  - `inner_radius` f64: Inner radius. (pixels, a sector if 0)
  - `outer_radius` f64: Outer radius. (pixels, not drawn if 0 or less or not greater than inner_radius)
  - `start_radian` f64: Start angle. (radians)
  - `end_radian` f64: End angle. (radians, not drawn if equal to the start, the difference is used only up to a full turn)

  Example: A progress ring filling clockwise from 12 o'clock

  ```rust
  use vanilla::{math, Graphic, Vector2};
  
  fn draw_progress(graphic: &mut Graphic, progress: f64) {
  	let start_radian = -math::PI / 2.0;
  	graphic.set_fill_color("#40c057");
  	graphic.draw_ring(Vector2::create(200.0, 200.0), 40.0, 50.0, start_radian, start_radian + math::PI * 2.0 * progress);
  }
  ```

- `pub fn draw_arc(&mut self, center: Vector2, radius: f64, start_radian: f64, end_radian: f64, line_width: f64)` (method, since 0.4.0): Draws an arc. (a line of line_width thickness along the radius from start_radian to end_radian)
  - set_stroke_color()
  - Angles and segment count are the same as draw_ring. The middle of the line thickness lies on the radius.
  - `center` Vector2: Center. (pixels)
  - `radius` f64: Radius. (pixels, the middle of the line thickness)
  - `start_radian` f64: Start angle. (radians)
  - `end_radian` f64: End angle. (radians)
  - `line_width` f64: Line thickness. (pixels)
- `pub fn draw_ring_with_color(&mut self, center: Vector2, inner_radius: f64, outer_radius: f64, start_radian: f64, end_radian: f64, color: Color)` (method, since 0.4.0): Ring drawing math. (called by draw_ring, draw_arc)
  - `center` Vector2: Center. (pixels)
  - `inner_radius` f64: Inner radius. (pixels)
  - `outer_radius` f64: Outer radius. (pixels, not drawn if 0 or less or not greater than inner_radius)
  - `start_radian` f64: Start angle. (radians, 0 is to the right)
  - `end_radian` f64: End angle. (radians, not drawn if equal to the start, the difference is used only up to a full turn)
  - `color` Color: Color to fill with.
- `pub fn draw_line_segments(&mut self, position_values: &[f64], size: f64)` (method, since 0.4.0): Draws many line segments. (four values x0, y0, x1, y1 per segment in one position array, drawn at once)
  - set_stroke_color()
  - Each segment is one quad widened by the thickness. (unlike draw_line, joints are not filled, for separate segments)
  - Reads the number array as is without building a Vector2 array. Segments of length 0 are skipped.
  - When the vertex buffer fills, it draws up to there and continues gathering. (with batching on, it is the same texture so it continues in one draw call)
  - `position_values` &[f64]: Number array with four values x0, y0, x1, y1 per segment. (pixels, a trailing remainder of fewer than four is dropped, not drawn if fewer than 4)
  - `size` f64: Line thickness. (pixels)

  Example: Drawing grid lines at once

  ```rust
  use vanilla::{Colors, Graphic};
  
  fn draw_grid(graphic: &mut Graphic) {
  	let mut position_values: Vec<f64> = Vec::new();
  	for line_index in 0..=10 {
  		let offset = line_index as f64 * 32.0;
  		position_values.extend_from_slice(&[offset, 0.0, offset, 320.0]);
  		position_values.extend_from_slice(&[0.0, offset, 320.0, offset]);
  	}
  	graphic.set_stroke_color(Colors::WHITE);
  	graphic.draw_line_segments(&position_values, 1.0);
  }
  ```

- `pub fn draw_image(&mut self, image: &Rc<Image>, position: Vector2, content_size: Vector2)` (method, since 0.3.2): Draws an image.
  - `image` &Rc<Image>: Image to draw. (the fill color is not used, only tint and global alpha apply)
  - `position` Vector2: Top left. (pixels)
  - `content_size` Vector2: Size to draw. (pixels, the whole image is stretched to this size)
- `pub fn draw_image_with_image_rect(&mut self, image: &Rc<Image>, position: Vector2, content_size: Vector2, image_rect: Rect)` (method, since 0.3.2): Draws only part of an image. (the whole image if image_rect is empty)
  - `image` &Rc<Image>: Image to draw.
  - `position` Vector2: Top left. (pixels)
  - `content_size` Vector2: Size to draw. (pixels)
  - `image_rect` Rect: Image region to draw. (image pixels, the whole image if all four values are 0)
- `pub fn draw_image_with_source_and_destination(&mut self, image: &Rc<Image>, source_x: f64, source_y: f64, source_width: f64, source_height: f64, destination_x: f64, destination_y: f64, destination_width: f64, destination_height: f64)` (method, since 0.3.2): Draws a source region of an image into a given region. (equivalent to the 9-argument Canvas2D drawImage)
  - Not drawn if the image texture cannot be obtained.
  - `image` &Rc<Image>: Image to draw.
  - `source_x` f64: Left of the source region. (image pixels)
  - `source_y` f64: Top of the source region. (image pixels)
  - `source_width` f64: Width of the source region. (image pixels)
  - `source_height` f64: Height of the source region. (image pixels)
  - `destination_x` f64: Left of the destination. (pixels)
  - `destination_y` f64: Top of the destination. (pixels)
  - `destination_width` f64: Width to draw. (pixels)
  - `destination_height` f64: Height to draw. (pixels)
- `pub fn draw_image_with_nine_slice(&mut self, image: &Rc<Image>, position: Vector2, size: Vector2, nine_slice: Rect)` (method, since 0.3.2): Draws an image as a nine-patch.
  - position.x / position.y / size.x / size.y of nine_slice are the left / top / right / bottom thickness respectively.
  - `image` &Rc<Image>: Image to draw.
  - `position` Vector2: Top left. (pixels, floored)
  - `size` Vector2: Size to draw. (pixels, ceiled, and the sum of both thicknesses if smaller than that)
  - `nine_slice` Rect: Thickness of the four borders. (both image pixels and drawn pixels, simply stretched if all thicknesses are 0)

  Example: A panel that keeps its 16 pixel border and stretches only the middle

  ```rust
  use std::rc::Rc;
  use vanilla::{Graphic, Image, Rect, Vector2};
  
  fn draw_panel(graphic: &mut Graphic, panel_image: &Rc<Image>) {
  	graphic.draw_image_with_nine_slice(panel_image, Vector2::create(20.0, 20.0), Vector2::create(300.0, 120.0), Rect::create(16.0, 16.0, 16.0, 16.0));
  }
  ```

- `pub fn set_font_string(&mut self, font_string: &str)` (method, since 0.3.2): Sets the font string. (equivalent to Canvas2D font, e.g. "16px DOSGothic")
  - `font_string` &str: Text in Canvas2D font form. (like "bold 16px sans-serif", unchanged if empty)
- `pub fn get_font_string(&self) -> &str` (method, since 0.3.2): Returns the font string.
  - returns &str: Current font string. (initially "10px sans-serif")
- `pub fn set_text_align(&mut self, text_align: TextAlign)` (method, since 0.3.2): Sets the horizontal alignment.
  - `text_align` TextAlign: Horizontal alignment. (initially Start)
- `pub fn get_text_align(&self) -> TextAlign` (method, since 0.3.2): Returns the horizontal alignment.
  - returns TextAlign: Current horizontal alignment.
- `pub fn set_text_direction(&mut self, text_direction: TextDirection)` (method, since 0.4.0): Sets the text direction. (the original setTextDirection, corresponds to Canvas2D direction)
  - It is the paragraph direction. The order within the text (bidirectional algorithm) and the left and right of alignment Start / End follow it.
  - Inherit is treated as Ltr. (default) Auto decides per string by the first strongly directional character. Use it for user-written text (nicknames and such).
  - `text_direction` TextDirection: Text direction. (initially Inherit)
- `pub fn get_text_direction(&self) -> TextDirection` (method, since 0.4.0): Returns the text direction.
  - returns TextDirection: The set text direction. (Inherit, Auto as is without resolving, the actual direction is resolve_text_direction)
- `pub fn resolve_text_direction(&self, text: &str) -> TextDirection` (method, since 0.4.0): Computes the actual direction of a string. (Ltr or Rtl, the original resolveTextDirection)
  - `text` &str: String to check the direction of when Auto.
  - returns TextDirection: Rtl if the setting is Rtl, detect_text_direction(text) if Auto, Ltr otherwise (Inherit, Ltr).
- `pub fn resolve_text_align(&self, text_align: TextAlign, text_direction: TextDirection) -> TextAlign` (method, since 0.3.2): Computes the actual horizontal alignment. (Start / End to Left / Right by direction, the original resolveTextAlign)
  - `text_align` TextAlign: Alignment to resolve.
  - `text_direction` TextDirection: Text direction. (only Rtl is treated as right to left)
  - returns TextAlign: Start is Right if Rtl, otherwise Left. End is the opposite. Others stay as is.
- `pub fn set_text_baseline(&mut self, text_baseline: TextBaseline)` (method, since 0.3.2): Sets the vertical baseline.
  - `text_baseline` TextBaseline: Vertical baseline. (initially Alphabetic)
- `pub fn get_text_baseline(&self) -> TextBaseline` (method, since 0.3.2): Returns the vertical baseline.
  - returns TextBaseline: Current vertical baseline.
- `pub fn measure_text(&self, text: &str) -> TextMetrics` (method, since 0.3.2): Measures a string. (with the current font string)
  - `text` &str: String to measure.
  - returns TextMetrics: Measured values. (pixels, the current transform is ignored) All 0 on desktop if there is no face to draw with.

  Example: A label fitted to the text width

  ```rust
  use vanilla::{Colors, Graphic, Rect, TextAlign, TextBaseline};
  
  fn draw_label(graphic: &mut Graphic, text: &str) {
  	graphic.set_font_string("20px sans-serif");
  	let text_metrics = graphic.measure_text(text);
  	let padding = 8.0;
  	let box_width = text_metrics.width + padding * 2.0;
  	let box_height = text_metrics.font_ascent + text_metrics.font_descent + padding * 2.0;
  	graphic.set_fill_color(Colors::BLACK);
  	graphic.draw_rect(Rect::create(20.0, 20.0, box_width, box_height));
  	graphic.set_text_align(TextAlign::Left);
  	graphic.set_text_baseline(TextBaseline::Top);
  	graphic.set_fill_color(Colors::WHITE);
  	graphic.draw_fill_text(text, 20.0 + padding, 20.0 + padding);
  }
  ```

- `pub fn measure_text_with_font_string(&self, font_string: &str, text: &str) -> TextMetrics` (method, since 0.4.0): Measures a string. (with the given font string, the current font string is not changed)
  - `font_string` &str: Font string to measure with. (Canvas2D font form)
  - `text` &str: String to measure.
  - returns TextMetrics: Measured values. (pixels, the current transform is ignored) All 0 on desktop if there is no face to draw with.
- `pub fn set_text_bake_scale_step(&mut self, text_bake_scale_step: f64)` (method, since 0.3.2): Sets the text bake scale quantization step.
  - Default 0.25. Groups scales so text that is often zoomed is not baked anew for every scale.
  - 0 means no quantization, baking at the actual scale.
  - `text_bake_scale_step` f64: Quantization step. (0 if less than 0)
- `pub fn get_text_bake_scale_step(&self) -> f64` (method, since 0.3.2): Returns the text bake scale quantization step.
  - returns f64: Quantization step. (initially 0.25)
- `pub fn set_text_bake_motion_scale_step(&mut self, text_bake_motion_scale_step: f64)` (method, since 0.4.0): Sets the text bake scale quantization step for nodes whose scale is moving. (default 0.25)
  - When the quantization step (set_text_bake_scale_step) is 0 and the transform scale of the drawn node differs from the last frame (zoom motion, popups, tweens, camera zoom),
    it bakes at the scale grouped by this step. It does not bake anew at a different scale every frame.
  - When the scale stops (same as the last frame), it bakes again at the exact scale and is sharp at 1:1.
  - 0 means no grouping even while moving. (same as before)
  - `text_bake_motion_scale_step` f64: Quantization step while the scale is moving. (0 if less than 0)
- `pub fn get_text_bake_motion_scale_step(&self) -> f64` (method, since 0.4.0): Returns the text bake scale quantization step for nodes whose scale is changing.
  - returns f64: Quantization step while the scale is moving. (initially 0.25)
- `pub fn set_text_bake_scale_moving(&mut self, is_text_bake_scale_moving: bool)` (method, since 0.4.0): Sets whether the scale of the node being drawn is moving. (decided by NodeTree, the caller can decide when drawing directly outside a node)
  - `is_text_bake_scale_moving` bool: true if the scale is moving.
- `pub fn is_text_bake_scale_moving(&self) -> bool` (method, since 0.4.0): Returns whether the scale of the node being drawn is changing.
  - returns bool: true if marked as moving.
- `pub fn update_text_bake_scale_moving(&mut self, last_drawn_maximum_scale: f64) -> f64` (method, since 0.4.0): Computes and decides whether the node's transform scale is moving because it differs from the last frame, and returns the scale to remember on the node. (NodeTree calls it after push_transform)
  - last_drawn_maximum_scale is the value from when that node was last drawn. (0 means unknown yet, a node drawn for the first time is treated as not moving)
  - If the quantization step is not 0 it always bakes grouped, so it returns the given value as is without computing.
  - `last_drawn_maximum_scale` f64: Scale returned when that node was last drawn. (0 if first time)
  - returns f64: Scale to remember on the node. (the largest scale of the current transform, the given value as is if the quantization step is not 0 or the motion step is 0)
- `pub fn set_text_pixel_snap_enabled(&mut self, is_text_pixel_snap_enabled: bool)` (method, since 0.3.2): Sets text pixel snapping.
  - When on, the top left of glyph quads is aligned to the device pixel grid for transforms without rotation / skew.
  - `is_text_pixel_snap_enabled` bool: true aligns text to device pixels. (initially false)
- `pub fn is_text_pixel_snap_enabled(&self) -> bool` (method, since 0.3.2): Returns whether text pixel snapping is on.
  - returns bool: true if pixel snapping is on.
- `pub fn set_text_antialias_enabled(&mut self, is_text_antialias_enabled: bool)` (method, since 0.4.0): Text antialiasing on / off. (the original Graphic.setTextAntialiasEnabled)
  - When off, the alpha of baked text is split into 0 and 255 at threshold 128 and the texture is sampled with NEAREST. (for pixel fonts)
  - It applies from text baked after switching. Text already baked stays as it is.
  - `is_text_antialias_enabled` bool: If true, turns it on. (true at first)
- `pub fn is_text_antialias_enabled(&self) -> bool` (method, since 0.4.0): Whether text antialiasing is on. (the original Graphic.isTextAntialiasEnabled)
  - returns bool: true if enabled.
- `pub fn calculate_text_bake_scale(&self) -> f64` (method, since 0.3.2): Computes the text bake scale. (based on the current transform matrix, the quantization step is set_text_bake_scale_step)
  - returns f64: The largest scale of the current transform rounded to the quantization step. (clamped to 0.25 ~ 8, to the motion step if the step is 0 and moving, not rounded if both are 0)
- `pub fn draw_text_entry(&mut self, entry: TextEntry, x: f64, y: f64, color: Option<Color>, text_direction: TextDirection)` (method, since 0.3.2): 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.
  - text_direction is the direction that decides alignment Start / End. (Ltr or Rtl, textDirection of the original drawTextEntry)
  - `entry` TextEntry: Text layout entry. (TextStringTextureCache::get_entry)
  - `x` f64: Reference x. (reference point of the horizontal alignment, pixels)
  - `y` f64: Reference y. (reference point of the vertical baseline, pixels)
  - `color` Option<Color>: Color to multiply by. (white if None, as baked)
  - `text_direction` TextDirection: Direction that decides alignment Start, End.
- `pub fn draw_fill_text(&mut self, text: &str, x: f64, y: f64)` (method, since 0.3.2): Draws filled text. (corresponds to Canvas2D fillText)
  - set_fill_color() / set_font_string() / set_text_align() / set_text_baseline()
  - `text` &str: String to draw. (not drawn if empty)
  - `x` f64: Reference x. (reference point of set_text_align, pixels)
  - `y` f64: Reference y. (reference point of set_text_baseline, pixels)
- `pub fn draw_stroke_text(&mut self, text: &str, x: f64, y: f64, line_width: f64)` (method, since 0.3.2): Draws outlined text. (corresponds to Canvas2D strokeText)
  - set_stroke_color() / set_font_string() / set_text_align() / set_text_baseline()
  - `text` &str: String to draw. (not drawn if empty)
  - `x` f64: Reference x. (reference point of set_text_align, pixels)
  - `y` f64: Reference y. (reference point of set_text_baseline, pixels)
  - `line_width` f64: Outline thickness. (pixels)
- `pub fn begin_clip_rect(&mut self, rect: Rect, round_size: f64)` (method, since 0.3.2): Starts limiting the draw area.
  - Based on the stencil buffer, so rotated/scaled areas are clipped exactly.
  - Giving round_size clips to a rounded rectangle.
  - Pushes the state with push_state, so call it paired with end_clip_rect. (end_clip_rect restores with pop_state) Nested clips clip to the intersection.
  - `rect` Rect: Rectangle to clip to. (in the current transform, pixels)
  - `round_size` f64: Corner radius. (square if 0 or less)

  Example: Drawing a circle only inside a rounded box

  ```rust
  use vanilla::{Colors, Graphic, Rect, Vector2};
  
  fn draw(graphic: &mut Graphic) {
  	graphic.begin_clip_rect(Rect::create(100.0, 100.0, 200.0, 100.0), 12.0);
  	graphic.set_fill_color(Colors::WHITE);
  	graphic.draw_circle(Vector2::create(100.0, 100.0), 80.0);
  	graphic.end_clip_rect();
  }
  ```

- `pub fn begin_opacity_layer(&mut self)` (method, since 0.4.0): Starts an opacity layer. (Like CSS opacity or an Adobe transparency group, collects what is drawn until end_opacity_layer into a separate target and puts it on at once with the current global alpha)
  - Drawings inside the layer do not show through where they overlap each other. (Multiplying opacity per node and putting each on separately shows the drawing below where they overlap)
  - The layer starts at global alpha 1. The layer target is an RGBA8 the size of the screen, and its depth is cleared and its stencil is filled with the current clip depth, so clips and 3D passes (is_depth_cleared false in run_external_pass) inside the layer work as they are.
    The outer clip applies when putting it on. Layers can be nested. If the target cannot be built, draws as is without a layer.
  - NodeTree draws a node with set_opacity_layer on and the node's descendants as a layer when its opacity is less than 1.

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

  ```rust
  use vanilla::{Graphic, Rect};
  
  fn draw(graphic: &mut Graphic) {
  	graphic.push_state();
  	graphic.set_global_alpha(0.5);
  	graphic.begin_opacity_layer();
  	graphic.set_fill_color("#ff0000");
  	graphic.draw_rect(Rect::create(100.0, 100.0, 200.0, 100.0));
  	graphic.set_fill_color("#0000ff");
  	graphic.draw_rect(Rect::create(200.0, 150.0, 200.0, 100.0));
  	graphic.end_opacity_layer();
  	graphic.pop_state();
  }
  ```

- `pub fn end_opacity_layer(&mut self)` (method, since 0.4.0): Ends an opacity layer. (Lays what was drawn after begin_opacity_layer onto the previous framebuffer with the global alpha at the time the layer was opened)
- `pub fn end_clip_rect(&mut self)` (method, since 0.3.2): Ends clipping the output region.
- `pub fn get_shader_program(&self) -> &ShaderProgram` (method, since 0.3.2): Returns the shader program. (the override if there is one, otherwise the default program)
  - returns &ShaderProgram: The override program if there is one, otherwise the default program.
- `pub fn set_shader_program_override(&mut self, shader_program: Option<Rc<ShaderProgram>>)` (method, since 0.3.2): Overrides the shader program. (returns to the default program if None)
  - Must have the same attribute locations / uniform names as the default program (projectionMatrix, modelMatrix, mainColor, tintColor, globalAlpha, mainTexture).
  - While the override program is in effect, that program is in use. Effect uniforms are uploaded directly through GL right after overriding.
  - `shader_program` Option<Rc<ShaderProgram>>: Program to override with. (obtained with resolve_shader_program, the default program if None)
- `pub fn resolve_shader_program(&mut self, program_group_name: &'static str, program_name: &'static str, create_shader_source: impl FnOnce() -> (String, String)) -> Option<Rc<ShaderProgram>>` (method, since 0.3.2): Returns the override shader program kept by name. (if none, creates and keeps it from the vertex / fragment source given by create_shader_source)
  - In place of the per-context program cache of the original ShaderSprite. In the Rust version, Graphic, which holds the GL context, keeps it.
  - Links with attribute locations fixed to match the default program, so the default vertex array is used as is.
  - If creation fails, it reports once and keeps None so it is not created again.
  - `program_group_name` &'static str: Group name. (such as the effect kind, the front part of the key)
  - `program_name` &'static str: Program name. (the back part of the key)
  - `create_shader_source` impl FnOnce() -> (String, String): Function called only when nothing is kept. ((vertex source, fragment source), GLSL ES 3.00)
  - returns Option<Rc<ShaderProgram>>: The kept program. None if creation failed. (None from then on too)

  Example: Drawing an image with a grayscale shader override

  ```rust
  use std::rc::Rc;
  use vanilla::{Graphic, Image, Vector2};
  
  const GRAY_VERTEXSHADER_SOURCE: &str = "#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: &str = "#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, vec3(0.299, 0.587, 0.114));
  	float alpha = textureColor.a * mainColor.a * globalAlpha;
  	outputColor = vec4(vec3(gray) * mainColor.a * globalAlpha, alpha);
  }
  ";
  
  fn draw_gray(graphic: &mut Graphic, image: &Rc<Image>) {
  	let shader_program = graphic.resolve_shader_program("example", "gray", || (GRAY_VERTEXSHADER_SOURCE.to_string(), GRAY_FRAGMENTSHADER_SOURCE.to_string()));
  	graphic.set_shader_program_override(shader_program);
  	graphic.draw_image(image, Vector2::create(0.0, 0.0), Vector2::create(128.0, 128.0));
  	graphic.set_shader_program_override(None);
  }
  ```

- `pub fn restore_render_state(&mut self)` (method, since 0.3.2): Restores the render state. (for continuing Graphic output after an external GL pass changed the program / vertex array / viewport / blending, the original restoreRenderState)
  - Does not restore the stencil clip state. (run_external_pass restores it at the end, same as the original)
- `pub fn get_drawing_buffer_width(&self) -> i32` (method, since 0.3.2): Returns the drawing buffer width. (pixels, the original webGL2RenderingContext.drawingBufferWidth)
  - returns i32: Drawing buffer width of the last apply_settings. (pixels)
- `pub fn get_drawing_buffer_height(&self) -> i32` (method, since 0.3.2): Returns the drawing buffer height. (pixels, the original webGL2RenderingContext.drawingBufferHeight)
  - returns i32: Drawing buffer height of the last apply_settings. (pixels)
- `pub fn read_framebuffer_pixels(&self) -> (u32, u32, Vec<u8>)` (method, since 0.3.2): Reads the screen drawn so far. (width, height, RGBA laid out top to bottom. Call it before presenting)
  - Treated as opaque like the original canvas. (alpha 255)
  - returns (u32, u32, Vec<u8>): (width, height, pixels). Pixels are RGBA bytes laid out from the top row (width x height x 4) and alpha is all 255. (read from the current read framebuffer)
- `pub fn get_color_space(&self) -> crate::core::colorspace::ColorSpace` (method, since 0.4.0): Returns the 3D color space. (original getColorSpace, fixed at creation, color_space from the engine configuration)
  - returns crate::core::colorspace::ColorSpace: ColorSpace::Gamma or ColorSpace::Linear. (2D batches are composited in gamma space either way)
- `pub fn get_gl(&self) -> &GlContext` (method, since 0.3.2): Returns the GL context. (the original getWebGL2RenderingContext)
  - The state functions of the received context (GlContext) go through the GL state cache, so the engine knows state changed after receiving it.
    Graphic does not remember bindings and 2D state separately and compares against the state cache before drawing, so even if the receiver changes the program, textures, blending, and the like, the next 2D draw sets them again.
  - Returns the color write mask to all channels. (what Graphic turned off so as not to write alpha to the desktop default framebuffer)
  - Does not forget the GL state cache. (same as the original; the inner glow::Context cannot be taken out, so the receiver cannot skip the state cache)
  - returns &GlContext: The GL context the Graphic holds. Pass it as is as the `&GlContext` argument of engine functions. (The inner glow::Context cannot be taken out)
- `pub fn get_current_framebuffer(&self) -> Option<GlFramebuffer>` (method, since 0.4.0): Return the framebuffer being drawn to now. (original getCurrentFramebuffer, the value remembered by the state cache, GL is not asked while drawing)
  - returns Option<GlFramebuffer>: The draw framebuffer bound now. None for the default framebuffer (window, canvas).

  Example: Read the current framebuffer and viewport in a scene

  ```rust
  use vanilla::Graphic;
  
  fn draw(graphic: &mut Graphic) {
  	let framebuffer = graphic.get_current_framebuffer();
  	let viewport = graphic.get_current_viewport();
  	println!("{} {} {}", framebuffer.is_none(), viewport.get_width(), viewport.get_height());
  	graphic.reset_gl_state_cache();
  }
  ```

- `pub fn get_current_viewport(&self) -> Rect` (method, since 0.4.0): Return the current viewport. (original getCurrentViewport, pixels, bottom-left origin, the value remembered by the state cache)
  - returns Rect: Viewport rectangle. (x, y, width, height)
- `pub fn reset_gl_state_cache(&self)` (method, since 0.4.0): Reset the GL state cache. (original resetGLStateCache, call it after changing GL state without going through the state cache; each value is asked from GL once on the next read)
  - The GlContext given by get_gl, run_external_pass and toon renderer callbacks sends state functions through the state cache, so there is no need to call this even when engine drawing continues inside the same callback.
  - GlContext has no way to take out the inner glow::Context, so game code cannot bypass the state cache.
    Call it when another library changed the state of the same GL context and engine drawing continues inside the same callback.
  - The engine does not reset by itself where it hands GL over (get_gl, run_external_pass, toon renderer callbacks). (Same as the original)
  - To find calls that bypassed the state cache, run with the environment variable VANILLA_GL_STATE_CHECK=1. (Before every engine draw it compares the remembered values with real GL and prints the mismatched part and the preceding state calls to standard error)
- `pub fn is_context_lost(&self) -> bool` (method, since 0.4.0): Whether the WebGL context is lost. (The original's isContextLost, true after webglcontextlost on the web and false again once the engine has rebuilt its base resources)
  - While lost, the engine does not draw and only updates scenes. Desktop never loses the context, so this is always false.
  - returns bool: true while lost.

  Example: Skipping the game's drawing while the context is lost

  ```rust
  use vanilla::{Colors, Graphic, Rect};
  
  fn draw(graphic: &mut Graphic) {
  	if graphic.is_context_lost() {
  		return;
  	}
  	graphic.set_fill_color(Colors::WHITE);
  	graphic.draw_rect(Rect::create(8.0, 8.0, 32.0, 32.0));
  }
  ```

- `pub fn enable_gpu_memory_tracking(&self)` (method, since 0.4.0): Turns GPU memory tracking on. (original Graphic.enableGpuMemoryTracking, for development)
  - Counts the textures, renderbuffers and buffers created after it is turned on. Does nothing if it is already on.
    Before it is on, GL creation and sizing calls only look at one flag, so nothing runs per frame. To count the resources the engine creates first, use EngineConfiguration::track_gpu_memory.

  Example: Turn GPU memory tracking on

  ```rust
  use vanilla::Graphic;
  
  fn enable(graphic: &Graphic) {
  	graphic.enable_gpu_memory_tracking();
  	assert!(graphic.is_gpu_memory_tracking_enabled());
  }
  ```

- `pub fn is_gpu_memory_tracking_enabled(&self) -> bool` (method, since 0.4.0): Whether GPU memory tracking is on. (original Graphic.isGpuMemoryTrackingEnabled)
  - returns bool: true if enabled.

  Example: Read whether it is on

  ```rust
  use vanilla::Graphic;
  
  fn check(graphic: &Graphic) -> bool {
  	graphic.is_gpu_memory_tracking_enabled()
  }
  ```

- `pub fn read_gpu_memory_usage(&self) -> crate::core::gpumemorytracker::GpuMemoryUsage` (method, since 0.4.0): Reads GPU memory. (original Graphic.readGpuMemoryUsage, for development)
  - Reads the GPU memory used by textures, renderbuffers and buffers by kind and by owner. (nominal values computed from format and size; multisample renderbuffers multiply by the sample count)
    If tracking is off, this call turns it on and counts what is created after it. To count everything from the start, set EngineConfiguration::track_gpu_memory to true.
  - returns crate::core::gpumemorytracker::GpuMemoryUsage: The total (including the canvas default framebuffer share), the canvas share, the share by kind and by owner (largest first; the owner is the top three frames of the creating call stack).

  Example: Read the GPU memory total

  ```rust
  use vanilla::Graphic;
  
  fn read(graphic: &Graphic) {
  	let usage = graphic.read_gpu_memory_usage();
  	println!("{} {}", usage.total_bytes, usage.owner_list.len());
  }
  ```

- `pub fn get_vertex_array(&self) -> GlVertexArray` (method, since 0.4.0): Returns the vertex array. (the one for default drawing, get the context with get_gl to touch GL)
  - returns GlVertexArray: Default vertex array.
- `pub fn get_vertex_buffer(&self) -> GlBuffer` (method, since 0.4.0): Returns the vertex buffer.
  - returns GlBuffer: Default vertex buffer.
- `pub fn get_vertex_data(&mut self) -> &mut [f32]` (method, since 0.4.0): Returns the scratch vertex data. (the array write_quad and draw_vertices use)
  - returns &mut [f32]: Scratch vertex array. (4096 vertices, 4 floats x, y, u, v per vertex)
- `pub fn get_white_texture(&self) -> GlTexture` (method, since 0.3.2): Returns the white texture.
  - returns GlTexture: 1 x 1 white texture. (used for solid color drawing)
- `pub fn get_white_color(&self) -> Color` (method, since 0.3.2): Returns white.
  - returns Color: White. (passed to draw_vertices to draw the texture color as is)
- `pub fn get_image_texture_cache(&self) -> &ImageTextureCache` (method, since 0.3.2): Returns the image texture cache.
  - returns &ImageTextureCache: Image texture cache.
- `pub fn get_text_string_texture_cache(&mut self) -> &mut TextStringTextureCache` (method, since 0.3.2): Returns the string texture cache. (for font registration)
  - returns &mut TextStringTextureCache: String texture cache.

## Functions and constants

- `pub const FLOATS_PER_VERTEX: usize = 4` (field, since 0.3.2): Number of floats per vertex. (x, y, u, v)
  - returns usize
- `pub const PARTICLE_FLOATS_PER_VERTEX: usize = 8` (field, since 0.3.2): Number of floats per particle vertex. (x, y, u, v, r, g, b, a)
  - returns usize
- `pub fn is_right_to_left_character(character: char) -> bool` (method, since 0.4.0): Whether a character is written right to left. (the original RIGHT_TO_LEFT_CHARACTER_PATTERN: Hebrew, Arabic, Syriac, Thaana, N'Ko and others and their presentation forms)
  - `character` char: Character to check.
  - returns bool: true if the code point is within U+0590 ~ U+08FF, U+FB1D ~ U+FDFF, U+FE70 ~ U+FEFF, U+10800 ~ U+10FFF, U+1E800 ~ U+1EFFF.
- `pub fn detect_text_direction(text: &str) -> TextDirection` (method, since 0.4.0): First strong direction of the text. (the "auto" of the original resolveTextDirection: the first of letter category characters and LRM, RLM, ALM, Ltr if none)
  - `text` &str: String to check.
  - returns TextDirection: Rtl if the first strong character (letter category characters and LRM, RLM, ALM) is a right-to-left character or RLM (U+200F), ALM (U+061C), otherwise Ltr. Ltr if there is no strong character.

  Example: Skipping digits and symbols and deciding by the first letter

  ```rust
  use vanilla::{detect_text_direction, TextDirection};
  
  assert_eq!(detect_text_direction("Hello"), TextDirection::Ltr);
  assert_eq!(detect_text_direction("123 \u{05E9}\u{05DC}\u{05D5}\u{05DD}"), TextDirection::Rtl);
  assert_eq!(detect_text_direction("\u{200F}abc"), TextDirection::Rtl);
  assert_eq!(detect_text_direction("2024!"), TextDirection::Ltr);
  ```

## BlendMode (enum) (Clone, Copy, Debug, PartialEq, Eq, Hash)

Blend mode. (the original SpriteBlendMode, corresponds to Canvas2D globalCompositeOperation)
- All 26 are drawn. 13 (Porter-Duff operators, Lighter, Multiply, Screen) use fixed blending, and the other 13 grab what is under the draw area and mix it in a shader. (same as the original)
- In Canvas2D, SourceIn, SourceOut, DestinationIn, DestinationAtop, Copy also erase outside the drawn shape (the whole clip area), but Graphic changes only inside the drawn shape. (same as the original)

- `Normal`: Default alpha compositing. ("source-over", fixed blending)
- `SourceIn`: Draws only where it overlaps the backdrop. ("source-in", backdrop alpha as a mask, fixed blending)
- `SourceOut`: Draws only where it does not overlap the backdrop. ("source-out", fixed blending)
- `SourceAtop`: Composites only over the overlapping part of the backdrop. ("source-atop", fixed blending)
- `DestinationOver`: Composites under the backdrop. ("destination-over", fixed blending)
- `DestinationIn`: Keeps only the overlapping part of the backdrop. ("destination-in", fixed blending)
- `DestinationOut`: Keeps only the non-overlapping part of the backdrop. ("destination-out", fixed blending)
- `DestinationAtop`: Keeps the backdrop where they overlap, and puts the drawing where there is no backdrop. ("destination-atop", fixed blending)
- `Lighter`: Adds colors. ("lighter", fixed blending)
- `Copy`: Puts only the drawing, ignoring the backdrop. ("copy", fixed blending)
- `Xor`: Keeps both except where they overlap. ("xor", fixed blending)
- `Multiply`: Multiply compositing. ("multiply", darkens, fixed blending on the default framebuffer, shader mixing on render targets)
- `Screen`: Screen compositing. ("screen", lightens, fixed blending)
- `Overlay`: Overlay. ("overlay", increases contrast, shader mixing)
- `Darken`: Picks the darker one. ("darken", shader mixing)
- `Lighten`: Picks the lighter one. ("lighten", shader mixing)
- `ColorDodge`: Color dodge. ("color-dodge", lightens, shader mixing)
- `ColorBurn`: Color burn. ("color-burn", darkens, shader mixing)
- `HardLight`: Hard light. ("hard-light", shader mixing)
- `SoftLight`: Soft light. ("soft-light", shader mixing)
- `Difference`: Difference compositing. ("difference", shader mixing)
- `Exclusion`: Lower contrast difference compositing. ("exclusion", shader mixing)
- `Hue`: Hue of the drawing with the saturation and luminosity of the backdrop. ("hue", shader mixing)
- `Saturation`: Saturation of the drawing with the hue and luminosity of the backdrop. ("saturation", shader mixing)
- `Color`: Hue and saturation of the drawing with the luminosity of the backdrop. ("color", shader mixing)
- `Luminosity`: Luminosity of the drawing with the hue and saturation of the backdrop. ("luminosity", shader mixing)

- `pub fn get_name(&self) -> &'static str` (method, since 0.3.2): Returns the original name. (a string like "source-over")
  - returns &'static str: The original globalCompositeOperation name. ("source-over" for Normal)
- `pub fn from_name(name: &str) -> Option<BlendMode>` (static, since 0.3.2): Finds by the original name. (None for unknown names. Used when reading from JSON such as timelines and particle descriptions)
  - `name` &str: The original globalCompositeOperation name. (lowercase and hyphens like "multiply", case-sensitive)
  - returns Option<BlendMode>: Blend mode matching the name. None for unknown names.

  Example: A name string from JSON to a blend mode

  ```rust
  use vanilla::BlendMode;
  
  assert_eq!(BlendMode::from_name("multiply"), Some(BlendMode::Multiply));
  assert_eq!(BlendMode::from_name("source-over"), Some(BlendMode::Normal));
  assert_eq!(BlendMode::from_name("unknown"), None);
  assert_eq!(BlendMode::ColorDodge.get_name(), "color-dodge");
  ```

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

Horizontal alignment.

- `Left`: Left aligned. (x is the left end of the text)
- `Center`: Center aligned. (x is the horizontal center of the text)
- `Right`: Right aligned. (x is the right end of the text)
- `Start`: Aligned to the start side of the text direction. (left for Ltr, right for Rtl, the initial value of Graphic)
- `End`: Aligned to the end side of the text direction. (right for Ltr, left for Rtl)

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

Vertical baseline.

- `Top`: Top baseline. (y is the top of the font ascent)
- `Middle`: Middle baseline. (y is midway between the top of the ascent and the bottom of the descent)
- `Bottom`: Bottom baseline. (y is the bottom of the font descent)
- `Ideographic`: Ideographic baseline. (like Bottom, y is the bottom of the descent)
- `Hanging`: Hanging baseline. (y is 0.8 times the ascent above the baseline)
- `Alphabetic`: Alphabetic baseline. (y is the baseline, the initial value of Graphic)

## TextDirection (enum) (Clone, Copy, Debug, PartialEq, Eq, Hash)

Text direction. (the original "inherit" | "ltr" | "rtl" | "auto", Canvas2D direction)
- Inherit is treated as left to right in Graphic. In text components it means following the Graphic direction at draw time.
- Auto decides per string by the first strongly directional character. (dir="auto" of HTML, left to right if none)

- `Inherit`: Inherit. (the initial value of Graphic, treated as Ltr in Graphic)
- `Ltr`: Left to right.
- `Rtl`: Right to left.
- `Auto`: Decides per string by the first strongly directional character. (Ltr if none)

- `pub fn from_name(name: &str) -> TextDirection` (static, since 0.4.0): Reads from the original text. ("ltr", "rtl", "auto", Inherit otherwise)
  - `name` &str: Original text. ("inherit", "ltr", "rtl", "auto", case-sensitive)
  - returns TextDirection: The read direction. Inherit for unknown text.
- `pub fn get_name(&self) -> &'static str` (method, since 0.4.0): Original text. ("inherit", "ltr", "rtl", "auto")
  - returns &'static str: Original text. (one of "inherit", "ltr", "rtl", "auto")
- `pub fn to_shaping_direction(&self) -> ShapingDirection` (method, since 0.4.0): Shaping direction. (only Rtl is right to left, used after resolving to the actual direction)
  - returns ShapingDirection: `ShapingDirection::RightToLeft` if Rtl, otherwise (including Inherit, Auto) `ShapingDirection::LeftToRight`.

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

Image smoothing quality. ("low", "medium", "high" of the original setImageSmoothingQuality)
- GL only has LINEAR / NEAREST, so it is only stored like the original.

- `Low`: Low. ("low")
- `Medium`: Medium. ("medium")
- `High`: High. ("high", the initial value of Graphic)
