# DX11 Phong shader problem, cannot find out the reason

## Recommended Posts

Hello everyone,

This is my first post here, and this is a (very) little "something" about me:
After finished my game in unity, I would like to port it to a custom framework in DX11 to have better performance and graphics, no matter how much time it will takes!

Actually I'm following some tutorial about DX11 here: http://www.rastertek.com/.

The problem I have right now is this:
[url=http://postimg.org/image/jc3jpfygn/][/url]

As you can see it's a simple plane, subdivided to 4!

The model was imported in the simplest way trough an fbx, so I've got 24 vertices and for each vertices there's normal and uv coords!
The normal for each vertex are 0 0 -1!

[url=http://postimg.org/image/7chwufx8r/][/url]

I cannot define what's the problem here!

The only one I could think is that I should use 24 indices and 9 vertex/normal/uv, but using control point will make me loose hard/soft edge in complex model!

Could you help me to find out the problem?

Thank you very much!

EDIT:

I've tried without duplicated vertices, so 9  vertices and 24 indices!
The problem should be somewere else!
Edited by politoleo

##### Share on other sites

My guess is normal transformation issue, looks like the center vertex normal is (0,0,-1), and the rest are not. The specular highlight is also not distributed in a symetrical way, which is strange.

##### Share on other sites

The buffer i'm passing is this one:

[url=http://postimg.org/image/wrbc6jd51/][/url]

Here is the shaders (I've just add the smoothstep function, the rest it's exactly like the tutorial, and I can observe the same with tutorial shader also)

VERTEX:

////////////////////////////////////////////////////////////////////////////////
// Filename: light.vs
////////////////////////////////////////////////////////////////////////////////

/////////////
// GLOBALS //
/////////////
cbuffer MatrixBuffer
{
matrix worldMatrix;
matrix viewMatrix;
matrix projectionMatrix;
};

cbuffer CameraBuffer
{
float3 cameraPosition;
};

//////////////
// TYPEDEFS //
//////////////
struct VertexInputType
{
float4 position : POSITION;
float2 tex : TEXCOORD0;
float3 normal : NORMAL;
};

struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
float3 normal : NORMAL;
float3 viewDirection : TEXCOORD1;
};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
{
PixelInputType output;
float4 worldPosition;

// Change the position vector to be 4 units for proper matrix calculations.
input.position.w = 1.0f;

// Calculate the position of the vertex against the world, view, and projection matrices.
output.position = mul(input.position, worldMatrix);
output.position = mul(output.position, viewMatrix);
output.position = mul(output.position, projectionMatrix);

// Store the texture coordinates for the pixel shader.
output.tex = input.tex;

// Calculate the normal vector against the world matrix only.
output.normal = mul(input.normal, (float3x3)worldMatrix);

// Normalize the normal vector.
output.normal = normalize(output.normal);

// Calculate the position of the vertex in the world.
worldPosition = mul(input.position, worldMatrix);

// Determine the viewing direction based on the position of the camera and the position of the vertex in the world.
output.viewDirection = cameraPosition.xyz - worldPosition.xyz;

// Normalize the viewing direction vector.
output.viewDirection = normalize(output.viewDirection);

return output;
}

PIXEL:

Texture2D shaderTexture;
SamplerState SampleType;

cbuffer LightBuffer
{
float4 ambientColor;
float4 diffuseColor;
float3 lightDirection;
float  specularPower;
float4 specularColor;
};

//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
float3 normal : NORMAL;
float3 viewDirection : TEXCOORD1;
};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
{
float4 textureColor;
float3 lightDir;
float lightIntensity;
float4 color;
float3 reflection;
float4 specular;

// Sample the pixel color from the texture using the sampler at this texture coordinate location.

// Set the default output color to the ambient light value for all pixels.
color = ambientColor;

// Invert the light direction for calculations.
lightDir = -lightDirection;

// Calculate the amount of light on this pixel.
lightIntensity = saturate(dot(input.normal, lightDir));

// Determine the final diffuse color based on the diffuse color and the amount of light intensity.

color += (diffuseColor * lightIntensity);

// Saturate the ambient and diffuse color.
color = saturate(color);

// Calculate the reflection vector based on the light intensity, normal vector, and light direction.
reflection = normalize(2 * lightIntensity * input.normal - lightDir);

// Determine the amount of specular light based on the reflection vector, viewing direction, and specular power.
specular = smoothstep(0.0,0.05,lightIntensity) * pow(saturate(dot(reflection, input.viewDirection)), specularPower);

specular = specular * specularColor;

// Multiply the texture pixel and the input color to get the textured result.
color = color * textureColor;

// Add the specular component last to the output color.
color = saturate(color + specular);

return color;
}


Thank you again!

Edited by politoleo

##### Share on other sites

PS.

It's not simmetrical because i was moving with the camera!

##### Share on other sites

What's your input layout (CreateInputLayout, IASetInputLayout)?

##### Share on other sites

This is the part of code for input layout initialisation for that shader:

	// Create the vertex input layout description.
// This setup needs to match the VertexType stucture in the Model and in the shader.
polygonLayout[0].SemanticName = "POSITION";
polygonLayout[0].SemanticIndex = 0;
polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[0].InputSlot = 0;
polygonLayout[0].AlignedByteOffset = 0;
polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[0].InstanceDataStepRate = 0;

polygonLayout[1].SemanticName = "TEXCOORD";
polygonLayout[1].SemanticIndex = 0;
polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT;
polygonLayout[1].InputSlot = 0;
polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[1].InstanceDataStepRate = 0;

polygonLayout[2].SemanticName = "NORMAL";
polygonLayout[2].SemanticIndex = 0;
polygonLayout[2].Format = DXGI_FORMAT_R32G32B32_FLOAT;
polygonLayout[2].InputSlot = 0;
polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA;
polygonLayout[2].InstanceDataStepRate = 0;

// Get a count of the elements in the layout.
numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]);

// Create the vertex input layout.


Thanks!

##### Share on other sites

Not sure if that is the problem, but you need to normalize the viewDirection and Normal inside the pixel shader, as they are not guranteed to be normalized after interpolation. And also make sure that lightDir is normalized.

##### Share on other sites

Thank you satanir, it really helped a lot!

Now everything looks ok from distance, but when you moove the camera the reflection will follow the poligon edge:

this is the pixel shader now:

Texture2D shaderTexture;
SamplerState SampleType;

cbuffer LightBuffer
{
float4 ambientColor;
float4 diffuseColor;
float3 lightDirection;
float  specularPower;
float4 specularColor;
};

//////////////
// TYPEDEFS //
//////////////
struct PixelInputType
{
float4 position : SV_POSITION;
float2 tex : TEXCOORD0;
float3 normal : NORMAL;
float3 viewDirection : TEXCOORD1;
};

////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
{
float4 textureColor;
float3 lightDir;
float lightIntensity;
float4 color;
float3 reflection;
float4 specular;

// Sample the pixel color from the texture using the sampler at this texture coordinate location.

// Set the default output color to the ambient light value for all pixels.
color = ambientColor;

// Invert the light direction for calculations.
lightDir = -lightDirection;

// Normalize view direction
input.viewDirection = normalize(input.viewDirection);

// Calculate the amount of light on this pixel.
lightIntensity = saturate(dot(input.normal, lightDir));

// Determine the final diffuse color based on the diffuse color and the amount of light intensity.

color += (diffuseColor * lightIntensity);

// Saturate the ambient and diffuse color.
color = saturate(color);

// Calculate the reflection vector based on the light intensity, normal vector, and light direction.
reflection = normalize(2 * lightIntensity * input.normal - lightDir);

// Determine the amount of specular light based on the reflection vector, viewing direction, and specular power.
specular = smoothstep(0.0,0.05,lightIntensity) * pow(saturate(dot(reflection, input.viewDirection)), specularPower);

specular = specular * specularColor;

// Multiply the texture pixel and the input color to get the textured result.
color = color * textureColor;

// Add the specular component last to the output color.
color = saturate(color + specular);

return color;
}



FAR:

[url=http://postimg.org/image/4a74zwm5h/][/url]

NEAR:

[url=http://postimg.org/image/wjyg3s09f/][/url]

Thank you!

##### Share on other sites

Fixed it by removing the viewDirection normalization in the vertex shader!

Thank you very much for the help guys!

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
627694
• Total Posts
2978673
• ### Similar Content

• hi,
i have read very much about the binding of a constantbuffer to a shader but something is still unclear to me.
e.g. when performing :   vertexshader.setConstantbuffer ( buffer,  slot )
is the buffer bound
or
b. to the VertexShader that is currently set as the active VertexShader
Is it possible to bind a constantBuffer to a VertexShader e.g. VS_A and keep this binding even after the active VertexShader has changed ?
I mean i want to bind constantbuffer_A  to VS_A, an Constantbuffer_B to VS_B  and  only use updateSubresource without using setConstantBuffer command every time.

Look at this example:
perform drawcall       ( buffer_A is used )

perform drawcall   ( buffer_B is used )
perform drawcall   (now which buffer is used ??? )

I ask this question because i have made a custom render engine an want to optimize to
the minimum  updateSubresource, and setConstantbuffer  calls

• I got a quick question about buffers when it comes to DirectX 11. If I bind a buffer using a command like:
IASetVertexBuffers IASetIndexBuffer VSSetConstantBuffers PSSetConstantBuffers  and then later on I update that bound buffer's data using commands like Map/Unmap or any of the other update commands.
Do I need to rebind the buffer again in order for my update to take effect? If I dont rebind is that really bad as in I get a performance hit? My thought process behind this is that if the buffer is already bound why do I need to rebind it? I'm using that same buffer it is just different data

• I am really stuck with something that should be very simple in DirectX 11.
1. I can draw lines using a PC (position, colored) vertices and a simple shader just fine.
2. I can draw 3D triangles using PCN (position, colored, normal) vertices just fine (even transparency and SpecularBlinnPhong shaders).

However, if I'm using my 3D shader, and I want to draw my PC lines in the same scene how can I do that?

If I change my lines to PCN and pass them to the 3D shader with my triangles, then the lighting screws them all up.  I only want the lighting for the 3D triangles, but no SpecularBlinnPhong/Lighting for the lines (just PC).
I am sure this is because if I change the lines to PNC there is not really a correct "normal" for the lines.
I assume I somehow need to draw the 3D triangles using one shader, and then "switch" to another shader and draw the lines?  But I have no clue how to use two different shaders in the same scene.  And then are the lines just drawn on top of the triangles, or vice versa (maybe draw order dependent)?
I must be missing something really basic, so if anyone can just point me in the right direction (or link to an example showing the implementation of multiple shaders) that would be REALLY appreciated.

I'm also more than happy to post my simple test code if that helps as well!

• By Reitano
Hi,
I am writing a linear allocator of per-frame constants using the DirectX 11.1 API. My plan is to replace the traditional constant allocation strategy, where most of the work is done by the driver behind my back, with a manual one inspired by the DirectX 12 and Vulkan APIs.
In brief, the allocator maintains a list of 64K pages, each page owns a constant buffer managed as a ring buffer. Each page has a history of the N previous frames. At the beginning of a new frame, the allocator retires the frames that have been processed by the GPU and frees up the corresponding space in each page. I use DirectX 11 queries for detecting when a frame is complete and the ID3D11DeviceContext1::VS/PSSetConstantBuffers1 methods for binding constant buffers with an offset.
The new allocator appears to be working but I am not 100% confident it is actually correct. In particular:
1) it relies on queries which I am not too familiar with. Are they 100% reliable ?
2) it maps/unmaps the constant buffer of each page at the beginning of a new frame and then writes the mapped memory as the frame is built. In pseudo code:
BeginFrame:
page.data = device.Map(page.buffer)
device.Unmap(page.buffer)
RenderFrame
Alloc(size, initData)
...
memcpy(page.data + page.start, initData, size)
Alloc(size, initData)
...
memcpy(page.data + page.start, initData, size)
(Note: calling Unmap at the end of a frame prevents binding the mapped constant buffers and triggers an error in the debug layer)
Is this valid ?
3) I don't fully understand how many frames I should keep in the history. My intuition says it should be equal to the maximum latency reported by IDXGIDevice1::GetMaximumFrameLatency, which is 3 on my machine. But, this value works fine in an unit test while on a more complex demo I need to manually set it to 5, otherwise the allocator starts overwriting previous frames that have not completed yet. Shouldn't the swap chain Present method block the CPU in this case ?
4) Should I expect this approach to be more efficient than the one managed by the driver ? I don't have meaningful profile data yet.
Is anybody familiar with the approach described above and can answer my questions and discuss the pros and cons of this technique based on his experience ?
For reference, I've uploaded the (WIP) allocator code at https://paste.ofcode.org/Bq98ujP6zaAuKyjv4X7HSv.  Feel free to adapt it in your engine and please let me know if you spot any mistakes
Thanks
Stefano Lanza

• Hey all. I've been working with compute shaders lately, and was hoping to build out some libraries to reuse code. As a prerequisite for my current project, I needed to sort a big array of data in my compute shader, so I was going to implement quicksort as a library function. My implementation was going to use an inout array to apply the changes to the referenced array.

I spent half the day yesterday debugging in visual studio before I realized that the solution, while it worked INSIDE the function, reverted to the original state after returning from the function.

My hack fix was just to inline the code, but this is not a great solution for the future.  Any ideas? I've considered just returning an array of ints that represents the sorted indices.

• 19
• 14
• 12
• 10
• 12