An Introduction to Elm-WebGL

  

Andrey Kuzmin @unsoundscapes

elm—(street-404, mogee, slice-show)

History

Why WebGL?

Familiar high-level API

WebGL.toHtml
  [ width 400
  , height 400
  , style
      [ ( "display"
        , "block"
        )
      ]
  ]
  [ renderable1
  , renderable2
  ]

Rendering Pipeline

Example: Rotating RGB Triangle

Code: Mesh

type alias Attribute = { position : Vec3, color : Vec3 }


triangle : Drawable Attribute
triangle =
  Triangle
    [ ( Attribute (vec3 0 1 0) (vec3 1 0 0)
      , Attribute (vec3 -1 -1 0) (vec3 0 1 0)
      , Attribute (vec3 1 -1 0) (vec3 0 0 1)
      )
    ]

Code: Vertex Shader

type alias Attribute = { position : Vec3, color : Vec3 }
type alias Uniform = { rotation : Mat4 }
type alias Varying = { vColor : Vec3 }

vertexShader : Shader Attribute Uniform Varying
vertexShader = [glsl|
  attribute vec3 position;
  attribute vec3 color;
  varying vec3 vColor;
  uniform mat4 rotation;
  void main () {
    gl_Position = rotation * vec4(position, 1.0);
    vColor = color;
  }
|]

Code: Fragment Shader

type alias Uniform = { rotation : Mat4 }
type alias Varying = { vColor : Vec3 }

fragmentShader : Shader {} Uniform Varying
fragmentShader = [glsl|
  precision mediump float;
  varying vec3 vColor;
  void main () {
    gl_FragColor = vec4(vColor, 1.0);
  }
|]

Code: Render

view : Model -> Html a
view angle =
  WebGL.toHtml
    [ width 300
    , height 300
    , style [("display", "block")]
    ]
    [ WebGL.render
        vertexShader
        fragmentShader
        triangle
        { rotation = makeRotate angle (vec3 0 1 0) }
    ]

Elm-linear-algebra

  • Fast because of native JavaScript arrays (Float32Array)
  • Provides Vec2, Vec3, Vec4 and Mat4 types
  • Implements many useful functions for 3D Graphics
  • Powers elm-webgl

More Examples

github.com/elm-community/elm-webgl

github.com/w0rm/elm-webgl-playground

Games using Elm-WebGL

Into The Heavens

Elm Street 404

Mogee

Thank you!