Direct3D9 教程02

其实我自己也还没有完全明白,所以还只简单的把正文档注释了一下,等我研究研究再补充! 
// 顶点渲染
// 暂时还没有怎么明白这个概念
#include  < d3d9.h >
#pragma  warning( disable : 4996 )  //  消除4996警告
#include 
< strsafe.h >
#pragma  warning( default : 4996 )


// 全局变量
LPDIRECT3D9             g_pD3D        =  NULL;  //  D3D驱动
LPDIRECT3DDEVICE9       g_pd3dDevice  =  NULL;  //  渲染设备
LPDIRECT3DVERTEXBUFFER9 g_pVB         =  NULL;  //  顶点渲染缓存句柄

//  顶点渲染结构体
struct  CUSTOMVERTEX
{
    FLOAT x, y, z, rhw; 
// 顶点象素位置装换,x,y为平面坐标系的位置,z是纵深,rhw齐次坐标W的倒数。
    DWORD color;        // 颜色
}
;

//  灵活顶点格式 FVF, 也就是告诉D3D我们的顶点渲染结构体是怎么定义的
#define  D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE) // 变换顶点+漫反射色

// -----------------------------------------------------------------------------
//  名称: InitD3D()
//  描述: 初始化 Direct3D
// -----------------------------------------------------------------------------
HRESULT InitD3D( HWND hWnd )
{
    
// 根据版本创建D3D对象
    if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
        
return E_FAIL;

    
//设置参数
    D3DPRESENT_PARAMETERS d3dpp;                //参数对象,用于下面的设备创建
    ZeroMemory( &d3dpp, sizeof(d3dpp) );        //用0来填充d3dpp内存区域,也就是初始化内存
    d3dpp.Windowed = TRUE;                        //设置为窗口模式
    d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;    //交换缓冲支持的效果类型,指定表面在交换链中是如何被交换的。这里为后备的缓存加载之后就删除。
    d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;    //显示模式

    
//创建设备驱动Direct3D
    if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT,                        //默认适配器
                                      D3DDEVTYPE_HAL,                            //硬件驱动 
                                      hWnd,                                        //设备所使用的窗体
                                      D3DCREATE_SOFTWARE_VERTEXPROCESSING,        //顶点像素渲染方式
                                      &d3dpp,                                    //参数
                                      &g_pd3dDevice                                //驱动设备
                                      ) ) )
    
{
        
return E_FAIL;
    }


    
// 初始化完成

    
return S_OK;
}


// -----------------------------------------------------------------------------
//  名称: InitVB()
//  描述: 初始化顶点渲染缓存
// -----------------------------------------------------------------------------
HRESULT InitVB()
{
    
// 初始化用于渲染三角形的三个顶点
    CUSTOMVERTEX Vertices[] =
    
{
        
150.0f,  50.0f0.5f1.0f0xffff0000, }// x, y, z, rhw, color
        250.0f250.0f0.5f1.0f0xff00ff00, },
        
{  50.0f250.0f0.5f1.0f0xff00ffff, },
    }
;

    
//创建缓存
    if( FAILED( g_pd3dDevice->CreateVertexBuffer( 3*sizeof(CUSTOMVERTEX),                //缓存的大小
                                                  0,                                    //高级应用:指定关于怎样使用缓存的额外信息
                                                  D3DFVF_CUSTOMVERTEX,                    //灵活顶点格式,使用的是前面定的宏
                                                  D3DPOOL_DEFAULT,                        //告诉D3D将顶点缓冲存储在内存中的哪个位置
                                                  &g_pVB,                                //返回来的指向IDirect3DVertexBuffer9的指针
                                                  NULL                                    //参数,无用,NULL 微软原打算弄个共享句柄之类
                                                  ) ) )
    
{
        
return E_FAIL;
    }


    
// 现在要做的就是把之前保存在数组中的顶点信息放在顶点缓冲区里面
    VOID* pVertices;
    
if( FAILED( g_pVB->Lock( 0,                                    //指定要开始锁定的缓冲区的位置。
                             sizeof(Vertices),                    //指定在锁定的缓冲区的大小。
                             (void**)&pVertices,                //用来保存返回的指向顶点缓冲区的指针。
                             0                                    //一些高级设置,只读之类的属性
                             ) ) )
        
return E_FAIL;
    
//填充数据
    memcpy( pVertices,                        //填充对象:顶点缓冲区的指针
            Vertices,                        //原数据
            sizeof(Vertices)                //填充的大小
            );
    
//填充完了,解锁
    g_pVB->Unlock();

    
return S_OK;
}



// -----------------------------------------------------------------------------
//  名称: Cleanup()
//  描述: 释放所有初始化对象
// -----------------------------------------------------------------------------
VOID Cleanup()
{
    
if( g_pVB != NULL )        
        g_pVB
->Release();

    
if( g_pd3dDevice != NULL ) 
        g_pd3dDevice
->Release();

    
if( g_pD3D != NULL )       
        g_pD3D
->Release();
}


// -----------------------------------------------------------------------------
//  名称: Render()
//  描述: 绘制场景
// -----------------------------------------------------------------------------
VOID Render()
{
    
if( NULL == g_pd3dDevice )
        
return;

    
//清除背景缓存并重新设置为蓝色    
    g_pd3dDevice->Clear( 0,                             // pRects中的矩形数,如果 pRects为NULL着该参数必须为0
                         NULL,                         //一个指向D3DRECT结构体的指针
                         D3DCLEAR_TARGET,             //D3DCLEAR标志,现在为清空当前的渲染器
                         D3DCOLOR_XRGB(0,0,255),     //颜色    
                         1.0f,                         // depth buffer的新z值
                         0                             //模板
                         );

    
// Begin the scene
    if( SUCCEEDED( g_pd3dDevice->BeginScene() ) )
    
{    
        
//来告诉D3D要渲染哪个顶点缓冲区里面的顶点
        g_pd3dDevice->SetStreamSource( 0,                        //设置数据流的数量,顶点缓冲得个数
                                       g_pVB,                    //要与数据流绑定的数据
                                       0,                        //设置从哪个位置开始读数据
                                       sizeof(CUSTOMVERTEX)        //数据流里面数据单元的大小
                                       );
        g_pd3dDevice
->SetFVF( D3DFVF_CUSTOMVERTEX );            //灵活顶点格式(这东西好几个地方都要设置麻烦!)
        
//来渲染顶点缓冲中的顶点
        g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST,        //渲染的基本类型的标志: D3DPT_TRIANGLELIST 这个标志来说明要渲染的是一个三角形带
                                     0,                            //读取得第一个顶点的索引值
                                     1                            //参数用来说明有多少个基本类型要渲染
                                     );

        
// 结束渲染
        g_pd3dDevice->EndScene();
    }


    
// 来显示翻转链中下一个缓冲区内容
    g_pd3dDevice->Present( NULL, NULL, NULL, NULL );
}


// -----------------------------------------------------------------------------
//  名称: MsgProc()
//  描述: Windows窗体句柄,这里和一个教程不太一样,没有怎么明白…………为什么要这样做
// -----------------------------------------------------------------------------
LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    
switch( msg )
    
{
        
case WM_DESTROY:
            Cleanup();
            PostQuitMessage( 
0 );
            
return 0;
    }


    
return DefWindowProc( hWnd, msg, wParam, lParam );
}



// -----------------------------------------------------------------------------
//  名称: WinMain()
//  描述: 应用程序入口
// -----------------------------------------------------------------------------
INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, INT )
{
    
// //直接初始化结构体
    WNDCLASSEX wc = sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L0L,
                      GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
                      
"D3D Tutorial", NULL }
;
    
//注册窗体类
    RegisterClassEx( &wc );

    
// Create the application's window
    HWND hWnd = CreateWindow( "D3D Tutorial""D3D Tutorial 02: Vertices",
                              WS_OVERLAPPEDWINDOW, 
100100300300,
                              NULL, NULL, wc.hInstance, NULL );

    
// 初始化 Direct3D
    if( SUCCEEDED( InitD3D( hWnd ) ) )
    
{
        
// 创建顶点渲染缓存
        if( SUCCEEDED( InitVB() ) )
        
{
            
// 显示窗体
            ShowWindow( hWnd, SW_SHOWDEFAULT );
            UpdateWindow( hWnd );

            
// 消息循环
            MSG msg;
            ZeroMemory( 
&msg, sizeof(msg) );
            
while( msg.message!=WM_QUIT )//这里是如果窗体不退出就一直运行渲染
            {
                
if( PeekMessage( &msg, NULL, 0U0U, PM_REMOVE ) )
                
{
                    TranslateMessage( 
&msg );
                    DispatchMessage( 
&msg );
                }

                
else
                    Render();
            }

        }

    }


    UnregisterClass( 
"D3D Tutorial", wc.hInstance );
    
return 0;
}

设置有什么不清楚,可以参考第一篇文章里面说的比较的详细: Direct3D9 教程01
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
directx 3d 实例#include #include "d3d9.h" #include "d3dx9.h" #include "Direct3D.h" // Direct3D objects IDirect3D9 *g_pD3D = NULL; IDirect3DDevice9 *g_pD3DDevice = NULL; // Sky vertex structure, fvf, vertex buffer, and texture typedef struct { float x, y, z, rhw; float u, v; } sSkyVertex; #define SKYFVF (D3DFVF_XYZRHW | D3DFVF_TEX1) IDirect3DVertexBuffer9 *g_SkyVB = NULL; IDirect3DTexture9 *g_SkyTexture = NULL; // Land and water meshes D3DXMESHCONTAINER_EX *g_WaterMesh = NULL; D3DXMESHCONTAINER_EX *g_LandMesh = NULL; // Window class and caption text char g_szClass[] = "TextureTransformationClass"; char g_szCaption[] = "Texture Transformation Demo by Jim Adams"; // Function prototypes int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow); long FAR PASCAL WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); void Matrix4x4To3x3(D3DXMATRIX *matOut, D3DXMATRIX *matIn); BOOL DoInit(HWND hWnd, BOOL Windowed = TRUE); void DoShutdown(); void DoFrame(); int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow) { WNDCLASSEX wcex; MSG Msg; HWND hWnd; // Initialize the COM system CoInitialize(NULL); // Create the window class here and register it wcex.cbSize = sizeof(wcex); wcex.style = CS_CLASSDC; wcex.lpfnWndProc = WindowProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInst; wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = NULL; wcex.lpszMenuName = NULL; wcex.lpszClassName = g_szClass; wcex.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if(!RegisterClassEx(&wcex)) return FALSE; // Create the main window hWnd = CreateWindow(g_szClass, g_szCaption, WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX, 0, 0, 640, 480, NULL, NULL, hInst, NULL); if(!hWnd) return FALSE; ShowWindow(hWnd, SW_NORMAL); UpdateWindow(hWnd); // Call init function and enter message pump if(DoInit(hWnd) == TRUE) { // Start message pump, waiting for user to exit ZeroMemory(&Msg, sizeof(MSG)); while(Msg.message != WM_QUIT) { if(PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&Msg); DispatchMessage(&Msg); } // Render a single frame DoFrame(); } } // Call shutdown DoShutdown(); // Unregister the window class UnregisterClass(g_szClass, hInst); // Shut down the COM system CoUninitialize(); return 0; } long FAR PASCAL WindowProc(HWND hWnd, UINT uMsg, \ WPARAM wParam, LPARAM lParam) { // Only handle window destruction messages switch(uMsg) { case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, uMsg, wParam, lParam); } return 0; } BOOL DoInit(HWND hWnd, BOOL Windowed) { // Initialize Direct3D InitD3D(&g_pD3D, &g_pD3DDevice, hWnd); // Load the land and water meshes LoadMesh(&g_WaterMesh, g_pD3DDevice, "..\\Data\\Water.x", "..\\Data\\"); LoadMesh(&g_LandMesh, g_pD3DDevice, "..\\Data\\Land.x", "..\\Data\\"); // Create the sky backdrop sSkyVertex SkyVerts[4] = { { 0.0f, 0.0, 1.0, 1.0f, 0.0f, 0.0f }, { 640.0f, 0.0, 1.0, 1.0f, 1.0f, 0.0f }, { 0.0f, 480.0, 1.0, 1.0f, 0.0f, 1.0f }, { 640.0f, 480.0, 1.0, 1.0f, 1.0f, 1.0f } }; g_pD3DDevice->CreateVertexBuffer(sizeof(SkyVerts), D3DUSAGE_WRITEONLY, SKYFVF, D3DPOOL_DEFAULT, &g_SkyVB, NULL); char *Ptr; g_SkyVB->Lock(0,0, (void**)&Ptr, 0); memcpy(Ptr, SkyVerts, sizeof(SkyVerts)); g_SkyVB->Unlock(); D3DXCreateTextureFromFile(g_pD3DDevice, "..\\Data\\Sky.bmp", &g_SkyTexture); // Setup a light D3DLIGHT9 Light; ZeroMemory(&Light, sizeof(Light)); Light.Diffuse.r = Light.Diffuse.g = Light.Diffuse.b = Light.Diffuse.a = 1.0f; Light.Type = D3DLIGHT_DIRECTIONAL; D3DXVECTOR3 vecLight = D3DXVECTOR3(-1.0f, -1.0f, 0.5f); D3DXVec3Normalize(&vecLight, &vecLight); Light.Direction = vecLight; g_pD3DDevice->SetLight(0, &Light); g_pD3DDevice->LightEnable(0, TRUE); // Start playing a waterfall sound PlaySound("..\\Data\\Waterfall.wav", NULL, SND_ASYNC | SND_LOOP); return TRUE; } void DoShutdown() { // Stop playing an ocean sound PlaySound(NULL, NULL, 0); // Free meshes delete g_WaterMesh; g_WaterMesh = NULL; delete g_LandMesh; g_LandMesh = NULL; // Release sky data ReleaseCOM(g_SkyVB); ReleaseCOM(g_SkyTexture); // Release D3D objects ReleaseCOM(g_pD3DDevice); ReleaseCOM(g_pD3D); } void DoFrame() { // Create and set the view transformation D3DXMATRIX matView; D3DXMatrixLookAtLH(&matView, &D3DXVECTOR3(360.0f, -170.0f, -430.0f), &D3DXVECTOR3(65.0f, 70.0f, -15.0f), &D3DXVECTOR3(0.0f, 1.0f, 0.0f)); g_pD3DDevice->SetTransform(D3DTS_VIEW, &matView); // Clear the device and start drawing the scene g_pD3DDevice->Clear(NULL, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_RGBA(0,0,64,255), 1.0, 0); if(SUCCEEDED(g_pD3DDevice->BeginScene())) { // Set identity matrix for world transformation D3DXMATRIX matWorld; D3DXMatrixIdentity(&matWorld); g_pD3DDevice->SetTransform(D3DTS_WORLD, &matWorld); // Draw the sky g_pD3DDevice->SetFVF(SKYFVF); g_pD3DDevice->SetStreamSource(0, g_SkyVB, 0, sizeof(sSkyVertex)); g_pD3DDevice->SetTexture(0, g_SkyTexture); g_pD3DDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2); // Enable lighting g_pD3DDevice->SetRenderState(D3DRS_LIGHTING, TRUE); // Draw the land meshes DrawMeshes(g_LandMesh); // Setup the texture transformation float TimeFactor = (float)(timeGetTime() / 500.0f); D3DXMATRIX matTexture; D3DXMatrixTranslation(&matTexture, 0.0f, -TimeFactor, 0.0f); Matrix4x4To3x3(&matTexture, &matTexture); g_pD3DDevice->SetTransform(D3DTS_TEXTURE0, &matTexture); g_pD3DDevice->SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2); // Draw the water (using alpha blending) DrawMeshes(g_WaterMesh); g_pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); // Disable lighting g_pD3DDevice->SetRenderState(D3DRS_LIGHTING, FALSE); // Turn off texture transformations g_pD3DDevice->SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE); // End the scene g_pD3DDevice->EndScene(); } // Present the scene to the user g_pD3DDevice->Present(NULL, NULL, NULL, NULL); } void Matrix4x4To3x3(D3DXMATRIX *matOut, D3DXMATRIX *matIn) { matOut->_11 = matIn->_11; // Copy over 1st row matOut->_12 = matIn->_12; matOut->_13 = matIn->_13; matOut->_14 = 0.0f; matOut->_21 = matIn->_21; // Copy over 2nd row matOut->_22 = matIn->_22; matOut->_23 = matIn->_23; matOut->_24 = 0.0f; matOut->_31 = matIn->_41; // Copy bottom row matOut->_32 = matIn->_42; // used for translation matOut->_33 = matIn->_43; matOut->_34 = 0.0f; matOut->_41 = 0.0f; // Clear the bottom row matOut->_42 = 0.0f; matOut->_43 = 0.0f; matOut->_44 = 1.0f; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值