Exemple #1
0
void Output(const std::string& filename)
{
	std::cout << "Buggazer tester, PID: " << GetCurrentProcessId() << "\n";
	std::fstream fs;
	fs.open(filename, std::fstream::in);

	if (!fs)
	{
		std::cout << "\"" << filename << "\" not found!\n";
		return;
	}

	std::cout << "Reading " << filename << "...\n";
	std::vector<std::string> lines;
	std::string line;
	while (getline(fs, line))
		lines.push_back(line);
	fs.close();

	std::cout << "writing... " << lines.size() << " lines\n";

	int i = 0;
	long t1 = getMilliCount();

	for (auto s = lines.begin(); s != lines.end(); ++s)
	{
		++i;
		//auto t = s + "\n";
		OutputDebugStringA(s->c_str());
		//Sleep(50);
	}
	long t2 = getMilliCount();

	std::cout << "OutputDebugStringA " << i << " lines, took: " << t2 - t1 << " ms\n";
}
Exemple #2
0
void EndlessTest()
{
	int length = 40; //260
	std::ostringstream ss;
	ss << "123456:jan-7890_ABC__DEF-te m_test";
	ss << length;
	std::string test = ss.str();
	for (size_t i = 0; i < length - test.size() - 1; ++i)
		ss << "X";

	ss << "\n";
	test = ss.str();

	//testLongString();

	for (;;)
	{
		long t1 = getMilliCount();

		for (int a = 0; a < 5; ++a)
		{
			OutputDebugStringA("    ## before me ##\n");

			// write exactly 2MB to the debug buffer;
			for (int i = 0; i < 9; ++i)
				OutputDebugStringA(test.c_str());

			long t2 = getMilliCount();
			OutputDebugStringA("    ## tracking me ##\n");
			std::cout << "took: " << t2 - t1 << " ms\n";
			Sleep(50);
		}
		//OutputDebugStringA("    ----> DBGVIEWCLEAR\n");
	}
}
Exemple #3
0
int getMilliSpan(int nTimeStart)
{
	int nSpan = getMilliCount() - nTimeStart;
	if (nSpan < 0)
		nSpan += 0x100000 * 1000;
	return nSpan;
}
    void GridLayoutTimeline::reload()
    {
        mGridLayouts.clear();

        // playback
        mIdxCurrentLayout = -1;
        mIdxPrevLayout = -1;
        mTransitionAmt = 1.0f;
        mPlaybackSpeed = 1.0f;
        mTotalDuration = 0;
        mStartTime = 0;
        mPlayheadTime = 0;
        mLastFrameTime = getMilliCount();
        
        loadAllGrids();
        
        if (mIdxCurrentLayout == -1)
        {
            ci::app::console() << "Didn't find any serialized grids." << endl;
            // Add an empty layout
            GridLayout newLayout;
            newLayout.setTimestamp(0);
            newLayout.setTransitionDuration(kDefaultTransitionDuration);
            mGridLayouts.push_back(newLayout);
            
            mIdxCurrentLayout = 0;
        }
        
        newLayoutWasSet();
    }
Exemple #5
0
main(int argc, char *argv[]){

	/** Check the number of parameters */
	if (argc < 3) {
		/** Tell the user how to run the program */
		cerr << "Usage: " << argv[0] << " num_col key_file" << endl;
        	return 1;
	}

	mr_init_threading();
	PFC pfc(AES_SECURITY);

	SecureSelect *db=NULL;

	int m=atoi(argv[1]);
	string key_name(argv[2]);

	db = new SecureSelect(m,&pfc,pfc.order());
	#ifdef VERBOSE
	int start = getMilliCount();
	#endif
	db->KeyGen(key_name);
	#ifdef VERBOSE
	int milliSecondsElapsed = getMilliSpan(start);
	cout << "\texec time " << milliSecondsElapsed << endl;
	#endif
}
SpaceShip::SpaceShip() : body(Point2d(INITIAL_X, INITIAL_Y), Point2d(INITIAL_X+BODY_WIDTH, INITIAL_Y+BODY_HEIGHT)), 
						cannon(
							Point2d(INITIAL_X+(BODY_WIDTH-CANON_WIDTH)/2, INITIAL_Y+BODY_HEIGHT),
							Point2d(INITIAL_X+(BODY_WIDTH+CANON_WIDTH)/2, INITIAL_Y+BODY_HEIGHT+CANON_HEIGHT)
						),
						bullets(),
						lastTime(getMilliCount()),
						alive(true) {}
Exemple #7
0
void        BattleShip::shoot( Container & missiles ) {
  if (canShoot()) {
    // missiles.push(new PlasmaCanon(posX + 12, posY + (-2), 1, -.05));
    // missiles.push(new PlasmaCanon(posX + 15, posY + (-1), 1, -.025));
    missiles.push(new PlasmaCanon(posX + 20, posY + 0, 1, 0));
    // missiles.push(new PlasmaCanon(posX + 15, posY + 1, 1, .025));
    // missiles.push(new PlasmaCanon(posX + 12, posY + 2, 1, .05));
    lastShoot = getMilliCount() / 1000.f;
  }
}
void InitGL( void )//__BEGIN_INIT__@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
{
        start = getMilliCount();
    

#include "tier2_GLOBALS.cpp"
        
        //==========================================================================
        #ifdef WIN32
            #include "cpp/setPixelFormat.cpp"
            #include "include/glext_Init_B.cpp"
            //alutInit(NULL, 0);
            //-------------------------------------
            SetVSyncState(true);
            //-----------------------------------------------------------------------------
                        rotateModelWithMiddleMouse[0] = Pass_MIDDLE_Mouse[0];
                        rotateModelWithMiddleMouse[1] = Pass_MIDDLE_Mouse[1];
                        //-----------------------------------------------------------------
                        zoomModelWithMiddleMouse      = Pass_MIDDLE_CONTROL_Mouse;
                        //-----------------------------------------------------------------     
                        moveModelWithMiddleMouse[0]   = Pass_MIDDLE_SHIFT_Mouse[0];
                        moveModelWithMiddleMouse[1]   = Pass_MIDDLE_SHIFT_Mouse[1];
                        //-----------------------------------------------------------------       
       
        //=================
        #endif
    
                   
    

                
        //=======================
        GLuint initializeLocator = 0;
        initializeModels();
        //=======================



    //==============================================================================
    #ifdef WIN32   
        //atexit(KillALData);//_tell_openAL_to_run_KillALData_function_at_shutdown 
    #endif
        
    
    
    glEnable(GL_DEPTH_TEST);
    //glDepthFunc(GL_LEQUAL);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    //glAlphaFunc(GL_GREATER, 0.1);
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
        
//====================================================================================================================================

}//__END_INIT__@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
bool SpaceShip::shootBullet() {
	int nTime = getMilliCount();
	if (nTime - lastTime > RATE_OF_FIRE) {
		lastTime = nTime;
		if (bullets.size() < MAX_BULLETS) {
			bullets.push_back(FriendlyBullet(cannon.getLowerLeft().x, cannon.getLowerLeft().y));
			return true;
		}
	}
	return false;
}
static void libusbCallback(struct libusb_transfer* transfer)
{
  if (start == 0)
  {
    start = getMilliCount();
    count = 0;
  }
  else
  {
    if (getMilliSpan(start) > 1000)
    {
      printf("%f bytes / second\n", (float)count / 1.0);
      start = getMilliCount();
      count = 0;
    }
  }

  count += transfer->actual_length;
  libusb_submit_transfer(transfer);
}
Exemple #11
0
int main( int argc, char* args[] )
{
    Particles emitter;

    //Start up SDL and create window
    if ( init(&gWindow, &renderer) )
    {
        printf( "Failed to initialize!\n" );
    }
    else
    {

        if (load_texture(&smokeTexture,  renderer) == 1) {
            printf("Failed to load texture\n");
        }
        else
        {


            initParticles( &emitter, 170, 315 );

            printf("in main %f\n", emitter.m_speed);
            emitter.m_lastRender = getMilliCount();

            //Main loop flag

#ifdef EMSCRIPTEN
            emscripten_set_main_loop_arg((em_arg_callback_func)loop, (void*)&emitter, 0, 1);
#else
            while (!quit) {
                SDL_Delay(15);
                loop(&emitter);
            }
#endif

        }
    }

    //Free resources and close SDL
    SDL_DestroyTexture(smokeTexture);
    smokeTexture = NULL;

    SDL_DestroyRenderer(renderer);
    renderer = NULL;

    SDL_DestroyWindow(gWindow);
    gWindow = NULL;

    IMG_Quit();
    SDL_Quit();

    return 0;
}
Exemple #12
0
void update(Particles *uemitter, Particle* part, int partNumber)
{
    Particles uemit = *uemitter;
    Uint32 timeElapsed;
    Uint32 curr = getMilliCount();
    timeElapsed = curr - uemit.m_lastRender;
    //printf("get -elapsed %d emitter last render %d\n", timeElapsed, emitter->m_lastRender);
    uemit.particles[partNumber].m_age += timeElapsed;
    if (!isAlive(&(uemit.particles[partNumber])))
    {
        printf("Dead\n");
        //printf( "age %u timedie %u\n", part->m_age, part->m_timeDie);
        // smoke eventually dies
        /*if (r01() > emitter.m_dieRate)
        {
          part->m_canRegen = FALSE;
        }
        if (!part->m_canRegen)
        {
          return;
        }*/
        // regenerate
        uemit.particles[partNumber].m_age = 1;
        startRand(&uemit, &(uemit.particles[partNumber]), partNumber);
        *uemitter = uemit;
        return;
    }
    // At start the particle fades in and expands rapidly (like in real life)
    double fadeIn = uemit.particles[partNumber].m_timeDie * 0.01;
    double startScale;
    double maxStartScale = 0.4;
    if (uemit.particles[partNumber].m_age < fadeIn)
    {
        uemit.particles[partNumber].m_alpha = ((uemit.particles[partNumber].m_age / fadeIn));
        //printf("fade calc = %f \n", (part->m_age/fadeIn)*10 );
        startScale = uemit.particles[partNumber].m_alpha * maxStartScale;
        // y increases quicker because particle is expanding quicker
        uemit.particles[partNumber].m_y += uemit.particles[partNumber].m_yVector * timeElapsed;

    }
    else
    {
        uemit.particles[partNumber].m_alpha = 1.0 - (uemit.particles[partNumber].m_age - fadeIn) / (uemit.particles[partNumber].m_timeDie - fadeIn);
        startScale = maxStartScale;
        uemit.particles[partNumber].m_y += uemit.particles[partNumber].m_yVector * timeElapsed;
    }
    // the x direction is influenced by wind velocity
    uemit.particles[partNumber].m_x += (uemit.particles[partNumber].m_xVector + uemit.m_windVelocity) * timeElapsed;
    uemit.particles[partNumber].m_scale = 0.001 + startScale + uemit.particles[partNumber].m_age / 4000.0;
    //printf( "x = %f y =%f\n", uemit.particles[partNumber].m_x, uemit.particles[partNumber].m_y);
    /*printf("update m_speed: %f\n", emitter->m_speed);*/
    *uemitter = uemit;
}
void DialogVideoPlayer::startPlaying() {
    qDebug() << "Start Playing";
    resizeDisplay();
    playing = true;
    ui->buttonPlay->setIcon(style()->standardIcon(QStyle::SP_MediaPause));
    if (ui->checkBoxMovie->isChecked()) {
        if (mediaPlayer->mediaStatus() == QMediaPlayer::InvalidMedia) {
            ui->checkBoxMovie->setChecked(false);
            ui->checkBoxMovie->setEnabled(false);
            stopPlaying();
            return;
        }

        while(mediaPlayer->mediaStatus() == QMediaPlayer::LoadingMedia) {
            qApp->processEvents();
        }

        mediaPlayer->setPosition(currentTimeMS + movieOffsetMS - firstSampleMS);
        mediaPlayer->play();

        while(mediaPlayer->state() == QMediaPlayer::PlayingState && playing) {

            // Get position in ms with offset since start of movie and map to data
            double current_movie_time = (double)(mediaPlayer->position()) + firstSampleMS - movieOffsetMS;
            updatePlaybackStateTime(current_movie_time);
            qApp->processEvents();
        }
        stopPlaying();
        mediaPlayer->pause();
    } else {
        clockStartTime = getMilliCount();
        playStartSampleMS = p_roughM->at(qMax(0, currentIndex), 0 );
        while(playing) {
            double current_movie_time = playStartSampleMS + getMilliCount() - clockStartTime;
            updatePlaybackStateTime(current_movie_time);
            qApp->processEvents();
        }
        stopPlaying();
    }
}
void SkeletalTracker::LoadPosition( NUI_SKELETON_DATA * pSkel, ArmPosition * pArmPosition)
{
	int i = NUI_SKELETON_POSITION_HAND_RIGHT;
	NuiTransformSkeletonToDepthImage( pSkel->SkeletonPositions[i], &(pArmPosition->m_rightHand.m_x), &(pArmPosition->m_rightHand.m_y), (USHORT*) &( pArmPosition->m_rightHand.m_z) );

	i = NUI_SKELETON_POSITION_HAND_LEFT;
	NuiTransformSkeletonToDepthImage( pSkel->SkeletonPositions[i], &(pArmPosition->m_leftHand.m_x), &(pArmPosition->m_leftHand.m_y), (USHORT*) &(pArmPosition->m_leftHand.m_z) );

	i = NUI_SKELETON_POSITION_HEAD;
	NuiTransformSkeletonToDepthImage( pSkel->SkeletonPositions[i], &(pArmPosition->m_body.m_x), &(pArmPosition->m_body.m_y), (USHORT*) &(pArmPosition->m_body.m_z) );

	pArmPosition->m_startTime = getMilliCount();
}
Exemple #15
0
main(int argc, char *argv[]){

	/** Check the number of parameters */
	if (argc < 5) {
		/** Tell the user how to run the program */
		cerr << "Usage: " << argv[0] << " token encrows results num_threads" << endl;
        	return 1;
	}

	mr_init_threading();
	PFC pfc(AES_SECURITY);

	SecureSelect *db=NULL;

	int m=0;
	string query_name(argv[1]);
	string enctable_name(argv[2]);
	string results_name(argv[3]);
	int num_threads = atoi(argv[4]);

	db = new SecureSelect(&pfc,pfc.order());

	if (!ifstream(query_name+"_ptok")){
		cout << "Query file doesn't exist" << endl;
		return 0;
	}

	if (!ifstream(enctable_name+"_enc_msgs")){
		cout << "Enctable file doesn't exist" << endl;
		return 0;
	}

	#ifdef VERBOSE
	int start = getMilliCount();
	#endif
	int res_num = db->ApplyPTokenMT(query_name, enctable_name, results_name, num_threads);
	//int res_num = db->ApplyPToken(query_name, enctable_name, results_name);
	#ifdef VERBOSE
	int milliSecondsElapsed = getMilliSpan(start);
	cout << "\texec time " << milliSecondsElapsed << endl;
	#endif

	if(res_num >=0){
		cout << res_num << " result(s) found" << endl;
		return 1;
	}
	else
		return 0;

}
Exemple #16
0
double GetWallTime()
{

#ifdef WINDOWS
	return (double)getMilliCount() / 1000.0;
#else
	struct timeval time;
	if (gettimeofday(&time, NULL))
	{
		//  Handle error
		return 0;
	}
	return (double)time.tv_sec + (double)time.tv_usec * .000001;
#endif
}
main(int argc, char *argv[]){

	/** Check the number of parameters */
	if (argc < 6) {
		/** Tell the user how to run the program */
		cerr << "Usage: " << argv[0] << " key_file rows encrows noise num_threads" << endl;
        	return 1;
	}

	/** Set the random seed for noise parameter generation */
	srand(time(NULL));

	mr_init_threading();
	PFC pfc(AES_SECURITY);

	SecureSelect *db=NULL;

	int m=0;
	string key_file(argv[1]);
	string table_name(argv[2]);
	string enctable_name(argv[3]);
	int rand_lim = atoi(argv[4]);
	int num_threads = atoi(argv[5]);

	db = new SecureSelect(&pfc,pfc.order());
	if(!db->LoadKey(key_file))
		return 0;

	if(rand_lim<1){
		cout << "Random paramter < 1, it has to be >= 1" << endl;
		return 0;
	}

	#ifdef VERBOSE
	int start = getMilliCount();
	#endif
	db->EncryptRowsMT(table_name,enctable_name,rand_lim, num_threads);
//	db->EncryptRows(table_name,enctable_name,rand_lim);
	#ifdef VERBOSE
	int milliSecondsElapsed = getMilliSpan(start);
	cout << "\texec time " << milliSecondsElapsed << endl;
	#endif

}
 long long GridLayoutTimeline::update()
 {
     if (mIsPlaying)
     {
         long long timestamp = getMilliCount();
         
         long long timeDelta = (timestamp - mLastFrameTime) * mPlaybackSpeed;
         mPlayheadTime += timeDelta;
         
         mLastFrameTime = timestamp;
         
         int nextID = mIdxCurrentLayout + 1;
         
         // Never loop
         if (nextID < mGridLayouts.size())
         {
             GridLayout & nextLayout = mGridLayouts[nextID];
             
             long long startTimeNextLayout = nextLayout.getTimestamp();
             if (startTimeNextLayout <= mPlayheadTime)
             {
                 stepToNextLayout();
             }
         }
         
         GridLayout & curLayout = mGridLayouts[mIdxCurrentLayout];
         long long startTimeCurLayout = curLayout.getTimestamp();
         long timeIntoLayout = mPlayheadTime - startTimeCurLayout;
         long transitionDuration = curLayout.getTransitionDuration();
         
         // Dont transition into the first slide
         if (mIdxCurrentLayout > 0)
         {
             mTransitionAmt = (float)std::min<double>((double)timeIntoLayout / (double)transitionDuration, 1.0);
         }
         
         return mPlayheadTime;
     }
     
     return 0;
     
 }
Exemple #19
0
void initParticles(Particles *em, int x, int y) {
    em->m_speed = 0.02;
    em->m_alpha = 1.0;
    em->m_windVelocity = 0.025;
    em->m_dieRate = 0.95;
    em->m_x = x;
    em->m_y = y;
    em->m_lastRender = getMilliCount();
    for (int i = 0; i < PART_COUNT; i++)
    {
        em->particles[i].m_x = 0;
        em->particles[i].m_canRegen = 1;
        em->particles[i].m_age = i * 50000 * em->m_speed;

        //Particle *cparticle = &emitter->particles[i];
        startRand(&*em, &((*em).particles[i]), i);
        //printf( "part = %d x = %f y =%f age = %u die = %u\n",i, em.particles[i].m_x, em.particles[i].m_y, em.particles[i].m_age, em.particles[i].m_timeDie);

    }
}
Exemple #20
0
//-------------------------------------------------------------------------
// Calculates the frames per second
//-------------------------------------------------------------------------
void calculateFPS()
{
	//  Increase frame count
	frameCount++;

	//  Get the number of milliseconds since glutInit called
	//  (or first call to glutGet(GLUT ELAPSED TIME)).
	currentTime = getMilliCount();

	//  Calculate time passed
	int timeInterval = currentTime - previousTime;

	if (timeInterval > 1000)
	{
		//  calculate the number of frames per second
		fps = frameCount / (timeInterval / 1000.0f);
		//  Set time
		previousTime = currentTime;

		//  Reset frame count
		frameCount = 0;
	}
}
 void GridLayoutTimeline::play()
 {
     mLastFrameTime = getMilliCount();
     mIsPlaying = true;
 }
bool WorkflowEngine::StartProcessLoop(Configuration * currentConfig) {

    bool isFinished = false;

    if(this->ValidateConfiguration(currentConfig) == false) {
        cerr<<"Config. validation failed. Check modules order!"<< endl;
        return false;
    }

    while(!isFinished) {
#if _DEBUG
        unsigned long start = getMilliCount();
#endif
        vector<Sample *> samples;
        {
            InputModule * module = currentConfig->GetInputModule();
            isFinished = module->Read(samples);
        }

#if _DEBUG
        unsigned long input = getMilliCount();
#endif
        for(int i=0; i< currentConfig->PreprocessingModulesCount(); i++ ) {
            PreprocessingModule * module = currentConfig->GetPreprocessingModule(i);
            module->Process(samples);
        }

#if _DEBUG
        unsigned long preprocessing = getMilliCount();
#endif
        {
            FeatureExtractionModule * module = currentConfig->GetFeatureExtractionModule();
            if(module != NULL) {
                module->ExtractFeatures(samples);
            }
        }

#if _DEBUG
        unsigned long featureExtraction = getMilliCount();
#endif
        for(int i=0; i< currentConfig->PostprocessingModulesCount(); i++ ) {
            PostprocessingModule * module = currentConfig->GetPostprocessingModule(i);
            isFinished |= module->Process(samples);
        }

#if _DEBUG
        unsigned long postprocessing = getMilliCount();
#endif
        {
            FinishingModule * module = currentConfig->GetFinishingModule();
            if(module != NULL) {
                isFinished |= module->Finish(samples);
            }
        }

#if _DEBUG
        unsigned long finishing = getMilliCount();
#endif
        // release all samples
        for(	vector<Sample* >::iterator it = samples.begin();
                it != samples.end();
                it++) {
            delete *it;
        }
#if _DEBUG
        cout << "IN: " << (input - start) <<
             ", PRE: " << (preprocessing - input) <<
             ", FE: " << (featureExtraction - preprocessing) <<
             ", POST: " << (postprocessing - featureExtraction) <<
             ", FIN: " << (finishing - postprocessing) <<
             " (TOTAL: " << (finishing - start) << ")" << endl;
#endif
    }
    return true;
}
            //-----------------------------------------------------------------------------
                        rotateModelWithMiddleMouse[0] = Pass_MIDDLE_Mouse[0];
                        rotateModelWithMiddleMouse[1] = Pass_MIDDLE_Mouse[1];
                        //-----------------------------------------------------------------
                        zoomModelWithMiddleMouse      = Pass_MIDDLE_CONTROL_Mouse;
                        //-----------------------------------------------------------------     
                        moveModelWithMiddleMouse[0]   = Pass_MIDDLE_SHIFT_Mouse[0];
                        moveModelWithMiddleMouse[1]   = Pass_MIDDLE_SHIFT_Mouse[1];
                        //-----------------------------------------------------------------       
       
        //=================
        #endif
                   
                   
                  
start = getMilliCount();
                
//################################################################################################################################
/*
        #ifdef __APPLE__
        
                if(sound_API_selector == 0)
                {
                        #include "AUDIO/openAL_iOS/openAL_iOS_Init.cpp"
                }        
                if(sound_API_selector == 1)
                {        
                        //#include "AUDIO/fMod_iOS/fMod_iOS_Init.cpp" //_____found_in_EAGLView
                }
        
        #endif
static int getMilliSpan( int startTime )
{
  int milliSpan = getMilliCount() - startTime;
  if (milliSpan < 0) milliSpan += 0x100000 * 1000;
  return milliSpan;
}
void DialogVideoPlayer::updatePlaybackState(int index, bool resetTimeSource) {

    bool trigger_fragment_mode = settingPlayMode == PlayModeFragment &&
                                 (index >= ((currentFragment + 1) * samplesPerFragment) || index == -1);

    if (trigger_fragment_mode) {
        if (settingLoop) {
            updatePlaybackState(currentFragment * samplesPerFragment, true);
        } else {
            stopPlaying();
        }
        return;
    }

    bool trigger_whole_file_mode = settingPlayMode == PlayModeWholeFile &&
                                   (index >= (int)p_roughM->n_rows || index == -1);

    if (trigger_whole_file_mode) {
        if (settingLoop) {
            updatePlaybackState(0, true);
        } else {
            stopPlaying();
        }
        return;
    }

    bool segment_in_bounds = currentSegment > 0 && currentSegment - 1 < (int)segmentsM.n_rows;
    bool trigger_segment_mode = segment_in_bounds && settingPlayMode == PlayModeSegment &&
            (index >= segmentsM(currentSegment - 1, SEGCOL_END) || index == -1);
    if (trigger_segment_mode) {

        if (settingLoop) {
            updatePlaybackState(segmentsM(currentSegment - 1, SEGCOL_START), true);
        } else {
            stopPlaying();
        }
        return;
    }

    // Display index
    currentIndex = index;
    currentTimeMS = p_roughM->at(qMax(0, currentIndex), 0 );

    // Display time since start
    int milliseconds = currentTimeMS - firstSampleMS;
    int minutes = floor(milliseconds / 60000);
    milliseconds -= minutes * 60000;
    int seconds = floor(milliseconds / 1000);
    milliseconds -= seconds * 1000;

    ui->labelTime->setText(QString("Time (m:s:ms): %1:%2:%3").arg(minutes).arg(seconds).arg(milliseconds));
    ui->spinBoxIndex->blockSignals(true);
    ui->spinBoxIndex->setValue(currentIndex);
    ui->spinBoxIndex->blockSignals(false);

    // Calculate current fragment
    int current_fragment = currentIndex > -1 ? (int)floor((double)currentIndex / samplesPerFragment) : -1;

    if (current_fragment != currentFragment) {
        currentFragment = current_fragment;
        paintTimeLine();
        paintFixations();
    }

    ui->spinBoxFragment->blockSignals(true);
    ui->spinBoxFragment->setValue(currentFragment);
    ui->spinBoxFragment->blockSignals(false);

    // Calculate current segment
    int current_segment = 0; // 0 means at start of file
    for (uword i = 0; i < segmentsM.n_rows -1; ++i) {
        if (currentIndex >= segmentsM(i, SEGCOL_START)) {
            current_segment = i;
        }
    }

    if (currentSegment != current_segment + 1) {
        currentSegment = current_segment + 1;


        if (!ui->checkBoxMovie->isChecked()) {
            paintBackgroundImage();
        }
    }

    ui->spinBoxSegment->blockSignals(true);
    ui->spinBoxSegment->setValue(currentSegment);
    ui->spinBoxSegment->blockSignals(false);

    paintCurrentVisualizationFrame();
    paintCurrentTimeLineLineFrame();

    if (resetTimeSource) {
        if (ui->checkBoxMovie->isChecked()) {
            mediaPlayer->setPosition(currentTimeMS + movieOffsetMS - firstSampleMS);
        } else {
            clockStartTime = getMilliCount();
            playStartSampleMS = p_roughM->at(qMax(0, currentIndex), 0 );
        }
    }
}
Exemple #26
0
int Timer::getDelta()
{
	m_DeltaMilliseconds = getMilliSpan( m_MilliCount );
	if( m_DeltaMilliseconds > 0 ) m_MilliCount = getMilliCount();
	return m_DeltaMilliseconds;
}
Exemple #27
0
void loop(void *passedEmit)
{
    //runs long enough and something is getting gced and x and y get off
    //change dead routine to use local copy of emitter
    Particles * emit = (Particles *)passedEmit;
    //make a local copy of the emitter
    Particles lemit = *emit;
    double angle = 0.0;
    SDL_Rect *clip = NULL;
    //variable maybe getting optimized out
    //printf("wind %f x = %f y = %f\n", lemit.m_windVelocity, lemit.particles[1].m_x, lemit.particles[1].m_y);
    //Event handler
    SDL_Event ev;

    //Handle events on queue
    while ( SDL_PollEvent( &ev ) != 0 )
    {
        //User requests quit
        if ( ev.type == SDL_QUIT )
        {
            quit = TRUE;
        }
    }


    //emitter->m_speed = 0.02;
    lemit.m_windVelocity += (r01() - 0.5) * 0.0015;
    if (lemit.m_windVelocity > 0.015)
    {
        lemit.m_windVelocity = 0.015;
    }
    if (lemit.m_windVelocity < 0.0)
    {
        lemit.m_windVelocity = 0.0;
    }
    SDL_RenderClear(renderer);
    SDL_RenderCopyEx(renderer,
                     bgTexture,
                     clip,
                     &bg,
                     angle,
                     NULL,
                     SDL_FLIP_NONE);

    for (int i = 0; i < PART_COUNT; i++)
    {
        //Particle *cparticle = &emitter->particles[i];
        update(&lemit, &(lemit.particles[i]), i);
        renderParticle(&(lemit.particles[i]), i);

    }
    //lastmill = getMilliCount();
    SDL_RenderPresent(renderer);
    //Update the surface
    SDL_UpdateWindowSurface( gWindow );
    lemit.m_lastRender = getMilliCount();
    //save the local copy back into the main emitter
    *((Particles *)passedEmit) = lemit;

    //logEmitter( emitter, 0 );

}
Exemple #28
0
Timer::Timer()
{
	m_MilliTimer = getMilliCount();
	m_MilliCount = getMilliCount();
	m_DeltaMilliseconds = getMilliSpan( m_MilliCount );
}
Exemple #29
0
/**
 * Main method (Duh ;) ) Runs the whole simulation. Main loop runs in this method
 *
 * @param argc number of command line arguments
 * @param argsv[] command line parameters. Several Config file parameters can be overriden by setting them here. "--visualize" is especially cool, as it shows an OpenGL live view
 *
 * @return 0 if successful
 */
int main(int argc, char* argsv[]) {
	if (argc > 1 && (!strcmp(argsv[1], "-?") || !strcmp(argsv[1], "help") || !strcmp(argsv[1], "--help"))) {
		std::cout << "This is the NUKULAR Simulator" << std::endl;
		std::cout << "Authors: " << std::endl;
		std::cout << "\tLeonhard Rannabauer" << std::endl;
		std::cout << "\tJakob Weiss" << std::endl;
		std::cout << "\tAlexander Winkler" << std::endl;
		std::cout << std::endl;
		std::cout << "By default, configuration will be loaded from a configuration file." << std::endl;
		std::cout << "The CWD will be searched for \"config.cfg\". Override this by specifying the" << std::endl;
		std::cout << "\t-configFile command line parameter with the path to your own configuration" << std::endl;
		std::cout << "\t(either .xml or .cfg format)" << std::endl;
		std::cout << std::endl;
		std::cout << "EXAMPLE: ./MolSim -configFile simulationConfig.xml -outputFilePrefix MD_sim -endTime 10" << std::endl;
		std::cout << std::endl;
		std::cout << "\t will load Settings from simulationConfig.xml, simulate the world for 10 seconds" << std::endl;
		std::cout << "\t and output the files with a prefix of \"MD_sim\", which will lead to files like" << std::endl;
		std::cout << "\t\"MD_sim_0010.vtu\"" << std::endl;
		return 0;
	}

	std::cout << "Initializing the logger..." << std::endl << std::flush;
	//Initialize the logging stuff
	initializeLogger();


	Settings::initSettings(argc, argsv);

	LOG4CXX_TRACE(rootLogger, "Settings initialized!");

#ifdef _OPENMP
	if(Settings::numThreads > 0) {
		LOG4CXX_INFO(rootLogger, "Setting OpenMP Threads to " << Settings::numThreads);
		omp_set_num_threads(Settings::numThreads);
	}
	else {
		LOG4CXX_INFO(rootLogger, "Running on " << omp_get_max_threads() << " threads");
		Settings::numThreads = omp_get_max_threads();
	}
#else
	Settings::numThreads = 1;
	LOG4CXX_INFO(rootLogger, "Running serial version!");
#endif

#ifdef PAPI_BENCH
	for(int i=0; i < Settings::numThreads; i++) {
		char fileName[200];
		sprintf(fileName, "CalcF #%i.txt", i);
		papiCalcFCounters[i] = new PapiEnv(fileName);
		sprintf(fileName, "CalcX #%i.txt", i);
		papiCalcXCounters[i] = new PapiEnv(fileName);
	}	
#endif
	//Check if we should be executing some unit tests
	if(!Settings::testCase.empty()) {
		return executeTests();
	}

	LOG4CXX_TRACE(rootLogger, "Creating Simulator instance...");
	Simulator *sim = new Simulator();
#ifndef NOGLVISUALIZER
	outputWriter::theSimulator = sim;
#endif
	//Check if we should initialize with old state file
	if(Settings::inputFile.size() !=0){
		std::cout << "state found"<<std::endl;
	}



	double current_time = Settings::startTime;

	int iteration = 0;

	int benchmarkStartTime = getMilliCount();
	double timeForOneIteration = 0;

	 // for this loop, we assume: current x, current f and current v are known
	int maxIterations = (Settings::endTime - Settings::startTime) / Settings::deltaT;
	int nextProgressBarDraw = 1;
	int iterationsPerPercent = (maxIterations/100) + 1;

	LOG4CXX_INFO(rootLogger, "Will calculate " <<  maxIterations << " iterations and output " << maxIterations/Settings::outputFrequency << " frames ");


	while (current_time < Settings::endTime) {
		if (iteration % Settings::outputFrequency == 0) {
			sim->plotParticles(iteration + Settings::outputFileIterationOffset);
		}
		sim->nextTimeStep();
		iteration++;
		if(iteration == nextProgressBarDraw) {
			nextProgressBarDraw+=iterationsPerPercent;
			printProgressBar(100*iteration/maxIterations, -(benchmarkStartTime - getMilliCount()));
		}
		LOG4CXX_TRACE(rootLogger, "Iteration " << iteration << " finished.");
		current_time += Settings::deltaT;
		timeForOneIteration = ((double)(benchmarkStartTime - getMilliCount()))/iteration;

#ifndef NOGLVISUALIZER
		while(outputWriter::renderingPaused)		usleep(2000);
#endif

#ifdef PAPI_BENCH
		for(int i=0; i < Settings::numThreads; i++) {
			papiCalcFCounters[i]->printResults();
			papiCalcXCounters[i]->printResults();
			papiCalcFCounters[i]->reset();
			papiCalcXCounters[i]->reset();
		}
#endif
	}


	int benchmarkEndTime = getMilliCount();

	if(Settings::saveLastState)
		sim->exportPhaseSpace();
	if(Settings::printStatistics)
		sim->exportStatistics();

	LOG4CXX_INFO(rootLogger, "Simulation finished. Took " << (benchmarkEndTime - benchmarkStartTime)/1000.0 << " seconds");

	delete sim;


	LOG4CXX_DEBUG(rootLogger, "Created " << Particle::createdInstances << " Particle instances (" << Particle::createdByCopy << " by copy)");
	LOG4CXX_DEBUG(rootLogger, "Destroyed " << Particle::destroyedInstances << " Particle instances");

#ifdef PAPI_BENCH
	
	for(int i=0; i < Settings::numThreads; i++) {
		std::cout << "Writing PAPI output for thread " << i << std::endl;
		papiCalcFCounters[i]->createResultFile();
		papiCalcXCounters[i]->createResultFile();
		delete 	papiCalcFCounters[i];
		delete papiCalcXCounters[i];
	}	
#endif
	//10 is arbitrarily chosen. there will always be some stray particles because of
	//static instances that will be destroyed at program exit
#ifndef NOGLVISUALIZER
	if(Particle::createdInstances - Particle::destroyedInstances - outputWriter::render3dParticles.size() > 10) {
#else
	if(Particle::createdInstances - Particle::destroyedInstances > 10) {
#endif
		LOG4CXX_WARN(rootLogger, "Significant mismatch between created and destroyed particle instances. This can be a memory leak! " << (Particle::createdInstances - Particle::destroyedInstances));
	}

	LOG4CXX_DEBUG(rootLogger, "output written. Terminating...");
	return 0;
}


int executeTests() {
	std::cout << "Running tests..." << std::endl;

	CppUnit::TextUi::TestRunner runner;

	bool all = !Settings::testCase.compare("all");

	if(all || !Settings::testCase.compare("ParticleContainer"))
	  runner.addTest(ParticleContainerTests::suite());

	if(all || !Settings::testCase.compare("ParticleGenerator"))
		 runner.addTest(ParticleGeneratorTests::suite());

//	if(all || !Settings::testCase.compare("Settings"))
//		 runner.addTest(SettingsXsdTest::suite());


	if(all || !Settings::testCase.compare("Matrix"))
		 runner.addTest(MatrixTests::suite());

	runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
													   std::cerr ) );
	// Run the tests.
	bool wasSuccessful = runner.run();

	// Return error code 1 if the one of test failed.
	if(wasSuccessful) {
	  std::cout << "Tests ok!" << std::endl;
	}
	else {
		std::cout << "Some tests failed!" << std::endl;
	}

	return wasSuccessful ? 0 : 1;
}