DirectX and Direct Draw

Document Sample
DirectX and Direct Draw Powered By Docstoc
					   Introduction to
DirectX Programming
     DirectDraw


    Abdennour El Rhalibi
                    What is DirectX?
   DirectX is a set of components, developed to
    provide Windows-based programs with high-
    performance, real-time access to available
    hardware on current computer systems.

   DirectX was primarily developed for Windows
    95, but Windows NT 4.0 currently supports a
    subset of DirectX.

   2D/3D graphics / multimedia API
       Designed for Game and Multimedia Programming
       Works only on MS Windows platform
            95/98/ME/2000/XP
            Old version for Windows NT                2
Architecture of DirectX




                          3
          The Component Object Model
                   (COM)
   A DirectX application is built from instances of COM objects.
    You can consider an object to be a black box that represents
    hardware or data that you access through interfaces.
    Commands are sent to the object through methods of the COM
    interface.

   For example, the IDirectDraw7::GetDisplayMode method of
    the IDirectDraw7 interface is called to get the current display
    mode of the display adapter from the DirectDraw object.

   Objects can bind to other objects at run time, and they can use
    the implementation of interfaces provided by the other object.

   If you know that an object is a COM object and you know
    which interfaces that object supports, your application can
    determine which services the first object can perform.

   One of the methods that all COM objects inherit, the
    QueryInterface method, lets you determine which interfaces
    an object supports and creates pointers to these interfaces.
                                                               4
COM - 2




          5
             The Component Object Model
                      (COM)
   IUnknown interface
      All COM objects support an interface called IUnknown. This
       interface provides DirectX with control of the object's lifetime
       and the ability to retrieve other interfaces implemented by the
       object. IUnknown has three methods:

           AddRef increments the object's reference count by 1 when
            an interface or another application binds itself to the object.

           QueryInterface queries the object about the features that it
            supports by requesting pointers to a specific interface.

           Release decrements the object's reference count by 1. When
            the count reaches 0, the object is deallocated.

.
                                                                       6
DirectX7 COM Object
   Many COM objects make up
    DirectX
       DLLs
   DirectX hides many details about
    handling COM objects.
       Wrapper functions in libraries.
       DDRAW.LIB, DSOUND.LIB,
        DINPUT.LIB, DSETUP.LIB,
        DPLAYX.LIB, D3DIM.LIB, D3DRM.LIB

                                           7
                DirectDraw - 2D graphics
   DirectDraw is the component of the DirectX application
    programming interface (API) that allows you to directly
    manipulate display memory, the hardware blitter, hardware
    overlay support, and flipping surface support.

   It provides direct access to display devices while maintaining
    compatibility with the Windows graphics device interface (GDI).

   It provides a device-independent way for games and Windows
    subsystem software, such as three-dimensional (3-D) graphics
    packages, to gain access to the features of specific 2D display
    devices.

   It works with a wide variety of display hardware, ranging from
    simple SVGA monitors to advanced hardware implementations
    that provide clipping, stretching, and non-RGB colour format
    support.

   Its interface is designed so that your applications can enumerate
    the capabilities of the underlying hardware and then use any 8
    supported hardware-accelerated features.
Architectural Overview of
DirectDraw
DirectDraw enables a much higher level of efficiency and speed in
   graphics-intensive applications for Windows than is possible
   with GDI, while maintaining device independence.
DirectDraw provides tools to perform such key tasks as:

   Manipulating multiple display surfaces
   Accessing the video memory directly
   Page flipping
   Back buffering
   Managing the palette
   Clipping

The DirectDraw component provides services through COM-based
  interfaces. In the most recent iteration, these interfaces are
  IDirectDraw7, IDirectDrawSurface7, IDirectDrawPalette,
  IDirectDrawClipper, and IDirectDrawVideoPort.


                                                              9
The Interfaces of DirectDraw




                               10
        Interface Characteristics - 1
   IUnknown
   IDirectDraw
       Main interface object
       Represents the video card and support hardware
       By MMS (Multiple Monitor Support – Windows
        98/NT),
            more than one DirectDraw object are needed
             sometimes.




                                                          11
        Interface Characteristics - 2
   IDirectDrawSurface
       On the video card (VRAM) or within system
        memory.
       Primary (current) and secondary (offscreen)
        surfaces.




                                                      12
      Interface Characteristics - 3
   IDirectDrawPalette




                                      13
        Interface Characteristics - 4
   IDirectDrawClipper
       Used to help with clipping DirectDraw raster
       Takes advantage of hardware acceleration if it’s
        available


   Latest version for DirectX7.0a
       Read readme and DDRAW.H
          IDirectDraw7
          IDirectDrawSurface7

          IDirectDrawPalette

          IDirectDrawClipper
                                                      14
          Using Interface Together
1.   Create DirectDraw object
     •   Retrieve a IDirectDraw7 interface
2.   Create at least a primary surface using
     IDirectDrawSurface
3.   Create a palette using IDrectDrawPalette
     •   Initialize palette
     •   Attach it to the surface
4.   Create a single clipper and size it.
5.   Draw on the primary surface.
                                                15
Sprite animation
Code analysis for Basic structure


          “how it works”
            goals for demo 0

   read an artist image from a file (bmp)
   register a default display window w/ os
   init DirectDraw
   set resolution to 640×480×8
   display image until esc
   after esc, shut down DirectDraw, clean up,
    reset display resolution
                                             18
background image for demo0




                             19
                 Why bmp?

   native to the Windows API
   the API is set up to make reading bmp
    files very easy
   might be able to convert jpg or gif to bmp




                                             20
    need to choose screen format:
      resolution & no. of colors
   ideally: provide a number of formats
       high res & high color format for people with
        expensive computers
       low res & low color for people with cheap computers
   choices for resolution
       640×480
       1024×768
       1280×960


                                                              21
               choices for color
   8-bit color: each bit stored as 8-bit index into a
    color table (palette) of 256, 24-bit colors
   16-bit color: each pixel is stored as a 16-bit color
    value (65,536 colors)
   24-bit color: each pixel is stored as a 24-bit color
    value (16,777,216 colors)
   32-bit color: 24-bit color with an unused 8-bit
    field (used in 3D programming for the alpha
    value)

                                                      22
                           color
   for average picture: 16-bit is dramatically better
    than 8-bit
   24-bit is a little better
   for this example, we’ll use 8-bit color
       save’s disk space
       8-bit is hardest to program
       Window’s API has functions for automatically
        stretching/shrinking images
       thus, converting to 24-bit is easy, but slow
   The example is full screen
                                                       23
           includes for Main.cpp

//main.cpp
//Read 640x480x256 bmp & display full screen (ESC to exit)

//system includes
#include <windows.h>
#include <windowsx.h>
#include <ddraw.h>
#include <stdio.h>
#define WIN32_LEAN_AND_MEAN



                                                         24
    more includes for Main.cpp
                                 //custom includes
                                 #include "defines.h"
                                 #include "bmp.h"
#ifndef __DEFINES_H__
#define __DEFINES_H__

#define SCREEN_WIDTH 640 //pixels wide
#define SCREEN_HEIGHT 480 //pixels high
#define COLORS 256 //number of colors
#define COLOR_DEPTH 8 //number of bits to store colors

#endif
                                                         25
                  To read a bmp
#include "defines.h"

class CBmpFileReader{ //bmp file input class
  protected:
   BITMAPFILEHEADER m_BMPFileHead; //bmp header
   BITMAPINFOHEADER m_BMPFileInfo; //bmp file information
   RGBQUAD m_rgbPalette[COLORS]; //the palette
   BYTE *m_cImage; //the image
  public:
   CBmpFileReader(); //constructor
   ~CBmpFileReader(); //destructor
   BOOL load(char *filename); //load from file
   BOOL draw(LPDIRECTDRAWSURFACE surface); //draw image
   BOOL setpalette(LPDIRECTDRAWPALETTE palette); //set palette
};
                                                                 26
                  WinMain

   most important function in Main.cpp
   Where’s function main()?
   opens a window on the desktop
   registers the window w/ the os
   maintains a message “pump”



                                          27
              Main.cpp: WinMain
 MSG msg; //current message
 HWND window_handle; //handle to fullscreen window
 window_handle=
      CreateDefaultWindow("directX Animation",hInstance);
if(!window_handle)return FALSE;
ShowWindow(window_handle,nCmdShow);
UpdateWindow(window_handle);
SetFocus(window_handle); //allow input from keyboard
ShowCursor(FALSE); //hide the cursor
//init graphics
BOOL OK=InitDirectDraw(window_handle);//initialize DirectDraw
if(OK)OK= LoadImages(); //load images from disk
if(!OK){ //bail out if initialization failed
  DestroyWindow(window_handle); return FALSE;
}                                                        28
         The message “pump”
 //message loop
  while(TRUE)
   if(PeekMessage(&msg,NULL,0,0,PM_NOREMOVE)){
     if(!GetMessage(&msg,NULL,0,0))return msg.wParam;
     TranslateMessage(&msg); DispatchMessage(&msg);
   }
   else if(!ActiveApp)WaitMessage();
} //WinMain




                                                        29
 ddsetup.cpp: CreateDefaultWindow
HWND CreateDefaultWindow(char* name, HINSTANCE hInstance){
  WNDCLASS wc; //window registration info
  //register display window
  wc.style=CS_HREDRAW|CS_VREDRAW; //style
  wc.lpfnWndProc=WindowProc; //window message handler
  wc.cbClsExtra=wc.cbWndExtra=0;
  wc.hInstance=hInstance;
  wc.hIcon=LoadIcon(hInstance,IDI_APPLICATION);
  wc.hCursor=LoadCursor(NULL,IDC_ARROW);
  wc.hbrBackground=NULL;
  wc.lpszMenuName=NULL;
  wc.lpszClassName=name;
  RegisterClass(&wc);
  //create and set up fullscreen window
  return CreateWindowEx(WS_EX_TOPMOST,name,name,
    WS_POPUP,0,0,GetSystemMetrics(SM_CXSCREEN),
    GetSystemMetrics(SM_CYSCREEN),NULL,NULL,hInstance,NULL);
}
                                                               30
         WinMain(): LoadImages()
LPDIRECTDRAWPALETTE CreatePalette(LPDIRECTDRAWSURFACE surface);
BOOL InitDirectDraw(HWND window_handle);
HWND CreateDefaultWindow(char* name,HINSTANCE hInstance);

BOOL LoadImages(){ //load pictures from disk
  //draw the first image to the primary surface
  if(!background.load("backgrnd.bmp")) //read from file
    return FALSE; //read failed
  if(!background.setpalette(lpPrimaryPalette)) //set palette
    return FALSE; //set palette failed
  if(!background.draw(lpPrimary)) //draw to surface
    return FALSE; //draw failed
  return TRUE; //all steps succeeded
}
                                                               31
//message handler (window procedure)
long CALLBACK WindowProc(HWND window_handle,UINT message,
               WPARAM wParam,LPARAM lParam){
 switch(message){
  case WM_ACTIVATEAPP: ActiveApp=wParam; break;
  case WM_CREATE: break;
  case WM_KEYDOWN: //keyboard hit
   if(keyboard_handler(wParam))DestroyWindow(window_handle);
   break;
  case WM_DESTROY: //end of game
   if(lpDirectDrawObject!=NULL){ //if DD object exists
     if(lpPrimary!=NULL) //if primary surface exists
       lpPrimary->Release(); //release primary surface
     lpDirectDrawObject->Release(); //release DD object
   }
   ShowCursor(TRUE); //show the mouse cursor
   PostQuitMessage(0); //and exit
   break;
  default: //default window procedure
   return DefWindowProc(window_handle,message,wParam,lParam);
 } //switch(message)
 return 0L;
} //WindowProc
              WinMain(): WindowProc                             32
               How we get out

BOOL keyboard_handler(WPARAM keystroke){
 BOOL result=FALSE; //return TRUE if game is to end
 switch(keystroke){
   case VK_ESCAPE: result=TRUE; break; //exit game
 }
 return result;
} //keyboard_handler




                                                      33

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:9
posted:8/19/2012
language:English
pages:33