正弦波近似 http://blog.csdn.net/ring0hx/article/details/44492415
float4 SmoothCurve( float4 x ) { return x * x *( 3.0 - 2.0 * x ); } float4 TriangleWave( float4 x ) { return abs( frac( x + 0.5 ) * 2.0 - 1.0 ); } float4 SmoothTriangleWave( float4 x ) { return SmoothCurve( TriangleWave( x ) ); }
在做一些游戏效果的时候经常需要用到正弦波,它平滑又有周期性,但是sin的计算开销略大。作为优化,在GPU Gem上看到一个用三次函数平滑三角波得到近似正弦波的方法不错:
<code class="language-c hljs has-numbering">float4 SmoothCurve( float4 x ) { <span class="hljs-keyword" style="color: rgb(0, 0, 255);">return x * x *( <span class="hljs-number">3.0 - <span class="hljs-number">2.0 * x ); } float4 TriangleWave( float4 x ) { <span class="hljs-keyword">return <span class="hljs-built_in">abs( frac( x + <span class="hljs-number">0.5 ) * <span class="hljs-number">2.0 - <span class="hljs-number">1.0 ); } float4 SmoothTriangleWave( float4 x ) { <span class="hljs-keyword">return SmoothCurve( TriangleWave( x ) ); }</span></span></span></span></span></span></span></span></span></code>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
三角波TriangleWave 函数图
平滑函数SmoothCurve 函数图
最后得到的SmoothTriangleWave函数图