Xbox LIVE Indie Games
Sort Discussions: Previous Discussion Next Discussion
Page 1 of 1 (2 posts)

PS/VS lighting problem

Last post 6/21/2014 7:11 PM by JujiPL. 1 replies.
  • 4/12/2014 3:43 PM

    PS/VS lighting problem

    Hi everyone. I'm fairly new to direct3d and this is my first post. I have written the following hlsl code to experiment with diffuse and ambient lighting but i observed some strange behaviour... if i make the object rotate using the worldmatrix, the light rotates aswell... it's like the light is moving proportionally to the object's rotation speed. I have set the light direction inside the hlsl. Might this be the problem? I'm fairly new to direct3d so please go slow with me.

    Texture2D colorMap_ : register( t0 );
    SamplerState colorSampler_ : register( s0 );

    cbuffer cbChangesEveryFrame : register( b0 )
        matrix worldMatrix;

    cbuffer cbNeverChanges : register( b1 )
        matrix viewMatrix;

    cbuffer cbChangeOnResize : register( b2 )
        matrix projMatrix;

    struct VS_Input
        float4 pos  : POSITION;
        float2 tex0 : TEXCOORD0;
        float3 normal: NORMAL;

    struct PS_Input
        float4 pos  : SV_POSITION;
        float2 tex0 : TEXCOORD0;
        float3 normal: NORMAL;

    PS_Input VS_Main( VS_Input vertex )
        PS_Input vsOut = ( PS_Input )0;
        vsOut.pos = mul( vertex.pos, worldMatrix );
        vsOut.pos = mul( vsOut.pos, viewMatrix );
        vsOut.pos = mul( vsOut.pos, projMatrix );
        vsOut.tex0 = vertex.tex0;

        vsOut.normal=mul(vertex.normal, (float3x3)worldMatrix);

        return vsOut;

    float4 PS_Main( PS_Input frag ) : SV_TARGET
        float3 ambientColor = float3( 0.2f, 0.2f, 0.2f );
        float4 textureColor;
        float3 lightDir;
        float lightIntensity;
        float4 color;
        textureColor = colorMap_.Sample(colorSampler_, frag.tex0);
        lightDir = -float3(1.0f, 1.0f, 1.0f);
        lightIntensity=clamp(dot(frag.normal, lightDir), 0.0f, 1.0f);
        float4 diffuseColor = float4(0.0f, 1.0f, 1.0f, 1.0f);
        color= saturate(diffuseColor*lightIntensity);
        color = color * textureColor + float4(ambientColor,1.0);
        return color;

    Yes, i have used as refrence other codes from books.
  • 6/21/2014 7:11 PM In reply to

    Re: PS/VS lighting problem


    It looks like your light is moving with the camera.
    When you move the camera, you should alter the light direction,
    because HLSL does not recalculate the movement implicitely.
    (position and direction between the camera and the light must change)

    Sample code:
    instead of passing
    you would set in the constant buffer such computation:
    XMVector4Transform(g_lightPosition, VIEW_MATRIX)

    This code is made in Visual C++, not in HLSL, but the solution would be made in the HLSL too.
Page 1 of 1 (2 posts) Previous Discussion Next Discussion