source: trunk/src/testing/app/wshare/ScreenCapture.cpp @ 4

Revision 4, 22.7 KB checked in by ajaworski, 13 years ago (diff)

Added modified SAGE sources

Line 
1/******************************************************************************
2 * SAGE - Scalable Adaptive Graphics Environment
3 *
4 * Copyright (C) 2004 Electronic Visualization Laboratory,
5 * University of Illinois at Chicago
6 *
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions are met:
11 *
12 *  * Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 *  * Redistributions in binary form must reproduce the above
15 *    copyright notice, this list of conditions and the following disclaimer
16 *    in the documentation and/or other materials provided with the distribution.
17 *  * Neither the name of the University of Illinois at Chicago nor
18 *    the names of its contributors may be used to endorse or promote
19 *    products derived from this software without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
25 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
26 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
27 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 *
33 * Direct questions, comments etc about SAGE to http://www.evl.uic.edu/cavern/forum/
34 *
35 *****************************************************************************/
36
37// ScreenCapture.cpp : Defines the entry point for the application.
38//
39
40#include "stdafx.h"
41#include "ScreenCapture.h"
42#include <stdio.h>
43#include "avifile.h"
44#include <shellapi.h>
45#include <commdlg.h>
46
47// headers for SAGE
48#include "sail.h"
49#include "misc.h"
50
51#include "libdxt.h"
52
53#include <direct.h>
54#include <stdio.h>
55#include <stdlib.h>
56#include <errno.h>
57
58
59sail *sageInf = NULL; // sail object
60
61#define MAX_LOADSTRING 100
62
63#define WM_NOTIFYICON_MESSAGE   WM_USER+1000
64
65#define ErrorMessage(x)         MessageBox(NULL,x,"Error",MB_OK|MB_ICONERROR)
66
67#define WINDOW_MODE                     true                            //Not in fullscreen mode
68#define BITSPERPIXEL            32
69
70HINSTANCE hInst;                                                                // current instance
71TCHAR szTitle[MAX_LOADSTRING];                                  // The title bar text
72TCHAR szWindowClass[MAX_LOADSTRING];                    // the main window class name
73
74ATOM                            MyRegisterClass(HINSTANCE hInstance);
75BOOL                            InitInstance(HINSTANCE, int);
76LRESULT CALLBACK        WndProc(HWND, UINT, WPARAM, LPARAM);
77LRESULT CALLBACK        About(HWND, UINT, WPARAM, LPARAM);
78
79HWND    ghWnd;
80HDC             hBackDC=NULL;
81LPVOID  pBits=NULL;
82HBITMAP hBackBitmap=NULL;
83HBITMAP hOldBitmap=NULL;
84
85int     nDisplayWidth;
86int     nDisplayHeight;
87
88IDirect3D9*                     g_pD3D=NULL;
89IDirect3DDevice9*       g_pd3dDevice=NULL;
90IDirect3DSurface9*      g_pSurface=NULL;
91
92HRESULT Reset();
93void    Render();
94void    Cleanup();
95HRESULT InitD3D(HWND hWnd);
96void    SaveBitmap(char *szFilename,HBITMAP hBitmap);
97
98UINT_PTR        nTimerId=0;
99CAviFile        *pAviFile=NULL;
100HMENU           ghMenu=NULL;
101RECT            gScreenRect ={0,0,0,0};
102bool            gbCapturing=false;
103
104int     nScreenWidth;
105int     nScreenHeight;
106HWND    hDesktopWnd;
107HDC     hDesktopDC;
108HDC     hCaptureDC;
109HBITMAP hCaptureBitmap;
110
111
112
113
114int APIENTRY _tWinMain(HINSTANCE hInstance,
115                     HINSTANCE hPrevInstance,
116                     LPTSTR    lpCmdLine,
117                     int       nCmdShow)
118{
119        MSG msg;
120        HACCEL hAccelTable;
121
122        // Initialize global strings
123        LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
124        LoadString(hInstance, IDC_SCREENCAPTURE, szWindowClass, MAX_LOADSTRING);
125        MyRegisterClass(hInstance);
126
127        // Perform application initialization:
128        if (!InitInstance (hInstance, nCmdShow))
129        {
130                return FALSE;
131        }
132
133        hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_SCREENCAPTURE);
134
135        // Main message loop:
136        while (GetMessage(&msg, NULL, 0, 0))
137        {
138                if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
139                {
140                        TranslateMessage(&msg);
141                        DispatchMessage(&msg);
142                }
143        }
144
145        return (int) msg.wParam;
146}
147
148
149
150//
151//  FUNCTION: MyRegisterClass()
152//
153//  PURPOSE: Registers the window class.
154//
155//  COMMENTS:
156//
157//    This function and its usage are only necessary if you want this code
158//    to be compatible with Win32 systems prior to the 'RegisterClassEx'
159//    function that was added to Windows 95. It is important to call this function
160//    so that the application will get 'well formed' small icons associated
161//    with it.
162//
163ATOM MyRegisterClass(HINSTANCE hInstance)
164{
165        WNDCLASSEX wcex;
166
167        wcex.cbSize = sizeof(WNDCLASSEX);
168
169        wcex.style                      = CS_HREDRAW | CS_VREDRAW;
170        wcex.lpfnWndProc        = (WNDPROC)WndProc;
171        wcex.cbClsExtra         = 0;
172        wcex.cbWndExtra         = 0;
173        wcex.hInstance          = hInstance;
174        wcex.hIcon                      = LoadIcon(hInstance, (LPCTSTR)IDI_SCREENCAPTURE);
175        wcex.hCursor            = LoadCursor(NULL, IDC_ARROW);
176        wcex.hbrBackground      = NULL;//(HBRUSH)(COLOR_WINDOW+1);
177        wcex.lpszMenuName       = (LPCTSTR)IDC_SCREENCAPTURE;
178        wcex.lpszClassName      = szWindowClass;
179        wcex.hIconSm            = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);
180
181        return RegisterClassEx(&wcex);
182}
183
184//
185//   FUNCTION: InitInstance(HANDLE, int)
186//
187//   PURPOSE: Saves instance handle and creates main window
188//
189//   COMMENTS:
190//
191//        In this function, we save the instance handle in a global variable and
192//        create and display the main program window.
193//
194BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
195{
196
197   hInst = hInstance; // Store instance handle in our global variable
198
199   ghWnd = CreateWindow(szWindowClass, szTitle, WS_POPUPWINDOW|WS_CAPTION|WS_VISIBLE,
200      480, 400, 320, 240, NULL, NULL, hInstance, NULL);
201
202   if (!ghWnd)
203   {
204      return FALSE;
205   }
206
207   ShowWindow(ghWnd, nCmdShow);
208   UpdateWindow(ghWnd);
209
210   return TRUE;
211}
212
213//
214//  FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
215//
216//  PURPOSE:  Processes messages for the main window.
217//
218//  WM_COMMAND  - process the application menu
219//  WM_PAINT    - Paint the main window
220//  WM_DESTROY  - post a quit message and return
221//
222//
223LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
224{
225        int wmId, wmEvent;
226        static NOTIFYICONDATA   nid;
227        static RECT     clientRect = {0,0,0,0};
228        static bool     bMinimized=false;
229
230        switch (message)
231        {
232        case WM_SYSCOMMAND:
233                {
234                        if(wParam==SC_CLOSE)
235                        {
236                                SendMessage(hWnd,WM_SYSCOMMAND,SC_MINIMIZE,0);
237                                return 0;
238                        }
239                        if(wParam==SC_MINIMIZE)
240                        {
241                                bMinimized=true;
242                                LONG_PTR ret=DefWindowProc(hWnd,message,wParam,lParam);
243                                SendMessage(hWnd,WM_COMMAND,MAKEWPARAM(ID_FILE_HIDEWINDOW,0),0);
244                                return ret;
245                        }
246                        return DefWindowProc(hWnd, message, wParam, lParam);
247                }
248
249        case WM_COMMAND:
250                wmId    = LOWORD(wParam);
251                wmEvent = HIWORD(wParam);
252                // Parse the menu selections:
253                switch (wmId)
254                {
255                case ID_FILE_STARTCAPTURINGTOAVI:
256                case ID_CAPTURE_START:
257                        {
258                                if(pAviFile==NULL)
259                                {
260                                        OPENFILENAME    ofn;
261                                        char    szFileName[512];
262                                        strcpy(szFileName,"Output.avi");
263                                        ZeroMemory(&ofn,sizeof(ofn));
264                                        ofn.lStructSize=sizeof(OPENFILENAME);
265                                        ofn.Flags=OFN_HIDEREADONLY|OFN_PATHMUSTEXIST;
266                                        ofn.lpstrFilter="Avi Files (*.avi)\0*.avi\0";
267                                        ofn.lpstrDefExt="avi";
268                                        ofn.lpstrFile=szFileName;
269                                        ofn.nMaxFile=512;
270                                        ofn.hwndOwner = hWnd;
271                                        if(!GetSaveFileName(&ofn))      break;
272
273                                        pAviFile = new CAviFile(szFileName);
274
275                                        nScreenWidth = GetSystemMetrics(SM_CXSCREEN);
276                                        nScreenHeight = GetSystemMetrics(SM_CYSCREEN);
277
278                                        //aInitialize();
279                                        //aLog("%d %d \n",nScreenWidth, nScreenHeight);
280
281                                        sageInf = new sail();
282                                        _chdir("C:\\sources\\sage3.0\\bin");
283
284                                        sailConfig scfg;
285                                        scfg.init("screencapture.conf");
286                                        scfg.setAppName("screencapture");
287                                        scfg.rank = 0;
288                                        scfg.master = true;
289                                        scfg.nwID = 1;
290                                        scfg.syncPort = 13000;
291                                        scfg.nodeNum = 1;
292                                        scfg.blockX= 64;
293                                        scfg.blockY= 64;
294                                        scfg.pixFmt = PIXFMT_888_INV;
295                                        //scfg.pixFmt = PIXFMT_8888_INV;
296                                        //scfg.pixFmt = PIXFMT_DXT;
297                                        scfg.rowOrd = BOTTOM_TO_TOP;
298                                        scfg.resX = nScreenWidth;
299                                        scfg.resY = nScreenHeight;
300                                        sageRect renderImageMap;
301                                        renderImageMap.left = 0.0;
302                                        renderImageMap.right = 1.0;
303                                        renderImageMap.bottom = 0.0;
304                                        renderImageMap.top = 1.0;
305                                        scfg.imageMap = renderImageMap;
306
307                                        scfg.winX = 0;
308                                        scfg.winY = 0;
309                                        scfg.winWidth  = nScreenWidth*2;
310                                        scfg.winHeight = nScreenHeight*2;
311
312                                        sageInf->init(scfg);
313                                        //aLog("Init done\n");
314
315                                        BITMAPINFO      bmpInfo;
316                                        ZeroMemory(&bmpInfo,sizeof(BITMAPINFO));
317                                        bmpInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
318                                        bmpInfo.bmiHeader.biBitCount=24;//BITSPERPIXEL;
319                                        bmpInfo.bmiHeader.biCompression = BI_RGB;
320                                        bmpInfo.bmiHeader.biWidth=nScreenWidth;
321                                        bmpInfo.bmiHeader.biHeight=nScreenHeight;
322                                        bmpInfo.bmiHeader.biPlanes=1;
323                                        bmpInfo.bmiHeader.biSizeImage=abs(bmpInfo.bmiHeader.biHeight)*bmpInfo.bmiHeader.biWidth*bmpInfo.bmiHeader.biBitCount/8;
324
325                                        hDesktopWnd = GetDesktopWindow();
326                                        hDesktopDC = GetDC(hDesktopWnd);
327                                        hCaptureDC = CreateCompatibleDC(hDesktopDC);
328                                        hCaptureBitmap = CreateDIBSection(hDesktopDC,&bmpInfo,DIB_RGB_COLORS,&pBits,NULL,0);
329                                        SelectObject(hCaptureDC,hCaptureBitmap);
330                                }
331
332                                nid.hIcon=LoadIcon(hInst,MAKEINTRESOURCE(IDI_ICON_PAUSE));
333                                strcpy(nid.szTip,"Capturing the Screen - Double Click to Pause");
334
335                                if(!Shell_NotifyIcon(NIM_MODIFY,&nid))                          //Modify the Icon State
336                                        MessageBox(NULL,"Unable to Set Notification Icon","Error",MB_ICONINFORMATION|MB_OK);
337
338                                SendMessage(hWnd,WM_SYSCOMMAND,SC_MINIMIZE,0);
339
340                gbCapturing = true;
341
342                                break;
343                        }
344                case ID_FILE_PAUSECAPTURINGTOAVI:
345                case ID_CAPTURE_STOP:
346                        {
347                                nid.hIcon=LoadIcon(hInst,MAKEINTRESOURCE(IDI_ICON_START));
348                                strcpy(nid.szTip,"Screen Capture Paused - Double Click to Resume");
349
350                                if(!Shell_NotifyIcon(NIM_MODIFY,&nid))                          //Modify the Icon State
351                                        MessageBox(NULL,"Unable to Set Notification Icon","Error",MB_ICONINFORMATION|MB_OK);
352
353                                gbCapturing = false;
354
355                                break;
356                        }
357                case ID_FILE_SHOWWINDOW:
358                        {
359                                if(bMinimized)  ShowWindow(hWnd,SW_RESTORE);
360                                else                    ShowWindow(hWnd,SW_SHOW);
361                                SetForegroundWindow(hWnd);
362                                bMinimized=false;
363                                break;
364                        }
365                case ID_FILE_HIDEWINDOW:
366                        {
367                                ShowWindow(hWnd,SW_HIDE);
368                                break;
369                        }
370                case ID_FILE_CAPTURESCREENSHOT:
371                case ID_EDIT_SAVEASBMP:
372                        {
373                                OPENFILENAME    ofn;
374                                char    szFileName[512];
375
376                                strcpy(szFileName,"ScreenShot.bmp");
377
378                ZeroMemory(&ofn,sizeof(ofn));
379                                ofn.lStructSize=sizeof(OPENFILENAME);
380                                ofn.Flags=OFN_HIDEREADONLY|OFN_PATHMUSTEXIST;
381                                ofn.lpstrFilter="Bitmap Files (*.bmp)\0*.bmp\0";
382                                ofn.lpstrDefExt="bmp";
383                                ofn.lpstrFile=szFileName;
384                                ofn.nMaxFile=512;
385                                ofn.hwndOwner = hWnd;
386                                if(!GetSaveFileName(&ofn))      break;
387
388                                SetCursor(LoadCursor(NULL,IDC_WAIT));
389
390                                g_pd3dDevice->GetFrontBufferData(0, g_pSurface);
391                                D3DXSaveSurfaceToFile(szFileName,D3DXIFF_BMP,g_pSurface,NULL,NULL);             //Save to File
392
393                                D3DLOCKED_RECT  lockedRect;
394                                if(FAILED(g_pSurface->LockRect(&lockedRect,NULL,D3DLOCK_NO_DIRTY_UPDATE|D3DLOCK_NOSYSLOCK|D3DLOCK_READONLY)))
395                                {
396                                        ErrorMessage("Unable to Lock Front Buffer Surface");    break;
397                                }
398                                for(int i=0;i<gScreenRect.bottom;i++)
399                                {
400                                        memcpy((BYTE*)pBits+(gScreenRect.bottom-i-1)*gScreenRect.right*BITSPERPIXEL/8,(BYTE*)lockedRect.pBits+i*lockedRect.Pitch,gScreenRect.right*BITSPERPIXEL/8);//g_d3dpp.BackBufferHeight*g_d3dpp.BackBufferWidth*4);
401                                }
402                                g_pSurface->UnlockRect();
403                                InvalidateRect(hWnd,NULL,false);
404
405                                SetCursor(LoadCursor(NULL,IDC_ARROW));
406                                break;
407                        }
408                case IDM_ABOUT:
409                        DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
410                        break;
411                case IDM_EXIT:
412                        DestroyWindow(hWnd);
413                        break;
414                default:
415                        return DefWindowProc(hWnd, message, wParam, lParam);
416                }
417                break;
418        case WM_INITMENU:
419                {
420                        HMENU   hMenu = (HMENU)wParam;
421                        EnableMenuItem(hMenu,ID_FILE_SHOWWINDOW,IsWindowVisible(hWnd)?MF_GRAYED:MF_ENABLED|MF_BYCOMMAND);
422                        EnableMenuItem(hMenu,ID_FILE_HIDEWINDOW,IsWindowVisible(hWnd)?MF_ENABLED:MF_GRAYED|MF_BYCOMMAND);
423                        EnableMenuItem(hMenu,ID_FILE_CAPTURESCREENSHOT,gbCapturing?MF_GRAYED|MF_BYCOMMAND:MF_ENABLED);
424                        EnableMenuItem(hMenu,ID_FILE_STARTCAPTURINGTOAVI,gbCapturing?MF_GRAYED|MF_BYCOMMAND:MF_ENABLED);
425                        EnableMenuItem(hMenu,ID_FILE_PAUSECAPTURINGTOAVI,gbCapturing?MF_ENABLED:MF_GRAYED|MF_BYCOMMAND);
426                        EnableMenuItem(hMenu,ID_CAPTURE_START,gbCapturing?MF_GRAYED|MF_BYCOMMAND:MF_ENABLED);
427                        EnableMenuItem(hMenu,ID_CAPTURE_STOP,gbCapturing?MF_ENABLED:MF_GRAYED|MF_BYCOMMAND);
428                        break;
429                }
430        case WM_INITMENUPOPUP:
431                {
432                        EnableMenuItem(ghMenu,ID_FILE_SHOWWINDOW,IsWindowVisible(hWnd)?MF_GRAYED:MF_ENABLED|MF_BYCOMMAND);
433                        EnableMenuItem(ghMenu,ID_FILE_HIDEWINDOW,IsWindowVisible(hWnd)?MF_ENABLED:MF_GRAYED|MF_BYCOMMAND);
434                        EnableMenuItem(ghMenu,ID_FILE_CAPTURESCREENSHOT,gbCapturing?MF_GRAYED|MF_BYCOMMAND:MF_ENABLED);
435                        EnableMenuItem(ghMenu,ID_FILE_STARTCAPTURINGTOAVI,gbCapturing?MF_GRAYED|MF_BYCOMMAND:MF_ENABLED);
436                        EnableMenuItem(ghMenu,ID_FILE_PAUSECAPTURINGTOAVI,gbCapturing?MF_ENABLED:MF_GRAYED|MF_BYCOMMAND);
437                        EnableMenuItem(ghMenu,ID_CAPTURE_START,gbCapturing?MF_GRAYED|MF_BYCOMMAND:MF_ENABLED);
438                        EnableMenuItem(ghMenu,ID_CAPTURE_STOP,gbCapturing?MF_ENABLED:MF_GRAYED|MF_BYCOMMAND);
439                        break;
440                }
441        case WM_CREATE:
442                {
443                        LRESULT ret=DefWindowProc(hWnd,message,wParam,lParam);
444                        if(ret<0)       return ret;
445
446                        BITMAPINFO      bmpInfo;
447                        ZeroMemory(&bmpInfo,sizeof(BITMAPINFO));
448                        bmpInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
449                        bmpInfo.bmiHeader.biBitCount=BITSPERPIXEL;
450                        bmpInfo.bmiHeader.biCompression = BI_RGB;
451                        bmpInfo.bmiHeader.biWidth=GetSystemMetrics(SM_CXSCREEN);
452                        bmpInfo.bmiHeader.biHeight=GetSystemMetrics(SM_CYSCREEN);
453                        bmpInfo.bmiHeader.biPlanes=1;
454                        bmpInfo.bmiHeader.biSizeImage=abs(bmpInfo.bmiHeader.biHeight)*bmpInfo.bmiHeader.biWidth*bmpInfo.bmiHeader.biBitCount/8;
455
456                        HDC     hdc=GetDC(GetDesktopWindow());
457                        hBackDC=CreateCompatibleDC(hdc);
458                        hBackBitmap=CreateDIBSection(hdc,&bmpInfo,DIB_RGB_COLORS,&pBits,NULL,0);
459                        if(hBackBitmap==NULL)
460                        {
461                                ErrorMessage("Unable to Create BackBuffer Bitamp");             return -1;
462                        }
463                        ReleaseDC(GetDesktopWindow(),hdc);
464
465                        ZeroMemory(&nid,sizeof(nid));
466                        nid.cbSize=sizeof(nid);
467                        nid.uID=1000;
468                        nid.uFlags=NIF_ICON|NIF_MESSAGE|NIF_TIP;
469                        nid.hIcon=LoadIcon(hInst,MAKEINTRESOURCE(IDI_SCREENCAPTURE));
470                        nid.hWnd=hWnd;
471                        strcpy(nid.szTip,"Screen Capture Application - Double Click to Start Capturing");
472                        nid.uCallbackMessage=WM_NOTIFYICON_MESSAGE;
473                        if(!Shell_NotifyIcon(NIM_ADD,&nid))     MessageBox(NULL,"Unable to Set Notification Icon","Error",MB_ICONINFORMATION|MB_OK);
474                        ghMenu=LoadMenu(hInst,MAKEINTRESOURCE(IDC_SCREENCAPTURE));
475
476                        if(FAILED(InitD3D(hWnd)))       return -1;
477
478                        nTimerId=SetTimer(hWnd,1,1000/35,NULL); //Timer set to 500 ms.
479
480                        return ret;
481                }
482        case WM_CHAR:
483                {
484                        if(wParam==VK_ESCAPE)
485                                DestroyWindow(hWnd);
486                        break;
487                }
488        case WM_TIMER:
489                {
490                        if(gbCapturing == false)        break;
491
492                        /*
493                        D3DLOCKED_RECT  lockedRect;
494                        g_pd3dDevice->GetFrontBufferData(0, g_pSurface);
495                        if(FAILED(g_pSurface->LockRect(&lockedRect,&gScreenRect,D3DLOCK_NO_DIRTY_UPDATE|D3DLOCK_NOSYSLOCK|D3DLOCK_READONLY)))
496                        {
497                                ErrorMessage("Unable to Lock Front Buffer Surface");    break;
498                        }
499                        for(int i=0;i<gScreenRect.bottom;i++)
500                        {
501                                //memcpy((BYTE*)pBits+(gScreenRect.bottom-i-1)*gScreenRect.right*BITSPERPIXEL/8,(BYTE*)lockedRect.pBits+i*lockedRect.Pitch,gScreenRect.right*BITSPERPIXEL/8);
502                        }
503                        g_pSurface->UnlockRect();
504                        InvalidateRect(hWnd,NULL,false);
505                        */
506
507                        //pAviFile->AppendNewFrame(gScreenRect.right,gScreenRect.bottom,pBits);                 //Append this Captured ScreenShot to the Movie
508
509                        void *buffer = sageInf->getBuffer();
510                        BitBlt(hCaptureDC,0,0,nScreenWidth,nScreenHeight,hDesktopDC,0,0,SRCCOPY|CAPTUREBLT);
511
512                    //CompressDXT((const byte*)pBits, (byte*)buffer, nScreenWidth, nScreenHeight, FORMAT_DXT1, 1);
513
514                        //memcpy(buffer, pBits, nScreenWidth*nScreenHeight*4);
515
516                        memcpy(buffer, pBits, nScreenWidth*nScreenHeight*3);
517
518                        sageInf->swapBuffer();
519
520                        sageMessage msg;
521                        if (sageInf->checkMsg(msg, false) > 0) {
522                                switch (msg.getCode()) {
523                                         case APP_QUIT : {
524                                                sageInf->shutdown();
525                                                exit(0);
526                                        break;
527                                        }
528                                }
529                        }
530
531                        break;
532                }
533        case WM_PAINT:
534                {
535                        PAINTSTRUCT     ps;
536                        HBITMAP hOldBitmap = (HBITMAP)SelectObject(hBackDC,hBackBitmap);
537                        HDC hdc = BeginPaint(hWnd, &ps);
538                        StretchBlt(hdc,0,0,clientRect.right,clientRect.bottom,hBackDC,0,0,gScreenRect.right,gScreenRect.bottom,SRCCOPY);
539                        EndPaint(hWnd, &ps);
540                        SelectObject(hBackDC,hOldBitmap);
541                        break;
542                }
543        case WM_SIZE:
544                {
545                        clientRect.right = LOWORD(lParam);
546                        clientRect.bottom = HIWORD(lParam);
547                        break;
548                }
549        case WM_NOTIFYICON_MESSAGE:
550                {
551                        switch(lParam)
552                        {
553                                case WM_MOUSEMOVE:break;
554                                case WM_LBUTTONDBLCLK:
555                                        {
556                                                SendMessage(hWnd,WM_COMMAND,MAKEWPARAM(gbCapturing?ID_FILE_PAUSECAPTURINGTOAVI:ID_FILE_STARTCAPTURINGTOAVI,0),0);
557                                                break;
558                                        }
559                                case WM_RBUTTONDOWN:
560                                        {
561                                                POINT pt;GetCursorPos(&pt);
562                                                SetForegroundWindow(hWnd);
563                                                TrackPopupMenu(GetSubMenu(ghMenu,0),TPM_LEFTALIGN|TPM_BOTTOMALIGN,pt.x,pt.y,0,hWnd,NULL);
564                                                break;
565                                        }
566                        }
567                        break;
568                }
569        case WM_DESTROY:
570                {
571                        if(nTimerId)
572                        {
573                                KillTimer(hWnd,nTimerId);
574                                nTimerId=0;
575                        }
576                        Cleanup();
577                        if(pAviFile)
578                        {
579                                delete pAviFile;
580                                pAviFile = NULL;
581                        }
582                        if(hBackDC)
583                        {
584                                DeleteDC(hBackDC);
585                                hBackDC=NULL;
586                        }
587                        if(hBackBitmap)
588                        {
589                                DeleteObject(hBackBitmap);
590                                hBackBitmap=NULL;
591                        }
592                        Shell_NotifyIcon(NIM_DELETE,&nid);
593                        DestroyMenu(ghMenu);
594                        PostQuitMessage(0);
595                        break;
596                }
597        default:
598                return DefWindowProc(hWnd, message, wParam, lParam);
599        }
600        return 0;
601}
602
603// Message handler for about box.
604LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
605{
606        switch (message)
607        {
608        case WM_INITDIALOG:
609                return TRUE;
610
611        case WM_COMMAND:
612                if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
613                {
614                        EndDialog(hDlg, LOWORD(wParam));
615                        return TRUE;
616                }
617                break;
618        }
619        return FALSE;
620}
621
622void Render()
623{
624        HRESULT hr;
625        if(g_pd3dDevice)
626        {
627                hr=g_pd3dDevice->TestCooperativeLevel();//Check Device Status - if Alt+tab or some such thing have caused any trouble
628                if(hr!=D3D_OK)
629                {
630                        if(hr==D3DERR_DEVICELOST)       return; //Device is lost - Do not render now
631                        if(hr==D3DERR_DEVICENOTRESET)           //Device is ready to be acquired
632                        {
633                                if(FAILED(Reset()))
634                                {
635                                        DestroyWindow(ghWnd);           //If Unable to Reset Device - Close the Application
636                                        return;
637                                }
638                        }
639                }
640                g_pd3dDevice->Clear(0,NULL,D3DCLEAR_TARGET,D3DCOLOR_XRGB(0,0,200),1.0f,0);
641                g_pd3dDevice->BeginScene();
642                g_pd3dDevice->EndScene();
643                g_pd3dDevice->Present(NULL,NULL,NULL,NULL);
644        }
645}
646
647void Cleanup()
648{
649        if(g_pSurface)
650        {
651                g_pSurface->Release();
652                g_pSurface=NULL;
653        }
654        if(g_pd3dDevice)
655        {
656                g_pd3dDevice->Release();
657                g_pd3dDevice=NULL;
658        }
659        if(g_pD3D)
660        {
661                g_pD3D->Release();
662                g_pD3D=NULL;
663        }
664}
665
666HRESULT InitD3D(HWND hWnd)
667{
668        D3DDISPLAYMODE  ddm;
669        D3DPRESENT_PARAMETERS   d3dpp;
670
671        if((g_pD3D=Direct3DCreate9(D3D_SDK_VERSION))==NULL)
672        {
673                ErrorMessage("Unable to Create Direct3D ");
674                return E_FAIL;
675        }
676
677        if(FAILED(g_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,&ddm)))
678        {
679                ErrorMessage("Unable to Get Adapter Display Mode");
680                return E_FAIL;
681        }
682
683        ZeroMemory(&d3dpp,sizeof(D3DPRESENT_PARAMETERS));
684
685        d3dpp.Windowed=WINDOW_MODE;
686        d3dpp.Flags=D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
687        d3dpp.BackBufferFormat=ddm.Format;
688        d3dpp.BackBufferHeight=nDisplayHeight=gScreenRect.bottom =ddm.Height;
689        d3dpp.BackBufferWidth=nDisplayWidth=gScreenRect.right =ddm.Width;
690        d3dpp.MultiSampleType=D3DMULTISAMPLE_NONE;
691        d3dpp.SwapEffect=D3DSWAPEFFECT_DISCARD;
692        d3dpp.hDeviceWindow=hWnd;
693        d3dpp.PresentationInterval=D3DPRESENT_INTERVAL_DEFAULT;
694        d3dpp.FullScreen_RefreshRateInHz=D3DPRESENT_RATE_DEFAULT;
695
696        if(FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hWnd,D3DCREATE_SOFTWARE_VERTEXPROCESSING ,&d3dpp,&g_pd3dDevice)))
697        {
698                ErrorMessage("Unable to Create Device");
699                return E_FAIL;
700        }
701
702        if(FAILED(g_pd3dDevice->CreateOffscreenPlainSurface(ddm.Width, ddm.Height, D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &g_pSurface, NULL)))
703        {
704                ErrorMessage("Unable to Create Surface");
705                return E_FAIL;
706        }
707
708        return S_OK;
709}
710
711HRESULT Reset()
712{
713        D3DDISPLAYMODE  ddm;
714        D3DPRESENT_PARAMETERS   d3dpp;
715
716        if(g_pSurface)                                                                                                          //Release the Surface - we need to get the latest surface
717        {
718                g_pSurface->Release();
719                g_pSurface = NULL;
720        }
721
722        if(FAILED(g_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT,&ddm)))      //User might have changed the mode - Get it afresh
723        {
724                ErrorMessage("Unable to Get Adapter Display Mode");
725                return E_FAIL;
726        }
727
728        ZeroMemory(&d3dpp,sizeof(D3DPRESENT_PARAMETERS));
729
730        d3dpp.Windowed=WINDOW_MODE;
731        d3dpp.Flags=D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
732        d3dpp.BackBufferFormat=ddm.Format;
733        d3dpp.BackBufferHeight=nDisplayHeight=gScreenRect.bottom =ddm.Height;
734        d3dpp.BackBufferWidth=nDisplayWidth=gScreenRect.right =ddm.Width;
735        d3dpp.MultiSampleType=D3DMULTISAMPLE_NONE;
736        d3dpp.SwapEffect=D3DSWAPEFFECT_DISCARD;
737        d3dpp.hDeviceWindow=ghWnd;
738        d3dpp.PresentationInterval=D3DPRESENT_INTERVAL_DEFAULT;
739        d3dpp.FullScreen_RefreshRateInHz=D3DPRESENT_RATE_DEFAULT;
740
741        if(FAILED(g_pd3dDevice->Reset(&d3dpp)))
742        {
743                //ErrorMessage("Unable to Create Device");                              //Dont present messages when device is lost
744                return E_FAIL;
745        }
746
747        if(FAILED(g_pd3dDevice->CreateOffscreenPlainSurface(ddm.Width, ddm.Height, D3DFMT_A8R8G8B8, D3DPOOL_SCRATCH, &g_pSurface, NULL)))
748        {
749                //ErrorMessage("Unable to Create Surface");
750                return E_FAIL;
751        }
752
753        return S_OK;
754}
755
756void    SaveBitmap(char *szFilename,HBITMAP hBitmap)
757{
758        HDC                                     hdc=NULL;
759        FILE*                           fp=NULL;
760        LPVOID                          pBuf=NULL;
761        BITMAPINFO                      bmpInfo;
762        BITMAPFILEHEADER        bmpFileHeader;
763
764        do{
765
766                hdc=GetDC(NULL);
767                ZeroMemory(&bmpInfo,sizeof(BITMAPINFO));
768                bmpInfo.bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
769                GetDIBits(hdc,hBitmap,0,0,NULL,&bmpInfo,DIB_RGB_COLORS);
770
771                if(bmpInfo.bmiHeader.biSizeImage<=0)
772                        bmpInfo.bmiHeader.biSizeImage=bmpInfo.bmiHeader.biWidth*abs(bmpInfo.bmiHeader.biHeight)*(bmpInfo.bmiHeader.biBitCount+7)/8;
773
774                if((pBuf=malloc(bmpInfo.bmiHeader.biSizeImage))==NULL)
775                {
776                        MessageBox(NULL,_T("Unable to Allocate Bitmap Memory"),_T("Error"),MB_OK|MB_ICONERROR);
777                        break;
778                }
779
780                bmpInfo.bmiHeader.biCompression=BI_RGB;
781                GetDIBits(hdc,hBitmap,0,bmpInfo.bmiHeader.biHeight,pBuf,&bmpInfo,DIB_RGB_COLORS);
782
783                if((fp=fopen(szFilename,"wb"))==NULL)
784                {
785                        MessageBox(NULL,_T("Unable to Create Bitmap File"),_T("Error"),MB_OK|MB_ICONERROR);
786                        break;
787                }
788
789                bmpFileHeader.bfReserved1=0;
790                bmpFileHeader.bfReserved2=0;
791                bmpFileHeader.bfSize=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+bmpInfo.bmiHeader.biSizeImage;
792                bmpFileHeader.bfType='MB';
793                bmpFileHeader.bfOffBits=sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER);
794
795                fwrite(&bmpFileHeader,sizeof(BITMAPFILEHEADER),1,fp);
796                fwrite(&bmpInfo.bmiHeader,sizeof(BITMAPINFOHEADER),1,fp);
797                fwrite(pBuf,bmpInfo.bmiHeader.biSizeImage,1,fp);
798
799        }while(false);
800
801                if(hdc)
802                        ReleaseDC(NULL,hdc);
803
804                if(pBuf)
805                        free(pBuf);
806
807                if(fp)
808                        fclose(fp);
809}
Note: See TracBrowser for help on using the repository browser.