Example #1
0
/* NOTES:
 *   For Win16, programmers generally use WINAPI WinMain(...) but WINAPI is defined in such a way
 *   that it always makes the function prolog return FAR. Unfortunately, when Watcom C's runtime
 *   calls this function in a memory model that's compact or small, the call is made as if NEAR,
 *   not FAR. To avoid a GPF or crash on return, we must simply declare it PASCAL instead. */
int PASCAL WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) {
	WNDCLASS wnd;
	MSG msg;

	myInstance = hInstance;

#if TARGET_MSDOS == 16 && TARGET_WINDOWS < 31 /* Windows 3.0 or older (any version capable of real-mode) */
    /* our data segment is discardable.
     * in Windows 3.0 real mode that means our data segment can disappear out from under us.
     * unfortunately I don't know how to call the data segment back in.
     * so we have to compensate by locking our data segment in place. */
    LockData();
#endif

	/* FIXME: Windows 3.0 Real Mode: Why are we unable to load our own Application Icon? */
	AppIcon = LoadIcon(hInstance,MAKEINTRESOURCE(IDI_APPICON));
	if (!AppIcon) MessageBox(NULL,"Unable to load app icon","Oops!",MB_OK);

#ifdef WIN16_NEEDS_MAKEPROCINSTANCE
	WndProc_MPI = MakeProcInstance((FARPROC)WndProc,hInstance);
#endif

	/* NTS: In the Windows 3.1 environment all handles are global. Registering a class window twice won't work.
	 *      It's only under 95 and later (win32 environment) where Windows always sets hPrevInstance to 0
	 *      and window classes are per-application.
	 *
	 *      Windows 3.1 allows you to directly specify the FAR pointer. Windows 3.0 however demands you
	 *      MakeProcInstance it to create a 'thunk' so that Windows can call you (ick). */
	if (!hPrevInstance) {
		wnd.style = CS_HREDRAW|CS_VREDRAW;
#ifdef WIN16_NEEDS_MAKEPROCINSTANCE
		wnd.lpfnWndProc = (WNDPROC)WndProc_MPI;
#else
		wnd.lpfnWndProc = WndProc;
#endif
		wnd.cbClsExtra = 0;
		wnd.cbWndExtra = 0;
		wnd.hInstance = hInstance;
		wnd.hIcon = AppIcon;
		wnd.hCursor = NULL;
		wnd.hbrBackground = NULL;
		wnd.lpszMenuName = NULL;
		wnd.lpszClassName = WndProcClass;

		if (!RegisterClass(&wnd)) {
			MessageBox(NULL,"Unable to register Window class","Oops!",MB_OK);
			return 1;
		}
	}

	HelloMsg();

	hwndMain = CreateWindow(WndProcClass,"Hello!",
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT,CW_USEDEFAULT,
		300,200,
		NULL,NULL,
		hInstance,NULL);
	if (!hwndMain) {
		MessageBox(NULL,"Unable to create window","Oops!",MB_OK);
		return 1;
	}

	ShowWindow(hwndMain,nCmdShow);
	UpdateWindow(hwndMain); /* FIXME: For some reason this only causes WM_PAINT to print gibberish and cause a GPF. Why? And apparently, Windows 3.0 repaints our window anyway! */

	while (GetMessage(&msg,NULL,0,0)) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

#if TARGET_MSDOS == 16
    /* Win16 only:
     * If we are the owner (the first instance that registered the window class),
     * then we must reside in memory until we are the last instance resident.
     * If we do not do this, then if multiple instances are open and the user closes US
     * before closing the others, the others will crash (having pulled the code segment
     * behind the window class out from the other processes). */
	if (!hPrevInstance) {
        while (GetModuleUsage(hInstance) > 1) {
            PeekMessage(&msg,NULL,0,0,PM_REMOVE);
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
#endif

	return msg.wParam;
}
Example #2
0
char *WREGetFileName( WREGetFileStruct *gf, DWORD flags, WREGetFileAction action )
{
    OPENFILENAME  wreofn;
    HWND          owner_window;
    bool          ret;
    DWORD         error;
    int           len;
    char          fn_drive[_MAX_DRIVE];
    char          fn_dir[_MAX_DIR];
    char          fn_name[_MAX_FNAME];
    char          fn_ext[_MAX_EXT + 1];
    HINSTANCE     app_inst;

    if( gf == NULL ) {
        return( NULL );
    }

    owner_window = WREGetMainWindowHandle();
    app_inst = WREGetAppInstance();

    if( app_inst == NULL || owner_window == NULL ) {
        return( NULL );
    }

    if( gf->title != NULL ) {
        len = strlen( gf->title );
        if( len < _MAX_PATH ) {
            memcpy( wrefntitle, gf->title, len + 1 );
        } else {
            memcpy( wrefntitle, gf->title, _MAX_PATH );
            wrefntitle[_MAX_PATH - 1] = 0;
        }
    } else {
        wrefntitle[0] = 0;
    }

    if( gf->file_name != NULL && *gf->file_name != '\0' ) {
        _splitpath( gf->file_name, fn_drive, fn_dir, fn_name, fn_ext );
        if( *fn_drive != '\0' || *fn_dir != '\0' ) {
            _makepath( wre_initial_dir, fn_drive, fn_dir, NULL, NULL );
        }
        _makepath( wre_file_name, NULL, NULL, fn_name, fn_ext );
    } else {
        wre_file_name[0] = 0;
    }

    /* set the initial directory */
    if( *wre_initial_dir == '\0' ) {
        getcwd( wre_initial_dir, _MAX_PATH );
    }

#if !defined ( __NT__ )
    // CTL3D no longer requires this
    flags |= OFN_ENABLEHOOK;
#endif

    /* initialize the OPENFILENAME struct */
    memset( &wreofn, 0, sizeof( OPENFILENAME ) );

    /* fill in non-variant fields of OPENFILENAME struct */
    wreofn.lStructSize = sizeof( OPENFILENAME );
    wreofn.hwndOwner = owner_window;
    wreofn.hInstance = app_inst;
    wreofn.lpstrFilter = gf->filter;
    wreofn.lpstrCustomFilter = NULL;
    wreofn.nMaxCustFilter = 0;
    wreofn.nFilterIndex = WREFindFileFilterIndex( gf->filter );
    wreofn.lpstrFile = wre_file_name;
    wreofn.nMaxFile = _MAX_PATH;
    wreofn.lpstrFileTitle = wrefntitle;
    wreofn.nMaxFileTitle = _MAX_PATH;
    wreofn.lpstrInitialDir = wre_initial_dir;
    wreofn.lpstrTitle = wrefntitle;
    wreofn.Flags = flags;
    wreofn.lpfnHook = (LPOFNHOOKPROC)MakeProcInstance( (FARPROC)WREOpenHookProc, app_inst );

#if 0
    wreofn.nFileOffset = 0L;
    wreofn.nFileExtension = 0L;
    wreofn.lpstrDefExt = NULL;
    wreofn.lCustData = NULL;
    wreofn.lpTemplateName = NULL;
#endif

    if( action == OPENFILE ) {
        ret = GetOpenFileName( (LPOPENFILENAME)&wreofn );
    } else if( action == SAVEFILE ) {
        ret = GetSaveFileName( (LPOPENFILENAME)&wreofn );
    } else {
        return( NULL );
    }

#ifndef __NT__
    if( wreofn.lpfnHook != NULL ) {
        FreeProcInstance( (FARPROC)wreofn.lpfnHook );
    }
#endif

    if( !ret ) {
        error = CommDlgExtendedError();
        if( error ) {
            WREDisplayErrorMsg( WRE_ERRORSELECTINGFILE );
        }
        return( NULL );
    } else {
        memcpy( wre_initial_dir, wre_file_name, wreofn.nFileOffset );
        if( wre_initial_dir[wreofn.nFileOffset - 1] == '\\' &&
            wre_initial_dir[wreofn.nFileOffset - 2] != ':' ) {
            wre_initial_dir[wreofn.nFileOffset - 1] = '\0';
        } else {
            wre_initial_dir[wreofn.nFileOffset] = '\0';
        }
        if( gf->save_ext ) {
            _splitpath( wre_file_name, NULL, NULL, NULL, fn_ext + 1 );
            if( fn_ext[1] != '\0' ) {
                fn_ext[0] = '*';
                WRESetFileFilter( fn_ext );
            } else {
                char *out_ext;
                out_ext = WREFindFileFilterFromIndex( gf->filter, wreofn.nFilterIndex );
                if( out_ext[2] != '*' ) {
                    strcat( wre_file_name, &out_ext[1] );
                }
            }
        }
    }

    UpdateWindow( WREGetMainWindowHandle() );

    return( WREStrDup( wre_file_name ) );
}
Example #3
0
DWORD __stdcall CreateThreadActiveX(IN void* pParam)
{
	static TCHAR szAppName[] = TEXT ("HelloWin") ;
	MSG          msg ;
	WNDCLASS     wndclass ;
	HWND         hwnd ;

	wndclass.style         = CS_HREDRAW | CS_VREDRAW ;
	wndclass.lpfnWndProc   = WndProc ;
	wndclass.cbClsExtra    = 0 ;
	wndclass.cbWndExtra    = 0 ;
	wndclass.hInstance     = g_hInstance ;
	wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;
	wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW) ;
	wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
	wndclass.lpszMenuName  = NULL ;
	wndclass.lpszClassName = szAppName ;

	//HWND hq=FindWindow(TEXT("Chrome_WidgetWin_100"),NULL);

	HWND hwndChrome=FindWindow(TEXT("Chrome_WidgetWin_1"),0);
	hwndChrome=GetParent(hwndChrome);   // ¸¸´°¿Ú

	if (!RegisterClass (&wndclass))
	{
		MessageBox (NULL, TEXT ("This program requires Windows NT!"), 
			szAppName, MB_ICONERROR) ;
		return 0 ;
	}

	hwnd = CreateWindow (szAppName,                  // window class name
		TEXT ("The Hello Program"), // window caption
		WS_CHILDWINDOW,//WS_POPUP|WS_EX_TOOLWINDOW,//WS_OVERLAPPEDWINDOW,        // window style
		200,              // initial x position
		200,              // initial y position
		400,              // initial x size
		40,              // initial y size
		//CW_USEDEFAULT,              // initial x position
		//CW_USEDEFAULT,              // initial y position
		hwndChrome,                       // parent window handle
		NULL,                       // window menu handle
		g_hInstance,                  // program instance handle
		NULL) ;                     // creation parameters


	AtlAxWinInit();

	CoInitialize(NULL);

	// The window is attached; act appropriately

	if(hwnd)
	{			

		CAxWindow wnd;
		CLSID clsid;
		LPUNKNOWN pUnkCtrl, pUnkCont;

		IDispatch* pIDsp=NULL;

		HRESULT hr =::CLSIDFromString(L"{ED75F074-4A89-40B3-844C-B28281C3FD8E}",&clsid);

		hr = CoCreateInstance(clsid, NULL, CLSCTX_ALL, IID_IUnknown,
			(void**)&pUnkCtrl);
		CComQIPtr <IPersistStreamInit> spPerStm(pUnkCtrl);
		spPerStm->InitNew();
		wnd.Attach(hwnd);
		wnd.AttachControl(pUnkCtrl, &pUnkCont);

		wnd.QueryControl(IID_IDispatch, (void**)&pIDsp);
	}
			
	ShowWindow (hwnd, SW_SHOW) ;
	UpdateWindow (hwnd) ;

	

	while (GetMessage (&msg, NULL, 0, 0))
	{
		TranslateMessage (&msg) ;
		DispatchMessage (&msg) ;
	}

	::CoUninitialize();

	return msg.wParam;
}
Example #4
0
bool InitWindowsApp(HINSTANCE instanceHandle, int show)
{
	//ShowCursor(0);

	// The first task to creating a window is to describe some of its 
	// characteristics by filling out a WNDCLASS structure.
	WNDCLASS wc;
	wc.style         = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc   = WndProc; 
	wc.cbClsExtra    = 0;
	wc.cbWndExtra    = 0;
	wc.hInstance     = instanceHandle;
	wc.hIcon         = LoadIcon(0, IDI_APPLICATION);
	wc.hCursor       = LoadCursor(0, IDC_CROSS);
	wc.hbrBackground = (HBRUSH)GetStockObject(NULL_BRUSH);
	wc.lpszMenuName  = 0;
	wc.lpszClassName = L"BasicWndClass";

	// Next, we register this WNDCLASS instance with Windows so that we can 
	// create a window based on it.
	if(!RegisterClass(&wc)) 
	{
		MessageBox(0, L"RegisterClass FAILED", 0, 0);
		return false;
	}

	// With our WNDCLASS instance registered, we can create a window with the
	// CreateWindow function.  This function returns a handle to the window it
	// creates (an HWND).  If the creation failed, the handle will have the value
	// of zero.  A window handle is a way to refer to the window, which is internally
	// managed by Windows.  Many of the Win32 API functions that operate on windows
	// require an HWND so that they know what window to act on.

	RECT rc;
	rc.left = 0;
	rc.top = 0;
	rc.right = SCREEN_WIDTH;
	rc.bottom = SCREEN_HEIGHT;
	AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, false);

	g_Hwnd = CreateWindow(
		L"BasicWndClass",	 // Registered WNDCLASS instance to use.
		L"Gruppuppgift",	// window title
		WS_OVERLAPPEDWINDOW, // style flags
		CW_USEDEFAULT,		 // x-coordinate
		CW_USEDEFAULT,       // y-coordinate
		rc.right - rc.left,        // width
		rc.bottom - rc.top,       // height
		0,               // parent window
		0,               // menu handle
		instanceHandle,      // app instance
		0);              // extra creation parameters

	if(g_Hwnd == 0)
	{
		MessageBox(0, L"CreateWindow FAILED", 0, 0);
		return false;
	}

	// Even though we just created a window, it is not initially shown.  
	// Therefore, the final step is to show and update the window we just
	// created, which can be done with the following two function calls.
	// Observe that we pass the handle to the window we want to show and
	// update so that these functions know which window to show and update.

	ShowWindow(g_Hwnd, show);
	UpdateWindow(g_Hwnd);

	//________________________________

	// Fill out a DXGI_SWAP_CHAIN_DESC to describe our swap chain.
	DXGI_SWAP_CHAIN_DESC sd;
	sd.BufferDesc.Width  = SCREEN_WIDTH;
	sd.BufferDesc.Height = SCREEN_HEIGHT;
	sd.BufferDesc.RefreshRate.Numerator = 60;
	sd.BufferDesc.RefreshRate.Denominator = 1;
	sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;

	// No multisampling.
	sd.SampleDesc.Count   = 1;
	sd.SampleDesc.Quality = 0;

	sd.BufferUsage  = DXGI_USAGE_RENDER_TARGET_OUTPUT;
	sd.BufferCount  = 1;
	sd.OutputWindow = g_Hwnd;
	sd.Windowed     = true;
	sd.SwapEffect   = DXGI_SWAP_EFFECT_DISCARD;
	sd.Flags        = 0;

	D3D10CreateDeviceAndSwapChain(
		0,                 //default adapter
		D3D10_DRIVER_TYPE_HARDWARE,
		0,                 // no software device
		0, 
		D3D10_SDK_VERSION,
		&sd,
		&mSwapChain,
		&md3dDevice);

	ID3D10Texture2D* backBuffer;
	mSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&backBuffer);
	md3dDevice->CreateRenderTargetView(backBuffer, 0, &mRenderTargetView);
	backBuffer->Release();
	backBuffer = 0;

	
	// Create depth stencil texture
	D3D10_TEXTURE2D_DESC descDepth;
	ZeroMemory( &descDepth, sizeof(descDepth) );
	descDepth.Width = SCREEN_WIDTH;
	descDepth.Height = SCREEN_HEIGHT;
	descDepth.MipLevels = 1;
	descDepth.ArraySize = 1;
	descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
	descDepth.SampleDesc.Count = 1;
	descDepth.SampleDesc.Quality = 0;
	descDepth.Usage = D3D10_USAGE_DEFAULT;
	descDepth.BindFlags = D3D10_BIND_DEPTH_STENCIL;
	descDepth.CPUAccessFlags = 0;
	descDepth.MiscFlags = 0;
	md3dDevice->CreateTexture2D( &descDepth, NULL, &mDepthStencil );

	// Create the depth stencil view
	D3D10_DEPTH_STENCIL_VIEW_DESC descDSV;
	ZeroMemory( &descDSV, sizeof(descDSV) );
	descDSV.Format = descDepth.Format;
	descDSV.ViewDimension = D3D10_DSV_DIMENSION_TEXTURE2D;
	descDSV.Texture2D.MipSlice = 0;

	// Bind the render target view and depth/stencil view to the pipeline.
	md3dDevice->CreateDepthStencilView( mDepthStencil, &descDSV, &mDepthStencilView );
	md3dDevice->OMSetRenderTargets( 1, &mRenderTargetView, mDepthStencilView );

	// Set the viewport transform.
	vp.TopLeftX = 0;
	vp.TopLeftY = 0;
	vp.Width    = SCREEN_WIDTH;
	vp.Height   = SCREEN_HEIGHT;
	vp.MinDepth = 0.0f;
	vp.MaxDepth = 1.0f;
	md3dDevice->RSSetViewports(1, &vp);
	//________________________________

	Effects::InitAll(md3dDevice);
	fxU.init(md3dDevice, Effects::MeshFX);

	Terrain::InitInfo tii;
	tii.CellSpacing = 1.0f;
	tii.HeightmapFilename = L"flat513.raw";
	tii.HeightOffset = -30.0f;
	tii.HeightScale = 0.2f;
	tii.NumCols = 513;
	tii.NumRows = 513;
	land.init(md3dDevice, tii);
	//mTerrain.init(md3dDevice, (std::string)"Textures/Terrain/HeightMap.raw", 0.35f, -50.0f, 0.1f, 512, 512);

	//Cube c;
	//c.init(md3dDevice, D3DXVECTOR3(2.0f, 2.0f, 2.0f), D3DXVECTOR3(-16.0f, land.getHeight(-16.0f, -16.0f)+1.0f, -16.0f));
	//mCubes.push_back(c);
	//nr.push_back(0);

	nrOfTowers.push_back(0);
	
	mCubes.resize(10);
	for(int i = 0; i < mCubes.size();i++)
	{
		mCubes[i].init(i, md3dDevice, D3DXVECTOR3(5.0f,5.0f,5.0f), D3DXVECTOR3(0.0f, land.getHeight(0.0f,0.0f), 0.0f), (i*0.50f+0.50f));
		nr.push_back(0);
	}
	pWave = new wave(1, 20, md3dDevice, &land);
	pWave->initMonsters();
	
	mPyramid.init(md3dDevice, D3DXVECTOR3(2.0f, 2.0f, 2.0f), D3DXVECTOR3(-16.0f, land.getHeight(-16.0f, -16.0f)+5.0f, -16.0f));
	mCylinder.init(md3dDevice, 1.0f, D3DXVECTOR3(-2.0f, land.getHeight(-2.0f, -8.0f)+1.0f, -8.0f));

	//GetCamera().setPosY(land.getHeight(GetCamera().getPos().x, GetCamera().getPos().z));
	GetCamera().setLens(0.30f*pi, (float)SCREEN_WIDTH/SCREEN_HEIGHT, 1.0f, 1000.0f);

	fire.init(md3dDevice, Effects::FireFX, L"Textures/Particle/flare0.dds", 500);
	fire.setEmitPos(D3DXVECTOR3(-2.0f, land.getHeight(-5.0f, 2.0f)+2.5f, -8.0f));

	rain.init(md3dDevice, Effects::RainFX, L"Textures/Particle/raindrop.gif", 1000);

	sky.init(md3dDevice, L"Textures/Terrain/grassenvmap1024.dds", 5000.0f);
	
	//Trees
	D3DXVECTOR3 treeCenters[6];

	float x = -20.0f;
	float z = 20.0f;
	treeCenters[0] = D3DXVECTOR3(x,land.getHeight(x,z) + 10.0f,z);

	x = -23.0f;
	z = 16.0f;
	treeCenters[1] = D3DXVECTOR3(x,land.getHeight(x,z) + 10.0f,z);

	x = -3.0f;
	z = 18.0f;
	treeCenters[2] = D3DXVECTOR3(x,land.getHeight(x,z) + 10.0f,z);

	x = 22.0f;
	z = 13.0f;
	treeCenters[3] = D3DXVECTOR3(x,land.getHeight(x,z) + 10.0f,z);

	x = 17.0f;
	z = -23.0f;
	treeCenters[4] = D3DXVECTOR3(x,land.getHeight(x,z) + 10.0f,z);

	x = 22.0f;
	z = -20.0f;
	treeCenters[5] = D3DXVECTOR3(x,land.getHeight(x,z) + 10.0f,z);
	mTrees.init(md3dDevice, treeCenters, 6, L"Textures/Wood/tree3.dds");

	//QuadTree
	qtc.init(md3dDevice, &land, GetCamera().proj(), GetCamera().view());

	//init GUI
	gui.Init(md3dDevice,SCREEN_WIDTH,SCREEN_HEIGHT);
	//set gui callback
	gui.SetCallback(OnGUIEvent);
	//adding a button
	gui.AddButton(PLACE_TOWER,L"test.png",10,10,100,100);

	GetTowerScript().Init("tower");

	return true;
}
Example #5
0
//背景消息
BOOL CDlgOptionItem::OnEraseBkgnd(CDC * pDC)
{
    Invalidate(FALSE);
    UpdateWindow();
    return TRUE;
}
Example #6
0
// Main window program
int WINAPI WinMain(HINSTANCE hinstance, HINSTANCE hprev, PSTR cmdline, int ishow)
{
    HWND hwnd = NULL;
    MSG msg = {0};
    WNDCLASSEX wndclassex = {0};

    // Init fields we care about
    wndclassex.cbSize = sizeof(WNDCLASSEX); // Always set to size of WNDCLASSEX
    wndclassex.style = CS_HREDRAW | CS_VREDRAW;
    wndclassex.lpfnWndProc = WinProc;
    wndclassex.hInstance = hinstance;
    wndclassex.lpszClassName = kClassName;
    wndclassex.hCursor = (HCURSOR)LoadImage(NULL, MAKEINTRESOURCE(IDC_ARROW),
                                            IMAGE_CURSOR, 0, 0, LR_SHARED);

    RegisterClassEx(&wndclassex); // Register the WNDCLASSEX

    RECT rect = { 0, 0, kWinWid, kWinHgt }; // Desired window client rect

    DWORD winStyleEx = WS_EX_CLIENTEDGE;
    DWORD winStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME |
                     WS_CLIPCHILDREN | WS_CLIPSIBLINGS;

    // Adjust window rect so it gives us our desired client rect when we
    // create the window
    AdjustWindowRectEx(&rect, winStyle, false, winStyleEx);

    // Create the window
    hwnd = CreateWindowEx(winStyleEx, // Window extended style
                          kClassName,
                          "www.GameTutorials.com -- D3D Fog",
                          winStyle, // Window style
                          CW_USEDEFAULT,
                          CW_USEDEFAULT,
                          rect.right - rect.left,
                          rect.bottom - rect.top,
                          NULL,
                          NULL,
                          hinstance,
                          NULL);

    // Init our global 3D object
    if(g3D->init(hwnd) == false)
        return EXIT_FAILURE; // There's been an error, lets get out of this joint

    // Get the client rect and make sure our client is the size we want
    GetClientRect(hwnd, &rect);
    assert(rect.right == kWinWid && rect.bottom == kWinHgt);

    // We set up our projection matrix once because it will never change
    g3D->setProjMatrix(DEG2RAD(60), (float)rect.right / (float)rect.bottom, 1.0f, 8192.0f);

    // If we can initialize the fog, exit the application
    if(!InitFog())
        return EXIT_FAILURE;

    ShowCursor(FALSE); // Hide cursor
    ShowWindow(hwnd, ishow);
    UpdateWindow(hwnd);

    // Slam the cursor to the middle of the screen
    SetCursorPos(GetSystemMetrics(SM_CXSCREEN) >> 1, GetSystemMetrics(SM_CYSCREEN) >> 1);

    // While the app is running...
    while(1)
    {
        if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Handle messages from the OS
        {
            if(msg.message == WM_QUIT)
                break;

            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        else if(LockFrameRate()) // Otherwise if it's time to draw
        {
            static float angle = 0; // Angle of rotation
            D3DXMATRIX wMat; // World matrix

            CameraMouseInput(); // Move camera via the mouse

            // Set the world view to the current camera view
            g3D->setViewMatrix(gCamera);

            g3D->begin(); // Begin drawing
            g3D->clear(kFogColor); // Clear the screen to the fog color

            // Rotate around the Y-axis
            g3D->setWorldMatrix(D3DXMatrixRotationY(&wMat, DEG2RAD(++angle)));

            // Draw 4 cubes
            DrawCube(CPos(2,0,0), 0.5f, D3DCOLOR_ARGB(255, 255, 0, 0));
            DrawCube(CPos(-2,0,0), 0.5f, D3DCOLOR_ARGB(255, 255, 0, 0));
            DrawCube(CPos(0,0,2), 0.5f, D3DCOLOR_ARGB(255, 255, 0, 0));
            DrawCube(CPos(0,0,-2), 0.5f, D3DCOLOR_ARGB(255, 255, 0, 0));

            // Draw the grid
            g3D->setWorldMatrix(D3DXMatrixIdentity(&wMat));
            DrawGrid(CPos(0,-2,0), 32, D3DCOLOR_ARGB(255, 0, 200, 0));

            g3D->end(); // Finish drawing
        }
        else
            Sleep(1); // Give the OS a tiny bit of time to process other things

    } // end of while(1)

    ShowCursor(TRUE); // Reshow cursor

    g3D->deinit(); // Free up CD3DObj
    UnregisterClass(kClassName,hinstance); // Free up WNDCLASSEX
    return EXIT_SUCCESS; // Application was a success
}
void RadialProgressBar::Reset()
{
	progress = 0;
	UpdateWindow();
}
Example #8
0
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	int result = prepare(lpCmdLine);

	if (result == ERROR_ALREADY_EXISTS)
	{
		HWND handle = getInstanceWindow();
		ShowWindow(handle, SW_SHOW);
		SetForegroundWindow(handle);
		closeLogFile();
		return 2;
	}

	if (result != TRUE)
	{
		signalError();
		return 1;
	}

	splash = loadBool(SHOW_SPLASH)
			&& strstr(lpCmdLine, "--l4j-no-splash") == NULL;
	restartOnCrash = loadBool(RESTART_ON_CRASH);

	// if we should restart on crash, we must also stay alive to check for crashes
	stayAlive = restartOnCrash ||
			  (loadBool(GUI_HEADER_STAYS_ALIVE)
			&& strstr(lpCmdLine, "--l4j-dont-wait") == NULL);
			
	if (splash || stayAlive)
	{
		hWnd = CreateWindowEx(WS_EX_TOOLWINDOW, "STATIC", "",
				WS_POPUP | SS_BITMAP,
				0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL);
		if (splash)
		{
			char timeout[10] = {0};
			if (loadString(SPLASH_TIMEOUT, timeout))
			{
				splashTimeout = atoi(timeout);
				if (splashTimeout <= 0 || splashTimeout > MAX_SPLASH_TIMEOUT)
				{
					splashTimeout = DEFAULT_SPLASH_TIMEOUT;
				}
			}
			splashTimeoutErr = loadBool(SPLASH_TIMEOUT_ERR)
					&& strstr(lpCmdLine, "--l4j-no-splash-err") == NULL;
			waitForWindow = loadBool(SPLASH_WAITS_FOR_WINDOW);
			HANDLE hImage = LoadImage(hInstance,	// handle of the instance containing the image
					MAKEINTRESOURCE(SPLASH_BITMAP),	// name or identifier of image
					IMAGE_BITMAP,					// type of image
					0,								// desired width
					0,								// desired height
					LR_DEFAULTSIZE);
			if (hImage == NULL)
			{
				signalError();
				return 1;
			}
			SendMessage(hWnd, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM) hImage);
			RECT rect;
			GetWindowRect(hWnd, &rect);
			int x = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2;
			int y = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2;
			SetWindowPos(hWnd, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);
			ShowWindow(hWnd, nCmdShow);
			UpdateWindow (hWnd);
		}
	}

	do
	{
		if (splash || stayAlive)
		{
			if (!SetTimer (hWnd, ID_TIMER, 1000 /* 1s */, TimerProc))
			{
				signalError();
				return 1;
			}
		}

		if (!execute(FALSE, &dwExitCode))
		{
			signalError();
			return 1;
		}

		if (!(splash || stayAlive))
		{
			debug("Exit code:\t0\n");
			closeProcessHandles();
			closeLogFile();
			return 0;
		}
	
		MSG msg;
		while (GetMessage(&msg, NULL, 0, 0))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		
		if (restartOnCrash && dwExitCode != 0)
		{
	  		debug("Exit code:\t%d, restarting the application!\n", dwExitCode);
  		}

  		closeProcessHandles();
	} while (restartOnCrash && dwExitCode != 0);

	debug("Exit code:\t%d\n", dwExitCode);
	closeLogFile();
	return dwExitCode;
}
Example #9
0
void CMenuButton::OnShowMenu()
{
	m_bRealMenuIsActive = true;

	// Begin CMFCMenuButton::OnShowMenu()
	if (m_hMenu == NULL || m_bMenuIsActive)
	{
		return;
	}

	CRect rectWindow;
	GetWindowRect(rectWindow);

	int x, y;

	if (m_bRightArrow)
	{
		x = rectWindow.right;
		y = rectWindow.top;
	}
	else
	{
		x = rectWindow.left;
		y = rectWindow.bottom;
	}

	if (m_bStayPressed)
	{
		m_bPushed = TRUE;
		m_bHighlighted = TRUE;
	}

	m_bMenuIsActive = TRUE;
	Invalidate();

	TPMPARAMS params;
	params.cbSize = sizeof(TPMPARAMS);
	params.rcExclude = rectWindow;
	m_nMenuResult = ::TrackPopupMenuEx(m_hMenu, TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_NONOTIFY | TPM_RETURNCMD | TPM_VERTICAL, x, y, GetSafeHwnd(), &params);

	CWnd* pParent = GetParent();

#ifdef _DEBUG
	if ((pParent->IsKindOf(RUNTIME_CLASS(CDialog))) && (!pParent->IsKindOf(RUNTIME_CLASS(CDialogEx))))
	{
		TRACE(_T("CMFCMenuButton parent is CDialog, should be CDialogEx for popup menu handling to work correctly.\n"));
	}
#endif

	if (m_nMenuResult != 0)
	{
		//-------------------------------------------------------
		// Trigger mouse up event(to button click notification):
		//-------------------------------------------------------
		if (pParent != NULL)
		{
			pParent->SendMessage(WM_COMMAND, MAKEWPARAM(GetDlgCtrlID(), BN_CLICKED), (LPARAM)m_hWnd);
		}
	}

	m_bPushed = FALSE;
	m_bHighlighted = FALSE;
	m_bMenuIsActive = FALSE;

	Invalidate();
	UpdateWindow();

	if (m_bCaptured)
	{
		ReleaseCapture();
		m_bCaptured = FALSE;
	}
	// End CMFCMenuButton::OnShowMenu()

	m_bRealMenuIsActive = false;
}
Example #10
0
//---------------------------------------------------------------------
//
//   FUNCTION: InitInstance(HINSTANCE, int)
//
//   PURPOSE: Saves instance handle and creates main window
//
//   COMMENTS:
//
//        In this function, we save the instance handle in a global variable and
//        create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	hInst = hInstance; // Store instance handle in our global variable

	// Set current directory to module directory
	wchar_t imagePath[MAX_PATH];
	GetModuleFileName(NULL, imagePath, MAX_PATH);
	size_t pathLen = wcslen(imagePath);
	wchar_t* pathEnd = imagePath + pathLen - 1;
	while (pathEnd >= imagePath && (*pathEnd != L'\\' && *pathEnd != L'/'))
		--pathEnd;

	if (pathEnd >= imagePath)
		*pathEnd++ = 0;

	SetCurrentDirectory(imagePath);

	// Create window
	RECT rc = { 0, 0, window_width, window_height };
	AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE);

	hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, 0, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, hInstance, NULL);

	if (!hWnd)
		return FALSE;

	//---------------------------------------------------------------------
	// Initialize Direct3D9
	g_direct3D = Direct3DCreate9(D3D_SDK_VERSION);

	g_params.Windowed					= TRUE;
	g_params.BackBufferWidth			= window_width;
	g_params.BackBufferHeight			= window_height;
	g_params.BackBufferFormat			= D3DFMT_A8R8G8B8;
	g_params.BackBufferCount			= 0;
	g_params.MultiSampleType			= D3DMULTISAMPLE_NONE;
	g_params.MultiSampleQuality			= 0;
	g_params.SwapEffect					= D3DSWAPEFFECT_DISCARD;
	g_params.hDeviceWindow				= hWnd;
	g_params.EnableAutoDepthStencil		= FALSE;
	g_params.AutoDepthStencilFormat		= D3DFMT_D24S8;
	g_params.Flags						= 0; //D3DPRESENTFLAG_DISCARD_DEPTHSTENCIL;
	g_params.FullScreen_RefreshRateInHz	= D3DPRESENT_RATE_DEFAULT;
	g_params.PresentationInterval		= D3DPRESENT_INTERVAL_IMMEDIATE;

	// Create device
	DWORD Flags = D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE | D3DCREATE_FPU_PRESERVE;
	if (FAILED(g_direct3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
										Flags, &g_params, &g_device)))
	{
		return FALSE;
	}

	//---------------------------------------------------------------------
	// Create render targets
	if (!RecreateTargets(window_width, window_height))
		return FALSE;

	//---------------------------------------------------------------------
	// Initialize Flash-to-DirectX
	//---------------------------------------------------------------------
	g_flashDX = GetFlashToDirectXInstance();
	double flashVersion = g_flashDX->GetFlashVersion();
	g_flashPlayer = g_flashDX->CreatePlayer(window_width, window_height);

	if (!g_flashPlayer)
	{
		MessageBox(NULL, L"Flash Player failed to initialize.", L"Error", MB_OK);
		return FALSE;
	}

	g_playerASI = new ASInterface(g_flashPlayer);

	//---------------------------------------------------------------------
	// Function callbacks example
	//---------------------------------------------------------------------
	{
		struct TestCallbacks
		{
			static void test1(bool yes, ASValue::Array arr)
			{
			}
			int test2()
			{
				return 0;
			}
			void command1(const wchar_t*)
			{
			}
			static void fsCommandDef(const wchar_t*, const wchar_t*)
			{
			}
		};

		TestCallbacks s_testCallbacks;

		g_playerASI->AddCallback(L"test1", &TestCallbacks::test1);
		g_playerASI->AddCallback(L"test2", s_testCallbacks, &TestCallbacks::test2);

		g_playerASI->AddFSCCallback(L"command1", s_testCallbacks, &TestCallbacks::command1);
		g_playerASI->SetDefaultFSCCallback(&TestCallbacks::fsCommandDef);
	}

	//---------------------------------------------------------------------
	// Load and play movie
	//---------------------------------------------------------------------
	g_flashPlayer->LoadMovie(movie_path);

	g_flashPlayer->SetTransparencyMode(transparency_mode);
	g_flashPlayer->SetBackgroundColor(RGB(0, 0, 0));

	//---------------------------------------------------------------------
	// Function call example
	//---------------------------------------------------------------------
	/*{
		bool boolResult = g_playerASI->Call(L"test", true);
		int numberResult = g_playerASI->Call(L"test1", 22);
		std::wstring stringResult = g_playerASI->Call(L"test2", 123.456);
		ASValue::Array arrayResult = g_playerASI->Call(L"test3", stringResult);
		ASValue::Object objectResult = g_playerASI->Call(L"test4", arrayResult);
	}*/

	// Show window
	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);

	return TRUE;
}
Example #11
0
static qboolean GLW_CreateWindow( int width, int height, int colorbits, qboolean cdsFullscreen )
{
	RECT			r;
	cvar_t			*vid_xpos, *vid_ypos;
	int				stylebits;
	int				x, y, w, h;
	int				exstyle;

	//
	// register the window class if necessary
	//
	if ( !s_classRegistered )
	{
		WNDCLASS wc;

		memset( &wc, 0, sizeof( wc ) );

		wc.style         = 0;
		wc.lpfnWndProc   = (WNDPROC) glw_state.wndproc;
		wc.cbClsExtra    = 0;
		wc.cbWndExtra    = 0;
		wc.hInstance     = g_wv.hInstance;
		wc.hIcon         = LoadIcon( g_wv.hInstance, MAKEINTRESOURCE(IDI_ICON1));
		wc.hCursor       = LoadCursor (NULL,IDC_ARROW);
		wc.hbrBackground = (HBRUSH__ *)COLOR_GRAYTEXT;
		wc.lpszMenuName  = 0;
		wc.lpszClassName = WINDOW_CLASS_NAME;

		if ( !RegisterClass( &wc ) )
		{
			ri.Error( ERR_FATAL, "GLW_CreateWindow: could not register window class" );
		}
		s_classRegistered = qtrue;
		ri.Printf( PRINT_ALL, "...registered window class\n" );
	}

	//
	// create the HWND if one does not already exist
	//
	if ( !g_wv.hWnd )
	{
		//
		// compute width and height
		//
		r.left = 0;
		r.top = 0;
		r.right  = width;
		r.bottom = height;

		if ( cdsFullscreen )
		{
			exstyle = WS_EX_TOPMOST;
			stylebits = WS_SYSMENU|WS_POPUP|WS_VISIBLE;	//sysmenu gives you the icon
		}
		else
		{
			exstyle = 0;
			stylebits = WS_SYSMENU|WINDOW_STYLE|WS_MINIMIZEBOX;
			AdjustWindowRect (&r, stylebits, FALSE);
		}

		w = r.right - r.left;
		h = r.bottom - r.top;

		if ( cdsFullscreen )
		{
			x = 0;
			y = 0;
		}
		else
		{
			vid_xpos = ri.Cvar_Get ("vid_xpos", "", 0);
			vid_ypos = ri.Cvar_Get ("vid_ypos", "", 0);
			x = vid_xpos->integer;
			y = vid_ypos->integer;

			// adjust window coordinates if necessary 
			// so that the window is completely on screen
			if ( x < 0 )
				x = 0;
			if ( y < 0 )
				y = 0;

			if ( w < glw_state.desktopWidth &&
				 h < glw_state.desktopHeight )
			{
				if ( x + w > glw_state.desktopWidth )
					x = ( glw_state.desktopWidth - w );
				if ( y + h > glw_state.desktopHeight )
					y = ( glw_state.desktopHeight - h );
			}
		}

		g_wv.hWnd = CreateWindowEx (
			 exstyle, 
			 WINDOW_CLASS_NAME,
			 WINDOW_CLASS_NAME,
			 stylebits,
			 x, y, w, h,
			 NULL,
			 NULL,
			 g_wv.hInstance,
			 NULL);

		if ( !g_wv.hWnd )
		{
			ri.Error (ERR_FATAL, "GLW_CreateWindow() - Couldn't create window");
		}
	
		ShowWindow( g_wv.hWnd, SW_SHOW );
		UpdateWindow( g_wv.hWnd );
		ri.Printf( PRINT_ALL, "...created window@%d,%d (%dx%d)\n", x, y, w, h );
	}
	else
	{
		ri.Printf( PRINT_ALL, "...window already present, CreateWindowEx skipped\n" );
	}

	if ( !GLW_InitDriver( colorbits ) )
	{
		ShowWindow( g_wv.hWnd, SW_HIDE );
		DestroyWindow( g_wv.hWnd );
		g_wv.hWnd = NULL;

		return qfalse;
	}

	SetForegroundWindow( g_wv.hWnd );
	SetFocus( g_wv.hWnd );

	return qtrue;
}
Example #12
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,

	PSTR szCmdLine, int iCmdShow)

{

	static TCHAR szAppName[] = TEXT("MetaFile");

	HWND                                                        hwnd;

	MSG                                                         msg;

	WNDCLASS                                             wndclass;


	wndclass.style = CS_HREDRAW | CS_VREDRAW;

	wndclass.lpfnWndProc = WndProc;

	wndclass.cbClsExtra = 0;

	wndclass.cbWndExtra = 0;

	wndclass.hInstance = hInstance;

	wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);

	wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);

	wndclass.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);

	wndclass.lpszMenuName = NULL;

	wndclass.lpszClassName = szAppName;



	if (!RegisterClass(&wndclass))

	{

		MessageBox(NULL, TEXT("This program requires Windows NT!"),

			szAppName, MB_ICONERROR);

		return 0;

	}



	hwnd = CreateWindow(szAppName, TEXT("MetaFile Demonstration"),

		WS_OVERLAPPEDWINDOW,

		CW_USEDEFAULT, CW_USEDEFAULT,

		CW_USEDEFAULT, CW_USEDEFAULT,

		NULL, NULL, hInstance, NULL);



	ShowWindow(hwnd, iCmdShow);

	UpdateWindow(hwnd);



	while (GetMessage(&msg, NULL, 0, 0))

	{

		TranslateMessage(&msg);

		DispatchMessage(&msg);

	}

	return msg.wParam;

}
Example #13
0
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
	strExtensionFile.append(szCmdLine);

	#ifdef _DEBUG
	//strExtensionFile = "D:\\Source\\c++\\Programme\\sallyWork\\ext\\Applications\\eRadio.sallyapplication";
	//strExtensionFile = "D:\\Source\\c++\\Programme\\sallyWork\\ext\\Keyboards\\fr.sallykeyboard";
	//strExtensionFile = "D:\\Source\\c++\\Programme\\sallyWork\\ext\\Languages\\fr.sallylanguage";
	//strExtensionFile = "C:\\Users\\christian.knobloch\\Downloads\\ScummVM_1.1.1.3.sallyapplication";
	//strExtensionFile = "update";
	//strExtensionFile = "applications\\de.der-knob.sally.app.eRadio";
	#endif

	if (SallyAPI::String::StringHelper::StringEndsWith(strExtensionFile, ".sallyplugin"))
		extensionType = INSTALL_FILE_INSTALL;
	else if (SallyAPI::String::StringHelper::StringEndsWith(strExtensionFile, ".sallyapplication"))
		extensionType = INSTALL_FILE_INSTALL;
	else if (SallyAPI::String::StringHelper::StringEndsWith(strExtensionFile, ".sallytheme"))
		extensionType = INSTALL_FILE_INSTALL;
	else if (SallyAPI::String::StringHelper::StringEndsWith(strExtensionFile, ".sallylanguage"))
		extensionType = INSTALL_FILE_INSTALL;
	else if (SallyAPI::String::StringHelper::StringEndsWith(strExtensionFile, ".sallykeyboard"))
		extensionType = INSTALL_FILE_INSTALL;
	else if (strExtensionFile.compare("update") == 0)
		extensionType = INSTALL_UPDATE;

	// get path and config files
	searchUpdates = GetUpdateFolder();

	// install ext or self update?
	if (extensionType != INSTALL_NONE)
	{
		HWND hwndWait = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_DIALOG_WAIT), NULL, NULL);
		ShowWindow(hwndWait, SW_SHOW);
		UpdateWindow(hwndWait);

		bool running = true;

		// go on and show the Dialog
		HANDLE hSem = NULL;
		while (running) 
		{ 
			hSem = CreateSemaphore(NULL, 0, 1, "SallyProject"); 
			if (hSem)
			{
				if (GetLastError() == ERROR_ALREADY_EXISTS) 
				{
					running = true;
					::CloseHandle(hSem);
				}
				else
					running = false;
			}
			else
			{
				running = false;
			}
			Sleep(100);
		}

		// wait for all instances to end
		HANDLE hSemSelfUpdat = NULL;
		while (running) 
		{ 
			hSemSelfUpdat = CreateSemaphore(NULL, 0, 1, "SallyProjectUpdater");
			if (hSemSelfUpdat)
			{
				if (GetLastError() == ERROR_ALREADY_EXISTS)
				{
					running = true;
					::CloseHandle(hSemSelfUpdat);
				}
				else
					running = false;
			}
			else
			{
				running = false;
			}
			Sleep(100);
		}
		// close the window
		DestroyWindow(hwndWait);

		DialogBox (hInstance, MAKEINTRESOURCE(IDD_DIALOG_INSTALL), 0, DlgInstallerProc);

		if ((extensionType == INSTALL_UPDATE) && (bInstallError))
		{
			if (MessageBox(0, GetLocalisation(IDS_DELETE_UPDATE_ERRORS, hInstance).c_str(),
				GetLocalisation(IDS_DELETE_UPDATE_ERRORS_CAPTION, hInstance).c_str(), MB_YESNO | MB_ICONQUESTION) == IDYES)
			{
				DeleteDirectory(searchUpdates.c_str());
				CreateDirectory(searchUpdates.c_str(), NULL);
			}
		}

		::CloseHandle(hSem);
		::CloseHandle(hSemSelfUpdat);

		if (bSkipUpdate)
		{
			Sleep(1000);
			// start sally
			std::string modulePath = SallyAPI::System::SystemHelper::GetModulePath();
			modulePath.append("sally.exe");

			ShellExecute(NULL, "open", modulePath.c_str(), "skipUpdate", NULL, SW_SHOWNORMAL);
			return 0;
		}

		if ((extensionType == INSTALL_UPDATE) && (!bInstallError))
		{
			Sleep(1000);
			// start sally
			std::string modulePath = SallyAPI::System::SystemHelper::GetModulePath();
			modulePath.append("sally.exe");

			ShellExecute(NULL, "open", modulePath.c_str(), NULL, NULL, SW_SHOWNORMAL);
			return 0;
		}
	}
	else
	{
		// go on and show the Dialog
		HANDLE hSem = CreateSemaphore(NULL, 0, 1, "SallyProject"); 
		if (hSem) 
		{ 
			if (GetLastError() == ERROR_ALREADY_EXISTS) 
			{
				MessageBox(0, GetLocalisation(IDS_APP_SALLY_RUNNING, hInstance).c_str(),
					GetLocalisation(IDS_APP_SALLY_RUNNING_CAPTION, hInstance).c_str(), MB_OK | MB_ICONINFORMATION);

				//Die Semaphore existiert bereits, also beenden 
				return 0; 
			} 
		}

		// show the config dialog
		DialogBox (hInstance, MAKEINTRESOURCE(IDD_DIALOG), 0, DlgProc);

		::CloseHandle(hSem);
	}
	return 0;
}
Example #14
0
File: oglg2d.cpp Project: garinh/cs
bool csGraphics2DOpenGL::Open ()
{
  if (is_open) return true;

  csRef<iVerbosityManager> verbosemgr (
    csQueryRegistry<iVerbosityManager> (object_reg));
  if (verbosemgr) 
    detector.SetVerbose (verbosemgr->Enabled ("renderer.windows.gldriver"));
  
  // create the window.
  if (FullScreen)
  {
    SwitchDisplayMode (false);
  }

  int pixelFormat = -1;
  csGLPixelFormatPicker picker (this);
  /*
    Check if the WGL pixel format check should be used at all.
    It appears that some drivers take "odd" choices when using the WGL
    pixel format path (e.g. returning Accum-capable formats even if none
    was requested).
   */
  bool doWGLcheck = false;
  {
    GLPixelFormat format;
    if (picker.GetNextFormat (format))
    {
      doWGLcheck = (format[glpfvMultiSamples] != 0);
      picker.Reset ();
    }
  }
  if (doWGLcheck)
    pixelFormat = FindPixelFormatWGL (picker);

  m_bActivated = true;

  int wwidth = fbWidth;
  int wheight = fbHeight;
  DWORD exStyle = 0;
  DWORD style = WS_POPUP | WS_SYSMENU;
  int xpos = 0;
  int ypos = 0;
  if (FullScreen)
  {
    /*exStyle |= WS_EX_TOPMOST;*/
  }
  else
  {
    style |= WS_CAPTION | WS_MINIMIZEBOX;
    if (AllowResizing) 
      style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
    
    wwidth += 2 * GetSystemMetrics (SM_CXFIXEDFRAME);
    wheight += 2 * GetSystemMetrics (SM_CYFIXEDFRAME) + GetSystemMetrics (SM_CYCAPTION);
    xpos = (GetSystemMetrics (SM_CXSCREEN) - wwidth) / 2;
    ypos = (GetSystemMetrics (SM_CYSCREEN) - wheight) / 2;
  }

  m_hWnd = m_piWin32Assistant->CreateCSWindow (this, exStyle, style,
    xpos, ypos, wwidth, wheight);

  if (!m_hWnd)
    SystemFatalError (L"Cannot create Crystal Space window", GetLastError());

  SetTitle (win_title);
  
  // Subclass the window
  if (IsWindowUnicode (m_hWnd))
  {
    m_OldWndProc = (WNDPROC)SetWindowLongPtrW (m_hWnd, GWLP_WNDPROC, 
      (LONG_PTR) WindowProc);
    SetWindowLongPtrW (m_hWnd, GWLP_USERDATA, (LONG_PTR)this);
  }
  else
  {
    m_OldWndProc = (WNDPROC)SetWindowLongPtrA (m_hWnd, GWLP_WNDPROC, 
      (LONG_PTR) WindowProc);
    SetWindowLongPtrA (m_hWnd, GWLP_USERDATA, (LONG_PTR)this);
  }

  hDC = GetDC (m_hWnd);
  if (pixelFormat == -1)
  {
    picker.Reset();
    pixelFormat = FindPixelFormatGDI (hDC, picker);
  }

  PIXELFORMATDESCRIPTOR pfd;
  if (DescribePixelFormat (hDC, pixelFormat, 
    sizeof(PIXELFORMATDESCRIPTOR), &pfd) == 0)
    SystemFatalError (L"DescribePixelFormat failed.", GetLastError());

  if (SetPixelFormat (hDC, pixelFormat, &pfd) != TRUE)
  {
    HRESULT spfErr = (HRESULT)GetLastError();
    SystemFatalError (L"SetPixelFormat failed.", spfErr);
  }

  currentFormat[glpfvColorBits] = pfd.cColorBits;
  currentFormat[glpfvAlphaBits] = pfd.cAlphaBits;
  currentFormat[glpfvDepthBits] = pfd.cDepthBits;
  currentFormat[glpfvStencilBits] = pfd.cStencilBits;
  currentFormat[glpfvAccumColorBits] = pfd.cAccumBits;
  currentFormat[glpfvAccumAlphaBits] = pfd.cAccumAlphaBits;

  Depth = pfd.cColorBits; 

  hardwareAccelerated = !(pfd.dwFlags & PFD_GENERIC_FORMAT) ||
    (pfd.dwFlags & PFD_GENERIC_ACCELERATED);

  hGLRC = wglCreateContext (hDC);
  wglMakeCurrent (hDC, hGLRC);

  UpdateWindow (m_hWnd);
  ShowWindow (m_hWnd, m_nCmdShow);
  SetForegroundWindow (m_hWnd);
  SetFocus (m_hWnd);
  
  /* Small hack to emit "no HW acceleration" message on both GDI Generic and
   * sucky Direct3D default OpenGL */
  hardwareAccelerated &= 
    (strncmp ((char*)glGetString (GL_VENDOR), "Microsoft", 9) != 0);
  if (!hardwareAccelerated)
  {
    Report (CS_REPORTER_SEVERITY_WARNING,
      "No hardware acceleration!");
  }

  detector.DoDetection (m_hWnd, hDC);
  Report (CS_REPORTER_SEVERITY_NOTIFY,
    "GL driver: %s %s", detector.GetDriverDLL(), 
    detector.GetDriverVersion() ? detector.GetDriverVersion() : 
      "<version unknown>");

  if (FullScreen)
  {
    /* 
     * from the Windows Shell docs:
     * "It is possible to cover the taskbar by explicitly setting the size 
     * of the window rectangle equal to the size of the screen with 
     * SetWindowPos."
     */
    SetWindowPos (m_hWnd, CS_WINDOW_Z_ORDER, 0, 0, fbWidth, fbHeight, 0);
  }

  if (!csGraphics2DGLCommon::Open ())
    return false;

  ext.InitWGL_EXT_swap_control (hDC);

  if (ext.CS_WGL_EXT_swap_control)
  {
    ext.wglSwapIntervalEXT (vsync ? 1 : 0);
    vsync = (ext.wglGetSwapIntervalEXT() != 0);
    Report (CS_REPORTER_SEVERITY_NOTIFY,
      "VSync is %s.", 
      vsync ? "enabled" : "disabled");
  }

  return true;
}
Example #15
0
SIGPROCDLG_API void CSigProcDlg::SetEditVar(const char *strIn)
{
	SetDlgItemText(IDC_VAR, strIn);
	varstr = strIn;
	UpdateWindow(hDlg);
}
Example #16
0
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, 
					PSTR szCMLine, int iCmdShow){
	static TCHAR szAppName[] = TEXT ("HelloApplication");
	static TCHAR szAppName2[] = TEXT ("HelloApplicationagain");
	HWND	hwnd;
	HWND    hwnd2;
	HWND    hwnd3;
	MSG		msg;
	WNDCLASS wndclass;
	WNDCLASS wndclass2;

	wndclass.style		= CS_HREDRAW | CS_VREDRAW;
	wndclass.lpfnWndProc = HelloWndProc;
	wndclass.cbClsExtra	= sizeof(int);
	wndclass.cbWndExtra = sizeof(int);
	wndclass.hInstance	= hInstance;
	wndclass.hIcon		= LoadIcon (NULL, IDI_APPLICATION);
	wndclass.hCursor	= LoadCursor (NULL, IDC_ARROW);
	wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
	wndclass.lpszMenuName = NULL;
	wndclass.lpszClassName = szAppName;

	wndclass2.style		= CS_HREDRAW | CS_VREDRAW;
	wndclass2.lpfnWndProc = SecondwindowProc;
	wndclass2.cbClsExtra	= 0;
	wndclass2.cbWndExtra = 0;
	wndclass2.hInstance	= hInstance;
	wndclass2.hIcon		= LoadIcon (NULL, IDI_APPLICATION);
	wndclass2.hCursor	= LoadCursor (NULL, IDC_ARROW);
	wndclass2.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH);
	wndclass2.lpszMenuName = NULL;
	wndclass2.lpszClassName = szAppName2;

	if (!RegisterClass (&wndclass)){
		MessageBox (NULL, TEXT ("This program requires Windows 95/98/NT,from1"),
					szAppName, MB_ICONERROR);
		return 0;
	}

	if (!RegisterClass (&wndclass2)){
		MessageBox (NULL, TEXT ("This program requires Windows 95/98/NT,from2"),
					szAppName, MB_ICONERROR);
		return 0;
	}
	
	hwnd = CreateWindow(szAppName,		
						TEXT("Hello World in Color."), 
						WS_OVERLAPPEDWINDOW,	
						100,		
						150,		
						400,		
						300,		
						NULL,				
						NULL,			
						hInstance,			
						NULL);

	hwnd2 = CreateWindow(szAppName,		
						TEXT("Hello World in Color."), 
						WS_OVERLAPPEDWINDOW,	
					    100 + 400,		
						150,		
						400,		
						300,		
						NULL,				
						NULL,			
						hInstance,			
						NULL);	

	hwnd3 = CreateWindow(szAppName2,		
						TEXT("Another widow from different class."), 
						WS_OVERLAPPEDWINDOW,	
					    100,		
						150 + 300,		
						400,		
						300,		
						NULL,				
						NULL,			
						hInstance,			
						NULL);

	SetClassLong(hwnd,0,(LONG)2);
	SetClassLong(hwnd2,0,(LONG)2);
	SetWindowLongPtr(hwnd,0,(LONG_PTR)0);
	SetWindowLongPtr(hwnd2,0,(LONG_PTR)1);
	ShowWindow(hwnd, iCmdShow);
	UpdateWindow(hwnd);
	ShowWindow(hwnd2, iCmdShow);
	UpdateWindow(hwnd2);
	ShowWindow(hwnd3, iCmdShow);
	UpdateWindow(hwnd3);
	while (GetMessage(&msg, NULL, 0, 0)){
		TranslateMessage(&msg);
		DispatchMessage(&msg);
		
	}

	return msg.wParam;
}
Example #17
0
SIGPROCDLG_API void CSigProcDlg::SetEditSig(const char *strIn)
{
	SetDlgItemText(IDC_SIG, strIn);
	sigstr = strIn;
	UpdateWindow(hDlg);
}
Example #18
0
/* returns non zero if ok */
int
mi_create_window(void)
{
  RECT rc;
  WNDCLASS wc;
  TCHAR classname[512];
  TCHAR caption[512];
  DWORD style;
  int x;
  int y;
  int w;
  int h;

  if (g_Wnd != 0 || g_Instance != 0)
  {
    return 0;
  }
  g_Instance = GetModuleHandle(NULL);
  ZeroMemory(&wc, sizeof(wc));
  wc.lpfnWndProc = WndProc; /* points to window procedure */
  /* name of window class */
  str_to_uni(classname, "rdesktop");
  wc.lpszClassName = classname;
  str_to_uni(caption, "ReactOS Remote Desktop");
  wc.hIcon = LoadIcon(g_Instance,
                      MAKEINTRESOURCE(IDI_MSTSC));
  /* Register the window class. */
  if (!RegisterClass(&wc))
  {
    return 0; /* Failed to register window class */
  }
  rc.left = 0;
  rc.right = rc.left + UI_MIN(g_width, g_screen_width);
  rc.top = 0;
  rc.bottom = rc.top + UI_MIN(g_height, g_screen_height);

  if (g_fullscreen)
  {
    style = WS_POPUP;
  }
  else
  {
    style = WS_OVERLAPPED | WS_CAPTION | WS_POPUP | WS_MINIMIZEBOX |
            WS_SYSMENU | WS_SIZEBOX | WS_MAXIMIZEBOX;
  }
  if (g_screen_width < g_width || g_screen_height < g_height)
  {
    style |= WS_HSCROLL | WS_VSCROLL;
  }
  AdjustWindowRectEx(&rc, style, 0, 0);
  x = CW_USEDEFAULT;
  y = CW_USEDEFAULT;
  w = rc.right - rc.left;
  h = rc.bottom - rc.top;

  g_Wnd = CreateWindow(wc.lpszClassName, caption,
                       style, x, y, w, h,
                       (HWND) NULL, (HMENU) NULL, g_Instance,
                       (LPVOID) NULL);
  g_clip_left = 0;
  g_clip_top = 0;
  g_clip_right = g_clip_left + g_width;
  g_clip_bottom = g_clip_top + g_height;
  if (g_workarea)
  {
    ShowWindow(g_Wnd, SW_SHOWMAXIMIZED);
  }
  else
  {
    ShowWindow(g_Wnd, SW_SHOWNORMAL);
  }
  UpdateWindow(g_Wnd);

  WSAAsyncSelect(g_tcp_sck, g_Wnd, WM_APP + 1, FD_READ);
  SetTimer(g_Wnd, 1, 333, 0);

  return 1;
}
Example #19
0
Bool
winCreateBoundingWindowFullScreen (ScreenPtr pScreen)
{
  winScreenPriv(pScreen);
  winScreenInfo		*pScreenInfo = pScreenPriv->pScreenInfo;
  int			iWidth = pScreenInfo->dwWidth;
  int			iHeight = pScreenInfo->dwHeight;
  HWND			*phwnd = &pScreenPriv->hwndScreen;
  WNDCLASS		wc;

  int                   xOrg = pScreenInfo->dwInitialX;
  int                   yOrg = pScreenInfo->dwInitialY;

#ifdef NXWIN_LOGO
  HANDLE nxIcon;

  nxIcon = LoadImage( GetModuleHandle(NULL),
                     MAKEINTRESOURCE(IDI_ICON2),
                     IMAGE_ICON,
                                         16,
                                         16,
                                         /*
                     GetSystemMetrics(SM_CXICON),
                     GetSystemMetrics(SM_CYICON),
                                         */
                     0
                    );

  if(nxIcon == NULL)
  {
     ErrorF ("cannot load icon\n");
  }

#endif

#if CYGDEBUG
  ErrorF ("winCreateBoundingWindowFullScreen\n");
#endif
  ErrorF ("winCreateBoundingWindowFullscreen - User w: %d h: %d\n",
	  pScreenInfo->dwUserWidth, pScreenInfo->dwUserHeight);
  ErrorF ("winCreateBoundingWindowFullscreen - Current w: %d h: %d\n",
	  pScreenInfo->dwWidth, pScreenInfo->dwHeight);
  
  /* Setup our window class */
  wc.style = CS_HREDRAW | CS_VREDRAW;
  wc.lpfnWndProc = winWindowProc;
  wc.cbClsExtra = 0;
  wc.cbWndExtra = 0;
  wc.hInstance = g_hInstance;
#ifdef NXWIN_LOGO
  wc.hIcon = nxIcon;
#else
  wc.hIcon = LoadIcon (g_hInstance, MAKEINTRESOURCE(IDI_XWIN));
#endif
  wc.hCursor = 0;
  wc.hbrBackground = 0;
  wc.lpszMenuName = NULL;
  wc.lpszClassName = WINDOW_CLASS;
  RegisterClass (&wc);

  /* Create the window */
  /* Store current Focus */
  *phwnd = CreateWindowExA (0,                  /* Extended styles */
			    WINDOW_CLASS,	/* Class name */
			    WINDOW_TITLE,	/* Window name */
			    (WS_POPUPWINDOW & ~WS_BORDER)
#ifdef NXWIN_ICONIC
                               | (nxwinIconicMode?WS_ICONIC:0)
#endif
                               ,
			    xOrg,		/* Horizontal position */
			    yOrg,		/* Vertical position */
			    iWidth,		/* Right edge */
			    iHeight,		/* Bottom edge */
			    (HWND) NULL,	/* No parent or owner window */
			    (HMENU) NULL,	/* No menu */
			    GetModuleHandle (NULL),/* Instance handle */
			    pScreenPriv);	/* ScreenPrivates */
  

  /* Branch on the server engine */
  switch (pScreenInfo->dwEngine)
    {
    case WIN_SERVER_SHADOW_GDI:
      /* Show the window */
      ShowWindow (*phwnd,   nxwinHideStart?SW_HIDE:SW_SHOWMAXIMIZED);
      break;

    default:
      /* Hide the window */
      ShowWindow (*phwnd,   nxwinHideStart?SW_HIDE:SW_SHOWNORMAL);
      break;
    }
  /* Send first paint message */
  UpdateWindow (*phwnd);
  SetWindowText(*phwnd, nxwinWinName);
  /* Attempt to bring our window to the top of the display */
  if( !nxwinHideStart )
      BringWindowToTop (*phwnd);

  return TRUE;
}
Example #20
0
/*
================
rvDebuggerServer::Break

Halt execution of the game threads and inform the debugger client that
the game has been halted
================
*/
void rvDebuggerServer::Break ( idInterpreter* interpreter, idProgram* program, int instructionPointer )
{
	msg_t				msg;
	byte				buffer[MAX_MSGLEN];
	const statement_t*	st;
	const char*			filename;

	// Clear all the break types
	mBreakStepOver = false;
	mBreakStepInto = false;
	mBreakNext     = false;
	
	// Grab the current statement and the filename that it came from
	st       = &program->GetStatement ( instructionPointer );
	filename = program->GetFilename ( st->file );

	idStr qpath;
	OSPathToRelativePath(filename, qpath);	
	qpath.BackSlashesToSlashes ( );

	// Give the mouse cursor back to the world
	Sys_GrabMouseCursor( false );	
	
	// Set the break variable so we know the main thread is stopped
	mBreak = true;
	mBreakProgram = program;
	mBreakInterpreter = interpreter;
	mBreakInstructionPointer = instructionPointer;
	
	// Inform the debugger of the breakpoint hit
	MSG_Init( &msg, buffer, sizeof( buffer ) );
	MSG_WriteShort ( &msg, (int)DBMSG_BREAK );
	MSG_WriteLong ( &msg, st->linenumber );
	MSG_WriteString ( &msg, qpath );
	SendPacket ( msg.data, msg.cursize );
		
	// Suspend the game thread.  Since this will be called from within the main game thread
	// execution wont return until after the thread is resumed
	SuspendThread ( mGameThread );						
	
	// Let the debugger client know that we have started back up again
	SendMessage ( DBMSG_RESUMED );

	// This is to give some time between the keypress that 
	// told us to resume and the setforeground window.  Otherwise the quake window
	// would just flash
	Sleep ( 150 );

	// Bring the window back to the foreground	
	SetForegroundWindow ( win32.hWnd );
	SetActiveWindow ( win32.hWnd );
	UpdateWindow ( win32.hWnd );
	SetFocus ( win32.hWnd );	
	
	// Give the mouse cursor back to the game
	Sys_GrabMouseCursor( true );	
	
	// Clear all commands that were generated before we went into suspended mode.  This is
	// to ensure we dont have mouse downs with no ups because the context was changed.
	idKeyInput::ClearStates();
}
void dGLWWidget::Update()
{
    UpdateWindow(m_nativeHandle);
}
Example #22
0
/*
=======================
GLW_CreateWindow

Responsible for creating the Win32 window.
If fullscreen, it won't have a border
=======================
*/
static bool GLW_CreateWindow( glimpParms_t parms ) {
	int				x, y, w, h;
	if ( !GLW_GetWindowDimensions( parms, x, y, w, h ) ) {
		return false;
	}

	int				stylebits;
	int				exstyle;
	if ( parms.fullScreen != 0 ) {
		exstyle = WS_EX_TOPMOST;
		stylebits = WS_POPUP|WS_VISIBLE|WS_SYSMENU;
	} else {
		exstyle = 0;
		stylebits = WINDOW_STYLE|WS_SYSMENU;
	}

	win32.hWnd = CreateWindowEx (
		 exstyle, 
		 WIN32_WINDOW_CLASS_NAME,
		 GAME_NAME,
		 stylebits,
		 x, y, w, h,
		 NULL,
		 NULL,
		 win32.hInstance,
		 NULL);

	if ( !win32.hWnd ) {
		common->Printf( "^3GLW_CreateWindow() - Couldn't create window^0\n" );
		return false;
	}

	::SetTimer( win32.hWnd, 0, 100, NULL );

	ShowWindow( win32.hWnd, SW_SHOW );
	UpdateWindow( win32.hWnd );
	common->Printf( "...created window @ %d,%d (%dx%d)\n", x, y, w, h );

	// makeCurrent NULL frees the DC, so get another
	win32.hDC = GetDC( win32.hWnd );
	if ( !win32.hDC ) {
		common->Printf( "^3GLW_CreateWindow() - GetDC()failed^0\n" );
		return false;
	}

	// Check to see if we can get a stereo pixel format, even if we aren't going to use it,
	// so the menu option can be 
	if ( GLW_ChoosePixelFormat( win32.hDC, parms.multiSamples, true ) != -1 ) {
		glConfig.stereoPixelFormatAvailable = true;
	} else {
		glConfig.stereoPixelFormatAvailable = false;
	}

	if ( !GLW_InitDriver( parms ) ) {
		ShowWindow( win32.hWnd, SW_HIDE );
		DestroyWindow( win32.hWnd );
		win32.hWnd = NULL;
		return false;
	}

	SetForegroundWindow( win32.hWnd );
	SetFocus( win32.hWnd );

	glConfig.isFullscreen = parms.fullScreen;

	return true;
}
	void ApplicationWindows::OnCreateInternal()
	{
		Options& opts = Core::GetOptions();
		HINSTANCE instance = ::GetModuleHandle(NULL);
		const bool windowCreated = CreateWin32Window(instance);
		if (!windowCreated)
			throw std::runtime_error("Window cannot be created.");

		//single instance check
		TCHAR fileName[MAX_PATH];
		GetModuleFileName(NULL, fileName, MAX_PATH);
		fileName[MAX_PATH - 1] = 0; //string can be not null-terminated on winXP
		for (int i = 0; i < MAX_PATH; ++i)
		{
			if (fileName[i] == L'\\') //symbol \ is not allowed in CreateMutex mutex name
				fileName[i] = ' ';
		}

		SetLastError(0);

		LPCWSTR class_name = L"Tetris";
		RegisterApplicationClass(instance, (WNDPROC)WndProc, class_name);

		// calculate client size
		RECT clientSize;
		clientSize.top = 0;
		clientSize.left = 0;
		clientSize.right = opts.width;
		clientSize.bottom = opts.height;

		ULONG style = WINDOWED_STYLE | WS_CLIPCHILDREN;
		AdjustWindowRect(&clientSize, style, FALSE);

		int realWidth = clientSize.right - clientSize.left;
		int realHeight = clientSize.bottom - clientSize.top;

		int windowLeft = -10000;
		int windowTop = -10000;

		// create window
		mh_window = CreateWindow(class_name, L"", style, windowLeft, windowTop,
			realWidth, realHeight, NULL, NULL, mh_instance, NULL);

		ShowWindow(mh_window, SW_SHOW);
		UpdateWindow(mh_window);

		// fix ugly ATI driver bugs. Thanks to ariaci (Taken from Irrlight).
		MoveWindow(mh_window, windowLeft, windowTop, realWidth, realHeight, TRUE);
		SetWindowText(mh_window, class_name);

		// move window
		clientSize.top = 0;
		clientSize.left = 0;
		clientSize.right = Core::GetOptions().width;
		clientSize.bottom = Core::GetOptions().height;

		AdjustWindowRect(&clientSize, style, FALSE);

		realWidth = clientSize.right - clientSize.left;
		realHeight = clientSize.bottom - clientSize.top;

		windowLeft = (GetSystemMetrics(SM_CXSCREEN) - realWidth) / 2;
		windowTop = (GetSystemMetrics(SM_CYSCREEN) - realHeight) / 2;
		MoveWindow(mh_window, windowLeft, windowTop, realWidth, realHeight, TRUE);

		Core::SetupRenderer(std::unique_ptr<IRenderer>(new OpenGLRenderer(mh_window, IRect())));
		auto p_renderer = Core::GetRenderer();
		p_renderer->Initialize();
		p_renderer->Reshape();

		RAWINPUTDEVICE Rid[2];
		// Keyboard
		Rid[0].usUsagePage = 0x01;
		Rid[0].usUsage = 0x06;
		Rid[0].dwFlags = 0;
		Rid[0].hwndTarget = NULL;
		// Mouse
		Rid[1].usUsagePage = 0x01;
		Rid[1].usUsage = 0x02;
		Rid[1].dwFlags = 0;
		Rid[1].hwndTarget = NULL;

		if (RegisterRawInputDevices(Rid, 2, sizeof(RAWINPUTDEVICE)) == FALSE)
			throw std::runtime_error("Cannot register input devices");

		// initialize timer
		QueryPerformanceFrequency(&liFrequency);
	}
Example #24
0
File: main.c Project: GYGit/reactos
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
    WNDCLASSEX wcFrame = {
        sizeof(WNDCLASSEX),
        CS_HREDRAW | CS_VREDRAW/*style*/,
        FrameWndProc,
        0/*cbClsExtra*/,
        0/*cbWndExtra*/,
        hInstance,
        LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MDI_APP)),
        LoadCursor(0, IDC_ARROW),
        0/*hbrBackground*/,
        0/*lpszMenuName*/,
        szFrameClass,
        (HICON)LoadImage(hInstance, MAKEINTRESOURCE(IDI_MDI_APP), IMAGE_ICON,
            GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_SHARED)
    };
    ATOM hFrameWndClass = RegisterClassEx(&wcFrame); // register frame window class
#if 0
    WNDCLASS wcChild = {
        CS_CLASSDC|CS_DBLCLKS|CS_VREDRAW,
        ChildWndProc,
        0/*cbClsExtra*/,
        0/*cbWndExtra*/,
        hInstance,
        0/*hIcon*/,
        LoadCursor(0, IDC_ARROW),
        0/*hbrBackground*/,
        0/*lpszMenuName*/,
        szChildClass
    };
    ATOM hChildWndClass = RegisterClass(&wcChild); // register child windows class
#else
    // WNDCLASSEX wcChild = {
    //     sizeof(WNDCLASSEX),
    //     CS_HREDRAW | CS_VREDRAW/*style*/,
    //     ChildWndProc,
    //     0/*cbClsExtra*/,
    //     sizeof(HANDLE)/*cbWndExtra*/,
    //     hInstance,
    //     LoadIcon(hInstance, MAKEINTRESOURCE(IDI_MDI_APP)),
    //     LoadCursor(0, IDC_ARROW),
    //     0/*hbrBackground*/,
    //     0/*lpszMenuName*/,
    //     szChildClass,
    //     (HICON)LoadImage(hInstance, MAKEINTRESOURCE(IDC_MDI_APP), IMAGE_ICON,
    //         GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), LR_SHARED)
    // };
    // ATOM hChildWndClass = RegisterClassEx(&wcChild); // register child windows class
#endif

    HMENU hMenu = LoadMenu(hInstance, MAKEINTRESOURCE(IDC_MDI_APP));
    HMENU hMenuOptions = GetSubMenu(hMenu, ID_OPTIONS_MENU);
    // HMENU hChildMenu = LoadMenu(hInstance, MAKEINTRESOURCE(IDC_MDI_APP_CHILD));

    INITCOMMONCONTROLSEX icc = {
        sizeof(INITCOMMONCONTROLSEX),
        ICC_BAR_CLASSES
    };

    HDC hdc = GetDC(0);

    hMenuFrame = hMenu;
//  hMenuView = GetSubMenu(hMenuFrame, ID_VIEW_MENU);
    hAccel = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MDI_APP));
    hFont = CreateFont(-MulDiv(8,GetDeviceCaps(hdc,LOGPIXELSY),72), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, _T("MS Sans Serif"));
    ReleaseDC(0, hdc);

    hFrameWnd = CreateWindowEx(0, (LPCTSTR)(int)hFrameWndClass, szTitle,
//  hFrameWnd = CreateWindow(szFrameClass, szTitle,
                    WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN,
                    CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
                    NULL/*hWndParent*/, hMenuFrame, hInstance, NULL/*lpParam*/);
    if (!hFrameWnd) {
        return FALSE;
    }

    if (InitCommonControlsEx(&icc))
    {
        int nParts[3];
        TBBUTTON toolbarBtns[] = {
            {0, 0, 0, TBSTYLE_SEP},
            {0, ID_WINDOW_NEW_WINDOW, TBSTATE_ENABLED, TBSTYLE_BUTTON},
            {1, ID_WINDOW_CASCADE, TBSTATE_ENABLED, TBSTYLE_BUTTON},
            {2, ID_WINDOW_TILE_HORZ, TBSTATE_ENABLED, TBSTYLE_BUTTON},
            {3, ID_WINDOW_TILE_VERT, TBSTATE_ENABLED, TBSTYLE_BUTTON},
            {4, 2/*TODO: ID_...*/, TBSTATE_ENABLED, TBSTYLE_BUTTON},
            {5, 2/*TODO: ID_...*/, TBSTATE_ENABLED, TBSTYLE_BUTTON},
        };

        hToolBar = CreateToolbarEx(hFrameWnd, WS_CHILD|WS_VISIBLE,
            IDC_TOOLBAR, 2, hInstance, IDB_TOOLBAR, toolbarBtns,
            sizeof(toolbarBtns)/sizeof(TBBUTTON), 16, 15, 16, 15, sizeof(TBBUTTON));
        CheckMenuItem(hMenuOptions, ID_OPTIONS_TOOLBAR, MF_BYCOMMAND|MF_CHECKED);

        // Create the status bar
        hStatusBar = CreateStatusWindow(WS_VISIBLE|WS_CHILD|WS_CLIPSIBLINGS|SBT_NOBORDERS,
                                        "", hFrameWnd, IDC_STATUSBAR);
        if (!hStatusBar)
            return FALSE;
        CheckMenuItem(hMenuOptions, ID_OPTIONS_STATUSBAR, MF_BYCOMMAND|MF_CHECKED);

        // Create the status bar panes
        nParts[0] = 100;
        nParts[1] = 210;
        nParts[2] = 400;
        SendMessage(hStatusBar, SB_SETPARTS, 3, (long)nParts);
    } else {
        CheckMenuItem(hMenuOptions, ID_OPTIONS_TOOLBAR, MF_BYCOMMAND|MF_GRAYED);
        CheckMenuItem(hMenuOptions, ID_OPTIONS_STATUSBAR, MF_BYCOMMAND|MF_GRAYED);
	}

    ShowWindow(hFrameWnd, nCmdShow);
    UpdateWindow(hFrameWnd);
    UpdateStatusBar();
    return TRUE;
}
Example #25
0
/******************************************************************************
 * FontEditCommand(hBox, id)
 *
 * purpose: interprets menu id and calls appropriate function to do the task
 *
 * params:  HWND hBox : handle to main window
 *          WORD id   : menu command id
 * returns: none
 *
 * side effects: plenty
 *
 *****************************************************************************/
VOID
FontEditCommand(
	HWND hBox,
	WORD id
	)
{
	CHAR * szError;                 /* String for error messages */
	LONG w; 
	DWORD y, i, j;
	BOOL fRepaint = FALSE;
	HMENU hMenu;
	DLGPROC lpprocAboutDlg;
	MSG message;

	szError = "";               /* No Errors yet */

	switch (id) {
	    case FONT_EXIT:
		if (!CheckSave())    /* See if any files need saving */
			break;
		/* Window's being destroyed. */
		if (fLoaded)         /* 4/8/87 Linsh added */
			DeleteBitmap(); /* Get rid of memory DC */
		PostQuitMessage(0);  /* Cause application to be terminated */
                break;

            case FONT_HELP_CONTENTS:
                WinHelp(hFont, gszHelpFile, HELP_CONTENTS, 0L);
                break;

            case FONT_HELP_SEARCH:
                /*
                 * Tell winhelp to be sure this app's help file is current,
                 * then invoke a search with an empty starting key.
                 */
                WinHelp(hFont, gszHelpFile, HELP_FORCEFILE, 0);
                WinHelp(hFont, gszHelpFile, HELP_PARTIALKEY, (DWORD)(LPSTR)"");
                break;

	    case FONT_ABOUT:
		lpprocAboutDlg = (DLGPROC)AboutDlg;
		DialogBox (hInst, vszABOUT, hBox, lpprocAboutDlg);
		FreeProcInstance (lpprocAboutDlg);
		break;

	    case FONT_LOAD:             /*  Check File Name  */
	    case FONT_NEW :
		if (!CheckSave())       /*  See if current font needs saving */
			return;
	/* to prevent scrambling of Show window chars, Bring back Show
        ** window to parent window's client area before invoking the dialog */

		if (CommDlgOpen(hBox,&ofstrFile,szNewFile,szExt,szFontFile,id)
				== FALSE) {

			InvalidateRect(hFont, (LPRECT)NULL, FALSE);
			UpdateWindow(hFont);
			return;
		}
		/* else drop thru */

	    case FONT_START:	/*  Here if file name passed as argument */
		InvalidateRect(hFont, (LPRECT)NULL, FALSE);
		UpdateWindow(hFont);

		szError = FontLoad (szNewFile, &ofstrFile);

	/* Hack : needed to remove umwanted WM_MOUSEMOVE messages from the 
         * queue.
         * Apparently, Windows needs to reposition the mouse after a dialog
         * is ended with a mouse double-click (releases mouse capture?) for
         * which a couple of WM_MOUSEMOVEs may get sent to parent app.
         * These mess with the edit box below the dialog if they happen to 
         * overlap.
         */
		PeekMessage((LPMSG) &message, hBox, WM_MOUSEMOVE, WM_MOUSEMOVE,
		    PM_REMOVE);

		if (fLoaded)    /* If loaded then do a few things */ {
		    jChar = iChar = 65;                 /* Show an A */
		    if ((BYTE)iChar > (BYTE)font.LastChar)
			jChar = iChar = font.FirstChar; /* .. if we can */
		    swH = 15;                   /* Good bet to make A visible */
		    fEdited = fChanged = FALSE;
		    ResizeShow();               /* Set Box to proper size */
		    ScrollFont();               /* Set thumb */
		    CharToBox(iChar);
		}
		FontRename(szError);
		SetFocus(hBox);
		return;

	    case FONT_SAVE:
		if (!NewFile) {
		    if (fLoaded && fChanged) {
			lstrcpy((LPSTR)szNewFile, (LPSTR)szFontFileFull);
			BoxToChar(iChar);           /* Just in case */
			szError = FontSave (szNewFile, &ofstrFile);
			FontRename(szError);        /* Rename or Print Error */
			return;
		    }
		    else
			return;
		}
	/* else file has been opened by selecting NEW... on menu.
         * Fall thro' and bring up SaveAs dialog minus default
         * filename in edit window */

	    case FONT_SAVEAS:
		BoxToChar(iChar);               /* Just in case */

		if (CommDlgSaveAs (hInst, hBox, &ofstrFile, szNewFile, szExt,
				szFontFile) == TRUE) {

		    szError = FontSave (szNewFile, &ofstrFile);
		    FontRename (szError);          /* Rename or Print Error */
		}

		/* to prevent scrambling of Show window chars,
           repaint show window after dialog is brought down */
		InvalidateRect (hFont, (LPRECT)NULL, TRUE);
		UpdateWindow (hFont);
		return;

	    case FONT_HEADER:
		/* to prevent scrambling of Show window chars,
		 * repaint show window after dialog is invoked */
		DialogBox(hInst, (LPSTR)vszDHeader, hBox, lpHeaderProc);
		InvalidateRect(hFont, (LPRECT)NULL, TRUE);
		UpdateWindow(hFont);
		return;

	    case FONT_RESIZE:
		/* to prevent scrambling of Show window chars,
		   repaint show window after dialog is brought down */
		if (DialogBox(hInst, (LPSTR)vszDResize, hBox, lpReSizeProc)) {
		    /* BoxToChar(iChar);*/ /* save current before resizing */
		    ResizeShow();       /* New Font Display Size */
		    CharToBox(iChar);               /* New Box display */
		}
		InvalidateRect(hFont, (LPRECT)NULL, TRUE);
		UpdateWindow(hFont);
		return;

	    case FONT_COPY:                     /* Copy to Clipboard */
		BoxToChar(iChar);               /* Just in case */
		ToClipboard(iChar, wBox, kBox);
		break;

	    case FONT_PASTE:            /* Paste in Character form Clipboard */
		BoxBackup();            /* In case we change our minds */
		ptA.x = ptA.y = 0;
		wBox = ClipboardToBox(ptA, wBox, kBox, TRUE);
		fRepaint = TRUE;
		break;

	    case WIDER_LEFT:
	    case WIDER_RIGHT:
	    case WIDER_BOTH:
	    case NARROWER_LEFT:
	    case NARROWER_RIGHT:
	    case NARROWER_BOTH:
	    case WIDTH:
		w = newWidth = wBox;
		if (font.Family & 1)            /* Variable width or else */ {
		    switch (id) {
			case WIDER_BOTH:
			    w++;
			case WIDER_LEFT:
			case WIDER_RIGHT:
			    w++;
			    break;
			case NARROWER_BOTH:
			    w--;
			case NARROWER_LEFT:
			case NARROWER_RIGHT:
			    w--;
			    break;
			case WIDTH:
			    if (DialogBox(hInst,
					(LPSTR)vszDWidth, hBox, lpWidthProc))
				w = newWidth;
			    break;
		    }

		    if (w < 0 || w >= wBoxLim) {
			MessageBox(hBox,
				(LPSTR)vszEdLimits0To64,
				(LPSTR)szAppName,
				MB_OK | MB_ICONASTERISK);
			break;                  /* Out of range! quit */
		    }
		    if (w > (LONG) font.MaxWidth) {
			if (IDOK == MessageBox(hBox,
					    (LPSTR)vszMaxWidthIncrease,
					    (LPSTR)szAppName,
					    MB_OKCANCEL | MB_ICONQUESTION))
			    font.MaxWidth = (WORD)w;
			else
			    break;
		    }
		    BoxBackup();                /* In case we change our minds */
		    wBox = (WORD)w;             /* Reset width */
		    fRepaint = TRUE;            /* Signal redraw */
		    switch (id) {
		    case WIDER_LEFT:
#ifdef DBCS	//DBCS_FIX
			DupCol(0, kBoxLim - 1);
			for (y = 0; y < kBoxLim; y++)
			    matBox[0][y] = FALSE;       /* Clear left column */
			break;
#endif
		    case WIDER_BOTH:            /* Shift character one right */
			DupCol(0, kBoxLim - 1);
			for (y = 0; y < kBoxLim; y++)
			    matBox[wBox -1][y] = FALSE; /* Clear right column */
			for (y = 0; y < kBoxLim; y++)
			    matBox[0][y] = FALSE;       /* Clear left column */
			break;
		    case NARROWER_LEFT:
		    case NARROWER_BOTH:	/* Shift character one left */
			if (wBox) {	/* .. unless width is already 0 */
			    for (j = 0; j <= kBox - 1; j++)
				for (i = 0; i <= wBox - 1; i++)
				    matBox[i][j] = matBox[i + 1][j];
			    break;
			}
		    }
		}
		else {
		    MessageBox(hBox,
			    (LPSTR)vszCannotChangeWidth,
			    (LPSTR)szAppName,
			    MB_OK | MB_ICONASTERISK);
		}
		break;

	    case ROW_ADD:
	    case ROW_DEL:
	    case COL_ADD:
	    case COL_DEL:
		/* set cursor to "+" shaped cursor */
		SetCapture (hBox); /* so that cursor doesn't get restored
				      before we are done */
		hOldCursor = SetCursor (LoadCursor (NULL, IDC_CROSS));
		fCaptured = TRUE;
		cursor = id;
		break;

	    case BOX_CLEAR:
	    case BOX_FILL:
	    case BOX_INV:
	    case BOX_HATCH:
	    case BOX_LEFTRIGHT:
	    case BOX_TOPBOTTOM:
	    case BOX_COPY:
	    case BOX_PASTE:
		/* Get one o' da funky cursors */
		SetCapture(hBox);
		hOldCursor = SetCursor(LoadCursor(hInst, MAKEINTRESOURCE(id)));
		fStartRubberBand = TRUE;
		CharRectDimensions((LPRECT)&FontRect);
		cursor = id;
		break;

	    case BOX_REFRESH:           /* Go get old version of character */
		BoxBackup();            /* In case we change our minds */
		CharToBox(iChar);
		hMenu = GetMenu(hBox);
		EnableMenuItem(hMenu, BOX_UNDO, MF_ENABLED);    /* Can Unrefresh! */
		break;
	    case BOX_UNDO:
		BoxRestore();
		hMenu = GetMenu(hBox);
		EnableMenuItem(hMenu, BOX_REFRESH, MF_ENABLED);
		fRepaint = TRUE;
		break;
	}
	if (fRepaint) {
		fEdited = fChanged = TRUE;
		InvalidateRect(hBox, (LPRECT)NULL, TRUE);
	}
}
Example #26
0
int WINAPI WinMain(HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int nCmdShow)
{
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);
	wcex.style = CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc = WndProc;
	wcex.cbClsExtra = 0;
	wcex.cbWndExtra = 0;
	wcex.hInstance = hInstance;
	wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
	wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wcex.lpszMenuName = NULL;
	wcex.lpszClassName = szWindowClass;
	wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));

	if (!RegisterClassEx(&wcex))
	{
		MessageBox(NULL,
			_T("Call to RegisterClassEx failed!"),
			_T("Win32 Guided Tour"),
			NULL);

		return 1;
	}

	hInst = hInstance; // Store instance handle in our global variable

	// The parameters to CreateWindow explained:
	// szWindowClass: the name of the application
	// szTitle: the text that appears in the title bar
	// WS_OVERLAPPEDWINDOW: the type of window to create
	// CW_USEDEFAULT, CW_USEDEFAULT: initial position (x, y)
	// 500, 100: initial size (width, length)
	// NULL: the parent of this window
	// NULL: this application does not have a menu bar
	// hInstance: the first parameter from WinMain
	// NULL: not used in this application
	HWND hWnd = CreateWindow(
		szWindowClass,
		szTitle,
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, CW_USEDEFAULT,
		500, 300,
		NULL,
		NULL,
		hInstance,
		NULL
		);

	hwndButton = CreateWindowEx(0,
		L"BUTTON",  // Predefined class; Unicode assumed 
		L"OK",      // Button text 
		WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  // Styles 
		310,         // x position 
		10,         // y position 
		100,        // Button width
		50,        // Button height
		hWnd,     // Parent window
		NULL,       // No menu.
		(HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE),
		NULL);      // Pointer not needed.

	editctl = CreateWindow(L"EDIT", 0, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_AUTOHSCROLL | ES_WANTRETURN, 10, 10, 300, 100, hWnd, (HMENU)(101), hInst, 0);
	

	if (!hWnd)
	{
		MessageBox(NULL,
			_T("Call to CreateWindow failed!"),
			_T("Win32 Guided Tour"),
			NULL);

		return 1;
	}

	// The parameters to ShowWindow explained:
	// hWnd: the value returned from CreateWindow
	// nCmdShow: the fourth parameter from WinMain
	ShowWindow(hWnd,
		nCmdShow);
	UpdateWindow(hWnd);

	// Main message loop:
	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0))
	{
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}

	return (int)msg.wParam;
}
Example #27
0
//----------------------------------------------------------------------------
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE, LPSTR acArgument, int)
{
    FWinApplication* pkTheApp = FWinApplication::GetApplication();
    assert( pkTheApp );
    if ( !pkTheApp )
        return -1;

    gs_hInstance = hInstance;

    if ( acArgument && strlen(acArgument) > 0 )
    {
        char* acProcessed = ProcessArgument(acArgument);
        pkTheApp->SetCommand(new Command(acProcessed));
        delete[] acProcessed;
    }

    if ( !pkTheApp->OnPrecreate() )
        return -2;

    // register the window class
    WNDCLASS kWC;
    kWC.style         = CS_HREDRAW | CS_VREDRAW;
    kWC.lpfnWndProc   = WinProc;
    kWC.cbClsExtra    = 0;
    kWC.cbWndExtra    = 0;
    kWC.hInstance     = hInstance;
    kWC.hIcon         = LoadIcon(NULL,IDI_APPLICATION);
    kWC.hCursor       = LoadCursor(NULL,IDC_ARROW);
    kWC.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
    kWC.lpszClassName = gs_acWindowClassName;
    if ( pkTheApp->GetMenuID() )
        kWC.lpszMenuName  = MAKEINTRESOURCE(pkTheApp->GetMenuID());
    else
        kWC.lpszMenuName = 0;

    RegisterClass(&kWC);

    // require the window to have the specified client area
    RECT kRect = { 0, 0, pkTheApp->GetWidth()-1, pkTheApp->GetHeight()-1 };
    AdjustWindowRect(&kRect,gs_dwWindowStyle,pkTheApp->GetMenuID());

    // create the application window
    int iXPos = CW_USEDEFAULT;
    int iYPos = CW_USEDEFAULT;
    int iXSize = kRect.right - kRect.left + 1;
    int iYSize = kRect.bottom - kRect.top + 1;
    HWND hWnd = CreateWindow(gs_acWindowClassName,pkTheApp->GetCaption(),
        gs_dwWindowStyle,iXPos,iYPos,iXSize,iYSize,0,0,hInstance,0);

    pkTheApp->SetWindowHandle(hWnd);

    // create status window
    if ( pkTheApp->GetStatusPaneQuantity() )
    {
        InitCommonControls();

        HWND hStatusWnd = CreateWindow(STATUSCLASSNAME,"",
            WS_CHILD | WS_VISIBLE,0,0,0,0,hWnd,0,hInstance,0);

        pkTheApp->SetStatusWindowHandle(hStatusWnd);
    }

    // display the window
    ShowWindow(hWnd,SW_SHOW);
    UpdateWindow(hWnd);

    // allow the application to initialize before starting the message pump
    if ( !pkTheApp->OnInitialize() )
        return -3;

    MSG kMsg;
    while ( true )
    {
        if ( PeekMessage(&kMsg,0,0,0,PM_REMOVE) )
        {
            if ( kMsg.message == WM_QUIT )
                break;

            HACCEL hAccel = 0;
            if ( !TranslateAccelerator(hWnd,hAccel,&kMsg) )
            {
                TranslateMessage(&kMsg);
                DispatchMessage(&kMsg);
            }
        }
        else
        {
            pkTheApp->OnIdle();
        }
    }

    pkTheApp->OnTerminate();

    UnregisterClass(gs_acWindowClassName,hInstance);

    return 0;
}
Example #28
0
//todo: this function is an abomination, this is just disgusting.  fix it.
//...seriously, this is really, really horrible.  I mean this is amazingly bad.
void OBS::MainCaptureLoop()
{
    int curRenderTarget = 0, curYUVTexture = 0, curCopyTexture = 0;
    int copyWait = NUM_RENDER_BUFFERS-1;

    bSentHeaders = false;
    bFirstAudioPacket = true;

    Vect2 baseSize    = Vect2(float(baseCX), float(baseCY));
    Vect2 outputSize  = Vect2(float(outputCX), float(outputCY));
    Vect2 scaleSize   = Vect2(float(scaleCX), float(scaleCY));

    HANDLE hScaleVal = yuvScalePixelShader->GetParameterByName(TEXT("baseDimensionI"));

    LPVOID nullBuff = NULL;

    //----------------------------------------
    // x264 input buffers

    int curOutBuffer = 0;

    x264_picture_t *lastPic = NULL;
    x264_picture_t outPics[NUM_OUT_BUFFERS];
    DWORD outTimes[NUM_OUT_BUFFERS] = {0, 0, 0};

    for(int i=0; i<NUM_OUT_BUFFERS; i++)
        x264_picture_init(&outPics[i]);

    if(bUsing444)
    {
        for(int i=0; i<NUM_OUT_BUFFERS; i++)
        {
            outPics[i].img.i_csp   = X264_CSP_BGRA; //although the x264 input says BGR, x264 actually will expect packed UYV
            outPics[i].img.i_plane = 1;
        }
    }
    else
    {
        for(int i=0; i<NUM_OUT_BUFFERS; i++)
            x264_picture_alloc(&outPics[i], X264_CSP_I420, outputCX, outputCY);
    }

    //----------------------------------------
    // time/timestamp stuff

    LARGE_INTEGER clockFreq;
    QueryPerformanceFrequency(&clockFreq);

    bufferedTimes.Clear();
    ctsOffsets.Clear();

#ifdef USE_100NS_TIME
    QWORD streamTimeStart = GetQPCTime100NS(clockFreq.QuadPart);
    QWORD frameTime100ns = 10000000/fps;

    QWORD sleepTargetTime = 0;
    bool bWasLaggedFrame = false;
#else
    DWORD streamTimeStart = OSGetTime();
#endif
    totalStreamTime = 0;

    lastAudioTimestamp = 0;

    latestVideoTime = firstSceneTimestamp = GetQPCTimeMS(clockFreq.QuadPart);

    DWORD fpsTimeNumerator = 1000-(frameTime*fps);
    DWORD fpsTimeDenominator = fps;
    DWORD fpsTimeAdjust = 0;

    DWORD cfrTime = 0;
    DWORD cfrTimeAdjust = 0;

    //----------------------------------------
    // start audio capture streams

    desktopAudio->StartCapture();
    if(micAudio) micAudio->StartCapture();

    //----------------------------------------
    // status bar/statistics stuff

    DWORD fpsCounter = 0;

    int numLongFrames = 0;
    int numTotalFrames = 0;

    int numTotalDuplicatedFrames = 0;

    bytesPerSec = 0;
    captureFPS = 0;
    curFramesDropped = 0;
    curStrain = 0.0;
    PostMessage(hwndMain, OBS_UPDATESTATUSBAR, 0, 0);

    QWORD lastBytesSent[3] = {0, 0, 0};
    DWORD lastFramesDropped = 0;
#ifdef USE_100NS_TIME
    double bpsTime = 0.0;
#else
    float bpsTime = 0.0f;
#endif
    double lastStrain = 0.0f;
    DWORD numSecondsWaited = 0;

    //----------------------------------------
    // 444->420 thread data

    int numThreads = MAX(OSGetTotalCores()-2, 1);
    HANDLE *h420Threads = (HANDLE*)Allocate(sizeof(HANDLE)*numThreads);
    Convert444Data *convertInfo = (Convert444Data*)Allocate(sizeof(Convert444Data)*numThreads);

    zero(h420Threads, sizeof(HANDLE)*numThreads);
    zero(convertInfo, sizeof(Convert444Data)*numThreads);

    for(int i=0; i<numThreads; i++)
    {
        convertInfo[i].width  = outputCX;
        convertInfo[i].height = outputCY;
        convertInfo[i].hSignalConvert  = CreateEvent(NULL, FALSE, FALSE, NULL);
        convertInfo[i].hSignalComplete = CreateEvent(NULL, FALSE, FALSE, NULL);

        if(i == 0)
            convertInfo[i].startY = 0;
        else
            convertInfo[i].startY = convertInfo[i-1].endY;

        if(i == (numThreads-1))
            convertInfo[i].endY = outputCY;
        else
            convertInfo[i].endY = ((outputCY/numThreads)*(i+1)) & 0xFFFFFFFE;
    }

    bool bFirstFrame = true;
    bool bFirstImage = true;
    bool bFirst420Encode = true;
    bool bUseThreaded420 = bUseMultithreadedOptimizations && (OSGetTotalCores() > 1) && !bUsing444;

    List<HANDLE> completeEvents;

    if(bUseThreaded420)
    {
        for(int i=0; i<numThreads; i++)
        {
            h420Threads[i] = OSCreateThread((XTHREAD)Convert444Thread, convertInfo+i);
            completeEvents << convertInfo[i].hSignalComplete;
        }
    }

    //----------------------------------------

    QWORD curStreamTime = 0, lastStreamTime, firstFrameTime = GetQPCTimeMS(clockFreq.QuadPart);
    lastStreamTime = firstFrameTime-frameTime;

    bool bFirstAudioPacket = true;

    while(bRunning)
    {
#ifdef USE_100NS_TIME
        QWORD renderStartTime = GetQPCTime100NS(clockFreq.QuadPart);

        if(sleepTargetTime == 0 || bWasLaggedFrame)
            sleepTargetTime = renderStartTime;
#else
        DWORD renderStartTime = OSGetTime();
        totalStreamTime = renderStartTime-streamTimeStart;

        DWORD frameTimeAdjust = frameTime;
        fpsTimeAdjust += fpsTimeNumerator;
        if(fpsTimeAdjust > fpsTimeDenominator)
        {
            fpsTimeAdjust -= fpsTimeDenominator;
            ++frameTimeAdjust;
        }
#endif

        bool bRenderView = !IsIconic(hwndMain) && bRenderViewEnabled;

        profileIn("frame");

#ifdef USE_100NS_TIME
        QWORD qwTime = renderStartTime/10000;
        latestVideoTime = qwTime;

        QWORD frameDelta = renderStartTime-lastStreamTime;
        double fSeconds = double(frameDelta)*0.0000001;

        //Log(TEXT("frameDelta: %f"), fSeconds);

        lastStreamTime = renderStartTime;
#else
        QWORD qwTime = GetQPCTimeMS(clockFreq.QuadPart);
        latestVideoTime = qwTime;

        QWORD frameDelta = qwTime-lastStreamTime;
        float fSeconds = float(frameDelta)*0.001f;

        //Log(TEXT("frameDelta: %llu"), frameDelta);

        lastStreamTime = qwTime;
#endif

        //------------------------------------

        if(bRequestKeyframe && keyframeWait > 0)
        {
            keyframeWait -= int(frameDelta);

            if(keyframeWait <= 0)
            {
                GetVideoEncoder()->RequestKeyframe();
                bRequestKeyframe = false;
            }
        }

        if(!bPushToTalkDown && pushToTalkTimeLeft > 0)
        {
            pushToTalkTimeLeft -= int(frameDelta);
            OSDebugOut(TEXT("time left: %d\r\n"), pushToTalkTimeLeft);
            if(pushToTalkTimeLeft <= 0)
            {
                pushToTalkTimeLeft = 0;
                bPushToTalkOn = false;
            }
        }

        //------------------------------------

        OSEnterMutex(hSceneMutex);

        if(bResizeRenderView)
        {
            GS->ResizeView();
            bResizeRenderView = false;
        }

        //------------------------------------

        if(scene)
        {
            profileIn("scene->Preprocess");
            scene->Preprocess();

            for(UINT i=0; i<globalSources.Num(); i++)
                globalSources[i].source->Preprocess();

            profileOut;

            scene->Tick(float(fSeconds));

            for(UINT i=0; i<globalSources.Num(); i++)
                globalSources[i].source->Tick(float(fSeconds));
        }

        //------------------------------------

        QWORD curBytesSent = network->GetCurrentSentBytes();
        curFramesDropped = network->NumDroppedFrames();
        bool bUpdateBPS = false;

        bpsTime += fSeconds;
        if(bpsTime > 1.0f)
        {
            if(numSecondsWaited < 3)
                ++numSecondsWaited;

            //bytesPerSec = DWORD(curBytesSent - lastBytesSent);
            bytesPerSec = DWORD(curBytesSent - lastBytesSent[0]) / numSecondsWaited;

            if(bpsTime > 2.0)
                bpsTime = 0.0f;
            else
                bpsTime -= 1.0;

            if(numSecondsWaited == 3)
            {
                lastBytesSent[0] = lastBytesSent[1];
                lastBytesSent[1] = lastBytesSent[2];
                lastBytesSent[2] = curBytesSent;
            }
            else
                lastBytesSent[numSecondsWaited] = curBytesSent;

            captureFPS = fpsCounter;
            fpsCounter = 0;

            bUpdateBPS = true;
        }

        fpsCounter++;

        curStrain = network->GetPacketStrain();

        EnableBlending(TRUE);
        BlendFunction(GS_BLEND_SRCALPHA, GS_BLEND_INVSRCALPHA);

        //------------------------------------
        // render the mini render texture

        LoadVertexShader(mainVertexShader);
        LoadPixelShader(mainPixelShader);

        SetRenderTarget(mainRenderTextures[curRenderTarget]);

        Ortho(0.0f, baseSize.x, baseSize.y, 0.0f, -100.0f, 100.0f);
        SetViewport(0, 0, baseSize.x, baseSize.y);

        if(scene)
            scene->Render();

        //------------------------------------

        if(bTransitioning)
        {
            if(!transitionTexture)
            {
                transitionTexture = CreateTexture(baseCX, baseCY, GS_BGRA, NULL, FALSE, TRUE);
                if(transitionTexture)
                {
                    D3D10Texture *d3dTransitionTex = static_cast<D3D10Texture*>(transitionTexture);
                    D3D10Texture *d3dSceneTex = static_cast<D3D10Texture*>(mainRenderTextures[lastRenderTarget]);
                    GetD3D()->CopyResource(d3dTransitionTex->texture, d3dSceneTex->texture);
                }
                else
                    bTransitioning = false;
            }
            else if(transitionAlpha >= 1.0f)
            {
                delete transitionTexture;
                transitionTexture = NULL;

                bTransitioning = false;
            }
        }

        if(bTransitioning)
        {
            EnableBlending(TRUE);
            transitionAlpha += float(fSeconds)*5.0f;
            if(transitionAlpha > 1.0f)
                transitionAlpha = 1.0f;
        }
        else
            EnableBlending(FALSE);

        //------------------------------------
        // render the mini view thingy

        if(bRenderView)
        {
            Vect2 renderFrameSize = Vect2(float(renderFrameWidth), float(renderFrameHeight));

            SetRenderTarget(NULL);

            LoadVertexShader(mainVertexShader);
            LoadPixelShader(mainPixelShader);

            Ortho(0.0f, renderFrameSize.x, renderFrameSize.y, 0.0f, -100.0f, 100.0f);
            SetViewport(0.0f, 0.0f, renderFrameSize.x, renderFrameSize.y);

            if(bTransitioning)
            {
                BlendFunction(GS_BLEND_ONE, GS_BLEND_ZERO);
                if(renderFrameIn1To1Mode)
                    DrawSprite(transitionTexture, 0xFFFFFFFF, 0.0f, 0.0f, outputSize.x, outputSize.y);
                else
                    DrawSprite(transitionTexture, 0xFFFFFFFF, 0.0f, 0.0f, renderFrameSize.x, renderFrameSize.y);
                BlendFunction(GS_BLEND_FACTOR, GS_BLEND_INVFACTOR, transitionAlpha);
            }

            if(renderFrameIn1To1Mode)
                DrawSprite(mainRenderTextures[curRenderTarget], 0xFFFFFFFF, 0.0f, 0.0f, outputSize.x, outputSize.y);
            else
                DrawSprite(mainRenderTextures[curRenderTarget], 0xFFFFFFFF, 0.0f, 0.0f, renderFrameSize.x, renderFrameSize.y);

            Ortho(0.0f, renderFrameSize.x, renderFrameSize.y, 0.0f, -100.0f, 100.0f);

            //draw selections if in edit mode
            if(bEditMode && !bSizeChanging)
            {
                LoadVertexShader(solidVertexShader);
                LoadPixelShader(solidPixelShader);
                solidPixelShader->SetColor(solidPixelShader->GetParameter(0), 0xFFFF0000);

                if(renderFrameIn1To1Mode)
                    Ortho(0.0f, renderFrameSize.x * downscale, renderFrameSize.y * downscale, 0.0f, -100.0f, 100.0f);
                else
                    Ortho(0.0f, baseSize.x, baseSize.y, 0.0f, -100.0f, 100.0f);

                if(scene)
                    scene->RenderSelections();
            }
        }
        else if(bForceRenderViewErase)
        {
            InvalidateRect(hwndRenderFrame, NULL, TRUE);
            UpdateWindow(hwndRenderFrame);
            bForceRenderViewErase = false;
        }

        //------------------------------------
        // actual stream output

        LoadVertexShader(mainVertexShader);
        LoadPixelShader(yuvScalePixelShader);

        Texture *yuvRenderTexture = yuvRenderTextures[curRenderTarget];
        SetRenderTarget(yuvRenderTexture);

        yuvScalePixelShader->SetVector2(hScaleVal, 1.0f/baseSize);

        Ortho(0.0f, outputSize.x, outputSize.y, 0.0f, -100.0f, 100.0f);
        SetViewport(0.0f, 0.0f, outputSize.x, outputSize.y);

        //why am I using scaleSize instead of outputSize for the texture?
        //because outputSize can be trimmed by up to three pixels due to 128-bit alignment.
        //using the scale function with outputSize can cause slightly inaccurate scaled images
        if(bTransitioning)
        {
            BlendFunction(GS_BLEND_ONE, GS_BLEND_ZERO);
            DrawSpriteEx(transitionTexture, 0xFFFFFFFF, 0.0f, 0.0f, scaleSize.x, scaleSize.y, 0.0f, 0.0f, scaleSize.x, scaleSize.y);
            BlendFunction(GS_BLEND_FACTOR, GS_BLEND_INVFACTOR, transitionAlpha);
        }

        DrawSpriteEx(mainRenderTextures[curRenderTarget], 0xFFFFFFFF, 0.0f, 0.0f, outputSize.x, outputSize.y, 0.0f, 0.0f, outputSize.x, outputSize.y);

        //------------------------------------

        if(bRenderView && !copyWait)
            static_cast<D3D10System*>(GS)->swap->Present(0, 0);

        OSLeaveMutex(hSceneMutex);

        //------------------------------------
        // present/upload

        profileIn("video encoding and uploading");

        bool bEncode = true;

        if(copyWait)
        {
            copyWait--;
            bEncode = false;
        }
        else
        {
            //audio sometimes takes a bit to start -- do not start processing frames until audio has started capturing
            if(!bRecievedFirstAudioFrame)
                bEncode = false;
            else if(bFirstFrame)
            {
                firstFrameTime = qwTime;
                bFirstFrame = false;
            }

            if(!bEncode)
            {
                if(curYUVTexture == (NUM_RENDER_BUFFERS-1))
                    curYUVTexture = 0;
                else
                    curYUVTexture++;
            }
        }

        if(bEncode)
        {
            curStreamTime = qwTime-firstFrameTime;

            UINT prevCopyTexture = (curCopyTexture == 0) ? NUM_RENDER_BUFFERS-1 : curCopyTexture-1;

            ID3D10Texture2D *copyTexture = copyTextures[curCopyTexture];
            profileIn("CopyResource");

            if(!bFirst420Encode && bUseThreaded420)
            {
                WaitForMultipleObjects(completeEvents.Num(), completeEvents.Array(), TRUE, INFINITE);
                copyTexture->Unmap(0);
            }

            D3D10Texture *d3dYUV = static_cast<D3D10Texture*>(yuvRenderTextures[curYUVTexture]);
            GetD3D()->CopyResource(copyTexture, d3dYUV->texture);
            profileOut;

            ID3D10Texture2D *prevTexture = copyTextures[prevCopyTexture];

            if(bFirstImage) //ignore the first frame
                bFirstImage = false;
            else
            {
                HRESULT result;
                D3D10_MAPPED_TEXTURE2D map;
                if(SUCCEEDED(result = prevTexture->Map(0, D3D10_MAP_READ, 0, &map)))
                {
                    int prevOutBuffer = (curOutBuffer == 0) ? NUM_OUT_BUFFERS-1 : curOutBuffer-1;
                    int nextOutBuffer = (curOutBuffer == NUM_OUT_BUFFERS-1) ? 0 : curOutBuffer+1;

                    x264_picture_t &prevPicOut = outPics[prevOutBuffer];
                    x264_picture_t &picOut = outPics[curOutBuffer];
                    x264_picture_t &nextPicOut = outPics[nextOutBuffer];

                    if(!bUsing444)
                    {
                        profileIn("conversion to 4:2:0");

                        if(bUseThreaded420)
                        {
                            outTimes[nextOutBuffer] = (DWORD)curStreamTime;

                            for(int i=0; i<numThreads; i++)
                            {
                                convertInfo[i].input     = (LPBYTE)map.pData;
                                convertInfo[i].pitch     = map.RowPitch;
                                convertInfo[i].output[0] = nextPicOut.img.plane[0];
                                convertInfo[i].output[1] = nextPicOut.img.plane[1];
                                convertInfo[i].output[2] = nextPicOut.img.plane[2];
                                SetEvent(convertInfo[i].hSignalConvert);
                            }

                            if(bFirst420Encode)
                                bFirst420Encode = bEncode = false;
                        }
                        else
                        {
                            outTimes[curOutBuffer] = (DWORD)curStreamTime;
                            Convert444to420((LPBYTE)map.pData, outputCX, map.RowPitch, outputCY, 0, outputCY, picOut.img.plane, SSE2Available());
                            prevTexture->Unmap(0);
                        }

                        profileOut;
                    }
                    else
                    {
                        outTimes[curOutBuffer] = (DWORD)curStreamTime;

                        picOut.img.i_stride[0] = map.RowPitch;
                        picOut.img.plane[0]    = (uint8_t*)map.pData;
                    }

                    if(bEncode)
                    {
                        DWORD curFrameTimestamp = outTimes[prevOutBuffer];
                        //Log(TEXT("curFrameTimestamp: %u"), curFrameTimestamp);

                        //------------------------------------

                        FrameProcessInfo frameInfo;
                        frameInfo.firstFrameTime = firstFrameTime;
                        frameInfo.prevTexture = prevTexture;

                        if(bUseCFR)
                        {
                            while(cfrTime < curFrameTimestamp)
                            {
                                DWORD frameTimeAdjust = frameTime;
                                cfrTimeAdjust += fpsTimeNumerator;
                                if(cfrTimeAdjust > fpsTimeDenominator)
                                {
                                    cfrTimeAdjust -= fpsTimeDenominator;
                                    ++frameTimeAdjust;
                                }

                                DWORD halfTime = (frameTimeAdjust+1)/2;

                                x264_picture_t *nextPic = (curFrameTimestamp-cfrTime <= halfTime) ? &picOut : &prevPicOut;
                                //Log(TEXT("cfrTime: %u, time: %u"), cfrTime, curFrameTimestamp);

                                //these lines are just for counting duped frames
                                if(nextPic == lastPic)
                                    ++numTotalDuplicatedFrames;
                                else
                                    lastPic = nextPic;

                                frameInfo.picOut = nextPic;
                                frameInfo.picOut->i_pts = cfrTime;
                                frameInfo.frameTimestamp = cfrTime;
                                ProcessFrame(frameInfo);

                                cfrTime += frameTimeAdjust;

                                //Log(TEXT("cfrTime: %u, chi frame: %u"), cfrTime, (curFrameTimestamp-cfrTime <= halfTime));
                            }
                        }
                        else
                        {
                            picOut.i_pts = curFrameTimestamp;

                            frameInfo.picOut = &picOut;
                            frameInfo.frameTimestamp = curFrameTimestamp;

                            ProcessFrame(frameInfo);
                        }
                    }

                    curOutBuffer = nextOutBuffer;
                }
                else
                {
                    //We have to crash, or we end up deadlocking the thread when the convert threads are never signalled
                    CrashError (TEXT("Texture->Map failed: 0x%08x"), result);
                }
            }

            if(curCopyTexture == (NUM_RENDER_BUFFERS-1))
                curCopyTexture = 0;
            else
                curCopyTexture++;

            if(curYUVTexture == (NUM_RENDER_BUFFERS-1))
                curYUVTexture = 0;
            else
                curYUVTexture++;
        }

        lastRenderTarget = curRenderTarget;

        if(curRenderTarget == (NUM_RENDER_BUFFERS-1))
            curRenderTarget = 0;
        else
            curRenderTarget++;

        if(bUpdateBPS || !CloseDouble(curStrain, lastStrain) || curFramesDropped != lastFramesDropped)
        {
            PostMessage(hwndMain, OBS_UPDATESTATUSBAR, 0, 0);
            lastStrain = curStrain;

            lastFramesDropped = curFramesDropped;
        }

        profileOut;
        profileOut;

        //------------------------------------
        // get audio while sleeping or capturing
        //ReleaseSemaphore(hRequestAudioEvent, 1, NULL);

        //------------------------------------
        // frame sync

#ifdef USE_100NS_TIME
        QWORD renderStopTime = GetQPCTime100NS(clockFreq.QuadPart);
        sleepTargetTime += frameTime100ns;

        if(bWasLaggedFrame = (sleepTargetTime <= renderStopTime))
            numLongFrames++;
        else
            SleepTo(clockFreq.QuadPart, sleepTargetTime);
#else
        DWORD renderStopTime = OSGetTime();
        DWORD totalTime = renderStopTime-renderStartTime;

        if(totalTime > frameTimeAdjust)
            numLongFrames++;
        else if(totalTime < frameTimeAdjust)
            OSSleep(frameTimeAdjust-totalTime);
#endif

        //OSDebugOut(TEXT("Frame adjust time: %d, "), frameTimeAdjust-totalTime);

        numTotalFrames++;
    }

    if(!bUsing444)
    {
        if(bUseThreaded420)
        {
            for(int i=0; i<numThreads; i++)
            {
                if(h420Threads[i])
                {
                    convertInfo[i].bKillThread = true;
                    SetEvent(convertInfo[i].hSignalConvert);

                    OSTerminateThread(h420Threads[i], 10000);
                    h420Threads[i] = NULL;
                }

                if(convertInfo[i].hSignalConvert)
                {
                    CloseHandle(convertInfo[i].hSignalConvert);
                    convertInfo[i].hSignalConvert = NULL;
                }

                if(convertInfo[i].hSignalComplete)
                {
                    CloseHandle(convertInfo[i].hSignalComplete);
                    convertInfo[i].hSignalComplete = NULL;
                }
            }

            if(!bFirst420Encode)
            {
                ID3D10Texture2D *copyTexture = copyTextures[curCopyTexture];
                copyTexture->Unmap(0);
            }
        }

        for(int i=0; i<NUM_OUT_BUFFERS; i++)
            x264_picture_clean(&outPics[i]);
    }

    Free(h420Threads);
    Free(convertInfo);

    Log(TEXT("Total frames rendered: %d, number of frames that lagged: %d (%0.2f%%) (it's okay for some frames to lag)"), numTotalFrames, numLongFrames, (double(numLongFrames)/double(numTotalFrames))*100.0);
    if(bUseCFR)
        Log(TEXT("Total duplicated CFR frames: %d"), numTotalDuplicatedFrames);
}
Example #29
0
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
	HWND hWnd;

   hInst = hInstance; // Store instance handle in our global variable

	hMainWnd	= hWnd	=
		CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);

   if (!hWnd)
   {
      return FALSE;
   }

	int x = 0, y = 416;
	SetWindowPos( hWnd, NULL, x, y, 400, 416, SWP_SHOWWINDOW );

	g_GameTimer.Compute();
	SetTimer( hWnd, TIMER_ID_DEFAULT, 1000, NULL );

#if !defined(__INTERNALSERVER)
	SetTimer( hWnd, TIMER_ID_WANTED, g_uWantedElapse, NULL );
#endif

#ifdef __EVENT0913
	SetTimer( hWnd, TIMER_ID_EVENT0913, 1000, NULL );
#endif	// __EVENT0913
#ifdef __EVENT1206
	SetTimer( hWnd, TIMER_ID_EVENT1206, 1000 * 60, NULL );
#endif	// __EVENT1206

	SetTimer( hWnd, TIMER_ID_EVENT, 1000 * 60, NULL );

	g_MyTrace.Initialize( hWnd, "SquireD", RGB( 0xff, 0xff, 0xff ), RGB( 0x00, 0x00, 0x00 ) );

	CTime time	= CTime::GetCurrentTime();
	g_MyTrace.Add( 0, FALSE, "%s", time.Format( "%Y/%m/%d %H:%M:%S" ) );
	g_MyTrace.AddLine( '\0' );

#ifndef _DEBUG
//	InitEH();
#endif	// _DEBUG

	g_TickCount.Start();

	if( !Script( "CoreServer.ini" ) )
	{
		return FALSE;
	}
	
	if( InitializeNetLib() == FALSE )
		return FALSE;

	if( !g_dpCoreSrvr.StartServer( PN_CORESRVR + 0 ) )
		return FALSE;

	if( !g_DPCacheSrvr.StartServer( PN_CORESRVR + 1 ) )
		return FALSE;

	if( !g_dpLoginSrvr.StartServer( PN_CORESRVR + 2 ) )
		return FALSE;

	if( !g_dpDatabaseClient.ConnectToServer( szDataBaseAddr, PN_DBSRVR_2, FALSE ) )
	{
		Error( "Not TransServer Connect" );
		return FALSE;
	}

	if( !g_PartyMng.CreateWorkers() )
	{
		assert( 0 );
	}

#ifdef __ENVIRONMENT_EFFECT
	if( CEnvironment::GetInstance()->CreateWorkers() == FALSE )
	{
		assert( 0 );
	}
#else // __ENVIRONMENT_EFFECT
	if( !g_Environment.CreateWorkers() )
	{
		assert( 0 );
	}
#endif // __ENVIRONMENT_EFFECT

   ShowWindow(hWnd, nCmdShow);
   UpdateWindow(hWnd);

   return TRUE;
}
Example #30
0
bool GLWindow::create(int width, int height, int bpp, bool fullscreen)
{
    DWORD      dwExStyle;       // Window Extended Style
    DWORD      dwStyle;         // Window Style

    m_isFullscreen = fullscreen; //Store the fullscreen flag

    m_windowRect.left = (long)0; // Set Left Value To 0
    m_windowRect.right = (long)width; // Set Right Value To Requested Width
    m_windowRect.top = (long)0;  // Set Top Value To 0
    m_windowRect.bottom = (long)height;   // Set Bottom Value To Requested Height

    // fill out the window class structure
    m_windowClass.cbSize          = sizeof(WNDCLASSEX);
    m_windowClass.style           = CS_HREDRAW | CS_VREDRAW;
    m_windowClass.lpfnWndProc     = GLWindow::StaticWndProc; //We set our static method as the event handler
    m_windowClass.cbClsExtra      = 0;
    m_windowClass.cbWndExtra      = 0;
    m_windowClass.hInstance       = m_hinstance;
    m_windowClass.hIcon           = LoadIcon(NULL, IDI_APPLICATION);  // default icon
    m_windowClass.hCursor         = LoadCursor(NULL, IDC_ARROW);      // default arrow
    m_windowClass.hbrBackground   = NULL;                             // don't need background
    m_windowClass.lpszMenuName    = NULL;                             // no menu
    m_windowClass.lpszClassName   = "GLClass";
    m_windowClass.hIconSm         = LoadIcon(NULL, IDI_WINLOGO);      // windows logo small icon

    // register the windows class
    if (!RegisterClassEx(&m_windowClass))
    {
        return false;
    }

    if (m_isFullscreen) //If we are fullscreen, we need to change the display mode                             
    {
        DEVMODE dmScreenSettings;                   // device mode
        
        memset(&dmScreenSettings, 0, sizeof(dmScreenSettings));
        dmScreenSettings.dmSize = sizeof(dmScreenSettings); 

        dmScreenSettings.dmPelsWidth = width;         // screen width
        dmScreenSettings.dmPelsHeight = height;           // screen height
        dmScreenSettings.dmBitsPerPel = bpp;             // bits per pixel
        dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;

        if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
        {
            // setting display mode failed, switch to windowed
            MessageBox(NULL, "Display mode failed", NULL, MB_OK);
            m_isFullscreen = false; 
        }
    }

    if (m_isFullscreen)                             // Are We Still In Fullscreen Mode?
    {
        dwExStyle = WS_EX_APPWINDOW;                  // Window Extended Style
        dwStyle = WS_POPUP;                       // Windows Style
        ShowCursor(false);                      // Hide Mouse Pointer
    }
    else
    {
        dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE;   // Window Extended Style
        dwStyle = WS_OVERLAPPEDWINDOW;                    // Windows Style
    }

    AdjustWindowRectEx(&m_windowRect, dwStyle, false, dwExStyle);     // Adjust Window To True Requested Size

    // class registered, so now create our window
    m_hwnd = CreateWindowEx(NULL,                                 // extended style
        "GLClass",                          // class name
        "BOGLGP - Chapter 3 - Pointy Example",      // app name
        dwStyle | WS_CLIPCHILDREN |
        WS_CLIPSIBLINGS,
        0, 0,                               // x,y coordinate
        m_windowRect.right - m_windowRect.left,
        m_windowRect.bottom - m_windowRect.top, // width, height
        NULL,                               // handle to parent
        NULL,                               // handle to menu
        m_hinstance,                          // application instance
        this);                              // we pass a pointer to the GLWindow here

    // check if window creation failed (hwnd would equal NULL)
    if (!m_hwnd)
        return 0;

    m_hdc = GetDC(m_hwnd);

    ShowWindow(m_hwnd, SW_SHOW);          // display the window
    UpdateWindow(m_hwnd);                 // update the window

    m_lastTime = GetTickCount() / 1000.0f; //Initialize the time
    return true;
}