{******************************************************************************}
{* Иллюстрация к книге "DirectX. Графика в проектах Delphi".                  *}
{* Издательство BHV. www.bhv.ru                                               *}
{* Краснов М.В. softgl@chat.ru                                                *}
{******************************************************************************}
unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  AppEvnts,
  DirectXGraphics, DXGUtils;

type
  TfrmD3D = class(TForm)
    ApplicationEvents1: TApplicationEvents;
    procedure FormCreate(Sender: TObject);
    procedure ApplicationEvents1Minimize(Sender: TObject);
    procedure FormActivate(Sender: TObject);
    procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean);
    procedure FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure ApplicationEvents1Restore(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
    FD3D            : IDIRECT3D8;
    FD3DDevice      : IDIRECT3DDEVICE8;
    FD3DVB          : IDIRECT3DVERTEXBUFFER8;
    FActive         : BOOL;
    MaterialYellow  : TD3DMaterial8;
    MaterialRed     : TD3DMaterial8;
    MaterialGray    : TD3DMaterial8;
    ThisTickCount   : DWORD;
    LastTickCount   : DWORD;
    function Render : HRESULT;
    function InitD3D : HRESULT;
    function InitVB : HRESULT;
    procedure DrawScene;
    procedure MoveMan;
    procedure SetupLights;
    procedure Cleanup;
    procedure ErrorOut (const Caption : PChar; const hError : HRESULT);
    procedure DrawSphere;
  public
    { Public declarations }
  end;

type
  TCUSTOMVERTEX = packed record
    X, Y, Z : Single;
    nX, nY, nZ : Single;
  end;

const
  D3DFVF_CUSTOMVERTEX = D3DFVF_XYZ or D3DFVF_NORMAL;

var
  frmD3D: TfrmD3D;
  Frames : Integer = 0;

  Angle : Single = 0.0;

  AngleFoot : Single = 0.0;
  StepFoot : Single = 0.05;

  matRot : TD3DMatrix;

  transFoot1, transFoot2 : TD3DMatrix;

  transHand1, transHand2 : TD3DMatrix;

  rotLeftFoot : TD3DMatrix;
  rotRightFoot : TD3DMatrix;

  matLeftFoot : TD3DMatrix;
  matRightFoot : TD3DMatrix;

  matLeftHand : TD3DMatrix;
  matRightHand : TD3DMatrix;

const
  {$I Legoman.pas}

implementation

{$R *.DFM}

procedure TfrmD3D.Cleanup;
begin
  if Assigned (FD3DVB) then begin
     FD3DVB._Release;
     FD3DVB := nil;
  end;

  if Assigned (FD3DDevice) then begin
     FD3DDevice._Release;
     FD3DDevice := nil;
  end;

  if Assigned (FD3D) then begin
     FD3D._Release;
     FD3D := nil;
  end;
end;

procedure TfrmD3D.ErrorOut (const Caption : PChar; const hError : HRESULT);
begin
  FActive := False;
  Cleanup;
  MessageBox (Handle, PChar(DXGErrorString (hError)), Caption, 0);
end;

function TfrmD3D.InitD3D : HRESULT;
var
  d3ddm : TD3DDISPLAYMODE;
  d3dpp : TD3DPRESENT_PARAMETERS;
  hRet : HRESULT;
begin
  FD3DDevice := nil;
  FD3DVB := nil;
  FD3D := nil;

  FD3D := Direct3DCreate8(D3D_SDK_VERSION);
  if FD3D = nil then begin
     Result := E_FAIL;
     Exit;
  end;

  hRet := FD3D.GetAdapterDisplayMode(D3DADAPTER_DEFAULT, d3ddm);
  if FAILED(hRet) then begin
     Result := hRet;
     Exit;
  end;

  ZeroMemory(@d3dpp, SizeOf(d3dpp));
  with d3dpp do begin
       Windowed := True;
       SwapEffect := D3DSWAPEFFECT_DISCARD;
       BackBufferFormat := d3ddm.Format;
       EnableAutoDepthStencil := True;
       AutoDepthStencilFormat := D3DFMT_D16;
  end;

  Result := FD3D.CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, Handle,
                              D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                              d3dpp, FD3DDevice);
end;

function TfrmD3D.Render : HRESULT;
var
  hRet : HRESULT;
begin
  if FD3DDevice = nil then begin
     Result := E_FAIL;
     Exit;
  end;

  hRet := FD3DDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, $00FFFFFF,
  1.0, 0);
  if FAILED(hRet) then begin
     Result := hRet;
     Exit;
  end;

  hRet := FD3DDevice.BeginScene;
  if FAILED(hRet) then begin
     Result := hRet;
     Exit;
  end;

  with FD3DDevice do begin
       SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
       SetRenderState(D3DRS_LIGHTING, DWORD (True));
  end;

  DrawScene;

  hRet := FD3DDevice.EndScene;
  if FAILED(hRet) then begin
     Result := hRet;
     Exit;
  end;

  Result := FD3DDevice.Present(nil, nil, 0, nil);
end;

procedure TfrmD3D.FormCreate(Sender: TObject);
var
  hRet : HRESULT;
  View, Proj : TD3DMatrix;
begin
  hRet := InitD3D;
  if Failed (hRet) then ErrorOut ('InitD3D', hRet);
  hRet := InitVB;
  if Failed (hRet) then ErrorOut ('InitVertex', hRet);

  DrawSphere;

  MaterialYellow  := InitMaterial(1, 1, 0, 0);
  MaterialRed     := InitMaterial(1, 0, 0, 0);
  MaterialGray    := InitMaterial(0.5, 0.5, 0.5, 0);

  SetTranslateMatrix(transFoot1, 0, 0, 0.25);
  SetTranslateMatrix(transFoot2, 0, 0, -0.25);

  SetTranslateMatrix(transHand1, 0.25, 0.0, -0.23);
  SetTranslateMatrix(transHand2, -0.25, 0.0, 0.23);

  SetupLights;

  SetViewMatrix(View, D3DVector(0.75, 0.75, 0.75), D3DVector(0, 0, 0), D3DVector(0, 0, 1));
  FD3DDevice.SetTransform(D3DTS_VIEW, View);

  SetProjectionMatrix(Proj, 1, 1, 0.1, 5);
  FD3DDevice.SetTransform(D3DTS_PROJECTION, Proj);
end;

procedure TfrmD3D.ApplicationEvents1Minimize(Sender: TObject);
begin
  FActive := False;
end;

procedure TfrmD3D.FormActivate(Sender: TObject);
begin
  LastTickCount := GetTickCount;
  FActive := True;
end;

procedure TfrmD3D.ApplicationEvents1Idle(Sender: TObject;
  var Done: Boolean);
var
  hRet : HRESULT;
begin
  if FActive then begin
     Inc (Frames);
     hRet := Render;
     if FAILED(hRet) then begin
        FActive := False;
        ErrorOut ('Render', hRet);
        Exit;
     end;

     ThisTickCount := GetTickCount;
     if ThisTickCount - LastTickCount > 15 then begin
        Caption := 'FPS = ' + Format('%6.2f',
                                 [frames * 1000 / (ThisTickCount - LastTickCount)]);
        Frames := 0;

        Angle := Angle + 0.05;
        if Angle > 2 * Pi then Angle := Angle - 2 * Pi;

        MoveMan;

        LastTickCount := GetTickCount;
     end;
  end;

  Done := False;
end;

procedure TfrmD3D.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if Key = VK_ESCAPE then Close;
end;

procedure TfrmD3D.ApplicationEvents1Restore(Sender: TObject);
begin
  FActive := True;
end;

procedure TfrmD3D.FormDestroy(Sender: TObject);
begin
  Cleanup
end;

function TfrmD3D.InitVB : HRESULT;
var
  hRet : HRESULT;
begin
  hRet := FD3DDevice.CreateVertexBuffer(2922 * 3 * SizeOf(TCustomVertex), 0,
                                        D3DFVF_CUSTOMVERTEX,
                                        D3DPOOL_DEFAULT, FD3DVB);
  if Failed(hRet) then begin
     Result := hRet;
     Exit;
  end;

  hRet := FD3DDevice.SetStreamSource(0, FD3DVB, SizeOf(TCustomVertex));
  if Failed(hRet) then begin
     Result := hRet;
     Exit;
  end;

  Result := FD3DDevice.SetVertexShader(D3DFVF_CUSTOMVERTEX);
end;

procedure TfrmD3D.DrawScene;
begin
  with FD3DDevice do begin
    SetMaterial(MaterialGray);

    SetTransform(D3DTS_WORLD, matLeftFoot);
    DrawPrimitive(D3DPT_TRIANGLELIST, 0, 112);

    SetTransform(D3DTS_WORLD, matRightFoot);
    DrawPrimitive(D3DPT_TRIANGLELIST, (112 + 204) * 3, 112); 

    SetMaterial(MaterialRed);
    SetTransform(D3DTS_WORLD, matLeftHand);
    DrawPrimitive(D3DPT_TRIANGLELIST, (112 + 204 + 112 + 620 + 614) * 3, 612);

    SetMaterial(MaterialYellow);
    DrawPrimitive(D3DPT_TRIANGLELIST, (112 + 204 + 112 + 620 + 614 + 612) * 3, 324);

    SetMaterial(MaterialRed);
    SetTransform(D3DTS_WORLD, matRightHand);
    DrawPrimitive(D3DPT_TRIANGLELIST, (112 + 204 + 112 + 620) * 3, 614);

    SetMaterial(MaterialYellow);
    DrawPrimitive(D3DPT_TRIANGLELIST, (112 + 204 + 112 + 620 + 614 + 612 + 324) * 3, 324);

    SetTransform(D3DTS_WORLD, matRot);
    DrawPrimitive(D3DPT_TRIANGLELIST, (112 + 204 + 112) * 3, 620);

    SetMaterial(MaterialRed);
    DrawPrimitive(D3DPT_TRIANGLELIST, 112 * 3, 204);
  end;
end;

procedure TfrmD3D.SetupLights;
var
  Light0 : TD3DLight8;
  Light1 : TD3DLight8;
begin
  Light0 := InitDirectionalLight(D3DVector(-1, -1, 0), 0.5, 0.5, 0.5, 0);
  Light1 := InitDirectionalLight(D3DVector(-1, -1, -1), 0.5, 0.5, 0.5, 0);

  FD3DDevice.SetLight(0, Light0);
  FD3DDevice.SetLight(1, Light1);

  FD3DDevice.LightEnable(0, True);
  FD3DDevice.LightEnable(1, True);
end;

procedure TfrmD3D.DrawSphere;
var
  i, j : Integer;
  Vertices : ^TCustomVertex;
  vi : Integer;
  ni : Integer;
begin
  FD3DVB.Lock(0, 2922 * 3 * SizeOf(TCustomVertex), PByte(Vertices), 0);

  for i := 0 to 2921 do
      for j := 0 to 2 do begin
      vi := face_indicies[i][j];
      ni := face_indicies[i][j+3];

         Vertices.X := Avertices[vi][0];
         Vertices.Y := Avertices[vi][1];
         Vertices.Z := Avertices[vi][2];

         Vertices.nX := normals[ni][0];
         Vertices.nY := normals[ni][1];
         Vertices.nZ := normals[ni][2];

         Inc(Vertices);
  end;

  FD3DVB.Unlock;
end;

procedure TfrmD3D.MoveMan;
begin
  SetRotateZMatrix (matRot, Angle);

  AngleFoot := AngleFoot + StepFoot;
  if (AngleFoot > Pi / 4) or (AngleFoot < -Pi / 4)
     then StepFoot := -StepFoot;

  SetRotateXMatrix (rotLeftFoot, AngleFoot);
  SetRotateXMatrix (rotRightFoot, -AngleFoot);

  matLeftFoot := MatrixMul(matRot,
           MatrixMul(transFoot2,
           MatrixMul(rotLeftFoot, transFoot1)));

  matRightFoot := MatrixMul(matRot,
           MatrixMul(transFoot2,
           MatrixMul(rotRightFoot, transFoot1)));

  matLeftHand :=  MatrixMul(matRot,
           MatrixMul(transHand2,
           MatrixMul(rotRightFoot, transHand1)));

  matRightHand := MatrixMul(matRot,
           MatrixMul(transHand2,
           MatrixMul(rotLeftFoot, transHand1)));
end;

end.
