Learning to Write Procedural Shaders

In OpenGL, there is a system that allows for very fast drawing of 2D and 3D graphics, using a mini language that runs on the GPU called OpenGL Shading Language (GLSL). IN PTB, these are the Procedural stimuli, as seen in e.g. DriftDemo4.m or ProceduralGarboriumDemo.m.

There are many learning resources available, but IMO the best online tutorial about GLSL is the book of shaders:

It gives a thoughtful introduction to shaders, and includes a real-time real-time GLSL editor embedded in the web page to experiment with GLSL code:

It also includes a nice glossary of many GLSL functions that are very useful, e.g. smoothstep.


ShaderToy is another GLSL online editor that also allows sharing shader code; so I created an example which is the PTB procedural shader code used by DriftDemo4.m and converted to work in ShaderToy:

https://www.shadertoy.com/view/wlGXRV

You can change the various parameters and get a feel for how they affect the output immediately. What you are editing in ShaderToy is called a fragment shader. This is basically the equivalent of the BasicSineGratingShader.frag.txt file you will find in Psychtoolbox/PsychOpenGL/PsychGLSLShaders/.

So the order of code calls in PTB is:

  • DriftDemo4.m uses CreateProceduralSineGrating.m to create a procedural texture.

  • CreateProceduralSineGrating.m loads the GLSL code found in BasicSineGratingShader.vert.txt & BasicSineGratingShader.frag.txt.

If you make a shader in one of the online editors, you can transfer it back to PTB by getting the variables back into the correct places. Variables that may change on every frame should go into the auxParameters that get passed to Screen('DrawTexture'), and variables that don’t change too often can be specified in the CreateProceduralXXX.m setup file. EDIT: Mario reminded us the documentation for this is found here: http://psychtoolbox.org/docs/ProceduralShadingAPI

As another example, here is a red-green chromatic grating in shadertoy:

https://www.shadertoy.com/view/wtKSDw

And the equivalent PTB code:



You can see how the variables are set up. In summary shaders are a fast and efficient way to draw stimuli, and although a bit daunting at first (lost outside the MATLAB IDE comfort zone), with these online real-time tools it makes learning how they work much easier.


bonus material: if you want to know how on earth occult tarot cards and GLSL GPU shaders are related, see https://patriciogonzalezvivo.github.io/PixelSpiritDeck/ :wink:

3 Likes

Should also mention that there’s PTB documentation about how to communicate parameters between the shaders and PTB’s Screen(‘DrawTexture’,…) command:

help ProceduralShadingAPI, or
http://psychtoolbox.org/docs/ProceduralShadingAPI

1 Like