Ejemplo n.º 1
0
void DockWindow::FloatAnimate(DockCont &dc, Rect target)
{
	int max = dockpane[0].GetAnimMaxTicks();
	dc.IgnoreMinSize(true);
	Rect dr = dc.GetRect();
	target -= dr;
	target.top += 16; // Fudge for titlebar. Should get from OS?
	target.left /= max;
	target.right /= max;
	target.top /= max;
	target.bottom /= max;
	for (int i = 0; i < max; i++) {
		dr += target;
		dc.SetRect(dr);
		ProcessEvents();
		Sleep(dockpane[0].GetAnimInterval());
	}
	dc.IgnoreMinSize(false);
}
Ejemplo n.º 2
0
void Player::Update(sf::Time deltaTime)
{
    ProcessEvents();
    float seconds = deltaTime.asSeconds();
    if (rotation_ != 0)
    {
        float angle = rotation_ * 250 * seconds;
        sprite_.rotate(angle);
    }
    if (is_moving_)
    {
        float angle = sprite_.getRotation() / 180 * M_PI - M_PI / 2;
        speed_ = sf::Vector2f(Configuration::max_speed_ * std::cos(angle), Configuration::max_speed_ * std::sin(angle));
        //speed_ += sf::Vector2f(std::cos(angle), std::sin(angle)) * 100.f * seconds; //ship like movement
    }
    sprite_.move(seconds * speed_);
    rotation_ = 0;
    //is_moving_ = 0;
}
Ejemplo n.º 3
0
void Threads::Process(const FractalJobHandeler & job)
{
	ProgressInfo statTotal(statusBar);

	rows = inp_row.GetData();
	cols = inp_col.GetData();
	densityR = picbox.GetSize().cy / rows;
	densityC = picbox.GetSize().cx / cols;
	maxIter = inp_iter.GetData();
	logmax= log10((double)maxIter);
	max_threads = inp_threads.GetData();
	
	statTotal.Set(0,rows*cols);
	
	TimeStop startTime;
	
	for (int r = 0; r < rows; r++){
		for (int c = 0; c < cols; c++)
		{
			while(threads >= max_threads)
				waitforfinish.Wait();
			
			AtomicInc(threads);
			Thread().Run(callback4(this, &Threads::ThreadRenderJob, r, c, job, 0));
			
			INTERLOCKED_(job_lock)
				active.Add((r * cols + c), 0);
			
			statTotal.Text(Format("Invoking calculations for sector R:%02d  C:%02d",r,c));
			time.Set(FormatTS(startTime.Elapsed()));
			picbox.Refresh();
			statTotal.Set(r * cols + c,rows*cols);
			ProcessEvents();
		}
	}
	
	while(threads > 0)
		waitforfinish.Wait();

	time.Set(FormatTS(startTime.Elapsed()));
	picbox.Refresh();
}
Ejemplo n.º 4
0
String Gdb::Cmd(const char *command)
{
	if(!dbg || !dbg->IsRunning() || IdeIsDebugLock()) return Null;
#ifdef _DEBUG
	TimeStop ts;
#endif
	Lock();
	if(command) {
		LLOG("========= Cmd: " << command);
		dbg->Write(String(command) + "\n");
		PutVerbose(command);
	}
	String result;
	int ms0 = msecs();
	while(dbg) {
		String s;
		if(!dbg->Read(s)) {
			PutVerbose(result);
			PutVerbose("Debugger terminated");
			break;
		}
		if(!s.IsEmpty() && Result(result, s)) {
			LLOG(result);
			PutVerbose(result);
			break;
		}
		if(ms0 != msecs()) {
			ProcessEvents();
			ms0 = msecs();
		}
//		if(s.GetCount() == 0)
			GuiSleep(0);
		if(TTYQuit())
			Stop();
	}
	Unlock();
#ifdef _DEBUG
	if(command)
		LLOG("Cmd Time of `" << command <<"` " << ts);
#endif
	return result;
}
Ejemplo n.º 5
0
int main(int argc, char* argv[])
{ //Start SDL 
	engine.NMSInit(WIDTH,HEIGHT,16,"Nemesis Engine",false);
	obj.LoadModel("models/drfreak/drfreak.md2","models/drfreak/drfreak.tga");
	obj.SetAnim(BOOM);
	//TEXMANAGER.LoadTexture("Texture.tga",5666); //Load the crate model
	while(true)
	{
		ProcessEvents(); // elabora gli eventi
		if(engine.running)
		{
			DrawScene(); // Draw the scene
			engine.CalculateFrameRate(); // Calculate the framerate
		}
		else
			break;
	}
	engine.NMSQuit();
	return 0; 
};
Ejemplo n.º 6
0
bool ClassDemoApp::UpdateAndRender() {
    float ticks = (float)SDL_GetTicks() / 1000.0f;
    float elapsed = ticks - lastFrameTicks;
    lastFrameTicks = ticks;

    float fixedElapsed = elapsed + timeLeftOver;
    if (fixedElapsed > FIXED_TIMESTEP * MAX_TIMESTEPS) {
        fixedElapsed = FIXED_TIMESTEP * MAX_TIMESTEPS;
    }
    while (fixedElapsed >=FIXED_TIMESTEP) {
        fixedElapsed -= FIXED_TIMESTEP;
        Update(FIXED_TIMESTEP);
    }
    timeLeftOver = fixedElapsed;

    ProcessEvents();
//    Update(elapsed);

    return done;
}
Ejemplo n.º 7
0
bool GameApp::UpdateAndRender(){
	
	float ticks = (float)SDL_GetTicks() / 1000.0f;
	float elapsed = ticks - lastFrameTicks;
	lastFrameTicks = ticks;
	ProcessEvents();
	EnemyActions();
	
	float fixed_elapsed = elapsed;
	if (fixed_elapsed > MAX_TIMESTEP * FIXED_TIMESTEP){
		fixed_elapsed = MAX_TIMESTEP*FIXED_TIMESTEP;
	}
	while (fixed_elapsed >= FIXED_TIMESTEP){
		fixed_elapsed -= FIXED_TIMESTEP;
		Update(FIXED_TIMESTEP);
	}
	Update(fixed_elapsed);
	Render();
	return done;
}
Ejemplo n.º 8
0
		void Game::Run()
		{
			sf::Clock clock;
			sf::Time timeSinceLastUpdate = sf::Time::Zero;

			while (mWindow.isOpen())
			{
				sf::Time elapsedTime = clock.restart();
				timeSinceLastUpdate += elapsedTime;
				while (timeSinceLastUpdate > TimePerFrame)
				{
					timeSinceLastUpdate -= TimePerFrame;

					ProcessEvents();
					Update(TimePerFrame);
				}

				UpdateStatistics(elapsedTime);
				Render();
			}
		}
Ejemplo n.º 9
0
void StartProgram(RenderWindow & window, Pendulum & pendulum)
{
	Clock frameClock;
	int timeSinceLastFrame;

	while (window.isOpen())
	{
		timeSinceLastFrame = frameClock.getElapsedTime().asMilliseconds();
		ProcessEvents(window);
		if (timeSinceLastFrame >= TIME_PER_FRAME)
		{
			frameClock.restart();

			ComputePhysics(pendulum);
			UpdatePendulum(pendulum);

			window.clear(Color::White);
			Draw(window, pendulum);
			window.display();
		}
	}
};
Ejemplo n.º 10
0
bool
XInterface::CheckActivity()
{
	setjmp(jmp);
	if(!g_connected)
	{
		// If we can't connect, we don't know anything....
		if( Connect() == false )
		{
			return false;
		}
	}
	
	bool cursor_active = false;
	bool xss_active = false;

	bool input_active = ProcessEvents();
	if ( ! input_active)
	{
		// TJ: the old code didn't check for pointer movement when there were events -- but I'm not sure that's the right thing to do.
		cursor_active = QueryPointer();
		xss_active = QuerySSExtension();
	}

	if (input_active || cursor_active || xss_active) {
		if (input_active) {
			dprintf(D_FULLDEBUG,"saw input_active\n");
		}
		if (cursor_active) {
			dprintf(D_FULLDEBUG,"saw cursor active\n");
		}
		if (xss_active) {
			dprintf(D_FULLDEBUG,"screensaver reported recent activity\n");
		}
	} else {
		dprintf(D_FULLDEBUG,"saw Idle for %.3f sec\n", (double)time(NULL) - _last_event);
	}
	return input_active || cursor_active;
}
Ejemplo n.º 11
0
int
MT_WaitForTasks(gboolean(*pCallback) (gpointer), int callbackTime, int autosave)
{
    int callbackLoops = callbackTime / UI_UPDATETIME;
    int waits = 0;
    int polltime = callbackLoops ? UI_UPDATETIME : callbackTime;
    guint as_source = 0;

    /* Set total tasks to wait for */
    td.totalTasks = td.addedTasks;
#if USE_GTK
    GTKSuspendInput();
#endif

    if (autosave)
        as_source = g_timeout_add(nAutoSaveTime * 60000, save_autosave, NULL);
    multi_debug("Waiting for all tasks");
    while (!WaitForAllTasks(polltime)) {
        waits++;
        if (pCallback && waits >= callbackLoops) {
            waits = 0;
            pCallback(NULL);
        }
        ProcessEvents();
    }
    if (autosave) {
        g_source_remove(as_source);
        save_autosave(NULL);
    }
    multi_debug("Done waiting for all tasks");

    td.doneTasks = td.addedTasks = 0;
    td.totalTasks = -1;

#if USE_GTK
    GTKResumeInput();
#endif
    return td.result;
}
Ejemplo n.º 12
0
static void DOT_StartupWindow(void)
{

  WindoW  w;
  GrouP   c, cg;
  DOTStartDataPtr sdata;
  PaneL   p;

  w = FixedWindow (-50, -33, -10, -10, "Welcome to D-Viewer", StdCloseWindowProc);

  p = SimplePanel (w, 28 * stdCharWidth, 4 * stdLineHeight, DOT_DrawAbout);
  sdata=(DOTStartDataPtr)MemNew(sizeof(DOTStartData));
  sdata->hStart=w;
  cg=HiddenGroup(w, 4, 0, NULL);
  sdata->dot=CheckBox(cg, "Dot plot", DOT_CheckDot);
  SetStatus(sdata->dot, TRUE);
  
  sdata->reg_blast=CheckBox(cg, "Bl2Seqs", DOT_CheckRegBlast);
  SetStatus(sdata->reg_blast, FALSE);
  sdata->auto_blast = CheckBox(cg, "Scoop", DOT_CheckAutoBlast);
  SetStatus(sdata->auto_blast, FALSE);

  sdata->seqa=CheckBox(cg, "SeqAnnote File", DOT_CheckSA);
  SetStatus(sdata->seqa, FALSE);
  c = HiddenGroup (w, 1, 3, NULL);
  SetGroupMargins(c, 10, 10);
  SetGroupSpacing (c, 10, 10);
  sdata->entrez=PushButton (c, "Fetch from Entrez", DOT_GetFromNetwork);
  Enable(sdata->entrez);
  sdata->file=PushButton (c, "Open Local Files", DOT_readExisting);
  Enable(sdata->file);
  PushButton (c, "Quit Program", DOT_quitProgram);
    
  SetObjectExtra(w, (Pointer)sdata, StdCleanupExtraProc);
  AlignObjects (ALIGN_CENTER, (HANDLE) p, (HANDLE) c, NULL,  NULL);
  Select(w);
  Show(w);
  ProcessEvents();
}
Ejemplo n.º 13
0
void StartProgram(RenderWindow & window, Car & car, Physics & physics, const RectangleShape & ground)
{
	Clock frameClock;
	int timeSinceLastFrame;

	while (window.isOpen())
	{
		timeSinceLastFrame = frameClock.getElapsedTime().asMilliseconds();
		ProcessEvents(window);
		if (timeSinceLastFrame >= TIME_PER_FRAME)
		{
			frameClock.restart();

			ComputePhysics(physics);
			UpdateCar(car, physics);

			window.clear(Color::White);
			Draw(window, car, ground);
			window.display();
		}
	}
}
bool ExponentialTransformationInterface::GenerateRealTimePreview( UInt16Image& image, const View& view, int zoomLevel, String& ) const
{
   m_realTimeThread = new RealTimeThread;

   for ( ;; )
   {
      ExponentialTransformationInstance previewInstance( instance );
      if ( zoomLevel < 0 )
         previewInstance.sigma /= -zoomLevel;

      m_realTimeThread->Reset( image, previewInstance );
      m_realTimeThread->Start();

      while ( m_realTimeThread->IsActive() )
      {
         ProcessEvents();

         if ( !IsRealTimePreviewActive() )
         {
            m_realTimeThread->Abort();
            m_realTimeThread->Wait();

            delete m_realTimeThread;
            m_realTimeThread = 0;
            return false;
         }
      }

      if ( !m_realTimeThread->IsAborted() )
      {
         image.Assign( m_realTimeThread->m_image );

         delete m_realTimeThread;
         m_realTimeThread = 0;
         return true;
      }
   }
}
Ejemplo n.º 15
0
		ReturnValue WindowsEventLoop::Run(ActivityHandler* pActivityHandler)
		{
			m_pActivityHandler = pActivityHandler;
			m_isRunning=true;

			InitializeDisplay();
			m_pActivityHandler->onActivate();

			// Global step loop.
			while(m_isRunning)
			{
				ProcessEvents();
				if(m_pActivityHandler->onStep() != RETURN_VALUE_OK)
				{
					m_isRunning=false;
				}
				SwapBuffers();
			}

			m_pActivityHandler->onDeactivate();
			DestroyDisplay();
			return RETURN_VALUE_OK;
		}
Ejemplo n.º 16
0
int
MT_WaitForTasks(gboolean(*pCallback) (gpointer), int callbackTime, int autosave)
{
    GList *member;
    guint cb_source = 0;
    guint as_source = 0;
    td.doneTasks = 0;

#if USE_GTK
    GTKSuspendInput();
#endif

    multi_debug("Waiting for all tasks");

    pCallback(NULL);
    cb_source = g_timeout_add(1000, pCallback, NULL);
    if (autosave)
        as_source = g_timeout_add(nAutoSaveTime * 60000, save_autosave, NULL);
    for (member = g_list_first(td.tasks); member; member = member->next, td.doneTasks++) {
        Task *task = member->data;
        task->fun(task->data);
        free(task->pLinkedTask);
        free(task);
        ProcessEvents();
    }
    g_list_free(td.tasks);
    if (autosave) {
        g_source_remove(as_source);
        save_autosave(NULL);
    }
    td.tasks = NULL;

#if USE_GTK
    GTKResumeInput();
#endif
    return td.result;
}
Ejemplo n.º 17
0
///////////////////////////////////////////////////////
// RADEventsXML::ConstructXMLDoc
//
// Constructs the XML document from the RADEventList 'rel'.
// Note: the current XML document is replaced, not updated,
// by this operation.
//
// Input/Output:
//	rel	- the RADEventsList instance that is converted to an
//		XML document.
//
///////////////////////////////////////////////////////
bool RADEventsXML::ConstructXMLDoc(RADEventsList& rel)
{
	_bstr_t bstr;
	HRESULT hr;
	IXMLDOMNode *pColNode = NULL;
	IXMLDOMNode *pIXMLDOMNode = NULL;

	if (this->m_pXMLDom != NULL) 
	{
		if (this->m_pIRNode == NULL)
			//  might need to create the entire tree, the file didn't exist
			// or  might need to just create the tree down to the Events level
		{
			this->m_pIRNode = ConstructEventParentNodeTree();
		}
		if (this->m_pIRNode == NULL )
			return false;  // attempt to create IR/Events has failed

		bstr = m_xcolpath;
		HRCALL(m_pXMLDom->selectSingleNode(bstr, &pColNode), "selectSingleNode");

		if (pColNode == NULL)
		{
			pColNode = ConstructColumnsNode();
			if (pColNode)
			{
				HRCALL(m_pIRNode->appendChild(pColNode,&pIXMLDOMNode), ""); 
				AddWhiteSpaceToNode(bstr_wsnt, m_pIRNode);
			} else // if (pColNode == NULL)
				return false; // forced re-selection of the newly constructed node tree has failed
		}
	}
	else
		return false;  // no DOM means punt
clean:
	return ProcessEvents(rel, false);  // build the event list on the IR/Events tree
}
Ejemplo n.º 18
0
int main()
{		
	//set the system to use the PLL and crank the frequency up to 72Mhz (max for processor)
	pllInit();
	
	//set up the timer used all over to wait for delays
	DelayTimerInit();
	
	
	//set up the timer used to schedule ffts
	FFTTimerInit();	
	
	//set up pins for ads communication
	InitPinsForAdsCommunication();
	
	//ads boots up with 250sps data ready pin, stop this
	stopAdsConversions();
	
	//start up the uart - bluetooth connection. Do this last in case we get something right away
	uartInit();
	
	LPC_IOCON->PIO3_2 = 0xD8;
	LPC_GPIO3->DIR |= (1<<2);
	LPC_GPIO3->DATA &= ~(1<<2);
	
	//pwup();
	//pwdnTimerInit();
	//startPwdnTimer();

	while(1)
	{
		// event processing loop to deal with deadlocks if everything were to run straight from interrupts
		ProcessEvents();
		//delay(60000);
	}
}
Ejemplo n.º 19
0
int main(int argc, char* argv[]) {
  int c;
  int ok = 0;
  for (c = 1; c < argc; ++c) {
    const char* file = NULL;
    const uint8_t* webp = NULL;
    size_t webp_size = 0;
    if (!strcmp(argv[c], "-h")) {
      printf("Usage: %s [-h] image.webp [more_files.webp...]\n", argv[0]);
      return 0;
    } else {
      file = argv[c];
    }
    if (file == NULL) continue;
    if (!ImgIoUtilReadFile(file, &webp, &webp_size)) {
      fprintf(stderr, "Error opening file: %s\n", file);
      goto Error;
    }
    if (webp_size != (size_t)(int)webp_size) {
      fprintf(stderr, "File too large.\n");
      goto Error;
    }
    ok = WebpToSDL((const char*)webp, (int)webp_size);
    free((void*)webp);
    if (!ok) {
      fprintf(stderr, "Error decoding file %s\n", file);
      goto Error;
    }
    ProcessEvents();
  }
  ok = 1;

 Error:
  SDL_Quit();
  return ok ? 0 : 1;
}
Ejemplo n.º 20
0
void ComidaGame::Loop(){

	wnd->setFramerateLimit(60);

	wnd->setVisible(true);

	while(wnd->isOpen()){
	
		if(!ProcessEvents())
			return;

		//updates
		tablero->Update();


		wnd->clear();

		//draws
		tablero->Draw(wnd);

		wnd->display();
	
	}
}
Ejemplo n.º 21
0
void Ide::DoProcessEvents()
{
    ProcessEvents();
}
Ejemplo n.º 22
0
void cyclic_space::step()
{
    calculate();
    Refresh();
    ProcessEvents();
}
Ejemplo n.º 23
0
int main(){
	auto pLogger = CB::Log::CLogger::GetInstance();
	pLogger->AddStream(CB::IO::File::Open(L"main.log", CB::IO::File::AccessType::WriteOnly, CB::IO::File::OpenAction::AlwaysCreate).Cast<CB::IO::IStream>());
	pLogger->AddStream(CB::IO::Console::Create().Cast<CB::IO::IStream>(), CB::Log::CTextFormatter::Create(CB::String::Encoding::ANSI).Cast<CB::Log::IEntryFormatter>());
	pLogger->SetDebugMode(true);

	try{
		auto pWinDriver = CB::Window::LoadDriver(L"MSWindowDriver");
		auto pGraphicDriver = CB::Graphic::LoadDriver(L"OGLGraphicDriver");
		{
			auto pWinManager = pWinDriver->CreateManager();
			auto pGraphicManager = pGraphicDriver->CreateManager(pWinManager);
			
			CB::Math::CSize outSize(640, 480);
			auto pWindow = pWinManager->CreateWindow(L"GraphicTest", CB::Window::Style::Single, outSize);

			auto pGraphicAdapter = pGraphicManager->GetDefaultAdapter();

			CB::Graphic::CDisplayMode dispMode(pWindow->GetSize(), 0, CB::Graphic::BufferFormat::B8G8R8X8);
			CB::Graphic::CDeviceDesc devDesc(pWindow, dispMode, CB::Graphic::BufferFormat::D24S8, false);

			CB::Collection::CList<CB::Graphic::FeatureLevel> featureLevels;
			featureLevels.Add(CB::Graphic::FeatureLevel::Level_1);

			auto pGraphicDevice = pGraphicAdapter->CreateDevice(pWindow, devDesc, featureLevels);

			pWindow->OnClose += CB::Signals::CFunc<const bool, CB::CRefPtr<CB::Window::IWindow>>(CloseEvent);

			pWindow->SetVisible(true);

			CB::Graphic::CDepthStencilStateDesc depthDesc;
			depthDesc.bDepthTestEnabled = true;
			depthDesc.uDepthFunction = CB::Graphic::CompareFunc::LessEqual;
			auto pDepthState = pGraphicDevice->CreateState(depthDesc);
			pGraphicDevice->SetState(pDepthState.Cast<CB::Graphic::IDeviceState>());

			CB::Graphic::CRasterizerStateDesc rastDesc;
			rastDesc.uCullMode = CB::Graphic::CullMode::None;
			auto pRastState = pGraphicDevice->CreateState(rastDesc);
			pGraphicDevice->SetState(pRastState.Cast<CB::Graphic::IDeviceState>());

			CB::Graphic::CBlendStateDesc blendDesc;
			blendDesc.ColorBlend.uDestOperand = CB::Graphic::BlendOption::OneMinusSourceAlpha;
			blendDesc.ColorBlend.uSourceOperand = CB::Graphic::BlendOption::SourceAlpha;
			blendDesc.ColorBlend.uOperation = CB::Graphic::BlendOperation::Add;
			blendDesc.AlphaBlend.uDestOperand = CB::Graphic::BlendOption::OneMinusSourceAlpha;
			blendDesc.AlphaBlend.uSourceOperand = CB::Graphic::BlendOption::SourceAlpha;
			blendDesc.AlphaBlend.uOperation = CB::Graphic::BlendOperation::Add;
			blendDesc.bEnabled[0] = true;
			auto pBlendState = pGraphicDevice->CreateState(blendDesc);
			pGraphicDevice->SetState(pBlendState.Cast<CB::Graphic::IDeviceState>());

			auto pFontManager = CB::Font::CManager::Create();

			auto pFontStream = CB::IO::File::Open(L"Assets/font.ttf").Cast<CB::IO::IStream>();
			auto pFont = pFontManager->Load(pFontStream);
			
			pFont->SelectFace(0);
			pFont->SetSize(24);

			CB::Collection::CList<CB::Tools::CFontCharDesc> charDescs;
			CB::Tools::CFontTextureGenerator fontGen(pGraphicDevice);

			fontGen.MaxTextureSize.Set(512, 512);
			auto pTexture = fontGen.Generate(pFont, charDescs);

			CB::Tools::CTextMeshGenerator textGen(charDescs);
			CB::Tools::CMeshRawIVT textMesh;

			textGen.Generate(L"Marek	M³ynarski!", textMesh);

			CB::Collection::CList<CB::Graphic::CVertexElement> vEls;
			vEls.Add(CB::Graphic::CVertexElement(0, L"vinput.vPosition", CB::Graphic::VertexType::Float, 3, 0));
			vEls.Add(CB::Graphic::CVertexElement(1, L"vinput.vTexCoord", CB::Graphic::VertexType::Float, 2, 0));

			GraphicTest::CShaderLoader shaders(pGraphicDevice, L"Shaders/TextureShader.cg");

			auto pTextDecl = pGraphicDevice->CreateVertexDeclaration(shaders.pVertexShader, vEls);

			auto pTextVertexBuffer = pGraphicDevice->CreateBuffer(CB::Graphic::BufferType::Vertex, CB::Graphic::BufferUsage::Dynamic, CB::Graphic::BufferAccess::Write, textMesh.Vertices);
			auto pTextTCoordBuffer = pGraphicDevice->CreateBuffer(CB::Graphic::BufferType::Vertex, CB::Graphic::BufferUsage::Dynamic, CB::Graphic::BufferAccess::Write, textMesh.TexCoords);
			auto pTextIndexBuffer = pGraphicDevice->CreateBuffer(CB::Graphic::BufferType::Index, CB::Graphic::BufferUsage::Dynamic, CB::Graphic::BufferAccess::Write, textMesh.Indices);

			float32 fAspect = (float32)outSize.Width / (float32)outSize.Height;
			CB::Math::CMatrix mProj = CB::Math::CMatrix::GetPerspective(fAspect, 60.0f, 1.0f, 100.0f);
			CB::Math::CMatrix mView = CB::Math::CMatrix::GetTranslation(-4.0f, 0.0f, -3.4f);
			CB::Math::CMatrix mModel = CB::Math::CMatrix::GetIdentity();

			shaders.pFragmentShader->SetSampler(L"texDiffuse", pTexture.Cast<CB::Graphic::IBaseTexture>());
			pTexture->SetFilters(CB::Graphic::TextureFilter::Linear, CB::Graphic::TextureFilter::Linear, CB::Graphic::TextureFilter::Linear);
			pTexture->SetAnisotropy(8);
			//g_pTexture = texture.pTexture;			

			while(g_bRun){
				pGraphicDevice->Clear(1.0f, 1);
				pGraphicDevice->Clear(CB::Math::CColor(1.0f, 0.5f, 0.0f, 1.0f));

				pGraphicDevice->BeginRender();

				pGraphicDevice->SetShader(shaders.pVertexShader);
				pGraphicDevice->SetShader(shaders.pFragmentShader);

				static float32 fV = 0.0f;
				fV += 20 * g_Timer.GetTimeDelta();
				mModel = CB::Math::CMatrix::GetRotation(CB::Math::AxisOrientation::AxisX, fV);

				shaders.pVertexShader->SetUniform(L"vinput.mProj", mProj);
				shaders.pVertexShader->SetUniform(L"vinput.mView", mView);
				shaders.pVertexShader->SetUniform(L"vinput.mModel", mModel);

				pGraphicDevice->SetVertexDeclaration(pTextDecl);
				pGraphicDevice->SetVertexBuffer(0, pTextVertexBuffer);
				pGraphicDevice->SetVertexBuffer(1, pTextTCoordBuffer);
				pGraphicDevice->SetIndexBuffer(pTextIndexBuffer);

				pGraphicDevice->RenderIndexed(textMesh.uNumberOfPolygons);

				pGraphicDevice->EndRender();

				g_Timer.Update();
				pWinManager->ProcessEvents();

				float fFPS = 1.0f / (g_Timer.GetTimeDelta() == 0.0f ? 1.0f : g_Timer.GetTimeDelta());
				uint32 uFPS = (uint32)fFPS;

				textMesh.Clear();
				textGen.Generate(L"FPS: " + CB::String::ToString(uFPS), textMesh);

				pTextVertexBuffer->LoadData(textMesh.Vertices);
				pTextTCoordBuffer->LoadData(textMesh.TexCoords);
				pTextIndexBuffer->LoadData(textMesh.Indices);

				pGraphicDevice->Swap();
			}

			g_pTexture.Release();
		}
	}
	catch(CB::Exception::CException& Exception){
		CB::Log::Write(Exception, CB::Log::LogLevel::Fatal);
		CB::Message::Show(Exception, CB::Message::Icon::Error);
	}
	return 0;
}
Ejemplo n.º 24
0
void CGameClient::OnNewSnapshot()
{
    m_NewTick = true;

    // clear out the invalid pointers
    mem_zero(&g_GameClient.m_Snap, sizeof(g_GameClient.m_Snap));
    m_Snap.m_LocalCid = -1;

    // secure snapshot
    {
        int Num = Client()->SnapNumItems(IClient::SNAP_CURRENT);
        for(int Index = 0; Index < Num; Index++)
        {
            IClient::CSnapItem Item;
            void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, Index, &Item);
            if(m_NetObjHandler.ValidateObj(Item.m_Type, pData, Item.m_DataSize) != 0)
            {
                if(g_Config.m_Debug)
                    dbg_msg("game", "invalidated index=%d type=%d (%s) size=%d id=%d", Index, Item.m_Type, m_NetObjHandler.GetObjName(Item.m_Type), Item.m_DataSize, Item.m_Id);
                Client()->SnapInvalidateItem(IClient::SNAP_CURRENT, Index);
            }
        }
    }

    ProcessEvents();

    if(g_Config.m_DbgStress)
    {
        if((Client()->GameTick()%100) == 0)
        {
            char aMessage[64];
            int MsgLen = rand()%(sizeof(aMessage)-1);
            for(int i = 0; i < MsgLen; i++)
                aMessage[i] = 'a'+(rand()%('z'-'a'));
            aMessage[MsgLen] = 0;

            CNetMsg_Cl_Say Msg;
            Msg.m_Team = rand()&1;
            Msg.m_pMessage = aMessage;
            Client()->SendPackMsg(&Msg, MSGFLAG_VITAL);
        }
    }

    // go trough all the items in the snapshot and gather the info we want
    {
        m_Snap.m_aTeamSize[0] = m_Snap.m_aTeamSize[1] = 0;

        int Num = Client()->SnapNumItems(IClient::SNAP_CURRENT);
        for(int i = 0; i < Num; i++)
        {
            IClient::CSnapItem Item;
            const void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, i, &Item);

            if(Item.m_Type == NETOBJTYPE_CLIENTINFO)
            {
                const CNetObj_ClientInfo *pInfo = (const CNetObj_ClientInfo *)pData;
                int Cid = Item.m_Id;
                IntsToStr(&pInfo->m_Name0, 6, m_aClients[Cid].m_aName);
                IntsToStr(&pInfo->m_Skin0, 6, m_aClients[Cid].m_aSkinName);

                m_aClients[Cid].m_UseCustomColor = pInfo->m_UseCustomColor;
                m_aClients[Cid].m_ColorBody = pInfo->m_ColorBody;
                m_aClients[Cid].m_ColorFeet = pInfo->m_ColorFeet;

                // prepare the info
                if(m_aClients[Cid].m_aSkinName[0] == 'x' || m_aClients[Cid].m_aSkinName[1] == '_')
                    str_copy(m_aClients[Cid].m_aSkinName, "default", 64);

                m_aClients[Cid].m_SkinInfo.m_ColorBody = m_pSkins->GetColor(m_aClients[Cid].m_ColorBody);
                m_aClients[Cid].m_SkinInfo.m_ColorFeet = m_pSkins->GetColor(m_aClients[Cid].m_ColorFeet);
                m_aClients[Cid].m_SkinInfo.m_Size = 64;

                // find new skin
                m_aClients[Cid].m_SkinId = g_GameClient.m_pSkins->Find(m_aClients[Cid].m_aSkinName);
                if(m_aClients[Cid].m_SkinId < 0)
                {
                    m_aClients[Cid].m_SkinId = g_GameClient.m_pSkins->Find("default");
                    if(m_aClients[Cid].m_SkinId < 0)
                        m_aClients[Cid].m_SkinId = 0;
                }

                if(m_aClients[Cid].m_UseCustomColor)
                    m_aClients[Cid].m_SkinInfo.m_Texture = g_GameClient.m_pSkins->Get(m_aClients[Cid].m_SkinId)->m_ColorTexture;
                else
                {
                    m_aClients[Cid].m_SkinInfo.m_Texture = g_GameClient.m_pSkins->Get(m_aClients[Cid].m_SkinId)->m_OrgTexture;
                    m_aClients[Cid].m_SkinInfo.m_ColorBody = vec4(1,1,1,1);
                    m_aClients[Cid].m_SkinInfo.m_ColorFeet = vec4(1,1,1,1);
                }

                m_aClients[Cid].UpdateRenderInfo();
                g_GameClient.m_Snap.m_NumPlayers++;

            }
            else if(Item.m_Type == NETOBJTYPE_PLAYERINFO)
            {
                const CNetObj_PlayerInfo *pInfo = (const CNetObj_PlayerInfo *)pData;

                m_aClients[pInfo->m_ClientId].m_Team = pInfo->m_Team;
                m_Snap.m_paPlayerInfos[pInfo->m_ClientId] = pInfo;

                if(pInfo->m_Local)
                {
                    m_Snap.m_LocalCid = Item.m_Id;
                    m_Snap.m_pLocalInfo = pInfo;

                    if (pInfo->m_Team == -1)
                        m_Snap.m_Spectate = true;
                }

                // calculate team-balance
                if(pInfo->m_Team != -1)
                    m_Snap.m_aTeamSize[pInfo->m_Team]++;

            }
            else if(Item.m_Type == NETOBJTYPE_CHARACTER)
            {
                const void *pOld = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_CHARACTER, Item.m_Id);
                if(pOld)
                {
                    m_Snap.m_aCharacters[Item.m_Id].m_Active = true;
                    m_Snap.m_aCharacters[Item.m_Id].m_Prev = *((const CNetObj_Character *)pOld);
                    m_Snap.m_aCharacters[Item.m_Id].m_Cur = *((const CNetObj_Character *)pData);

                    if(m_Snap.m_aCharacters[Item.m_Id].m_Prev.m_Tick)
                        Evolve(&m_Snap.m_aCharacters[Item.m_Id].m_Prev, Client()->PrevGameTick());
                    if(m_Snap.m_aCharacters[Item.m_Id].m_Cur.m_Tick)
                        Evolve(&m_Snap.m_aCharacters[Item.m_Id].m_Cur, Client()->GameTick());
                }
            }
            else if(Item.m_Type == NETOBJTYPE_GAME)
                m_Snap.m_pGameobj = (CNetObj_Game *)pData;
            else if(Item.m_Type == NETOBJTYPE_FLAG)
                m_Snap.m_paFlags[Item.m_Id%2] = (const CNetObj_Flag *)pData;
        }
    }

    // setup local pointers
    if(m_Snap.m_LocalCid >= 0)
    {
        CSnapState::CCharacterInfo *c = &m_Snap.m_aCharacters[m_Snap.m_LocalCid];
        if(c->m_Active)
        {
            m_Snap.m_pLocalCharacter = &c->m_Cur;
            m_Snap.m_pLocalPrevCharacter = &c->m_Prev;
            m_LocalCharacterPos = vec2(m_Snap.m_pLocalCharacter->m_X, m_Snap.m_pLocalCharacter->m_Y);
        }
    }
    else
        m_Snap.m_Spectate = true;

    CTuningParams StandardTuning;
    CServerInfo CurrentServerInfo;
    Client()->GetServerInfo(&CurrentServerInfo);
    if(CurrentServerInfo.m_aGameType[0] != '0')
    {
        if(str_comp(CurrentServerInfo.m_aGameType, "DM") != 0 && str_comp(CurrentServerInfo.m_aGameType, "TDM") != 0 && str_comp(CurrentServerInfo.m_aGameType, "CTF") != 0)
            m_ServerMode = SERVERMODE_MOD;
        else if(mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) == 0)
            m_ServerMode = SERVERMODE_PURE;
        else
            m_ServerMode = SERVERMODE_PUREMOD;
    }


    // update render info
    for(int i = 0; i < MAX_CLIENTS; i++)
        m_aClients[i].UpdateRenderInfo();
}
Ejemplo n.º 25
0
int main(int argc, char *argv[])
{
	
	SDL_Event event;
	bool done = false;
	float lastFrameTicks = 0.0f;
	float ball_angle = 0.0f;
	srand(time(NULL));

	Matrix projectionMatrix;
	Matrix viewMatrix;
	Setup(&displayWindow, &projectionMatrix);

	GLuint paddle = LoadTexture("blue_panel.png", GL_RGBA);

	Matrix leftM;
	Entity leftPaddle(paddle);
	leftPaddle.width = 0.3f;
	leftPaddle.x = -3.2f;
	leftPaddle.speed = 2.0f;

	Matrix rightM;
	Entity rightPaddle(paddle);
	rightPaddle.width = 0.3f;
	rightPaddle.x = 3.2f;
	rightPaddle.speed = 2.0f;

	Matrix ballM;
	GLuint ballT = LoadTexture("green_panel.png", GL_RGBA);
	Entity ball(ballT);
	ball.height = 0.25f;
	ball.width = 0.25f;
	ball.speed = 3.0f;
	if (rand() % 1){
		ball_angle = (rand() % 90 + 135);
	}
	else{
		ball_angle = (rand() % 90 + 316);
	}

	std::vector<Entity> entities;
	entities.push_back(leftPaddle);
	entities.push_back(rightPaddle);


	std::vector<Matrix> modelM;
	modelM.push_back(leftM);
	modelM.push_back(rightM);


	ShaderProgram program(RESOURCE_FOLDER"vertex_textured.glsl", RESOURCE_FOLDER"fragment_textured.glsl");

	glUseProgram(program.programID);
	
	while (!done) {
		

		float ticks = (float)SDL_GetTicks() / 1000.0f;
		float elapsed = ticks - lastFrameTicks;
		lastFrameTicks = ticks;
		ProcessEvents(&event, &done, elapsed, entities);

		Update(entities,ball,ball_angle,elapsed);
		glClear(GL_COLOR_BUFFER_BIT);

		Render(&program, &projectionMatrix,&viewMatrix, modelM, entities,ball,ballM);
		
	}
	
	SDL_Quit();
	return 0;
}
Ejemplo n.º 26
0
void CGameClient::OnNewSnapshot()
{
	m_NewTick = true;

	// clear out the invalid pointers
	mem_zero(&g_GameClient.m_Snap, sizeof(g_GameClient.m_Snap));
	m_Snap.m_LocalClientID = -1;

	// secure snapshot
	{
		int Num = Client()->SnapNumItems(IClient::SNAP_CURRENT);
		for(int Index = 0; Index < Num; Index++)
		{
			IClient::CSnapItem Item;
			void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, Index, &Item);
			if(m_NetObjHandler.ValidateObj(Item.m_Type, pData, Item.m_DataSize) != 0)
			{
				if(g_Config.m_Debug)
				{
					char aBuf[256];
					str_format(aBuf, sizeof(aBuf), "invalidated index=%d type=%d (%s) size=%d id=%d", Index, Item.m_Type, m_NetObjHandler.GetObjName(Item.m_Type), Item.m_DataSize, Item.m_ID);
					Console()->Print(IConsole::OUTPUT_LEVEL_DEBUG, "game", aBuf);
				}
				Client()->SnapInvalidateItem(IClient::SNAP_CURRENT, Index);
			}
		}
	}

	ProcessEvents();

	if(g_Config.m_DbgStress)
	{
		if((Client()->GameTick()%100) == 0)
		{
			char aMessage[64];
			int MsgLen = rand()%(sizeof(aMessage)-1);
			for(int i = 0; i < MsgLen; i++)
				aMessage[i] = 'a'+(rand()%('z'-'a'));
			aMessage[MsgLen] = 0;

			CNetMsg_Cl_Say Msg;
			Msg.m_Team = rand()&1;
			Msg.m_pMessage = aMessage;
			Client()->SendPackMsg(&Msg, MSGFLAG_VITAL);
		}
	}

	// go trough all the items in the snapshot and gather the info we want
	{
		m_Snap.m_aTeamSize[TEAM_RED] = m_Snap.m_aTeamSize[TEAM_BLUE] = 0;

		int Num = Client()->SnapNumItems(IClient::SNAP_CURRENT);
		for(int i = 0; i < Num; i++)
		{
			IClient::CSnapItem Item;
			const void *pData = Client()->SnapGetItem(IClient::SNAP_CURRENT, i, &Item);

			if(Item.m_Type == NETOBJTYPE_CLIENTINFO)
			{
				const CNetObj_ClientInfo *pInfo = (const CNetObj_ClientInfo *)pData;
				int ClientID = Item.m_ID;
				IntsToStr(&pInfo->m_Name0, 4, m_aClients[ClientID].m_aName);
				IntsToStr(&pInfo->m_Clan0, 3, m_aClients[ClientID].m_aClan);
				m_aClients[ClientID].m_Country = pInfo->m_Country;
				IntsToStr(&pInfo->m_Skin0, 6, m_aClients[ClientID].m_aSkinName);

				m_aClients[ClientID].m_UseCustomColor = pInfo->m_UseCustomColor;
				m_aClients[ClientID].m_ColorBody = pInfo->m_ColorBody;
				m_aClients[ClientID].m_ColorFeet = pInfo->m_ColorFeet;

				// prepare the info
				if(m_aClients[ClientID].m_aSkinName[0] == 'x' || m_aClients[ClientID].m_aSkinName[1] == '_')
					str_copy(m_aClients[ClientID].m_aSkinName, "default", 64);

				m_aClients[ClientID].m_SkinInfo.m_ColorBody = m_pSkins->GetColorV4(m_aClients[ClientID].m_ColorBody);
				m_aClients[ClientID].m_SkinInfo.m_ColorFeet = m_pSkins->GetColorV4(m_aClients[ClientID].m_ColorFeet);
				m_aClients[ClientID].m_SkinInfo.m_Size = 64;

				// find new skin
				m_aClients[ClientID].m_SkinID = g_GameClient.m_pSkins->Find(m_aClients[ClientID].m_aSkinName);
				if(m_aClients[ClientID].m_SkinID < 0)
				{
					m_aClients[ClientID].m_SkinID = g_GameClient.m_pSkins->Find("default");
					if(m_aClients[ClientID].m_SkinID < 0)
						m_aClients[ClientID].m_SkinID = 0;
				}

				if(m_aClients[ClientID].m_UseCustomColor)
					m_aClients[ClientID].m_SkinInfo.m_Texture = g_GameClient.m_pSkins->Get(m_aClients[ClientID].m_SkinID)->m_ColorTexture;
				else
				{
					m_aClients[ClientID].m_SkinInfo.m_Texture = g_GameClient.m_pSkins->Get(m_aClients[ClientID].m_SkinID)->m_OrgTexture;
					m_aClients[ClientID].m_SkinInfo.m_ColorBody = vec4(1,1,1,1);
					m_aClients[ClientID].m_SkinInfo.m_ColorFeet = vec4(1,1,1,1);
				}

				m_aClients[ClientID].UpdateRenderInfo();

			}
			else if(Item.m_Type == NETOBJTYPE_PLAYERINFO)
			{
				const CNetObj_PlayerInfo *pInfo = (const CNetObj_PlayerInfo *)pData;

				m_aClients[pInfo->m_ClientID].m_Team = pInfo->m_Team;
				m_aClients[pInfo->m_ClientID].m_Active = true;
				m_Snap.m_paPlayerInfos[pInfo->m_ClientID] = pInfo;
				m_Snap.m_NumPlayers++;

				if(pInfo->m_Local)
				{
					m_Snap.m_LocalClientID = Item.m_ID;
					m_Snap.m_pLocalInfo = pInfo;

					if(pInfo->m_Team == TEAM_SPECTATORS)
					{
						m_Snap.m_SpecInfo.m_Active = true;
						m_Snap.m_SpecInfo.m_SpectatorID = SPEC_FREEVIEW;
					}
				}

				// calculate team-balance
				if(pInfo->m_Team != TEAM_SPECTATORS)
					m_Snap.m_aTeamSize[pInfo->m_Team]++;

			}
			else if(Item.m_Type == NETOBJTYPE_CHARACTER)
			{
				const void *pOld = Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_CHARACTER, Item.m_ID);
				m_Snap.m_aCharacters[Item.m_ID].m_Cur = *((const CNetObj_Character *)pData);
				if(pOld)
				{
					m_Snap.m_aCharacters[Item.m_ID].m_Active = true;
					m_Snap.m_aCharacters[Item.m_ID].m_Prev = *((const CNetObj_Character *)pOld);

					if(m_Snap.m_aCharacters[Item.m_ID].m_Prev.m_Tick)
						Evolve(&m_Snap.m_aCharacters[Item.m_ID].m_Prev, Client()->PrevGameTick());
					if(m_Snap.m_aCharacters[Item.m_ID].m_Cur.m_Tick)
						Evolve(&m_Snap.m_aCharacters[Item.m_ID].m_Cur, Client()->GameTick());
				}
			}
			else if(Item.m_Type == NETOBJTYPE_SPECTATORINFO)
			{
				m_Snap.m_pSpectatorInfo = (const CNetObj_SpectatorInfo *)pData;
				m_Snap.m_pPrevSpectatorInfo = (const CNetObj_SpectatorInfo *)Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_SPECTATORINFO, Item.m_ID);

				m_Snap.m_SpecInfo.m_SpectatorID = m_Snap.m_pSpectatorInfo->m_SpectatorID;
			}
			else if(Item.m_Type == NETOBJTYPE_GAMEINFO)
			{
				static bool s_GameOver = 0;
				m_Snap.m_pGameInfoObj = (const CNetObj_GameInfo *)pData;
				if(!s_GameOver && m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER)
					OnGameOver();
				else if(s_GameOver && !(m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER))
					OnStartGame();
				s_GameOver = m_Snap.m_pGameInfoObj->m_GameStateFlags&GAMESTATEFLAG_GAMEOVER;
			}
			else if(Item.m_Type == NETOBJTYPE_GAMEDATA)
			{
				m_Snap.m_pGameDataObj = (const CNetObj_GameData *)pData;
				m_Snap.m_GameDataSnapID = Item.m_ID;
				if(m_Snap.m_pGameDataObj->m_FlagCarrierRed == FLAG_TAKEN)
				{
					if(m_FlagDropTick[TEAM_RED] == 0)
						m_FlagDropTick[TEAM_RED] = Client()->GameTick();
				}
				else if(m_FlagDropTick[TEAM_RED] != 0)
						m_FlagDropTick[TEAM_RED] = 0;
				if(m_Snap.m_pGameDataObj->m_FlagCarrierBlue == FLAG_TAKEN)
				{
					if(m_FlagDropTick[TEAM_BLUE] == 0)
						m_FlagDropTick[TEAM_BLUE] = Client()->GameTick();
				}
				else if(m_FlagDropTick[TEAM_BLUE] != 0)
						m_FlagDropTick[TEAM_BLUE] = 0;
			}
			else if(Item.m_Type == NETOBJTYPE_FLAG)
				m_Snap.m_paFlags[Item.m_ID%2] = (const CNetObj_Flag *)pData;
		}
	}

	// setup local pointers
	if(m_Snap.m_LocalClientID >= 0)
	{
		CSnapState::CCharacterInfo *c = &m_Snap.m_aCharacters[m_Snap.m_LocalClientID];
		if(c->m_Active)
		{
			m_Snap.m_pLocalCharacter = &c->m_Cur;
			m_Snap.m_pLocalPrevCharacter = &c->m_Prev;
			m_LocalCharacterPos = vec2(m_Snap.m_pLocalCharacter->m_X, m_Snap.m_pLocalCharacter->m_Y);
		}
		else if(Client()->SnapFindItem(IClient::SNAP_PREV, NETOBJTYPE_CHARACTER, m_Snap.m_LocalClientID))
		{
			// player died
			m_pControls->OnPlayerDeath();
		}
	}
	else
	{
		m_Snap.m_SpecInfo.m_Active = true;
		if(Client()->State() == IClient::STATE_DEMOPLAYBACK && DemoPlayer()->GetDemoType() == IDemoPlayer::DEMOTYPE_SERVER &&
			m_DemoSpecID != SPEC_FREEVIEW && m_Snap.m_aCharacters[m_DemoSpecID].m_Active)
			m_Snap.m_SpecInfo.m_SpectatorID = m_DemoSpecID;
		else
			m_Snap.m_SpecInfo.m_SpectatorID = SPEC_FREEVIEW;
	}

	// clear out unneeded client data
	for(int i = 0; i < MAX_CLIENTS; ++i)
	{
		if(!m_Snap.m_paPlayerInfos[i] && m_aClients[i].m_Active)
			m_aClients[i].Reset();
	}

	// update friend state
	for(int i = 0; i < MAX_CLIENTS; ++i)
	{
		if(i == m_Snap.m_LocalClientID || !m_Snap.m_paPlayerInfos[i] || !Friends()->IsFriend(m_aClients[i].m_aName, m_aClients[i].m_aClan, true))
			m_aClients[i].m_Friend = false;
		else
			m_aClients[i].m_Friend = true;
	}

	// sort player infos by score
	mem_copy(m_Snap.m_paInfoByScore, m_Snap.m_paPlayerInfos, sizeof(m_Snap.m_paInfoByScore));
	for(int k = 0; k < MAX_CLIENTS-1; k++) // ffs, bubblesort
	{
		for(int i = 0; i < MAX_CLIENTS-k-1; i++)
		{
			if(m_Snap.m_paInfoByScore[i+1] && (!m_Snap.m_paInfoByScore[i] || m_Snap.m_paInfoByScore[i]->m_Score < m_Snap.m_paInfoByScore[i+1]->m_Score))
			{
				const CNetObj_PlayerInfo *pTmp = m_Snap.m_paInfoByScore[i];
				m_Snap.m_paInfoByScore[i] = m_Snap.m_paInfoByScore[i+1];
				m_Snap.m_paInfoByScore[i+1] = pTmp;
			}
		}
	}
	// sort player infos by team
	int Teams[3] = { TEAM_RED, TEAM_BLUE, TEAM_SPECTATORS };
	int Index = 0;
	for(int Team = 0; Team < 3; ++Team)
	{
		for(int i = 0; i < MAX_CLIENTS && Index < MAX_CLIENTS; ++i)
		{
			if(m_Snap.m_paPlayerInfos[i] && m_Snap.m_paPlayerInfos[i]->m_Team == Teams[Team])
				m_Snap.m_paInfoByTeam[Index++] = m_Snap.m_paPlayerInfos[i];
		}
	}

	CTuningParams StandardTuning;
	CServerInfo CurrentServerInfo;
	Client()->GetServerInfo(&CurrentServerInfo);
	if(CurrentServerInfo.m_aGameType[0] != '0')
	{
		if(str_comp(CurrentServerInfo.m_aGameType, "DM") != 0 && str_comp(CurrentServerInfo.m_aGameType, "TDM") != 0 && str_comp(CurrentServerInfo.m_aGameType, "CTF") != 0)
			m_ServerMode = SERVERMODE_MOD;
		else if(mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) == 0)
			m_ServerMode = SERVERMODE_PURE;
		else
			m_ServerMode = SERVERMODE_PUREMOD;
	}

	// add tuning to demo
	if(DemoRecorder()->IsRecording() && mem_comp(&StandardTuning, &m_Tuning, sizeof(CTuningParams)) != 0)
	{
		CMsgPacker Msg(NETMSGTYPE_SV_TUNEPARAMS);
		int *pParams = (int *)&m_Tuning;
		for(unsigned i = 0; i < sizeof(m_Tuning)/sizeof(int); i++)
			Msg.AddInt(pParams[i]);
		Client()->SendMsg(&Msg, MSGFLAG_RECORD|MSGFLAG_NOSEND);
	}

	if(!m_DDRaceMsgSent && m_Snap.m_pLocalInfo)
	{
		CNetMsg_Cl_IsDDRace Msg;
		Client()->SendPackMsg(&Msg, MSGFLAG_VITAL);
		m_DDRaceMsgSent = true;
	}

	if(m_ShowOthers == -1 || (m_ShowOthers != -1 && m_ShowOthers != g_Config.m_ClShowOthers))
	{
		// no need to send, default settings
		//if(!(m_ShowOthers == -1 && g_Config.m_ClShowOthers))
		{
			CNetMsg_Cl_ShowOthers Msg;
			Msg.m_Show = g_Config.m_ClShowOthers;
			Client()->SendPackMsg(&Msg, MSGFLAG_VITAL);
		}

		// update state
		m_ShowOthers = g_Config.m_ClShowOthers;
	}
}
Ejemplo n.º 27
0
static void Run          ( intf_thread_t *p_intf )
{
    intf_sys_t    *p_sys = p_intf->p_sys;
    mtime_t        i_last_run = mdate();

    for( ;; )
    {
        int canc = vlc_savecancel();
        vlc_mutex_lock( &p_sys->lock );

        int i_watches = vlc_array_count( p_sys->p_watches );
        struct pollfd *p_fds = calloc( i_watches, sizeof( struct pollfd ) );

        int i_fds = GetPollFds( p_intf, p_fds );

        mtime_t i_now = mdate(), i_loop_interval = i_now - i_last_run;

        msg_Dbg( p_intf,
                 "%lld µs elapsed since last wakeup",
                 (long long) i_loop_interval );

        int i_next_timeout = UpdateTimeouts( p_intf, i_loop_interval );
        i_last_run = i_now;

        vlc_mutex_unlock( &p_sys->lock );

        if( -1 != i_next_timeout )
            msg_Dbg( p_intf, "next timeout is in %d ms", i_next_timeout );
        msg_Dbg( p_intf, "Sleeping until something happens" );

        /* thread cancellation is allowed while the main loop sleeps */
        vlc_restorecancel( canc );

        int i_pollres = poll( p_fds, i_fds, i_next_timeout );
        int i_errsv   = errno;

        canc = vlc_savecancel();

        msg_Dbg( p_intf, "the main loop has been woken up" );

        if( -1 == i_pollres )
        { /* XXX: What should we do when poll() fails ? */
            char buf[64];
            msg_Err( p_intf, "poll() failed: %s", strerror_r( i_errsv, buf, 64 ) );
            free( p_fds ); p_fds = NULL;
            vlc_restorecancel( canc );
            continue;
        }

        /* Was the main loop woken up manually ? */
        if( 0 < i_pollres && ( p_fds[0].revents & POLLIN ) )
        {
            char buf;
            msg_Dbg( p_intf, "Removing a byte from the self-pipe" );
            (void)read( p_fds[0].fd, &buf, 1 );
        }

        /* We need to lock the mutex while building lists of events,
         * timeouts and watches to process but we can't keep the lock while
         * processing them, or else we risk a deadlock:
         *
         * The signal functions could lock mutex X while p_events is locked;
         * While some other function in vlc (playlist) might lock mutex X
         * and then set a variable which would call AllCallback(), which itself
         * needs to lock p_events to add a new event.
         */
        vlc_mutex_lock( &p_intf->p_sys->lock );

        /* Get the list of timeouts to process */
        unsigned int i_timeouts = vlc_array_count( p_sys->p_timeouts );
        DBusTimeout *p_timeouts[i_timeouts];
        for( unsigned int i = 0; i < i_timeouts; i++ )
        {
            p_timeouts[i] = vlc_array_item_at_index( p_sys->p_timeouts, i );
        }

        /* Get the list of watches to process */
        i_watches = vlc_array_count( p_sys->p_watches );
        DBusWatch *p_watches[i_watches];
        for( int i = 0; i < i_watches; i++ )
        {
            p_watches[i] = vlc_array_item_at_index( p_sys->p_watches, i );
        }

        /* Get the list of events to process */
        int i_events = vlc_array_count( p_intf->p_sys->p_events );
        callback_info_t* p_info[i_events];
        for( int i = i_events - 1; i >= 0; i-- )
        {
            p_info[i] = vlc_array_item_at_index( p_intf->p_sys->p_events, i );
            vlc_array_remove( p_intf->p_sys->p_events, i );
        }

        /* now we can release the lock and process what's pending */
        vlc_mutex_unlock( &p_intf->p_sys->lock );

        ProcessEvents( p_intf, p_info, i_events );
        ProcessWatches( p_intf, p_watches, i_watches, p_fds, i_fds );

        free( p_fds ); p_fds = NULL;

        ProcessTimeouts( p_intf, p_timeouts, i_timeouts );
        DispatchDBusMessages( p_intf );

        vlc_restorecancel( canc );
    }
}
Ejemplo n.º 28
0
 void CCDFrameInterface::StartExposureButton_Click(Button& sender, bool checked){
	 if (ThePixInsightINDIInterface!=0){
#if defined(WIN32) 
	  const char* tmpDir = getenv("TMP");
#else
	  const char* tmpDir = getenv("TMPDIR");
#endif
	   if (tmpDir!=NULL) {
		PixInsightINDIInstance* pInstance=&ThePixInsightINDIInterface->instance;
		if (pInstance==NULL)
			return;
		GUI->StartExposure_PushButton.Disable();
		INDIPropertyListItem uploadLocal;
		bool serverSendsImage=true;
		if (pInstance->getINDIPropertyItem(m_Device,"UPLOAD_MODE","UPLOAD_LOCAL",uploadLocal)){
			serverSendsImage=!(uploadLocal.PropertyValue==String("ON"));
		}

		for (int num=0; num<m_NumOfExposures;++num){

			GUI->ExpFrame_Edit.SetText(String(num));

			INDINewPropertyListItem newPropertyListItem;
			newPropertyListItem.Device=m_Device;
			newPropertyListItem.Property=String("CCD_EXPOSURE");
			newPropertyListItem.Element=String("CCD_EXPOSURE_VALUE");
			newPropertyListItem.PropertyType=String("INDI_NUMBER");
			newPropertyListItem.NewPropertyValue=String(m_ExposureDuration);

			GUI->ExposureDuration_Timer.Start();
			bool send_ok = pInstance->sendNewPropertyValue(newPropertyListItem,true/*isAsynchCall*/);

			if (!send_ok){
				break;
			}


			// TODO enable abort
			if (serverSendsImage){
				while (!pInstance->getImageDownloadedFlag() && !pInstance->getInternalAbortFlag()){Sleep(1);ProcessEvents();}
				pInstance->setImageDownloadedFlag(false);
			} else {
				INDIPropertyListItem ccdExposure;
				bool serverExposureIsBusy=false;
				// timimg problem: wait until server sends  BUSY
				do {
					pInstance->getINDIPropertyItem(m_Device,"CCD_EXPOSURE","CCD_EXPOSURE_VALUE",ccdExposure);
					Sleep(1);
					ProcessEvents();
					serverExposureIsBusy = ccdExposure.PropertyState==IPS_BUSY ;
				} while (!serverExposureIsBusy && (GUI->ExpDur_Edit.Text().ToFloat() < pcl_timeout) && !pInstance->getInternalAbortFlag());

				do {

					pInstance->getINDIPropertyItem(m_Device,"CCD_EXPOSURE","CCD_EXPOSURE_VALUE",ccdExposure);
					Sleep(1);
					ProcessEvents();
				} while((ccdExposure.PropertyState==IPS_BUSY)&& !pInstance->getInternalAbortFlag());
			}

			if (pInstance->getInternalAbortFlag()){
				// stop timer
				GUI->ExposureDuration_Timer.Stop();
				GUI->ExposureDelay_Timer.Stop();
				break;
			}

			if (serverSendsImage) {
				Array<ImageWindow> imgArray = ImageWindow::Open(String(tmpDir)+ String("/Image.fits"), IsoString("image"));

				if (imgArray.Length()!=0){
					imgArray[0].ZoomToFit( false ); // don't allow zoom > 1
					imgArray[0].Show();
				}

				if (m_saveFrame) {
					IsoString source = IsoString(String(tmpDir)+ String("/Image.fits"));
					IsoString dest   = IsoString(m_FrameFolder) + IsoString(this->m_FramePrefix) + IsoString("_") +  IsoString(num) + IsoString(".fits");

					std::ifstream infile(source.c_str(), std::ifstream::binary);
					std::ofstream outfile(dest.c_str(), std::ofstream::binary);

					// get size of file
					infile.seekg(0, infile.end);
					long size = infile.tellg();
					infile.seekg(0);

					// allocate memory for file content
					char* buffer = new char[size];

					// read content of infile
					infile.read(buffer, size);

					// write to outfile
					outfile.write(buffer, size);

					// release dynamically-allocated memory
					delete[] buffer;

					outfile.close();
					infile.close();
				}
			}
			// wait until next exposure
			if (GUI->ExpDelayTime_Edit.Text().ToInt()!=0){
				GUI->ExposureDelay_Timer.Start();
				m_isWaiting=true;
			}
			while (m_isWaiting){ProcessEvents();}
		}
		pInstance->setInternalAbortFlag(false);
		GUI->StartExposure_PushButton.Enable();
	   } 

	 }
 }
Ejemplo n.º 29
0
void VMenu2::Resize(bool force)
{
	if(!force && (!ProcessEvents() || SendMessage(DM_ENABLEREDRAW, -1, nullptr)<0))
	{
		NeedResize=true;
		return;
	}
	NeedResize=false;

	FarListInfo info={sizeof(FarListInfo)};
	SendMessage(DM_LISTINFO, 0, &info);


	int X1 = m_X1;
	int Y1 = m_Y1;
	if(!ShortBox)
	{
		if(X1>1)
			X1-=2;
		if(Y1>0)
			Y1-=1;
	}


	int width=info.MaxLength+(ShortBox?2:6) + 3;
	if(m_X2>0)
		width=m_X2-X1+1;

	if(width>ScrX+1)
		width=ScrX+1;


	int height=GetShowItemCount();
	if(MaxHeight && height>MaxHeight)
		height=MaxHeight;

	height+=ShortBox?2:4;
	if(m_Y2>0)
		height=m_Y2-Y1+1;


	int mh=Y1<0 ? ScrY : ScrY-Y1;

	mh+=ShortBox ? 1 : 2;

	if(mh<0)
		mh=0;
	if(height>mh)
	{
		if(m_Y2<=0 && Y1>=ScrY/2)
		{
			Y1+=ShortBox?1:3;
			if(height>Y1)
				height=Y1;
			Y1-=height;
		}
		else
			height=mh;
	}

	int X=X1;
	if(X>0 && (X+width>ScrX))
		X-=X+width-ScrX;


	COORD size;
	size.X=width;
	size.Y=height;
	SendMessage(DM_RESIZEDIALOG, true, &size);

	SMALL_RECT ipos;
	if(ShortBox)
	{
		ipos.Left=0;
		ipos.Top=0;
		ipos.Right=width-1;
		ipos.Bottom=height-1;
	}
	else
	{
		ipos.Left=2;
		ipos.Top=1;
		ipos.Right=width-3;
		ipos.Bottom=height-2;
	}
	SendMessage(DM_SETITEMPOSITION, 0, &ipos);

	COORD pos;
	pos.X=X;
	pos.Y=Y1;
	SendMessage(DM_MOVEDIALOG, true, &pos);
}
Ejemplo n.º 30
0
    int DoRun()
    {
        // we must ensure that OnExit() is called even if an exception is thrown
        // from inside ProcessEvents() but we must call it from Exit() in normal
        // situations because it is supposed to be called synchronously,
        // wxModalEventLoop depends on this (so we can't just use ON_BLOCK_EXIT or
        // something similar here)
    #if wxUSE_EXCEPTIONS
        for( ; ; )
        {
            try
            {
    #endif // wxUSE_EXCEPTIONS

                // this is the event loop itself
                for( ; ; )
                {
                    // generate and process idle events for as long as we don't
                    // have anything else to do
                    while ( !m_shouldExit && !Pending() && ProcessIdle() )
                        ;

                    if ( m_shouldExit )
                        break;

                    // a message came or no more idle processing to do, dispatch
                    // all the pending events and call Dispatch() to wait for the
                    // next message
                    if ( !ProcessEvents() )
                    {
                        // we got WM_QUIT
                        break;
                    }
                }

                // Process the remaining queued messages, both at the level of the
                // underlying toolkit level (Pending/Dispatch()) and wx level
                // (Has/ProcessPendingEvents()).
                //
                // We do run the risk of never exiting this loop if pending event
                // handlers endlessly generate new events but they shouldn't do
                // this in a well-behaved program and we shouldn't just discard the
                // events we already have, they might be important.
                for( ; ; )
                {
                    bool hasMoreEvents = false;
                    if ( wxTheApp && wxTheApp->HasPendingEvents() )
                    {
                        wxTheApp->ProcessPendingEvents();
                        hasMoreEvents = true;
                    }

                    if ( Pending() )
                    {
                        Dispatch();
                        hasMoreEvents = true;
                    }

                    if ( !hasMoreEvents )
                        break;
                }

    #if wxUSE_EXCEPTIONS
                // exit the outer loop as well
                break;
            }
            catch ( ... )
            {
                try
                {
                    if ( !wxTheApp || !wxTheApp->OnExceptionInMainLoop() )
                    {
                        OnExit();
                        break;
                    }
                    //else: continue running the event loop
                }
                catch ( ... )
                {
                    // OnException() throwed, possibly rethrowing the same
                    // exception again: very good, but we still need OnExit() to
                    // be called
                    OnExit();
                    throw;
                }
            }
        }
    #endif // wxUSE_EXCEPTIONS

        return m_exitcode;
    }