Moving Vertices

3D graphics hardware works by rendering triangles to the screen. In 2D graphics, a rectangular region on the screen is made up of two triangles, known as a quad. At the corners of those triangles are the vertices. A quad has four vertices (a, b, c, and d) that the two triangles share, as follows:

a___d
|\  |
| \ |
|__\|
b   c

Generally speaking, it isn't necessary to manually shift these vertices into the right place. Indigo will take care of this for you, based on the settings you provide for your entity, like its position, scale and rotation.

That said, sometimes it is necessary or interesting to do so. Perhaps to make an entity wobble or skew.

To do that, we need to provide a vertex shader program that tells Indigo how to adjust the position of each vertex.

How to move vertices in a vertex shader

We need to define a shader that takes both the usual fragment shader, and also a vertex shader. In this case we pass in the default environment to both.

val shader: Shader =
  UltravioletShader(
    ShaderId("shader"),
    EntityShader.vertex[VertexEnv](vertex, VertexEnv.reference),
    EntityShader.fragment[FragmentEnv](fragment, FragmentEnv.reference)
  )

A vertex shader is just a function that takes a vec4 of the current vertex position, and returns a new vec4 of the manipulated vertex position.

In this example, we calculate an angle based on the current time, and then shift the current vertex by that angle.

  inline def vertex: Shader[VertexEnv, Unit] =
    Shader[VertexEnv] { env =>
      def vertex(v: vec4): vec4 =
        val angle = env.TAU * (env.TIME % 1.0f)

        v + vec4(
          vec2(sin(angle) * 0.2f, cos(angle) * 0.2f),
          vec2(0.0f)
        )
    }