Beispiel #1
0
bool CRefresher::NeedRefresh(CTimer &timer) const
{
    return timer.Time() > m_RefreshTime;
}
Beispiel #2
0
//********************************************************************
// main()
//********************************************************************
int main(){

  //instantiate log object and log
  CLog *pLog = CLog::Instance();
  pLog->Log("*********************************************************");
  pLog->Log("Program starting..................");
  pLog->SetDelimiter(':');
  pLog->LogDate();
  pLog->LogTime();
  pLog->Log("************************ *********************************");
   
  cout << "Enter name: ";
  cin >> g_playerName;
  //system("cls");

  //initialize console
  Console con(80, 25);//50);
  con.SetConsolePosition(0,0);
  con.CenterConsoleWindow();
  con.cls();

  Initialize();
  
  CONSOLE_SCREEN_BUFFER_INFO csbi = con.GetScreenBufferInfo();
  pLog->LogPair("Screen Buffer Size",csbi.dwSize.X, csbi.dwSize.Y);
  pLog->LogPair("Window Size",csbi.dwMaximumWindowSize.X, csbi.dwMaximumWindowSize.Y);
  pLog->LogPair("Left-Top",csbi.srWindow.Left, csbi.srWindow.Top);
  pLog->LogPair("Right-Bottom",csbi.srWindow.Right, csbi.srWindow.Bottom);
  pLog->LogPair("Maximum Window Size", csbi.dwMaximumWindowSize.X, csbi.dwMaximumWindowSize.Y);
  COORD maxSize = con.GetMaximumScreenSize();
  pLog->LogPair("Max Size",maxSize.X, maxSize.Y);

  //game timer
  CTimer loopTimer;
  CTimer renderTimer;
  loopTimer.Initialize();
  renderTimer.Initialize();
  double timeDelta = 0;

  char buffer[] = "Chuck's Factory Game";
  con.setTitle(buffer);

  //main game loop
  //********************************************
  bool quit = false;    
  while(!quit){ 
    timeDelta = loopTimer.GetTimeDifference();
    g_pNext = g_pCurrent->Update(timeDelta);
	  if(NULL != g_pNext)
	  {
      g_pCurrent = g_pNext;
    }
     
    if(g_pCurrent == g_pStateQuit )
      quit = true;

  	// Render our current game object
    //if(renderTimer.GetTimer(0.1)== true)
      g_pCurrent->Render(con);
  }
  //********************************************
  //end game loop

  //free resources
  delete g_pStateIntro;
  delete g_pStateMenu;
  delete g_pStateQuit;
  delete g_pStateRules;
  delete g_pStateScore;
  delete g_pStatePlay;

  for(int i = 0; i < 9; ++i)
    g_audio.StopSoundClip(i);

  system("cls");
  
  //normal termination of game
  pLog->Log("*********************************************************");
  pLog->Log("Program terminating normally..................");
  pLog->SetDelimiter(':');
  pLog->LogTime();
  pLog->Log("*********************************************************");
  
  return 0;
}
Beispiel #3
0
int main(int argc,char* argv[])
{
	//register ctrl+c handler
	signal (SIGINT,ctrl_c_handler);
	//initialize the logging system
	if (initializeLogging()==false) return -1;

	//auto-detect screen resolution (in case of a single display) and initialize the GUI
	gui = new CGui(&imageWidth,&imageHeight,dualMonitor);
	image = new CRawImage(imageWidth,imageHeight);

	//read number of robots and pheromone half-life from the command line
	numBots = atoi(argv[2]);
	float evaporation = atof(argv[1]);

	float diffusion = 0;
	float influence = 1.0;

	/*initialize the pheromone fields
	* pheromone field 0 simulates a longer-decay pheromone that the other robots follow
	* pheromone field 1 is released by the leader if it gets too close to arena boundaries causing the leader to avoid them - this pheromone decays quickly
	* pheromone field 2 is released by the leader to supress pheromone field 0 (this avoids the leader to detect pheromone 0 by its sensors)
	*evaporation defines pheromone's half-life, diffusion its spreading over time and strength determines how the pheromone influences the LCD-displayed image
	for details, see the chapter 2 of paper Arvin, Krajnik, Turgut, Yue: "CosPhi: Artificial Pheromone System for Robotic Swarms Research", IROS 2015*/
	pherofield[0] = new CPheroField(imageWidth,imageHeight,evaporation,diffusion,influence);
	pherofield[1] = new CPheroField(imageWidth,imageHeight,0.1,0,1);
	pherofield[2] = new CPheroField(imageWidth,imageHeight,0.1,0,-5);

	/*connect to the localization system*/
	client = new CPositionClient();
	client->init(whyconIP,"6666");
	image->getSaveNumber();

	randomPlacement();

	globalTimer.pause();
	CTimer performanceTimer;
	performanceTimer.start();
	while (stop == false){
		//get the latest data from localization system and check if the calibration finished
		stop = (globalTimer.getTime()/1000000>experimentTime);
	

		/*PHEROMONE DECAY*/ 
		pherofield[0]->recompute();	//main pheromone half-life (user-settable, usually long)
		pherofield[1]->recompute();		//collision avoidance pheromone with quick decay
		pherofield[2]->recompute();		//suppression pheromone with quick decay

		client->checkForData();

		/*PHEROMONE INJECTION*/
		if (calibration==false && placement==false)
		{
			int leader = 0;

			/*PHEROMONE 1 - released by the leading robot*/
			for (int i = 0;i<numBots;i++)
			{
				if (client->getID(i) == leaderID){
				       	pherofield[0]->addTo(client->getX(i)*imageWidth/arenaLength,client->getY(i)*imageHeight/arenaWidth,i,pheroStrength);
					leader = i;
				}
			}
			/*cause the leading robot to release pheromone 1 that is used for obstacle avoidance and 2 that temporarily suppresses pheromone 0*/
			float dist = 0.030;	//distance of the pheromone release relatively to the leader (controls pheromones 1 and 2 only) 
			float addPhi = 0;	//angle of the pheromone release relatively to the leader (controls pheromones 1 and 2 only) 
			float phi = client->getPhi(leader);
		
			/*is the leader close to the arena edge ?*/
			if ((client->getX(leader)<avoidDistance && cos(phi)<0) || (client->getX(leader)>arenaLength-avoidDistance && cos(phi) > 0 )|| (client->getY(leader)<avoidDistance && sin(phi)<0) || (client->getY(leader)>arenaWidth-avoidDistance && sin(phi)>0))
			{
				/*leader is close to the arena edge -> release pheromone 1 that causes the robot to turn away */
				pherofield[1]->addTo((client->getX(leader)+dist*cos(phi+addPhi))*imageWidth/arenaLength,(client->getY(leader)+dist*sin(phi+addPhi))*imageHeight/arenaWidth,0,pheroStrength,35);
			}else{
				/*leader is not close to the arena edge -> release pheromone 2 suporessed pheromone 0, so that the leader does not pick it's own pheromone */
				pherofield[2]->addTo((client->getX(leader)+dist*cos(phi+addPhi))*imageWidth/arenaLength,(client->getY(leader)+dist*sin(phi+addPhi))*imageHeight/arenaWidth,0,pheroStrength,45);
			}
			/*save positions for later analysis*/
			logRobotPositions();
		}

		//convert the pheromone field to grayscale image
		image->combinePheromones(pherofield,3,0);		//the last value determines the color channel - 0 is for grayscale, 1 is red etc. 
		gui->drawImage(image);
		
	
		//experiment preparation phase 2: draw initial and real robot positions
		initRadius = robotDiameter/arenaLength*imageWidth/2;	//calculate robot radius in pixels, so that it matches the real robot dimensions
		for (int i = 0;i<numBots && placement;i++)
		{
			 gui->displayInitialPositions(initX[i],initY[i],initA[i],initBrightness,initRadius+10);
			 if (client->exists(i) && calibration == false)  gui->displayRobot(client->getX(i)*imageWidth/arenaLength,client->getY(i)*imageHeight/arenaWidth,client->getPhi(i),0,initRadius+10);
		}
	
		/*this chunk of code is used to determine lag*/
		/*float t = globalTimer.getTime()/1000000.0;	
		for (int i = 0;i<numBots;i++){
			if (client->exists(i)){
				gui->displayRobot(client->getX(i)*imageWidth/arenaLength,client->getY(i)*imageHeight/arenaWidth,client->getPhi(i),0,initRadius+10);
				float dx = fabs(100+50*t-client->getX(i)*imageWidth/arenaLength);
				float dy = fabs(imageHeight/2-client->getY(i)*imageHeight/arenaWidth);
				printf("Distance: %.3f Lag: %f \n",sqrt(dx*dx+dy*dy),sqrt(dx*dx+dy*dy)/50);
			}
		}
		gui->displayPattern(100+t*50,imageHeight/2,initRadius);*/


		//experiment preparation phase 1: draw calibration, contact WhyCon to calibrate and draw initial robot positions
		if (calibration){
			int calibRadius = initRadius/(cameraHeight-robotHeight)*cameraHeight;		//slightly enlarge to compensate for the higher distance from the camera
			gui->displayCalibrationInfo(cameraHeight,client->numSearched,client->numDetected,calibRadius,performanceTimer.getTime()/1000);
			client->calibrate(numBots,arenaLength,arenaWidth,cameraHeight,robotDiameter,robotHeight);
			client->checkForData();
		}else if (placement){
			 gui->displayPlacementInfo(client->numSearched,client->numDetected);
		}
		calibration = client->calibrated==false;


		//update GUI etc
		gui->update();
		processEvents();
		printf("GUI refresh: %i ms, updates %i frame delay %.0f ms\n",performanceTimer.getTime()/1000,client->updates,(performanceTimer.getRealTime()-client->frameTime)/1000.0);
		performanceTimer.reset();
	}
	fclose(robotPositionLog);
	if (globalTimer.getTime()/1000000<experimentTime) {
		remove(logFileName); 
		printf("EXPERIMENT TERMINATED MANUALLY\n");
	}else{
		printf("EXPERIMENT FINISHED SUCESSFULLY, results saved to %s.\n",logFileName);
	}
	for (int i = 0;i<3;i++) delete pherofield[i];
	delete client;
	delete image;
	delete gui;
	return 0;
}
Beispiel #4
0
int CMain::OnExecute()
{
	if(init() == false)
	{
		return 1;
	}

	if(load_files() == false)
	{
		return 2;
	}

	CTimer myTimer;
	myTimer.start();
	//int frame = 0;
	//bool cap = true;
	//Timer fps;


	SDL_Event event; //Load the event structures

	message1 = TTF_RenderText_Solid(font, "You mad? Yep, you are.", textColor); //font-file, text, color
	message2 = TTF_RenderText_Solid(font, "You mad? Oh, you aren't? :(.", textColor);

	if(message1 == false || message2 == false)
	{
		return 3;
	}

	while(quit == false)
	{
		while(SDL_PollEvent(&event))
		{
			if(event.type == SDL_KEYDOWN)
			{
				switch( event.key.keysym.sym )
				{
					case SDLK_UP: message = message1; break;
					case SDLK_DOWN: message = message2; break;
					case SDLK_1: if(Mix_PlayChannel(-1, high, 0) == -1) //channel (-1 = first available channel), Mix_Chunk(), repeat (-1 = infinite)
								 {
									return 1;
								 } break;
					case SDLK_2: if(Mix_PlayChannel(-1, med, 0) == -1)
								 {
									return 1;
								 } break;
					case SDLK_3: if(Mix_PlayChannel(-1, low, 0) == -1)
								 {
									return 1;
								 }  break;
					case SDLK_4: if(Mix_PlayingMusic() == 0)
								 {
									if(Mix_PlayMusic(music, -1) == -1) //music, repeat
									{
										return 1;
									}
								 } 
								 else
								 {
									 if(Mix_PausedMusic() == 1)
									 {
										Mix_ResumeMusic();
									 }
									 else
									 {
										Mix_PauseMusic();
									 }
								 }  break;
					case SDLK_0: Mix_HaltMusic();  break;
					case SDLK_s: if(myTimer.is_started() == true)
								 {
									 myTimer.stop();
								 }
								 else
								 {
									 myTimer.start();
								 }  break;
					case SDLK_p: if(myTimer.is_paused() == true)
								 {
									 myTimer.unpause();
								 }
								 else
								 {
									 myTimer.pause();
								 } break;
					case SDLK_F10: quit = true; break;
				}
			}
			else if(event.type == SDL_QUIT)
			{
				quit = true;
			}
		}

		stringstream time;
		time << "Timer: " << myTimer.getTicks() / 1000.f;

		seconds = TTF_RenderText_Solid(font, time.str().c_str(), textColor);

		CSurface::apply_surface(0, 0, background, screen); //X, Y, source, destination
		CSurface::apply_surface(320, 0, background, screen);
		CSurface::apply_surface(0, 240, background, screen);
		CSurface::apply_surface(320, 240, background, screen);
		CSurface::apply_surface(180, 140, image, screen);
		CSurface::apply_surface((SCREEN_WIDTH - seconds->w) / 2, 25, seconds, screen);

		if(message != NULL)
		{
			CSurface::apply_surface(100, 0, message, screen);
			message = NULL;
		}

		clip[ 0 ].x = 0; 
		clip[ 0 ].y = 0; 
		clip[ 0 ].w = 100; 
		clip[ 0 ].h = 100; 
		
		clip[ 1 ].x = 100; 
		clip[ 1 ].y = 0; 
		clip[ 1 ].w = 100; 
		clip[ 1 ].h = 100; 

		clip[ 2 ].x = 0; 
		clip[ 2 ].y = 100; 
		clip[ 2 ].w = 100; 
		clip[ 2 ].h = 100; 

		clip[ 3 ].x = 100; 
		clip[ 3 ].y = 100; 
		clip[ 3 ].w = 100; 
		clip[ 3 ].h = 100; 

		CSurface::apply_surface( 0, 0, dots, screen, &clip[ 0 ] ); //X, Y, source, destination, rectangle of which to copy
		CSurface::apply_surface( 540, 0, dots, screen, &clip[ 1 ] );
		CSurface::apply_surface( 0, 380, dots, screen, &clip[ 2 ] );
		CSurface::apply_surface( 540, 380, dots, screen, &clip[ 3 ] );

		if(SDL_Flip(screen) == -1) //Refresh the screen
		{
			return 4;
		}
	}

	cleanup();

	return 0;
}
Beispiel #5
0
//-----------------------------------------------------------------------------
// Wrap an unsafe call in a mutex to assure safety
// Biggest error issues are:
// 1. Timeout (probably handler doesn't exist)
// 2. Handler can be destroyed at any time.
//-----------------------------------------------------------------------------
IPCFuncCallSource::EError IPCFuncCallSource::DoThreadSafeCall()
{
    DWORD dwErr;
    EError err = Ok;

#if defined(ENABLE_TIMING)
    g_time.Reset();
    g_time.Start();
#endif

    HANDLE hStartEnum = NULL;
    HANDLE hDoneEnum = NULL;
    HANDLE hWrapCall = NULL;
    DWORD dwWaitRet;

    // Check if we have a handler (handler creates the events) and
    // abort if not.  Do this check asap to optimize the most common
    // case of no handler.
    hStartEnum = WszOpenEvent(EVENT_ALL_ACCESS,	
                                FALSE,
                                FixupName(StartEnumEventName));
    if (hStartEnum == NULL) 
    {
        dwErr = GetLastError();
        err = Fail_NoHandler;
        goto errExit;
    }

    hDoneEnum = WszOpenEvent(EVENT_ALL_ACCESS,
                                FALSE,
                                FixupName(DoneEnumEventName));
    if (hDoneEnum == NULL) 
    {
        dwErr = GetLastError();
        err = Fail_NoHandler;
        goto errExit;
    }

    // Need to create the mutex
    hWrapCall = WszCreateMutex(NULL, FALSE, FixupName(WrapMutexName));
    if (hWrapCall == NULL)
    {
        dwErr = GetLastError();
        err = Fail_CreateMutex;
        goto errExit;
    }


// Wait for our turn	
    dwWaitRet = WaitForSingleObject(hWrapCall, START_ENUM_TIMEOUT);
    dwErr = GetLastError();
    switch(dwWaitRet) {
    case WAIT_OBJECT_0:
        // Good case. All other cases are errors and goto errExit.
        break;

    case WAIT_TIMEOUT:
        err = Fail_Timeout_Lock;
        goto errExit;
        break;
    default:
        err = Failed;
        goto errExit;
        break;
    }

    // Our turn: Make the function call
    {
        BOOL fSetOK = 0;

    // Reset the 'Done event' to make sure that Handler sets it after they start.
        ResetEvent(hDoneEnum);
        dwErr = GetLastError();

    // Signal Handler to execute callback   
        fSetOK = SetEvent(hStartEnum);
        dwErr = GetLastError();

    // Now wait for handler to finish.
        
        dwWaitRet = WaitForSingleObject(hDoneEnum, START_ENUM_TIMEOUT);
        dwErr = GetLastError();
        switch (dwWaitRet)
        {   
        case WAIT_OBJECT_0:
            break;
        case WAIT_TIMEOUT:
            err = Fail_Timeout_Call;
            break;      
        default:
            err = Failed;
            break;
        }
        

        ReleaseMutex(hWrapCall);
        dwErr = GetLastError();

    } // End function call



errExit:
// Close all handles
    if (hStartEnum != NULL) 
    {
        CloseHandle(hStartEnum);
        hStartEnum = NULL;
        
    }
    if (hDoneEnum != NULL) 
    {
        CloseHandle(hDoneEnum);
        hDoneEnum = NULL;
    }
    if (hWrapCall != NULL) 
    {
        CloseHandle(hWrapCall);
        hWrapCall = NULL;
    }

#if defined(ENABLE_TIMING)
    g_time.End();
    DWORD dwTime = g_time.GetEllapsedMS();
#endif


    return err;

}
Beispiel #6
0
void change_phase(GamePhaseType new_phase){

	GamePhase = new_phase;
	PhaseTime = Timer.time();
	endphase = FALSE;
	static int first = 1;

	switch(GamePhase){

	case LOGO_PHASE:
			LoadSounds(0);
			display_screen("./images/logo.bmp");
			SoundManager->play(TITLE_SOUND);
			SoundManager->play(LOGO_SOUND);
			break;

	case TITLE_PHASE:
		
			SoundManager->stop(); //silence previous phase
        	MidiPlayer.Load(song_list[INTRO_MUSIC].c_str());
			MidiPlayer.Play();
			display_screen("./images/title.bmp"); 
			break;
			
	case HELP_PHASE:
			SoundManager->stop();
			display_screen("./images/help.bmp"); break;

	case ENEMY_PHASE:
			display_screen("./images/enemies.bmp"); break;

	case MENU_PHASE:

			SoundManager->stop(); //silence previous phase
        
			if(!first){
				MidiPlayer.Stop();
				MidiPlayer.Load(song_list[INTRO_MUSIC].c_str());
				MidiPlayer.Play();
			}
			
			display_screen("./images/menu.bmp"); break;

	case PLAYING_PHASE:

			
	        SoundManager->stop(); //silence previous phase
            SoundManager->clear(); //clear out old sounds
			LoadSounds(1);

			if(first){
		    CreateObjects(); //create new objects
			first = 0;

			}
				SoundManager->play(BEGIN0_SOUND+Random.number(0,2));
			
				MidiPlayer.Stop();
				MidiPlayer.Load(song_list[THEME_MUSIC].c_str());
				MidiPlayer.Play();
			
		//	SoundManager->play(ENGINE_SOUND,LOOP_SOUND);
			break;
	case GAMEOVER_PHASE:

			MidiPlayer.Stop();
			
						
			display_screen("./images/game_over.bmp");
			Sleep(2000);
			SoundManager->stop(); //silence previous phase
			SoundManager->play(GAMEOVER1_SOUND);
			 break;

	}
}
Beispiel #7
0
void CLogic::loadSounds(void)
{
	CTimer t;
	t.start();
	distSound = audiere::OpenSoundEffect(data->audioDevice, "resources/sounds/distance.wav", audiere::MULTIPLE);
	distSound->setVolume(0.30f);
	std::cout << "sound: resources/sounds/distance.wav " << t.getElapsedMilliseconds() << "ms" << std::endl;
	t.reset();
	looseSound = audiere::OpenSoundEffect(data->audioDevice, "resources/sounds/theend.mp3", audiere::MULTIPLE);
	looseSound->setVolume(1.00f);
	std::cout << "sound: resources/sounds/theend.mp3 " << t.getElapsedMilliseconds() << "ms" << std::endl;
	t.reset();
	winSound = audiere::OpenSoundEffect(data->audioDevice, "resources/sounds/win.mp3", audiere::MULTIPLE);
	winSound->setVolume(0.70f);
	std::cout << "sound: resources/sounds/win.mp3 " << t.getElapsedMilliseconds() << "ms" << std::endl;
	t.reset();
	ambSound = audiere::OpenSoundEffect(data->audioDevice, "resources/sounds/tokyo.mp3", audiere::MULTIPLE);
	ambSound->setVolume(0.9);
	std::cout << "sound: resources/sounds/tokyo.mp3 " << t.getElapsedMilliseconds() << "ms" << std::endl;
	t.reset();
	explSound = audiere::OpenSoundEffect(data->audioDevice, "resources/sounds/explosion.mp3", audiere::MULTIPLE);
	explSound->setVolume(0.5);
	std::cout << "sound: resources/sounds/explosion.mp3 " << t.getElapsedMilliseconds() << "ms" << std::endl;
	t.stop();
	soundsLoaded = true;
}
Beispiel #8
0
/************************************************************************************************
  WinMain (...)
************************************************************************************************/
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	// Always perform a leak check just before app exits.
	int nDbgFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
	nDbgFlags |= _CRTDBG_LEAK_CHECK_DF;
	_CrtSetDbgFlag(nDbgFlags);

  //instantiate log object and log
  CLog *pLog = CLog::Instance();
  pLog->Log("*********************************************************");
  pLog->Log("Program starting..................");
  pLog->SetDelimiter(':');
  pLog->LogDate();
  pLog->LogTime();
  pLog->Log("************************ *********************************");


  pLog->Log ("***********************************************");
  pLog->Log("Game Challenge 6");
  pLog->LogDate();
  pLog->LogTime();
  pLog->Log("***********************************************");

  Graphics g_con;  
  CAudioManager *pAudio = CAudioManager::Instance();

  //***********************************************************************
  //read config.ini file
  // C O N F I G . I N I
  //***********************************************************************
  pLog->Log("************ Config.ini ************");
  CINIReader config;          //reads and stores INI file data
  config.LoadFile("config.ini");
  std::string sValue;
  std::string sParameter;
  int nParameterValue;

  //default values
  g_Global.g_screenWidth = 1024;
  g_Global.g_screenHeight = 768;

  if(config.IsValid() == true){
    pLog->Log("Valid config.ini file");
    pLog->Log("Numbers of lines in config file",config.GetNumberOfLines());

    for(int j=0; j< config.GetNumberOfLines();j++){
      sParameter = config.GetTerm(config.GetLineFromFile(j),1);
      sValue = config.GetTerm(config.GetLineFromFile(j),2);
      nParameterValue =  atoi(sValue.c_str());

      pLog->Log(sParameter, nParameterValue);      
      
      //load g_Global object with config.ini data
      if(sParameter == "WindowedMode" && nParameterValue == 1)
        g_Global.g_WindowedMode = true;
      else if(sParameter == "WindowedMode" && nParameterValue == 0)
        g_Global.g_WindowedMode = false;
      //else if(sParameter == "ScreenWidth" && nParameterValue > 0)
      //  g_Global.g_screenWidth = nParameterValue;
      //else if(sParameter == "ScreenHeight" && nParameterValue > 0)
      //  g_Global.g_screenHeight = nParameterValue;
      //else if(sParameter == "GameLevel" && nParameterValue > 0 && nParameterValue < 6)
      //  g_Global.g_GameLevel = nParameterValue;
      //else if(sParameter == "GameSnow" && nParameterValue == 1)
      //  g_Global.g_bGameSnow = true;
      //else if(sParameter == "GameSnow" && nParameterValue == 0)
      //  g_Global.g_bGameSnow = false;
      else if(sParameter == "GameAudio" && nParameterValue == 1)
        g_Global.g_bGameAudio = true;
      else if(sParameter == "GameAudio" && nParameterValue == 0)
        g_Global.g_bGameAudio = false;
      else if(sParameter == "FrameRate" && nParameterValue == 1)
        g_Global.g_bDisplayFramerate = true;
      else if(sParameter == "FrameRate" && nParameterValue == 0)
        g_Global.g_bDisplayFramerate = false;
    }
  } 
  pLog->Log("Reading Config.ini file is complete!");
	// Break on specific memory allocation number
	//_CrtSetBreakAlloc(175);
  
  MSG msg;    
  g_bRunning = true;//Start program running

  //Make a window and initialize DirectX in windowed mode
  MakeWindow(hInstance, g_Global.g_WindowedMode, g_con);

  //map game state information
  g_pStateIntro->addTransitionEvent(EVENT_GO_MAIN, g_pStateMain);
  g_pStateMain->addTransitionEvent(EVENT_GO_HISTORY, g_pStateHistory);
  g_pStateMain->addTransitionEvent(EVENT_GO_RELOAD, g_pStateReload);
  g_pStateMain->addTransitionEvent(EVENT_GO_CREDITS, g_pStateCredits);
  g_pStateMain->addTransitionEvent(EVENT_GO_SELECT, g_pStateSelect);
  g_pStateHistory->addTransitionEvent(EVENT_GO_MAIN, g_pStateMain);
  g_pStateReload->addTransitionEvent(EVENT_GO_MAIN, g_pStateMain);
  g_pStateCredits->addTransitionEvent(EVENT_GO_END, g_pStateEnd);
  g_pStateSelect->addTransitionEvent(EVENT_GO_AWARDS, g_pStateAwards);
  g_pStateAwards->addTransitionEvent(EVENT_GO_SELECT, g_pStateSelect);  
  g_pStateSelect->addTransitionEvent(EVENT_GO_PLAY, g_pStatePlay);
  g_pStateSelect->addTransitionEvent(EVENT_GO_MAIN, g_pStateMain);
  g_pStatePlay->addTransitionEvent(EVENT_GO_WIN, g_pStateWin);
  g_pStatePlay->addTransitionEvent(EVENT_GO_LOSE, g_pStateLose);
  g_pStateWin->addTransitionEvent(EVENT_GO_SELECT, g_pStateSelect);
  g_pStateLose->addTransitionEvent(EVENT_GO_SELECT, g_pStateSelect);
  g_pStatePlay->addTransitionEvent(EVENT_GO_SELECT, g_pStateSelect);
  g_pStatePlay->addTransitionEvent(EVENT_GO_CONTROL, g_pStateControl);
  
  //sonar transitions
  g_pStateSonar->addTransitionEvent(EVENT_GO_RADAR, g_pStateRadar);
  g_pStateSonar->addTransitionEvent(EVENT_GO_FIRECONTROL, g_pStateFireControl);
  g_pStateSonar->addTransitionEvent(EVENT_GO_STATUS, g_pStateStatus);
  g_pStateSonar->addTransitionEvent(EVENT_GO_CHART, g_pStateChart);  
  g_pStateSonar->addTransitionEvent(EVENT_GO_CONTROL, g_pStateControl);

  //radar transitions
  g_pStateRadar->addTransitionEvent(EVENT_GO_SONAR, g_pStateSonar);
  g_pStateRadar->addTransitionEvent(EVENT_GO_FIRECONTROL, g_pStateFireControl);
  g_pStateRadar->addTransitionEvent(EVENT_GO_STATUS, g_pStateStatus);
  g_pStateRadar->addTransitionEvent(EVENT_GO_CHART, g_pStateChart);  
  g_pStateRadar->addTransitionEvent(EVENT_GO_CONTROL, g_pStateControl);

  //scope transitions
  g_pStateScope->addTransitionEvent(EVENT_GO_CONTROL, g_pStateControl);
  g_pStateScope->addTransitionEvent(EVENT_GO_WIN, g_pStateWin);
  g_pStateScope->addTransitionEvent(EVENT_GO_LOSE, g_pStateLose);
  
  //conn transitions
  g_pStateControl->addTransitionEvent(EVENT_GO_PLAY, g_pStatePlay);
  g_pStateControl->addTransitionEvent(EVENT_GO_SONAR, g_pStateSonar);
  g_pStateControl->addTransitionEvent(EVENT_GO_RADAR, g_pStateRadar);
  g_pStateControl->addTransitionEvent(EVENT_GO_FIRECONTROL, g_pStateFireControl);
  g_pStateControl->addTransitionEvent(EVENT_GO_STATUS, g_pStateStatus);
  g_pStateControl->addTransitionEvent(EVENT_GO_CHART, g_pStateChart);  
  g_pStateControl->addTransitionEvent(EVENT_GO_SCOPE, g_pStateScope);
  g_pStateControl->addTransitionEvent(EVENT_GO_SELECT, g_pStateSelect);
  g_pStateControl->addTransitionEvent(EVENT_GO_WIN, g_pStateWin);
  g_pStateControl->addTransitionEvent(EVENT_GO_LOSE, g_pStateLose);

  //fire control transitions
  g_pStateFireControl->addTransitionEvent(EVENT_GO_SONAR, g_pStateSonar);
  g_pStateFireControl->addTransitionEvent(EVENT_GO_RADAR, g_pStateRadar);
  g_pStateFireControl->addTransitionEvent(EVENT_GO_STATUS, g_pStateStatus);
  g_pStateFireControl->addTransitionEvent(EVENT_GO_CHART, g_pStateChart);  
  g_pStateFireControl->addTransitionEvent(EVENT_GO_CONTROL, g_pStateControl);

  //status transitions
  g_pStateStatus->addTransitionEvent(EVENT_GO_SONAR, g_pStateSonar);
  g_pStateStatus->addTransitionEvent(EVENT_GO_RADAR, g_pStateRadar);
  g_pStateStatus->addTransitionEvent(EVENT_GO_FIRECONTROL, g_pStateFireControl);
  g_pStateStatus->addTransitionEvent(EVENT_GO_CHART, g_pStateChart);  
  g_pStateStatus->addTransitionEvent(EVENT_GO_CONTROL, g_pStateControl);

  //chart transitions
  g_pStateChart->addTransitionEvent(EVENT_GO_SONAR, g_pStateSonar);
  g_pStateChart->addTransitionEvent(EVENT_GO_RADAR, g_pStateRadar);
  g_pStateChart->addTransitionEvent(EVENT_GO_FIRECONTROL, g_pStateFireControl);
  g_pStateChart->addTransitionEvent(EVENT_GO_STATUS, g_pStateStatus);
  g_pStateChart->addTransitionEvent(EVENT_GO_CONTROL, g_pStateControl);
  g_pStateChart->addTransitionEvent(EVENT_GO_WIN, g_pStateWin);
  g_pStateChart->addTransitionEvent(EVENT_GO_LOSE, g_pStateLose);

  g_Timer.initialize();
  g_LoopTimer.initialize();
  g_FPS_Timer.initialize();
  g_con.InitD3D (g_hWnd, g_Global.g_WindowedMode);

  //***********************************************************************
  //load textures from graphics file
  // G R A P H I C F I L E S . D A T
  //***********************************************************************
  pLog->Log("************ Graphicfiles.dat ************");
  CFileReader* cfr = new CFileReader;
  cfr->LoadFile("data\\graphicfiles.dat");
  int fileNumber;
  std::string fileName;
  if(cfr->IsValid()== true){
    pLog->Log("Numbers of lines in file",cfr->GetNumberOfLines());
    for(int j=0; j< cfr->GetNumberOfLines();j++){
      sValue =cfr->GetTerm(cfr->GetLineFromFile(j),1);
      fileNumber = atoi(sValue.c_str());
      sValue = cfr->GetTerm(cfr->GetLineFromFile(j),2);
      fileName = "assets\\artwork\\";
      fileName = fileName + sValue;
      //pLog->Log("Loaded file",fileName);
      pLog->Log(fileName, fileNumber);
      g_con.LoadTexture(fileName, fileNumber);
    }
  } 
  else{
    pLog->Log("ERROR****************** Failure to load textures (graphicfiles.dat)");
    delete cfr;
    g_con.CloseD3D();
    pLog->Log("DirectX closed!");
    Shutdown();
    return 0;
  }

  if(g_Sprite.LoadSprites() == true){
    pLog->Log("Sprites loaded!");
  }
  else{
    pLog->Log("ERROR****************** Failure to sprite data (sprites.dat)");
  }

  //used for framerate display
  std::ostringstream oss;
  std::string sFramerate;
  std::string sText;
  int nDisplayFPSCount = 0;

  //initialize audio manager
  //***************************************************************
  if(g_Global.g_bGameAudio == true){
    pLog->Log("Loading audio clip...");
    if(pAudio->IsValidSound())
      pLog->Log("Audio system is okay!");
    else
      pLog->Log("Audio system failure!");
    
    //load sounds
    pAudio->LoadSample(SOUND_BEEP, "assets\\sounds\\beep-03.wav");
    pAudio->LoadSample(SOUND_REMEMBER, "assets\\sounds\\remember.mp3");
    pAudio->LoadSample(SOUND_HYMN, "assets\\sounds\\navy_hymn.mp3");
    pAudio->LoadSample(SOUND_PERISCOPE, "assets\\sounds\\periscop.wav");
    pAudio->LoadSample(SOUND_BUTTON_CLICK, "assets\\sounds\\button_click.wav");
    pAudio->LoadSample(SOUND_DEPTH_CHARGE1,"assets\\sounds\\dc1.mp3");
    pAudio->LoadSample(SOUND_DEPTH_CHARGE2,"assets\\sounds\\dc2.mp3");
    pAudio->LoadSample(SOUND_TORPEDO1,"assets\\sounds\\torpedo3.mp3");
    pAudio->LoadSample(SOUND_TORPEDO2,"assets\\sounds\\torpedo4.mp3");
    pAudio->LoadSample(SOUND_AMBIENCE1,"assets\\sounds\\ambience1.mp3");
    pAudio->LoadSample(SOUND_CLEAR_BRIDGE,"assets\\sounds\\clear_bridge.wav");
    pAudio->LoadSample(SOUND_DIVING,"assets\\sounds\\diving.mp3");
    pAudio->LoadSample(SOUND_GQ,"assets\\sounds\\general_quarters.wav");
    pAudio->LoadSample(SOUND_ANCHORS,"assets\\sounds\\AnchorsAway.mp3");
    pAudio->LoadSample(SOUND_TAPS,"assets\\sounds\\Taps.mp3");
    pAudio->LoadSample(SOUND_SINKING,"assets\\sounds\\sinking2.mp3");
    pAudio->LoadSample(SOUND_ANTHEM,"assets\\sounds\\USA.mp3");
    pAudio->LoadSample(SOUND_FUNERAL,"assets\\sounds\\fnrlMrch.wav");
    pAudio->LoadSample(SOUND_PING,"assets\\sounds\\sonar1.mp3");
    
    //load stream
    pAudio->LoadStream(SOUND_BIO, "assets\\sounds\\fish.mp3");
    pAudio->AddStreamClip(SOUND_BIO1, SOUND_BIO, 0, 17708);
    pAudio->AddStreamClip(SOUND_BIO2, SOUND_BIO, 17708, 26434);
    pAudio->AddStreamClip(SOUND_BIO3, SOUND_BIO, 26434, 42859);
    pAudio->AddStreamClip(SOUND_BIO4, SOUND_BIO, 42859, 59541);
    pAudio->AddStreamClip(SOUND_BIO5, SOUND_BIO, 59541, 80073);

    for(int i = 0; i < pAudio->Size(); i++){
      pLog->Log(pAudio->GetFilename(i), i); //write filename and file index to log file
    }
  }
  else{
    pLog->Log("Audio disabled");
  }

  pLog->Log("Main game loop entered!");
  ::ShowCursor(false); 
  //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Version Number
  //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Version Number
  //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Version Number
  //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< Version Number
  g_strFPS = "Game Challenge 6 (Chuck Bolin) - \"Sinking of the Rising Sun\", v0.047 Final Version";
  ::SetWindowText(g_hWnd, g_strFPS.c_str());
  double timeDelta;

  g_con.InitializePyro();

  //Main application loop
  //*******************************************************
  while (g_bRunning)
  {
    //Handle messages
    if (PeekMessage (&msg,NULL,0,0,PM_REMOVE)){
        TranslateMessage (&msg);
        DispatchMessage (&msg);
    }        
    else{}
      timeDelta = g_LoopTimer.getTimeDifference();
      g_pNext = g_pCurrent->update(timeDelta);
      if(g_pNext == g_pStateEnd)
        g_bRunning = false;
      else if(NULL != g_pNext)
	    {
        g_pCurrent->deactivate();
        g_pCurrent = g_pNext;
        g_pCurrent->activate();
      }
     
	  // Render our current game object
    g_pCurrent->render(g_con);

    //call each second update FPS
    nDisplayFPSCount++;
    if(g_FPS_Timer.getTimer(1)){
      //g_FPS_Counter++;
      oss.str(""); //clear oss
      oss << (int) nDisplayFPSCount;
      //if(g_FPS_Counter > 60){  //call every 60 seconds
      //  pLog->Log("FPS",oss.str());
      //  g_FPS_Counter == 0;
      //}

  	  // update our FPS string.
	    // This thing can be rendered inside any of the game objects.
      g_strFPS = "FPS " + oss.str();
      g_Global.g_strFPS = "FPS " + oss.str();

      nDisplayFPSCount=0;//reset frame count
    }
  }//while(...
  g_con.ClosePyro();
  g_con.CloseD3D();
  pLog->Log("DirectX closed!");
  Shutdown();

  return 0;//(int)msg.wParam;  //returns exit code to operating system
} 
Beispiel #9
0
int __cdecl main(int argc, char* argv[])
{
	WNDCLASSEX wc={sizeof(WNDCLASSEX), 0, wp, 0, 0, 0, 0, 0, 0, 0, "GLAP301"};
	wc.hCursor=LoadCursor(0, IDC_ARROW);;
	wc.hIcon=LoadIcon(0,IDI_APPLICATION);
	RegisterClassEx(&wc);

	RECT wrect={0, 0, W, H};
	AdjustWindowRectEx(&wrect, WS_OVERLAPPEDWINDOW, FALSE, WS_EX_APPWINDOW);
	HWND win=CreateWindowEx(WS_EX_APPWINDOW, "GLAP301", "Render Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
		wrect.right-wrect.left, wrect.bottom-wrect.top, 0, 0, 0, 0);

	ShowWindow(win, SW_SHOWNORMAL);
	UpdateWindow(win);

	MSG msg={0, 0, 0, 0, 0, {0, 0}};

	CTimer timer;

	CUIGL GL;
	GL.Init(W, H, 1, 1, win);

	WGLPROC(glCreateShader);
	WGLPROC(glShaderSource);
	WGLPROC(glCompileShader);
	WGLPROC(glGetShaderiv);
	WGLPROC(glGetShaderInfoLog);
	WGLPROC(glCreateProgram);
	WGLPROC(glAttachShader);
	WGLPROC(glLinkProgram);
	WGLPROC(glUseProgram);
	WGLPROC(glGenBuffers);
	WGLPROC(glDeleteBuffers);
	WGLPROC(glBindBuffer);
	WGLPROC(glBufferData);
	WGLPROC(glMapBuffer);
	WGLPROC(glUnmapBuffer);
	WGLPROC(glVertexAttribPointer);
	WGLPROC(glGetAttribLocation);
	WGLPROC(glEnableVertexAttribArray);
	WGLPROC(glActiveTexture);
	WGLPROC(glGetUniformLocation);
	WGLPROC(glProgramUniform1i);
	WGLPROC(glProgramUniform3f);
	WGLPROC(glProgramUniform4f);
	WGLPROC(glProgramUniformMatrix4fv);

	GLuint ibo=-1;
	glGenBuffers(1, &ibo);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, ibsize, ib, GL_STATIC_DRAW);

	GLuint vbo=-1;
	glGenBuffers(1, &vbo);
	glBindBuffer(GL_ARRAY_BUFFER, vbo);
	glBufferData(GL_ARRAY_BUFFER, vbsize, vb, GL_STATIC_DRAW);

	glEnableClientState(GL_VERTEX_ARRAY);

	glEnableVertexAttribArray(0);
	glEnableVertexAttribArray(1);
	glEnableVertexAttribArray(2);
	glEnableVertexAttribArray(3);
	glEnableVertexAttribArray(4);

	glEnable(GL_DEPTH);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glDepthFunc(GL_LESS);

	glEnable(GL_CULL_FACE);
	glCullFace(GL_FRONT);

	GLuint body_tex=LoadTexture("data\\body_diff.png");
	GLuint body_norm=LoadTexture("data\\body_norm.png");
	GLuint fur_tex=LoadTexture("data\\fur_diff.png");
	GLuint fur_norm=LoadTexture("data\\fur_norm.png");

	GLShader sh;

	glClearColor(0.3f, 0.5f, 0.8f, 1.0f);
	glClearDepth(1.0f);

	while(1)
	{
		while(PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
			if(msg.message==WM_QUIT)
				break;
		}

		if(gAppState.reloadShaders)
		{
			sh.CreateFromFile("data\\model.vs", "data\\model.fs");
			gAppState.reloadShaders=false;

			glVertexAttribPointer(glGetAttribLocation(sh.GetPName(), "i_pos"), 3, GL_FLOAT, GL_FALSE, 4*16, (void*)(0*4));
			glVertexAttribPointer(glGetAttribLocation(sh.GetPName(), "i_nor"), 3, GL_FLOAT, GL_FALSE, 4*16, (void*)(3*4));
			glVertexAttribPointer(glGetAttribLocation(sh.GetPName(), "i_tan"), 3, GL_FLOAT, GL_FALSE, 4*16, (void*)(10*4));
			glVertexAttribPointer(glGetAttribLocation(sh.GetPName(), "i_bin"), 3, GL_FLOAT, GL_FALSE, 4*16, (void*)(13*4));
			glVertexAttribPointer(glGetAttribLocation(sh.GetPName(), "i_tex"), 2, GL_FLOAT, GL_FALSE, 4*16, (void*)(6*4));
		}

		glProgramUniform1i(sh.GetPName(), glGetUniformLocation(sh.GetPName(),"sTex"), 0);
		glProgramUniform1i(sh.GetPName(), glGetUniformLocation(sh.GetPName(),"sNor"), 1);

		float4x4 wm;
		wm=float4x4::Scale(0.05)
			*float4x4::RotY(-sin(mpx), cos(mpx))
			*float4x4::RotX(-1, 0)
			*float4x4::RotX(-sin(mpy*0.3), cos(mpy*0.3))
			;

		float fov=1.3;
		float camrx=(mx-W/2.0f)/5000.0;
		float camry=(my-H/2.0f)/5000.0;
		float4x4 vpm=float4x4::Projection(0.25, 2000, fov, H/(float)W*fov).Transposed()
			*float4x4::Translation(0, 0, dz)
			*float4x4::RotY(0, -1)
			*float4x4::RotX(sin(camry), cos(camry))
			*float4x4::RotY(-sin(camrx), cos(camrx))
			;

		
		glProgramUniformMatrix4fv(sh.GetPName(), glGetUniformLocation(sh.GetPName(),"u_wm" ), 1, false, &wm.m00);
		glProgramUniformMatrix4fv(sh.GetPName(), glGetUniformLocation(sh.GetPName(),"u_vpm"), 1, false, &vpm.m00);

		double time=timer.GetTime();

		float lightPos0[3]={sin(time),0.5, cos(time)};
		float lightPos1[3]={sin(-time*0.5),-0.5, cos(time*0.5)};;
		float lightPos2[3]={camrx*70, camry*70, -3};

		float lightCol0[3]={1.0,0.7,0.3};
		float lightCol1[3]={0.3,0.7,1.0};
		float lightCol2[3]={1.0,1.0,1.0};

		glProgramUniform3f(sh.GetPName(), glGetUniformLocation(sh.GetPName(),"lightPos0"), lightPos0[0], lightPos0[1], lightPos0[2]);
		glProgramUniform3f(sh.GetPName(), glGetUniformLocation(sh.GetPName(),"lightPos1"), lightPos1[0], lightPos1[1], lightPos1[2]);
		glProgramUniform3f(sh.GetPName(), glGetUniformLocation(sh.GetPName(),"lightPos2"), lightPos2[0], lightPos2[1], lightPos2[2]);

		glProgramUniform3f(sh.GetPName(), glGetUniformLocation(sh.GetPName(),"lightCol0"), lightCol0[0], lightCol0[1], lightCol0[2]);
		glProgramUniform3f(sh.GetPName(), glGetUniformLocation(sh.GetPName(),"lightCol1"), lightCol1[0], lightCol1[1], lightCol1[2]);
		glProgramUniform3f(sh.GetPName(), glGetUniformLocation(sh.GetPName(),"lightCol2"), lightCol2[0], lightCol2[1], lightCol2[2]);


		glDepthMask(true);
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
		glEnable(GL_DEPTH_TEST);

		sh.Use();

		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, body_tex);
		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, body_norm);

		glDisable(GL_BLEND);
		glEnable(GL_CULL_FACE);

		glDrawElements(GL_TRIANGLES, (4340*3), GL_UNSIGNED_INT, 0);

		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, fur_tex);
		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, fur_norm);

		glDepthMask(false);
		glEnable(GL_BLEND);
		glDisable(GL_CULL_FACE);

		glDrawElements(GL_TRIANGLES, indexcount-(4340*3), GL_UNSIGNED_INT, (void*)(4340*3*4));

		GL.FrameEnd();
		if(msg.message==WM_QUIT)
			break;
		if(gAppState.quitRequested)
			break;
		Sleep(10); // prevent 100% CPU consuming
	}
	return 0;
};
Beispiel #10
0
BOOL CFolderListCtrl::SetCurFolder( const CSCADString& sFolderPath, bool bForce)
{
	if( !bForce && !m_sFolderPath.CompareNoCase( sFolderPath ) )
		return TRUE;
	Timer.Start();
	m_DirChangeListener.SetDir(sFolderPath, m_hWnd);
/*
	SCDefProjInfo proj_info;

	SCADDefProj::GetInfo( m_Properties.m_DefProj, proj_info );
	SCMdl3DSetCameraPos( proj_info.m_ptViewDir, proj_info.m_ptUpOrient );
*/
	// ReSharper disable once CppEntityAssignedButNoRead
	extern SCDefProjType ThumbProjection;
	ThumbProjection = m_Properties.m_DefProj;
	if(CSCAD3DMdlSettings::Get3DS())
	{
		CSCAD3DMdlSettings::Get3DS()->CancelDraw();
		CSCAD3DMdlSettings::Get3DS()->SetStartDrawPos( 0 );
	}

	CreateImageList();
	DeleteAllItemsData();
	DeleteAllItems();
	m_sFolderPath = sFolderPath;
	m_nItemCount = 0;
	m_nImageBalance = 0;
	m_nSelectedItem = -1;
	SetSelectionMark( 0 );
	
	int i;

	for( i = m_imlLargeIcons.GetImageCount() - 1; i >= 0; i-- )
		m_imlLargeIcons.Remove( i );
	for( i = m_imlSmallIcons.GetImageCount() - 1; i >= 0; i-- )
		m_imlSmallIcons.Remove( i );

	if( _taccess( sFolderPath, 0 ) == -1 )
		return TRUE;

	SCStringVector::iterator itExt = m_Properties.m_vsExt.begin();
	CSCADString sPath;

	struct _tfinddata_t fd;

	int nLargeIconInd = 0;
	int nSmallIconInd = 0;

	for( ; itExt != m_Properties.m_vsExt.end(); ++itExt )
	{
		sPath = m_sFolderPath + _T("\\") + *itExt;

		intptr_t hFindHandle = _tfindfirst( sPath, &fd );

		if( hFindHandle == -1 )
			continue;

		AddFileTypeIcons(fd, nLargeIconInd, nSmallIconInd);

		do
		{
			AddFileItem(fd, nLargeIconInd, nSmallIconInd, *itExt);
		} while( _tfindnext( hFindHandle, &fd ) != -1 );
		_findclose( hFindHandle );
	}
	SortItems( m_flciColumns[m_nCurColumn].m_fnCmp, m_bSortAscending );
	m_nImageBalance = m_nItemCount;
	SetRedrawItemPos( 0, true );
	if( AfxGetMainWnd() )
	{
		CSCADViewerStatBar &theStatusBar = static_cast<CScadViewerFrame*>(AfxGetMainWnd())->GetStatusBar();
		theStatusBar.SetFileCount( m_nItemCount );
	}
	UpdateFileCount();		

	return TRUE;
}
Beispiel #11
0
int main( int argc, char **argv )
{
  if ( SDL_Init( SDL_INIT_EVERYTHING ) < 0 )
    throw runtime_error(SDL_GetError());
  
  SDL_Window *window = SDL_CreateWindow( "particles example",
					 SDL_WINDOWPOS_CENTERED,
					 SDL_WINDOWPOS_CENTERED,
					 WINDOW_WIDTH, 
					 WINDOW_HEIGHT, 
					 SDL_WINDOW_SHOWN
					 );
  if ( window == NULL )
    throw runtime_error(SDL_GetError());
  
  SDL_Renderer *renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_SOFTWARE);
  
  if ( renderer == NULL )
    throw runtime_error(SDL_GetError());


  const int MAX_NUMBER_OF_PARTICLES = 500;
  CVector2f pos(320,240);

  CSimpleParticleSystem system(renderer, MAX_NUMBER_OF_PARTICLES, pos);

  CTimer t;
  t.Reset();

  bool bRunning = true;
  
  while ( bRunning )
  {
    t.Update();
    SDL_Event ev;

    while ( SDL_PollEvent( & ev ))  // Check event queue.
    {
      switch( ev.type )
      {
      case SDL_QUIT: // when window is closed
	bRunning = false;
	break;
      case SDL_KEYDOWN:
	switch( ev.key.keysym.sym )
	{
	case SDLK_SPACE:
	  system.Initialize(10);
	  break;
	default:
	  break;
	}
	break;
      }
    }
    SDL_SetRenderDrawColor(renderer,0,0,0,0);
    SDL_RenderClear(renderer);

    // Make sure that time has passed between updates
    if( t.GetPassedTimeMS() >= 5)
    {
      system.Update( t.GetPassedTime() );
      t.Reset();
    }
    system.Render( renderer );

    SDL_RenderPresent(renderer);

  }
  SDL_Quit();

  return 0;
}
Beispiel #12
0
void HandleEndOfFrame()
{
#ifdef DAEDALUS_DEBUG_DISPLAYLIST
	if(DLDebugger_IsDebugging())
		return;
#endif

	DPF( DEBUG_FRAME, "********************************************" );

	bool		activate_pause_menu( false );
	//
	//	Figure out how long the last frame took
	//
#ifdef DAEDALUS_PROFILE_EXECUTION
	DumpDynarecStats( elapsed_time );
#endif
	//
	//	Enter the debug menu as soon as select is newly pressed
	//
	static u32 oldButtons = 0;
	SceCtrlData pad;

	sceCtrlPeekBufferPositive(&pad, 1);

	// If kernelbuttons.prx couldn't be loaded, allow select button to be used instead
	//
	if(oldButtons != pad.Buttons)
	{
		if( gCheatsEnabled && (pad.Buttons & PSP_CTRL_SELECT) )
		{
			CheatCodes_Activate( GS_BUTTON );
		}

		if(pad.Buttons & PSP_CTRL_HOME)
		{
			while(!activate_pause_menu)
			{
				sceCtrlPeekBufferPositive(&pad, 1);
				if(!(pad.Buttons & PSP_CTRL_HOME))
				{
					activate_pause_menu = true;
				}
			}
		}
	}
	oldButtons = pad.Buttons;

	if(activate_pause_menu)
	{
		// See how much texture memory we're using
		//CTextureCache::Get()->DropTextures();
//#ifdef DAEDALUS_DEBUG_MEMORY
		//CVideoMemoryManager::Get()->DisplayDebugInfo();
//#endif

		// No longer needed since we save normally now, and not jsut when entering the pause menu ;)
		//Save_Flush(true);

		// switch back to the LCD display
		CGraphicsContext::Get()->SwitchToLcdDisplay();

		// Call this initially, to tidy up any state set by the emulator
		CGraphicsContext::Get()->ClearAllSurfaces();

		CDrawText::Initialise();

		CUIContext *	p_context( CUIContext::Create() );

		if(p_context != NULL)
		{
			// Already set in ClearBackground() @ UIContext.h
			//p_context->SetBackgroundColour( c32( 94, 188, 94 ) );		// Nice green :)

			CPauseScreen *	pause( CPauseScreen::Create( p_context ) );
			pause->Run();
			delete pause;
			delete p_context;
		}

		CDrawText::Destroy();

		//
		// Commit the preferences database before starting to run
		//
		CPreferences::Get()->Commit();
	}
	//
	//	Reset the elapsed time to avoid glitches when we restart
	//
#ifdef DAEDALUS_PROFILE_EXECUTION
	gTimer.Reset();
#endif

}
Beispiel #13
0
	virtual void Execute(LPCSTR args) {
		
#if 0
		if (!Level().autosave_manager().ready_for_autosave()) {
			Msg		("! Cannot save the game right now!");
			return;
		}
#endif
		if(!IsGameTypeSingle()){
			Msg("for single-mode only");
			return;
		}
		if(!g_actor || !Actor()->g_Alive())
		{
			Msg("cannot make saved game because actor is dead :(");
			return;
		}

		string_path				S,S1;
		S[0]					= 0;
//.		sscanf					(args ,"%s",S);
		strcpy_s					(S,args);
		
#ifdef DEBUG
		CTimer					timer;
		timer.Start				();
#endif
		if (!xr_strlen(S)){
			strconcat			(sizeof(S),S,Core.UserName,"_","quicksave");
			NET_Packet			net_packet;
			net_packet.w_begin	(M_SAVE_GAME);
			net_packet.w_stringZ(S);
			net_packet.w_u8		(0);
			Level().Send		(net_packet,net_flags(TRUE));
		}else{
			if(!valid_file_name(S)){
				Msg("invalid file name");
				return;
			}

			NET_Packet			net_packet;
			net_packet.w_begin	(M_SAVE_GAME);
			net_packet.w_stringZ(S);
			net_packet.w_u8		(1);
			Level().Send		(net_packet,net_flags(TRUE));
		}
#ifdef DEBUG
		Msg						("Game save overhead  : %f milliseconds",timer.GetElapsed_sec()*1000.f);
#endif
		SDrawStaticStruct* _s		= HUD().GetUI()->UIGame()->AddCustomStatic("game_saved", true);
		_s->m_endTime				= Device.fTimeGlobal+3.0f;// 3sec
		string_path					save_name;
		strconcat					(sizeof(save_name),save_name,*CStringTable().translate("st_game_saved"),": ", S);
		_s->wnd()->SetText			(save_name);

		strcat					(S,".dds");
		FS.update_path			(S1,"$game_saves$",S);
		
#ifdef DEBUG
		timer.Start				();
#endif
		MainMenu()->Screenshot		(IRender_interface::SM_FOR_GAMESAVE,S1);

#ifdef DEBUG
		Msg						("Screenshot overhead : %f milliseconds",timer.GetElapsed_sec()*1000.f);
#endif
	}
Beispiel #14
0
void BatchTestMain( int argc, char* argv[] )
{
	// TODO: Allow other directories and configuration
#ifdef DAEDALUS_PSP
	const char * const romdir = "host1:/";
#else
	const char * const romdir = g_DaedalusConfig.mRomsDir;
#endif

	bool	random_order( false );		// Whether to randomise the order of processing, to help avoid hangs
	bool	update_results( false );	// Whether to update existing results
	s32		run_id( -1 );				// New run by default

	for(int i = 1; i < argc; ++i )
	{
		const char * arg( argv[i] );
		if( *arg == '-' )
		{
			++arg;
			if( strcmp( arg, "rand" ) == 0 || strcmp( arg, "random" ) == 0 )
			{
				random_order = true;
			}
			else if( strcmp( arg, "u" ) == 0 || strcmp( arg, "update" ) == 0 )
			{
				update_results = true;
			}
			else if( strcmp( arg, "r" ) == 0 || strcmp( arg, "run" ) == 0 )
			{
				if( i+1 < argc )
				{
					++i;	// Consume next arg
					run_id = atoi( argv[i] );
				}
			}
		}
	}

	IO::Filename batchdir;
	Dump_GetDumpDirectory( batchdir, "batch" );

	IO::Filename rundir;
	if( run_id < 0 )
	{
		if( !MakeRunDirectory( rundir, batchdir ) )
		{
			printf( "Couldn't start a new run\n" );
			return;
		}
	}
	else
	{
		SprintRunDirectory( rundir, batchdir, run_id );
		if( !IO::Directory::IsDirectory( rundir ) )
		{
			printf( "Couldn't resume run %d\n", run_id );
			return;
		}
	}

	gBatchTestEventHandler = new CBatchTestEventHandler();

	IO::Filename logpath;
	MakeNewLogFilename( logpath, rundir );
	gBatchFH = fopen(logpath, "w");
	if( !gBatchFH )
	{
		printf( "Unable to open '%s' for writing", logpath );
		return;
	}

	std::vector< std::string > roms;
	MakeRomList( romdir, roms );

	u64 time;
	if( NTiming::GetPreciseTime( &time ) )
		srand( (int)time );

	CTimer	timer;

	//	Set up an assert hook to capture all asserts
	SetAssertHook( BatchAssertHook );

	// Hook in our Vbl handler.
	CPU_RegisterVblCallback( &BatchVblHandler, NULL );

	IO::Filename tmpfilepath;
	IO::Path::Combine( tmpfilepath, rundir, "tmp.tmp" );

	while( !roms.empty() )
	{
		gBatchTestEventHandler->Reset();

		u32 idx( 0 );

		// Picking roms in a random order means we can work around roms which crash the emulator a little more easily
		if( random_order )
			idx = rand() % roms.size();

		std::string	r;
		r.swap( roms[idx] );
		roms.erase( roms.begin() + idx );

		// Make a filename of the form: '<rundir>/<romfilename>.txt'
		IO::Filename rom_logpath;
		IO::Path::Combine( rom_logpath, rundir, IO::Path::FindFileName( r.c_str() ) );
		IO::Path::SetExtension( rom_logpath, ".txt" );

		bool	result_exists( IO::File::Exists( rom_logpath ) );

		if( !update_results && result_exists )
		{
			// Already exists, skip
			fprintf( gBatchFH, "\n\n%#.3f: Skipping %s - log already exists\n", timer.GetElapsedSecondsSinceReset(), r.c_str() );
		}
		else
		{
			fprintf( gBatchFH, "\n\n%#.3f: Processing: %s\n", timer.GetElapsedSecondsSinceReset(), r.c_str() );

			gRomLogFH = fopen( tmpfilepath, "w" );
			if( !gRomLogFH )
			{
				fprintf( gBatchFH, "#%.3f: Unable to open temp file\n", timer.GetElapsedSecondsSinceReset() );
			}
			else
			{
				fflush( gBatchFH );

				// TODO: use ROM_GetRomDetailsByFilename and the alternative form of ROM_LoadFile with overridden preferences (allows us to test if roms break by changing prefs)
				System_Open( r.c_str() );

				CPU_Run();

				System_Close();

				const char * reason( CBatchTestEventHandler::GetTerminationReasonString( gBatchTestEventHandler->GetTerminationReason() ) );

				fprintf( gBatchFH, "%#.3f: Finished running: %s - %s\n", timer.GetElapsedSecondsSinceReset(), r.c_str(), reason );

				// Copy temp file over rom_logpath
				gBatchTestEventHandler->PrintSummary( gRomLogFH );
				fclose( gRomLogFH );
				gRomLogFH = NULL;
				if( result_exists )
				{
					IO::File::Delete( rom_logpath );
				}
				if( !IO::File::Move( tmpfilepath, rom_logpath ) )
				{
					fprintf( gBatchFH, "%#.3f: Coping %s -> %s failed\n", timer.GetElapsedSecondsSinceReset(), tmpfilepath, rom_logpath );
				}
			}

		}

	}

	CPU_UnregisterVblCallback( &BatchVblHandler, NULL );
	SetAssertHook( NULL );

	fclose( gBatchFH );
	gBatchFH = NULL;

	delete gBatchTestEventHandler;
	gBatchTestEventHandler = NULL;
}
Beispiel #15
0
void CLandmark::getQG_optimized()
{
#ifdef _OPENMP
//	omp_set_num_threads(omp_get_max_threads());
	omp_set_num_threads(4);
	#pragma omp parallel for
#endif
	for (unsigned int i=0; i < vertices.size(); ++i)
	{
#ifdef DEBUG_MSG
		CTimer timer;
		double tim;
		timer.tic();
#endif
		int best = 0;
		fl_double_t maximum = -FL_DBL_MAX;

		for (unsigned int j=0; j < q[i].size(); ++j)
		{
			//std::string appearance_type = vertices[i].appearances[j]->getName();
			std::string appearance_type = vertices[i].appearances[j]->getType();
			EAppearanceModelType type = SPARSE_LBP;

			if (appearance_type.compare("SPARSE_LBP")==0)
			{
				type = SPARSE_LBP;
			}

			switch (type)
			{
				case SPARSE_LBP:
					vertices[i].appearances[j]->update_optimized(NFfeaturesPool->getFeaturesFromPool(0), w[i][j], q[i][j], &groundTruthPositionsNF[INDEX(0, i, 2)]);
				break;
				case EXTENDED_SPARSE_LBP:
					// TODO: Implementation needed
				break;
				case HOG:
					// TODO: Implementation needed
				break;
			}

			fl_double_t sum = 0.0;
			//for (int k=0; k < vertices[i].appearances[j]->getFeatureDimension(); ++k)
			for (int k=0; k < vertices[i].appearances[j]->getLength(); ++k)
				sum += q[i][j][k];

			if (sum > maximum)
			{
				maximum = sum;
				best = j;
			}
		}

		vertices[i].best = best;
#ifdef DEBUG_MSG
		tim = timer.toc();
		std::cout << "GetQG: Node " << i << " took " << tim << " ms" << std::endl;
#endif
	}

	for (uint32_t i = 0; i < edges.size(); ++i)
	{
		edges[i]->update(w[kLandmarksCount+i][0], g[i], normalizedFrame, groundTruthPositionsNF);
	}
}
Beispiel #16
0
int upload(const char* file, const char* dst, Sector& client)
{
   //check if file already exists

   struct stat st;
   if (stat(file, &st) < 0)
   {
      cout << "cannot locate source file " << file << endl;
      return -1;
   }

   SNode attr;
   if (client.stat(dst, attr) >= 0)
   {
      if (attr.m_llSize == st.st_size)
      {
         cout << "destination file " << dst << " exists on Sector FS. skip.\n";
         return 0;
      }
   }

   CTimer timer;
   uint64_t t1 = timer.getTime();  // returns time in microseconds (usecs)

   struct stat s;
   stat(file, &s);
   cout << "uploading " << file << " of " << s.st_size << " bytes" << endl;

   SectorFile* f = client.createSectorFile();

   int64_t reserve = s.st_size;
   if (reserve <= 0)
      reserve = 1;

   int r = f->open(dst, SF_MODE::WRITE, "", reserve);
   if (r < 0)
   {
      cerr << "unable to open file " << dst << endl;
      Utility::print_error(r);
      return -1;
   }

   int64_t result = f->upload(file);

   f->close();
   client.releaseSectorFile(f);

   if (result >= 0)
   {
      float throughput = s.st_size * 8.0f / 1000000.0f / ((timer.getTime() - t1) / 1000000.0f);

      cout << "Uploading accomplished! " << "AVG speed " << throughput << " Mb/s." << endl << endl ;
   }
   else
   {
      cout << "Uploading failed! Please retry. " << endl << endl;
      Utility::print_error(result);
      return -1;
   }

   return 0;
}
Beispiel #17
0
void capped_cylinder_ray_collision_test()
{
	Fcylinder c;
	c.m_center.set(0,0,0);
	c.m_direction.set(0,0,1);
	c.m_height=2;
	c.m_radius=1;
	//ray
	Fvector dir,pos;float R;
	dir.set(1,0,0);pos.set(0,0,0);R=3;
	
	//inside
	RAYvsCYLINDER(c,pos,dir,R,FALSE);//true , 1
	RAYvsCYLINDER(c,pos,dir,R,TRUE);//false ,
	dir.set(0,0,1);
	RAYvsCYLINDER(c,pos,dir,R,FALSE);//true , 2
	RAYvsCYLINDER(c,pos,dir,R,TRUE);//false

	//outside
	pos.set(-3,0,0);dir.set(1,0,0);R=4;
	RAYvsCYLINDER(c,pos,dir,R,FALSE);//true , 2
	RAYvsCYLINDER(c,pos,dir,R,TRUE);//true , 2
	R=1;
	RAYvsCYLINDER(c,pos,dir,R,FALSE);//false
	pos.set(0,0,-3);dir.set(0,0,1);R=4;
	RAYvsCYLINDER(c,pos,dir,R,FALSE);//true , 1
	RAYvsCYLINDER(c,pos,dir,R,TRUE);//true, 1

	pos.set(-3,-3,-3);dir.set(1,1,1);dir.normalize();R=10;
	RAYvsCYLINDER(c,pos,dir,R,TRUE);//true, ?
	float ir[2];
	c.intersect(pos,dir,ir);
	//
	pos.set(0,0,0);
	RAYvsCYLINDER(c,pos,dir,R,FALSE);//true, ?
	c.intersect(pos,dir,ir);
	RAYvsCYLINDER(c,pos,dir,R,TRUE);//false
	CTimer t;t.Start();
	for(int i=0;i<1000000;i++)
	{
		Fcylinder c;
		c.m_center.random_point(Fvector().set(2,2,2));
		c.m_direction.random_dir();
		c.m_height=Random.randF(0.2f,2.f);
		c.m_radius=Random.randF(0.1f,2.f);
		//ray
		Fvector dir,pos;float R=Random.randF(0.1f,2.f);
		dir.random_dir();pos.random_point(Fvector().set(2,2,2));
		RAYvsCYLINDER(c,pos,dir,R,TRUE);
	}
	Msg("my RAYvsCYLINDE time %f ms",t.GetElapsed_sec()*1000.f);
	t.Start();
	for(int i=0;i<1000000;i++)
	{
		Fcylinder c;
		c.m_center.random_point(Fvector().set(2,2,2));
		c.m_direction.random_dir();
		c.m_height=Random.randF(0.2f,2.f);
		c.m_radius=Random.randF(0.1f,2.f);
		//ray
		Fvector dir,pos;//float R=Random.randF(0.1f,2.f);
		dir.random_dir();pos.random_point(Fvector().set(2,2,2));
		c.intersect(pos,dir,ir);
	}
		Msg("current intersect time %f ms",t.GetElapsed_sec()*1000.f);

}
Beispiel #18
0
/***********************************************************************************
WinMain - Entry point for program.
***********************************************************************************/
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine, int nCmdShow)
{
    
    CLog *pLog = CLog::Instance();
    pLog->Log(" ");
    pLog->Log("***************************************");
    pLog->Log("Program Start"); 
    pLog->LogDate();   
    pLog->Log("***************************************");
    
    //request player choose fullscreen or windowed mode
    CConfigData cfg;
    cfg.LoadConfigFile("assets//data//config.cfg");
    bool bFullscreen = false;
    
    bFullscreen = cfg.FullScreen;
    int msgReturn = ::MessageBox(NULL, "Fullscreen? (Y/N)", "Select Display Option", MB_YESNO);
    if(msgReturn == IDYES)
      bFullscreen = true;

    //variable declarations
    CGameData gameData;
    CTimer gTimerFPS;
    int gLoopCount = 0;
    int gSecondCount = 0;
    bool g_bRunning = true;
    bool gExitProgram = false; //this is set true with ESC, for rendering to stop properly
    if(bFullscreen == true)
      gameData.m_windowedYOffset = 0;
    else
      gameData.m_windowedYOffset = 21;

    //determine if we play new or saved game
    /*
    gameData.m_playNewGame = true;
    HRESULT hr = ::MessageBox(0, "Play new game?", "New or saved game!", MB_YESNO);
    if(hr == IDYES)
      gameData.m_playNewGame = true;
    else
      gameData.m_playNewGame = false;
    */
    //gameData.m_playNewGame = true;

    //setup game data    

    pLog->Log("Program Name", cfg.ProgramName);
    pLog->Log("Version", cfg.ProgramVersion);

    //create window
    HWND hWnd;
    WNDCLASSEX wc;
    ZeroMemory(&wc, sizeof(WNDCLASSEX));
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = (WNDPROC)WindowProc;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.lpszClassName = "WindowClass";
    wc.hIconSm = LoadIcon (hInstance, MAKEINTRESOURCE(IDI_ICON1)); 
    RegisterClassEx(&wc);
        
    //screen data - need at least 800x600 

	if(!bFullscreen)
	{
		if(cfg.ScreenWidth < 800)
		{
			cfg.ScreenWidth = 800;   
		}
    	if(cfg.ScreenHeight < 600)
		{
			cfg.ScreenHeight = 600;    
		}
	}
	cfg.ScreenLeft = 0;
    cfg.ScreenTop = 0;

    //create window
    std::string sCaption = cfg.ProgramName + " - " + cfg.ProgramVersion;
    hWnd = CreateWindowEx(NULL,
                          "WindowClass",
                          sCaption.c_str(), //cfg.ProgramVersion.c_str(),  
                          bFullscreen == true ? WS_EX_TOPMOST | WS_POPUP : WS_BORDER | WS_CAPTION | WS_SYSMENU,  
                          cfg.ScreenLeft, cfg.ScreenTop, 
                          bFullscreen == true ? CW_USEDEFAULT : cfg.ScreenWidth, 
                          bFullscreen == true ? CW_USEDEFAULT : cfg.ScreenHeight,
                          NULL,NULL,hInstance,NULL);
    ShowWindow(hWnd, nCmdShow);
    pLog->Log("Window Loaded and Displayed!");
    gameData.m_hWnd = hWnd;

    // set up and initialize Direct3D
	CGraphics con(hWnd, cfg.ScreenWidth, cfg.ScreenHeight, cfg.RefreshRate, (D3DFORMAT)cfg.Format, cfg.Adapter, bFullscreen);

    if(con.InitializeDirectX() == false)
	{
      ::MessageBox(hWnd, "Failed to Create IDirect3D9 Interface.", "Error", 0);
      return 0;
    }
	if(con.IsDisplayModeSupported() == false)
	{
	//	::MessageBox(hWnd, "Display mode not supported.", "Error", 0);
  //    	return 0;
	}
	if(con.InitializeDevice() == false)
	{
      ::MessageBox(hWnd, "Could not create IDirect3DDevice9 Device.", "Error", 0);
      return 0;
    }




    //load framework assets
    if(con.LoadAssetFile(cfg.FrameworkAssetFile) == false){
      pLog->Log("Failure loading " + cfg.FrameworkAssetFile);
      ::MessageBox(hWnd,"Failed to load editor.dat file", "Error", 0);
      return 0;
    }
    else
      pLog->Log(cfg.FrameworkAssetFile + " (frame graphics) was loaded successfully!");

    //load game play assets
    if(con.LoadAssetFile(cfg.GamePlayAssetFile) == false){
      pLog->Log("Failure loading " + cfg.GamePlayAssetFile);
      ::MessageBox(hWnd,"Failed to load assets.dat file", "Error", 0);
      return 0;
    }
    else
      pLog->Log(cfg.GamePlayAssetFile + " (game play graphics) was loaded successfully!");

     //load objects
    //***************************************************************************
    if(gameData.LoadObjectFile(cfg.GameObjectFile) == false){
      pLog->Log("Failure loading " + cfg.GameObjectFile);
      //::MessageBox(hWnd,"Failed to load objects.dat file", "Error", 0);
     // return 0;
    }
    else{
      pLog->Log(cfg.GameObjectFile + " (objects file) was loaded successfully!");
     // for(int i = 0; i < gameData.m_catalog.GetTableSize();++i){
//        pLog->Log("object", gameData.m_catalog.GetTerm(i, 0), gameData.m_catalog.GetTerm(i, 2));
     // }
    }

    gTimerKey.Initialize();
    gTimerKey.ResetTimer();
    mouse.SetHandle(hWnd);
    gTimerFPS.Initialize();
    
    //game timer for update
    CTimer timerGame;
    timerGame.Initialize();

    //define events for changing game states
    //*************************************************************************
    //g_pStateIntro->AddTransitionEvent(EVENT_GO_PLAY1, g_pStatePlay1);
    //g_pStatePlay1->AddTransitionEvent(EVENT_GO_CREDITS, g_pStateCredits);   
    g_pStateIntro->AddTransitionEvent(EVENT_GO_MAIN, g_pStateMain);
    g_pStateMain->AddTransitionEvent(EVENT_GO_PLAY1, g_pStatePlay1);
    g_pStateMain->AddTransitionEvent(EVENT_GO_HELP, g_pStateHelp);
    g_pStateMain->AddTransitionEvent(EVENT_GO_CREDITS, g_pStateCredits);
    g_pStatePlay1->AddTransitionEvent(EVENT_GO_QUIT, g_pStateQuit);
    //g_pStatePlay1->AddTransitionEvent(EVENT_GO_MAIN, g_pStateMain);

    g_pStateHelp->AddTransitionEvent(EVENT_GO_MAIN, g_pStateMain);
    g_pStateCredits->AddTransitionEvent(EVENT_GO_QUIT, g_pStateQuit);    
    g_pCurrent = g_pStatePlay1;// g_pStateIntro;

    //************************************** S O U N D ************************
    //initialize sound manager
    //audio setup
    //CAudioManager *pAudio = CAudioManager::Instance();
    //pAudio->LoadFile("assets\\data\\sounds.dat");

    //load sound asset file
    //pAudio->LoadFile(cfg.SoundAssetFile);
/*
    if(pAudio->LoadFile(cfg.SoundAssetFile) == false){
      pLog->Log("Failure loading " + cfg.GamePlayAssetFile);//assets.dat audio files!");
      ::MessageBox(hWnd,"Failed to load assets.dat audio files!", "Error", 0);
    }
    else
      pLog->Log(cfg.GamePlayAssetFile + " (audio) was loaded successfully!");
  */      
/*
    if(pAudio->IsValidSound() == true)
      pLog->Log("Audio system initialized (size)", pAudio->Size());
    else
      pLog->Log("Audio failure!");
*/
    //log all audio files    
    if(cfg.LogDebugInfo == true){
      pLog->Log("************************** Audio Files Loaded **************");
//      for(int i = 0; i < pAudio->Size(); i++){
//        pLog->Log(pAudio->GetFilename(i)); 
//      }
      pLog->Log("");
    }

    // enter the main loop
    //************************************** M A I N  L O O P *****************
    MSG msg;
    pLog->Log("Entering Main Control Loop");
    float timeDiff = 0.0f;
    g_pCurrent->Activate(gameData, cfg, con);

	int iLost = 0;
    //*********************
    // PYRO
    //con.InitializePyro();
    while(g_bRunning)
    {
      DWORD starting_point = GetTickCount();
      ::Sleep(1);
      if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
      {
          if (msg.message == WM_QUIT)
              break;

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

      //manage frame count determination
      gLoopCount++;
      if(gTimerFPS.getTimer(1.0) == true){
        gameData.m_FPS = static_cast<float>(gLoopCount);
        gLoopCount = 0;   
        gSecondCount++;
        if(gSecondCount > 30){ //log every 30 seconds
          gSecondCount = 0;
          if(cfg.LogDebugInfo == true)
            pLog->Log("FPS",gameData.m_FPS);
        }
      }

      //stores mouse button status for use in other classes
      gameData.m_bLeftMouseDown =  mouse.LeftButtonDown();
      gameData.m_bRightMouseDown = mouse.RightButtonDown();
      
      //update
      g_pLast = g_pCurrent;
      g_pNext = g_pCurrent->Update(timerGame.getTimeDifference(), gameData, cfg, con);

      if(g_pNext == g_pStateQuit)
        g_bRunning = false;
      else if(NULL != g_pNext)
	    {
        if(g_pNext != g_pLast){
          g_pLast->Deactivate(gameData, cfg, con);
          g_pCurrent = g_pNext;
          g_pCurrent->Activate(gameData, cfg, con);
        }
      }  
      
iLost = g_pCurrent->IsLost(con, cfg);

if(iLost == 0)
{
	g_pCurrent->Render(con, gameData, cfg);
}
else if(iLost == 2)
{
	g_bRunning = false;
}


      // check the 'escape' key
      if(g_bRunning == false){
        gExitProgram = true;
        PostMessage(hWnd, WM_DESTROY, 0, 0);
      }
    }
    pLog->Log("Exited main loop");
    
    //**************************
    // PYRO
    //con.ClosePyro();
    
    // clean up DirectX and COM
    con.CleanupDirectX();
    Shutdown();

    pLog->Log("DirectX Cleaned Up");
    pLog->Log("Shutdown complete!");
    pLog->Log("***************************************");
    pLog->Log(" Program Terminated Normally");
    pLog->Log("***************************************");

    return static_cast<int>(msg.wParam);
}
Beispiel #19
0
void ProcessFrame(){ //process a frame of animation
  const int LOGO_DISPLAY_TIME=5500; //duration of logo
  const int TITLE_DISPLAY_TIME=20000; //duration of title
  static int not_first = 0;
  static int last_time = Timer.time();
  
  //check for lost surfaces, eg alt+tab
  if(lpPrimary->IsLost()){
    RestoreSurfaces(); Redraw();
  }
  


  switch(GamePhase){ //what phase are we in?
    case LOGO_PHASE: //displaying logo screen
      Sleep(100); //surrender time to other processes
      if(endphase||Timer.elapsed(PhaseTime,LOGO_DISPLAY_TIME))
        change_phase(TITLE_PHASE); //go to title screen
      break;
    case TITLE_PHASE: //displaying title screen
      Sleep(100); //surrender time to other processes
      if(endphase||Timer.elapsed(PhaseTime,TITLE_DISPLAY_TIME))
        change_phase(MENU_PHASE); //go to menu
      break;
	case HELP_PHASE: if(endphase)
					  change_phase(ENEMY_PHASE); //go to menu
    case ENEMY_PHASE: if(endphase)
					  change_phase(MENU_PHASE); //go to menu
      
    case MENU_PHASE: //main menu
	
      Sleep(100); //surrender time to other processes
      if(endphase){
		  if(not_first){
		   CurrentLevel = 0;
		  theObjects.reset(0);
		  }
		  else{
			   not_first = 1;

		  }

		  change_phase(PLAYING_PHASE); //play game
	  }
      break;
    case PLAYING_PHASE: //game engine
	  
		if(Timer.elapsed(last_time,35)){
			if(mouse_mode){
			g_input.Update();	//update the input
			ProcessInput();	//process it
			}
			last_time = Timer.time();
		}

	  ComposeFrame(); //compose a frame in back surface
	  //PutText(temp.c_str(),lpPrimary);
      if(endphase) 
        change_phase(MENU_PHASE); 
	  if(theObjects.lives_remaining < 0){

		  change_phase(GAMEOVER_PHASE);
	  }
	  if(theObjects.won()) {
		 //change_phase(MENU_PHASE);
		  theObjects.reset(++CurrentLevel);
	  }
	  
	  
	  
      break;
	case GAMEOVER_PHASE:
		Sleep(100);
		if(endphase){
			change_phase(MENU_PHASE);
		}
		break;
	default: break;
  }
} //ProcessFrame
Beispiel #20
0
void CGameObject::move(){ //move object
  int time = g_cTimer.time();

  if(time > waitTime){
	  if(!MenuUp){
		  bool moved = false;
		  //do{
			  const float XSCALE = 100.0f; //to scale back horizontal motion
			  const float YSCALE = 100.0f; //to scale back vertical motion
			  const float MARGIN = 100.0f; //margin on top of page

			  float xdelta = 0.0f, ydelta = 0.0f; //change in position
			   //current time
			  int tfactor = time-m_nLastMoveTime; //time since last move

			  //compute xdelta and ydelta, horizontal and vertical distance
			  xdelta = (m_fXspeed * (float)tfactor)/XSCALE; //x distance moved  
			  if(m_bCanFly)
				ydelta = (m_fYspeed * (float)tfactor)/YSCALE; //y distance moved
			  else{
				float t = (float)(time-m_nBirthTime);
				ydelta = 3.0f + m_fYspeed * 2.0f + t*t/10000.0f; //y distance moved
			  }

			  //delta motion

			 D3DXVECTOR3 v = D3DXVECTOR3(m_structLocation.x + xdelta, m_structLocation.y - ydelta, 500.0f);
			 CGameObject* temp = new CGameObject(DUMMY_OBJECT,"dummy",v,0,0);

			 //Check and see if object is a spell

			 switch(m_nObjectType){
			 case FIREBALL_OBJECT: 
			 case LIGHTNING_OBJECT: 
			 case TORNADO_OBJECT: 
			 case BARRIER_OBJECT: 
			 case ENEMYFIREBALL_OBJECT: 
			 case ENEMYHOMING_OBJECT: moved = true; break;

			 case CROW_OBJECT:
			 case MONSTER_OBJECT:
			 case MONSTER2_OBJECT:
			 case FLAMEGUY_OBJECT:
			 case FLAMEGUY2_OBJECT:
			 case ROUNDMAN_OBJECT:
			 case ROUNDMAN2_OBJECT: if(g_cObjectManager.monsterSmartMoveCheck(temp)) moved = true; break;
			 default: moved = true;
			 }

			 /*
			 if(isSpell)
				 moved = true;
			 else if( g_cObjectManager.distance(g_cObjectManager.m_pPlayerObject,temp) < 700.0f) //Can we see the monster? {
				   if(g_cObjectManager.monsterSmartMoveCheck(temp))
						moved = true;
			  else
				  moved = true; //Who cares if the monster is on a tree
			*/

		   if(moved){
			   m_structLocation.x += xdelta; //x motion
			   m_structLocation.y -= ydelta; //y motion
		   }


		   if(m_nBounceCount>=3)m_nLifeTime = 1; //force cull by making lifetime tiny
				m_nLastMoveTime = time;

		 // }while(!moved);

		}
	  else
		  m_nLastMoveTime = time;
	}
  else
	  m_nLastMoveTime = time;
  
}
bool ESceneAIMapTools::GenerateMap(bool bFromSelectedOnly)
{
	bool bRes = false;
	if (!GetSnapList()->empty()){
	    if (!RealUpdateSnapList()) return false;
	    if (m_Nodes.empty()){
			ELog.DlgMsg(mtError,"Append at least one node.");
            return false;
        }

        if (!m_Flags.is(flSlowCalculate)){
            // evict resources
            ExecCommand				(COMMAND_EVICT_OBJECTS);
            ExecCommand				(COMMAND_EVICT_TEXTURES);
        
            // prepare collision model
            u32 avg_face_cnt 		= 0;
            u32 avg_vert_cnt 		= 0;
            u32 mesh_cnt		 	= 0;
            Fbox snap_bb;			
            {
                snap_bb.invalidate	();
                for (ObjectIt o_it=m_SnapObjects.begin(); o_it!=m_SnapObjects.end(); o_it++){
                    CSceneObject* 	S = dynamic_cast<CSceneObject*>(*o_it); VERIFY(S);
                    avg_face_cnt	+= S->GetFaceCount();
                    avg_vert_cnt	+= S->GetVertexCount();
                    mesh_cnt	   	+= S->Meshes()->size();
                    Fbox 			bb;
                    S->GetBox		(bb);
                    snap_bb.merge	(bb);
                }
            }

            SPBItem* pb = UI->ProgressStart(mesh_cnt,"Prepare collision model...");

            CDB::Collector* CL		= ETOOLS::create_collector();
            Fvector verts[3];
            for (ObjectIt o_it=m_SnapObjects.begin(); o_it!=m_SnapObjects.end(); o_it++){
                CSceneObject* 		S = dynamic_cast<CSceneObject*>(*o_it); VERIFY(S);
                CEditableObject*    E = S->GetReference(); VERIFY(E);
                EditMeshVec& 		_meshes = E->Meshes();
                for (EditMeshIt m_it=_meshes.begin(); m_it!=_meshes.end(); m_it++){
                    pb->Inc(AnsiString().sprintf("%s [%s]",S->Name,(*m_it)->Name().c_str()).c_str());
                    const SurfFaces&	_sfaces = (*m_it)->GetSurfFaces();
                    for (SurfFaces::const_iterator sp_it=_sfaces.begin(); sp_it!=_sfaces.end(); sp_it++){
                        CSurface* surf		= sp_it->first;
                        // test passable
    //.			        SGameMtl* mtl 		= GMLib.GetMaterialByID(surf->_GameMtl());
    //.					if (mtl->Flags.is(SGameMtl::flPassable))continue;
                        Shader_xrLC* c_sh	= Device.ShaderXRLC.Get(surf->_ShaderXRLCName());
                        if (!c_sh->flags.bCollision) 			continue;
                        // collect tris
                        const IntVec& face_lst 	= sp_it->second;
                        for (IntVec::const_iterator it=face_lst.begin(); it!=face_lst.end(); it++){
                            E->GetFaceWorld	(S->_Transform(),*m_it,*it,verts);
                            ETOOLS::collector_add_face_d(CL,verts[0],verts[1],verts[2], *it);
                            if (surf->m_Flags.is(CSurface::sf2Sided))
                                ETOOLS::collector_add_face_d(CL,verts[2],verts[1],verts[0], *it);
                        }
                    }
                }
            }
        
            UI->ProgressEnd(pb);

            UI->SetStatus		("Building collision model...");
            // create CFModel
            m_CFModel 			= ETOOLS::create_model_cl(CL);
            ETOOLS::destroy_collector(CL);        
    	}
        
        // building
        Scene->lock			();
CTimer tm;
tm.Start();
        BuildNodes			(bFromSelectedOnly);
tm.GetElapsed_sec();
        Scene->unlock		();
//.        Log("-test time: ",	g_tm.GetElapsed_sec());
		Log("-building time: ",tm.GetElapsed_sec());
//.        Msg("-Rate: %3.2f Count: %d",(g_tm.GetElapsed_sec()/tm.GetElapsed_sec())*100.f,g_tm.count);

        // unload CFModel  
		ETOOLS::destroy_model(m_CFModel);
	
        Scene->UndoSave		();
        bRes = true;

        UI->SetStatus		("");
    }else{ 
    	ELog.DlgMsg(mtError,"Fill snap list before generating slots!");
    }
    return bRes;
}
Beispiel #22
0
void actionServerCallback(const scitos_apps_msgs::ChargingGoalConstPtr& goal, Server* as)
{
    initComponents();
    timer.reset();
    timer.start();
    timeOut = (int) goal->Timeout*1000;
    if (goal->Command == "charge") {
        if (calibrated==false) {
            sprintf(response,"Cannot approach the charging station because the docking is not calibrated.\nRead the readme file on how to perform calibration procedure.");
            state = STATE_REJECTED;
        } else {
            state = STATE_INIT;
            robot->progress = 10;
            robot->lightsOn();
        }
    }
    if (goal->Command == "test") {
        robot->lightsOn();
        ptupos = (int)goal->Timeout;
        robot->movePtu(275,0);
        waitCycles = 0;
        state = STATE_TEST1;
    }
    if (goal->Command == "calibrate") {
        state = STATE_CALIBRATE;
        robot->measure(NULL,NULL,maxMeasurements);
        robot->lightsOn();
    }
    if (goal->Command == "undock") {
        if (chargerDetected == false) {
            state = STATE_REJECTED;
            sprintf(response,"Cannot undock because not on the charging station.");
        } else {
            robot->wait(100);
            state = STATE_UNDOCK_INIT;
        }
    }
    if (state == STATE_REJECTED) {
        result.Message = response;
        server->setAborted(result);
        robot->lightsOff();
        return;
    }
    while (state != STATE_IDLE && state != STATE_ABORTED && state != STATE_TIMEOUT && state != STATE_PREEMPTED) {
        usleep(200000);
        server->publishFeedback(feedback);
    }
    result.Message = response;
    if (state == STATE_PREEMPTED) {
        server->setPreempted(result);
        state = STATE_IDLE;
        robot->lightsOff();
        return;
    } else if (state == STATE_ABORTED) {
        server->setAborted(result);
        robot->lightsOff();
        return;
    } else if (success)
    {
        robot->progress = 100;
        server->setSucceeded(result);
        success = false;
    } else {
        server->setAborted(result);
    }
    robot->lightsOff();
}
void CFrelement::build(unsigned char* signal,int signalLengthi,CFFTPlan *plan,int printStuff)
{
	signalLength = signalLengthi;
	int fftLength = signalLength/2+1;
	if (order > fftLength-1)order = fftLength-1;
	fftw_complex *coeffs;
	double *fftSignal;
	CTimer timer;
	timer.start();
	int tim = 0;
	unsigned char *reconstructed = (unsigned char*)malloc(signalLength*sizeof(unsigned char));

	if (order > 0){
		fftSignal = plan->signal;
		coeffs = plan->coeffs;
		gain = 0;
		for (int i = 0;i<signalLength;i++) gain+=signal[i];
		gain = gain/signalLength;

		for (int i = 0;i<signalLength;i++) fftSignal[i] = (signal[i]-gain);
		timer.reset();
		//cout << "FFT preparation time " << timer.getTime() << endl;

		/*calculation of the spectral model*/
		fftw_execute_dft_r2c(plan->direct,fftSignal,coeffs);
		if (debug) cout << "FFT calculation time " << timer.getTime() << endl;
		timer.reset();
		SFrelement *tmpFrelements = (SFrelement *)malloc(fftLength*sizeof(SFrelement));
		for(int i=0;i<fftLength;i++)
		{
			tmpFrelements[i].amplitude = (coeffs[i][0]*coeffs[i][0]+coeffs[i][1]*coeffs[i][1]);
			tmpFrelements[i].frequency = i;
		}
		//gain = sqrt(tmpFrelements[0].amplitude)/signalLength;

		if (printStuff >0)
		{
			printf("Spectrum: 0 %f\n",gain);
			for (int i = 1;i<printStuff;i++) printf("Spectrum: %i %lf\n",i,sqrt(tmpFrelements[i].amplitude)/signalLength); 
		}

		partial_sort(tmpFrelements+1,tmpFrelements+order+1,tmpFrelements+fftLength,fremenSort);
		//partial_sort(tmpFrelements+1,tmpFrelements+order+1,tmpFrelements+100,fremenSort);
		tim = timer.getTime();

		for(int i=1;i<order+1;i++){
			frelements[i-1].amplitude = sqrt(tmpFrelements[i].amplitude)/signalLength;
			frelements[i-1].phase = atan2(coeffs[tmpFrelements[i].frequency][1],coeffs[tmpFrelements[i].frequency][0]);
			frelements[i-1].frequency = tmpFrelements[i].frequency;
		}
		free(tmpFrelements);
		tim = timer.getTime();
		if (debug) cout << "Spectrum recovery time " << tim << endl;

		reconstruct(reconstructed,plan);
	}else{
		int sum = 0;
		for (int i = 0;i<signalLength;i++) sum += signal[i];
		gain = ((float) sum)/signalLength;
		if (gain < 0.5){ 
			memset(reconstructed,0,signalLength*sizeof(unsigned char)); 
		}else{
			memset(reconstructed,1,signalLength*sizeof(unsigned char));
		} 
	}
	/*calculation of the outlier set*/
	unsigned char flip = 0;
	for (int i = 0;i<signalLength;i++)
	{
		if (signal[i] != (reconstructed[i]^flip)){
			 flip = 1-flip;
			 unsigned int* outlierSetTmp = (unsigned int*)realloc(outlierSet,(outliers+1)*(sizeof(int)));
			 if (outlierSetTmp == NULL) fprintf(stderr,"Failed to reallocate the outlier set!\n"); 
			 outlierSet = outlierSetTmp;
			 outlierSet[outliers++] = i;
		}
	}
	free(reconstructed);

	return;
}
Beispiel #24
0
void state_cleanup()
{
    if (state == STATE_DOCKING_SUCCESS) sprintf(response,"The robot has successfully reached the charger in %i s with precision %.0f mm.",timer.getTime()/1000,realPrecision*1000);
    if (state == STATE_DOCKING_FAILURE) sprintf(response,"The robot has failed reach the charger, which has been seen %i times.",stationSpotted);
    if (state == STATE_UNDOCKING_SUCCESS) sprintf(response,"Undocking  successfully completed.%s",posString);
    if (state == STATE_TEST_SUCCESS) sprintf(response,"Testrun successfully completed at %f %f.",cos(tangle)*tdistance+0.55,sin(tangle)*tdistance);
    if (state == STATE_UNDOCKING_FAILURE) sprintf(response,"Undocking  not completed.");
    if (state == STATE_CALIBRATION_SUCCESS) sprintf(response,"Calibration OK.");
//	if (state == STATE_CALIBRATION_FAILURE) sprintf(response,"Calibration failed.");
    if (state == STATE_TIMEOUT) sprintf(response,"Requested action was not completed in the requested time. Station spotted %i times.\n",stationSpotted);
    if ((int) state >= STATE_DOCKING_SUCCESS && (int)state <= STATE_TIMEOUT) {
        robot->progress = 100;
        state = STATE_IDLE;
        robot->moveHead();
        robot->halt();
        ros::spinOnce();
    }
}
namespace NDataManager
{
	// Default initialize all data
	TNavData			m_navData = {};
	TEnvironmentData	m_environmentData = {};
	TCapeData			m_capeData = {};
	TThrusterData		m_thrusterData = {};
	TCameraMountData	m_cameraMountData = {};
	TControllerData		m_controllerData = {};

	CTimer				m_timer_1hz;
	CTimer				m_timer_10hz;

	uint32_t			m_loopsPerSec = 0;

	// Called during Setup() to initialize any DataManager members to specific values
	void Initialize()
	{
		m_thrusterData.MATC		= true;

		m_cameraMountData.CMNT	= CAMERA_SERVO_TARGET_MIDPOINT_US;
		m_cameraMountData.CMTG	= CAMERA_SERVO_TARGET_MIDPOINT_US;
	}

	void OutputNavData()
	{
		// Print Nav Data on the serial line
		Serial.print( F( "hdgd:" ) );
		Serial.print( m_navData.HDGD );
		Serial.print( ';' );
		Serial.print( F( "deap:" ) );
		Serial.print( m_navData.DEEP );
		Serial.print( ';' );
		Serial.print( F( "deep:" ) );		// Compatibility for 30.1.x cockpit updates
		Serial.print( m_navData.DEEP );
		Serial.print( ';' );
		Serial.print( F( "pitc:" ) );
		Serial.print( m_navData.PITC );
		Serial.print( ';' );
		Serial.print( F( "roll:" ) );
		Serial.print( m_navData.ROLL );
		Serial.print( ';' );
		Serial.print( F( "yaw:" ) );
		Serial.print( m_navData.YAW );
		Serial.print( ';' );
		Serial.print( F( "fthr:" ) );
		Serial.print( m_navData.FTHR );
		Serial.println( ';' );

		Serial.print( F( "norm_roll:" ) );
		Serial.print( m_controllerData.roll );
		Serial.println( ';' );
		Serial.print( F( "norm_pitch:" ) );
		Serial.print( m_controllerData.pitch );
		Serial.println( ';' );
		Serial.print( F( "norm_yaw:" ) );
		Serial.print( m_controllerData.yaw );
		Serial.println( ';' );

		Serial.print( F( "yawError:" ) );
		Serial.print( m_controllerData.yawError );
		Serial.println( ';' );

		Serial.print( F( "yawCommand:" ) );
		Serial.print( m_controllerData.yawCommand );
		Serial.println( ';' );
	}

	void OutputSharedData()
	{
		// Print all other shared data on the serial line

		// Thruster Data
		Serial.print( F( "motorAttached:" ) );
		Serial.print( m_thrusterData.MATC );
		Serial.println( ';' );

		// Camera Mount Data
		Serial.print( F( "servo:" ) );
		Serial.print( m_cameraMountData.CMNT );
		Serial.print( ';' );
		Serial.print( F( "starg:" ) );
		Serial.print( m_cameraMountData.CMTG );
		Serial.println( ';' );

		// Cape Data
		Serial.print( F( "fmem:" ) );
		Serial.print( m_capeData.FMEM );
		Serial.print( ';' );
		Serial.print( F( "vout:" ) );
		Serial.print( m_capeData.VOUT );
		Serial.print( ';' );
		Serial.print( F( "iout:" ) );
		Serial.print( m_capeData.IOUT );
		Serial.print( ';' );
		Serial.print( F( "btti:" ) );
		Serial.print( m_capeData.BTTI );
		Serial.print( ';' );
		Serial.print( F( "atmp:" ) );
		Serial.print( m_capeData.ATMP );
		Serial.print( ';' );
		Serial.print( F( "ver:" ) );
		Serial.print( F( "CUSTOM_BUILD" ) );
		Serial.print( ';' );
		Serial.print( F( "cmpd:" ) );
		Serial.print( F( __DATE__ ) );
		Serial.print( F( ", " ) );
		Serial.print( F( __TIME__ ) );
		Serial.print( F( ", " ) );
		Serial.println( F( __VERSION__ ) );
		Serial.print( ';' );
		Serial.print( F( "time:" ) );
		Serial.print( m_capeData.UTIM );
		Serial.println( ';' );

		// Environment Data
		Serial.print( F( "pres:" ) );
		Serial.print( m_environmentData.PRES );
		Serial.print( ';' );
		Serial.print( F( "temp:" ) );
		Serial.print( m_environmentData.TEMP );
		Serial.println( ';' );

		// Module loop timers in milliseconds
		Serial.print( F( "modtime:" ) );

		for( int i = 0; i < NModuleManager::m_moduleCount; ++i )
		{
			Serial.print( NModuleManager::m_pModules[ i ]->m_name );
			Serial.print( '|' );
			Serial.print( NModuleManager::m_pModules[ i ]->m_executionTime );
			Serial.print( '|' );
		}

		Serial.println( ';' );
	}

	void HandleOutputLoops()
	{
		++m_loopsPerSec;

		// 1Hz update loop
		if( m_timer_1hz.HasElapsed( 1000 ) )
		{
			// Send shared data to beaglebone
			OutputSharedData();

			// Loops per sec
			Serial.print( F( "alps:" ) );
			Serial.print( m_loopsPerSec );
			Serial.println( ';' );

			// Reset loop counter
			m_loopsPerSec = 0;
		}

		// 10Hz Update loop
		if( m_timer_10hz.HasElapsed( 100 ) )
		{
			// Send nav data to beaglebone
			OutputNavData();
		}
	}
}
Beispiel #26
0
void CSheduler::ProcessStep			()
{
	// Normal priority
	u32		dwTime					= Device.dwTimeGlobal;
	CTimer							eTimer;
	for (int i=0;!Items.empty() && Top().dwTimeForExecute < dwTime; ++i) {
		u32		delta_ms			= dwTime - Top().dwTimeForExecute;

		// Update
		Item	T					= Top	();
#ifdef DEBUG_SCHEDULER
		Msg		("SCHEDULER: process step [%s][%x][false]",*T.scheduled_name,T.Object);
#endif // DEBUG_SCHEDULER
		u32		Elapsed				= dwTime-T.dwTimeOfLastExecute;
		bool	condition;
		
		condition					= (NULL==T.Object || !T.Object->shedule_Needed());
		if (condition) {
			// Erase element
#ifdef DEBUG_SCHEDULER
			Msg						("SCHEDULER: process unregister [%s][%x][%s]",*T.scheduled_name,T.Object,"false");
#endif // DEBUG_SCHEDULER
//			if (T.Object)
//				Msg					("0x%08x UNREGISTERS because shedule_Needed() returned false",T.Object);
//			else
//				Msg					("UNREGISTERS unknown object");
			Pop						();
			continue;
		}

		// Insert into priority Queue
		Pop							();

		// Real update call
		// Msg						("------- %d:",Device.dwFrame);
#ifdef DEBUG
		T.Object->dbg_startframe	= Device.dwFrame;
		eTimer.Start				();
//		LPCSTR		_obj_name		= T.Object->shedule_Name().c_str();
#endif // DEBUG

		// Calc next update interval
		u32		dwMin				= _max(u32(30),T.Object->shedule.t_min);
		u32		dwMax				= (1000+T.Object->shedule.t_max)/2;
		float	scale				= T.Object->shedule_Scale	(); 
		u32		dwUpdate			= dwMin+iFloor(float(dwMax-dwMin)*scale);
		clamp	(dwUpdate,u32(_max(dwMin,u32(20))),dwMax);

		

		m_current_step_obj = T.Object;
//			try {
			T.Object->shedule_Update	(clampr(Elapsed,u32(1),u32(_max(u32(T.Object->shedule.t_max),u32(1000)))) );
			if (!m_current_step_obj)
			{
#ifdef DEBUG_SCHEDULER
				Msg						("SCHEDULER: process unregister (self unregistering) [%s][%x][%s]",*T.scheduled_name,T.Object,"false");
#endif // DEBUG_SCHEDULER
				continue;
			}
//			} catch (...) {
#ifdef DEBUG
//				Msg		("! xrSheduler: object '%s' raised an exception", _obj_name);
//				throw	;
#endif // DEBUG
//			}
		m_current_step_obj = NULL;

#ifdef DEBUG
//		u32	execTime				= eTimer.GetElapsed_ms		();
#endif // DEBUG

		// Fill item structure
		Item						TNext;
		TNext.dwTimeForExecute		= dwTime+dwUpdate;
		TNext.dwTimeOfLastExecute	= dwTime;
		TNext.Object				= T.Object;
		TNext.scheduled_name		= T.Object->shedule_Name();
		ItemsProcessed.push_back	(TNext);


#ifdef DEBUG
//		u32	execTime				= eTimer.GetElapsed_ms		();
		// VERIFY3					(T.Object->dbg_update_shedule == T.Object->dbg_startframe, "Broken sequence of calls to 'shedule_Update'", _obj_name );
		if (delta_ms> 3*dwUpdate)	{
			//Msg	("! xrSheduler: failed to shedule object [%s] (%dms)",	_obj_name, delta_ms	);
		}
//		if (execTime> 15)			{
//			Msg	("* xrSheduler: too much time consumed by object [%s] (%dms)",	_obj_name, execTime	);
//		}
#endif // DEBUG

		// 
		if ((i % 3) != (3 - 1))
			continue;

		if (Device.dwPrecacheFrame==0 && CPU::QPC() > cycles_limit)		
		{
			// we have maxed out the load - increase heap
			psShedulerTarget		+= (psShedulerReaction * 3);
			break;
		}
	}

	// Push "processed" back
	while (ItemsProcessed.size())	{
		Push	(ItemsProcessed.back())	;
		ItemsProcessed.pop_back		()	;
	}

	// always try to decrease target
	psShedulerTarget	-= psShedulerReaction;
}
Beispiel #27
0
/**  Start training/learning a model w.r.t. the loss object (and the data supplied to it).
 *
 */
void CBMRM::Train()
{
   CTimer totalTime;             // total runtime of the training
   CTimer innerSolverTime;       // time for inner optimization (e.g., QP or LP)
   CTimer lossAndGradientTime;   // time for loss and gradient computation
   
   unsigned int iter = 0;        // iteration count
   double loss = 0.0;            // loss function value
   double exactObjVal = 0.0;     // (exact) objective function value
   double approxObjVal = -1e99;  // convex lower-bound (approximate) of objective function value
   double minExactObjVal = 1e99; // minimum of all previously evaluated (exact) objective function value
   double regVal = 0.0;          // value of the regularizer term e.g., 0.5*w'*w
   double epsilon = 0.0;         // := minExactObjVal - approxObjVal       
   double gamma = 0.0;           // := exactObjVal - approxObjVal
   double prevEpsilon = 0.0;
   double innerSolverTol = 1.0;  // optimization tolerance for inner solver
   int exitFlag = 0;
   
   unsigned int row = 0; 
   unsigned int col = 0;
   TheMatrix &w = _model->GetW();
   
   w.Shape(row, col);   
   TheMatrix a(row, col, SML::DENSE);   // gradient vector
   TheMatrix w_best(row,col,SML::DENSE);  // w_t at which pobj is the smallest
   
#ifdef PARALLEL_BMRM
   double someloss = 0.0;                     // temporary loss incurred on each sub-dataset
   double *tmpaw = new double[row*col];       // temporary array for gradient/w
   double *tmpfinalaw = new double[row*col];  // temporary final array for reducing/broadcasting gradient/w
#endif

   // start training
   totalTime.Start();

   // Initialize piecewise linear lower bound of empirical risk
   {
      iter = 1;

      lossAndGradientTime.Start();
      _loss->ComputeLossAndGradient(loss, a);
      lossAndGradientTime.Stop();

#ifdef PARALLEL_BMRM
      MASTER(procID)
#endif
      {
         if(verbosity)
         {
            printf("Initial iteration: computing first linearization at w_0... loss(w_0)=%.6e\n",loss);
            fflush(stdout);
         }
      }


#ifdef PARALLEL_BMRM      
      // Aggregate computed loss value and gradient
      for(unsigned int rowidx=0; rowidx<row; rowidx++)
      {
         unsigned int rowlen = 0;
         a.GetRow(rowidx, rowlen, &tmpaw[rowidx*col]);
         assert(rowlen == col);
      }
      memset(tmpfinalaw,0,sizeof(double)*row*col);
      someloss = loss;
      loss = 0.0;
      MPI_Barrier(MPI_COMM_WORLD);
      MPI_Reduce(&someloss, &loss, 1, MPI_DOUBLE, MPI_SUM, ROOT_PROC_ID, MPI_COMM_WORLD);
      MPI_Reduce(tmpaw, tmpfinalaw, row*col, MPI_DOUBLE, MPI_SUM, ROOT_PROC_ID, MPI_COMM_WORLD);   
      for(unsigned int rowidx=0; rowidx<row; rowidx++)
         a.SetRow(rowidx, col, &tmpfinalaw[rowidx*col]);
#endif
   }
   
   do
   {
      iter++;

#ifdef PARALLEL_BMRM
      MASTER(procID)
#endif
      {
         // Minimize piecewise linear lower bound R_t
         innerSolverTime.Start();
         innerSolver->Solve(w, a, loss, approxObjVal);
         innerSolverTime.Stop();
      }

#ifdef PARALLEL_BMRM
      // Broadcast updated w
      for(unsigned int rowidx=0; rowidx<row; rowidx++)
      {
         unsigned int rowlen = 0;
         w.GetRow(rowidx, rowlen, &tmpaw[rowidx*col]);
         assert(rowlen == col);
      }
      memset(tmpfinalaw, 0, sizeof(double)*row*col);
      MPI_Bcast(tmpaw, row*col, MPI_DOUBLE, ROOT_PROC_ID, MPI_COMM_WORLD);
      for (unsigned int rowidx=0; rowidx<row; rowidx++)
         w.SetRow(rowidx, col, &tmpaw[rowidx*col]);
#endif

      // Compute new linearization with updated w
      lossAndGradientTime.Start();
      _loss->ComputeLossAndGradient(loss, a);
#ifdef LINESEARCH_BMRM
      loss = _loss->GetLossOfWbest();
      _loss->GetWbest(w_best);
#endif
      lossAndGradientTime.Stop();

#ifdef PARALLEL_BMRM      
      // Aggregate computed loss value and gradient
      for(unsigned int rowidx=0; rowidx<row; rowidx++)
      {
         unsigned int rowlen = 0;
         a.GetRow(rowidx, rowlen, &tmpaw[rowidx*col]);
         assert(rowlen == col);
      }
      memset(tmpfinalaw,0,sizeof(double)*row*col);
      someloss = loss;
      loss = 0.0;
      MPI_Barrier(MPI_COMM_WORLD);
      MPI_Reduce(&someloss, &loss, 1, MPI_DOUBLE, MPI_SUM, ROOT_PROC_ID, MPI_COMM_WORLD);
      MPI_Reduce(tmpaw, tmpfinalaw, row*col, MPI_DOUBLE, MPI_SUM, ROOT_PROC_ID, MPI_COMM_WORLD);   
      for(unsigned int rowidx=0; rowidx<row; rowidx++)
         a.SetRow(rowidx, col, &tmpfinalaw[rowidx*col]);
#endif
      
#ifdef PARALLEL_BMRM
      MASTER(procID)
#endif
      {
         // Update iteration details and keep best minimizer
#ifdef LINESEARCH_BMRM
         regVal = innerSolver->ComputeRegularizerValue(w_best);
         exactObjVal = loss + regVal;
         minExactObjVal = min(minExactObjVal,exactObjVal);
#else
         regVal = innerSolver->ComputeRegularizerValue(w);
         exactObjVal = loss + regVal;
         if(exactObjVal < minExactObjVal)
         {
            minExactObjVal = exactObjVal;
            w_best.Assign(w);
         }
#endif
         prevEpsilon = epsilon;
         gamma = exactObjVal - approxObjVal;
         epsilon = minExactObjVal - approxObjVal;
      
         // Optional: Adjust inner solver optimization tolerance
         //   This reduces the number of iteration most of the time.
         //   This in some sense mimics the proximity control in proximal BM
         AdjustInnerSolverOptTol(innerSolverTol, prevEpsilon, epsilon);

         // Display details of each iteration
         DisplayIterationInfo(iter,exactObjVal,approxObjVal,epsilon,gamma,
                              loss,regVal,totalTime.CurrentCPUTotal());
            
         // Save model obtained in previous iteration
         SaveCheckpointModel(iter);
      
         // Check if termination criteria satisfied
         exitFlag = CheckTermination(iter,epsilon,gamma,minExactObjVal,exactObjVal);
      }

#ifdef PARALLEL_BMRM
      // Broadcast loop termination flag
      MPI_Bcast(&exitFlag, 1, MPI_INT, ROOT_PROC_ID, MPI_COMM_WORLD);
#endif
   } while(!exitFlag);

   totalTime.Stop();
   
#ifdef PARALLEL_BMRM
   MASTER(procID)
#endif
   {
      // Display after-training details
      DisplayAfterTrainingInfo(iter,minExactObjVal,approxObjVal,loss,
                               w_best,lossAndGradientTime,innerSolverTime,totalTime);
   }
}
int RunTcpTestClient(const char* ip, int port, unsigned int threads, 
			unsigned int request_count, FTcpRequest RequestCb, void* args,
			FClientCtxNew ClientNewCb, FClientCtxFree ClientFreeCb,int expectedCode, int num)
{
	if(threads > MAX_TEST_THREADS){
		NLOG_ERROR("threads(%d) > MAX_TEST_THREADS(%d)", threads, MAX_TEST_THREADS);
		return -1;
	}
	signal(SIGINT, test_signal_handler);
	signal(SIGQUIT, test_signal_handler);

	int connections = threads;

	g_thread_cnt = threads;
	g_timeTimer.InitThreadTimer(&TimerAdd, NULL);
	g_timeTimer.SetTimerName("timeTimer");
	g_timeTimer.StartTimer(0.001, 0.001);

	memset(&g_errors, 0, sizeof(int)*0xFFFF);
	memset(&g_threads, 0, sizeof(CThread*)*MAX_TEST_THREADS);
	memset(&g_ctxs, 0, sizeof(ClientCtx*)*MAX_TEST_THREADS);
	
	unsigned int i;
	NLOG_INFO("################## Test Begin ###################");
	NLOG_INFO("################# Connect Begin #################");
	for(i=0;ClientNewCb != NULL && i < connections; i++){
		g_ctxs[i] = ClientNewCb(ip, port); 
		if(g_ctxs[i] == NULL){
			NLOG_ERROR("Connec to [%s:%d] failed!", ip,port);
			return -1;
		}
	}
	NLOG_INFO("#################  Connect End  #################");

	g_start = second();
	g_now_second = second();

	char threadName[32];
	for(i=0;i < threads; i++){
		sprintf(threadName, "thread-%d", i);
		
		NLOG_INFO("########## One Thread One Socket ##############");
		g_threads[i] = new CTcpTestThread(threadName, g_ctxs[i],
			request_count, &g_counter, RequestCb, args, num);
		
		
		g_threads[i]->Start();

	}
	
	for(i=0;i < threads; i++){
		g_threads[i]->Join();
		delete g_threads[i];
		g_threads[i] = NULL;
	}
	
	for(i=0;ClientFreeCb != NULL&&i < connections; i++){
		ClientFreeCb(g_ctxs[i]);
		g_ctxs[i] = NULL;
	}
	
	NLOG_INFO("################## Test End ###################");
	if((unsigned)g_counter > request_count){//修正for循环引起的超界问题。
		g_counter = request_count;
	}
	Report(expectedCode);

	return 0;
}
Beispiel #29
0
void runDelphi(shared_ptr<SPrime> param)
{
    
#ifdef DELPHI_OUTPUT
    
    string delphi_ntime = "delphi_run_" + to_string(param->ntimes) + ".log";
    
#endif
    
#ifndef DELPHI_OUTPUT
    
    string delphi_ntime = "delphi_run_" + to_string(param->ntimes) + ".log";
    
#endif
    
    ofstream logFile(delphi_ntime);
    StreamRedirector redirect_cout(cout,logFile.rdbuf());
    StreamRedirector redirect_cerr(cerr,logFile.rdbuf());

    cout << boolalpha;
    
    cerr << boolalpha;
    
    
    try
    {
        CTimer * pTester =  new CTimer; // record execution time
        
        pTester->start();
        
        shared_ptr<CTimer> pTimer( new CTimer); // record execution time
        
        
        shared_ptr<IDataContainer> pDataContainer( new CDelphiData(param,pTimer) );

//        pDataContainer->showMap("showmap_atbegin.dat");
        
        int& inhomo(pDataContainer->getKey_Ref<int>("inhomo"));
        const int& iGaussian(pDataContainer->getKey_constRef<int>("gaussian"));
        bool& logs (pDataContainer->getKey_Ref<bool>("logs"));
        bool& logg (pDataContainer->getKey_Ref<bool>("logg"));
        
        inhomo=0;
        
        
        if( iGaussian==1 && logs )
        {
            logg=true; //for gaussian
            inhomo=1;
        }
        
        //********************************************************************************//
        //                                                                                //
        //    realize an object of CDelphiSpace class to construct molecular surfaces     //
        //                                                                                //
        //********************************************************************************//
        
        
        
        unique_ptr<IAbstractModule> pSpace( new CDelphiSpace(pDataContainer,pTimer) );
        
        pSpace->run();
        
        pSpace.reset();
        
//        pDataContainer->showMap("showmap_aftersuf.dat");
        
        if( !(iGaussian==1&&inhomo==0&&logs) )
        {
            cout << " number of atom coordinates read  :" << right << setw(10) << pDataContainer->getKey_constRef<delphi_integer>("natom") << endl;
        }
        
        if (pDataContainer->getKey_constRef<bool>("isolv"))
        {
            if( !(iGaussian==1&&inhomo==0&&logs) )
            {
                cout << " total number of assigned charges :" << right << setw(10) << pDataContainer->getKey_constRef<delphi_integer>("nqass") << endl;
                cout << " net assigned charge              :" << right << setw(10) << pDataContainer->getKey_constRef<delphi_real>("qnet") << endl;
                cout << " assigned positive charge         :" << right << setw(10) << pDataContainer->getKey_constRef<delphi_real>("qplus") << endl;
                cout << " centred at (gu)                  :" << right << setw(10) << pDataContainer->getKey_constRef< SGrid<delphi_real> >("cqplus").nX << " "
                    << right << setw(10) << pDataContainer->getKey_constRef< SGrid<delphi_real> >("cqplus").nY << " "
                    << right << setw(10) << pDataContainer->getKey_constRef< SGrid<delphi_real> >("cqplus").nZ << endl;
                cout << " assigned negative charge         :" << right << setw(10) << pDataContainer->getKey_constRef<delphi_real>("qmin") << endl;
                cout << " centred at (gu)                  :" << right << setw(10) << pDataContainer->getKey_constRef< SGrid<delphi_real> >("cqmin").nX << " "
                    << right << setw(10) << pDataContainer->getKey_constRef< SGrid<delphi_real> >("cqmin").nY << " "
                    << right << setw(10) << pDataContainer->getKey_constRef< SGrid<delphi_real> >("cqmin").nZ << endl;
                cout << "\nnumber of dielectric boundary points" << right << setw(10) << pDataContainer->getKey_constRef<delphi_integer>("ibnum") << endl;
            }
            if (pDataContainer->getKey_constRef<bool>("iexun") && 0 == pDataContainer->getKey_constRef<delphi_integer>("ibnum"))
                throw CNoBndyAndDielec(pTimer);
            
            //********************************************************************************//
            //                                                                                //
            //   realize an object of CDelphiFastSOR class to calculate potentials on grids   //
            //                                                                                //
            //********************************************************************************//

            
            unique_ptr<CDelphiFastSOR> pSolver( new CDelphiFastSOR(pDataContainer,pTimer) );
            
            if (param->bndcon == 3) {
                
               pSolver->getPRIME(param);

            }
            
            pSolver->run();
            
            pSolver.reset();
 
//            pDataContainer->showMap("showmap_afteritr.dat");
            
            //********************************************************************************//
            //                                                                                //
            //          realize an object of CDelphiEnergy class to calculate energies        //
            //                                                                                //
            //********************************************************************************//

            
            unique_ptr<IAbstractModule> pEnergy( new CDelphiEnergy(pDataContainer,pTimer) );
            
            pEnergy->run();
            
            pEnergy.reset();
            
//            pDataContainer->showMap("showmap_aftereng.dat");
            
            if(iGaussian==1&&inhomo==1&&logs) //second run for Gaussian
            {
                inhomo=0;
                
                unique_ptr<IAbstractModule> pSpace( new CDelphiSpace(pDataContainer,pTimer) );
                pSpace->run();
                pSpace.reset();
                
                unique_ptr<IAbstractModule> pSolver( new CDelphiFastSOR(pDataContainer,pTimer) );
                pSolver->run();
                pSolver.reset();
                

                unique_ptr<IAbstractModule> pEnergy( new CDelphiEnergy(pDataContainer,pTimer) );
                pEnergy->run();
                pEnergy.reset();
                
            }

            
            //********************************************************************************//
            //                                                                                //
            //               realize an object of CSite class to write site info              //
            //                                                                                //
            //********************************************************************************//
            
            
            unique_ptr<CSite> pSite( new CSite(pDataContainer,pTimer) );
            
            if (pDataContainer->getKey_constRef<bool>("isite"))
            {
                int iisitsf = 0;
                if (pDataContainer->getKey_Ref<bool>("isitsf")) iisitsf = 1;
                pSite->writeSite(iisitsf);
            }
            
            if (pDataContainer->getKey_constRef<bool>("phiwrt")) pSite->writePhi();
            
//            pDataContainer->showMap("showmap_aftersite.dat");
            
            /*
             * equivalent to out(frc,file="filename") in the parameter file
             
            if (0 == pSite->prime_grdphiv.size())
            {
                pSite.reset();
                pTimer->exit(); pTimer.reset();
            }
            */
            
            param->strAtomDes = pSite->prime_atomdes;
            param->vecGridPot = pSite->prime_grdphiv;
            param->vecSiteCrg = pSite->prime_crhgv;
            
            
            
            
#ifdef PRIME
            pSite->clearIO();
#endif
            
            pSite.reset();

            
        }
        
        //********************************************************************************//
        //                                                                                //
        //       retrieve the solvation energy and grid energy from data container        //
        //                                                                                //
        //********************************************************************************//
        
        param->ergs = pDataContainer->getKey_Val<delphi_real>("ergs");
        param->ergg = pDataContainer->getKey_Val<delphi_real>("ergg");
        
        if(pDataContainer->getKey_constRef<int>("ibctyp") == 2)
        {
            param->igrid1 = pDataContainer->getKey_constRef<delphi_integer>("igrid");
            param->scale1 = pDataContainer->getKey_constRef<delphi_real>("scale");
            param->oldmid1 = pDataContainer->getKey_constRef<SGrid<delphi_real> >("oldmid");
            param->phimap = pDataContainer->getKey_constRef<vector<delphi_real> >("phimap");
            
//            pDataContainer->showMap("test_phimap");
        }
        
        pDataContainer.reset();
        
        pTimer->exit(); pTimer.reset();
        
        delete pTester;
        
#ifdef DELPHI_OUTPUT
        param->ntimes++;
#endif
        remove(&delphi_ntime[0]);
    } // ---------- end of try block
    catch (CException&)
    {
        cerr << "\n\n ......... PROGRAM ABORTS WITH AN EXCEPTION AND " << CWarning::iWarningNum << " WARNING(S) ........\n\n";
    }
    
    cout << "\n\n .........  PROGRAM EXITS SUCCESSFULLY : WITH TOTAL " << CWarning::iWarningNum << " WARNING(S) ........\n\n";
    
    cout.unsetf(ios_base::floatfield); // return to cout default notation 
    
}
Beispiel #30
0
void CRefresher::Reset(CTimer &timer)
{
    m_RefreshTime = timer.RetryTime();
}