# graphics3d/skinnedmodelrenderer (vanilla-engine 0.4.0)

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

Skinned model renderer. (the original graphics3d/skinnedmodelrenderer.js)
- Owns the skinning PBR shader template + environment state (shadow map / sun / fog), one per scene. SkinnedModel holds only data/pose,
  and this object does the rendering, taking a model instance.
- Injecting fragment shader source lets you build another shading template on the same skinning/morph vertex path.
  (a derived renderer sets its own uniforms after using the shader and calls draw())
- The GLSL is the same as the original. (Cook-Torrance GGX, screen space derivative cotangent normal map, 3x3 PCF shadow, hemisphere ambient, distance fog)
  ${MORPH_GLSL} / ${MORPH_TARGET_MAXIMUM} in the original template string are ported as concat! and the number 96. (a test checks that the two match)
- Texture units: 0 = base_color, 1 = shadow map, 2 ~ 8 = material slots, 15 = morph target texture.
  Without a shadow map, a 1x1 comparison depth texture is bound to the shadow unit. (same as the original)
- Differences from the original:
  - Draw functions take gl and &mut SkinnedModel. Uploading changed morph targets (step 6 of the original update) and wireframe indices
    is done here first. Matrix arguments are &[f64; 16] like the original getElements(). (matrix.get_elements())
  - set_shadow_map copies 16 values instead of holding the array by reference like the original.
  - Creation returns shader compile failure as an error (Result).

## SkinnedModelRenderer (struct)

Skinned model renderer.

Example: Build a renderer, set the sun and fog, then draw one model

```rust
use vanilla::{Graphic, Matrix4, SkinnedModel, SkinnedModelRenderer, Vector3};

fn create_renderer(graphic: &Graphic) -> Result<SkinnedModelRenderer, String> {
	let mut skinned_model_renderer = SkinnedModelRenderer::new(graphic.get_gl(), None, None)?;
	let sun_direction = Vector3::create(0.5, 0.8, 0.35).normalize();
	skinned_model_renderer.set_sun_direction(sun_direction.x, sun_direction.y, sun_direction.z);
	skinned_model_renderer.set_fog_color(0.62, 0.72, 0.86);
	skinned_model_renderer.set_fog_range(25.0, 80.0);
	Ok(skinned_model_renderer)
}

fn draw_model(graphic: &mut Graphic, skinned_model_renderer: &SkinnedModelRenderer, skinned_model: &mut SkinnedModel) {
	graphic.flush_batch();
	let aspect_ratio = graphic.get_drawing_buffer_width() as f64 / graphic.get_drawing_buffer_height().max(1) as f64;
	let camera_position = Vector3::create(0.0, 1.6, 4.0);
	let mut view_projection_matrix = Matrix4::create_perspective(std::f64::consts::PI / 3.0, aspect_ratio, 0.1, 100.0);
	view_projection_matrix.multiply(&Matrix4::create_look_at(camera_position, Vector3::create(0.0, 1.0, 0.0), Vector3::up()));
	let model_matrix = Matrix4::create_identity();
	let gl = graphic.get_gl();
	unsafe {
		gl.enable(glow::DEPTH_TEST);
		gl.clear(glow::DEPTH_BUFFER_BIT);
	}
	skinned_model_renderer.draw(gl, skinned_model, view_projection_matrix.get_elements(), model_matrix.get_elements(), camera_position.x, camera_position.y, camera_position.z);
	graphic.restore_render_state();
}
```

- `pub fn new(gl: &GlContext, fragment_shader_source: Option<&str>, vertex_shader_source: Option<&str>) -> Result<SkinnedModelRenderer, String>` (constructor, since 0.3.2): Constructor. (replacement fragment / vertex shader source, default PBR / default skinning when None)
  - A replacement vertex shader must follow the same attribute location / output conventions.
  - `gl` &GlContext: GL context.
  - `fragment_shader_source` Option<&str>: Replacement fragment shader source. (GLSL ES 3.0, None uses the default PBR)
  - `vertex_shader_source` Option<&str>: Replacement vertex shader source. (None uses the default skinning)
  - returns Result<SkinnedModelRenderer, String>: A new renderer. (shadow strength 0, sun direction (0, 1, 0), fog color (0.8, 0.85, 0.92), fog distance 55 ~ 250) Err if shader compilation or linking, or creating the empty shadow texture fails.

  Example: Plug flat color shading into the default skinning vertex path

  ```rust
  use vanilla::SkinnedModelRenderer;
  
  const FLAT_FRAGMENTSHADER_SOURCE: &str = "#version 300 es
  precision highp float;
  out vec4 outputColor;
  void main() {
  	outputColor = vec4(1.0, 0.5, 0.2, 1.0);
  }";
  
  fn create_flat_renderer(gl: &vanilla::GlContext) -> Result<SkinnedModelRenderer, String> {
  	SkinnedModelRenderer::new(gl, Some(FLAT_FRAGMENTSHADER_SOURCE), None)
  }
  ```

- `pub fn upload_joint_matrices(&self, gl: &GlContext, joint_matrix_array: &[f32])` (method, since 0.4.0): Upload joint matrices. (JointBlock uniform block; ShaderProgram binds the program to the same binding point after linking; original uploadJointMatrices)
  - `gl` &GlContext: GL context.
  - `joint_matrix_array` &[f32]: Number of joint matrices. (a multiple of 16)
- `pub fn draw(&self, gl: &GlContext, skinned_model: &mut SkinnedModel, view_projection_elements: &[f32; 16], model_matrix_elements: &[f32; 16], camera_x: f64, camera_y: f64, camera_z: f64)` (method, since 0.3.2): Draw. (iterates the model instance's drawables, applies materials + uploads joint matrices)
  - Depth test / culling / blend / framebuffer are set by the caller. (same as the original)
  - `gl` &GlContext: GL context.
  - `skinned_model` &mut SkinnedModel: Model to draw. (changed morph targets are uploaded first)
  - `view_projection_elements` &[f32; 16]: View x projection matrix. (16 column-major values, matrix.get_elements())
  - `model_matrix_elements` &[f32; 16]: Model matrix. (16 column-major values)
  - `camera_x` f64: Camera world X. (used for specular reflection and fog distance)
  - `camera_y` f64: Camera world Y.
  - `camera_z` f64: Camera world Z.
- `pub fn draw_depth(&self, gl: &GlContext, skinned_model: &mut SkinnedModel, light_view_projection_elements: &[f32; 16], model_matrix_elements: &[f32; 16])` (method, since 0.3.2): Draws the depth pass. (shadow map casting, call after ShadowMap.begin_render())
  - `gl` &GlContext: GL context.
  - `skinned_model` &mut SkinnedModel: Model that casts the shadow. (uploads changed morph targets first)
  - `light_view_projection_elements` &[f32; 16]: Light view x projection matrix. (16 column-major values, ShadowMap::get_light_view_projection_matrix)
  - `model_matrix_elements` &[f32; 16]: Model matrix. (16 column-major values)

  Example: Draw depth into the shadow map and receive shadows in the screen pass

  ```rust
  use vanilla::{Matrix4, ShadowMap, SkinnedModel, SkinnedModelRenderer, Vector3};
  
  fn draw_with_shadow(gl: &vanilla::GlContext, skinned_model_renderer: &mut SkinnedModelRenderer, shadow_map: &mut ShadowMap, skinned_model: &mut SkinnedModel, view_projection_matrix: &Matrix4, camera_position: Vector3, drawing_buffer_width: i32, drawing_buffer_height: i32) {
  	let model_matrix = Matrix4::create_identity();
  	let sun_direction = Vector3::create(0.5, 0.8, 0.35).normalize();
  	shadow_map.update_light_matrix(Vector3::zero(), sun_direction.multiply_scalar(-1.0), 4.0, 0.5, 30.0);
  	let light_view_projection_elements = *shadow_map.get_light_view_projection_matrix().get_elements();
  	shadow_map.begin_render(gl);
  	skinned_model_renderer.draw_depth(gl, skinned_model, &light_view_projection_elements, model_matrix.get_elements());
  	skinned_model_renderer.set_shadow_map(Some(shadow_map.get_depth_texture()), Some(&light_view_projection_elements), 1.0 / shadow_map.get_resolution() as f64);
  	skinned_model_renderer.set_shadow_strength(1.0);
  	skinned_model_renderer.set_sun_direction(sun_direction.x, sun_direction.y, sun_direction.z);
  	unsafe {
  		gl.bind_framebuffer(glow::FRAMEBUFFER, None);
  		gl.viewport(0, 0, drawing_buffer_width, drawing_buffer_height);
  		gl.clear(glow::DEPTH_BUFFER_BIT);
  	}
  	skinned_model_renderer.draw(gl, skinned_model, view_projection_matrix.get_elements(), model_matrix.get_elements(), camera_position.x, camera_position.y, camera_position.z);
  }
  ```

- `pub fn draw_wireframe(&self, gl: &GlContext, skinned_model: &mut SkinnedModel, view_projection_elements: &[f32; 16], model_matrix_elements: &[f32; 16], red: f64, green: f64, blue: f64, alpha: f64)` (method, since 0.3.2): Draws the wireframe. (edge lines, reflects morph / skinning, the caller sets blend / depth state)
  - Temporarily swaps the drawable vertex array's element buffer to line indices, draws, and restores the original indices.
  - `gl` &GlContext: GL context.
  - `skinned_model` &mut SkinnedModel: Model to draw. (drawables without line indices are uploaded here first)
  - `view_projection_elements` &[f32; 16]: View x projection matrix. (16 column-major values)
  - `model_matrix_elements` &[f32; 16]: Model matrix. (16 column-major values)
  - `red` f64: Line color red. (0 ~ 1)
  - `green` f64: Line color green. (0 ~ 1)
  - `blue` f64: Line color blue. (0 ~ 1)
  - `alpha` f64: Line opacity. (0 ~ 1, blending must be on for translucency)
- `pub fn apply_morph_uniforms(&self, gl: &GlContext, shader_program: &ShaderProgram, drawable: &Drawable)` (method, since 0.3.2): Applies morph uniforms. (drawable's morph texture/weights, disabled with count 0 if there are no targets)
  - `gl` &GlContext: GL context.
  - `shader_program` &ShaderProgram: Shader to set the uniforms on. (the program currently in use)
  - `drawable` &Drawable: Drawable to read the morph state from.
- `pub fn set_shadow_map(&mut self, shadow_map_texture: Option<GlTexture>, light_view_projection_elements: Option<&[f32; 16]>, texel_size: f64)` (method, since 0.3.2): Sets the shadow map. (receives shadows in the main pass, the matrix is copied)
  - `shadow_map_texture` Option<GlTexture>: Shadow map depth texture. (None means no shadows are received)
  - `light_view_projection_elements` Option<&[f32; 16]>: Light view x projection matrix. (the 16 values are copied, None means no shadows are received)
  - `texel_size` f64: Shadow map texel size. (1 / resolution, PCF sample spacing, default 1 / 2048)
- `pub fn set_shadow_strength(&mut self, shadow_strength: f64)` (method, since 0.3.2): Sets the shadow strength. (0 = no receiving)
  - `shadow_strength` f64: Shadow strength. (0 ~ 1, 0 means no shadows are received, default 0)
- `pub fn set_sun_direction(&mut self, x: f64, y: f64, z: f64)` (method, since 0.3.2): Sets the sun direction.
  - `x` f64: Direction X pointing toward the sun. (normalized by the shader, default (0, 1, 0))
  - `y` f64: Direction Y.
  - `z` f64: Direction Z.
- `pub fn set_fog_color(&mut self, red: f64, green: f64, blue: f64)` (method, since 0.3.2): Sets the fog color.
  - `red` f64: Red. (0 ~ 1)
  - `green` f64: Green. (0 ~ 1)
  - `blue` f64: Blue. (0 ~ 1)
- `pub fn set_fog_range(&mut self, start_distance: f64, end_distance: f64)` (method, since 0.3.2): Sets the fog distance range.
  - `start_distance` f64: Camera distance where fog begins. (world units, default 55)
  - `end_distance` f64: Camera distance at which fog covers fully. (world units, default 250, smoothstep in between)
- `pub fn get_empty_shadow_texture(&self) -> GlTexture` (method, since 0.4.0): Returns the empty shadow texture. (1x1 comparison depth texture bound to the shadow unit when not receiving shadows, shared by derived renderers)
  - returns GlTexture: 1x1 comparison depth texture. (held by the renderer, so do not delete it)
- `pub fn get_shader_program(&self) -> Rc<ShaderProgram>` (method, since 0.3.2): Returns the shader program. (the skinning PBR template, shared by models and materials)
  - returns Rc<ShaderProgram>: Shader program. (returns a clone of the Rc)
- `pub fn get_depth_shader_program(&self) -> &ShaderProgram` (method, since 0.3.2): Returns the depth shader program.
  - returns &ShaderProgram: Depth pass shader program. (used by draw_depth)
- `pub fn get_wireframe_shader_program(&self) -> &ShaderProgram` (method, since 0.3.2): Returns the wireframe shader program.
  - returns &ShaderProgram: Wireframe shader program. (used by draw_wireframe)

## Functions and constants

- `pub const MORPH_TEXTURE_UNIT: u32 = 15` (field, since 0.3.2): Morph target texture unit. (a value that does not overlap material slots 0 / 2~8, shadow map 1, or extra slots 9~)
  - returns u32
- `pub const MORPH_GLSL: &str = morphGlslSource!()` (field, since 0.3.2): Morph target GLSL. (the original MORPH_GLSL, derived renderers put it into their replacement vertex shaders)
  - returns &str
- `pub const SKINNED_VERTEXSHADER_SOURCE: &str` (field, since 0.3.2): Skinning vertex shader. (morph targets → weighted blend of 4 joints, fixed attribute locations)
  - returns &str
- `pub const SKINNED_FRAGMENTSHADER_SOURCE: &str` (field, since 0.3.2): Skinning fragment shader. (metallic-roughness PBR + sun/hemisphere lighting + shadow map + distance fog)
  - Normal mapping uses a cotangent frame based on screen-space derivatives. (no tangent attribute needed)
  - FBX specular/gloss path: when use_glossiness=1, roughness = 1 - gloss, and the specular map modulates F0.
  - returns &str
