# graphics3d/material (vanilla-engine 0.4.0)

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

Material. (the original graphics3d/material.js)
- Shader template reference + metallic-roughness PBR parameters/textures, format neutral. Models only apply material instances.
- Builds GL textures from the neutral material description made by importers (factors + image bytes, MaterialDescription).
- FBX specular/gloss maps approximate roughness through the glossiness path.
- The texture unit layout is the same as the original: 0 = base_color, 1 = shadow map only (do not use), 2 ~ 8 = normal / metallicRoughness /
  glossiness / occlusion / emissive / specular / opacity, extra slots are 9 and above.
- Differences from the original:
  - The shader program is shared with the renderer as `Rc<ShaderProgram>`. Model drawables point to materials with `Rc<Material>`. (the original reference semantics)
    set_texture / set_use_alpha_cutout / set_subsurface_factor, which modify the instance in the original, hold their state in Cell internally so they can be called with &self.
  - Image decoding is done on the spot with the image crate (png, jpeg, webp, gif, bmp, ico) instead of the original createImageBitmap (async). So there is no async.
    As in the original on Chrome, the type is not used for decoding and the format is detected from the content. (Chrome createImageBitmap(Blob) also picks the decoder by content, not by the Blob type)
    Like the original, flip_y flips it vertically and is_color_data uploads it as SRGB8_ALPHA8.
  - The Promise of the original loadImageDescription(url) is a load handle (ImageDescriptionLoadHandle), like ImageAsset. load_image_description(engine, asset path, options)
    requests the bytes through the engine's asset loading (asset folder candidates on desktop, fetch from asset_base_url on the web), and once loaded get_image_description builds the description.
    The handle can be awaited directly. (inside an engine task, Material::load_image_description(engine, path, options).await yields the description like the original await)
    mime_type is the content-type of the response, as in the original. (the web fetch response header, None without the header) Desktop has no response, so it is the type detected from the content.
    (Image::sniff_image_mime_type, the image table of WHATWG MIME sniffing plus AVIF, None when unknown) create_image_description(bytes), which takes bytes, is the same as the original.
  - The source (canvas/bitmap) of the original image description is taken as RGBA pixels (ImageSource).

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

Already decoded RGBA pixels. (the source of the original image description, in place of a canvas/bitmap, straight alpha, top to bottom)

Example: Put 2 x 1 pixels (red, blue) as the source of an image description

```rust
use std::rc::Rc;
use vanilla::{ImageDescription, ImageSource};

let image_source = ImageSource { width: 2, height: 1, pixels: vec![255, 0, 0, 255, 0, 0, 255, 255] };
let image_description = ImageDescription { source: Some(Rc::new(image_source)), is_color_data: true, ..ImageDescription::default() };
assert!(image_description.bytes.is_empty());
assert_eq!(image_description.source.as_ref().map(|source| source.width), Some(2));
```

- `pub width: u32` (field, since 0.3.2): Width in pixels.
  - returns u32
- `pub height: u32` (field, since 0.3.2): Height in pixels.
  - returns u32
- `pub pixels: Vec<u8>` (field, since 0.3.2): RGBA bytes. (4 bytes per pixel, from the top row, length at least width x height x 4)
  - returns Vec<u8>

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

Image description. (the original { bytes, mime_type, flip_y, is_color_data, anisotropy } or { source, flip_y })
- bytes is the png / jpeg / webp file content. When several textures use the same image, it is shared with Rc. (duplicate references to FBX videos)

Example: Build a description for a color texture from file bytes

```rust
use vanilla::{ImageDescriptionOptions, Material};

let bytes = std::fs::read("examples/assets/atlas/icons.png").unwrap();
let options = ImageDescriptionOptions { flip_y: false, is_color_data: true, anisotropy: 8.0 };
let image_description = Material::create_image_description(bytes, Some(String::from("image/png")), Some(options));
assert!(image_description.is_color_data);
assert_eq!(image_description.anisotropy, 8.0);
assert!(image_description.source.is_none());
```

- `pub bytes: Rc<Vec<u8>>` (field, since 0.3.2): Image file content. (png, jpeg, webp, gif, bmp, ico, when it is empty and there is no source either, create_texture uses the fallback color)
  - returns Rc<Vec<u8>>
- `pub mime_type: Option<String>` (field, since 0.3.2): Type. (the response content-type or the type detected from the content, not used for decoding, None when unknown)
  - returns Option<String>
- `pub source: Option<Rc<ImageSource>>` (field, since 0.3.2): Already decoded RGBA pixels. (used instead of bytes when present)
  - returns Option<Rc<ImageSource>>
- `pub flip_y: bool` (field, since 0.3.2): Whether to flip vertically on upload. (imageOrientation of the original createImageBitmap)
  - returns bool
- `pub is_color_data: bool` (field, since 0.3.2): Whether it is color data. (if true, uploaded as SRGB8_ALPHA8 and sampled linearly, false for data maps such as normals)
  - returns bool
- `pub anisotropy: f64` (field, since 0.3.2): Anisotropic filter level. (not used at 0 or below, clamped to the device maximum, ignored without the extension)
  - returns f64

## ImageDescriptionOptions (struct) (Clone, Copy, Debug, Default, PartialEq)

Image description options. (options { flip_y, is_color_data, anisotropy } of the original loadImageDescription)

Example: The default has everything off, and passing None for options is the same as the default

```rust
use vanilla::{ImageDescriptionOptions, Material};

assert_eq!(ImageDescriptionOptions::default(), ImageDescriptionOptions { flip_y: false, is_color_data: false, anisotropy: 0.0 });
let image_description = Material::create_image_description(vec![1, 2, 3], None, None);
assert!(!image_description.flip_y);
assert!(!image_description.is_color_data);
assert_eq!(image_description.anisotropy, 0.0);
```

- `pub flip_y: bool` (field, since 0.3.2): Whether to flip vertically. (default false)
  - returns bool
- `pub is_color_data: bool` (field, since 0.3.2): Whether it is color data. (if true, uploaded as sRGB, default false)
  - returns bool
- `pub anisotropy: f64` (field, since 0.3.2): Anisotropic filter level. (not used at 0, default 0)
  - returns f64

## ImageDescriptionLoadHandle (struct) (Clone, Debug, IntoFuture)

Image description load handle. (returned by Material::load_image_description, stands in for the Promise of the original loadImageDescription)
- A scene can hand get_load_handle to SceneBase::track_load_handle to defer initialize until loading finishes.

Example: Load asset bytes and build a description (on desktop it finishes on the spot)

```rust
use vanilla::{Engine, EngineConfiguration, ImageDescriptionOptions, Material};

let engine = Engine::new(EngineConfiguration::new());
let options = ImageDescriptionOptions { is_color_data: true, ..ImageDescriptionOptions::default() };
let load_handle = Material::load_image_description(&engine, "examples/assets/atlas/icons.png", Some(options));
assert!(load_handle.is_finished());
let image_description = load_handle.get_image_description().unwrap().unwrap();
assert_eq!(image_description.mime_type.as_deref(), Some("image/png"));
assert!(image_description.is_color_data);

let missing_load_handle = Material::load_image_description(&engine, "missing_texture.png", None);
assert!(missing_load_handle.get_image_description().unwrap().is_err());
```

- `pub fn get_load_handle(&self) -> &AssetLoadHandle` (method, since 0.4.0): Byte read handle. (for handing to a scene)
  - returns &AssetLoadHandle: Byte read handle. (for handing to SceneBase::track_load_handle)
- `pub fn is_finished(&self) -> bool` (method, since 0.4.0): Whether it has finished. (loaded or failed)
  - returns bool: true if loaded or loading failed.
- `pub fn get_image_description(&self) -> Option<Result<ImageDescription, String>>` (method, since 0.4.0): Builds an image description from the loaded bytes. (None while loading, Err when loading fails. The original message is "Material image load failed: url")
  - returns Option<Result<ImageDescription, String>>: None while loading. `Some(Ok(description))` when loaded, `Some(Err("Material image load failed: path"))` when loading fails.
(the options are the ones given to load_image_description, mime_type is the response content-type, and on desktop the type detected from the content)

## ImageDescriptionLoadFuture (struct) (Clone, Debug, Future)

Future that waits for the image description load. (just await ImageDescriptionLoadHandle. The resolved value of the original loadImageDescription Promise)

Example: Await the handle inside an engine task

```rust
use vanilla::{Engine, ImageDescriptionOptions, Material};

fn load_texture_description(engine: &Engine) {
	engine.spawn_task(|mut engine_context| async move {
		let options = ImageDescriptionOptions { is_color_data: true, ..ImageDescriptionOptions::default() };
		let load_handle = engine_context.with(|engine| Material::load_image_description(engine, "examples/assets/atlas/icons.png", Some(options)));
		if let Ok(image_description) = load_handle.await {
			assert!(!image_description.bytes.is_empty());
		}
	});
}
```

## MaterialDescription (struct) (Clone, Debug)

Neutral material description. (the object made by the original createDefaultDescription, factors + images, GL independent)

Example: Change the color and roughness of the default description and add a normal map image

```rust
use vanilla::{ImageDescriptionOptions, Material};

let mut description = Material::create_default_description();
assert_eq!(description.metallic_factor, 0.0);
description.base_color_factor = [0.8, 0.6, 0.5];
description.roughness_factor = 0.7;
let bytes = std::fs::read("examples/assets/atlas/icons.png").unwrap();
description.normal_image = Some(Material::create_image_description(bytes, None, Some(ImageDescriptionOptions::default())));
assert!(description.normal_image.is_some());
assert!(description.base_color_image.is_none());
```

- `pub base_color_factor: [f64; 3]` (field, since 0.3.2): Base color factor. (linear rgb, multiplied by the texture color, default white)
  - returns [f64; 3]
- `pub metallic_factor: f64` (field, since 0.3.2): Metallic factor. (0 ~ 1, default 0)
  - returns f64
- `pub roughness_factor: f64` (field, since 0.3.2): Roughness factor. (0 ~ 1, default 1)
  - returns f64
- `pub emissive_factor: [f64; 3]` (field, since 0.3.2): Emissive factor. (linear rgb, multiplied by the emissive texture, default black)
  - returns [f64; 3]
- `pub base_color_image: Option<ImageDescription>` (field, since 0.3.2): Base color image. (1x1 white when None)
  - returns Option<ImageDescription>
- `pub normal_image: Option<ImageDescription>` (field, since 0.3.2): Normal map image. (1x1 (128, 128, 255) flat normal when None)
  - returns Option<ImageDescription>
- `pub metallic_roughness_image: Option<ImageDescription>` (field, since 0.3.2): Metallic roughness map image. (g roughness, b metallic, 1x1 white when None)
  - returns Option<ImageDescription>
- `pub glossiness_image: Option<ImageDescription>` (field, since 0.3.2): Glossiness map image. (when present, roughness is approximated through the glossiness path, 1x1 white when None)
  - returns Option<ImageDescription>
- `pub occlusion_image: Option<ImageDescription>` (field, since 0.3.2): Occlusion map image. (1x1 white when None)
  - returns Option<ImageDescription>
- `pub emissive_image: Option<ImageDescription>` (field, since 0.3.2): Emissive map image. (1x1 white when None)
  - returns Option<ImageDescription>
- `pub specular_image: Option<ImageDescription>` (field, since 0.3.2): Specular map image. (1x1 white when None)
  - returns Option<ImageDescription>
- `pub opacity_image: Option<ImageDescription>` (field, since 0.3.2): Opacity map image. (when present, alpha cutout is turned on, 1x1 white when None)
  - returns Option<ImageDescription>

## Material (struct)

Material.
- Several materials share one shader template, and apply sets the factor uniforms and texture units on that shader.

Example: Build a material from a description and apply it before drawing

```rust
use vanilla::{ImageDescriptionOptions, Material, SkinnedModelRenderer};

fn create_material(gl: &vanilla::GlContext, skinned_model_renderer: &SkinnedModelRenderer) -> Result<Material, String> {
	let mut description = Material::create_default_description();
	description.base_color_factor = [0.8, 0.6, 0.5];
	let bytes = std::fs::read("examples/assets/atlas/icons.png").map_err(|error| error.to_string())?;
	let options = ImageDescriptionOptions { is_color_data: true, ..ImageDescriptionOptions::default() };
	description.base_color_image = Some(Material::create_image_description(bytes, None, Some(options)));
	let shader_program = skinned_model_renderer.get_shader_program();
	let material = Material::create_from_description(gl, shader_program.clone(), &description)?;
	shader_program.use_program(gl);
	material.apply(gl);
	Ok(material)
}
```

- `pub fn new(shader_program: Rc<ShaderProgram>) -> Material` (constructor, since 0.3.2): Constructor. (no textures, white factor, metallic 1, roughness 1)
  - `shader_program` Rc<ShaderProgram>: Shader template to use. (what the renderer's get_shader_program returns)
  - returns Material: A material with a white factor, metallic 1, roughness 1, and all default slot textures None. (subsurface factor 1, alpha cutout off)
- `pub fn create_default_description() -> MaterialDescription` (static, since 0.3.2): Creates a default material description. (white matte non-metal)
  - returns MaterialDescription: A description with a white base, metallic 0, roughness 1, black emissive and no images.
- `pub fn create_from_description(gl: &GlContext, shader_program: Rc<ShaderProgram>, description: &MaterialDescription) -> Result<Material, String>` (static, since 0.3.2): Creates from a neutral material description. (image bytes to GL textures, error if they cannot be decoded)
  - If it fails midway, it deletes the textures made so far and returns the error.
  - `gl` &GlContext: GL context. (taken out with Graphic::get_gl)
  - `shader_program` Rc<ShaderProgram>: Shader template to use. (what the renderer's get_shader_program returns)
  - `description` &MaterialDescription: Description holding factors and images. (empty image slots become 1x1 fallback color textures)
  - returns Result<Material, String>: A material with textures built for all 8 default slots. (glossiness path when glossiness_image is present, alpha cutout when opacity_image is present)
Err(error message) if an image cannot be decoded or a texture cannot be created.
- `pub fn create_texture(gl: &GlContext, image_description: Option<&ImageDescription>, fallback_color: [u8; 4]) -> Result<GlTexture, String>` (static, since 0.3.2): Creates a texture. (image description → GL texture, 1x1 solid color fallback if none)
  - is_color_data: a color texture stored in sRGB, sampled in linear space with hardware decode (SRGB8_ALPHA8).
  - anisotropy: anisotropic filter level. (ignored if the extension is unsupported)
  - `gl` &GlContext: GL context.
  - `image_description` Option<&ImageDescription>: Image to upload. (fallback color when None, or when bytes is empty and there is no source)
  - `fallback_color` [u8; 4]: Fallback color. (RGBA bytes, built as a 1x1 texture)
  - returns Result<GlTexture, String>: New GL texture. (for images: mipmaps, LINEAR_MIPMAP_LINEAR, repeat wrap) Err(error message) if the image cannot be decoded, the pixels are fewer than width x height x 4 bytes, or the texture cannot be created.

  Example: Build an sRGB color texture when there are bytes, otherwise a white 1x1

  ```rust
  use vanilla::core::graphic::GlTexture;
  use vanilla::{ImageDescriptionOptions, Material};
  
  fn create_albedo_texture(gl: &vanilla::GlContext, bytes: Option<Vec<u8>>) -> Result<GlTexture, String> {
  	let options = ImageDescriptionOptions { is_color_data: true, anisotropy: 8.0, ..ImageDescriptionOptions::default() };
  	let image_description = bytes.map(|bytes| Material::create_image_description(bytes, None, Some(options)));
  	Material::create_texture(gl, image_description.as_ref(), [255, 255, 255, 255])
  }
  ```

- `pub fn create_image_description(bytes: Vec<u8>, mime_type: Option<String>, options: Option<ImageDescriptionOptions>) -> ImageDescription` (static, since 0.3.2): Creates an image description from bytes. (the part after fetch of the original loadImageDescription, the web passes BlobAsset bytes)
  - `bytes` Vec<u8>: Image file content. (png, jpeg, webp, gif, bmp, ico)
  - `mime_type` Option<String>: Type. (such as the response content-type, not used for decoding, None when unknown)
  - `options` Option<ImageDescriptionOptions>: Flip, color data and anisotropy options. (all off and 0 when None)
  - returns ImageDescription: An image description without source. (not decoded here, create_texture decodes it)
- `pub fn load_image_description(engine: &Engine, url: &str, options: Option<ImageDescriptionOptions>) -> ImageDescriptionLoadHandle` (static, since 0.3.2): Requests an image description load from an asset path (URL on the web). (the original static loadImageDescription, once loaded the handle's get_image_description builds it)
  - `engine` &Engine: Engine to load the asset with.
  - `url` &str: Asset path. (relative to the asset folder candidates on desktop, an address relative to asset_base_url on the web, data: addresses also work)
  - `options` Option<ImageDescriptionOptions>: Description options. (all off and 0 when None)
  - returns ImageDescriptionLoadHandle: Load handle. (on desktop it is read on the spot and already finished, on the web it finishes when fetch finishes, get the description with get_image_description or await)

  Example: Request in the scene's load and take the description out in initialize after loading

  ```rust
  use vanilla::{Engine, ImageDescriptionLoadHandle, ImageDescriptionOptions, Material, Scene, SceneBase};
  
  struct TextureScene {
  	scene_base: SceneBase,
  	load_handle: Option<ImageDescriptionLoadHandle>,
  }
  
  impl Scene for TextureScene {
  	fn get_scene_base(&self) -> &SceneBase {
  		&self.scene_base
  	}
  
  	fn get_scene_base_mut(&mut self) -> &mut SceneBase {
  		&mut self.scene_base
  	}
  
  	fn load(&mut self, engine: &Engine) {
  		let options = ImageDescriptionOptions { is_color_data: true, ..ImageDescriptionOptions::default() };
  		let load_handle = Material::load_image_description(engine, "examples/assets/atlas/icons.png", Some(options));
  		self.scene_base.track_load_handle(load_handle.get_load_handle());
  		self.load_handle = Some(load_handle);
  	}
  
  	fn initialize(&mut self, _engine: &Engine) {
  		if let Some(Some(Ok(image_description))) = self.load_handle.as_ref().map(|load_handle| load_handle.get_image_description()) {
  			assert!(!image_description.bytes.is_empty());
  		}
  	}
  }
  ```

- `pub fn set_texture(&self, uniform_name: &str, texture_unit: u32, texture: Option<GlTexture>)` (method, since 0.3.2): Sets an extra texture. (a slot specific to the shader template, uniform name / texture unit outside the default slots)
  - Unit 1 is reserved for the shadow map and 0 / 2~8 are default slots, so use 9 or above. The same name keeps its position and only its value changes.
  - `uniform_name` &str: Name of the shader's sampler uniform.
  - `texture_unit` u32: Texture unit. (9 or above)
  - `texture` Option<GlTexture>: Texture to bind. (when None, the unit is bound empty, deleting is up to the side that set it)

  Example: Set a gray 1x1 texture on the height detail slot of the skin shader

  ```rust
  use vanilla::{Material, SKIN_TEXTURE_UNIT_DETAILHEIGHT};
  
  fn attach_detail_height(gl: &vanilla::GlContext, material: &Material) -> Result<(), String> {
  	let detail_height_texture = Material::create_texture(gl, None, [128, 128, 128, 255])?;
  	material.set_texture("detailHeightTexture", SKIN_TEXTURE_UNIT_DETAILHEIGHT, Some(detail_height_texture));
  	Ok(())
  }
  ```

- `pub fn apply(&self, gl: &GlContext)` (method, since 0.3.2): Apply. (sets uniforms on the referenced shader + binds texture units)
  - Uniforms go to the program currently in use, so call use_program on the referenced shader first. TEXTURE0 is active afterward.
  - `gl` &GlContext: GL context.
- `pub fn get_shader_program(&self) -> &Rc<ShaderProgram>` (method, since 0.3.2): Returns the referenced shader program. (the material template's shader)
  - returns &Rc<ShaderProgram>: Referenced shader program. (shared with the renderer)
- `pub fn get_base_color_factor(&self) -> [f64; 3]` (method, since 0.3.2): Returns the base color factor.
  - returns [f64; 3]: Base color factor. (linear rgb)
- `pub fn set_base_color_factor(&self, base_color_factor: [f64; 3])` (method, since 0.4.0): Set the base color factor. (linear rgb multiplier; on a shared material every model using it changes)
  - `base_color_factor` [f64; 3]: Base color factor. (linear rgb)

  Example: Tint only the material copy red

  ```rust
  use std::rc::Rc;
  use vanilla::{Material, ShaderProgram};
  
  fn tint_instance(shared_material: &Rc<Material>) -> Material {
  	let instance_material = shared_material.create_instance();
  	instance_material.set_base_color_factor([1.0, 0.4, 0.4]);
  	instance_material
  }
  
  fn check(shader_program: Rc<ShaderProgram>) {
  	let shared_material = Rc::new(Material::new(shader_program));
  	let instance_material = tint_instance(&shared_material);
  	assert_eq!(shared_material.get_base_color_factor(), [1.0, 1.0, 1.0]);
  	assert_eq!(instance_material.get_base_color_factor(), [1.0, 0.4, 0.4]);
  }
  let _ = check;
  ```

- `pub fn create_instance(&self) -> Material` (method, since 0.4.0): Create a material copy. (like Unity's material and sharedMaterial, only the values fork and the textures are borrowed from the original)
  - Copies the factors, flags, default slot textures and extra textures added with set_texture. No GPU texture is uploaded again.
  - The copy's destroy does not delete the borrowed textures. Finish using the copies before destroying the original (the material that created the textures).
  - returns Material: Copy that uses the same shader and textures with values that can change separately. (texture byte count 0)
- `pub fn get_texture_byte_count(&self) -> usize` (method, since 0.4.0): Return the texture byte count. (GPU bytes of the default slot textures this material created, including mipmaps; 0 for a copy)
  - returns usize: GPU texture byte count. (counted as RGBA8, a solid 1x1 is 4)
- `pub fn get_metallic_factor(&self) -> f64` (method, since 0.3.2): Returns the metallic factor.
  - returns f64: Metallic factor.
- `pub fn get_roughness_factor(&self) -> f64` (method, since 0.3.2): Returns the roughness factor.
  - returns f64: Roughness factor.
- `pub fn get_emissive_factor(&self) -> [f64; 3]` (method, since 0.3.2): Returns the emissive factor.
  - returns [f64; 3]: Emissive factor. (linear rgb)
- `pub fn get_use_glossiness(&self) -> bool` (method, since 0.3.2): Returns whether the glossiness path is used.
  - returns bool: true if roughness is approximated with the glossiness map. (when the description had glossiness_image)
- `pub fn set_subsurface_factor(&self, subsurface_factor: f64)` (method, since 0.3.2): Sets the subsurface factor. (screen-space scattering mask multiplier of the skin shader, 0 for non-scattering parts like eyes / teeth)
  - `subsurface_factor` f64: Scattering mask multiplier. (default 1, no scattering at 0)
- `pub fn get_subsurface_factor(&self) -> f64` (method, since 0.3.2): Returns the subsurface factor.
  - returns f64: Subsurface factor. (default 1)
- `pub fn set_use_alpha_cutout(&self, use_alpha_cutout: bool)` (method, since 0.3.2): Sets whether alpha cutout is used. (for materials with an opacity texture attached later)
  - `use_alpha_cutout` bool: If true, transparent areas are cut out with the opacity texture.
- `pub fn get_use_alpha_cutout(&self) -> bool` (method, since 0.3.2): Returns whether alpha cutout is used. (when it has an opacity map, hair/eyelashes etc.)
  - returns bool: true if alpha cutout is used.
- `pub fn get_texture_bindings(&self) -> Vec<(String, u32, Option<GlTexture>)>` (method, since 0.3.2): Returns the texture binding list. (uniform name / texture unit / GL texture, extra slots after the 8 default slots)
  - returns Vec<(String, u32, Option<GlTexture>)>: (uniform name, texture unit, texture) list. (the 8 default slots, then the extra slots set with set_texture in the order they were set)
- `pub fn destroy(&self, gl: &GlContext)` (method, since 0.3.2): Destroy. (frees the default slot textures, extra slot textures are deleted by the side that set them)
  - `gl` &GlContext: GL context used at creation.

## Functions and constants

- `pub const TEXTURE_UNIT_BASECOLOR: u32 = 0` (field, since 0.3.2): Texture unit layout. (unit 1 is reserved for the SkinnedModel shadow map, do not use)
  - returns u32
- `pub const TEXTURE_UNIT_SHADOWMAP: u32 = 1` (field, since 0.3.2): Shadow map unit. (SkinnedModel renderer only, materials do not use it)
  - returns u32
- `pub const TEXTURE_UNIT_NORMAL: u32 = 2` (field, since 0.3.2): Normal map unit. (uniform normalTexture)
  - returns u32
- `pub const TEXTURE_UNIT_METALLICROUGHNESS: u32 = 3` (field, since 0.3.2): Metallic roughness map unit. (uniform metallicRoughnessTexture)
  - returns u32
- `pub const TEXTURE_UNIT_GLOSSINESS: u32 = 4` (field, since 0.3.2): Glossiness map unit. (uniform glossinessTexture, FBX specular/gloss path)
  - returns u32
- `pub const TEXTURE_UNIT_OCCLUSION: u32 = 5` (field, since 0.3.2): Occlusion map unit. (uniform occlusionTexture)
  - returns u32
- `pub const TEXTURE_UNIT_EMISSIVE: u32 = 6` (field, since 0.3.2): Emissive map unit. (uniform emissiveTexture)
  - returns u32
- `pub const TEXTURE_UNIT_SPECULAR: u32 = 7` (field, since 0.3.2): Specular map unit. (uniform specularTexture)
  - returns u32
- `pub const TEXTURE_UNIT_OPACITY: u32 = 8` (field, since 0.3.2): Opacity map unit. (uniform opacityTexture, alpha cutout)
  - returns u32
- `pub fn decode_image_bytes(bytes: &[u8]) -> Result<(u32, u32, Vec<u8>), String>` (method, since 0.3.2): Decodes image bytes. (png / jpeg / webp → width, height, straight alpha RGBA)
  - `bytes` &[u8]: Image file content. (the format is detected from the content)
  - returns Result<(u32, u32, Vec<u8>), String>: (width, height, straight alpha RGBA bytes). Err("Material: image decode failed: reason") if it cannot be decoded.

  Example: Decode a png file and bytes that cannot be decoded

  ```rust
  use vanilla::graphics3d::material::decode_image_bytes;
  
  let bytes = std::fs::read("examples/assets/atlas/icons.png").unwrap();
  let (width, height, pixels) = decode_image_bytes(&bytes).unwrap();
  assert_eq!((width, height), (128, 128));
  assert_eq!(pixels.len(), 128 * 128 * 4);
  assert!(decode_image_bytes(&[1, 2, 3]).is_err());
  ```

- `pub fn flip_pixel_rows(pixels: &mut [u8], width: usize, height: usize)` (method, since 0.3.2): Flips pixel rows vertically. (the original createImageBitmap imageOrientation: "flip_y")
  - `pixels` &mut [u8]: RGBA bytes. (changed in place, panics if shorter than width x height x 4 bytes)
  - `width` usize: Width in pixels.
  - `height` usize: Height in pixels.

  Example: Swap the top and bottom rows of a 1 x 2 image

  ```rust
  use vanilla::graphics3d::material::flip_pixel_rows;
  
  let mut pixels = vec![255, 0, 0, 255, 0, 0, 255, 255];
  flip_pixel_rows(&mut pixels, 1, 2);
  assert_eq!(pixels, vec![0, 0, 255, 255, 255, 0, 0, 255]);
  ```

