C++ – HLSL DirectX9: Is there a getTime() function or similar


I'm currently working on a project using C++ and DirectX9 and I'm looking into creating a light source which varies in colour as time goes on.

I know C++ has a timeGetTime() function, but was wondering if anyone knows of a function in HLSL that will allow me to do this?


Best Solution

Use a shader constant in HLSL (see this introduction). Here is example HLSL code that uses timeInSeconds to modify the texture coordinate:

float4x4 view_proj_matrix; 
float4x4 texture_matrix0; 
// My time in seconds, passed in by CPU program
float    timeInSeconds;

struct VS_OUTPUT 
   float4 Pos     : POSITION; 
   float3 Pshade  : TEXCOORD0; 

VS_OUTPUT main (float4 vPosition : POSITION) 
   VS_OUTPUT Out = (VS_OUTPUT) 0;  

   // Transform position to clip space 
   Out.Pos = mul (view_proj_matrix, vPosition); 

   // Transform Pshade 
   Out.Pshade = mul (texture_matrix0, vPosition);

   // Transform according to time
   Out.Pshade = MyFunctionOfTime( Out.Pshade, timeInSeconds );

   return Out; 

And then in your rendering (CPU) code before you call Begin() on the effect you should call:

// C++
myLightSourceTime = GetTime(); // Or system equivalent here:
m_pEffect->SetFloat ("timeInSeconds ", &myLightSourceTime); 

If you don't understand the concept of shader constants, have a quick read of the PDF. You can use any HLSL data type as a constant (eg bool, float, float4, float4x4 and friends).