C++ Programmer's Cookbook

{C++ 基础} {C++ 高级} {C#界面,C++核心算法} {设计模式} {C#基础}

Managed DirectX --- create Device

// -----------------------------------------------------------------------------
//  File: CreateDevice.cs
//
//  Desc: This is the first tutorial for using Direct3D. In this tutorial, all
//        we are doing is creating a Direct3D device and using it to clear the
//        window.
//
//  Copyright (c) Microsoft Corporation. All rights reserved.
// -----------------------------------------------------------------------------
using  System;
using  System.Drawing;
using  System.Windows.Forms;
using  Microsoft.DirectX;
using  Microsoft.DirectX.Direct3D;

namespace  DeviceTutorial
{
    
public   class  CreateDevice : Form
    
{
        
//  Our global variables for this project
        Device device  =   null //  Our rendering device

        
public  CreateDevice()
        
{
            
//  Set the initial size of our form
             this .ClientSize  =   new  System.Drawing.Size( 400 , 300 );
            
//  And it's caption
             this .Text  =   " D3D Tutorial 01: CreateDevice " ;
        }

        
        
public   bool  InitializeGraphics()
        
{
            
try
            
{
                
//  Now let's setup our D3D stuff
                PresentParameters presentParams  =   new  PresentParameters();
                presentParams.Windowed
= true ;
                presentParams.SwapEffect 
=  SwapEffect.Discard;
                device 
=   new  Device( 0 , DeviceType.Hardware,  this , CreateFlags.SoftwareVertexProcessing, presentParams);
                
return   true ;
            }

            
catch  (DirectXException)
            

                
return   false
            }

        }

        
private   void  Render()
        
{
            
if  (device  ==   null
                
return ;

            
// Clear the backbuffer to a blue color 
            device.Clear(ClearFlags.Target, System.Drawing.Color.Blue,  1.0f 0 );
            
// Begin the scene
            device.BeginScene();
            
            
//  Rendering of scene objects can happen here
    
            
// End the scene
            device.EndScene();
            device.Present();
        }

        
protected   override   void  OnPaint(System.Windows.Forms.PaintEventArgs e)
        
{
            
this .Render();  //  Render on painting
        }

        
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
        }


        
///   <summary>
        
///  The main entry point for the application.
        
///   </summary>

         static   void  Main() 
        
{

            
using  (CreateDevice frm  =   new  CreateDevice())
            
{
                
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();
                }

            }

        }

    }

}


1 creating the Direct3D device
   PresentParameters object that is used to set the windows display characteristics.      presentParameters 用来设置windows的特征. 她的windowed设为  true  表示以窗口显示,没有菜单和子窗口,但是有最大,最小和关闭button.
2 Device的构造函数中,指定了hardware device是优先的,顶点的处理有软件来处理.但是如果我们有好的显卡且我们设置  CreateFlags.HardwareVertexProcessing参数,则我们有更好的性能.
3  Application.DoEvents(); 不能没有,否则窗口不接受消息,一直render().
4 Device.Clear method使窗口颜色被设置为blue. Device.BeginScene则真正开始render. the EndScene and Present methods 表示完成render.

包含检查硬件的支持:
//------------------------------------------------------------------------------
//           Name: dx9cs_initialization.cs
//         Author: Kevin Harris
//  Last Modified: 06/15/05
//    Description: This sample demonstrates how to initialize Direct3D.
//------------------------------------------------------------------------------

using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace DX9Sample
{
    
public class DX9Form : System.Windows.Forms.Form
    
{
        
private Device d3dDevice = null;

        
public DX9Form()
        
{
            
this.ClientSize = new System.Drawing.Size( 640480 );
            
this.Text = "Direct3D (DX9/C#) - Initialization";
            
this.SetStyle( ControlStyles.AllPaintingInWmPaint | ControlStyles.Opaque, true );
        }


        
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        
{
            
this.Render();
            
this.Invalidate();
        }


        
protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e)
        
{
            
switch( e.KeyCode )
            
{
                
case System.Windows.Forms.Keys.Escape:
                    
this.Dispose();
                    
break;
            }

        }


        
protected override void Dispose(bool disposing)
        
{
            
base.Dispose( disposing );
        }


        
static void Main() 
        
{
            
using( DX9Form frm = new DX9Form() )
            
{
                frm.Show();
                frm.Init();
                Application.Run( frm );
            }

        }


        
/// <summary>
        
/// This method basically creates and initialize the Direct3D device and
        
/// anything else that doens't need to be recreated after a device 
        
/// reset.
        
/// </summary>

        private void Init() 
        
{
            
// Does the hardware support a 16-bit z-buffer?
            if!Manager.CheckDeviceFormat( Manager.Adapters.Default.Adapter, 
                                           DeviceType.Hardware,
                                           Manager.Adapters.Default.CurrentDisplayMode.Format, 
                                           Usage.DepthStencil,
                                           ResourceType.Surface,
                                           DepthFormat.D16 ) )
            
{
                
// POTENTIAL PROBLEM: We need at least a 16-bit z-buffer!
                return;
            }


            
//
            
// Do we support hardware vertex processing? if so, use it. 
            
// If not, downgrade to software.
            
//

            Caps caps 
= Manager.GetDeviceCaps( Manager.Adapters.Default.Adapter, 
                                               DeviceType.Hardware );
            CreateFlags flags;

            
if( caps.DeviceCaps.SupportsHardwareTransformAndLight )
                flags 
= CreateFlags.HardwareVertexProcessing;
            
else
                flags 
= CreateFlags.SoftwareVertexProcessing;

            
//
            
// Everything checks out - create a simple, windowed device.
            
//

            PresentParameters d3dpp 
= new PresentParameters();

            d3dpp.BackBufferFormat       
= Format.Unknown;
            d3dpp.SwapEffect             
= SwapEffect.Discard;
            d3dpp.Windowed               
= true;
            d3dpp.EnableAutoDepthStencil 
= true;
            d3dpp.AutoDepthStencilFormat 
= DepthFormat.D16;
            d3dpp.PresentationInterval   
= PresentInterval.Immediate; 

            d3dDevice 
= new Device( 0, DeviceType.Hardware, this, flags, d3dpp );

            
// Register an event-handler for DeviceReset and call it to continue
            
// our setup.
            d3dDevice.DeviceReset += new System.EventHandler( this.OnResetDevice );
            OnResetDevice( d3dDevice, 
null );
        }


        
/// <summary>
        
/// This event-handler is a good place to create and initialize any 
        
/// Direct3D related objects, which may become invalid during a 
        
/// device reset.
        
/// </summary>

        public void OnResetDevice(object sender, EventArgs e)
        
{
            
// This sample doens't create anything that requires recreation 
            
// after the DeviceReset event.
        }


        
private void Render()
        
{
            d3dDevice.Clear( ClearFlags.Target 
| ClearFlags.ZBuffer, 
                             Color.FromArgb(
25502550), 1.0f0 );

            d3dDevice.BeginScene();
            
            
// Render geometry here
    
            d3dDevice.EndScene();

            d3dDevice.Present();
        }

    }

}


posted on 2006-05-09 18:31 梦在天涯 阅读(1147) 评论(1)  编辑 收藏 引用 所属分类: DirectX

评论

# re: Managed DirectX --- create Device 2006-05-17 17:31 梦在天涯

Managed DirectX是对DirectX大部分功能的托管封装,可以用任何支持.NET的语言开发。MDX只对DirectX做了非常低层次的封装,因此保持了用COM接口DirectX开发时的大部分原貌。MDX的性能是不用担心的,因为它还是象COM DirectX一样提供对硬件层次的访问,大部分功能都是在你的显卡/网卡/声卡上起作用的,托管部分只是它的接口。事实证明MDX在DirectX Graphics中的性能与COM接口的DirectX不相上下。既然MDX的开发方式、API和性能都与COM接口的DirectX差不多,那为什么要用MDX呢?我自己对这个问题的回答是:

1、托管代码的对象模型更好。MDX基于类库的组织结构,比用COM接口的处理方式更方便。
2、用MDX,一般不用操心资源释放的问题。很大一部分资源释放的操作,都被封装好了。
3、与更多现代技术结合得更好。我们可以让DirectX程序使用XML、WebService和智能客户端等技术。

Direct3D程序最基本的流程是:创建Windows窗口、创建设备、处理消息循环、物体图形显示、退出和清理。在MDX的世界里,窗口创建和处理消息循环我们交给Windows Forms模型来做,剩下最主要的任务就是创建设备和物体图形显示。Direct3D设备是Direct3D开发最基本的入口,它定义了Direct3D所有的绘图组件,大部分的操作都需要从Direct3D设备开始。创建设备需要设定几个参数,包括显卡序号、设备类型、所属窗口、3D运算方式等。除了这些信息外,还需要一个PresentParameters类型的参数,其中定义了Direct3D设备所需的相关信息。下面代码中的InitializeDirect3D函数完整的演示了创建设备的步骤

设备类型:Direct3D支持3种设备,其中HAL和REF最为重要。HAL通过硬件进行光栅化、坐标变换和光照处理等,速度最快。REF则是用软件实现相关的操作,仅用于硬件不支持某种操作的情况。DeviceType枚举定义了设备类型可能的选项。

3D运算方式包括一些选项,如HardwareVertexProcessing,PureHardwareVertexProcessing等,用于指定顶点运算由硬件执行还是软件执行等。

PresentParameters还包括一些设置,如后台缓冲区的高度、宽度和像素格式,以及从后台缓冲区复制到前台缓存屏幕显示的方式等等。如果Direct3D采用窗口方式运行,像素格式必须查询当前的显示模式获得。

Direct3D设备创建成功以后,就可以进入图形显示阶段。在下面的代码中以Render()函数的形式出现。在绘制图形前,需要调用Device::Clear()函数重制ViewPort的颜色缓冲区。ViewPort就是3D形状投射到平面显示器上供我们看到的那个区域。Clear函数的Flag参数指定了对颜色缓冲区、深度缓冲区还是模板缓冲区进行初始化。因为我用ATI显卡,所以我选择了将颜色缓冲区初始化为红色:)。接下来是调用BeginScene()函数和EndScene()函数。实际的绘图中,所有渲染的代码都必须放在BeginScene函数和EndScene函数之间,否则就会出错。最后调用Present()函数,将后台缓冲区中的数据复制到前台缓冲区,我们就能看见图形了。

  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


公告

EMail:itech001#126.com

导航

统计

  • 随笔 - 461
  • 文章 - 4
  • 评论 - 746
  • 引用 - 0

常用链接

随笔分类

随笔档案

收藏夹

Blogs

c#(csharp)

C++(cpp)

Enlish

Forums(bbs)

My self

Often go

Useful Webs

Xml/Uml/html

搜索

  •  

积分与排名

  • 积分 - 1785074
  • 排名 - 5

最新评论

阅读排行榜