{{ message }}

Instantly share code, notes, and snippets.

# motoishmz/GLSL-Math.md

Forked from patriciogonzalezvivo/GLSL-Math.md
Created Feb 13, 2016
GLSL Math functions

### Trigonometry

``````const float PI = 3.1415926535897932384626433832795;
const float PI_2 = 1.57079632679489661923;
const float PI_4 = 0.785398163397448309616;

float PHI = (1.0+sqrtf(5.0))/2.0;
``````
``````float PI180 = float(PI / 180.0);
float sind(float a){return sin(a * PI180);}
float cosd(float a){return cos(a * PI180);}

``````
``````mat4 scale(float x, float y, float z){
return mat4(
vec4(x,   0.0, 0.0, 0.0),
vec4(0.0, y,   0.0, 0.0),
vec4(0.0, 0.0, z,   0.0),
vec4(0.0, 0.0, 0.0, 1.0)
);
}

mat4 translate(float x, float y, float z){
return mat4(
vec4(1.0, 0.0, 0.0, 0.0),
vec4(0.0, 1.0, 0.0, 0.0),
vec4(0.0, 0.0, 1.0, 0.0),
vec4(x,   y,   z,   1.0)
);
}

mat4 RotateX(float phi){
return mat4(
vec4(1.,0.,0.,0),
vec4(0.,cos(phi),-sin(phi),0.),
vec4(0.,sin(phi),cos(phi),0.),
vec4(0.,0.,0.,1.));
}

mat4 RotateY(float theta){
return mat4(
vec4(cos(theta),0.,-sin(theta),0),
vec4(0.,1.,0.,0.),
vec4(sin(theta),0.,cos(theta),0.),
vec4(0.,0.,0.,1.));
}

mat4 RotateZ(float psi){
return mat4(
vec4(cos(psi),-sin(psi),0.,0),
vec4(sin(psi),cos(psi),0.,0.),
vec4(0.,0.,1.,0.),
vec4(0.,0.,0.,1.));
}
``````

### IQ Functions by Iñigo Quilez

``````float almostIdentity( float x, float m, float n ){
if( x>m ) return x;

const float a = 2.0f*n - m
const float b = 2.0f*m - 3.0f*n;
const float t = x/m;

return (a*t + b)*t*t + n;
}
``````
``````float impulse( float k, float x ){
const float h = k*x;
return h*expf(1.0f-h);
}
``````
``````float cubicPulse( float c, float w, float x ){
x = fabsf(x - c);
if( x>w ) return 0.0f;
x /= w;
return 1.0f - x*x*(3.0f-2.0f*x);
}
``````
``````float expStep( float x, float k, float n ){
return expf( -k*powf(x,n) );
}
``````
``````float parabola( float x, float k ){
return powf( 4.0f*x*(1.0f-x), k );
}
``````
``````float pcurve( float x, float k ){
float k = powf(a+b,a+b) / (pow(a,a)*pow(b,b));
return k * powf( x, a ) * powf( 1.0-x, b );
}
``````