void Circle::Update(float a_dt)
{
	Vector3 vPos = GetPosition();
	float e = 0.8f;
	float frictionCoefficient = 0.5f;

	//Apply friction
	m_vVelocity -= (m_vVelocity * a_dt) * frictionCoefficient;
	//Apply Velocity
	vPos += m_vVelocity * a_dt;
	
	//Reflecting along each wall
	if (vPos.x + m_fRadius > GetWindowDimensions().x / 2.f)
	{
		vPos.x = GetWindowDimensions().x / 2.f - m_fRadius;
		m_vVelocity = m_vVelocity.GetReflected(Vector3(-1,0,0)) * e;
	}
	if (vPos.y + m_fRadius > GetWindowDimensions().y / 2.f)
	{
		vPos.y = GetWindowDimensions().y / 2.f - m_fRadius;
		m_vVelocity = m_vVelocity.GetReflected(Vector3(0,-1,0)) * e;
	}
	if (vPos.x - m_fRadius < -GetWindowDimensions().x / 2.f)
	{
		vPos.x = -GetWindowDimensions().x / 2.f + m_fRadius;
		m_vVelocity = m_vVelocity.GetReflected(Vector3(1,0,0)) * e;
	}
	if (vPos.y - m_fRadius < -GetWindowDimensions().y / 2.f)
	{
		vPos.y = -GetWindowDimensions().y / 2.f + m_fRadius;
		m_vVelocity = m_vVelocity.GetReflected(Vector3(0,1,0)) * e;
	}

	SetPosition(vPos);
}
Exemple #2
0
static void
ApplyGridLayout(wnd_ctrls *Controls, int WindowWidth, int WindowHeight, int MarginX, int MarginY)
{
	if(Controls) {
		// NOTE: Build a nice grid layout
		
		// TODO: We might want to consider to formalize the notion of a layout if we are going to
		// add more controls to the window.
		float GridSpacingX = (float)WindowWidth / (float)NUM_ELEMENTS_X;
		float GridSpacingY = (float)WindowHeight / (float)NUM_ELEMENTS_Y;

		wnd_dim Dim;
		UINT SetPosFlags = SWP_NOACTIVATE | SWP_NOCOPYBITS | SWP_NOZORDER | SWP_SHOWWINDOW;

		Dim = GetWindowDimensions(Controls->ComboBox);
		SetWindowPos(Controls->ComboBox, 0, MarginX, (int)((GridSpacingY - Dim.Height) / 2), MAIN_WINDOW_WIDTH - 2 * MarginX, MAIN_WINDOW_HEIGHT, SetPosFlags);

		// NOTE: CW_USEDEFAULT does not work for some reason. Thanks Microsoft.
		// TODO: To support different fonts this has to figure out how big the actual button really should be.
		int TextBoxWidth = (int)(WindowWidth - 2 * MarginX);
		int TextBoxHeight = (int)(GridSpacingY - 2 * MarginY);
		int TextY = (int)(GridSpacingY + MarginY);
		SetWindowPos(Controls->StaticText, 0, MarginX, TextY, TextBoxWidth, TextBoxHeight, SetPosFlags);

		int ButtonWidth = (int)(GridSpacingX - 2 * MarginX);
		int ButtonHeight = (int)(GridSpacingY - 2 * MarginY);
		int ButtonOffsetX = MarginX;
		int ButtonY = (int)(2 * GridSpacingY + MarginY);
		SetWindowPos(Controls->ButtonOK, 0, ButtonOffsetX, ButtonY, ButtonWidth, ButtonHeight, SetPosFlags);
		SetWindowPos(Controls->ButtonCancel, 0, (int)(GridSpacingX + ButtonOffsetX), ButtonY, ButtonWidth, ButtonHeight, SetPosFlags);

		// TODO: This is pure hackery.
		SetWindowPos(Controls->CheckBox, 0, (int)(2 * GridSpacingX + ButtonOffsetX), ButtonY, ButtonWidth, ButtonHeight, SetPosFlags);
	}
}
void CPUTWindowWin::SetFullscreenState(bool fullscreen)
{
    if (mFullscreen == fullscreen)
    {
        return;
    }


    if (fullscreen)
    {
        int x, y, windowWidth, windowHeight;
        GetWindowDimensions(&x, &y, &windowWidth, &windowHeight);
        RECT windowRect = { x, y, windowWidth + x, windowHeight + y };
        mWindowedRect = windowRect;

        int desktopX, desktopY;
        int desktopWidth, desktopHeight;
        GetDesktopDimensions(&desktopX, &desktopY, &desktopWidth, &desktopHeight);

        mWindowedStyle = GetWindowLong(mhWnd, GWL_STYLE);

        SetWindowLong(mhWnd, GWL_STYLE, (mWindowedStyle & ~WS_OVERLAPPEDWINDOW) | WS_POPUP);

        SetWindowPos(mhWnd, HWND_TOP, desktopX, desktopY, desktopWidth, desktopHeight,
            SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING | SWP_NOZORDER);

        mFullscreen = true;
    }
    else
    {
        int width = mWindowedRect.right - mWindowedRect.left;
        int height = mWindowedRect.bottom - mWindowedRect.top;
        SetWindowLong(mhWnd, GWL_STYLE, mWindowedStyle);
        SetWindowPos(mhWnd, HWND_TOP, mWindowedRect.left, mWindowedRect.top, width, height,
            SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOSENDCHANGING | SWP_NOZORDER | SWP_FRAMECHANGED);
        mFullscreen = false;
    }
}
int CALLBACK WinMain(HINSTANCE instance, HINSTANCE previousInstance, LPSTR commandLine, int showCode)
{
	WNDCLASS window = {};

	ResizeDibSection(backBuffer, 1280, 720);

	window.style = CS_HREDRAW | CS_VREDRAW;
	window.lpfnWndProc = MainWindowCallback;
	window.hInstance = instance;
	//window.hIcon;
	window.lpszClassName = "Handmade Hero Take 1";
	DefineControllerFuntions();

	if (RegisterClass(&window))
	{
		HWND handle = CreateWindowEx(0, window.lpszClassName,
			"Handmade Hero", WS_VISIBLE | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT,
			CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, instance, 0);

		if (handle)
		{
			int samplesPerSecond = 48000;
			int blueOffset = 0,
					greenOffset = 0;
			uint32 runningSampleIndex = 0;
			int hertz = 256;
			int squareWavePeriod = samplesPerSecond / hertz;
			int halfPeriod = squareWavePeriod / 2;
			int bytesPerSample = sizeof(int16) * 2;
			int audioBufferSize = samplesPerSecond * bytesPerSample;
			int16 toneVolume = 6000;

			InitializeSound(handle, samplesPerSecond, audioBufferSize);
			audioBuffer->Play(0, 0, 0);

			MSG message;
			BOOL messageResult;
			while (isRunning) {

				// GetMessageA blocks. PeekMessage does not
				while (PeekMessage(&message, 0, 0, 0, PM_REMOVE)) {

					if (message.message == WM_QUIT) {
						isRunning = false;
					}

					TranslateMessage(&message);
					DispatchMessage(&message);
				}

				for (DWORD controllerIndex = 0; controllerIndex < XUSER_MAX_COUNT; controllerIndex++) {
					XINPUT_STATE controllerState;
					if (XInputGetState(controllerIndex, &controllerState) == ERROR_SUCCESS) {
						// The controller is plugged in
						XINPUT_GAMEPAD *pad = &controllerState.Gamepad;

						if (pad->wButtons & XINPUT_GAMEPAD_DPAD_UP)
						{
							greenOffset++;
						}
						if (pad->wButtons & XINPUT_GAMEPAD_DPAD_DOWN)
						{
							greenOffset--;
						}
						if (pad->wButtons & XINPUT_GAMEPAD_DPAD_LEFT)
						{
							blueOffset -= 2;
						}
						if ((pad->wButtons & XINPUT_GAMEPAD_DPAD_RIGHT) || pad->sThumbLX < 0)
						{
							blueOffset++;
						}
						bool leftShoulderPressed = (pad->wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER);
						bool rightShoulderPressed = (pad->wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER);
						bool aButtonPressed = (pad->wButtons & XINPUT_GAMEPAD_A);
						bool bButtonPressed = (pad->wButtons & XINPUT_GAMEPAD_B);
						bool xButtonPressed = (pad->wButtons & XINPUT_GAMEPAD_X);
						bool yButtonPressed = (pad->wButtons & XINPUT_GAMEPAD_Y);

					}
					else {
						// Controller not available.
					}

					XINPUT_VIBRATION goodVibrations;
					goodVibrations.wLeftMotorSpeed = 6000;
					goodVibrations.wRightMotorSpeed = 6000;
					XInputSetState(0, &goodVibrations);

				}

				renderGradient(backBuffer, blueOffset++, greenOffset);

				// DirectSound output test
				DWORD playCursor;
				DWORD writeCurser;
				if(SUCCEEDED(audioBuffer->GetCurrentPosition(&playCursor, &writeCurser)))
				{
					DWORD byteToLock = runningSampleIndex * bytesPerSample % samplesPerSecond;
					int32 bytesToWrite;
					if(byteToLock > playCursor)
					{
						bytesToWrite = (audioBufferSize - byteToLock);
						bytesToWrite += playCursor;
					}
					else{
						bytesToWrite = playCursor - byteToLock;
					}

					VOID *region1;
					DWORD region1Size;
					VOID *region2;
					DWORD region2Size;


					HRESULT  response = audioBuffer->Lock(byteToLock, bytesToWrite, &region1, &region1Size, &region2, &region2Size, 0);
					if(SUCCEEDED(response))
					{
						int16 *sampleOutput = (int16 *)region1;
						DWORD region1SampleCount = region1Size / bytesPerSample;
						for (int32 sampleIndex = 0; sampleIndex < region1SampleCount; sampleIndex++)
						{
							int16 sampleValue = ((runningSampleIndex++ > halfPeriod) % 2) ? toneVolume : -toneVolume;
							*sampleOutput++ = sampleValue;
							*sampleOutput++ = sampleValue;
						}

						DWORD region2SampleCount = region2Size / bytesPerSample;
						for (int32 sampleIndex = 0; sampleIndex < region2SampleCount; sampleIndex++)
						{
							int16 sampleValue = ((runningSampleIndex++ > halfPeriod) % 2) ? toneVolume : -toneVolume;
							*sampleOutput++ = sampleValue;
							*sampleOutput++ = sampleValue;
						}

						audioBuffer->Unlock(region1, region1Size, region2, region2Size);
					}
				}

				HDC deviceContext = GetDC(handle);
				window_dimensions updateScreen = GetWindowDimensions(handle);
				DisplayBufferInWindow(deviceContext, updateScreen, backBuffer);
				ReleaseDC(handle, deviceContext);
			}
		}
	}

	return 0;
}
LRESULT CALLBACK
MainWindowCallback(HWND window, UINT message, WPARAM wParam, LPARAM lParam)
{
	LRESULT result = 0;
	switch (message)
	{
	case WM_DESTROY:
		isRunning = false;
		break;
	case WM_CLOSE:
		isRunning = false;
		break;
	case WM_SYSKEYDOWN:
	case WM_SYSKEYUP:
	case WM_KEYDOWN:
	case WM_KEYUP:
	{
		uint32 virtualKeyCode = wParam;
		bool wasPreviouslyDown = (lParam & (1 << 30)) != 0;
		bool isCurrentlyDown = (lParam & (1 << 31)) == 0;

		if (virtualKeyCode == 'W') {

		}
		else if (virtualKeyCode == 'A') {

		}
		else if (virtualKeyCode == 'S') {

		}
		else if (virtualKeyCode == 'D') {

		}
		else if (virtualKeyCode == 'Q') {

		}
		else if (virtualKeyCode == 'E') {

		}
		else if (virtualKeyCode == VK_UP) {

		}
		else if (virtualKeyCode == VK_LEFT) {

		}
		else if (virtualKeyCode == VK_DOWN) {

		}
		else if (virtualKeyCode == VK_RIGHT) {

		}
		else if (virtualKeyCode == VK_SPACE) {

		}
		else if (virtualKeyCode == VK_ESCAPE) {

		}

		int32 altKeyIsDown = (lParam & (1 << 29));
		if(virtualKeyCode == VK_F4 && altKeyIsDown){
			isRunning = false;
		}

	}
	break;
	case WM_PAINT:
	{
		PAINTSTRUCT painting;
		HDC context = BeginPaint(window, &painting);

		DisplayBufferInWindow(context, GetWindowDimensions(window), backBuffer);

		EndPaint(window, &painting);
	}
	break;
	default:
		result = DefWindowProc(window, message, wParam, lParam);
		break;
	}

	return result;
}
Exemple #6
0
bool CDlgEventLog::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin CDlgEventLog member initialisation
    CMainDocument* pDoc     = wxGetApp().GetDocument();
    wxASSERT(pDoc);
    wxASSERT(wxDynamicCast(pDoc, CMainDocument));
    
    m_iPreviousRowCount = 0;
    m_iTotalDocCount = 0;
    m_iPreviousFirstMsgSeqNum = pDoc->GetFirstMsgSeqNum();
    m_iPreviousLastMsgSeqNum = m_iPreviousFirstMsgSeqNum - 1;

    m_iNumDeletedFilteredRows = 0;
    m_iTotalDeletedFilterRows = 0;
    
    if (!s_bIsFiltered) {
        s_strFilteredProjectName.clear();
    }
    m_iFilteredIndexes.Clear();
	m_bProcessingRefreshEvent = false;
    m_bWasConnected = false;
    m_bEventLogIsOpen = true;
////@end CDlgEventLog member initialisation

    CSkinAdvanced* pSkinAdvanced = wxGetApp().GetSkinManager()->GetAdvanced();
    wxPoint oTempPoint;
    wxSize  oTempSize;

    wxASSERT(pSkinAdvanced);
    wxASSERT(wxDynamicCast(pSkinAdvanced, CSkinAdvanced));

    if ((pos == wxDefaultPosition) && (size == wxDefaultSize)) {
        // Get size and position from the previous configuration
        GetWindowDimensions( oTempPoint, oTempSize );

#ifdef __WXMSW__
        // Get the current display space for the current window
		int iDisplay = wxNOT_FOUND;
		if ( wxGetApp().GetFrame() != NULL )
            iDisplay = wxDisplay::GetFromWindow(wxGetApp().GetFrame());
		if ( iDisplay == wxNOT_FOUND )
            iDisplay = 0;
        wxDisplay *display = new wxDisplay(iDisplay);
        wxRect rDisplay = display->GetClientArea();

		// Check that the saved height and width is not larger than the displayable space.
		// If it is, then reduce the size.
        if ( oTempSize.GetWidth() > rDisplay.width ) oTempSize.SetWidth(rDisplay.width);
        if ( oTempSize.GetHeight() > rDisplay.height ) oTempSize.SetHeight(rDisplay.height);

        // Check if part of the display was going to be off the screen, if so, center the 
        // display on that axis
		if ( oTempPoint.x < rDisplay.x ) {
			oTempPoint.x = rDisplay.x;
		} else if ( oTempPoint.x + oTempSize.GetWidth() > rDisplay.x + rDisplay.width ) {
			oTempPoint.x = rDisplay.x + rDisplay.width - oTempSize.GetWidth();
		}

		if ( oTempPoint.y < rDisplay.y ) {
			oTempPoint.y = rDisplay.y;
		} else if ( oTempPoint.y + oTempSize.GetHeight() > rDisplay.y + rDisplay.height ) {
			oTempPoint.y = rDisplay.y + rDisplay.height - oTempSize.GetHeight();
		}

        delete display;
#endif
#ifdef __WXMAC__
        // If the user has changed the arrangement of multiple 
        // displays, make sure the window title bar is still on-screen.
    if (!IsWindowOnScreen(oTempPoint.x, oTempPoint.y, oTempSize.GetWidth(), oTempSize.GetHeight())) {
        oTempPoint.y = oTempPoint.x = 30;
    }
#endif  // ! __WXMAC__
    } else {
        oTempPoint = pos;
        oTempSize = size;
    }

    wxDialog::Create( parent, id, caption, oTempPoint, oTempSize, style );

    SetSizeHints(DLGEVENTLOG_MIN_WIDTH, DLGEVENTLOG_MIN_HEIGHT);
    SetExtraStyle(GetExtraStyle()|wxWS_EX_BLOCK_EVENTS);

    // Initialize Application Title
    wxString strCaption = caption;
    if (strCaption.IsEmpty()) {
        strCaption.Printf(_("%s - Event Log"), pSkinAdvanced->GetApplicationName().c_str());
    }
    SetTitle(strCaption);

    // Initialize Application Icon
    SetIcons(*pSkinAdvanced->GetApplicationIcon());

    CreateControls();

	// Create List Pane Items
    m_pList->InsertColumn(COLUMN_PROJECT, _("Project"), wxLIST_FORMAT_LEFT, 109);
    m_pList->InsertColumn(COLUMN_TIME, _("Time"), wxLIST_FORMAT_LEFT, 130);
    m_pList->InsertColumn(COLUMN_MESSAGE, _("Message"), wxLIST_FORMAT_LEFT, 378);

    m_pMessageInfoAttr = new wxListItemAttr(
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT),
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW),
        wxNullFont
    );
    m_pMessageErrorAttr = new wxListItemAttr(
        *wxRED,
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW),
        wxNullFont
    );
#if EVENT_LOG_STRIPES
    m_pMessageInfoGrayAttr = new wxListItemAttr(
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT),
        wxColour(240, 240, 240),
        wxNullFont
    );
    m_pMessageErrorGrayAttr = new wxListItemAttr(*wxRED, wxColour(240, 240, 240), wxNullFont);
#else
    m_pMessageInfoGrayAttr = new wxListItemAttr(*m_pMessageInfoAttr);
    m_pMessageErrorGrayAttr = new wxListItemAttr(*m_pMessageErrorAttr);
#endif

    SetTextColor();
    RestoreState();
    OnRefresh();
    // Register that we had the Event Log open immediately
    SaveState();
    
    m_Shortcuts[0].Set(wxACCEL_CTRL|wxACCEL_SHIFT, (int)'F', ID_SGDIAGNOSTICLOGFLAGS);
    m_pAccelTable = new wxAcceleratorTable(1, m_Shortcuts);

    SetAcceleratorTable(*m_pAccelTable);

    return true;
}
Exemple #7
0
bool CDlgEventLog::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin CDlgEventLog member initialisation
    CMainDocument* pDoc     = wxGetApp().GetDocument();
    wxASSERT(pDoc);
    wxASSERT(wxDynamicCast(pDoc, CMainDocument));
    
    m_iPreviousRowCount = 0;
    m_iTotalDocCount = 0;
    m_iPreviousFirstMsgSeqNum = pDoc->GetFirstMsgSeqNum();
    m_iPreviousLastMsgSeqNum = m_iPreviousFirstMsgSeqNum - 1;

    m_iNumDeletedFilteredRows = 0;
    m_iTotalDeletedFilterRows = 0;
    
    if (!s_bIsFiltered) {
        s_strFilteredProjectName.clear();
    }
    m_iFilteredIndexes.Clear();
	m_bProcessingRefreshEvent = false;
    m_bWasConnected = false;
    m_bEventLogIsOpen = true;
////@end CDlgEventLog member initialisation

    CSkinAdvanced* pSkinAdvanced = wxGetApp().GetSkinManager()->GetAdvanced();
    wxPoint oTempPoint;
    wxSize  oTempSize;

    wxASSERT(pSkinAdvanced);
    wxASSERT(wxDynamicCast(pSkinAdvanced, CSkinAdvanced));

    if ((pos == wxDefaultPosition) && (size == wxDefaultSize)) {
        // Get size and position from the previous configuration
        GetWindowDimensions( oTempPoint, oTempSize );

#ifdef __WXMSW__
        // Windows does some crazy things if the initial position is a negative
        // value.
        oTempPoint.x = wxDefaultCoord;
        oTempPoint.y = wxDefaultCoord;
#endif

#ifdef __WXMAC__
        // If the user has changed the arrangement of multiple 
        // displays, make sure the window title bar is still on-screen.
    if (!IsWindowOnScreen(oTempPoint.x, oTempPoint.y, oTempSize.GetWidth(), oTempSize.GetHeight())) {
        oTempPoint.y = oTempPoint.x = 30;
    }
#endif  // ! __WXMAC__
    } else {
        oTempPoint = pos;
        oTempSize = size;
    }

    wxDialog::Create( parent, id, caption, oTempPoint, oTempSize, style );

    SetExtraStyle(GetExtraStyle()|wxWS_EX_BLOCK_EVENTS);

    // Initialize Application Title
    wxString strCaption = caption;
    if (strCaption.IsEmpty()) {
        strCaption.Printf(_("%s - Event Log"), pSkinAdvanced->GetApplicationName().c_str());
    }
    SetTitle(strCaption);

    // Initialize Application Icon
    wxIconBundle icons;
    icons.AddIcon(*pSkinAdvanced->GetApplicationIcon());
    icons.AddIcon(*pSkinAdvanced->GetApplicationIcon32());
    SetIcons(icons);

    CreateControls();

	// Create List Pane Items
    m_pList->InsertColumn(COLUMN_PROJECT, _("Project"), wxLIST_FORMAT_LEFT, 109);
    m_pList->InsertColumn(COLUMN_TIME, _("Time"), wxLIST_FORMAT_LEFT, 130);
    m_pList->InsertColumn(COLUMN_MESSAGE, _("Message"), wxLIST_FORMAT_LEFT, 378);

    m_pMessageInfoAttr = new wxListItemAttr(
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT),
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW),
        wxNullFont
    );
    m_pMessageErrorAttr = new wxListItemAttr(
        *wxRED,
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW),
        wxNullFont
    );
#if EVENT_LOG_STRIPES
    m_pMessageInfoGrayAttr = new wxListItemAttr(
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT),
        wxColour(240, 240, 240),
        wxNullFont
    );
    m_pMessageErrorGrayAttr = new wxListItemAttr(*wxRED, wxColour(240, 240, 240), wxNullFont);
#else
    m_pMessageInfoGrayAttr = new wxListItemAttr(*m_pMessageInfoAttr);
    m_pMessageErrorGrayAttr = new wxListItemAttr(*m_pMessageErrorAttr);
#endif

    SetTextColor();
    RestoreState();
    OnRefresh();

    return true;
}
Exemple #8
0
void Game::MoveInvaders()
{
	Rocket::Core::Vector2f new_positions[NUM_INVADERS];

	// We loop through all invaders, calculating their new positions, if any of them go over the screen bounds,
	// then we switch direction, move the invaders down and start at 0 again
	for (int i = 0; i < NUM_INVADERS; i++)
	{
		if (invaders[i]->GetState() == Invader::DEAD)
			continue;

		new_positions[i] = invaders[i]->GetPosition();
		new_positions[i].x += INVADER_MOVEMENT * current_invader_direction;
		if (new_positions[i].x < 0 || new_positions[i].x + INVADER_SPACING_X > WINDOW_WIDTH)
		{
			// Switch direction and start back at 0 (-1 as the for loop increments)
			current_invader_direction *= -1.0f;
			i = -1;

			// Move all invaders down
			for (int j = 0; j < NUM_INVADERS; j++)
			{
				if (invaders[j]->GetState() == Invader::DEAD)
					continue;

				Rocket::Core::Vector2f position = invaders[j]->GetPosition();
				position.y += INVADER_SPACING_Y;
				invaders[j]->SetPosition(position);
			}

			// Increase speed of invaders
			invader_move_freq *= INVADER_UPDATE_MODIFIER;			
		}
	}

	// Assign invaders their new position and advance their animation frame
	bool invaders_alive = false;

	for (int i = 0; i < NUM_INVADERS; i++)
	{
		if (invaders[i]->GetState() == Invader::DEAD)
			continue;

		invaders[i]->SetPosition(new_positions[i]);
		invaders[i]->UpdateAnimation();

		// If an invader hits the bottom, instant death
		if (new_positions[i].y >= GetWindowDimensions().y - INVADER_SPACING_Y)
		{
			OnGameOver();
			return;
		}

		invaders_alive = true;
	}

	if (!invaders_alive)
	{
		SetWave(GameDetails::GetWave() + 1);
		InitialiseWave();
	}
}
Exemple #9
0
CollisionApp::CollisionApp()
  : m_dTurn(0.0f)
  , m_moveRate(2.0f)
  , m_turnRate(2.0f)
  , m_playerMoving(false)
{
  this->ToggleOutputWindow(false);
  Context::Init(Log);

  Window::WindowFactory windowFactory;

  Window::InitData windowData;
  windowData.isImGuiWindow = false;
  int appW(0), appH(0);
  GetWindowDimensions(appW, appH);
  windowData.width = appW;
  windowData.height = appH;
  windowData.clearColor = (vec4(0.0f, 0.0f, 0.0f, 1.0f));

  m_pViewport = windowFactory.GetNewWindow(windowData);

  float margin = 0.5f;
  m_canvasDim = 10.0f;

  //Add boundary lines
  BoundaryLine bl;
  bl.line = Line(vec3(margin, margin, 1.0f), vec3(1.0f, 0.0f, 0.0f));
  bl.length = m_canvasDim - 2.0f * margin;
  m_boundaryLines.push_back(bl);

  bl.line = Line(vec3(m_canvasDim - margin, margin, 1.0f), vec3(0.0f, 1.0f, 0.0f));
  m_boundaryLines.push_back(bl);

  bl.line = Line(vec3(m_canvasDim - margin, m_canvasDim - margin, 1.0f), vec3(-1.0f, 0.0f, 0.0f));
  m_boundaryLines.push_back(bl);

  bl.line = Line(vec3(margin, m_canvasDim - margin, 1.0f), vec3(0.0f, -1.0f, 0.0f));
  m_boundaryLines.push_back(bl);

  float crossDim = 0.6f;
  vec3 crossCenter(5.0f, 5.0f, 1.0f);

  // Upper arm
  vec3 lo = crossCenter + vec3(crossDim, crossDim, 0.0f);
  bl.length = 3.0f * crossDim;
  bl.line = Line(lo, vec3::yAxis());
  m_boundaryLines.push_back(bl);

  lo = crossCenter + vec3(crossDim, 4.0f * crossDim, 0.0f);
  bl.length = 2.0f * crossDim;
  bl.line = Line(lo, -vec3::xAxis());
  m_boundaryLines.push_back(bl);

  lo = crossCenter + vec3(-crossDim, 4.0f * crossDim, 0.0f);
  bl.length = 3.0f * crossDim;
  bl.line = Line(lo, -vec3::yAxis());
  m_boundaryLines.push_back(bl);

  // Left arm
  lo = crossCenter + vec3(-crossDim, crossDim, 0.0f);
  bl.length = 3.0f * crossDim;
  bl.line = Line(lo, -vec3::xAxis());
  m_boundaryLines.push_back(bl);

  lo = crossCenter + vec3(-4.0f * crossDim, crossDim, 0.0f);
  bl.length = 2.0f * crossDim;
  bl.line = Line(lo, -vec3::yAxis());
  m_boundaryLines.push_back(bl);

  lo = crossCenter + vec3(-4.0f * crossDim, -crossDim, 0.0f);
  bl.length = 3.0f * crossDim;
  bl.line = Line(lo, vec3::xAxis());
  m_boundaryLines.push_back(bl);

  // Bottom arm
  lo = crossCenter + vec3(-crossDim, -crossDim, 0.0f);
  bl.length = 3.0f * crossDim;
  bl.line = Line(lo, -vec3::yAxis());
  m_boundaryLines.push_back(bl);

  lo = crossCenter + vec3(-crossDim, -4.0f * crossDim, 0.0f);
  bl.length = 2.0f * crossDim;
  bl.line = Line(lo, vec3::xAxis());
  m_boundaryLines.push_back(bl);

  lo = crossCenter + vec3(crossDim, -4.0f * crossDim, 0.0f);
  bl.length = 3.0f * crossDim;
  bl.line = Line(lo, vec3::yAxis());
  m_boundaryLines.push_back(bl);

  // Right arm
  lo = crossCenter + vec3(crossDim, -crossDim, 0.0f);
  bl.length = 3.0f * crossDim;
  bl.line = Line(lo, vec3::xAxis());
  m_boundaryLines.push_back(bl);

  lo = crossCenter + vec3(4.0f * crossDim, -crossDim, 0.0f);
  bl.length = 2.0f * crossDim;
  bl.line = Line(lo, vec3::yAxis());
  m_boundaryLines.push_back(bl);

  lo = crossCenter + vec3(4.0f * crossDim, crossDim, 0.0f);
  bl.length = 3.0f * crossDim;
  bl.line = Line(lo, -vec3::xAxis());
  m_boundaryLines.push_back(bl);

  //Boundary points
  vec3 bp = crossCenter + vec3(crossDim, 4.0f * crossDim, 0.0f);
  m_boundaryPoints.push_back(bp);
  bp = crossCenter + vec3(-crossDim, 4.0f * crossDim, 0.0f);
  m_boundaryPoints.push_back(bp);
  bp = crossCenter + vec3(-4.0f * crossDim, crossDim, 0.0f);
  m_boundaryPoints.push_back(bp);
  bp = crossCenter + vec3(-4.0f * crossDim, -crossDim, 0.0f);
  m_boundaryPoints.push_back(bp);
  bp = crossCenter + vec3(-crossDim, -4.0f * crossDim, 0.0f);
  m_boundaryPoints.push_back(bp);
  bp = crossCenter + vec3(crossDim, -4.0f * crossDim, 0.0f);
  m_boundaryPoints.push_back(bp);
  bp = crossCenter + vec3(4.0f * crossDim, -crossDim, 0.0f);
  m_boundaryPoints.push_back(bp);
  bp = crossCenter + vec3(4.0f * crossDim, crossDim, 0.0f);
  m_boundaryPoints.push_back(bp);

  //Player puck
  float playerRadius = 0.3f;
  m_player.disk.SetRadius(playerRadius);
  float playerOffset = margin + playerRadius + 0.1f;
  m_player.disk.SetCenter(vec3(playerOffset, playerOffset, 1.0f));
  m_player.angle =  0.0f;
  //m_player.disk.SetCenter(vec3(0.799999952f, playerOffset, 1.0f));
  //m_player.angle = 2.46666574f;
  m_player.speed = 0.0f;
  

  //------------------------------------------------------------------------------------
  //  Add drawables
  //------------------------------------------------------------------------------------
  ScreenObject so;
  so.draw = true;
  Context::LineMesh player_lm = GenerateCircle(1.0f);
  player_lm.color.Set(1.0f, 0.0f, 0.0f, 1.0f);
  m_circleHandle = m_contextLine.AddObject(player_lm);
  m_drawables.insert(dItem(m_circleHandle, so));

  player_lm.color.Set(1.0f, 0.5f, 0.0f, 1.0f);
  so.draw = false;
  m_circleHandleInt = m_contextLine.AddObject(player_lm);
  m_drawables.insert(dItem(m_circleHandleInt, so));

  Context::LineMesh arrow_lm = GenerateArrow();
  so.draw = true;
  arrow_lm.color.Set(1.0f, 0.0f, 0.0f, 1.0f);
  m_arrowHandle = m_contextLine.AddObject(arrow_lm);
  m_drawables.insert(dItem(m_arrowHandle, so));

  arrow_lm.color.Set(1.0f, 0.5f, 0.0f, 1.0f);
  so.draw = false;
  m_arrowHandleInt = m_contextLine.AddObject(arrow_lm);
  m_drawables.insert(dItem(m_arrowHandleInt, so));

  Context::LineMesh lm;
  lm.color.Set(1.0f, 0.0f, 0.0f, 1.0f);
  for (auto const & l : m_boundaryLines)
  {
    Context::LineVertex lv0, lv1;

    lv0.point[0] = l.line.Origin()[0];
    lv0.point[1] = l.line.Origin()[1];
    lv0.point[2] = 0.0f;
    lv0.point[3] = 1.0f;

    lv1.point[0] = l.line.Origin()[0] + l.length * l.line.Direction()[0];
    lv1.point[1] = l.line.Origin()[1] + l.length * l.line.Direction()[1];
    lv1.point[2] = 0.0f;
    lv1.point[3] = 1.0f;

    lm.verts.push_back(lv0);
    lm.verts.push_back(lv1);

    Context::Line l;
    l.indices[0] = lm.verts.size() - 1;
    l.indices[1] = lm.verts.size() - 2;
    lm.lines.push_back(l);
  }

  mat4 scale, translation;
  scale.Scaling(2.0f / m_canvasDim);

  vec4 tvec(-1.0f, -1.0f, 0.0f, 0.0f);
  translation.Translation(tvec);
  m_transform = scale * translation;

  so.draw = true;
  m_drawables.insert(dItem(m_contextLine.AddObject(lm), so));

  m_contextLine.CommitLoadList();
}
// WINDOWS MAIN FUNCTION
// hInst = current instance of the program
// hPrevInst = previous instance which is not used anymore.
// cmdLine = holds command line arguments to be passed in to the program
// cmdShow = holds an integer to specify if we want to show this window.
int CALLBACK WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR cmdLine, int cmdShow)
{
    WNDCLASS wc = {0};
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.hInstance = hInst;
    wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
    wc.lpszClassName = wndClassName;
    wc.hCursor = 0; //TODO: Add cursors and icons to this program.
    wc.hIcon = 0;
    wc.lpfnWndProc = (WNDPROC)wndProc;

    RegisterClass(&wc);

    HWND window = CreateWindow(wndClassName, wndTitle,
                               WS_OVERLAPPEDWINDOW,
                               CW_USEDEFAULT, CW_USEDEFAULT,
                               wndWidth, wndHeight,
                               0, 0, hInst, 0);
    
    if(window)
    {
        ShowWindow(window, SW_SHOW);
        UpdateWindow(window);

        // NOTE: Initializing SDL
        if(SDL_Init(SDL_INIT_VIDEO) != 0 )
        {
            DestroyWindow(window);
            return -2;
        }

        IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG);
        
        sdlWindow = SDL_CreateWindowFrom((void*)window);

        char error[MAX_PATH];
        stringCopy(error, SDL_GetError());
        OutputDebugStringA(error);

        if(!sdlWindow)
        {
            SDL_Quit();
            DestroyWindow(window);
            return -3;
        }
        
        renderer = SDL_CreateRenderer(sdlWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);

        if(!renderer)
        {
            SDL_DestroyWindow(sdlWindow);
            SDL_Quit();
            DestroyWindow(window);
            return -4;
        }

        i32 RefreshRate = 0;
        HDC dc = GetDC(window);
        i32 winRefreshRate = GetDeviceCaps(dc, VREFRESH);

        if( winRefreshRate > 1 )
        {
            RefreshRate = winRefreshRate / 2;
        }
        else
        {
            RefreshRate = 30;
        }

        r32 targetSecsPerFrame = 1.0f / RefreshRate;

        GameMemory memory = {};
        memory.permanentSize = Megabytes(64);
        memory.transientSize = Megabytes(64);
        memory.totalSize = memory.permanentSize + memory.transientSize;
        
        gameMemoryBlock = VirtualAlloc( 0, memory.totalSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

        if(!gameMemoryBlock)
        {
            SDL_DestroyRenderer(renderer);
            SDL_DestroyWindow(sdlWindow);
            SDL_Quit();
            DestroyWindow(window);
            return -5;
        }

        memory.permanentBlock = gameMemoryBlock;
        memory.transientBlock = (i8*)gameMemoryBlock + memory.permanentSize;
        memory.readEntireFile = ReadEntireFile;
        memory.freeFile = FreeFile;
        memory.writeEntireFile = WriteEntireFile;

        Win32Dims windowDims = GetWindowDimensions(window);
        
        Render render = {};
        render.renderer = renderer;
        render.screenW = windowDims.width;
        render.screenH = windowDims.height;
        
        GameController input = {0};
        input.dt = targetSecsPerFrame;
        
        Win32State state = {0};
        state.memoryBlock = gameMemoryBlock;
        state.memorySize = memory.totalSize;

        GameCodeDLL gameCode =  Win32LoadGameCode("Game.dll", "Game_temp.dll", "lock.tmp");
        
        isRunning = true;

        r32 sleepIsGranular = (timeBeginPeriod(1) == TIMERR_NOERROR);
        
        LARGE_INTEGER lastCounter = Win32GetClock();

        i64 lastCycles = __rdtsc();
        
        LARGE_INTEGER performanceFreqPerSecRes;
        QueryPerformanceFrequency(&performanceFreqPerSecRes);
        globalPerformanceCountFreq = performanceFreqPerSecRes.QuadPart;
        
        // NOTE: PROGRAM LOOP!!
        while(isRunning)
        {
            // NOTE: compare File times for us to be able to reload the new game code
            FILETIME currentFileTime = Win32GetLastWriteTime("Game.dll");
            if(CompareFileTime(&currentFileTime, &gameCode.lastWriteTime) != 0)
            {
                Win32UnloadGameCode(&gameCode);
                gameCode = Win32LoadGameCode("Game.dll", "Game_temp.dll", "lock.tmp");
            }
            
            MSG msg = {0};
            while(PeekMessage(&msg, window, 0, 0, PM_REMOVE))
            {
                switch(msg.message)
                {
                    case WM_CLOSE:
                    {
                        isRunning = false;
                    }break;

                    case WM_KEYUP:
                    case WM_KEYDOWN:
                    case WM_SYSKEYUP:
                    case WM_SYSKEYDOWN:
                    {
                        u32 vkCode = (u32)msg.wParam;   // This contains the keycode for the key that the user pressed.
                        bool isDown = ((msg.lParam & (1 << 31)) == 0);  // Check to see if the key is down now.
                        bool wasDown = ((msg.lParam & (1 << 30)) != 0); // Check to see if the key was down previously.

                        if(isDown != wasDown)
                        {
                            if(vkCode == 'W')
                            {
                                input.moveUp.isDown = isDown;
                            }
                            else if(vkCode == 'S')
                            {
                                input.moveDown.isDown = isDown;
                            }
                            else if(vkCode == 'A')
                            {
                                input.moveLeft.isDown = isDown;
                            }
                            else if(vkCode == 'D')
                            {
                                input.moveRight.isDown = isDown;
                            }
                            if(vkCode == VK_UP)
                            {
                                input.actionUp.isDown = isDown;
                            }
                            else if(vkCode == VK_DOWN)
                            {
                                input.actionDown.isDown = isDown;
                            }
                            else if(vkCode == VK_LEFT)
                            {
                                input.actionLeft.isDown = isDown;
                            }
                            else if(vkCode == VK_RIGHT)
                            {
                                input.actionRight.isDown = isDown;
                            }
                            else if(vkCode == VK_ESCAPE)
                            {
                                input.back.isDown = isDown;
                            }
                            else if(vkCode == 'O')
                            {
                                if(isDown)
                                {
                                    if(state.recordingIndex == 0)
                                    {
                                        BeginRecording(&state, 1);
                                    }
                                    else
                                    {
                                        EndRecording(&state);
                                        BeginPlayback(&state, 1);
                                    }
                                }
                            }
                            else if(vkCode == 'P')
                            {
                                if(isDown)
                                {
                                    if(state.playbackIndex > 0)
                                    {
                                        EndPlayback(&state);
                                        ZeroMemory(&input, sizeof(input));
                                    }
                                }
                            }
                        }

                        if(isDown)
                        {
                            bool AltKeyWasDown = ((msg.lParam & (1 << 29)) != 0);
                            if(vkCode == VK_RETURN && AltKeyWasDown)
                            {
                                if(msg.hwnd)
                                {
                                    isFullscreen = !isFullscreen;
                                    Win32FullscreenToggle(msg.hwnd);
                                }
                            }
                        }

                    }break;

                    default:
                    {
                        TranslateMessage(&msg);
                        DispatchMessage(&msg);
                    }
                }
            }

            if(input.back.isDown)
            {
                isRunning = false;
                PostQuitMessage(0);
            }

            if(state.recordingIndex > 0)
            {
                RecordingInput(&state, &input);
            }
            else if(state.playbackIndex > 0)
            {
                PlaybackInput(&state, &input);
            }

            Win32Dims windowDims = GetWindowDimensions(window);
            Win32UpdateWindow(windowDims, (i32*)&render.screenW, (i32*)&render.screenH);
            
            if(gameCode.UpdateRender)
            {
                gameCode.UpdateRender(&memory, &input, &render);
            }

            LARGE_INTEGER workCounter = Win32GetClock();
            r32 workSecsElapsed = Win32GetSecondsElapsed(lastCounter, workCounter);

            r32 secondsElapsed = workSecsElapsed;
            if(secondsElapsed < targetSecsPerFrame)
            {
                if(sleepIsGranular)
                {
                    DWORD sleepMS = (DWORD)(1000.0f * (targetSecsPerFrame - secondsElapsed));
                    if(sleepMS > 0)
                    {
                        Sleep(sleepMS);
                    }
                }

                r32 testSecsElapsed = Win32GetSecondsElapsed(lastCounter, Win32GetClock());
                if(testSecsElapsed < targetSecsPerFrame)
                {
                    //TODO: LOG MISSED SLEEP HERE!!
                }

                while(secondsElapsed < targetSecsPerFrame)
                {
                    secondsElapsed = Win32GetSecondsElapsed(lastCounter, Win32GetClock());
                }
            }
            else
            {
                //TODO: MISSED FRAME RATE!!
            }
            
            LARGE_INTEGER endCounter = Win32GetClock();

            i64 endCycles = __rdtsc();
            
            r64 elapsedCounts = (r64)(endCounter.QuadPart - lastCounter.QuadPart);
            r64 elapsedCycles = (r64)(endCycles - lastCycles);

            r32 MSperFrame = ((1000.0f * Win32GetSecondsElapsed(lastCounter, endCounter)));
            r32 FPS = (r32)(globalPerformanceCountFreq / elapsedCounts);
            r32 MegaCyclesPerFrame = (r32)(elapsedCycles / (1000.0f * 1000.0f));
            
            char buffer[256];
            sprintf_s(buffer, "%.02fms, %.02ffps, %.02fmcpf\n", MSperFrame, FPS, MegaCyclesPerFrame);            
            OutputDebugStringA(buffer);
            
            lastCounter = endCounter;
            lastCycles = endCycles;
            
        } // NOTE: END OF WHILE LOOP

        //IMPORTANT: Unload this when we exit the program.
        Win32UnloadGameCode(&gameCode);        
    }
    else
    {
        // TODO: Handle Error Loggin here!!
        return -1;
    }

    if(gameMemoryBlock)
    {
        VirtualFree(gameMemoryBlock, 0, MEM_RELEASE);
    }
    
    //Close
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(sdlWindow);
    IMG_Quit();
    SDL_Quit();
    DestroyWindow(window);

    return 0;
}
bool CDlgEventLog::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style )
{
////@begin CDlgEventLog member initialisation
    m_iPreviousRowCount = 0;
    m_iTotalDocCount = 0;
    m_iPreviousTotalDocCount = 0;
    if (!s_bIsFiltered) {
        s_strFilteredProjectName.clear();
    }
    m_iFilteredIndexes.Clear();
	m_bProcessingRefreshEvent = false;
    m_bEventLogIsOpen = true;
////@end CDlgEventLog member initialisation

    CSkinAdvanced* pSkinAdvanced = wxGetApp().GetSkinManager()->GetAdvanced();
    wxPoint oTempPoint;
    wxSize  oTempSize;

    wxASSERT(pSkinAdvanced);
    wxASSERT(wxDynamicCast(pSkinAdvanced, CSkinAdvanced));

    if ((pos == wxDefaultPosition) && (size == wxDefaultSize)) {
        // Get size and position from the previous configuration
        GetWindowDimensions( oTempPoint, oTempSize );

#ifdef __WXMSW__
        // Windows does some crazy things if the initial position is a negative
        // value.
        oTempPoint.x = wxDefaultCoord;
        oTempPoint.y = wxDefaultCoord;
#endif

#ifdef __WXMAC__
        // If the user has changed the arrangement of multiple 
        // displays, make sure the window title bar is still on-screen.
        Rect titleRect = {oTempPoint.y, oTempPoint.x, oTempPoint.y+22, oTempPoint.x+oTempSize.x };
        InsetRect(&titleRect, 5, 5);    // Make sure at least a 5X5 piece visible
        RgnHandle displayRgn = NewRgn();
        CopyRgn(GetGrayRgn(), displayRgn);  // Region encompassing all displays
        Rect menuRect = ((**GetMainDevice())).gdRect;
        menuRect.bottom = GetMBarHeight() + menuRect.top;
        RgnHandle menuRgn = NewRgn();
        RectRgn(menuRgn, &menuRect);                // Region hidden by menu bar
        DiffRgn(displayRgn, menuRgn, displayRgn);   // Subtract menu bar retion
        if (!RectInRgn(&titleRect, displayRgn))
            oTempPoint.y = oTempPoint.x = 30;
        DisposeRgn(menuRgn);
        DisposeRgn(displayRgn);
#endif  // ! __WXMAC__
    } else {
        oTempPoint = pos;
        oTempSize = size;
    }

    wxDialog::Create( parent, id, caption, oTempPoint, oTempSize, style );

    SetExtraStyle(GetExtraStyle()|wxWS_EX_BLOCK_EVENTS);

    // Initialize Application Title
    wxString strCaption = caption;
    if (strCaption.IsEmpty()) {
        strCaption.Printf(_("%s - Event Log"), pSkinAdvanced->GetApplicationName().c_str());
    }
    SetTitle(strCaption);

    // Initialize Application Icon
    wxIconBundle icons;
    icons.AddIcon(*pSkinAdvanced->GetApplicationIcon());
    icons.AddIcon(*pSkinAdvanced->GetApplicationIcon32());
    SetIcons(icons);

    CreateControls();

	// Create List Pane Items
    m_pList->InsertColumn(COLUMN_PROJECT, _("Project"), wxLIST_FORMAT_LEFT, 109);
    m_pList->InsertColumn(COLUMN_TIME, _("Time"), wxLIST_FORMAT_LEFT, 130);
    m_pList->InsertColumn(COLUMN_MESSAGE, _("Message"), wxLIST_FORMAT_LEFT, 378);

    m_pMessageInfoAttr = new wxListItemAttr(
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT),
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW),
        wxNullFont
    );
    m_pMessageErrorAttr = new wxListItemAttr(
        *wxRED,
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW),
        wxNullFont
    );
#if EVENT_LOG_STRIPES
    m_pMessageInfoGrayAttr = new wxListItemAttr(
        wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT),
        wxColour(240, 240, 240),
        wxNullFont
    );
    m_pMessageErrorGrayAttr = new wxListItemAttr(*wxRED, wxColour(240, 240, 240), wxNullFont);
#else
    m_pMessageInfoGrayAttr = new wxListItemAttr(*m_pMessageInfoAttr);
    m_pMessageErrorGrayAttr = new wxListItemAttr(*m_pMessageErrorAttr);
#endif

    SetTextColor();
    RestoreState();

    return true;
}