D3DX8指南04_Lights

来源:互联网 发布:网络爬虫是什么 编辑:程序博客网 时间:2024/06/05 12:39

根据 DirectX 8.1 SDK samples/Multimedia/Direct3D/Tutorials/Tut03_Matrices翻译
保留原文注释

//-----------------------------------------------------------------------------
// File: Lights.cpp
//
// Desc: Rendering 3D geometry is much more interesting when dynamic lighting
//       is added to the scene. To use lighting in D3D, you must create one or
//       lights, setup a material, and make sure your geometry contains surface
//       normals. Lights may have a position, a color, and be of a certain type
//       such as directional (light comes from one direction), point (light
//       comes from a specific x,y,z coordinate and radiates in all directions)
//       or spotlight. Materials describe the surface of your geometry,
//       specifically, how it gets lit (diffuse color, ambient color, etc.).
//       Surface normals are part of a vertex, and are needed for the D3D's
//       internal lighting calculations.
//-----------------------------------------------------------------------------
program Tut04_Lights;

uses
  Windows,
  Messages,
  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_pVB       :IDirect3DVertexBuffer8 = nil; // Buffer to hold vertices

// A structure for our custom vertex type. We added a normal, and omitted the
// color (which is provided by the material)
type
  CUSTOMVERTEX=record
    position:TD3DXVector3; // The 3D position for the vertex
    normal  :TD3DXVector3; // The surface normal for the vertex
  end;

// Our custom FVF, which describes our custom vertex structure
const D3DFVF_CUSTOMVERTEX = (D3DFVF_XYZ or D3DFVF_NORMAL);

//-----------------------------------------------------------------------------
// 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.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 off culling
  g_pd3dDevice.SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );

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

  Result:=S_OK;
end;

//-----------------------------------------------------------------------------
// Name: InitGeometry()
// Desc: Creates the scene geometry
//-----------------------------------------------------------------------------
function InitGeometry :HRESULT;
var
 pVertices,P:^CUSTOMVERTEX;
 i:DWORD;
 theta:Single;
begin
  // Create the vertex buffer.
  if FAILED(g_pd3dDevice.CreateVertexBuffer(50*2*sizeof(CUSTOMVERTEX),
                                            0, D3DFVF_CUSTOMVERTEX,
                                            D3DPOOL_DEFAULT, g_pVB)) then begin
   Result:=E_FAIL;
   exit;
  end;

  // Fill the vertex buffer. We are algorithmically generating a cylinder
  // here, including the normals, which are used for lighting.
  pVertices:=nil;
  if FAILED(g_pVB.Lock(0, 0, PByte(pVertices), 0)) then begin
   Result:=E_FAIL;
   exit;
  end;
  for i:=0 to 49 do begin
     theta := (2*D3DX_PI*i)/(50-1);
     P:=pVertices;
     Inc(P,2*i+0);
     P.position := D3DXVECTOR3( sin(theta),-1.0, cos(theta) );
     P.normal   := D3DXVECTOR3( sin(theta), 0.0, cos(theta) );
     P:=pVertices;
     Inc(P,2*i+1);
     P.position := D3DXVECTOR3( sin(theta), 1.0, cos(theta) );
     P.normal   := D3DXVECTOR3( sin(theta), 0.0, cos(theta) );
  end;
  g_pVB.Unlock;

  pVertices:=nil;

  Result:=S_OK;
end;

//-----------------------------------------------------------------------------
// Name: Cleanup()
// Desc: Releases all previously initialized objects
//-----------------------------------------------------------------------------
procedure Cleanup;
begin
 g_pVB       :=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 );
 D3DXMatrixRotationX( matWorld, GetTickCount/500.0 ); //原文使用mmsystem的timeGetTime()/500.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: SetupLights()
// Desc: Sets up the lights and materials for the scene.
//-----------------------------------------------------------------------------
procedure SetupLights;
var
  mtrl   :TD3DMaterial8;
  vecDir :TD3DXVector3;
  light  :TD3DLight8;
begin
 // Set up a material. The material here just has the diffuse and ambient
 // colors set to yellow. Note that only one material can be used at a time.
 Fillchar(mtrl, sizeof(mtrl), 0);
 mtrl.Diffuse.r := 1.0;
 mtrl.Diffuse.g := 1.0;
 mtrl.Diffuse.b := 0.0;
 mtrl.Diffuse.a := 1.0;
 mtrl.Ambient := mtrl.Diffuse;
 g_pd3dDevice.SetMaterial( mtrl );

 // Set up a white, directional light, with an oscillating direction.
 // Note that many lights may be active at a time (but each one slows down
 // the rendering of our scene). However, here we are just using one. Also,
 // we need to set the D3DRS_LIGHTING renderstate to enable lighting
 Fillchar(light, sizeof(light), 0);
 light._Type := D3DLIGHT_DIRECTIONAL;
 light.Diffuse.r := 1.0;
 light.Diffuse.g := 1.0;
 light.Diffuse.b := 1.0;
 vecDir := D3DXVECTOR3(cos(GetTickCount/350.0),
                         1.0,
                         sin(GetTickCount/350.0) );
 D3DXVec3Normalize( light.Direction, vecDir );
 light.Range := 1000.0;
 g_pd3dDevice.SetLight( 0, light );
 g_pd3dDevice.LightEnable( 0, TRUE );
 g_pd3dDevice.SetRenderState( D3DRS_LIGHTING, Ord(TRUE) );

 // Finally, turn on some ambient light.
 g_pd3dDevice.SetRenderState( D3DRS_AMBIENT, $202020 );

end;

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

  // Begin the scene
  g_pd3dDevice.BeginScene;

  // Setup the lights and materials
  SetupLights;

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

  // Render the vertex buffer contents
  g_pd3dDevice.SetStreamSource(0, g_pVB, sizeof(CUSTOMVERTEX));
  g_pd3dDevice.SetVertexShader(D3DFVF_CUSTOMVERTEX);
  g_pd3dDevice.DrawPrimitive(D3DPT_TRIANGLELIST, 0, 2*50-2);

  // 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 04: Lights',
                      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.
 

原创粉丝点击