MeshForm.cs
上传用户:lslight
上传日期:2022-01-10
资源大小:14248k
文件大小:24k
- ///////////////////////////////////////////////////////////////////////
- // ■■■■ ■■■■■ ■■■■ ■ ■ //
- // ■ ■ ■ ■ ■ //
- // ■ ■ ■ ■■■ ■ ■ //
- // ■ ■ ■ ■ ■ ■ //
- // ■■■■ ■ ■■■■ ■■■■ //
- // Copyright (c) 三峡大学水利与环境学院 肖泽云. All rights reserved. //
- ////////////////////////////////////////////////////////////////////////
- using System;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Windows.Forms;
- using Microsoft.DirectX;
- using Microsoft.DirectX.Direct3D;
- namespace Mesh网格
- {
- public partial class MeshForm : Form
- {
- Device device = null;//定义绘图设备
- private CustomVertex.PositionTextured[] vertices;//定义顶点变量
- private Texture texture;//定义贴图变量
- private Material material;//定义材质变量
- private float angleY=0.01f;//定义绕Y轴旋转变量
- private Vector3 CamPostion = new Vector3(0, 30, -30);//定义摄像机位置
- private Vector3 CamTarget = new Vector3(0, 0, 0);//定义摄像机目标位置
- private int mouseLastX,mouseLastY;//记录鼠标按下时的坐标位置
- private bool isRotateByMouse=false;//记录是否由鼠标控制旋转
- private bool isMoveByMouse = false;//记录是否由鼠标控制移动
- private Mesh meshObj;//定义网格对象
- private Material[] meshMaterials; //定义网格材质对象
- private Texture[] meshTextures; // 定义网格贴图对象
- private Mesh meshObjCopy;//定义复制的网格对象
- private ProgressiveMesh progMesh;//定义渐进网格对象
- private int numFaces;//定义渐进网格的面数目
- private AnimationRootFrame rootFrame;
- private Mesh[] meshArrayObj;//定义网格模型数组
- private Matrix[] meshPosition;//定义网格模型空间坐标数组
- public MeshForm()
- {
- this.ClientSize = new Size(800, 600);//指定窗体尺寸
- this.Text = "Mesh网格";//指定窗体标题
- }
- public bool InitializeDirect3D()
- {
- try
- {
- PresentParameters presentParams = new PresentParameters();
- presentParams.Windowed = true; //指定以Windows窗体形式显示
- presentParams.SwapEffect = SwapEffect.Discard; //当前屏幕绘制后它将自动从内存中删除
- presentParams.AutoDepthStencilFormat = DepthFormat.D16;
- presentParams.EnableAutoDepthStencil = true;
- presentParams.PresentationInterval = PresentInterval.Immediate;
- device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams); //实例化device对象
-
- //meshObj = Mesh.Box(device, 5f, 3f, 6f);//定义长方体几何对象
- meshObj = Mesh.Cylinder(device, 10f, 10f, 50f, 20, 20);//定义圆柱体对象
- //meshObj = Mesh.Polygon(device, 10f, 5);//定义五边形对象
- //meshObj = Mesh.Sphere(device, 10f, 20, 20);//定义球体对象
- //meshObj = Mesh.Torus(device, 2f, 6f, 20, 40);//定义圆环对象
- //meshObj = Mesh.Teapot(device);//定义茶壶对象
- //MeshDeclaration(20);//定义网格
- /*
- Vector3[] points = new Vector3[8];
- points[0] = new Vector3(0f, 3f, 0f);
- points[1] = new Vector3(0f, 3f, 6f);
- points[2] = new Vector3(5f, 3f, 6f);
- points[3] = new Vector3(5f, 3f, 0f);
- points[4] = new Vector3(0f, 0f, 0f);
- points[5] = new Vector3(0f, 0f, 6f);
- points[6] = new Vector3(5f, 0f, 6f);
- points[7] = new Vector3(5f, 0f, 0f);
- DrawHexClass drawHexClass = new DrawHexClass(device, points);
- //meshObj = drawHexClass.MeshObject;
- meshObj = DrawHexClass.DrawHexObject(device, points);
- */
- //从X文件导入网格
- //meshObj = Mesh.FromFile(@"E:DirectXDirectX_C#MediaModelsbox03.X", MeshFlags.SystemMemory, device);
- //MeshFromFile(@"E:DirectXDirectX_C#MediaModels", "box03.X");
- //meshObjCopy=meshObj.Clone(meshObj.Options.Value, meshObj.VertexFormat, device);
- int[] adjacency=new int[meshObj.NumberFaces*3];
- meshObj.GenerateAdjacency(0.01f,adjacency);
- progMesh = new ProgressiveMesh(meshObj, adjacency, meshObj.NumberFaces/30, MeshFlags.SimplifyFace);
- numFaces = meshObj.NumberFaces / 30;//设置渐进网格初始值
- //三维文字网格
- //System.Drawing.Font myFont = new System.Drawing.Font("Times New Roman", 28, FontStyle.Regular);//设置字体
- //meshObj = Mesh.TextFromFont(device, myFont, "Hello,DirectX!", 0.01f, 0.1f);
- VertexDeclaration();//定义顶点
- LoadTexturesAndMaterials();//导入贴图和材质
- //定义模型
- meshArrayObj = new Mesh[5];
- meshArrayObj[0] = Mesh.Cylinder(device, 1f, 1f, 5f, 10, 10);//定义圆柱体对象
- meshArrayObj[1] = Mesh.Polygon(device, 1f, 5);//定义五边形对象
- meshArrayObj[2] = Mesh.Sphere(device, 1f, 10, 10);//定义球体对象
- meshArrayObj[3] = Mesh.Torus(device, 0.2f, 0.6f, 10, 20);//定义圆环对象
- meshArrayObj[4] = Mesh.Teapot(device);//定义茶壶对象
- //定义模型坐标
- meshPosition = new Matrix[5];
- //meshPosition[0] = Matrix.Translation(0f,0f,-10f);
- meshPosition[0] = Matrix.RotationX((float)Math.PI/2) * Matrix.Translation(0f, 0f, -10f);
- meshPosition[1] = Matrix.Translation(-20f, 0f, 0f);
- meshPosition[2] = Matrix.Translation(-10f, 0f, 0f);
- //meshPosition[3] = Matrix.Translation(0f, 0f, 0f);
- meshPosition[3] = Matrix.RotationX((float)Math.PI / 2) * Matrix.Translation(0f, 0f, 0f);
- meshPosition[4] = Matrix.Translation(10f, 0f, 10f);
- return true;
- }
- catch (DirectXException e)
- {
- MessageBox.Show(e.ToString(), "Error"); //处理异常
- return false;
- }
- }
- private void MeshDeclaration(int count)//定义网格
- {
- //定义索引
- Int16[] arrayIndices = new Int16[(count - 1) * (count - 1) * 6];
- //定义顶点
- CustomVertex.PositionColored[] arrayVertices=new CustomVertex.PositionColored[count*count];
- //定义属性
- AttributeRange attributeRange=new AttributeRange();
- //实例化网格对象
- meshObj = new Mesh(arrayIndices.Length / 3, arrayVertices.Length, MeshFlags.SystemMemory, CustomVertex.PositionColored.Format, device);
- //设置顶点坐标值
- for (int i = 0; i < count; i++)
- {
- for (int j = 0; j < count; j++)
- {
- arrayVertices[j + i * count].X = (float)j;
- arrayVertices[j + i * count].Y = 0f;
- arrayVertices[j + i * count].Z = (float)i;
- arrayVertices[j + i * count].Color = Color.DarkGreen.ToArgb();
- }
- }
- //设置索引
- for (int i = 0; i < count - 1; i++)
- {
- for (int j = 0; j < count - 1; j++)
- {
- int num=6*(i*(count-1)+j);
- arrayIndices[num] = (Int16)(i * count + j);
- arrayIndices[num + 1] = (Int16)(i * count + j + 1);
- arrayIndices[num + 2] = (Int16)((i + 1) * count + j);
- arrayIndices[num + 3] = (Int16)(i * count + j + 1);
- arrayIndices[num + 4] = (Int16)((i + 1) * count + j + 1);
- arrayIndices[num + 5] = (Int16)((i + 1) * count + j);
- }
- }
- //设置属性
- attributeRange.AttributeId = 0;
- attributeRange.FaceStart = 0;
- attributeRange.FaceCount = arrayIndices.Length / 3;
- attributeRange.VertexStart = 0;
- attributeRange.VertexCount = arrayVertices.Length;
- //设置网格对象的索引缓冲和顶点缓冲数据
- meshObj.VertexBuffer.SetData(arrayVertices, 0, LockFlags.None);
- meshObj.IndexBuffer.SetData(arrayIndices, 0, LockFlags.None);
- meshObj.SetAttributeTable(new AttributeRange[] { attributeRange });
- }
- private void MeshFromFile(string xFilePath,string xFileName)//从文件导入网格
- {
- ExtendedMaterial[] materials;
- //从X文件导入网格
- meshObj = Mesh.FromFile(xFilePath + "\" + xFileName, MeshFlags.SystemMemory, device, out materials);
- if (meshTextures == null)
- {
- meshTextures = new Texture[materials.Length];
- meshMaterials = new Material[materials.Length];
- for (int i = 0; i < materials.Length; i++)
- {
- meshMaterials[i] = materials[i].Material3D;
- meshMaterials[i].Ambient = meshMaterials[i].Diffuse;
- // 创建贴图
- Console.WriteLine(i.ToString() + ":" + materials[i].ToString());
- meshTextures[i] = TextureLoader.FromFile(device, xFilePath + "\" + materials[i].TextureFilename);
- }
- }
- }
- private void VertexDeclaration()//定义顶点
- {
- vertices = new CustomVertex.PositionTextured[6];
- vertices[0].Position = new Vector3(10f, 0f, 10f);
- vertices[0].Tu = 1;
- vertices[0].Tv = 0;
- vertices[1].Position = new Vector3(-10f, 0f, -10f);
- vertices[1].Tu = 0;
- vertices[1].Tv = 1;
- vertices[2].Position = new Vector3(10f,0f,-10f);
- vertices[2].Tu = 1;
- vertices[2].Tv = 1;
- vertices[3].Position = new Vector3(-10f, 0f,-10f);
- vertices[3].Tu = 0;
- vertices[3].Tv = 1;
- vertices[4].Position = new Vector3(10f, 0f, 10f);
- vertices[4].Tu = 1;
- vertices[4].Tv = 0;
- vertices[5].Position = new Vector3(-10f, 0f, 10f);
- vertices[5].Tu = 0;
- vertices[5].Tv = 0;
- }
- private void LoadTexturesAndMaterials()//导入贴图和材质
- {
- material = new Material();
- material.Diffuse = Color.White;
- material.Ambient = Color.White;
- material.Specular = Color.LightGray;
- material.SpecularSharpness = 15.0F;
- device.Material = material;
- texture = TextureLoader.FromFile(device, "CTGU.jpg");
- }
- public void Render()
- {
- if (device == null) //如果device为空则不渲染
- {
- return;
- }
- SetUpCamera();
- device.Clear(ClearFlags.Target|ClearFlags.ZBuffer, Color.DarkSlateBlue, 1.0f, 0); //清除windows界面为深蓝色
- device.BeginScene();
- //在此添加渲染图形代码
- //device.RenderState.FillMode = FillMode.WireFrame;
- /*
- AttributeRange[] attributeRange = meshObj.GetAttributeTable();
- for (int i = 0; i < attributeRange.Length; i++)
- {
- Console.WriteLine("attributeRange[{0}].AttributeId:" + attributeRange[i].AttributeId.ToString(), i);
- Console.WriteLine("attributeRange[{0}].FaceCount:" + attributeRange[i].FaceCount.ToString(), i);
- Console.WriteLine("attributeRange[{0}].FaceStart:" + attributeRange[i].FaceStart.ToString(), i);
- Console.WriteLine("attributeRange[{0}].VertexCount:" + attributeRange[i].VertexCount.ToString(), i);
- Console.WriteLine("attributeRange[{0}].VertexStart:" + attributeRange[i].VertexStart.ToString(), i);
- }
- //获取邻接信息
- int[] adjacency = new int[meshObj.NumberFaces * 3];
- meshObj.GenerateAdjacency(0.01f, adjacency);
- for (int i = 0; i < adjacency.Length; i++)
- {
- Console.Write("adjacency[{0}]:{1} ", i,adjacency[i]);
- }
- */
- //绘制原始网格
- //device.Transform.World = Matrix.Add(device.Transform.World, Matrix.Translation(100f, 0f, 0f));
- //meshObj.DrawSubset(0);
- /*
- for (int i = 0; i < meshObj.NumberAttributes; i++)
- {
- //设置网格子集的材质和贴图
- device.Material = meshMaterials[i];
- device.SetTexture(0, meshTextures[i]);
- //绘制网格子集
- meshObj.DrawSubset(i);
- }
- */
- //绘制复制的网格
- //device.Transform.World = Matrix.Subtract(device.Transform.World, Matrix.Translation(100f, 0f, 0f));
- //progMesh.DrawSubset(0);
- //meshObjCopy.DrawSubset(0);
-
- //灯光设置
- device.RenderState.Lighting = true;
- device.Lights[0].Type = LightType.Directional;
- device.Lights[0].Diffuse = System.Drawing.Color.Red;
- device.Lights[0].Direction = new Vector3(-50.0f,50.0f,50.0f);
- device.Lights[0].Enabled = true; //打开灯光
- device.Lights[1].Type = LightType.Directional;
- device.Lights[1].Diffuse = System.Drawing.Color.Green;
- device.Lights[1].Direction = new Vector3(50f,-50.0f,50.0f);
- device.Lights[1].Enabled = true; //打开灯光
- device.RenderState.Ambient = Color.SlateGray;
-
- device.RenderState.CullMode=Cull.None;
- //device.SetTexture(0, texture);//设置贴图
- //device.VertexFormat = CustomVertex.PositionTextured.Format;
- //device.DrawUserPrimitives(PrimitiveType.TriangleList, 2, vertices);
- //device.RenderState.Lighting = false;
- for (int i = 0; i < meshArrayObj.Length; i++)
- {
- //设置当前世界矩阵
- device.Transform.World = meshPosition[i];
- meshArrayObj[i].DrawSubset(0);
- }
- device.EndScene();
- device.Present();
- }
- private void SetUpCamera()//摄像机
- {
- Matrix viewMatrix = Matrix.LookAtLH(CamPostion, CamTarget, new Vector3(0, 1, 0));
- device.Transform.Projection = Matrix.PerspectiveFovLH((float)Math.PI / 4, this.Width / this.Height, 1f, 500f);
- device.Transform.View = viewMatrix;
- }
- protected override void OnKeyDown(KeyEventArgs e)
- {
- Vector4 tempV4;
- Matrix currentView = device.Transform.View;//当前摄像机的视图矩阵
- if (Control.ModifierKeys== Keys.Control && e.KeyCode == Keys.S)
- {
- //定义衔接关系
- int[] adjacency = new int[meshObj.NumberFaces * 3];
- meshObj.GenerateAdjacency(0.01f, adjacency);
- //定义材质属性
- ExtendedMaterial[] exmaterials = new ExtendedMaterial[meshMaterials.Length];
- //设置材质
- for (int i = 0; i < meshMaterials.Length; i++)
- {
- exmaterials[i].Material3D = meshMaterials[i];
- exmaterials[i].TextureFilename = "";
- }
- meshObj.Save("SaveBox012.x", adjacency, exmaterials, XFileFormat.Text);
- MessageBox.Show("保存文件成功!");
- }
- switch (e.KeyCode)
- {
- case Keys.Left:
- CamPostion.Subtract(CamTarget);
- tempV4 = Vector3.Transform(CamPostion, Matrix.RotationQuaternion(
- Quaternion.RotationAxis(new Vector3(currentView.M12, currentView.M22, currentView.M32), -angleY)));
- CamPostion.X = tempV4.X + CamTarget.X;
- CamPostion.Y = tempV4.Y + CamTarget.Y;
- CamPostion.Z = tempV4.Z + CamTarget.Z;
- break;
- case Keys.Right:
- CamPostion.Subtract(CamTarget);
- tempV4 = Vector3.Transform(CamPostion, Matrix.RotationQuaternion(
- Quaternion.RotationAxis(new Vector3(currentView.M12, currentView.M22, currentView.M32), angleY)));
- CamPostion.X = tempV4.X + CamTarget.X;
- CamPostion.Y = tempV4.Y + CamTarget.Y;
- CamPostion.Z = tempV4.Z + CamTarget.Z;
- break;
- case Keys.Up:
- CamPostion.Subtract(CamTarget);
- tempV4 = Vector3.Transform(CamPostion, Matrix.RotationQuaternion(
- Quaternion.RotationAxis(new Vector3(device.Transform.View.M11
- , device.Transform.View.M21, device.Transform.View.M31), -angleY)));
- CamPostion.X = tempV4.X + CamTarget.X;
- CamPostion.Y = tempV4.Y + CamTarget.Y;
- CamPostion.Z = tempV4.Z + CamTarget.Z;
- break;
- case Keys.Down:
- CamPostion.Subtract(CamTarget);
- tempV4 = Vector3.Transform(CamPostion, Matrix.RotationQuaternion(
- Quaternion.RotationAxis(new Vector3(device.Transform.View.M11
- , device.Transform.View.M21, device.Transform.View.M31), angleY)));
- CamPostion.X = tempV4.X + CamTarget.X;
- CamPostion.Y = tempV4.Y + CamTarget.Y;
- CamPostion.Z = tempV4.Z + CamTarget.Z;
- break;
- case Keys.Add:
- CamPostion.Subtract(CamTarget);
- CamPostion.Scale(0.95f);
- CamPostion.Add(CamTarget);
- numFaces++;
- progMesh.NumberFaces = numFaces;
- break;
- case Keys.Subtract:
- CamPostion.Subtract(CamTarget);
- CamPostion.Scale(1.05f);
- CamPostion.Add(CamTarget);
- numFaces--;
- progMesh.NumberFaces = numFaces;
- break;
- }
- Console.WriteLine(numFaces.ToString());
- Matrix viewMatrix = Matrix.LookAtLH(CamPostion, CamTarget, new Vector3(0, 1, 0));
- device.Transform.View = viewMatrix;
- }
- protected override void OnMouseDown(MouseEventArgs e)
- {
- if (e.Button == MouseButtons.Left)
- {
- mouseLastX = e.X;
- mouseLastY = e.Y;
- isRotateByMouse = true;
- }
- else if (e.Button == MouseButtons.Middle)
- {
- mouseLastX = e.X;
- mouseLastY = e.Y;
- isMoveByMouse=true;
- }
- }
-
- protected override void OnMouseUp(MouseEventArgs e)
- {
- //base.OnMouseUp(e);
- /*float tempAngleY = 2*(float)(e.X - mouseLastX) / this.Width;
- Vector4 tempV4 = Vector3.Transform(CamPostion, Matrix.RotationQuaternion(
- Quaternion.RotationAxis(new Vector3(0, 1, 0), tempAngleY)));
- CamPostion.X = tempV4.X; CamPostion.Y = tempV4.Y; CamPostion.Z = tempV4.Z;
- Matrix viewMatrix = Matrix.LookAtLH(CamPostion, CamTarget, new Vector3(0, 1, 0));
- device.Transform.View = viewMatrix;
- */
- isRotateByMouse = false;
- isMoveByMouse = false;
- }
- protected override void OnMouseMove(MouseEventArgs e)
- {
- if (isRotateByMouse)
- {
- Matrix currentView = device.Transform.View;//当前摄像机的视图矩阵
- float tempAngleY = 2 * (float)(e.X - mouseLastX) / this.Width;
- CamPostion.Subtract(CamTarget);
- Vector4 tempV4 = Vector3.Transform(CamPostion, Matrix.RotationQuaternion(
- Quaternion.RotationAxis(new Vector3(currentView.M12, currentView.M22, currentView.M32), tempAngleY)));
- CamPostion.X = tempV4.X;
- CamPostion.Y = tempV4.Y;
- CamPostion.Z = tempV4.Z;
- float tempAngleX = 4 * (float)(e.Y - mouseLastY) / this.Height;
- tempV4 = Vector3.Transform(CamPostion, Matrix.RotationQuaternion(
- Quaternion.RotationAxis(new Vector3(currentView.M11, currentView.M21, currentView.M31), tempAngleX)));
- CamPostion.X = tempV4.X + CamTarget.X;
- CamPostion.Y = tempV4.Y + CamTarget.Y;
- CamPostion.Z = tempV4.Z + CamTarget.Z;
- Matrix viewMatrix = Matrix.LookAtLH(CamPostion, CamTarget, new Vector3(0, 1, 0));
- device.Transform.View = viewMatrix;
- mouseLastX = e.X;
- mouseLastY = e.Y;
- }
- else if (isMoveByMouse)
- {
- Matrix currentView = device.Transform.View;//当前摄像机的视图矩阵
- float moveFactor=0.01f;
- CamTarget.X += -moveFactor * ((e.X - mouseLastX) * currentView.M11 - (e.Y - mouseLastY) * currentView.M12);
- CamTarget.Y += -moveFactor * ((e.X - mouseLastX) * currentView.M21 - (e.Y - mouseLastY) * currentView.M22);
- CamTarget.Z += -moveFactor * ((e.X - mouseLastX) * currentView.M31 - (e.Y - mouseLastY) * currentView.M32);
- CamPostion.X +=- moveFactor * ((e.X - mouseLastX) * currentView.M11 - (e.Y - mouseLastY) * currentView.M12);
- CamPostion.Y += -moveFactor * ((e.X - mouseLastX) * currentView.M21 - (e.Y - mouseLastY) * currentView.M22);
- CamPostion.Z += -moveFactor * ((e.X - mouseLastX) * currentView.M31 - (e.Y - mouseLastY) * currentView.M32);
-
- Matrix viewMatrix = Matrix.LookAtLH(CamPostion, CamTarget, new Vector3(0, 1, 0));
- device.Transform.View = viewMatrix;
- mouseLastX = e.X;
- mouseLastY = e.Y;
- }
- }
- protected override void OnMouseWheel(MouseEventArgs e)
- {
- float scaleFactor = -(float)e.Delta / 2000 + 1f;
- CamPostion.Subtract(CamTarget);
- CamPostion.Scale(scaleFactor);
- CamPostion.Add(CamTarget);
- Matrix viewMatrix = Matrix.LookAtLH(CamPostion, CamTarget, new Vector3(0, 1, 0));
- device.Transform.View = viewMatrix;
- }
- static void Main()
- {
- MeshForm CameraTransform = new MeshForm(); //创建窗体对象
- if (CameraTransform.InitializeDirect3D() == false) //检查Direct3D是否启动
- {
- MessageBox.Show("无法启动Direct3D!", "错误!");
- return;
- }
- CameraTransform.Show(); //如果一切都初始化成功,则显示窗体
- while (CameraTransform.Created) //设置一个循环用于实时更新渲染状态
- {
- CameraTransform.Render(); //保持device渲染,直到程序结束
- //CameraTransform.SetUpCamera();//建立摄像机
- Application.DoEvents(); //处理键盘鼠标等输入事件
- }
- }
- }
- }