D3DX8指南06_Meshes

来源:互联网 发布:java获取文件大小 编辑:程序博客网 时间:2024/05/19 16:48

根据 DirectX 8.1 SDK samples/Multimedia/Direct3D/Tutorials/Tut06_Meshes翻译
保留原文注释
请自行准备.X文件及材质,这里使用DirectX SDK自带文件tiger.X

//-----------------------------------------------------------------------------
// File: Meshes.cpp
//
// Desc: For advanced geometry, most apps will prefer to load pre-authored
//       meshes from a file. Fortunately, when using meshes, D3DX does most of
//       the work for this, parsing a geometry file and creating vertx buffers
//       (and index buffers) for us. This tutorial shows how to use a D3DXMESH
//       object, including loading it from a file and rendering it. One thing
//       D3DX does not handle for us is the materials and textures for a mesh,
//       so note that we have to handle those manually.
//
//       Note: one advanced (but nice) feature that we don't show here is that
//       when cloning a mesh we can specify the FVF. So, regardless of how the
//       mesh was authored, we can add/remove normals, add more texture
//       coordinate sets (for multi-texturing), etc.
//-----------------------------------------------------------------------------
program Tut06_Meshes;

uses
  Windows,
  Messages,
  SysUtils,
  Direct3D8 in 'JEDI/Direct3D8.pas',
  DXTypes in 'JEDI/DXTypes.pas',
  DXFile in 'JEDI/DXFile.pas',
  D3DX8 in 'JEDI/D3DX8.pas';

//-----------------------------------------------------------------------------
// Global variables
//-----------------------------------------------------------------------------
var
g_pD3D           :IDirect3D8        = nil; // Used to create the D3DDevice
g_pd3dDevice     :IDirect3DDevice8  = nil; // Our rendering device

g_pMesh          :ID3DXMesh         = nil;   // Our mesh object in sysmem
g_pMeshMaterials :array of TD3DMaterial8     = nil; // Materials for our mesh
g_pMeshTextures  :array of IDirect3DTexture8 = nil; // Textures for our mesh
g_dwNumMaterials :DWORD             = 0;

//-----------------------------------------------------------------------------
// Name: InitD3D()
// Desc: Initializes Direct3D
//-----------------------------------------------------------------------------
function InitD3D(hWnd: THandle) :HRESULT;
var
 d3ddm :TD3DDisplayMode;
 d3dpp :TD3DPresentParameters;
begin
 // Create the D3D object.
 g_pD3D:=Direct3DCreate8(D3D_SDK_VERSION);
 if g_pD3D=nil then begin
   Result:=E_FAIL;
   exit;
 end;

 // Get the current desktop display mode, so we can set up a back
 // buffer of the same format
 if FAILED(g_pD3D.GetAdapterDisplayMode( D3DADAPTER_DEFAULT, d3ddm )) then begin
   Result:=E_FAIL;
   exit;
 end;

 // Set up the structure used to create the D3DDevice. Since we are now
 // using more complex geometry, we will create a device with a zbuffer.
 Fillchar(d3dpp, sizeof(d3dpp), 0);
 d3dpp.Windowed := TRUE;
 d3dpp.SwapEffect := D3DSWAPEFFECT_DISCARD;
 d3dpp.BackBufferFormat := d3ddm.Format;
 d3dpp.EnableAutoDepthStencil := TRUE;
 d3dpp.AutoDepthStencilFormat := D3DFMT_D16;

 // Create the Direct3D device.
 if FAILED(g_pD3D.CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                      D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                      d3dpp, g_pd3dDevice )) then begin
   Result:=E_FAIL;
   exit;
  end;

  // Turn on the zbuffer
  g_pd3dDevice.SetRenderState( D3DRS_ZENABLE, Ord(TRUE) );

  // Turn on ambient lighting
  g_pd3dDevice.SetRenderState( D3DRS_AMBIENT, $ffffffff );

  Result:=S_OK;
end;

//-----------------------------------------------------------------------------
// Name: InitGeometry()
// Desc: Load the mesh and build the material and texture arrays
//-----------------------------------------------------------------------------
function InitGeometry :HRESULT;
var
  pD3DXMtrlBuffer:ID3DXBuffer;
  d3dxMaterials  :PD3DXMaterial;
  i:DWORD;
begin
  // Load the mesh from the specified file
  if FAILED( D3DXLoadMeshFromX( 'Tiger.x', D3DXMESH_SYSTEMMEM,
                                   g_pd3dDevice, nil,
                                   @pD3DXMtrlBuffer, @g_dwNumMaterials,
                                   g_pMesh ) ) then begin
   Result:=E_FAIL;
   exit;
  end;

  // We need to extract the material properties and texture names from the
  // pD3DXMtrlBuffer
  d3dxMaterials := pD3DXMtrlBuffer.GetBufferPointer;
  SetLength(g_pMeshMaterials, g_dwNumMaterials);
  SetLength(g_pMeshTextures, g_dwNumMaterials);

  for i:=0 to g_dwNumMaterials - 1 do begin
    // Copy the material
    g_pMeshMaterials[i]:=d3dxMaterials.MatD3D;

    // Set the ambient color for the material (D3DX does not do this)
    g_pMeshMaterials[i].Ambient:=g_pMeshMaterials[i].Diffuse;

    // Create the texture
    if FAILED( D3DXCreateTextureFromFile( g_pd3dDevice,
                                          d3dxMaterials.pTextureFilename,
                                          g_pMeshTextures[i] ) ) then begin
        g_pMeshTextures[i] := nil;
    end;
    Inc(d3dxMaterials);
  end;

  // Done with the material buffer
  pD3DXMtrlBuffer:=nil;

  Result:=S_OK;
end;

//-----------------------------------------------------------------------------
// Name: Cleanup()
// Desc: Releases all previously initialized objects
//-----------------------------------------------------------------------------
procedure Cleanup;
var
 i:Integer;
begin
 SetLength(g_pMeshMaterials, 0);
 g_pMeshMaterials := nil;

 for i:=Low(g_pMeshTextures) to High(g_pMeshTextures) do
   g_pMeshTextures[i]:=nil;
 SetLength(g_pMeshTextures, 0);
 g_pMeshTextures := nil;

 g_pMesh     :=nil;
 g_pd3dDevice:=nil;
 g_pD3D      :=nil;
end;

//-----------------------------------------------------------------------------
// Name: SetupMatrices()
// Desc: Sets up the world, view, and projection transform matrices.
//-----------------------------------------------------------------------------
procedure SetupMatrices;
var
 matWorld, matView, matProj :TD3DXMatrix;
begin
 // For our world matrix, we will just leave it as the identity
 D3DXMatrixIdentity( matWorld );
 D3DXMatrixRotationY( matWorld, GetTickCount/1000.0 ); //原文使用mmsystem的timeGetTime()/1000.0f
 g_pd3dDevice.SetTransform( D3DTS_WORLD, matWorld );

 // Set up our view matrix. A view matrix can be defined given an eye point,
 // a point to lookat, and a direction for which way is up. Here, we set the
 // eye five units back along the z-axis and up three units, look at the
 // origin, and define "up" to be in the y-direction.
 D3DXMatrixLookAtLH( matView, D3DXVECTOR3( 0.0, 3.0,-5.0 ),
                              D3DXVECTOR3( 0.0, 0.0, 0.0 ),
                              D3DXVECTOR3( 0.0, 1.0, 0.0 ) );
 g_pd3dDevice.SetTransform( D3DTS_VIEW, matView );

 // For the projection matrix, we set up a perspective transform (which
 // transforms geometry from 3D view space to 2D viewport space, with
 // a perspective divide making objects smaller in the distance). To build
 // a perpsective transform, we need the field of view (1/4 pi is common),
 // the aspect ratio, and the near and far clipping planes (which define at
 // what distances geometry should be no longer be rendered).
 D3DXMatrixPerspectiveFovLH( matProj, D3DX_PI/4, 1.0, 1.0, 100.0 );
 g_pd3dDevice.SetTransform( D3DTS_PROJECTION, matProj );
end;

//-----------------------------------------------------------------------------
// Name: Render()
// Desc: Draws the scene
//-----------------------------------------------------------------------------
procedure Render;
var
 i:DWORD;
begin
  // Clear the backbuffer to a blue color
  g_pd3dDevice.Clear( 0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER,
                         D3DCOLOR_XRGB(0,0,255), 1.0, 0 );

  // Begin the scene
  g_pd3dDevice.BeginScene;

  // Setup the world, view, and projection matrices
  SetupMatrices;

  // Meshes are divided into subsets, one for each material. Render them in
  // a loop
  for i:=0 to g_dwNumMaterials - 1 do begin
     // Set the material and texture for this subset
     g_pd3dDevice.SetMaterial( g_pMeshMaterials[i] );
     g_pd3dDevice.SetTexture( 0, g_pMeshTextures[i] );

     // Draw the mesh subset
     g_pMesh.DrawSubset( i );
  end;

  // End the scene
  g_pd3dDevice.EndScene;

  // Present the backbuffer contents to the display
  g_pd3dDevice.Present(nil, nil, 0, nil);
end;

//-----------------------------------------------------------------------------
// Name: MsgProc()
// Desc: The window's message handler
//-----------------------------------------------------------------------------
function MsgProc( h_Wnd : THandle; aMSG : Cardinal; wParam : Cardinal; lParam : Integer ) : LRESULT; stdcall;
begin
  case aMSG of
    WM_DESTROY:
       PostQuitMessage( 0 );
  end;

  Result :=DefWindowProc(h_Wnd, aMSG, wParam, lParam);
end;

//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: The application's entry point
//-----------------------------------------------------------------------------
function WinMain( hInst :LongWord  ) :Integer;
var
 wc   :TWndClassEx;
 hWnd :THandle;
 aMsg :TMsg;
begin
 // Register the window class
 FillChar(wc,sizeof(wc),0);
 wc.cbSize:=sizeof(wc);
 wc.style:=CS_CLASSDC;
 wc.lpfnWndProc:=@MsgProc;
 wc.cbClsExtra:=0;
 wc.cbWndExtra:=0;
 wc.hInstance:=hInst;
 wc.hIcon:=0;
 wc.hCursor:=0;
 wc.hbrBackground:=0;
 wc.lpszMenuName:=nil;
 wc.lpszClassName:='D3D Tutorial';
 wc.hIconSm:=0;
 RegisterClassEx(wc);

 // Create the application's window
 hWnd := CreateWindow('D3D Tutorial', 'D3D Tutorial 06: Meshes',
                      WS_OVERLAPPEDWINDOW, 100, 100, 300, 300,
                      GetDesktopWindow(), 0, wc.hInstance, nil);

 // Initialize Direct3D
 if SUCCEEDED(InitD3D(hWnd)) then
    // Create the scene geometry
    if SUCCEEDED(InitGeometry) then begin
       // Show the window
       ShowWindow( hWnd, SW_SHOWDEFAULT );
       UpdateWindow( hWnd );

       // Enter the message loop
       Fillchar(aMSG, sizeof(aMSG), 0);
       while not (aMsg.message = WM_QUIT) do
         if PeekMessage( aMsg, 0, 0, 0, PM_REMOVE ) then begin
           TranslateMessage ( aMsg ) ;
           DispatchMessage ( aMsg ) ;
         end else
           Render;
    end;

 // Clean up everything and exit the app
 Cleanup;
 UnregisterClass( 'D3D Tutorial', wc.hInstance );
 Result:=0;
end;

begin
  WinMain(hInstance);
  Halt(0);
end.
 

原创粉丝点击