Friday, September 23, 2011

XNA oddity with VertexPositionNormalColored

Getting my feet wet on the XNA 4.0 framework.
Going along on the tutorial over at Reimers.

When I got to the lighting section, my game form started going blank.
No errors, just a big black background.

So after many (many) recopies and re-pastes from the webpage, I narrowed down the silent bug to the ordering of the fields of the struct "VertexPositionNormalColored" (which inherits from the interface "IVertexType") Position, Color, and Normal.

Here is the corrected version that doesn't go funky:


        [ StructLayout( LayoutKind.Explicit ) ]
        public struct VertexPositionNormalColored : IVertexType {
            public static readonly int SizeInBytes = 28;

            public static readonly VertexDeclaration VertexDeclaration =
                new VertexDeclaration( new[] {
                    new VertexElement( 0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0 ),
                    new VertexElement( sizeof ( float ) * 3, VertexElementFormat.Color, VertexElementUsage.Color, 0 ),
                    new VertexElement( sizeof ( float ) * 4, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0 )
                } );

            [ FieldOffset( 0 ) ]
            public Vector3 Position;

            [ FieldOffset( 12 ) ]
            public Color Color;

            [ FieldOffset( 16 ) ]
            public Vector3 Normal;

            public VertexPositionNormalColored( Vector3 p, Vector3 n, Color c ) {
                this.Position = p;
                this.Normal = n;
                this.Color = c;
            }

            VertexDeclaration IVertexType.VertexDeclaration { get { return VertexDeclaration; } }
        }

No comments: