Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
GLSL fragment shader which renders a portion of a given sprite sheet
module SpriteSheet exposing (..)
import Math.Vector2 exposing (Vec2, vec2)
import WebGL exposing (Texture, Shader)
{-|
Render a portion of a sprite sheet.
-}
fragmentSpriteSheet : Shader {} { u | spriteSheet : Texture, spriteSheetSize: Vec2, spriteSize: Vec2, index : Float } { vcoord : Vec2 }
fragmentSpriteSheet =
[glsl|
precision mediump float;
uniform sampler2D spriteSheet;
uniform vec2 spriteSheetSize; // In px
uniform vec2 spriteSize; // In px
uniform float index; // Sprite index in sprite sheet (0-...)
varying vec2 vcoord;
void main () {
float w = spriteSheetSize.x;
float h = spriteSheetSize.y;
// Normalize sprite size (0.0-1.0)
float dx = spriteSize.x / w;
float dy = spriteSize.y / h;
// Figure out number of tile cols of sprite sheet
float cols = w / spriteSize.x;
// From linear index to row/col pair
float col = mod(index, cols);
float row = floor(index / cols);
// Finally to UV texture coordinates
vec2 uv = vec2(dx * vcoord.x + col * dx, 1.0 - dy - row * dy + dy * vcoord.y);
gl_FragColor = texture2D(spriteSheet, uv);
}
|]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment