urgent, please help managed directx

Dec 1 2005 9:46 AM
Hello
i don't know this is right place for this question, sorry for that
I work on a little project that load's mesh data from a custom txt file, in managed way;  i also know the other way to load from .x file.
but this code give me the access violation exception
in Mesh.drawsubset(0) line.
I am using directx 9.0c april 2005 and vs2005.
any ideas can help
I am sorry for throwing my problem to you
[source lang="c#"]
 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
//using Microsoft.DirectX.Direct3Dx
using System.IO;
namespace MeshDemo
{
    public partial class Meshes : Form
    {
        private float xRotate = 0;
        private float yRotate = 0;
        private float zRotate = 0;
        private float h = 0;
        private Device device = null;
        //private VertexBuffer vertexBuffer = null;
        private Mesh MyMesh = null;
        private int NumberOfVertices;
        private int NumberofIndices;
        PresentParameters presentParams;
        public Int64 iter=0;
        Material mtrl;
        public Meshes()
        {
            InitializeComponent();
        }
 
        static void Main()
        {
 
            using (Meshes frm = new Meshes())
            {
                if (!frm.InitializeGraphics()) // Initialize Direct3D
                {
                    MessageBox.Show("Could not initialize Direct3D.  This tutorial will exit.");
                    return;
                }
                frm.Show();
 
                // While the form is still valid, render and process messages
                while (frm.Created)
                {
                    frm.Render();
                    Application.DoEvents();
                }
            }
        }
 
        public bool InitializeGraphics()
        {
            try
            {
                InitDevice();
                SetupDevice();
               
                device.DeviceReset += new EventHandler(OnDeviceReset);
                OnDeviceReset(null, EventArgs.Empty);
               
 
//                this.OnCreateDevice(device, null);
 
                return true;
            }
            catch (DirectXException)
            {
                return false;
            }
 
        }
 
 
 
        private void OnDeviceReset(object sender, EventArgs e)
        {
            InitDevice();
        }
        private void SetupDevice()
        {
            device.RenderState.Lighting = true;
            device.RenderState.Ambient = System.Drawing.Color.Yellow;
            device.RenderState.ZBufferEnable = true;
            //device.RenderState.DiffuseMaterialSource = ColorSource.Material;
            mtrl = new Material();
            Color c = Color.FromArgb(127, 255, 0, 0);
 
            mtrl.Diffuse = c;
            mtrl.Ambient = c;
            mtrl.Specular = c;
            mtrl.Emissive = c;
 
            device.Material = mtrl;
        }
        private void InitDevice()
        {
            // Now let's setup our D3D stuff
            presentParams = new PresentParameters();
            presentParams.Windowed = true;
            presentParams.SwapEffect = SwapEffect.Discard;
            presentParams.DeviceWindow = this.pictureBox2;
            presentParams.AutoDepthStencilFormat = DepthFormat.D16;
            presentParams.EnableAutoDepthStencil = true;
            device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams);
        }
        protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e)
        {
            if ((int)(byte)e.KeyChar == (int)System.Windows.Forms.Keys.Escape)
                this.Close(); // Esc was pressed
           
        }
        protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
 
    {
        if ((int)(byte)e.KeyCode == (int)System.Windows.Forms.Keys.Up)
                xRotate += 0.1F;
            if ((int)(byte)e.KeyCode == (int)System.Windows.Forms.Keys.Down)
                xRotate -= 0.1f;
            if ((int)(byte)e.KeyCode == (int)System.Windows.Forms.Keys.Right)
                yRotate += 0.1f;
            if ((int)(byte)e.KeyCode == (int)System.Windows.Forms.Keys.Left)
                yRotate -= 0.1f;
            if ((int)(byte)e.KeyCode == (int)System.Windows.Forms.Keys.W)
                zRotate += 0.1f;
            if ((int)(byte)e.KeyCode == (int)System.Windows.Forms.Keys.S)
                zRotate -= 0.1f;
            if ((int)(byte)e.KeyCode == (int)System.Windows.Forms.Keys.NumPad8)
                h += 1;
            if ((int)(byte)e.KeyCode == (int)System.Windows.Forms.Keys.NumPad2)
                h -= 1;
 
    }
 
        //protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        //{
        //    //Application.DoEvents();
        //    //this.Render(); // Render
        //    //Application.DoEvents();
        //}
 

        private void Render()
        {
 
            if (device == null)
                return;
 
            //Clear the backbuffer to a blue color (ARGB = 000000ff)
            device.Clear(ClearFlags.Target, System.Drawing.Color.WhiteSmoke, 1.0f, 0);
            //Begin the scene
           
            device.BeginScene();
 
            Calculate();
            //device.SetStreamSource(0, MyMesh.VertexBuffer, 0);
            device.VertexFormat = CustomVertex.PositionColored.Format;
 
            iter += 1;
            SetupMatrices();
            //MyMesh.LockVertexBuffer(LockFlags.None);
            //MyMesh.LockIndexBuffer(LockFlags.None);
            //MyMesh.LockAttributeBuffer(LockFlags.None);
            MyMesh.DrawSubset(0);
            //Geometry.ComputeBoundingBox
           // MyMesh.UnlockAttributeBuffer();
           // MyMesh.UnlockIndexBuffer();
            //MyMesh.UnlockVertexBuffer();
            //device.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);
            //End the scene
            device.EndScene();
            device.Present();
        }
 
        private void SetupMatrices()
        {
            // For our world matrix, we will just rotate the object about the y-axis.
 
            // Set up the rotation matrix to generate 1 full rotation (2*PI radians)
            // every 1000 ms. To avoid the loss of precision inherent in very high
            // floating point numbers, the system time is modulated by the rotation
            // period before conversion to a radian angle.
            //float fangle;
            //int  iTime  = Environment.TickCount % 1000;
            //fangle = iTime * (2.0f * (float)Math.PI) / 1000.0f;
            //device.Transform.World = Matrix.RotationY(fangle);
 
            device.Transform.World = Matrix.RotationX(xRotate);
            //device.Transform.World = Matrix.RotationY(yRotate);
            //device.Transform.World = Matrix.RotationZ(zRotate);
            // Set up our view matrix. A view matrix can be defined given an eye
            // point, a point to lookat, and a direction for which way is up. Here,
            // we set the eye five units back along the z-axis and up three units,
            // look at the origin, and define "up" to be in the y-direction.
 
            device.Transform.View = Matrix.LookAtLH(
                new Vector3(0.0f, 3.0f, -5.0f),
                new Vector3(0.0f, 0.0f, 0.0f),
                new Vector3(0.0f, 1.0f, 0.0f));
 
            // For the projection matrix, we set up a perspective transform (which
            // transforms geometry from 3D view space to 2D viewport space, with
            // a perspective divide making objects smaller in the distance). To build
            // a perpsective transform, we need the field of view (1/4 pi is common),
            // the aspect ratio, and the near and far clipping planes (which define
            // at what distances geometry should be no longer be rendered).
            device.Transform.Projection = Matrix.PerspectiveFovLH(
                (float)Math.PI / 4,
                1.0f,
                0.4f,
                10000.0f);
        }
 

        private void Calculate()
        {
 

            try
            {
                String line;
 
                int color,index1;
                float x, y, z;
 
                #region vertices creation
               
                using (StreamReader sr = new StreamReader(@"Mesh.txt"))
                {
                    if (MyMesh != null)
                    {
                        MyMesh.Dispose();
                        MyMesh = null;
                    }
                    NumberOfVertices = int.Parse(sr.ReadLine());
                   
                    MyMesh =new Mesh(NumberOfVertices/3, NumberOfVertices,
                        MeshFlags.VbManaged|MeshFlags.IbManaged, CustomVertex.PositionColored.Format, device);
                    //
                       CustomVertex.PositionColored[] arrayVertices =
                            new CustomVertex.PositionColored[NumberOfVertices];
 
                    for (int arrayIndex = 0; arrayIndex < NumberOfVertices; arrayIndex++)
                    {
                            line = sr.ReadLine();
                            x = float.Parse(line);
                            line = sr.ReadLine();
                            y = float.Parse(line);
                            line = sr.ReadLine();
                            z = float.Parse(line);
                            line = sr.ReadLine();
                            color = int.Parse(line);
                           
                            CustomVertex.PositionColored vertex = new CustomVertex.PositionColored(x, y, z, color);
 
                            arrayVertices[arrayIndex] = vertex;
                       
                    }
 
                   
                    line = sr.ReadLine();
                    NumberofIndices=int.Parse(line);
                    int[] arrayIndices = new int[NumberofIndices];
                    for (int arrayIndex = 0; arrayIndex < NumberofIndices; arrayIndex++)
                    {
                        line = sr.ReadLine();
                        index1 = int.Parse(line);
        
                        arrayIndices[arrayIndex] = index1;
 
                    }
                    AttributeRange attributeRange = new AttributeRange();
                    // There is only one attribute value for this mesh.
                    // By specifying an attribute range the DrawSubset function
                    // does not have to scan the entire mesh for all faces that are
                    // are marked with a particular attribute id.
                    attributeRange.AttributeId = 0;
                    attributeRange.FaceStart = 0;
                    attributeRange.FaceCount = arrayIndices.Length / 3;
                    attributeRange.VertexStart = 0;
                    attributeRange.VertexCount = arrayVertices.Length;
                    MyMesh.VertexBuffer.SetData(arrayVertices, 0, LockFlags.None);
                    MyMesh.IndexBuffer.SetData(arrayIndices, 0, LockFlags.None);
                    //MyMesh.LockAttributeBuffer(LockFlags.None);
                    MyMesh.SetAttributeTable(new AttributeRange[] { attributeRange });
                    //MyMesh.UnlockAttributeBuffer();
 
                }
                #endregion
 
            }
            catch (Direct3DXException e)
            {
                MessageBox.Show("Error in vertex creatioin:{0}", e.ToString());
            }
        }
       
    }
}
 
[/source]