Created
February 28, 2019 10:58
-
-
Save tamask/929e66bd87c08493d8deca3b1baa5e6b to your computer and use it in GitHub Desktop.
Various math util functions for cg
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef _MATHUTIL | |
#define _MATHUTIL | |
#define PI 3.141592653589793115997963468544185161590576171875 | |
inline float floorq(float v, float q) { | |
return floor(v / q) * q; | |
} | |
inline float ceilq(float v, float q) { | |
return ceil(v / q) * q; | |
} | |
inline float roundq(float v, float q) { | |
return round(v / q) * q; | |
} | |
inline float never0(float v) { | |
return (sign(v) + 0.00001) * max(abs(v), 0.00001); | |
} | |
inline float smooth(float v) { | |
return cos(v * PI + PI) / 2 + .5; | |
} | |
inline float circle(float x) { | |
return sqrt(1 - pow(x - 1, 2)); | |
} | |
inline float circlei(float x) { | |
return 1 - sqrt(1 - pow((1 - x) - 1, 2)); | |
} | |
inline float tri(float v) { | |
return 1 - abs(v % 1 * 2 - 1); | |
} | |
inline float parabola(float x) { | |
return x * (0.5 + (1 - x * 2) * 0.5) * 4; | |
} | |
inline float bounce(float v) { | |
return 1 - pow(abs(v % 1 * 2 - 1), 2); | |
} | |
inline float2 rotate2(float2 v, float r) { | |
float sinx = sin(r); | |
float cosx = cos(r); | |
float2x2 m = float2x2(cosx, -sinx, sinx, cosx); | |
return mul(v, m); | |
} | |
inline float2 bend2(float2 v, float factor) | |
{ | |
float x, y, theta, sint, cost; | |
x = v.y; | |
y = v.x; | |
theta = x * factor; | |
sint = sin(theta); | |
cost = cos(theta); | |
if (abs(factor) > 0) { | |
return float2( | |
(y - 1 / factor) * cost + 1 / factor, | |
-(y - 1 / factor) * sint); | |
} else { | |
return v; | |
} | |
} | |
inline float lerpx(float a, float b, float v, float bias, float scale) | |
{ | |
v = clamp((v - bias) / scale, 0, 1); | |
v = a * (1 - v) + b * v; | |
return v; | |
} | |
inline float2 ray_x_plane(float3 ro, float3 rd, float3 po, float3 pn) { | |
/* | |
input: | |
ro = ray origin; | |
rd = ray direction; | |
po = plane origin; | |
pn = plane normal; | |
output: | |
x: > 0 = intersection found | |
y: distance to plane | |
*/ | |
float d = dot(pn, rd); | |
if (abs(d) > 0.0001) | |
{ | |
float t = dot(po - ro, pn) / d; | |
if (t >= 0) | |
return float2(1, t); | |
} | |
return float2(0, 0); | |
} | |
inline float4 ray_x_plane_point(float3 ro, float3 rd, float3 po, float3 pn) { | |
float2 res = ray_x_plane(ro, rd, po, pn); | |
if (res.x > 0) | |
return half4(ro + rd * res.y, res.x); | |
else | |
return half4(ro, res.x); | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment