Skip to main content

TouchDesigner GLSL Cheat Sheet

Rotation

// Example Pixel Shader

uniform float u_time;

// rotation matrix from the book of shaders
// <https://thebookofshaders.com/08/>

mat2 rotate2d(float _angle){
return mat2(cos(_angle),-sin(_angle),
sin(_angle),cos(_angle));
}

// many thanks to Mike Walczyk for letting me pick his brain

out vec4 fragColor;
void main()
{
// derive aspect from inputs
vec2 aspect = uTD2DInfos[0].res.zw / uTD2DInfos[0].res.w ;

// remap -1 to 1
vec2 newUV = vUV.st * 2.0 - 1.0;

// correct for aspect
newUV = newUV * aspect;

// perform rotation
newUV = rotate2d(u_time) * newUV;

// undo aspect correction
newUV = newUV * 1 / aspect;

// change remapping back to 0-1
newUV = newUV * 0.5 + 0.5;

// sample texture
vec4 color = texture(sTD2DInputs[0], newUV);

// output color
fragColor = TDOutputSwizzle(color);
}

Rotation Matrix

// rotation matrix from the book of shaders
// <https://thebookofshaders.com/08/>

mat2 rotate2d(float _angle){
return mat2(cos(_angle),-sin(_angle),
sin(_angle),cos(_angle));
}

Remap 0-1 to -1-1

// remap -1 to 1
vec2 newUV = vUV.st * 2.0 - 1.0;

Vertex Stage Normal Recalculation

// - - - - - added functions  - - - - -

// tangent basis
mat3 getTangentBasis( in vec3 tangentY ){
vec3 upVector = vec3( 0.0, 1.0, 0.0 );
vec3 tangentX = normalize( cross( upVector, tangentY ) );
vec3 tangentZ = cross( tangentY, tangentX );
return mat3( tangentX, tangentY, tangentZ );
}

// mesh deformation
vec3 applyDeformation( in vec3 pos, in vec3 norm ){

float disp = 0.0;

if( noiseType ){
disp TDSimplexNoise( vec4( pos * noiseScale + translate , time ) ) * dispScale;
}
else{
disp = TDPerlinNoise( vec4( pos * noiseScale + translate , time ) ) * dispScale;
}

vec3 deformP = norm * disp + pos;
return deformP;
}

// compute vertext normal
vec3 computeVertNorm( in vec3 pos, in vec3 norm ){
float offset = 0.1;
mat3 basis = getTangentBasis( norm );
vec3 xvn = offset *basis[ 0 ];
vec3 zv = offset* basis[ 2 ];

vec3 x0 = applyDeformation( pos + xv , norm );
vec3 x1 = applyDeformation( pos - xv , norm );
vec3 z0 = applyDeformation( pos + zv , norm );
vec3 z1 = applyDeformation( pos - zv , norm );

return cross( x1 - x0, z1 - z0 );
}