Skip to content

Instantly share code, notes, and snippets.

@stash
Last active February 18, 2020 23:43
Show Gist options
  • Save stash/644f86019666aa689f70436198e73683 to your computer and use it in GitHub Desktop.
Save stash/644f86019666aa689f70436198e73683 to your computer and use it in GitHub Desktop.
Heartbeat function in HLSL
// Approximates a heartbeat
// Roughly approximates mathematical formula:
// x = t * f * PI
// y = h * sin(x)^(2 * p + 1) * sin(x + d)
// where
// f is frequency in Hz if t is fractional seconds
// p is a power factor (the "slope" of the main upswing of the wave)
// d is an "offset" that shifts the peak and trough heights
// h is an overall height factor
//
// Example function:
// http://www.iquilezles.org/apps/graphtoy/?f1(x)=pow(sin(2*3.14159*x),31)*sin(2*3.14159*x+1.4)*4
// where:
// (f) frequency is 2Hz
// (p) power is 15 (so, an exponent of 2p+1 = 31)
// (d) offset is 1.4
// (h) height is multiplied by 4 to get it roughly inside of [-1,1]
float heartbeat(float t, float frequency, float power, float offset, float height) {
float x = t * frequency * 3.1415926535897932384626433832795;
float s1 = sin(x);
float s2 = sin(x + offset);
// pow(x,y) in HLSL isn't defined for x < 0,
// so take advantage of the fact that squaring gets rid of the sign anyhow
float a = pow(s1 * s1, power); // i.e., pow(abs(s1), 2 * power)
a *= s1; // one more power to get (2*n+1)th power, with original sign
return height * a * s2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment