Exemplo n.º 1
1
int APIENTRY
WinMain(
    HINSTANCE hCurrentInst,
    HINSTANCE hPreviousInst,
    LPSTR lpszCmdLine,
    int nCmdShow)
{
    WNDCLASS wndClass;
    HWND hWnd;
    MSG msg;

    /* Define and register a window class */
    wndClass.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW;
    wndClass.lpfnWndProc = WndProc;
    wndClass.cbClsExtra = 0;
    wndClass.cbWndExtra = 0;
    wndClass.hInstance = hCurrentInst;
    wndClass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
    wndClass.hbrBackground = GetStockObject(WHITE_BRUSH);
    wndClass.lpszMenuName = NULL;
    wndClass.lpszClassName = className;
    RegisterClass(&wndClass);

    /* Figure out a default size for the window */
    winWidth = GetSystemMetrics(SM_CYSCREEN) / 3;
    winHeight = GetSystemMetrics(SM_CYSCREEN) / 3;

    /* Create a window of the previously defined class */
    hWnd = CreateWindow(
	className,		/* Window class's name */
	windowName,		/* Title bar text */
	WS_OVERLAPPEDWINDOW |	/* The window's style */
	WS_CLIPCHILDREN |
	WS_CLIPSIBLINGS,
	winX, winY,		/* Position */
	winWidth, winHeight,	/* Size */
	NULL,			/* Parent window's handle */
	NULL,			/* Menu handle */
	hCurrentInst,		/* Instance handle */
	NULL);			/* No additional data */

    /* Map the window to the screen */
    ShowWindow(hWnd, nCmdShow);

    /* Force the window to repaint itself */
    UpdateWindow(hWnd);

    /* Process Messages */
    while (1) {
	/* execute the idle function while there are no messages to process */
	while (idleFunc &&
	       PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) == FALSE)
	{
	    (*idleFunc)();
	}
	if (GetMessage(&msg, NULL, 0, 0) != TRUE) {
	    break;
	}
	TranslateMessage(&msg);
	DispatchMessage(&msg);
    }

    return msg.wParam;
}
Exemplo n.º 2
0
void dumpstuff(WiimoteHandler* wiimote) {
	VRBackendBasics graphics_objects = BeginDirectx(false, "");
	MSG msg;
	int prev_time = timeGetTime();
	int frame_index = 0;

	unsigned int rhod_entity_id = graphics_objects.entity_handler->AddEntity(makerhod(graphics_objects));
	unsigned int wiimote_entity_id = graphics_objects.entity_handler->AddEntity(makewiimote(graphics_objects));
	
	graphics_objects.entity_handler->FinishUpdate();

	Quaternion obj_orient;

	while (TRUE)
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
			TranslateMessage(&msg);
			DispatchMessage(&msg);

			if (msg.message == WM_QUIT) {
				break;
			}
			else if (msg.message == WM_KEYDOWN) {
				graphics_objects.input_handler->HandleKeydown(msg.wParam);

				switch (msg.wParam) {
				case 'F':
					wiimote->RequestCalibrateMotionPlus();
					break;
				case 'C':
					wiimote->SendOutputReport(OutputReportTemplates::request_calibration);
				}
			}
		}

		obj_orient = wiimote->GetCurrentState().orientation;
		// Convert orientation from wiimote coord system to screen coord system
		std::swap(obj_orient.y, obj_orient.z);
		//float tmp = obj_orient.y;
		//obj_orient.y = obj_orient.z;
		//obj_orient.z = tmp;
		obj_orient.x = -obj_orient.x;
		ConstantBufferTyped<TransformationMatrixAndInvTransData>* wiimote_settings = graphics_objects.entity_handler->GetEntityObjectSettings<TransformationMatrixAndInvTransData>(wiimote_entity_id);
		wiimote_settings->SetBothTransformations(
			DirectX::XMMatrixMultiply(
				DirectX::XMMatrixRotationQuaternion(
					DirectX::XMVectorSet(
						obj_orient.x,
						obj_orient.y,
						obj_orient.z,
						obj_orient.w)),
					DirectX::XMMatrixTranslation(0, 0, -4)));
		graphics_objects.entity_handler->FinishUpdate();

		int new_time = timeGetTime();
		int time_delta = new_time - prev_time;
		prev_time = new_time;

		graphics_objects.input_handler->UpdateStates(frame_index);
		graphics_objects.world->UpdateLogic(time_delta);

		graphics_objects.render_pipeline->Render();

		++frame_index;
	}

	// clean up DirectX and COM
	graphics_objects.view_state->Cleanup();
	if (graphics_objects.input_handler->IsOculusActive()) {
		graphics_objects.oculus->Cleanup();
	}

}
Exemplo n.º 3
0
// windows stuff.. 
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
   MSG       msg;
   WNDCLASS  wc;
   HWND      hWnd;
   // set up and register wndclass wc... windows stuff
   wc.style = CS_HREDRAW | CS_VREDRAW;
   wc.lpfnWndProc = (WNDPROC) WinProc;
   wc.cbClsExtra = 0;
   wc.cbWndExtra = sizeof(DWORD);
   wc.hInstance = hInstance;
   wc.hIcon = NULL;
   wc.hCursor = LoadCursor(NULL, IDC_ARROW);
   wc.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);
   wc.lpszMenuName = NULL;
   wc.lpszClassName = "D3D8PROG";

   if (! RegisterClass(&wc))
   {
      // error
      return false;
   }

   //  create window
   hWnd = CreateWindow("D3D8PROG", "Direct3D 8 Program",   // class and caption
            WS_VISIBLE | WS_POPUP,   // style
            0,                       // horizontal start..
            0,                       // vertical start..
            800,                     // horz end
            600,                     // vertical end..
            GetDesktopWindow(),      // parent..
            NULL,                    // menu..
            hInstance,               // instance
            NULL);                   // params..
   
   if (! hWnd)
      return false;

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

   if (init3D(hWnd) != true)   // error checking...
   {   
      cleanup();
      return false;
   }
    
   if (initData() != true)
   {
      cleanup();
      return false;
   }
   
   do   // control loop... life of the program
   {
      if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))   // gets messages when they appear
      {
         TranslateMessage(&msg);   // standard win message stuff..
         DispatchMessage(&msg);
      }
      else   // if no message.. render
      {
         // this is where you do stuff when there aren't messages.. mainly render..
         // might rearrange and doMath and/or other stuff here...
         // depends what would be best in the future.. 
         // for now just render         
         render();
      }
   } while (WM_QUIT != msg.message);

   cleanup();   // clean it up!
   return msg.wParam;   // more win stuff..
}
Exemplo n.º 4
0
int WINAPI get_url_into_file(WCHAR *uri, char *path, int *cancelled)
{
	int success = FALSE;
	*cancelled = FALSE;

	HINTERNET hinet, hdownload;
	char data[BUFSIZE];		/* Flawfinder: ignore */
	unsigned long bytes_read;

#if _DEBUG
	fprintf(logfile,"Opening '%s'\n",path);
	fflush(logfile);
#endif	

	FILE* fp = fopen(path, "wb");		/* Flawfinder: ignore */

	if (!fp)
	{
#if _DEBUG
		fprintf(logfile,"Failed to open '%s'\n",path);
		fflush(logfile);
#endif	
		return success;
	}
	
#if _DEBUG
	fprintf(logfile,"Calling InternetOpen\n");
	fflush(logfile);
#endif	
	// Init wininet subsystem
	hinet = InternetOpen(L"LindenUpdater", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
	if (hinet == NULL)
	{
		return success;
	}

#if _DEBUG
	fprintf(logfile,"Calling InternetOpenUrl: %s\n",wchars_to_utf8chars(uri));
	fflush(logfile);
#endif	
	hdownload = InternetOpenUrl(hinet, uri, NULL, 0, INTERNET_FLAG_NEED_FILE, NULL);
	if (hdownload == NULL)
	{
#if _DEBUG
		DWORD err = GetLastError();
		fprintf(logfile,"InternetOpenUrl Failed: %d\n",err);
		fflush(logfile);
#endif	
		return success;
	}

	DWORD sizeof_total_bytes = sizeof(gTotalBytes);
	HttpQueryInfo(hdownload, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &gTotalBytes, &sizeof_total_bytes, NULL);
	
	DWORD total_bytes = 0;
	success = InternetQueryDataAvailable(hdownload, &total_bytes, 0, 0);
	if (success == FALSE)
	{
#if _DEBUG
		DWORD err = GetLastError();
		fprintf(logfile,"InternetQueryDataAvailable Failed: %d bytes Err:%d\n",total_bytes,err);
		fflush(logfile);
#endif	
 		return success;
	}

	success = FALSE;
	while(!success && !(*cancelled))
	{
		MSG msg;

#if _DEBUG
		fprintf(logfile,"Calling InternetReadFile\n");
		fflush(logfile);
#endif	
		if (!InternetReadFile(hdownload, data, BUFSIZE, &bytes_read))
		{
#if _DEBUG
			fprintf(logfile,"InternetReadFile Failed.\n");
			fflush(logfile);
#endif
			// ...an error occurred
			return FALSE;
		}

#if _DEBUG
		if (!bytes_read)
		{
			fprintf(logfile,"InternetReadFile Read 0 bytes.\n");
			fflush(logfile);
		}
#endif

#if _DEBUG
		fprintf(logfile,"Reading Data, bytes_read = %d\n",bytes_read);
		fflush(logfile);
#endif	
		
		if (bytes_read == 0)
		{
			// If InternetFileRead returns TRUE AND bytes_read == 0
			// we've successfully downloaded the entire file
			wsprintf(gProgress, L"Download complete.");
			success = TRUE;
		}
		else
		{
			// write what we've got, then continue
			fwrite(data, sizeof(char), bytes_read, fp);

			gTotalBytesRead += int(bytes_read);

			if (gTotalBytes != -1)
				wsprintf(gProgress, L"Downloaded: %d%%", 100 * gTotalBytesRead / gTotalBytes);
			else
				wsprintf(gProgress, L"Downloaded: %dK", gTotalBytesRead / 1024);

		}

#if _DEBUG
		fprintf(logfile,"Calling InvalidateRect\n");
		fflush(logfile);
#endif	
		
		// Mark the window as needing redraw (of the whole thing)
		InvalidateRect(gWindow, NULL, TRUE);

		// Do the redraw
#if _DEBUG
		fprintf(logfile,"Calling UpdateWindow\n");
		fflush(logfile);
#endif	
		UpdateWindow(gWindow);

#if _DEBUG
		fprintf(logfile,"Calling PeekMessage\n");
		fflush(logfile);
#endif	
		while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);

			if (msg.message == WM_QUIT)
			{
				// bail out, user cancelled
				*cancelled = TRUE;
			}
		}
	}

#if _DEBUG
	fprintf(logfile,"Calling InternetCloseHandle\n");
	fclose(logfile);
#endif
	
	fclose(fp);
	InternetCloseHandle(hdownload);
	InternetCloseHandle(hinet);

	return success;
}
Exemplo n.º 5
0
Bool
winIsFakeCtrl_L (UINT message, WPARAM wParam, LPARAM lParam)
{
  MSG		msgNext;
  LONG		lTime;
  Bool		fReturn;

  /*
   * Fake Ctrl_L presses will be followed by an Alt_R keypress
   * with the same timestamp as the Ctrl_L press.
   */
  if (message == WM_KEYDOWN
      && wParam == VK_CONTROL
      && (HIWORD (lParam) & KF_EXTENDED) == 0)
    {
      /* Got a Ctrl_L press */

      /* Get time of current message */
      lTime = GetMessageTime ();

      /* Look for fake Ctrl_L preceeding an Alt_R press. */
      fReturn = PeekMessage (&msgNext, NULL,
			     WM_KEYDOWN, WM_KEYDOWN,
			     PM_NOREMOVE);

      /*
       * Try again if the first call fails.
       * NOTE: This usually happens when TweakUI is enabled.
       */
      if (!fReturn)
	{
	  /* Voodoo to make sure that the Alt_R message has posted */
	  Sleep (0);

	  /* Look for fake Ctrl_L preceeding an Alt_R press. */
	  fReturn = PeekMessage (&msgNext, NULL,
				 WM_KEYDOWN, WM_KEYDOWN,
				 PM_NOREMOVE);
	}

      /* Is next press an Alt_R with the same timestamp? */
      if (fReturn && msgNext.wParam == VK_MENU
	  && msgNext.time == lTime
	  && (HIWORD (msgNext.lParam) & KF_EXTENDED))
	{
	  /* 
	   * Next key press is Alt_R with same timestamp as current
	   * Ctrl_L message.  Therefore, this Ctrl_L press is a fake
	   * event, so discard it.
	   */
	  return TRUE;
	}
    }

  /* 
   * Fake Ctrl_L releases will be followed by an Alt_R release
   * with the same timestamp as the Ctrl_L release.
   */
  if ((message == WM_KEYUP || message == WM_SYSKEYUP)
      && wParam == VK_CONTROL
      && (HIWORD (lParam) & KF_EXTENDED) == 0)
    {
      /* Got a Ctrl_L release */

      /* Get time of current message */
      lTime = GetMessageTime ();

      /* Look for fake Ctrl_L release preceeding an Alt_R release. */
      fReturn = PeekMessage (&msgNext, NULL,
			     WM_KEYUP, WM_SYSKEYUP, 
			     PM_NOREMOVE);

      /*
       * Try again if the first call fails.
       * NOTE: This usually happens when TweakUI is enabled.
       */
      if (!fReturn)
	{
	  /* Voodoo to make sure that the Alt_R message has posted */
	  Sleep (0);

	  /* Look for fake Ctrl_L release preceeding an Alt_R release. */
	  fReturn = PeekMessage (&msgNext, NULL,
				 WM_KEYUP, WM_SYSKEYUP, 
				 PM_NOREMOVE);
	}

      /* Is next press an Alt_R with the same timestamp? */
      if (fReturn
	  && (msgNext.message == WM_KEYUP
	      || msgNext.message == WM_SYSKEYUP)
	  && msgNext.wParam == VK_MENU
	  && msgNext.time == lTime
	  && (HIWORD (msgNext.lParam) & KF_EXTENDED))
	{
	  /*
	   * Next key release is Alt_R with same timestamp as current
	   * Ctrl_L message. Therefore, this Ctrl_L release is a fake
	   * event, so discard it.
	   */
	  return TRUE;
	}
    }
  
  /* Not a fake control left press/release */
  return FALSE;
}
int WINAPI WinMain(HINSTANCE	hInstance,			// Instance
	HINSTANCE	hPrevInstance,		// Previous Instance
	LPSTR		lpCmdLine,			// Command Line Parameters
	int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure
	BOOL	done = FALSE;								// Bool Variable To Exit Loop

	eng = Engine();

														// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL, "Would You Like To Run In Fullscreen Mode?", "Start FullScreen?", MB_YESNO | MB_ICONQUESTION) == IDNO)
	{
		eng.SetScreenMode(FALSE);							// Windowed Mode
	}

	// Create Our OpenGL Window
	if (!CreateGLWindow("NeHe's Textures, Lighting & Keyboard Tutorial", 640, 480, 16, eng.GetScreenMode()))
	{
		return 0;									// Quit If Window Was Not Created
	}

	while (!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message == WM_QUIT)				// Have We Received A Quit Message?
			{
				done = TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			// Draw The Scene.  Watch For ESC Key And Quit Messages From DrawGLScene()
			//bool *keys = eng.GetKeys();
			if ((eng.GetActive() && !eng.DrawGLScene()) || keys[VK_ESCAPE])	// Active?  Was There A Quit Received?
			{
				done = TRUE;							// ESC or DrawGLScene Signalled A Quit
			}
			else									// Not Time To Quit, Update Screen
			{
				SwapBuffers(eng.hDC);					// Swap Buffers (Double Buffering)
				if (keys['L'] && !lp)
				{
					lp = TRUE;
					light = !light;
					if (!light)
					{
						glDisable(GL_LIGHTING);
					}
					else
					{
						glEnable(GL_LIGHTING);
					}
				}
				if (!keys['L'])
				{
					lp = FALSE;
				}
				if (keys[VK_PRIOR])
				{
					GLfloat z = eng.GetDepth();
					z -= 0.02f;
					eng.SetDepth(z);
				}
				if (keys[VK_NEXT])
				{
					GLfloat z = eng.GetDepth();
					z += 0.02f;
					eng.SetDepth(z);
				}
				if (keys[VK_UP])
				{
					GLfloat xspeed = eng.GetXSpeed();
					xspeed -= 0.001f;
					eng.SetXSpeed(xspeed);
				}
				if (keys[VK_DOWN])
				{
					GLfloat xspeed = eng.GetXSpeed();
					xspeed += 0.001f;
					eng.SetXSpeed(xspeed);
				}
				if (keys[VK_RIGHT])
				{
					GLfloat yspeed = eng.GetYSpeed();
					yspeed += 0.001f;
					eng.SetYSpeed(yspeed);
				}
				if (keys[VK_LEFT])
				{
					GLfloat yspeed = eng.GetYSpeed();
					yspeed -= 0.001f;
					eng.SetYSpeed(yspeed);
				}

				if (keys[VK_F1])						// Is F1 Being Pressed?
				{
					keys[VK_F1] = FALSE;					// If So Make Key FALSE
					eng.KillGLWindow();						// Kill Our Current Window
					eng.SetScreenMode(!eng.GetScreenMode());				// Toggle Fullscreen / Windowed Mode
															// Recreate Our OpenGL Window
					if (!CreateGLWindow("NeHe's Textures, Lighting & Keyboard Tutorial", 640, 480, 16, eng.GetScreenMode()))
					{
						return 0;						// Quit If Window Was Not Created
					}
				}
			}
		}
	}

	// Shutdown
	eng.KillGLWindow();									// Kill The Window
	return (msg.wParam);							// Exit The Program
}
Exemplo n.º 7
0
INT WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR szCmdLine, int iCmdShow)
{
	WNDCLASSEX winClass ;

	winClass.lpszClassName = "ScreenQuad";
	winClass.cbSize        = sizeof(WNDCLASSEX);
	winClass.style         = CS_HREDRAW | CS_VREDRAW;
	winClass.lpfnWndProc   = MsgProc;
	winClass.hInstance     = hInstance;
	winClass.hIcon	       = NULL ;
	winClass.hIconSm	   = NULL ;
	winClass.hCursor       = LoadCursor(NULL, IDC_ARROW) ; // to avoid busy cursor
	winClass.hbrBackground = NULL ;
	winClass.lpszMenuName  = NULL ;
	winClass.cbClsExtra    = 0;
	winClass.cbWndExtra    = 0;

	RegisterClassEx (&winClass) ;  

	HWND hWnd = CreateWindowEx(NULL,  
		winClass.lpszClassName,		// window class name
		"ScreenQuad",				// window caption
		WS_OVERLAPPEDWINDOW, 		// window style
		32,							// initial x position
		32,							// initial y position
		600,						// initial window width
		600,						// initial window height
		NULL,						// parent window handle
		NULL,						// window menu handle
		hInstance,					// program instance handle
		NULL) ;						// creation parameters

	// Create window failed
	if(hWnd == NULL)
	{
		MessageBoxA(hWnd, "Create Window failed!", "Error", 0) ;
		return -1 ;
	}

	// Initialize Direct3D
	if( SUCCEEDED(InitD3D(hWnd)))
	{ 
		InitVB() ;

		// Show the window
		ShowWindow( hWnd, SW_SHOWDEFAULT );
		UpdateWindow( hWnd );

		// Enter the message loop
		MSG    msg ; 
		ZeroMemory( &msg, sizeof(msg) );
		PeekMessage( &msg, NULL, 0U, 0U, PM_NOREMOVE );

		while (msg.message != WM_QUIT)  
		{
			if( PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE) != 0)
			{
				TranslateMessage (&msg) ;
				DispatchMessage (&msg) ;
			}
			else // Render the game if there is no message to process
			{
				Render() ;
			}
		}
	}

	UnregisterClass(winClass.lpszClassName, hInstance) ;
	return 0;
}
/// <summary>
/// Handle a completed frame from the Kinect Fusion processor.
/// </summary>
/// <returns>S_OK on success, otherwise failure code</returns>
void CKinectFusionExplorer::HandleCompletedFrame()
{
    KinectFusionProcessorFrame const* pFrame = nullptr;

    // Flush any extra WM_FRAMEREADY messages from the queue
    MSG msg;
    while (PeekMessage(&msg, m_hWnd, WM_FRAMEREADY, WM_FRAMEREADY, PM_REMOVE)) {}

    m_processor.LockFrame(&pFrame);

    if (!m_bSavingMesh) // don't render while a mesh is being saved
    {
        if (m_processor.IsVolumeInitialized())
        {
            m_pDrawDepth->Draw(pFrame->m_pDepthRGBX, pFrame->m_cbImageSize);
            m_pDrawReconstruction->Draw(pFrame->m_pReconstructionRGBX, pFrame->m_cbImageSize);
            m_pDrawTrackingResiduals->Draw(pFrame->m_pTrackingDataRGBX, pFrame->m_cbImageSize);
        }

        SetStatusMessage(pFrame->m_statusMessage);
        SetFramesPerSecond(pFrame->m_fFramesPerSecond);
    }

    if (pFrame->m_bIntegrationResumed)
    {
        m_params.m_bPauseIntegration = false;
        CheckDlgButton(m_hWnd, IDC_CHECK_PAUSE_INTEGRATION, BST_UNCHECKED);
        m_processor.SetParams(m_params);
    }
    else if (m_processor.IsCameraPoseFinderAvailable() && !m_params.m_bPauseIntegration)
    {
        m_params.m_bPauseIntegration = true;
        CheckDlgButton(m_hWnd, IDC_CHECK_PAUSE_INTEGRATION, BST_CHECKED);
        m_processor.SetParams(m_params);
    }

    if (!m_bUIUpdated && m_processor.IsVolumeInitialized())
    {
        const int Mebi = 1024 * 1024;

        // We now create both a color and depth volume, doubling the required memory, so we restrict
        // which resolution settings the user can choose when the graphics card is limited in memory.
        if (pFrame->m_deviceMemory <= 1 * Mebi)  // 1GB
        {
            // Disable 640 voxel resolution in all axes - cards with only 1GB cannot handle this
            HWND hButton = GetDlgItem(m_hWnd, IDC_VOXELS_X_640);
            EnableWindow(hButton, FALSE);
            hButton = GetDlgItem(m_hWnd, IDC_VOXELS_Y_640);
            EnableWindow(hButton, FALSE);
            hButton = GetDlgItem(m_hWnd, IDC_VOXELS_Z_640);
            EnableWindow(hButton, FALSE);

            if (Is64BitApp() == FALSE)
            {
                // Also disable 512 voxel resolution in one arbitrary axis on 32bit machines
                hButton = GetDlgItem(m_hWnd, IDC_VOXELS_Y_512);
                EnableWindow(hButton, FALSE);
            }
        }
        else if (pFrame->m_deviceMemory <= 2 * Mebi)  // 2GB
        {
            if (Is64BitApp() == FALSE)
            {
                // Disable 640 voxel resolution in one arbitrary axis on 32bit machines
                HWND hButton = GetDlgItem(m_hWnd, IDC_VOXELS_Y_640);
                EnableWindow(hButton, FALSE);
            }
            // True 64 bit apps seem to be more able to cope with large volume sizes.
        }

        m_bUIUpdated = true;
    }

    m_bColorCaptured = pFrame->m_bColorCaptured;

    m_processor.UnlockFrame();
}
Exemplo n.º 9
0
//程序运行  
int CCApplication::run()  
{  
    //设置注册表PVRFrame隐藏  
    PVRFrameEnableControlWindow(false);  
    //主消息循环  
    MSG msg;  
    LARGE_INTEGER nFreq;  
    LARGE_INTEGER nLast;  
    LARGE_INTEGER nNow;  
//WINDOWS高精度定时器的用法,先获取频率  
QueryPerformanceFrequency(&nFreq);  
//获取当前的计数值,即频率x当前时间  
    QueryPerformanceCounter(&nLast);  
	//initInstance函数为虚函数,由派生类AppDelegate进行了重载。此段代码在调用AppDelegate重载的initInstance函数之后调用applicationDidFinishLaunching函数完成一些初始化处理。  
	//注:AppDelegate重载initInstance函数做了什么我们暂且只先认为它如平时我们WINDOWS基本框架程序一样创建了一个Windows窗口。【伏笔1后面会有讲解】。  
    if (! initInstance() || ! applicationDidFinishLaunching())  
    {  
        return 0;  
    }  
//取得当前使用的OPENGL窗口管理实例对象  
CCEGLView& mainWnd = CCEGLView::sharedOpenGLView();  
//将窗口居中显示  
    mainWnd.centerWindow();  
    ShowWindow(mainWnd.getHWnd(), SW_SHOW);  
//非常熟悉!进入WINDOWS消息循环  
    while (1)  
{  
   //如果没有获取到WINDOWS消息  
        if (! PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))  
        {  
            // 取得当前的计数值,即频率x当前时间  
            QueryPerformanceCounter(&nNow);  
            //m_nAnimationInterval.QuadPart的值 为setAnimationInterval函数进行设置的固定值。此处是为了判断时间流逝了多久,是否应该更新显示设备  
            if (nNow.QuadPart - nLast.QuadPart > m_nAnimationInterval.QuadPart)  
            {  
  //如果时间流逝达到了设定的FPS时间差,则更新计数值。  
                nLast.QuadPart = nNow.QuadPart;  
  //这里是设备渲染场景的函数,【伏笔2后面会有讲解】   
                CCDirector::sharedDirector()->mainLoop();  
            }  
            else  
            {  
  //sleep0秒的意义是让CPU做下时间片切换,防止死循环而使系统其它程序得不到响应。  
                Sleep(0);  
            }  
            continue;  
        }  
   //有消息获取到  
        if (WM_QUIT == msg.message)  
        {  
   // 如果获取的消息是退出则退出循环。  
            break;  
        }  
        // 如果没有定义加速键或者处理完加速键信息  
        if (! m_hAccelTable || ! TranslateAccelerator(msg.hwnd, m_hAccelTable, &msg))  
        {  
   //处理Windows消息  
            TranslateMessage(&msg);  
            DispatchMessage(&msg);  
        }  
    }  
    return (int) msg.wParam;  
}  
Exemplo n.º 10
0
DWORD WINAPI ContentPartnerThreadProc(LPVOID lpParameter)
{
   CONTENT_PARTNER_THREAD_CONTEXT* pThreadCtx = NULL;
   CComPtr<IWMPContentPartnerCallback> spCallback;
   MSG msg = {0};
   HRESULT hr = S_OK;
   BOOL comInitialized = FALSE;

   if(NULL == lpParameter)
   {
      hr = E_INVALIDARG;
      goto cleanup;
   }

   pThreadCtx = static_cast<CONTENT_PARTNER_THREAD_CONTEXT*>(lpParameter);

   if(NULL == pThreadCtx->pIStream)
   {
      hr = E_INVALIDARG;
      goto cleanup;
   }

   hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);

   if(FAILED(hr))
   {
      ATLTRACE2("%x: ContentPartnerThreadProc(type %d): CoInitializeEx failed. %x\n", GetCurrentThreadId(), pThreadCtx->threadType, hr);
      goto cleanup;
   }  

   comInitialized = TRUE;

   // Get a pointer to an IWMPContentPartnerCallback interface.

   hr = CoGetInterfaceAndReleaseStream(
      pThreadCtx->pIStream,
      __uuidof(IWMPContentPartnerCallback),
      reinterpret_cast<LPVOID*>(&spCallback) );

   // The stream was released (even if CoGetInterfaceAndReleaseStream failed). 
   // Set the stream pointer to NULL.
   pThreadCtx->pIStream = NULL;

   if(FAILED(hr))
   {
      ATLTRACE2("%x: ContentPartnerThreadProc(type %d): Failed to get IWMPContentPartnerCallback interface. %x\n", GetCurrentThreadId(), pThreadCtx->threadType, hr);
      goto cleanup;
   }

   if(NULL == spCallback)
   {
      hr = E_UNEXPECTED;
      goto cleanup;
   }

   ATLTRACE2("%x: ContentPartnerThreadProc(type %d): Succeeded in getting IWMPContentPartnerCallback interface.\n", GetCurrentThreadId(), pThreadCtx->threadType);

   // Make sure we have a message queue.
   PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE);

   // Tell the main thread that we are ready to receive messages.
   SetEvent(pThreadCtx->hInitialized);

   hr = ContentPartnerMessageLoop(pThreadCtx, spCallback);

cleanup:

   if(NULL != pThreadCtx)
   {
      // Set this event here, just in case there was a "goto cleanup"
      // before the event was set.
      SetEvent(pThreadCtx->hInitialized);

      // The thread that started this thread allocated a
      // CONTENT_PARTNER_THREAD_CONTEXT structure.
      // We must free that memory here.
   
     if(NULL != pThreadCtx->pIStream)
      {
         // For some reason, CoGetInterfaceAndReleaseStream never got called.
         // So release the stream here.
         pThreadCtx->pIStream->Release();
         pThreadCtx->pIStream = NULL;
      }

      ATLTRACE2("%x: ContentPartnerThreadProc(type %d): Returning %x\n", GetCurrentThreadId(), pThreadCtx->threadType, hr);

      delete pThreadCtx;
      pThreadCtx = NULL;
   }
                   
   if(comInitialized)
   {
      CoUninitialize();
   } 

 
   return hr;
}
Exemplo n.º 11
0
HRESULT ContentPartnerMessageLoop(
   CONTENT_PARTNER_THREAD_CONTEXT* pThreadCtx,
   CComPtr<IWMPContentPartnerCallback> spCallback)
{
   MSG msg = {0};
   HRESULT hr = S_OK;

   if(NULL == pThreadCtx || NULL == spCallback)
   {
      hr = E_UNEXPECTED;
      goto cleanup;
   }

   // Windows message loop
   while(TRUE)
   {
      BOOL ret = 0;

      // Suppose we have several messages (for example, 
      // buy or download messages) in the queue, and then 
      // the user closes Windows Media Player. We would like
      // to let Windows Media Player close without waiting for all
      // those queued messages to be processed.
      //
      // So we use the following strategy.
      //
      // Peek into the message queue to see if there is an exit message.
      // If there is an exit message anywhere in the queue, break out of
      // the message loop even though there might be several
      // messages remaining in the queue.
      
      if( PeekMessage(
             &msg, 
             NULL, 
             pThreadCtx->msgExitMessageLoop, 
             pThreadCtx->msgExitMessageLoop,
             PM_REMOVE) )
      {
         ATLTRACE2("%x: ContentPartnerMessageLoop(type &d): PeekMessage retrieved an exit message.\n", GetCurrentThreadId(), pThreadCtx->threadType);
         goto cleanup;
      }

      ret = GetMessage(&msg, 0, 0, 0);
      if(-1 == ret)
      {
          ATLTRACE2("%x: ContentPartnerMessageLoop(type %d): GetMessage failed (returned -1).\n", GetCurrentThreadId(), pThreadCtx->threadType);
          hr = HRESULT_FROM_WIN32(GetLastError());
          goto cleanup;
      }

      if(pThreadCtx->msgExitMessageLoop == msg.message)
      {
         ATLTRACE2("%x: ContentPartnerMessageLoop(type %d): GetMessage retrieved an exit message.\n", GetCurrentThreadId(), pThreadCtx->threadType);
         break; // Break out of the message loop.
      }

      switch(pThreadCtx->threadType)
      {
      case ThreadTypeDownload:
         hr = HandleMessageForDownloadThread(&msg, pThreadCtx, spCallback);
         break;
      case ThreadTypeBuy:
         hr = HandleMessageForBuyThread(&msg, pThreadCtx, spCallback);
         break;
      case ThreadTypeRefreshLicense:
         hr = HandleMessageForRefreshLicenseThread(&msg, pThreadCtx, spCallback);
         break;
      case ThreadTypeLogin:
         hr = HandleMessageForLoginThread(&msg, pThreadCtx, spCallback);
         break;
      case ThreadTypeSendMessage:
         hr = HandleMessageForSendMessageThread(&msg, pThreadCtx, spCallback);
         break;
      case ThreadTypeUpdateDevice:
         hr = HandleMessageForUpdateDeviceThread(&msg, pThreadCtx, spCallback);
         break;
      case ThreadTypeList:
         hr = HandleMessageForListThread(&msg, pThreadCtx, spCallback);
         break;
      default:
         hr = E_UNEXPECTED;
      } // switch(threadType)
      

      if(FAILED(hr))
      {
         goto cleanup;
      }

   } // while(TRUE)

cleanup:

   if(NULL != pThreadCtx)
   {
      switch(pThreadCtx->threadType)
      {
      case ThreadTypeDownload:
         RemoveMessagesFromDownloadThreadQueue(pThreadCtx);
         break;
      case ThreadTypeBuy:
         RemoveMessagesFromDownloadThreadQueue(pThreadCtx);
         break;
      case ThreadTypeRefreshLicense:
         RemoveMessagesFromDownloadThreadQueue(pThreadCtx);
         break;
      case ThreadTypeLogin:
         RemoveMessagesFromDownloadThreadQueue(pThreadCtx);
         break;
      case ThreadTypeSendMessage:
         RemoveMessagesFromSendMessageThreadQueue(pThreadCtx);
         break;
      case ThreadTypeUpdateDevice:
         RemoveMessagesFromUpdateDeviceThreadQueue(pThreadCtx);
         break;
      case ThreadTypeList:
         RemoveMessagesFromListThreadQueue(pThreadCtx);
         break;
      } // switch(threadType)

      ATLTRACE2("%x: ContentPartnerMessageLoop(type %d): Returning %x.\n", GetCurrentThreadId(), pThreadCtx->threadType, hr);
   }

   return hr;
} // ContentPartnerMessageLoop
Exemplo n.º 12
0
//entry point for any windows program
int WINAPI WinMain(	HINSTANCE hInstance,
					HINSTANCE hPrevInstance,
					LPSTR lpCmdLine,
					int nCmdShow)
{
	//start timer
	TIM->Start();
	D3DApp dapp;
	//gTextureMan = new TextureManager();

	//the handle for the window, filled by a function
	HWND hWnd;
	//this struct holds info for the window  class
	WNDCLASSEX wc;



	//clear out the window class for use
	ZeroMemory(&wc, sizeof(WNDCLASSEX) );

	//fill in the struct with the needed information
	wc.cbSize = sizeof(WNDCLASSEX);
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc = WindowProc;
	wc.hInstance = hInstance;
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH) COLOR_WINDOW;
	wc.lpszClassName = "WindowClass1";

	//register the window class
	RegisterClassEx(&wc);

	// create the window and use the result as the handle
    hWnd = CreateWindowEx(NULL,
                          "WindowClass1",    // name of the window class
                          "DirectXGraphics by Jimmy Roland",   // title of the window
                          WS_OVERLAPPEDWINDOW,    // window style
                          300,    // x-position of the window
                          300,    // y-position of the window
                          SCREEN_WIDTH,    // width of the window
                          SCREEN_HEIGHT,    // height of the window
                          NULL,    // we have no parent window, NULL
                          NULL,    // we aren't using menus, NULL
                          hInstance,    // application handle
                          NULL);    // used with multiple windows, NULL

    // display the window on the screen
    ShowWindow(hWnd, nCmdShow);

	//start Visual Leak Detector
	VLDEnable();

	//create global for DirectInput pointer
	gDInput = new DirectInput(hInstance, hWnd, 
		DISCL_NONEXCLUSIVE |
		DISCL_FOREGROUND,
		DISCL_NONEXCLUSIVE |
		DISCL_FOREGROUND);


	//set up and initialize Direct3D
	dapp.InitD3D(hWnd,hInstance, true);
	// enter the main loop:
	//gD3DDev = *dapp.GetDevice();
    // this struct holds Windows event messages
    MSG msg;


    // Enter the infinite message loop
    while(TRUE)
    {
        // Check to see if any messages are waiting in the queue
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            // translate keystroke messages into the right format
            TranslateMessage(&msg);

            // send the message to the WindowProc function
            DispatchMessage(&msg);
        }

        // If the message is WM_QUIT, exit the while loop
        if(msg.message == WM_QUIT)
            break;

		//DirectInput polling
		gDInput->poll();
		//dapp.SetMousePos(hWnd);

        // Run game code here
		dapp.Update( (float)TIM->GetTimeElapsed() );
    }

	VLDReportLeaks();
	//clean up DirectX and COM
	dapp.CleanDirect3D();

	//delete global
	delete gDInput;

    // return this part of the WM_QUIT message to Windows
    return msg.wParam;
}
Exemplo n.º 13
0
int WINAPI WinMain(  HINSTANCE  hInstance,        // Дескриптор приложения

                     HINSTANCE  hPrevInstance,        // Дескриптор родительского приложения

                     LPSTR    lpCmdLine,        // Параметры командной строки

                     int    nCmdShow )        // Состояние отображения окна

{

    MSG  msg;              // Структура для хранения сообщения Windows

    BOOL  done = FALSE;            // Логическая переменная для выхода из цикла


    // Спрашивает пользователя, какой режим экрана он предпочитает

    if( MessageBox( NULL, "Хотите ли Вы запустить приложение в полноэкранном режиме?",  "Запустить в полноэкранном режиме?", MB_YESNO | MB_ICONQUESTION) == IDNO )

    {

        fullscreen = FALSE;          // Оконный режим

    }


    // Создать наше OpenGL окно

    if( !CreateGLWindow( "NeHe OpenGL окно", 800, 600, 32, fullscreen ) )

    {

        return 0;              // Выйти, если окно не может быть создано

    }


    while( !done )                // Цикл продолжается, пока done не равно true

    {

        if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )    // Есть ли в очереди какое-нибудь сообщение?

        {

            if( msg.message == WM_QUIT )        // Мы поучили сообщение о выходе?

            {

                done = TRUE;          // Если так, done=true

            }

            else              // Если нет, обрабатывает сообщения

            {


                TranslateMessage( &msg );        // Переводим сообщение

                DispatchMessage( &msg );        // Отсылаем сообщение

            }

        }

        else                // Если нет сообщений

        {


            // Прорисовываем сцену.

            if( active )          // Активна ли программа?

            {

                if(keys[VK_ESCAPE])        // Было ли нажата клавиша ESC?

                {

                    done = TRUE;      // ESC говорит об останове выполнения программы

                }

                else            // Не время для выхода, обновим экран.

                {

                    DrawGLScene();        // Рисуем сцену

                    SwapBuffers( hDC );    // Меняем буфер (двойная буферизация)

                }

            }

            if( keys[VK_F1] )          // Была ли нажата F1?

            {

                keys[VK_F1] = FALSE;        // Если так, меняем значение ячейки массива на false

                KillGLWindow();          // Разрушаем текущее окно

                fullscreen = !fullscreen;      // Переключаем режим

                // Пересоздаём наше OpenGL окно

                if( !CreateGLWindow( "NeHe's OpenGL структура", 800, 600, 32, fullscreen ) )

                {

                    return 0;        // Выходим, если это невозможно

                }

            }

        }

    }


    // Shutdown

    KillGLWindow();                // Разрушаем окно

    return ( msg.wParam );              // Выходим из программы

}
Exemplo n.º 14
0
int WINAPI WinMain (HINSTANCE hInstance,
					HINSTANCE legacy,
					LPSTR lpCmdLine,
					int nCmdShow)
{
	__EXPN__ = new ExceptionData_t (20, "ExceptionErrors.txt");
	srand (static_cast<UINT>(time (nullptr)));

	

	try
	{
		WindowClass window (int (SCREEN_WIDTH * 0.98f), int (SCREEN_HEIGHT * 0.9f));
		AllocConsole ();
		FILE* file = nullptr;
		freopen_s (&file, "CONOUT$", "w", stdout);

		Direct3DProcessor d3dProc (&window);
		d3dProc.ApplyBlendState (d3dProc.AddBlendState (true));

		//d3dProc.ApplyRasterizerState (d3dProc.AddRasterizerState (false, false, true));

		//XMMATRIX world = XMMatrixTranslation (0.0f, 0.0f, 0.0f);
		CamInfo_t camInfo = { { BASE_X, BASE_Y, BASE_Z, 1.0f }, {}, 0.01f , 0.0f};
		Direct3DCamera cam (&window,
							camInfo.pos.x, camInfo.pos.y, camInfo.pos.z,
							0.0f, -1.0f, 1.0f,
							0.0, 1.0f, 0.0f,
							FOV, 0.5f);

		XMStoreFloat4(&camInfo.dir, cam.GetDir());

		ConstantBufferIndex_t camBuf = d3dProc.RegisterConstantBuffer (&camInfo,
																	   sizeof (camInfo),
																	   1);
		d3dProc.UpdateConstantBuffer (camBuf);

		MeteoObject meteo ("Data/COSMOMESH", "Data/Fronts", "Data/H", &camInfo.step, 0.01f, &d3dProc, &cam);
		cam.Update ();

		meteo.RunPolygonalBuilding();
		//SetForegroundWindow (window.hwnd ());


		printf("Processing\n");
		d3dProc.ProcessObjects ();


		MSG msg = {};
		bool rotate = true;
		bool wasPressedSpace = false;
		uint64_t ticksOld = 0;
		uint64_t ticksNew = GetTickCount64 ();
		char ticksN = 0;

		printf("Drawing\n");
		
		int hour = 0;
		while (true)
		{
			if (PeekMessage (&msg, nullptr, 0, 0, PM_REMOVE))
			{
				TranslateMessage (&msg);
				DispatchMessage (&msg);

				if (msg.message == WM_QUIT) break;
			}
			// SCENE PROCESSING

			/*if (rotate) meteo.Rotate (0.01f);
			if (GetAsyncKeyState (VK_SPACE) & 0x8000)
			{
				if (!wasPressedSpace)
				{
					rotate = !rotate;
					wasPressedSpace = true;
				}
			}
			else wasPressedSpace = false;*/
			if (GetAsyncKeyState('J') & 0x8000)
			{
				while (GetAsyncKeyState('J'));
				camInfo.noise = 2.0f - camInfo.noise;
			}

			ProcessCam (&cam, &camInfo);

			meteo.PreDraw ();

			cam.Update ();
			cam.StorePos (camInfo.pos);
			d3dProc.UpdateConstantBuffer (camBuf);

			d3dProc.SendCBToGS (camBuf);
			d3dProc.SendCBToPS (camBuf);
			d3dProc.ProcessDrawing (&cam, true);
			d3dProc.Present ();
			if (ticksN >= 10)
			{
				ticksN = 0;
				ticksOld = ticksNew;
				ticksNew = GetTickCount64();

				printf ("%.2f fps %f step noise %s          \r", 10000.0f/(ticksNew - ticksOld), camInfo.step, camInfo.noise > 1.0f ? "ON" : "OFF");

				/*if (10000.0f / (ticksNew - ticksOld) - TARGET_FPS > 10.0f)
					 camInfo.step -= 0.0005f;
				else 
				if (10000.0f / (ticksNew - ticksOld) - TARGET_FPS < -10.0f)
					camInfo.step += 0.0005f;
				if (camInfo.step < 0.0f) camInfo.step = 0.0001f;*/
				
			}
			ticksN++;
			//_getch();
			//break;
		}
		FreeConsole ();
	}
	catch (ExceptionHandler_t& ex)
	{
		_MessageBox ("Exception occurred\nCheck \"ExceptionErrors.txt\"");
		ex.WriteLog (__EXPN__);
		system ("start ExceptionErrors.txt");
	}
	catch (std::exception err)
	{
		_MessageBox ("Exception occurred: %s\n", err.what ());
	}
	catch (...)
	{
		_MessageBox ("Exception occurred\n");
	}

	delete __EXPN__;


	return 0;
}
Exemplo n.º 15
0
/// <summary>
/// Creates the main window and begins processing
/// </summary>
/// <param name="hInstance">handle to the application instance</param>
/// <param name="nCmdShow">whether to display minimized, maximized, or normally</param>
int CDataCollection::Run(HINSTANCE hInstance, int nCmdShow)
{
    MSG       msg = {0};
    WNDCLASS  wc;

    // Dialog custom window class
    ZeroMemory(&wc, sizeof(wc));
    wc.style         = CS_HREDRAW | CS_VREDRAW;
    wc.cbWndExtra    = DLGWINDOWEXTRA;
    wc.hInstance     = hInstance;
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hIcon         = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APP));
    wc.lpfnWndProc   = DefDlgProc;
    wc.lpszClassName = L"DataCollectionAppDlgWndClass";

    if (!RegisterClass(&wc))
    {
        return 0;
    }

    // Create main application window
    HWND hWndApp = CreateDialogParam(
        hInstance,
        MAKEINTRESOURCE(IDD_APP),
        NULL,
        (DLGPROC)CDataCollection::MessageRouter, 
        reinterpret_cast<LPARAM>(this));

    // Show window
    ShowWindow(hWndApp, nCmdShow);

    const int eventCount = 2;
	HANDLE hEvents[eventCount]={m_hNextColorFrameEvent, m_hNextSkeletonEvent};

	
    // Main message loop
    while (WM_QUIT != msg.message)
    {
        

        // Check to see if we have either a message (by passing in QS_ALLINPUT)
        // Or a Kinect event (hEvents)
        // Update() will check for Kinect events individually, in case more than one are signalled
        DWORD dwEvent = MsgWaitForMultipleObjects(eventCount, hEvents, FALSE, INFINITE, QS_ALLINPUT);
	    
        // Check if this is an event we're waiting on and not a timeout or message
        if ((WAIT_OBJECT_0 == dwEvent)||(WAIT_OBJECT_0+1)==dwEvent)
        {
			
            Update();
        }
		
        if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            // If a dialog message will be taken care of by the dialog proc
            if ((hWndApp != NULL) && IsDialogMessage(hWndApp, &msg))
            {
                continue;
            }

            TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
    }

    return static_cast<int>(msg.wParam);
}
Exemplo n.º 16
0
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpszCmdLine, int nCmdShow) {
	wchar_t progname[] = L"CerealBox";


	windata.gameoutput.graphic.width = 1920/2;
	windata.gameoutput.graphic.height = 1080/2;

	windata.running = ootrue;
	windata.gameMemory = (void *) calloc((size_t)gameMemorySize(), 1L);

	oouint audioBufferSize = win32AudioBufferSize();
    windata.gameoutput.audio.buffer = (ooshort *) calloc((size_t)audioBufferSize, 1L);
	oouint audioFramesPerSecond = win32AudioFramesPerSecond();

	WNDCLASSEXW winclass;
	ZeroMemory(&winclass, sizeof(WNDCLASSEXW));

	
	MSG msg;

	winclass.cbSize = sizeof(WNDCLASSEXW);
	winclass.style = CS_DBLCLKS;
	winclass.lpfnWndProc = &winproc;
	winclass.cbClsExtra = 0;
	winclass.cbWndExtra = 0;
	winclass.hInstance = hInst;
	winclass.hIcon = LoadIcon(NULL,IDI_WINLOGO);
	winclass.hCursor = LoadCursor(NULL,IDC_ARROW);
	winclass.lpszClassName = progname;


	if(!RegisterClassExW(&winclass)) {
		return 0;
	}

	oouint startX = 100;
	oouint startY = 100;

	DWORD windowStyle =  WS_SYSMENU|WS_CAPTION|WS_BORDER|WS_OVERLAPPED|WS_VISIBLE|WS_MINIMIZEBOX;

#ifdef OO_FULLSCREEN
	windowStyle = WS_EX_TOPMOST | WS_POPUP;
	win32GetScreenResolution(&windata.gameoutput.graphic.width, &windata.gameoutput.graphic.height);
	startX = 0;
	startY = 0;
#endif
	RECT wr = {0, 0, windata.gameoutput.graphic.width, windata.gameoutput.graphic.height};
	AdjustWindowRect(&wr, windowStyle, FALSE);

	windata.window = CreateWindowW(
		progname,
		progname,
		windowStyle,
		startX,
		startY,
		wr.right - wr.left,
		wr.bottom - wr.top,
		NULL,
		NULL,
		hInst,
		NULL);

	initGraphics(&windata);
	win32AudioInit(windata.window);

	ShowWindow(windata.window,nCmdShow);
	UpdateWindow(windata.window);

	LARGE_INTEGER timeFrequency;
	QueryPerformanceFrequency(&timeFrequency);

	LARGE_INTEGER lastTime;
	ZeroMemory(&lastTime, sizeof(LARGE_INTEGER) );
	LARGE_INTEGER time;
	windata.gameinput.dt = 1.f/60.f;

	windata.windowDC = GetDC(windata.window);

	ooint monitorRefreshHz = 60;
	oofloat frameMs = 1.f / (oofloat)monitorRefreshHz;
	ooint win32RefreshRate = GetDeviceCaps(windata.windowDC, VREFRESH);
	if( win32RefreshRate>1 ) {
		monitorRefreshHz = win32RefreshRate;
		frameMs = 1.f / (oofloat)monitorRefreshHz;
	}

	while( windata.running ) {
		PeekMessage(&msg,NULL,0,0,PM_REMOVE);
		if(msg.message == WM_QUIT) {
			break;
		}


		TranslateMessage(&msg);
		DispatchMessage(&msg);

		win32ProcessMouseEvents(windata.window, &windata);

		QueryPerformanceCounter(&time);
		if( lastTime.QuadPart>0 ) {
			windata.gameinput.dt = (oofloat)(time.QuadPart - lastTime.QuadPart);
			windata.gameinput.dt /= timeFrequency.QuadPart;

			windata.gameoutput.audio.framesToWrite = (oouint)(windata.gameinput.dt*audioFramesPerSecond);
			if(windata.gameoutput.audio.framesToWrite>audioBufferSize) {
				windata.gameoutput.audio.framesToWrite = audioBufferSize;
			}

			advanceGame(windata.gameMemory,&windata.gameinput,&windata.gameoutput);

			win32AudioOutput(windata.gameoutput.audio.buffer, windata.gameoutput.audio.framesToWrite);
			renderGraphics(&windata);
		}
		
		lastTime = time;
		
	}

	ReleaseDC(windata.window, windata.windowDC);

	destroyGraphics(&windata);
	win32AudioDestroy();
	free(windata.gameMemory);
	free(windata.gameoutput.audio.buffer);

	return (msg.wParam);
}
Exemplo n.º 17
0
int SSOThread::Run()
{
	ComInit usingCOM(COINIT_APARTMENTTHREADED|COINIT_DISABLE_OLE1DDE|COINIT_SPEED_OVER_MEMORY);

	HKEY hkey;
	CLSID clsid;
	WCHAR name[MAX_PATH], value[MAX_PATH];

	typedef vector<SIfacePtr<IOleCommandTarget>*> SSOVector;
	SSOVector sso_ptrs;

	if (!RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\ShellServiceObjectDelayLoad"), &hkey)) {
		for(int idx=0; ; ++idx) {
			DWORD name_len = MAX_PATH;
			DWORD value_len = sizeof(value);

			if (RegEnumValueW(hkey, idx, name, &name_len, 0, NULL, (LPBYTE)&value, &value_len))
				break;

			if (!_alive)
				break;

			SIfacePtr<IOleCommandTarget>* sso_ptr = new SIfacePtr<IOleCommandTarget>;

			if (CLSIDFromString(value, &clsid) == NOERROR) {
				if (SUCCEEDED(sso_ptr->CreateInstance(clsid, IID_IOleCommandTarget))) {
					if (SUCCEEDED((*sso_ptr)->Exec(&CGID_ShellServiceObject, OLECMDID_NEW, OLECMDEXECOPT_DODEFAULT, NULL, NULL)))
						sso_ptrs.push_back(sso_ptr);
				}
			}
		}

		RegCloseKey(hkey);
	}

	if (!sso_ptrs.empty()) {
		MSG msg;

		while(_alive) {
			if (MsgWaitForMultipleObjects(1, &_evtFinish, FALSE, INFINITE, QS_ALLINPUT) == WAIT_OBJECT_0+0)
				break;	// _evtFinish has been set.

			while(_alive) {
				if (!PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
					break;

				if (msg.message == WM_QUIT)
					break;

				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}

		 // shutdown all running Shell Service Objects
		for(SSOVector::iterator it=sso_ptrs.begin(); it!=sso_ptrs.end(); ++it) {
			SIfacePtr<IOleCommandTarget>* sso_ptr = *it;
			(*sso_ptr)->Exec(&CGID_ShellServiceObject, OLECMDID_SAVE, OLECMDEXECOPT_DODEFAULT, NULL, NULL);
			delete sso_ptr;
		}
	}

	return 0;
}
Exemplo n.º 18
0
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
{

	MyGyouretuKeisan k;

	MYMATRIX mat;
	float matf[16];
	for (int i=0;i<16;i++) {
		mat.m[i/4][i%4] = rand() %30 + 1;
		matf[i] = mat.m[i/4][i%4];
	}
	float mat_out[16];
	float edayo[16];

	k.getMatrixInverse(matf,4,mat_out);
	k.getMatrixMultiply(4,4,matf,4,4,mat_out, edayo);

	MYMATRIX inv_mat;
	for (int i=0;i<16;i++) {
		inv_mat.m[i/4][i%4] = mat_out[i];
	}
//	MyMatrixMultiply(mat,inv_mat,mat);
	MyMatrixInverse(mat,NULL,mat);

	/*
	float matdayo[12*12];
	float matdayo2[12*12];
	float out_matdayo[12*12];
	for (int i=0;i<144;i++) {
		matdayo[i] = rand() % 30 + 1;
	}
	k.getMatrixInverse(matdayo,12,matdayo2);
	k.getMatrixMultiply(12,12,matdayo,12,12,matdayo2,out_matdayo);
	*/



	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(lpCmdLine);
#ifdef _DEBUG	
	_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#define D3D_DEBUG_INFO
#endif
	setlocale( LC_ALL, "Japanese" );

	if (AnotherInstance()) {
		return 0;
	}

	Input* input = new Input();
	MSG msg = {0};
	try {
	if(FAILED( InitWindow(hInstance, nCmdShow, input))){
		return 0;
	}
	} catch (KTROBO::GameError* err) {
		KTROBO::mylog::writelog(KTROBO::FATAL_ERROR, "init device failure");
		KTROBO::mylog::writelog(err->getErrorCode(),err->getMessage());
	//	MessageBoxA(g_hWnd,err->getMessage(),KTROBO::GameError::getErrorCodeString(err->getErrorCode()),MB_OK);
		delete err;
	
		goto ktrobo_error;
	} catch (...) {
		goto ktrobo_error;
	}
	
	

	game = new KTROBO::Game();
	
	try {
	
		game->Init(g_hWnd);
	} catch (KTROBO::GameError* err) {

		KTROBO::mylog::writelog(KTROBO::FATAL_ERROR, "init device failure");
		KTROBO::mylog::writelog(err->getErrorCode(),err->getMessage());
	//	MessageBoxA(g_hWnd,err->getMessage(),KTROBO::GameError::getErrorCodeString(err->getErrorCode()),MB_OK);
		delete err;
		

		goto ktrobo_error;
	} catch (...) {
		goto ktrobo_error;
	}

	// Main message loop
	//MSG msg = {0};
	try {
		
	
	while( WM_QUIT != msg.message ){
		if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ){
			TranslateMessage( &msg );
			DispatchMessage( &msg );
		}else{
			Sleep(1);
			InputMessageDispatcher::messageMake();
		}
	}
	}catch (KTROBO::GameError& err) {
		KTROBO::mylog::writelog(err.getErrorCode(),err.getMessage());
//		MessageBoxA(g_hWnd,err.getMessage(),KTROBO::GameError::getErrorCodeString(err.getErrorCode()),MB_OK);
	} catch (...) {
//		MessageBoxW(g_hWnd,L"unknown error",L"ERROR",MB_OK);
	}

ktrobo_error:

	ClearMainWindow(hInstance);
	if (input) {
		delete input;
		input = 0;
	}
	if (game) {
		game->Del();
		delete game;
		game = 0;
	}
	KTROBO::CS::instance()->Del();

	return 0;//(int)msg.wParam;
}
Exemplo n.º 19
0
Arquivo: main.cpp Projeto: mxt819/H405
//=============================================================================
//	エントリー関数
//=============================================================================
int APIENTRY WinMain(HINSTANCE _instanceHandle ,HINSTANCE _instanceHandlePrev, LPSTR _cmdLine, int _cmdShow)
{
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

	UNREFERENCED_PARAMETER(_instanceHandlePrev);
	UNREFERENCED_PARAMETER(_cmdLine);

	DWORD execLastTime;
	DWORD LastTimeFPS;
	DWORD currentTime;
	DWORD flameCount;

	WNDCLASSEX wcex =
	{
		sizeof(WNDCLASSEX),
		CS_CLASSDC,
		WndProc,
		0,
		0,
		_instanceHandle,
		NULL,
		LoadCursor(NULL, IDC_ARROW),
		(HBRUSH)(COLOR_WINDOW + 1),
		NULL,
		CLASS_NAME,
		NULL
	};

	HWND windowHandle;
	MSG msg;
	
	//	ウィンドウクラスの登録
	RegisterClassEx(&wcex);

	//	ウィンドウの作成
	windowHandle = CreateWindowEx(0,
								  CLASS_NAME,
								  WINDOW_NAME,
								  WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX & ~WS_THICKFRAME,
								  CW_USEDEFAULT,
								  CW_USEDEFAULT,
								  static_cast<int>(SCREEN_WIDTH + GetSystemMetrics(SM_CXDLGFRAME) * 2),
								  static_cast<int>(SCREEN_HEIGHT + GetSystemMetrics(SM_CXDLGFRAME) * 2 + GetSystemMetrics(SM_CYCAPTION)),
								  NULL,
								  NULL,
								  _instanceHandle,
								  NULL);

	//	フレームカウント初期化
	timeBeginPeriod(1);	//	分解能を設定
	execLastTime = LastTimeFPS = timeGetTime();
	currentTime = flameCount = 0;

	//	ウインドウの表示(初期化処理の後に呼ばないと駄目)
	ShowWindow(windowHandle, _cmdShow);
	UpdateWindow(windowHandle);


#ifndef _DEBUG
	LoadLibraryA("WiiYourself.dll");
#else
	LoadLibraryA("WiiYourself_debug.dll");
#endif



	LPDIRECT3D9 direct3D;	//	Direct3D9用デバイス
	LPDIRECT3DDEVICE9 device;	//	_deviceオブジェクト(描画に必要)
	D3DDISPLAYMODE displayMode;
	D3DPRESENT_PARAMETERS presentParameter;

	//	Direct3Dオブジェクトの作成
	direct3D = Direct3DCreate9(D3D_SDK_VERSION);
	direct3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &displayMode);

	//	デバイスのプレゼンテーションパラメータの設定
	//--------------------------------------------------------------------
	//	ワークをゼロクリア
	ZeroMemory(&presentParameter, sizeof(presentParameter));

	//	バックバッファの数をセット
	presentParameter.BackBufferCount = 1;

	//ゲーム画面サイズ
	presentParameter.BackBufferWidth = static_cast<int>SCREEN_WIDTH;
	presentParameter.BackBufferHeight = static_cast<int>SCREEN_HEIGHT;

	//	バックバッファフォーマットはディスプレイモードに合わせて使う
	presentParameter.BackBufferFormat = displayMode.Format;

	//	映像信号に同期してフリップする
	presentParameter.SwapEffect = D3DSWAPEFFECT_DISCARD;

	//	ウィンドウモード
	presentParameter.Windowed = TRUE;

	//	デプスバッファ(Zバッファ)とステンシルバッファを作成
	presentParameter.EnableAutoDepthStencil = TRUE;

	//	デプスバッファの利用方法
	//	D3DFMT_D16		デプスバッファのみを16bitとして扱う
	//	D3DFMT_D24S8	デプスバッファを24bit ステンシルバッファを8bitとして扱う
	presentParameter.AutoDepthStencilFormat = D3DFMT_D24S8;

	//	ウィンドウモード
	presentParameter.FullScreen_RefreshRateInHz = 0;
	presentParameter.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;
	//--------------------------------------------------------------------

	direct3D->CreateDevice(D3DADAPTER_DEFAULT,
		D3DDEVTYPE_HAL,
		windowHandle,
		D3DCREATE_HARDWARE_VERTEXPROCESSING,
		&presentParameter,
		&device);




	CDebug* debug = new CDebug();
	debug->Init(device);

	CKeyboard* keyboard = new CKeyboard();
	keyboard->Init(_instanceHandle, windowHandle);

	CMouse* mouse = new CMouse();
	mouse->Init(_instanceHandle, windowHandle);

	CWiiController* wiiController = new CWiiController();


	//	メッセージループ
	for (;;)
	{
		if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
		{
			if (msg.message == WM_QUIT)
			{
				//	PostQuitMessage()が呼ばれたらループ終了
				break;
			}
			else
			{
				//	メッセージの翻訳とディスパッチ
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
		}
		else
		{
			currentTime = timeGetTime();
			if ((currentTime - LastTimeFPS) >= 500)
			{
				#ifdef _DEBUG
					countFPS = flameCount * 1000 / (currentTime - LastTimeFPS);
				#endif

				LastTimeFPS = currentTime;
				flameCount = 0;
			}

			if ((currentTime - execLastTime) >= (1000 / 60))
			{
				execLastTime = currentTime ;


				keyboard->Update();
				mouse->Update();
				wiiController->update();


				{
					//	本体
					{
						debug->SetDebug("本体の加速度X [%f]\n", wiiController->getAccelerationX());
						debug->SetDebug("本体の加速度Y [%f]\n", wiiController->getAccelerationY());
						debug->SetDebug("本体の加速度Z [%f]\n", wiiController->getAccelerationZ());

						debug->SetDebug("本体の回転角X [%f]\n", wiiController->getRotX());
						debug->SetDebug("本体の回転角Y [%f]\n", wiiController->getRotY());
						debug->SetDebug("本体の回転角Z [%f]\n", wiiController->getRotZ());

						debug->SetDebug("本体の回転角の変異X [%f]\n", wiiController->getChangeRotX());
						debug->SetDebug("本体の回転角の変異Y [%f]\n", wiiController->getChangeRotY());
						debug->SetDebug("本体の回転角の変異Z [%f]\n", wiiController->getChangeRotZ());

						debug->SetDebug("本体の角速度X [%f]\n", wiiController->getRotSpeedX());
						debug->SetDebug("本体の角速度Y [%f]\n", wiiController->getRotSpeedY());
						debug->SetDebug("本体の角速度Z [%f]\n", wiiController->getRotSpeedZ());
					}

					//	ヌンチャク
					{
						debug->SetDebug("ヌンチャクの加速度X [%f]\n", wiiController->getAccelerationNX());
						debug->SetDebug("ヌンチャクの加速度Y [%f]\n", wiiController->getAccelerationNY());
						debug->SetDebug("ヌンチャクの加速度Z [%f]\n", wiiController->getAccelerationNZ());

						debug->SetDebug("ヌンチャクの回転角X [%f]\n", wiiController->getRotNX());
						debug->SetDebug("ヌンチャクの回転角Y [%f]\n", wiiController->getRotNY());
						debug->SetDebug("ヌンチャクの回転角Z [%f]\n", wiiController->getRotNZ());

						debug->SetDebug("ヌンチャクの位置X [%f]\n", wiiController->getJoystick().x);
						debug->SetDebug("ヌンチャクの位置Y [%f]\n", wiiController->getJoystick().y);
					}

					//	赤外線
					{
						debug->SetDebug("赤外線X [%f]\n", wiiController->getIR().x);
						debug->SetDebug("赤外線Y [%f]\n", wiiController->getIR().y);
					}

					debug->SetDebug("バッテリー残量[%d%]\n", wiiController->battery());

					debug->SetDebug("モーションPlusの接続状態[%d]\n", wiiController->getMotionConnect());

					/*if (wiiController->getTrigger(WC_A))
						wiiController->rumble(true);

					if (wiiController->getTrigger(WC_B))
						wiiController->rumble(false);

					if (wiiController->getTrigger(WC_UP))
						wiiController->rumble((unsigned int)1000);*/

					//	Aボタン
					{
						if (wiiController->getPress(WC_A))
							debug->SetDebug("A [ON]\n");
						else
							debug->SetDebug("A [OFF]\n");
					}

					//	Bボタン
					{
						if (wiiController->getPress(WC_B))
							debug->SetDebug("B [ON]\n");
						else
							debug->SetDebug("B [OFF]\n");
					}

					//	Cボタン
					{
						if (wiiController->getPress(WC_C))
							debug->SetDebug("C [ON]\n");
						else
							debug->SetDebug("C [OFF]\n");
					}

					//	Zボタン
					{
						if (wiiController->getPress(WC_Z))
							debug->SetDebug("Z [ON]\n");
						else
							debug->SetDebug("Z [OFF]\n");
					}

					//	↑ボタン
					{
						if (wiiController->getPress(WC_UP))
							debug->SetDebug("UP [ON]\n");
						else
							debug->SetDebug("UP [OFF]\n");
					}

					//	↓ボタン
					{
						if (wiiController->getPress(WC_DOWN))
							debug->SetDebug("DOWN [ON]\n");
						else
							debug->SetDebug("DOWN [OFF]\n");
					}

					//	←ボタン
					{
						if (wiiController->getPress(WC_LEFT))
							debug->SetDebug("LEFT [ON]\n");
						else
							debug->SetDebug("LEFT [OFF]\n");
					}

					//	→ボタン
					{
						if (wiiController->getPress(WC_RIGHT))
							debug->SetDebug("RIGHT [ON]\n");
						else
							debug->SetDebug("RIGHT [OFF]\n");
					}

					//	-ボタン
					{
						if (wiiController->getPress(WC_MINUS))
							debug->SetDebug("MINUS [ON]\n");
						else
							debug->SetDebug("MINUS [OFF]\n");

						if(wiiController->getTrigger(WC_MINUS))
							wiiController->rotSpeedCalibration();
					}

					//	+ボタン
					{
						if (wiiController->getPress(WC_PLUS))
							debug->SetDebug("PLUS [ON]\n");
						else
							debug->SetDebug("PLUS [OFF]\n");

						if(wiiController->getTrigger(WC_PLUS))
							wiiController->rotReset();
					}

					//	1ボタン
					{
						if (wiiController->getPress(WC_ONE))
							debug->SetDebug("ONE [ON]\n");
						else
							debug->SetDebug("ONE [OFF]\n");
					}

					//	2ボタン
					{
						if (wiiController->getPress(WC_TWO))
							debug->SetDebug("TWO [ON]\n");
						else
							debug->SetDebug("TWO [OFF]\n");
					}

					//	HOMEボタン
					{
						if (wiiController->getPress(WC_HOME))
							debug->SetDebug("HOME [ON]\n");
						else
							debug->SetDebug("HOME [OFF]\n");
					}
				}

				//	バックバッファ&Zバッファのクリア
				device->Clear(0,
					NULL,
					(D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER),
					D3DCOLOR_RGBA(255, 255, 255, 255),
					1.0f,
					0);

				//	Direct3Dによる描画の開始
				if (SUCCEEDED(device->BeginScene()))
				{
					CDebug::Draw();

					//	Direct3Dによる描画の終了
					device->EndScene();
				}

				//	バックバッファとフロントバッファの入れ替える
				device->Present(NULL, NULL, NULL, NULL);

				flameCount++;
			}
		}
	}

	SAFE_DELETE(wiiController);
	SAFE_DELETE(keyboard);
	SAFE_DELETE(mouse);
	SAFE_DELETE(debug);

	//	ウィンドウクラスの登録を解除
	UnregisterClass(CLASS_NAME, wcex.hInstance);

	timeEndPeriod(1);	//	分解能を戻す

	return static_cast<int>(msg.wParam);
}
Exemplo n.º 20
0
static DWORD WINAPI DecodeThread( LPVOID ) {
	MSG msg;
	PeekMessage( &msg, NULL, 0, 0, PM_NOREMOVE );
	bool eof = false;
	while ( true ) {
		bool quit = false;
		while ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) {
			if ( msg.message == WM_QUIT ) {
				quit = true;
			} else if ( msg.message == WM_OPENMPT_SEEK ) {
				double pos_seconds = self->mod->set_position_seconds( msg.lParam * 0.001 );
				self->decode_position_frames = (std::int64_t)( pos_seconds * (double)self->samplerate);
				eof = false;
				inmod.outMod->Flush( (int)( pos_seconds * 1000.0 ) );
			}
		}
		if ( quit ) {
			break;
		}
		if ( eof ) {
			inmod.outMod->CanWrite(); // update output plugin state
			if ( !inmod.outMod->IsPlaying() ) {
				PostMessage( inmod.hMainWindow, WM_WA_MPEG_EOF, 0, 0 );
				return 0;
			}
			Sleep( 10 );
		} else {
			bool dsp_active = inmod.dsp_isactive() ? true : false;
			if ( inmod.outMod->CanWrite() >= (int)( WINAMP_BUFFER_SIZE_FRAMES * self->channels * sizeof( signed short ) ) * ( dsp_active ? WINAMP_DSP_HEADROOM_FACTOR : 1 ) ) {
				int frames = 0;
				switch ( self->channels ) {
				case 1:
					frames = self->mod->read( self->samplerate, WINAMP_BUFFER_SIZE_FRAMES, (&(self->buffer[0]))+0*WINAMP_BUFFER_SIZE_FRAMES );
					for ( int frame = 0; frame < frames; frame++ ) {
						self->interleaved_buffer[frame*1+0] = self->buffer[0*WINAMP_BUFFER_SIZE_FRAMES+frame];
					}
					break;
				case 2:
					frames = self->mod->read( self->samplerate, WINAMP_BUFFER_SIZE_FRAMES, (&(self->buffer[0]))+0*WINAMP_BUFFER_SIZE_FRAMES, (&(self->buffer[0]))+1*WINAMP_BUFFER_SIZE_FRAMES );
					for ( int frame = 0; frame < frames; frame++ ) {
						self->interleaved_buffer[frame*2+0] = self->buffer[0*WINAMP_BUFFER_SIZE_FRAMES+frame];
						self->interleaved_buffer[frame*2+1] = self->buffer[1*WINAMP_BUFFER_SIZE_FRAMES+frame];
					}
					break;
				case 4:
					frames = self->mod->read( self->samplerate, WINAMP_BUFFER_SIZE_FRAMES, (&(self->buffer[0]))+0*WINAMP_BUFFER_SIZE_FRAMES, (&(self->buffer[0]))+1*WINAMP_BUFFER_SIZE_FRAMES, (&(self->buffer[0]))+2*WINAMP_BUFFER_SIZE_FRAMES, (&(self->buffer[0]))+3*WINAMP_BUFFER_SIZE_FRAMES );
					for ( int frame = 0; frame < frames; frame++ ) {
						self->interleaved_buffer[frame*4+0] = self->buffer[0*WINAMP_BUFFER_SIZE_FRAMES+frame];
						self->interleaved_buffer[frame*4+1] = self->buffer[1*WINAMP_BUFFER_SIZE_FRAMES+frame];
						self->interleaved_buffer[frame*4+2] = self->buffer[2*WINAMP_BUFFER_SIZE_FRAMES+frame];
						self->interleaved_buffer[frame*4+3] = self->buffer[3*WINAMP_BUFFER_SIZE_FRAMES+frame];
					}
					break;
				}
				if ( frames == 0 ) {
					eof = true;
				} else {
					self->decode_position_frames += frames;
					std::int64_t decode_pos_ms = (self->decode_position_frames * 1000 / self->samplerate );
					inmod.SAAddPCMData( &( self->interleaved_buffer[0] ), self->channels, BPS, (int)decode_pos_ms );
					inmod.VSAAddPCMData( &( self->interleaved_buffer[0] ), self->channels, BPS, (int)decode_pos_ms );
					if ( dsp_active ) {
						frames = inmod.dsp_dosamples( &( self->interleaved_buffer[0] ), frames, BPS, self->channels, self->samplerate );
					}
					int bytes = frames * self->channels * sizeof( signed short );
					inmod.outMod->Write( (char*)&( self->interleaved_buffer[0] ), bytes );
				}
			} else {
				Sleep( 10 );
			}
		}
	}
	return 0;
}
Exemplo n.º 21
0
/**
 * Program start point, build the windows GUI, initialise the emulator.
 * Enter the program main loop, and tidy up when finished.
 */
int WINAPI WinMain (HINSTANCE hThisInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR lpszArgument,
                    int nFunsterStil)

{
        static const char szClassName[] = "WindowsApp";
        MSG messages = {0};     /**< Here messages to the application are saved */
        WNDCLASSEX wincl;       /**< Data structure for the windowclass */

        hinstance=hThisInstance;

        /* The Window structure */
        wincl.hInstance = hThisInstance;
        wincl.lpszClassName = szClassName;
        wincl.lpfnWndProc = WindowProcedure;      /* This function is called by windows */
        wincl.style = CS_DBLCLKS;                 /* Catch double-clicks */
        wincl.cbSize = sizeof (WNDCLASSEX);

        /* Use custom icon and default mouse-pointer */
        wincl.hIcon = LoadIcon(hThisInstance, "allegro_icon");
        wincl.hIconSm = LoadIcon(hThisInstance, "allegro_icon");
        wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
        wincl.lpszMenuName = NULL;                 /* No menu */
        wincl.cbClsExtra = 0;                      /* No extra bytes after the window class */
        wincl.cbWndExtra = 0;                      /* structure or the window instance */
        /* Use Windows's default color as the background of the window */
        wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;

        /* Register the window class, and if it fails quit the program */
        if (!RegisterClassEx (&wincl))
           return 0;

        /* Load Menu from resources file */
        menu=LoadMenu(hThisInstance,TEXT("MainMenu"));

        /* Add in CDROM links to the settings menu dynamically */
        initmenu();

        /* The class is registered, let's create the program*/
        ghwnd = CreateWindowEx (
           0,                   /* Extended possibilites for variation */
           szClassName,         /* Classname */
           "RPCEmu v" VERSION,      /* Title Text */
           WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX, /* overlapped window with no sizing frame */
           CW_USEDEFAULT,       /* Windows decides the position */
           CW_USEDEFAULT,       /* where the window ends up on the screen */
           640 + (GetSystemMetrics(SM_CXFIXEDFRAME) * 2), /* The window width */
           480 + (GetSystemMetrics(SM_CYFIXEDFRAME) * 2) + GetSystemMetrics(SM_CYMENU) + GetSystemMetrics(SM_CYCAPTION), /* and height in pixels */
           HWND_DESKTOP,        /* The window is a child-window to desktop */
           menu,                /* Menu handle */
           hThisInstance,       /* Program Instance handler */
           NULL                 /* No Window Creation data */
           );

        /* Make the window visible on the screen */
        ShowWindow (ghwnd, nFunsterStil);
        win_set_window(ghwnd);

        allegro_init();     /* allegro */

	/* Allegro does not appear to read the window position until it
	   receives a window move message. This results in the mousehack
	   pointer being offset incorrectly until the window is moved.

	   To workaround this issue, we generate a window move message to the
	   window's current position.
	 */
	{
		WINDOWINFO wi;

		GetWindowInfo(ghwnd, &wi);
		PostMessage(ghwnd, WM_MOVE, 0, MAKELPARAM(wi.rcClient.left, wi.rcClient.top));
	}

        /* Initialise the emulation and read the config file */
        if (startrpcemu())
           return -1;

        /* Initialise the podules */
        opendlls();

        /* Based on the contents of config file, dynamically update the Windows GUI items */
        if (config.cdromtype > 2) {
                WindowProcedure(ghwnd, WM_COMMAND, IDM_CDROM_DISABLED + config.cdromtype, 0);
        }
        CheckMenuItem(menu, IDM_CDROM_DISABLED + config.cdromtype, MF_CHECKED);

        CheckMenuItem(menu, IDM_MOUSE_TWOBUTTON,
                      config.mousetwobutton ? MF_CHECKED : MF_UNCHECKED);
        CheckMenuItem(menu, IDM_CPUIDLE,
                      config.cpu_idle ? MF_CHECKED : MF_UNCHECKED);
        
        if (config.mousehackon) {
                CheckMenuItem(menu, IDM_MOUSE_FOL, MF_CHECKED);
        } else {
                CheckMenuItem(menu, IDM_MOUSE_CAP, MF_CHECKED);
        }

        /* Return the mouse clipping to normal on program exit */
        atexit(releasemousecapture);

//        SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
        install_int_ex(vblupdate, BPS_TO_TIMER(config.refresh));
        drawscre=0;

        /* Program main loop */
        while (!quited)
        {
                /* Execute the emulation */
                execrpcemu();

                /* Update title with mips speed */
                if (updatemips)
                {
                        char title[128];

                        if (mousehack) {
                               sprintf(title, "RPCEmu v" VERSION " - MIPS: %.1f, AVG: %.1f",
                                       perf.mips, perf.mips_total / perf.mips_count);
                        } else {
                               sprintf(title, "RPCEmu v" VERSION " - MIPS: %.1f, AVG: %.1f - %s",
                                       perf.mips, perf.mips_total / perf.mips_count,
                                       (mousecapture) ?
                                           "Press CTRL-END to release mouse" :
                                           "Click to capture mouse");
                        }
                        SetWindowText(ghwnd, title);
                        updatemips=0;
                }

		if (handle_sigio) {
			handle_sigio = 0;
			sig_io(1);
		}

                /* Exit full screen? */
                if ((key[KEY_LCONTROL] || key[KEY_RCONTROL]) && key[KEY_END] && fullscreen)
                {
                        togglefullscreen(0);
                        mousecapture=0;
                }

                /* Release mouse from mouse capture mode? */
                if ((key[KEY_LCONTROL] || key[KEY_RCONTROL]) && key[KEY_END] && mousecapture && !config.mousehackon)
                {
                        ClipCursor(&oldclip);
                        mousecapture=0;
                        updatemips=1;
                }

                /* Handle Windows events */
                if (PeekMessage(&messages,NULL,0,0,PM_REMOVE))
                {
                        if (messages.message==WM_QUIT)
                        {
                                quited=1;
                        }
                        /* Translate virtual-key messages into character messages */
                        TranslateMessage(&messages);
                        /* Send message to WindowProcedure */
                        DispatchMessage(&messages);
                }
        }

        /* Program has exited. Tidy up */
        endrpcemu();
        
        /* The program return-value is 0 - The value that PostQuitMessage() gave */
        return messages.wParam;
}
Exemplo n.º 22
0
/* need to add extended codes */
int
text_getch(TW *tw)
{
    MSG msg;
    int ch;
    text_to_cursor(tw);
    tw->bGetCh = TRUE;
    if (tw->bFocus) {
        SetCaretPos(tw->CursorPos.x*tw->CharSize.x - tw->ScrollPos.x,
            tw->CursorPos.y*tw->CharSize.y + tw->CharAscent
            - tw->CaretHeight - tw->ScrollPos.y);
        ShowCaret(tw->hwnd);
    }

#ifdef GS_NO_UTF8
    while (PeekMessage(&msg, (HWND)NULL, 0, 0, PM_NOREMOVE)) {
        if (GetMessage(&msg, (HWND)NULL, 0, 0)) {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }
#else
    while (PeekMessageW(&msg, (HWND)NULL, 0, 0, PM_NOREMOVE)) {
        if (GetMessageW(&msg, (HWND)NULL, 0, 0)) {
            TranslateMessage(&msg);
            DispatchMessageW(&msg);
        }
    }
#endif

    if (tw->quitnow)
       return EOF;	/* window closed */

    while (!text_kbhit(tw)) {
        if (!tw->quitnow) {
#ifdef GS_NO_UTF8
            if (GetMessage(&msg, (HWND)NULL, 0, 0)) {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
#else
            if (GetMessageW(&msg, (HWND)NULL, 0, 0)) {
                TranslateMessage(&msg);
                DispatchMessageW(&msg);
            }
#endif
        }
        else
           return EOF;	/* window closed */
    }

    ch = *tw->KeyBufOut++;
    if (ch=='\r')
        ch = '\n';
    if (tw->KeyBufOut - tw->KeyBuf >= tw->KeyBufSize)
        tw->KeyBufOut = tw->KeyBuf;		/* wrap around */
    if (tw->bFocus)
        HideCaret(tw->hwnd);
    tw->bGetCh = FALSE;
    return ch;
}
Exemplo n.º 23
0
void CExtMiniDockFrameWnd::_ResizingStart(
	UINT nHitTest,
	const CPoint & point
	)
{
#ifdef _USRDLL
	// If this is a DLL, need to set up MFC state
	AFX_MANAGE_STATE(AfxGetStaticModuleState());
#endif

	ASSERT( m_nResizingMode == HTNOWHERE );
	ASSERT( IsWindowVisible() );

	CExtPopupMenuWnd::CancelMenuTracking();
	CWnd::CancelToolTips();

CExtControlBar * pExtBar = GetControlBarExt();
	ASSERT_VALID( pExtBar );
	if( !pExtBar->_IsShowContentWhenDragging()
		&&	pExtBar->IsFixedMode()
		)
	{
		m_nResizingMode = HTNOWHERE;
		pExtBar->m_pDockContext->StartResize(nHitTest, point);
		return;
	}

	switch( nHitTest )
	{
	case HTLEFT:
	case HTRIGHT:
	case HTTOP:
	case HTTOPLEFT:
	case HTTOPRIGHT:
	case HTBOTTOM:
	case HTBOTTOMLEFT:
	case HTBOTTOMRIGHT:
		m_nResizingMode = nHitTest;
	break;
	default:
		return;
	} // switch( nHitTest )

#ifdef _DEBUG
int nPos = 1;
CControlBar * pDebugDummyBar = NULL;
	while(
		pDebugDummyBar == NULL
		&& nPos < m_wndDockBar.m_arrBars.GetSize()
		)
		pDebugDummyBar =
			reinterpret_cast<CExtDockBar&>
				(m_wndDockBar).
					GetDockedControlBar(nPos++);
	ASSERT(pDebugDummyBar != NULL);
	ASSERT_KINDOF(CExtControlBar, pDebugDummyBar);
	ASSERT(pDebugDummyBar->m_pDockContext != NULL);
	// CBRS_SIZE_DYNAMIC toolbars cannot have the CBRS_FLOAT_MULTI style
	ASSERT((m_wndDockBar.m_dwStyle & CBRS_FLOAT_MULTI) == 0);
#endif // _DEBUG
	
	ASSERT( pExtBar == pDebugDummyBar );
	ASSERT(pExtBar->m_pDockContext != NULL);

	if( !pExtBar->IsFixedMode() )
		ModifyStyle( __REMOVED_NONFIXMODE_STYLES, 0 );
	BringWindowToTop();
	CExtMouseCaptureSink::SetCapture( GetSafeHwnd() );
	GetWindowRect( &m_rcWndResizingStart );

	while( m_nResizingMode != HTNOWHERE )
	{
		::WaitMessage();
		MSG msg;
		// Process all the messages in the message queue
		while( PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) )
		{
			bool bStop = false;
			switch( msg.message )
			{
			case WM_ACTIVATEAPP:
			case WM_COMMAND:
				bStop = true;
			break;
			default:
				if(	WM_KEYFIRST <= msg.message
					&& msg.message <= WM_KEYLAST
					)
				bStop = true;
			break;
			} // switch( msg.message )
			if( (!bStop) &&
				CExtMouseCaptureSink::GetCapture() != GetSafeHwnd()
				)
				bStop = true;
			if( bStop )
			{
				_ResizingEnd();
				return;
			}
			if( !AfxGetApp()->PumpMessage() )
			{
				PostQuitMessage(0);
				return; // Signal WM_QUIT received
			} // if( !AfxGetApp()->PumpMessage() )
		} // while( PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE) )
		
		if( CExtControlBar::g_bEnableOnIdleCalls )
		{
			LONG lIdle = 0;
			while( AfxGetApp()->OnIdle(lIdle++) );
		}
	} // while( m_nResizingMode != HTNOWHERE )
}
Exemplo n.º 24
0
bool wxGUIEventLoop::YieldFor(long eventsToProcess)
{
    // set the flag and don't forget to reset it before returning
    m_isInsideYield = true;
    m_eventsToProcessInsideYield = eventsToProcess;

    wxON_BLOCK_EXIT_SET(m_isInsideYield, false);

#if wxUSE_LOG
    // disable log flushing from here because a call to wxYield() shouldn't
    // normally result in message boxes popping up &c
    wxLog::Suspend();

    // ensure the logs will be flashed again when we exit
    wxON_BLOCK_EXIT0(wxLog::Resume);
#endif // wxUSE_LOG

    // we don't want to process WM_QUIT from here - it should be processed in
    // the main event loop in order to stop it
    MSG msg;
    int nPaintsReceived = 0;
    while ( PeekMessage(&msg, (HWND)0, 0, 0, PM_NOREMOVE) &&
            msg.message != WM_QUIT )
    {
#if wxUSE_THREADS
        wxMutexGuiLeaveOrEnter();
#endif // wxUSE_THREADS

        if (msg.message == WM_PAINT)
        {
            // NOTE: WM_PAINTs are categorized as wxEVT_CATEGORY_UI
            if ((eventsToProcess & wxEVT_CATEGORY_UI) == 0)
            {
                // this msg is not going to be dispatched...
                // however WM_PAINT is special: until there are damaged
                // windows, Windows will keep sending it forever!
                if (nPaintsReceived > 10)
                {
                    // we got 10 WM_PAINT consecutive messages...
                    // we must have reached the tail of the message queue:
                    // we're now getting _only_ WM_PAINT events and this will
                    // continue forever (since we don't dispatch them
                    // because of the user-specified eventsToProcess mask)...
                    // break out of this loop!
                    break;
                }
                else
                    nPaintsReceived++;
            }
            //else: we're going to dispatch it below,
            //      so we don't need to take any special action
        }
        else
        {
            // reset the counter of consecutive WM_PAINT messages received:
            nPaintsReceived = 0;
        }

        // choose a wxEventCategory for this Windows message
        wxEventCategory cat;
        switch (msg.message)
        {
#if !defined(__WXWINCE__)
            case WM_NCMOUSEMOVE:

            case WM_NCLBUTTONDOWN:
            case WM_NCLBUTTONUP:
            case WM_NCLBUTTONDBLCLK:
            case WM_NCRBUTTONDOWN:
            case WM_NCRBUTTONUP:
            case WM_NCRBUTTONDBLCLK:
            case WM_NCMBUTTONDOWN:
            case WM_NCMBUTTONUP:
            case WM_NCMBUTTONDBLCLK:
#endif

            case WM_KEYDOWN:
            case WM_KEYUP:
            case WM_CHAR:
            case WM_DEADCHAR:
            case WM_SYSKEYDOWN:
            case WM_SYSKEYUP:
            case WM_SYSCHAR:
            case WM_SYSDEADCHAR:
#ifdef WM_UNICHAR
            case WM_UNICHAR:
#endif
            case WM_HOTKEY:
            case WM_IME_STARTCOMPOSITION:
            case WM_IME_ENDCOMPOSITION:
            case WM_IME_COMPOSITION:
            case WM_COMMAND:
            case WM_SYSCOMMAND:

            case WM_IME_SETCONTEXT:
            case WM_IME_NOTIFY:
            case WM_IME_CONTROL:
            case WM_IME_COMPOSITIONFULL:
            case WM_IME_SELECT:
            case WM_IME_CHAR:
            case WM_IME_KEYDOWN:
            case WM_IME_KEYUP:

#if !defined(__WXWINCE__)
            case WM_MOUSEHOVER:
            case WM_MOUSELEAVE:
#endif
#ifdef WM_NCMOUSELEAVE
            case WM_NCMOUSELEAVE:
#endif

            case WM_CUT:
            case WM_COPY:
            case WM_PASTE:
            case WM_CLEAR:
            case WM_UNDO:

            case WM_MOUSEMOVE:
            case WM_LBUTTONDOWN:
            case WM_LBUTTONUP:
            case WM_LBUTTONDBLCLK:
            case WM_RBUTTONDOWN:
            case WM_RBUTTONUP:
            case WM_RBUTTONDBLCLK:
            case WM_MBUTTONDOWN:
            case WM_MBUTTONUP:
            case WM_MBUTTONDBLCLK:
            case WM_MOUSEWHEEL:
                cat = wxEVT_CATEGORY_USER_INPUT;
                break;

            case WM_TIMER:
                cat = wxEVT_CATEGORY_TIMER;
                break;

            default:
                if (msg.message < WM_USER)
                {
                    // 0;WM_USER-1 is the range of message IDs reserved for use
                    // by the system.
                    // there are too many of these types of messages to handle
                    // them in this switch
                    cat = wxEVT_CATEGORY_UI;
                }
                else
                    cat = wxEVT_CATEGORY_UNKNOWN;
        }

        // should we process this event now?
        if (cat & eventsToProcess)
        {
            if ( !wxTheApp->Dispatch() )
                break;
        }
        else
        {
            // remove the message and store it
            ::GetMessage(&msg, NULL, 0, 0);
            m_arrMSG.Add(msg);
        }
    }

    // if there are pending events, we must process them.
    if (wxTheApp)
        wxTheApp->ProcessPendingEvents();

    // put back unprocessed events in the queue
    DWORD id = GetCurrentThreadId();
    for (size_t i=0; i<m_arrMSG.GetCount(); i++)
    {
        PostThreadMessage(id, m_arrMSG[i].message,
                          m_arrMSG[i].wParam, m_arrMSG[i].lParam);
    }

    m_arrMSG.Clear();

    return true;
}
Exemplo n.º 25
0
int Window::Launch()
{
	WNDCLASS wc;
	ZeroMemory(&wc, sizeof(wc));
	wc.cbClsExtra = 0;
	wc.cbWndExtra = 0;
	wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	wc.hInstance = *hInstance;
	wc.lpfnWndProc = WndProc;
	wc.lpszClassName = L"MainWindow";
	wc.lpszMenuName = 0;
	wc.style = CS_HREDRAW | CS_VREDRAW;

	RegisterClass(&wc);

	if (settings->fullscreen)
	{
		handle = CreateWindowEx(NULL,
			L"MainWindow",
			name,
			WS_EX_TOPMOST | WS_POPUP,
			0, 0,
			settings->monitorRes->width, settings->monitorRes->height,
			NULL,
			NULL,
			*hInstance,
			NULL
			);
	}
	else
	{
		// Get the X and Y position the render field should be
		int _posX = (settings->monitorRes->width - settings->screenRes->width) / 2;
		int _posY = (settings->monitorRes->height - settings->screenRes->height) / 2;

		// Put it in a rectangle
		RECT _desiredSize;
		_desiredSize.left = _posX;
		_desiredSize.top = _posY;
		_desiredSize.right = settings->screenRes->width;
		_desiredSize.bottom = settings->screenRes->height;

		// Adjust the rectangle so the render field is the size it should be
		AdjustWindowRect(&_desiredSize, WS_CAPTION, FALSE);

		handle = CreateWindow(
			L"MainWindow", 
			name, 
			WS_CAPTION, 
			_desiredSize.left, _desiredSize.top,
			_desiredSize.right,
			_desiredSize.bottom,
			NULL, 
			NULL, 
			*hInstance, 
			NULL
			);
	}

	ShowWindow(handle, 5);
	UpdateWindow(handle);

	windowIsUp = true;

	// Hide the cursor
	ShowCursor(FALSE);

	// Enter the message loop to send keyboard and mouse input to the Pc Input Reciever
	MSG msg;
	ZeroMemory(&msg, sizeof(msg));

	while (msg.message != WM_QUIT)
	{
		if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
		{
			switch (msg.message)
			{
				case WM_KEYDOWN : pcReciever->KeyPressed(msg.wParam); break;
				case WM_KEYUP : pcReciever->KeyReleased(msg.wParam); break;
				case WM_MOUSEMOVE: pcReciever->MouseMoved(msg.lParam); break;
				case WM_LBUTTONDOWN: pcReciever->MouseButtonPressed(MOUSE_LBUTTON); break;
				case WM_RBUTTONDOWN: pcReciever->MouseButtonPressed(MOUSE_RBUTTON); break;
				case WM_MBUTTONDOWN: pcReciever->MouseButtonPressed(MOUSE_MBUTTON); break;
				case WM_LBUTTONUP: pcReciever->MouseButtonReleased(MOUSE_LBUTTON); break;
				case WM_RBUTTONUP: pcReciever->MouseButtonReleased(MOUSE_RBUTTON); break;
				case WM_MBUTTONUP: pcReciever->MouseButtonReleased(MOUSE_MBUTTON); break;
				default:
					TranslateMessage(&msg);
					DispatchMessage(&msg);
			}
		}
	}

	UnregisterClass(L"MainWindow", wc.hInstance);

	windowIsUp = false;

	return 1;
}
Exemplo n.º 26
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow)
{
	/* rejestrujemy klasê okna */

	WNDCLASSEX KlasaOkna;
	
	// wype³niamy strukturê WNDCLASSEX
	ZeroMemory (&KlasaOkna, sizeof(WNDCLASSEX));
	KlasaOkna.cbSize = sizeof(WNDCLASSEX);
	KlasaOkna.hInstance = hInstance;
	KlasaOkna.lpfnWndProc = WindowEventProc;
	KlasaOkna.lpszClassName = g_strKlasaOkna.c_str();
	KlasaOkna.hCursor = LoadCursor(NULL, IDC_ARROW);
	KlasaOkna.hIcon = LoadIcon(NULL, IDI_APPLICATION);
	KlasaOkna.hbrBackground = (HBRUSH) GetStockObject(BLACK_BRUSH);
	KlasaOkna.style = CS_OWNDC					// w³asny kontekst urz¹dzenia okna
					  | CS_HREDRAW | CS_VREDRAW;
	
	// rejestrujemy klasê okna
	RegisterClassEx (&KlasaOkna);


	/* tworzymy okno */

	// tworzymy okno funkcj¹ CreateWindowEx
	g_hwndOkno = CreateWindowEx(NULL,					// rozszerzony styl okna
								g_strKlasaOkna.c_str(),	// klasa okna
								"Zepsuty telewizor",		// tekst na pasku tytu³u
								WS_OVERLAPPED | WS_BORDER
								| WS_CAPTION | WS_SYSMENU,
								CW_USEDEFAULT,			// wspó³rzêdna pozioma
								CW_USEDEFAULT,			// wspó³rzêdna pionowa
								400,						// szerokoϾ
								300,						// wysokoϾ
								NULL,					// uchwyt do okna nadrzêdnego
								NULL,					// uchwyt do menu
								hInstance,				// uchwyt do instancji aplikacji
								NULL);					// dodatkowe dane
	
	// pokazujemy nasze okno
	ShowWindow (g_hwndOkno, nCmdShow);


	/* przygotowujemy siê do rysowania efektu */

	// pobieramy uchwyt do kontekstu urz¹dzenia obszaru klienta okna
	g_hdcOkno = GetDC(g_hwndOkno);

    // pobieramy prostok¹t tego¿ obszaru
	// (poniewa¿ okno jest sta³ych rozmiarów, nie zmieni siê on)
	GetClientRect (g_hwndOkno, &g_rcObszarKlienta);

	// inicjujemy generator liczb pseudolosowych
	srand (static_cast<unsigned>(time(NULL)));


	/* pêtla komunikatów */

	MSG msgKomunikat;
	msgKomunikat.message = WM_NULL;
	while (msgKomunikat.message != WM_QUIT)
	{
		if (PeekMessage(&msgKomunikat, NULL, 0, 0, PM_REMOVE))
		{
			TranslateMessage (&msgKomunikat);
			DispatchMessage (&msgKomunikat);
		}
		else
			Pracuj();
	}

	// zwracamy kod wyjœcia
	return static_cast<int>(msgKomunikat.wParam);
}
Exemplo n.º 27
0
int WINAPI WinMain( HINSTANCE hInstance,
                    HINSTANCE hPrevInstance,
                    LPSTR     lpCmdLine,
                    int       nCmdShow )
{

	// local
    WNDCLASSEX	winClass;
    MSG			uMsg;
	char*		winClassName = "rtvsD3dWinLite";

	// initialise message
    memset(&uMsg,0,sizeof(uMsg));

	// init
    winClass.lpszClassName = winClassName;
    winClass.cbSize        = sizeof(WNDCLASSEX);
    winClass.style         = CS_HREDRAW | CS_VREDRAW;
    winClass.lpfnWndProc   = WindowProc;
    winClass.hInstance     = hInstance;
    winClass.hIcon         = LoadIcon(hInstance, (LPCTSTR)IDI_ICON1);
    winClass.hIconSm       = LoadIcon(hInstance, (LPCTSTR)IDI_ICON2);
    winClass.hCursor       = LoadCursor(NULL, IDC_ARROW);
    winClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
    winClass.lpszMenuName  = NULL;
    winClass.cbClsExtra    = 0;
    winClass.cbWndExtra    = 0;

	// IF register class fails THEN end
    if( !RegisterClassEx(&winClass) )
        return E_FAIL;

	// create window
    g_hWnd = CreateWindowEx( NULL, winClassName, 
                             "Application Framework Demo",
                             WS_OVERLAPPEDWINDOW | WS_VISIBLE,
                             0, 0, 1200, 800, NULL, NULL, hInstance, NULL );

	// IF create window fails THEN end
    if( g_hWnd == NULL )
        return E_FAIL;

	// housekeeping
    ShowWindow( g_hWnd, nCmdShow );
    UpdateWindow( g_hWnd );

	// create application
	g_app = new rtvsD3dApp(0);

	// non-device one time application setup 
	g_app->setup();

	// non-device one time setup
    setup();

	// device dependent setup
    setupDX();

	// WHILE NOT quit, handle messages and display
    while( uMsg.message != WM_QUIT )
    {
        if( PeekMessage( &uMsg, NULL, 0, 0, PM_REMOVE ) )
        { 
            TranslateMessage( &uMsg );
            DispatchMessage( &uMsg );
        }
        else
            display();
    }

	// device dependent cleanup
    cleanupDX();

	// non-device dependant one time cleanup
	cleanup();

	// non-device one time application cleanup
	g_app->cleanup();

	// unregister windows class
    UnregisterClass(
		winClassName,
		winClass.hInstance
		);

    return uMsg.wParam;
}
Exemplo n.º 28
0
void CPpcMainWnd::OnHotKey(int nId, UINT fuModifiers, UINT uVirtKey)
{
	// 未処理のWM_HOTKEYを削除する
	MSG msg;
	while (PeekMessage(&msg, m_hWnd, WM_HOTKEY, WM_HOTKEY, PM_REMOVE));

	CPpcOptions* pOptions = (CPpcOptions*)m_pOptions;
	if (!pOptions) return;

	// 登録情報を参照する
	for (int i = 0; i < pOptions->m_listKeyMap.GetCount(); i++) {
		ACCEL* p = (ACCEL*)pOptions->m_listKeyMap.GetAt(i);
		if (p->key == uVirtKey) {
			// モーダルダイアログが表示されている場合は
			// ダイアログをだすもの、メニューを出すものを処理しない
			if (m_fMenuLoop || m_hMenu || (GetWindowLong(m_hWnd, GWL_STYLE) & WS_DISABLED)) {
				switch (p->cmd) {
				case IDM_PLAY_PLAYPAUSE:
				case IDM_PLAY_STOP:
				case IDM_PLAY_PREV:
				case IDM_PLAY_REW:
				case IDM_PLAY_FF:
				case IDM_PLAY_NEXT:
				case IDM_PLAY_REPEAT:
				case IDM_TOOL_VOLUP:
				case IDM_TOOL_VOLDOWN:
				case IDM_TOOL_TOGGLEDISPLAY:
				case IDM_TOOL_HOLD:
				case IDM_TOOL_HOLDDISP:
				case IDM_PLAY_PLAYSTOP:
					break;
				default: return;
				}
			}

			if (m_fHold) {
				BOOL fHold = FALSE;
				ACCEL* p = (ACCEL*)pOptions->m_listKeyMap.GetAt(i);
				for (int j = 0; j < sizeof(s_uHoldKeys) / sizeof(UINT) / 2; j++) {
					if (s_uHoldKeys[j][0] == p->key) {
						fHold = TRUE;
						break;
					}
				}

				if (p->cmd == IDM_TOOL_TOGGLEDISPLAY ||
					p->cmd == IDM_TOOL_HOLD ||
					p->cmd == IDM_TOOL_HOLDDISP || !fHold)
					PostMessage(m_hWnd, WM_COMMAND, p->cmd, 0);
				else {
					KillTimer(m_hWnd, ID_TIMER_HOLD);
					m_fDrawHold = TRUE;
					SetTimer(m_hWnd, ID_TIMER_HOLD, TIMER_HOLD_INTERVAL, NULL);
					UpdateTitle();
				}
			}
			else PostMessage(m_hWnd, WM_COMMAND, p->cmd, 0);

			// バックライト制御以外で
			// 自動バックライトON制御が有効のとき
			if (pOptions->m_fDispAutoOn &&
				(p->cmd != IDM_TOOL_TOGGLEDISPLAY && p->cmd != IDM_TOOL_HOLDDISP)) {
				TurnOnDisplay();
				m_fDisplay = TRUE;

				InvalidateRect(m_hWnd, NULL, TRUE);
				UpdateWindow(m_hWnd);
			}
			return;
		}
	}

	if (m_fHold) {
		KillTimer(m_hWnd, ID_TIMER_HOLD);
		m_fDrawHold = TRUE;
		SetTimer(m_hWnd, ID_TIMER_HOLD, TIMER_HOLD_INTERVAL, NULL);
		UpdateTitle();
	}
}
Exemplo n.º 29
0
int WINAPI WinMain(HINSTANCE hInst,HINSTANCE hPrevInst,
				   LPSTR cmdLine,int cmdShow)
{
	MSG msg;
	g_bLmouseButt = false;

	if(!SysInit(hInst))
		return -1;

	appRunning = true;

	buffer.RecalcOffs();

	InitSinCos();

	InitApp();

	// Initialzie the FPS counting variables

	fps			= 0;
	frmCounter	= 0;
	timeLast	= GetTickCount();

	//initialize dTime vars	pentru dTime
	LARGE_INTEGER qwTicksPerSec;
	QueryPerformanceFrequency(&qwTicksPerSec);
	LONGLONG m_llQPFTicksPerSec = qwTicksPerSec.QuadPart;

	LARGE_INTEGER qwTicks;
	QueryPerformanceCounter(&qwTicks);
	m_llLastElapsedTime = qwTicks.QuadPart;

	while(appRunning)
	{
		if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
		{
			switch(msg.message)
			{
			case WM_QUIT:
				{
					appRunning = false;
				}
				break;
			case WM_MOUSEMOVE:
				{
					g_ptMouse.x = GET_X_LPARAM(msg.lParam); 
					g_ptMouse.y = GET_Y_LPARAM(msg.lParam); 
				}
				break;
			case WM_LBUTTONDOWN:
				{
					g_bLmouseButt = true;
				}
				break;
			case WM_LBUTTONUP:
				{
					g_bLmouseButt = false;
				}
				break;
			}

			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
		
		if(buffer.IsBuffer())
		{
			// Clear buffer
			buffer.clearBuffer();
			
			LARGE_INTEGER qwTime;
			QueryPerformanceCounter(&qwTime);

			double fElapsedTime = (double) (qwTime.QuadPart - m_llLastElapsedTime) / (double) m_llQPFTicksPerSec;
			m_llLastElapsedTime = qwTime.QuadPart;

			//max 5000 fps	si min 30 fps
			if(fElapsedTime <= 0.0001f)
				fElapsedTime = 0.0001f;
			if(fElapsedTime > 0.04f)
				fElapsedTime = 0.04f;
			//Update stuff
			UpdateFrame(fElapsedTime);
			// Render stuff
			RenderFrame(fElapsedTime);
			
			// Swap buffers
			SwapBuffers();

			// Keep track of FPS
			UpdateFPS();
		}
	}

	SysDeinit();

	return 0;
}
Exemplo n.º 30
0
int WINAPI WinMain(	HINSTANCE	hInstance,			// Instance
					HINSTANCE	hPrevInstance,		// Previous Instance
					LPSTR		lpCmdLine,			// Command Line Parameters
					int			nCmdShow)			// Window Show State
{
	MSG		msg;									// Windows Message Structure


#if 0
	// Ask The User Which Screen Mode They Prefer
	if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO)
	{
		fullscreen=FALSE;							// Windowed Mode
	} // end of the if 
#endif 


	// for the sake of simplicity, start in windowed mode
#if FULL_SCREEN_F
	fullscreen=TRUE;
#else
	fullscreen=FALSE;
#endif


	// Create Our OpenGL Window
	if (!CreateGLWindow("glAnt",SCREEN_WIDTH,SCREEN_HEIGHT,
			INIT_BIT_RATE,fullscreen))
	{
		return 0;									// Quit If Window Was Not Created
	}

	while(!done)									// Loop That Runs While done=FALSE
	{
		if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))	// Is There A Message Waiting?
		{
			if (msg.message==WM_QUIT)				// Have We Received A Quit Message?
			{
				done=TRUE;							// If So done=TRUE
			}
			else									// If Not, Deal With Window Messages
			{
				TranslateMessage(&msg);				// Translate The Message
				DispatchMessage(&msg);				// Dispatch The Message
			}
		}
		else										// If There Are No Messages
		{
			Run_Anim();			// draw and process!!!

			SwapBuffers(hDC);					// Swap Buffers (Double Buffering)

		
			// process the keyboard some where else
			HandleCameraKeys(keys);

			if (keys[VK_F1])						// Is F1 Being Pressed?
			{
				keys[VK_F1]=FALSE;					// If So Make Key FALSE
				KillGLWindow();						// Kill Our Current Window
				fullscreen=!fullscreen;				// Toggle Fullscreen / Windowed Mode

				// Recreate Our OpenGL Window
				if (!CreateGLWindow("glAnts",
					640,480,INIT_BIT_RATE,fullscreen))
				{
					return 0;						// Quit If Window Was Not Created
				} // end if Create
			} // end if f1

		}
	}


	

	// Shutdown
	KillGLWindow();									// Kill The Window

	return (msg.wParam);							// Exit The Program

} // end of the functino