程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> DirectX 3D 之C#開發

DirectX 3D 之C#開發

編輯:C#基礎知識

C#下進行directX3D開發,一個旋轉的4稜錐的例子。

建議看兩個文檔<Managed DirectX 9圖形和游戲編程簡略中文文檔>和<Managed DirectX 9 SDK 中文文檔>。

另外最好下載個DirectX SDK (August 2007).rar。裡面有些范例還是非常好的。

一、首先在電腦上裝了DirectX。

二、建立一個C#的Windows應用程序,添加兩個引用Microsoft.DirectX和Microsoft.DirectX.Direct3D;

三、Form1.cs

具體代碼如下:

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;          //開發directx需要包含的兩個命名空間
using Microsoft.DirectX.Direct3D;

 

namespace Rectangle
{
    public partial class form1 : Form
    {
        
        /// <summary>
        /// 設備對象,場景中所有圖形對象的父對象
        /// </summary>
        private Device device = null; 

        /// <summary>
        /// 坐標系四稜錐頂點緩沖
        /// </summary>
        VertexBuffer vertexBuffer = null; 

        /// <summary>
        /// 此參數設置為必須,它定義了要創建的Direct3D設備的表示參數,如後台緩沖區的高度、寬度和像素格式、如何從後台緩沖區復制到前台緩存、以及屏幕顯示的方式等等
        /// </summary>
        PresentParameters presentParameters = new PresentParameters();
        
        /// <summary>
        /// 暫停標志
        /// </summary>
        bool pause = false;

        /// <summary>
        /// 隨機數,用來生成隨機顏色用的
        /// </summary>
        Random rn = new Random();

        /// <summary>
        /// 構造函數,設置窗體大小
        /// </summary>
        public form1()
        {
            this.ClientSize = new System.Drawing.Size(300, 300);
        }

        /// <summary>
        /// 初始化繪圖環境
        /// </summary>
        /// <returns></returns>
        public bool InitializeGraphics()
        {
            try
            {
                //設置屏幕顯示模式為窗口模式
                presentParameters.Windowed = true;
                //設置如何從後台緩沖區復制到前台緩沖區(SwapEffect.Discard表示緩沖區在顯示後立即被捨棄,這樣可以節省開銷)
                presentParameters.SwapEffect = SwapEffect.Discard;
                //創建一個設備
                device = new Device(0, DeviceType.Hardware, this, CreateFlags.SoftwareVertexProcessing, presentParameters);
                //為設備釋放訂閱事件處理
                device.DeviceReset += new System.EventHandler(this.OnResetDevice);
                
                this.OnCreateDevice(device, null);
                this.OnResetDevice(device, null);
                pause = false;
                return true;
            }

            catch (DirectXException)
            {
                return false;
            }
        }

        /// <summary>
        /// 設備創建時建立頂點緩沖
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnCreateDevice(object sender, EventArgs e)
        {
            Device dev = (Device)sender;

            //創建頂點緩沖,有個頂點
            vertexBuffer = new VertexBuffer(typeof(CustomVertex.PositionColored), 18, dev, 0, CustomVertex.PositionColored.Format, Pool.Default);
            //為創建頂點緩存訂閱事件處理
            vertexBuffer.Created += new System.EventHandler(this.OnCreateVertexBuffer);

            this.OnCreateVertexBuffer(vertexBuffer, null);
        }


        /// <summary>
        /// 設備撤銷的事件處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnResetDevice(object sender, EventArgs e)
        {
            Device dev = (Device)sender;
            //關閉剔除模式,使我們能看見此四稜錐的前面和後面
            dev.RenderState.CullMode = Cull.None;
            // 關閉場景裡的燈光,顯示頂點自己的顏色
            dev.RenderState.Lighting = false;
        }

        /// <summary>
        /// 創建頂點緩存的事件處理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnCreateVertexBuffer(object sender, EventArgs e)
        {
            
            VertexBuffer vb = (VertexBuffer)sender;
            CustomVertex.PositionColored[] verts = (CustomVertex.PositionColored[])vb.Lock(0, 0);
            
            //四稜錐原始的個點
            Vector3 vertex1 = new Vector3(25, 0, 0);
            Vector3 vertex2 = new Vector3(0, 0, -25);
            Vector3 vertex3 = new Vector3(-25, 0, 0);
            Vector3 vertex4 = new Vector3(0, 0, 25);
            Vector3 vertex5 = new Vector3(0, 25, 0);

            //四稜錐中包含個三角形,所以要構造個點來繪制
            verts[0].Position = vertex1;
            verts[1].Position = vertex2;
            verts[2].Position = vertex5;
            verts[3].Position = vertex2;
            verts[4].Position = vertex3;
            verts[5].Position = vertex5;
            verts[6].Position = vertex3;
            verts[7].Position = vertex4;
            verts[8].Position = vertex5;
            verts[9].Position = vertex4;
            verts[10].Position = vertex1;
            verts[11].Position = vertex5;
            verts[12].Position = vertex2;
            verts[13].Position = vertex1;
            verts[14].Position = vertex3;
            verts[15].Position = vertex3;
            verts[16].Position = vertex1;
            verts[17].Position = vertex4;


            //給每個點賦予隨機顏色
            for (int i = 0; i < 18; i++)
            {
                verts[i].Color = Color.FromArgb(SetColor(), SetColor(), SetColor()).ToArgb();

            }
                vb.Unlock();

 

        }

        /// <summary>
        /// 返回到之間的一個隨機數,用來生成隨機顏色
        /// </summary>
        /// <returns></returns>
        public int SetColor()
        {
            int number = rn.Next(256);
            return number;
        }


        /// <summary>
        /// 設置攝像機的位置
        /// </summary>
        private void SetupCamera()
        {
            //設置世界矩陣,根據系統運行時間而變化
            device.Transform.World = Matrix.RotationAxis(new Vector3((float)Math.Cos(Environment.TickCount / 250.0f), 1, (float)Math.Sin(Environment.TickCount / 250.0f)), Environment.TickCount / 3000.0f);
            //設置攝像機的位置,它在z軸上-50處,看著原點,y軸為正方向
            device.Transform.View = Matrix.LookAtLH(new Vector3(0.0f, 0.0f, -50f), new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 1.0f, 0.0f));

            //設置攝像機的視界,角度為度,看的最近為,看的最遠處為.不再這個視界中的影像都不會被顯示
            device.Transform.Projection = Matrix.PerspectiveFovLH(((float)(float)Math.PI / 2 ), 1.0f, 10.0f, 200.0f);
        }


        /// <summary>
        /// 繪制圖形
        /// </summary>
        public void Render()
        {
            if (device == null)
                return;

            if (pause)
                return;

            //背景設為綠色
            device.Clear(ClearFlags.Target, System.Drawing.Color.Blue, 1.0f, 0);
            //開始場景
            device.BeginScene();
            // 設置世界,視野和投影矩陣
            SetupCamera();

            // 給設備指定頂點緩存
            device.SetStreamSource(0, vertexBuffer, 0);

            //設置設備的頂點格式
            device.VertexFormat = CustomVertex.PositionColored.Format;

            //繪制圖形,使用的方法為三角形列表,個數為個
            device.DrawPrimitives(PrimitiveType.TriangleList, 0, 6);
                        
            //結束場景
            device.EndScene();

            //更新場景
            device.Present();
        }

        //重載OnPaint函數
        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            //繪制圖形
            this.Render(); 
        }
    }
}

四,program.cs中的代碼為:

using System;
using System.Collections.Generic;
using System.Windows.Forms;

 

namespace Rectangle
{
    static class Program
    {
        /// <summary>
        /// 應用程序的主入口點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            using (form1 frm = new form1())
            {

                if (!frm.InitializeGraphics()) // 初始化 Direct3D
                {
                    MessageBox.Show("不能初始化 Direct3D.程序將退出.");
                    return;
                }
                frm.Show();

                // While the form is still valid, render and process messages
                while (frm.Created)
                {
                    frm.Render();
                    Application.DoEvents(); //處理當前在消息隊列中的所有 Windows 消息
                }
            }
        }
    }
}
 

運行後你會看到一個不斷旋轉的四稜錐。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved