How to fill triangle with different colors on front and back sides?

Started by
11 comments, last by Yura 11 years, 3 months ago
I have primitive triangles (triangle list) and have back culling off
[source lang="csharp"] d3dDevice.SetRenderState(RenderState.CullMode, Cull.None);[/source]

And now I want to fill this triangle with colour in such way, so front side had one colour and when I rotate it to back side, it had another colour.
Is it possible to do that?
Each point of triangle can have it's colour
Advertisement
if you pass the camera position to your vertex shader, then you can check facing with the following ..

output.faceShear = dot(input.normal,gEyePosition - input.position);

Then you can select front and back face with


if (input.faceShear >= 0.0)
return float4(input.colorA,1);
else
return float4(input.colorB,1);
For shader model 3 there's also the VFACE semantic, automatically available in the pixel shader (just define a [font=courier, courier new, serif] float face : VFACE[/font] parameter in your shader function).

Or are you using the fixed function pipeline ?

@Gavin: Hmmm, does this really work ? E.g. normals don't need to coincide with the face normals.
It really works, as long as the 3 normals are perpendicular to the face and forward facing. But no, the normals don't have to coincide with the face normals, and if they were non-perpendicular then you would get color flipping across the face. But I didn't think the OP was interested in the general case, just a specific requirement. I thought there was something in DX11 to give the front/back face, like the semantic you've mentioned, but I couldn't say about DX9. So I just gave him the first solution that came to mind.

But, Yura, definitely follow unbirds suggestion if that works.

For shader model 3 there's also the VFACE semantic, automatically available in the pixel shader (just define a [font=courier, courier new, serif] float face : VFACE[/font] parameter in your shader function).

Or are you using the fixed function pipeline ?

@Gavin: Hmmm, does this really work ? E.g. normals don't need to coincide with the face normals.


I do not use any shaders, so can you explain in details, what and where shoud I fix in my code

[source lang="csharp"][StructLayout(LayoutKind.Sequential)]
struct Vertex
{
public Vector4 Position;
public Color Color;
//public Vector3 Normal;
}


private void InitGeometryTriangles()
{
FormList();

List<Vertex> points = new List<Vertex>();
for (int i = 0; i < elements.Length; i++)
{
List<Node> list = elements.Nodes;

int listCount = list.Count;
for (int j = 0; j < listCount; j++)
{

points.Add(new Vertex() { Color = SharpDX.Color.Gray, Position = new Vector4(list[j].X, list[j].Y, list[j].Z, 1.0f) });

if (j == 2)
{
points.Add(new Vertex() { Color = SharpDX.Color.Gray, Position = new Vector4(list[j].X, list[j].Y, list[j].Z, 1.0f) });
}
}

points.Add(new Vertex() { Color = SharpDX.Color.Gray, Position = new Vector4(list[0].X, list[0].Y, list[0].Z, 1.0f) });
}

totalPointsCount = points.Count;
vertices = new VertexBuffer(d3dDevice, Marshal.SizeOf(typeof(Vertex)) * totalPointsCount, SharpDX.Direct3D9.Usage.WriteOnly,
myVertexFormat, Pool.Managed);

vertices.Lock(0, 0, LockFlags.None).WriteRange(points.ToArray());
vertices.Unlock();

var vertexElems = new[] {
new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.Position, 0),
new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0),
VertexElement.VertexDeclarationEnd
};
vertexDecl = new VertexDeclaration(d3dDevice, vertexElems);
}

private void RedrawPrimitives()
{
d3dDevice.VertexFormat = myVertexFormat;
d3dDevice.VertexDeclaration = vertexDecl;

d3dDevice.Clear(ClearFlags.Target, SharpDX.Color.White, 1.0f, 0);
d3dDevice.BeginScene();

d3dDevice.SetStreamSource(0, vertices, 0, Marshal.SizeOf(typeof(Vertex)));
d3dDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, totalPointsCount / 3);

d3dDevice.EndScene();
d3dDevice.Present();
}[/source]

Thanks for reply!
If you're not using shaders then neither of our suggestions are going to be of any use. Instead you will have to provide two triangles, one for each side, and turn back-face culling on, so that they don't interfere with each other when rendering.

If you're not using shaders then neither of our suggestions are going to be of any use. Instead you will have to provide two triangles, one for each side, and turn back-face culling on, so that they don't interfere with each other when rendering.


Can you post here some example of shader, similar to my problem
and provide guidance on the application of this shader in my code?
One more question: how to make my triangles not permeable (opaque)?
You can do it in two pass. The first pass just set cull mode to back face so it cull back face polygons and draw the front frace with the color you want. For the second pass just set cull mode to front face and draw all the back faces with the color you want.
@Gavins: Thanks for the clarification about the normals.

@BornToCode: +1. That's what I approximately had in mind for a FFP setup.

I also find Gavin's idea with doubling the triangles quite nice. Just add the vertices twice (with different color), once as before, once in reverse order, that should do it. With an index buffer this is even easier and less wasteful.

Transparency - or any other special/custom form of final color mixing with the background - is called blending. You enable it through

device.SetRenderState(RenderState.AlphaBlendEnable, true);

There are a couple of render states for configuration.
E.g. the usual (nonpremultiplied) alpha blending is setup through:

device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha);
device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha);
device.SetRenderState(RenderState.BlendOperation, BlendOperation.Add);

Now you need to provide a sensible alpha channel, in your case through vertex color. An alpha of 255 (or 1.0 normalized) will give you full opacity, 128 will blend the color about halfway with the background.

This is relatively easy to setup, but can be hard to get right. Depending on your blending mode, you may also need to draw your objects/primitives ordered (farthest first). As a workaround: Use additive blending, this is order-independant.

Hmmmm, writing a shader mini-tutorial here ? Sorry, not in the mood smile.png. You should actually find quite plenty, just not especially for SlimDX.

Still: Highly advised in the long run, since it's the way to do real-time graphics for probably a decade now. It's really fun, since you are now programming the graphics hardware, which gives higher flexibility. But it's also harder to debug and sometimes cumbersome to get things right.

If time allows start now. I advise to use the effect framework, not raw shaders. I also advise to learn about index buffer and custom vertex format, aka VertexDeclaration (since the flexible vertex format is not really flexibel. The D3DX functions D3DXDeclaratorFromFVF, D3DXFVFFromDeclarator, D3DXGetDeclVertexSize will come in handy here, they are available in SlimDX.Direct3D9.D3DX).

Edit: Ah, sorry, you already are using a declaration.

This topic is closed to new replies.

Advertisement