Gimun Eom
Gimun Eom

Reputation: 441

Can I calculate global variable in HLSL before vertex shader applied?

there are three global variable g_A, g_B, g_C I want to do this; g_C = g_A * g_B

I tried this;

technique RenderScene
{
    g_C = g_A * g_B;

    pass P0
    {          
        VertexShader = compile vs_2_0 RenderSceneVS();
        PixelShader  = compile ps_2_0 RenderScenePS(); 
    }
}

However, it's improper syntax. What should I do?

Must I calculate this variable in c++ code before rendering?

Upvotes: 0

Views: 1354

Answers (1)

Slagh
Slagh

Reputation: 342

DirectX 9 and 10 Effects support "preshaders", where static expressions will be pulled out to be executed on the CPU automatically.

See D3DXSHADER_NO_PRESHADER in the documentation, which is a flag that suppresses this behavior. Here's a web link: http://msdn.microsoft.com/en-us/library/windows/desktop/bb205441(v=vs.85).aspx

Your declaration of g_C is missing both static and the type e.g. float. You'll also need to move it into global scope.

When you compile it with fxc, you might see something like the following (note the preshader block after the comment block):

technique RenderScene
{
    pass P0
    {
        vertexshader = 
            asm {
            //
            // Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
            //
            // Parameters:
            //
            //   float4 g_A;
            //   float4 g_B;
            //
            //
            // Registers:
            //
            //   Name         Reg   Size
            //   ------------ ----- ----
            //   g_A          c0       1
            //   g_B          c1       1
            //

                preshader
                mul c0, c0, c1

            // approximately 1 instruction used
            //
            // Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
                vs_2_0
                mov oPos, c0

            // approximately 1 instruction slot used
            };

        pixelshader = 
            asm {
            //
            // Generated by Microsoft (R) HLSL Shader Compiler 9.29.952.3111
                ps_2_0
                def c0, 0, 0, 0, 0
                mov r0, c0.x
                mov oC0, r0

            // approximately 2 instruction slots used
            };
    }
}

I compiled the following:

float4 g_A;
float4 g_B;
static float4 g_C = g_A * g_B;

float4 RenderSceneVS() : POSITION
{
    return g_C;
}

float4 RenderScenePS() : COLOR
{
    return 0.0;
}

technique RenderScene
{
    pass P0
    {          
        VertexShader = compile vs_2_0 RenderSceneVS();
        PixelShader  = compile ps_2_0 RenderScenePS();
    }
}

with fxc /Tfx_2_0 t.fx to generate the listing. They're not very interesting shaders...

Upvotes: 1

Related Questions