Basic Shaders

Welcome to the wild world of shaders where the most advanced graphical effects are at your fingertips!  Otter supports both vertex and fragment shaders written in GLSL (the capabilities of Otter are the exact same as SFML, so be sure to check out the resources on the SFML site for more details.)

This example will show a few quick fragment shader effects on a static image.  Download the example shaders here:

basic.frag

color.frag

gray.frag

invert.frag

distort.frag

And of course here is the image that the example will be using:

Credit for the above image goes to The Daily Otter and Josh More.  Download the shaders and the image and check out the example code:

using Otter;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicShaders {
  class Program {
    static void Main(string[] args) {
      // Create a Game.
      var game = new Game("Shader Example");

      // Set the background color.
      game.Color = Color.Shade(0.1f);

      // Create a new Scene.
      var scene = new Scene();

      // Create a ShaderTest Entity and pass in 5 shader paths.
      var shaderTest = new ShaderTest(
        "basic.frag",
        "color.frag",
        "gray.frag",
        "invert.frag",
        "distort.frag"
        );

      // Add the ShaderTest to the Scene.
      scene.Add(shaderTest);

      // Start the Game!
      game.Start(scene);
    }
  }

  class ShaderTest : Entity {
    // The passed in Shader paths.
    string[] shaders;

    // The current Shader index.
    int shaderIndex;

    // The Image to use.
    public Image Image = new Image("otter.jpg");

    public ShaderTest(params string[] shaders) {
      // Center the Image, and add it to the Entity.
      Image.CenterOrigin();
      AddGraphic(Image);

      // Grab the shaders array from the constructor.
      this.shaders = shaders;
    }

    public override void Added() {
      base.Added();
      // Center the Entity in the Game's bounds.
      SetPosition(Game.HalfWidth, Game.HalfHeight);

      // Update the Shader.
      UpdateShader();
    }

    public override void Update() {
      base.Update();

      // Switch the Shader using the left and right arrow keys.
      if (Input.KeyPressed(Key.Left)) {
        shaderIndex--;
        UpdateShader();
      }
      if (Input.KeyPressed(Key.Right)) {
        shaderIndex++;
        UpdateShader();
      }
    }

    void UpdateShader() {
      // Make sure the index doesn't go out of bounds.
      shaderIndex = (int)Util.Clamp(shaderIndex, 0, shaders.Length - 1);

      // Load in the new Shader.
      Image.Shader = new Shader(shaders[shaderIndex]);
    }
  }
}

When running the example press the left and right arrow keys to switch between the different example shaders provided.

 

Examples