# core/shaderprogram (vanilla-engine 0.4.0)

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

Shader program.
- The original is GLSL ES 3.00 (#version 300 es). To run on desktop GL 3.3 core, only the header is changed to #version 330 core before compiling.
  (precision qualifiers are accepted without meaning since GLSL 1.30, so the body is left as is)
- Uniform / attribute locations are read and cached on the first query.

## ShaderProgram (struct)

Shader program. (a GL program linking vertex and fragment shaders, with a cache of uniform and attribute locations)
- Sources are written in GLSL ES 3.00. On desktop only the header is changed to #version 330 core before compiling.
- Does not hold the GL context and takes it per function. (Graphic's get_gl)

Example: Create a solid color program and upload uniforms

```rust
use vanilla::{Graphic, ShaderProgram};

const VERTEX_SHADER_SOURCE: &str = "#version 300 es
in vec2 vertexPosition;
void main() {
	gl_Position = vec4(vertexPosition, 0.0, 1.0);
}
";

const FRAGMENT_SHADER_SOURCE: &str = "#version 300 es
precision highp float;
uniform vec4 mainColor;
out vec4 outputColor;
void main() {
	outputColor = mainColor;
}
";

fn create_program(graphic: &Graphic) -> Result<ShaderProgram, String> {
	let gl = graphic.get_gl();
	let shader_program = ShaderProgram::create_with_attribute_locations(gl, VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE, &[("vertexPosition", 0)])?;
	shader_program.use_program(gl);
	let main_color_location = shader_program.get_uniform_location(gl, "mainColor");
	unsafe {
		gl.uniform_4_f32(main_color_location.as_ref(), 1.0, 0.5, 0.0, 1.0);
	}
	assert_eq!(shader_program.get_attribute_location(gl, "vertexPosition"), Some(0));
	Ok(shader_program)
}
```

- `pub fn new(gl: &GlContext, vertex_shader_source: &str, fragment_shader_source: &str) -> Result<ShaderProgram, String>` (constructor, since 0.3.2): Creates. (an error holding the log on compile / link failure, the shaders and programs built until then are deleted)
  - `gl` &GlContext: GL context. (get_gl of Graphic)
  - `vertex_shader_source` &str: Vertex shader source. (GLSL ES 3.00)
  - `fragment_shader_source` &str: Fragment shader source. (GLSL ES 3.00)
  - returns Result<ShaderProgram, String>: The linked program. Err with the info log if shader compilation or program linking fails, Err with the error text if a GL object cannot be created.
- `pub fn create_with_attribute_locations(gl: &GlContext, vertex_shader_source: &str, fragment_shader_source: &str, attribute_location_list: &[(&str, u32)]) -> Result<ShaderProgram, String>` (static, since 0.3.2): Creates with attribute locations fixed before linking. (the original constructor's attributeLocationTable argument, for sharing another program's vertex array)
  - `gl` &GlContext: GL context.
  - `vertex_shader_source` &str: Vertex shader source. (GLSL ES 3.00)
  - `fragment_shader_source` &str: Fragment shader source. (GLSL ES 3.00)
  - `attribute_location_list` &[(&str, u32)]: List of (attribute name, location). (bound with bind_attrib_location before linking, same as new if empty)
  - returns Result<ShaderProgram, String>: The linked program. Err with the info log if shader compilation or program linking fails, Err with the error text if a GL object cannot be created.
- `pub fn create_deferred(gl: &GlContext, vertex_shader_source: &str, fragment_shader_source: &str, attribute_location_list: &[(&str, u32)]) -> Result<ShaderProgram, String>` (static, since 0.4.0): Creation that only hands off compiling and linking without checking the result. (The original constructor's isDeferred; finish_build must be called before use)
  - With KHR_parallel_shader_compile the driver builds in the background and is_build_complete can poll completion without blocking the main thread.
  - `gl` &GlContext: GL context.
  - `vertex_shader_source` &str: Vertex shader source. (GLSL ES 3.00)
  - `fragment_shader_source` &str: Fragment shader source. (GLSL ES 3.00)
  - `attribute_location_list` &[(&str, u32)]: List of (attribute name, location). (Bound before linking)
  - returns Result<ShaderProgram, String>: The handed-off program. A compile or link error is reported by finish_build. Err with the error text if a GL object cannot be created.

  Example: Handing off the build and finishing it when done

  ```rust
  use vanilla::{Graphic, ShaderProgram};
  
  const VERTEX_SHADER_SOURCE: &str = "#version 300 es
  in vec2 vertexPosition;
  void main() {
  	gl_Position = vec4(vertexPosition, 0.0, 1.0);
  }
  ";
  
  const FRAGMENT_SHADER_SOURCE: &str = "#version 300 es
  precision highp float;
  out vec4 outputColor;
  void main() {
  	outputColor = vec4(1.0);
  }
  ";
  
  fn build(graphic: &Graphic) -> Result<ShaderProgram, String> {
  	let gl = graphic.get_gl();
  	let shader_program = ShaderProgram::create_deferred(gl, VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE, &[("vertexPosition", 0)])?;
  	assert!(shader_program.is_deferred());
  	// Finish it once it is done. (finish_build waits until done if it is not)
  	if shader_program.is_build_complete(gl) {
  		shader_program.finish_build(gl)?;
  	}
  	Ok(shader_program)
  }
  ```

- `pub fn is_parallel_compile_supported(gl: &GlContext) -> bool` (static, since 0.4.0): Whether the parallel shader compile extension exists. (The original isParallelCompileSupported, KHR_parallel_shader_compile; the web uses the same extension)
  - `gl` &GlContext: GL context.
  - returns bool: True if present. (If present, compiling and linking can be handed off and completion polled without blocking the main thread)
- `pub fn is_deferred(&self) -> bool` (method, since 0.4.0): Whether the build is handed off and not yet finished. (True if built with create_deferred and finish_build has not been called yet)
  - returns bool: True if the building handed off is not finished yet.
- `pub fn is_build_complete(&self, gl: &GlContext) -> bool` (method, since 0.4.0): Whether the handed-off build is done. (The original isBuildComplete; true if nothing was handed off or it is already finished, or if the extension is missing; it only asks and never blocks)
  - `gl` &GlContext: GL context that created the program.
  - returns bool: True if done. (Even when true, call finish_build to check the result before use)
- `pub fn finish_build(&self, gl: &GlContext) -> Result<(), String>` (method, since 0.4.0): Finishes the handed-off build. (The original finishBuild; checks the compile and link results and waits until done if not; does nothing if nothing was handed off or it is already finished)
  - On failure, deletes the shaders and program and returns an Err with the info log. (Same message as the constructor)
  - `gl` &GlContext: GL context that created the program.
  - returns Result<(), String>: Ok on success. Err if compiling or linking failed.
- `pub fn use_program(&self, gl: &GlContext)` (method, since 0.3.2): Use. (original useProgram, not set on GL again when the state cache remembers this program is already in use)
  - `gl` &GlContext: GL context that created the program.
- `pub fn get_uniform_location(&self, gl: &GlContext, name: &str) -> Option<crate::core::graphic::GlUniformLocation>` (method, since 0.3.2): Returns the uniform location.
  Uses clone because of the web version. (on desktop it is Copy, so clippy objects)
  - `gl` &GlContext: GL context that created the program.
  - `name` &str: Uniform name. (exactly as named in the shader source)
  - returns Option<crate::core::graphic::GlUniformLocation>: Uniform location. None if there is no active uniform with that name. (read on the first query, and even its absence is cached)
- `pub fn get_attribute_location(&self, gl: &GlContext, name: &str) -> Option<u32>` (method, since 0.3.2): Returns the attribute location.
  - `gl` &GlContext: GL context that created the program.
  - `name` &str: Attribute name. (as named in the shader source)
  - returns Option<u32>: Attribute location. None if there is no active attribute with that name. (read and cached on the first query)
- `pub fn get_program(&self) -> crate::core::graphic::GlProgram` (method, since 0.3.2): Returns the GL program.
  - returns crate::core::graphic::GlProgram: The linked GL program object.

## Functions and constants

- `pub const JOINT_BLOCK_NAME: &str = "JointBlock"` (field, since 0.4.0): Name of the joint matrix uniform block fixed by the engine. (if a linked program has a block with this name, it is bound to the JOINT_BLOCK_BINDING point; original JOINT_BLOCK_NAME)
  - Large arrays such as joint matrices do not fit the default-block uniform limit (the minimum of 256 slots that WebGL2 guarantees), so they are passed through a uniform block.
    (toon material block 0, outline block 1 and frame block 2 are bound separately by the toon renderer)
  - returns &str
- `pub const JOINT_BLOCK_BINDING: u32 = 3` (field, since 0.4.0): Binding point of the joint matrix uniform block. (original JOINT_BLOCK_BINDING)
  - returns u32
