Skip to content

Instantly share code, notes, and snippets.

@passiomatic
Created April 2, 2017 19:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save passiomatic/4e108740db98eea5d2e6873267271f37 to your computer and use it in GitHub Desktop.
Save passiomatic/4e108740db98eea5d2e6873267271f37 to your computer and use it in GitHub Desktop.
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