近期一直在研究关于DirectX处理.X文件方面的知识,走了很多的弯路,也感觉浪费了很多时间。记得之前看过一篇大神写的博客,说是不管某一方面的知识多么简单,但总会有“外行“,总还是会有一些人不太了解,所以写下这篇博客分享下,也许你会用到。
private Device device = null;//定义绘图设备
private Mesh meshObj = null;//定义网格对象
private Material[] meshMaterials;//定义网格材质对象
private Texture[] meshTextures;//定义网格贴图对象
ExtendedMaterial[] materials;//用于保存材质信息
private void MeshFromFile(string xFilePath, string xFileName)//从文件导入网格
{
//从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;
//导入贴图
//meshTextures[i] = TextureLoader.FromFile(device,xFilePath + "\\" + materials[i].TextureFilename);
}
}
}
public bool InitializeDirect3D()
{
try
{
PresentParameters presentParams = new PresentParameters();
presentParams.Windowed = true; //指定以Windows窗体形式显示
presentParams.SwapEffect = SwapEffect.Discard; //当前屏幕绘制后它将自动从内存中删除
device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParams); //实例化device对象
MeshFromFile(@"C:\Users\Administrator\Desktop", "jian8.x");
return true;
}
catch (DirectXException e)
{
MessageBox.Show(e.ToString(), "Error"); //处理异常
return false;
}
}
///
/// 定义渲染函数
///
public void Render()
{
if (device == null) //如果device为空则不渲染
{
return;
}
device.Clear(ClearFlags.Target, Color.LightSkyBlue, 1.0f, 0); //清除windows界面为深蓝色
device.BeginScene();
// 1.设备基本绘制参数设置
device.RenderState.ZBufferEnable = true;
device.RenderState.CullMode = Cull.None;
device.RenderState.Lighting = true;
device.RenderState.AmbientColor = 0x808080;
device.RenderState.NormalizeNormals = true;
//加灯光
device.Lights[0].Diffuse = Color.FromArgb(255, 255, 255);
device.Lights[0].Type = LightType.Directional;
device.Lights[0].Direction = new Vector3(1f, 1f, 1f);
device.Lights[0].Enabled = true;
// 纹理采样的uv设置
device.SamplerState[0].AddressU = TextureAddress.Wrap;
device.SamplerState[0].AddressV = TextureAddress.Wrap;
// 透明通道的开启
device.RenderState.AlphaBlendEnable = true;
device.TextureState[0].ColorArgument1 = TextureArgument.TextureColor;
device.TextureState[0].ColorOperation = TextureOperation.SelectArg1;
//在此添加渲染图形代码
for (int i = 0; i < meshMaterials.Length; i++)
{
//设置网格子集的材质和贴图
device.Material = meshMaterials[i];
//device.SetTexture(0, meshTextures[i]);
//绘制网格子集
meshObj.DrawSubset(i);
}
device.EndScene();
device.Present();
}
static void Main()
{
BasicForm basicForm = new BasicForm(); //创建窗体对象
if (basicForm.InitializeDirect3D() == false) //检查Direct3D是否启动
{
MessageBox.Show("无法启动Direct3D!", "错误!");
return;
}
basicForm.Show(); //如果一切都初始化成功,则显示窗体
while (basicForm.Created) //设置一个循环用于实时更新渲染状态
{
basicForm.Render(); //保持device渲染,直到程序结束
basicForm.SetUpCamera();
Application.DoEvents(); //处理键盘鼠标等输入事件
}
}