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

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  AppEvnts, ExtCtrls,
  DirectDraw, DDUtil;

type
  TfrmDD = class(TForm)
    ApplicationEvents1: TApplicationEvents;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure ApplicationEvents1Deactivate(Sender: TObject);
    procedure FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure ApplicationEvents1Restore(Sender: TObject);
    procedure FormActivate(Sender: TObject);
    procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
    FDD            : IDirectDraw7;
    FDDSPrimary    : IDirectDrawSurface7;
    FDDSBackGround : IDirectDrawSurface7;
    FDDSBack       : IDirectDrawSurface7;
    FDDSImage      : IDirectDrawSurface7;
    FActive        : BOOL;
    ThisTickCount  : DWORD;
    LastTickCount  : DWORD;
    function Blend (const X, Y : Integer) : HRESULT;
    function Prepare : HRESULT;
    function UpdateFrame : HRESULT;
    function RestoreAll : HRESULT;
    function FlipPages : HRESULT;
    procedure ErrorOut(hRet : HRESULT; FuncName : String);
  public
    { Public declarations }
  protected
    procedure FormSetCursor(var aMsg : TMessage); message WM_SETCURSOR;
  end;

const
  ScreenWidth    = 640;
  ScreenHeight   = 480;
  ScreenBitDepth = 16;
  groundBmp      = '..\LAKE.BMP';
  imageBmp       = '..\bug.bmp';
  imageWidth     = 84;
  imageHeight    = 80;
  Alpha          = 127;

var
  frmDD : TfrmDD;
  Angle : Single = 0;

  Pict : Array [0..imageWidth - 1, 0..imageHeight - 1] of Word;
  ColorKey : Word;

implementation

{$R *.DFM}

procedure TfrmDD.ErrorOut(hRet : HRESULT; FuncName : String);
var
  t : TextFile;
begin
  AssignFile (t, 'Debug.txt');
  Rewrite (t);
  WriteLn (t, FuncName + ': ' + DDErrorString (hRet));
  CloseFile (t);
  Destroy;
end;

procedure TfrmDD.FormCreate(Sender: TObject);
var
  hRet : HRESULT;
  ddsd : TDDSurfaceDesc2;
  ddscaps : TDDSCaps2;  
begin
  FDDSImage := nil;
  FDDSBack := nil;
  FDDSBackGround := nil;
  FDDSPrimary := nil;
  FDD := nil;

  hRet := DirectDrawCreateEx (nil, FDD, IDirectDraw7, nil);
  if Failed(hRet) then ErrorOut(hRet, 'DirectDrawCreateEx');

  hRet := FDD.SetCooperativeLevel(Handle, DDSCL_FULLSCREEN or DDSCL_EXCLUSIVE);
  if Failed(hRet) then ErrorOut(hRet, 'SetCooperativeLevel');

  hRet := FDD.SetDisplayMode (ScreenWidth, ScreenHeight, ScreenBitDepth, 0, 0);
  if Failed(hRet) then ErrorOut(hRet, 'SetDisplayMode');

  ZeroMemory (@ddsd, SizeOf(ddsd));
  with ddsd do begin
       dwSize := SizeOf(ddsd);
       dwFlags := DDSD_CAPS or DDSD_BACKBUFFERCOUNT;
       ddsCaps.dwCaps := DDSCAPS_PRIMARYSURFACE or DDSCAPS_FLIP or DDSCAPS_COMPLEX;
       dwBackBufferCount := 1;
  end;
  hRet := FDD.CreateSurface(ddsd, FDDSPrimary, nil);
  if Failed(hRet) then ErrorOut(hRet, 'Create Primary Surface');

  FDDSBackGround := DDLoadBitmap(FDD, groundBmp, ScreenWidth, ScreenHeight);
  if FDDSBackGround = nil then ErrorOut(DD_FALSE, 'DDLoadBitmap');

  FDDSImage := DDLoadBitmap(FDD, imageBmp, 0, 0);
  if FDDSImage = nil then ErrorOut(DD_FALSE, 'DDLoadBitmap');

  ZeroMemory (@ddscaps, SizeOf(ddscaps));
  ddscaps.dwCaps := DDSCAPS_BACKBUFFER;
  hRet := FDDSPrimary.GetAttachedSurface(ddscaps, FDDSBack);
  if Failed(hRet) then ErrorOut(hRet, 'GetAttachedSurface');

  hRet := Prepare;
  if Failed (Prepare) then ErrorOut(hRet, 'Prepare');

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

  if Failed (FDDSPrimary.Blt (nil, FDDSBackGround, nil, DDBLT_WAIT, nil)) then Close;
  if Failed (FDDSBack.Blt (nil, FDDSBackGround, nil, DDBLT_WAIT, nil)) then Close;
end;

procedure TfrmDD.FormDestroy(Sender: TObject);
begin
  if Assigned(FDD) then begin
      if Assigned(FDDSBackGround) then FDDSBackGround := nil;
      if Assigned(FDDSBack) then FDDSBack := nil;
      if Assigned(FDDSPrimary) then FDDSPrimary := nil;
      FDD := nil;
  end;
end;

procedure TfrmDD.ApplicationEvents1Deactivate(Sender: TObject);
begin
  FActive := False;
  Application.Minimize;
end;

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

procedure TfrmDD.FormSetCursor(var aMsg : TMessage);
begin
  SetCursor(0);
end;

function TfrmDD.RestoreAll : HRESULT;
var
  hRet : HRESULT;
begin
  hRet := FDDSPrimary._Restore;
  if Succeeded (hRet) then begin
      FDDSBackGround := nil;
      FDDSBackGround := DDLoadBitmap(FDD, groundBmp, ScreenWidth, ScreenHeight);
      if FDDSBackGround = nil then ErrorOut(DD_FALSE, 'DDLoadBitmap');
      hRet := FDDSPrimary.Blt (nil, FDDSBackGround, nil, DDBLT_WAIT, nil);
      if Failed (hRet) then begin
         Result := hRet;
         Exit;
      end;
      Result := FDDSBack.Blt (nil, FDDSBackGround, nil, DDBLT_WAIT, nil);
  end else Result := hRet;
end;

procedure TfrmDD.ApplicationEvents1Restore(Sender: TObject);
begin
  WindowState := wsMaximized;
  FActive := True;
end;

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

procedure TfrmDD.ApplicationEvents1Idle(Sender: TObject;
  var Done: Boolean);
begin
  if FActive then
     if Failed (UpdateFrame) then RestoreAll;
  Done := False;
end;

function TfrmDD.UpdateFrame : HRESULT;
var
  X, Y : Integer;
  wrkRect : TRECT;
  hRet : HRESULT;
begin
  ThisTickCount := GetTickCount;

  if ThisTickCount - LastTickCount > 60 then begin
     X := 288 + trunc (cos(Angle) * 150);
     Y := 208 + trunc (sin(Angle) * 150);
     SetRect (wrkRect, X, Y, X + imageWidth, Y + imageHeight);

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

     hRet := Blend (288 + trunc (cos(Angle) * 150),
                    208 + trunc (sin(Angle) * 150));
     if Failed (hRet) then begin
        Result := hRet;
        Exit;
     end;

     hRet := FlipPages;
     if Failed (hRet) then begin
        Result := hRet;
        Exit;
     end;

     hRet := FDDSBack.Blt (@wrkrect, FDDSBackGround, @wrkRect, DDBLT_WAIT, nil);
     if Failed (hRet) then begin
        Result := hRet;
        Exit;
     end;

     LastTickCount := GetTickCount;
  end;

  Result := DD_OK;
end;

function TfrmDD.Prepare : HRESULT;
var
  desc : TDDSURFACEDESC2;
  i, j : Integer;
  hRet : HRESULT;
begin
  ZeroMemory (@desc, SizeOf(desc));
  desc.dwSize := SizeOf(desc);

  hRet := FDDSImage.Lock (nil, desc, DDLOCK_WAIT, 0);
  if Failed (hRet) then begin
     Result := hRet;
     Exit;
  end;

  for i := 0 to imageWidth - 1 do
   for j := 0 to imageHeight - 1 do
     Pict [i, j] := PWORD (Integer (desc.lpSurface) + j * desc.lPitch
      + i * (ScreenBitDepth div 8))^;

  ColorKey := Pict [0, 0];

  Result := FDDSImage.Unlock (nil);
end;

function TfrmDD.Blend (const X, Y : Integer) : HRESULT;
var
  desc : TDDSURFACEDESC2;
  i, j : Integer;
  wrkPointer : PWORD;
  sTemp, dTemp : WORD;
  sb, db, sg, dg, sr, dr : Byte;
  blue, green, red : Byte;
  hRet : HRESULT;
begin
  ZeroMemory (@desc, SizeOf(desc));
  desc.dwSize := SizeOf(desc);

  hRet := FDDSBack.Lock (nil, desc, DDLOCK_WAIT, 0);
  if Failed (hRet) then begin
     Result := hRet;
     Exit;
  end;

  for i := 0 to imageWidth - 1 do
      for j := 0 to imageHeight - 1 do
       if Pict [i, j] <> ColorKey then begin
       wrkPointer := PWORD (Integer(desc.lpSurface) + (Y + j) * desc.lPitch +
                     (X + i) * (ScreenBitDepth div 8));
       sTemp := Pict [i, j];
       dTemp := wrkPointer^;

       sb := sTemp and $1f;
       db := dTemp and $1f;
       sg := (sTemp shr 5)  and $3f;
       dg := (dTemp shr 5)  and $3f;
       sr := (sTemp shr 11) and $1f;
       dr := (dTemp shr 11) and $1f;
       blue  := (ALPHA * (sb - db) shr 8) + db;
       green := (ALPHA * (sg - dg) shr 8) + dg;
       red   := (ALPHA * (sr - dr) shr 8) + dr;
       wrkPointer^ := blue or (green shl 5) or (red shl 11);
  end;

  Result := FDDSBack.Unlock (nil);
end;

function TfrmDD.FlipPages : HRESULT;
begin
  Result := FDDSPrimary.Flip(nil, DDFLIP_WAIT);
end;

procedure TfrmDD.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Hide
end;

end.


