Esempio n. 1
0
ViewPtr<plugin::Api> Simulation::loadPlugin(const String& name) noexcept
{
    try
    {
        // Test if plugin is used
        auto it = m_plugins.find(name);

        // Found
        if (it != m_plugins.end())
            return it->second;

        // Load plugin
        auto api = plugin::Manager::s().load(name);

        if (!api)
            return nullptr;

        // Register API
        m_plugins.emplace(name, api);

        // Init simulation
        api->initSimulation(*this);

        return api;
    }
    catch (const Exception& e)
    {
        Log::warning(e.what());
    }

    return nullptr;
}
Esempio n. 2
0
void fluidControlWidget::resetToCollectedFlux()
{

	if(mySimulation == NULL){
		initSimulation();
	}
	meshMetaInfo & mesh = * Model::getModel()->getMeshInfo();

	std::vector<tuple3f> dirs;
	tuple3f n;

	vector<tuple3f> & constr_dirs = Model::getModel()->getInputCollector().getFaceDir();
	vector<int> & constr_fcs = Model::getModel()->getInputCollector().getFaces();

	for(int i = 0; i < mesh.getBasicMesh().getFaces().size(); i++){
		

		dirs.push_back(tuple3f());
	}

	for(int i = 0; i < constr_dirs.size(); i++){
		dirs[constr_fcs[i]] = constr_dirs[i];
	}

	mySimulation->setFlux(dirs);
	mySimulation->flux2Vorticity();
	
	mySimulation->showFlux2Vel();

	
}
Esempio n. 3
0
void fluidControlWidget::singleSimulationStep()
{
	if(mySimulation == NULL){
		initSimulation();
	}
	//this->mySimulation->pathTraceAndShow((0.f +this->stepSlider->value())/100);
	this->updateTimeStep();
	this->mySimulation->oneStep();
	updateAnimationLabel(mySimulation->getSimTime(), mySimulation->getFPS());
	mySimulation->showFlux2Vel();
}
Esempio n. 4
0
void fluidControlWidget::debugSome2()
{
	if(borderConstrDirs.size()!=2){
		return;
	}
	if(mySimulation == NULL){
		initSimulation();
	}

	meshMetaInfo * mesh = Model::getModel()->getMeshInfo();
	
	//set up a harmonic field
	borderConstrDirs[0].set(0,0.1,0);
	borderConstrDirs[1].set(0,0,0);
	oneForm harmonicFlux = mySimulation->setHarmonicFlow(borderConstrDirs);
	mySimulation->showHarmonicField();
	mySimulation->updateVelocities();

	//compute the actual fluxes of the vel field.
	harmonicFlux.add(mySimulation->getFlux());
	vector<tuple3f> & vels = mySimulation->getVelocities();

	//pathtrace 0 and calc pathtraced velocities.
	mySimulation->pathTraceDualVertices(0);
	mySimulation->updateBacktracedVelocities();

	//velocity difference of timestep 0 backtraced velocity and velocity-
	vector<tuple3f> & backtracedVels = mySimulation->getBacktracedVelocities();
	vector<double> temp;
	for(int i = 0; i < backtracedVels.size(); i++){
		temp.push_back((backtracedVels[i]- vels[i]).norm());
	}
	saveVector<double>(temp, "velDiff","C:/Users/bertholet/Dropbox/To Delete/pathTracingTests/time0backtracedVelvsVel.m");

	temp.clear();
	for(int i = 0; i < backtracedVels.size(); i++){
		temp.push_back((vels[i]).norm());
	}
	saveVector<double>(temp, "velNorm","C:/Users/bertholet/Dropbox/To Delete/pathTracingTests/velocityNorms.m");

	//calc backtraced vorticities
	mySimulation->backtracedVorticity();
	nullForm & vort = mySimulation->getVorticity();

	saveVector<double>(vort.getVals(), "tracedVort","C:/Users/bertholet/Dropbox/To Delete/pathTracingTests/time0backtracedVort.m");
	pardisoMatrix star2d1 = DDGMatrices::star2(*mesh)* DDGMatrices::d1(*mesh);
	
	//calc "true" vorticity
	star2d1.mult(harmonicFlux.getVals(),temp,true);
		saveVector<double>(vort.getVals(), "trueVort","C:/Users/bertholet/Dropbox/To Delete/pathTracingTests/trueCalcedVort.m");

}
Esempio n. 5
0
void fluidControlWidget::updateTimeStep()
{
	if(mySimulation == NULL){
		initSimulation();
	}
	stepSize = getTimestep();

	stringstream ss;
	ss << "Timestep Size (" << stepSize << ")";
	this->stepSliderLabel->setText(ss.str().c_str());

	this->mySimulation->setStepSize(stepSize);
//	this->mySimulation->pathTraceAndShow(stepSize);
}
Esempio n. 6
0
void fluidControlWidget::updateViscosity()
{
	if(mySimulation == NULL){
		initSimulation();
	}

	float viscy = getViscosity();

	stringstream ss;
	ss << "Viscosity (" << viscy<< ")";
	this->viscosityLabel->setText(ss.str().c_str());

	mySimulation->setViscosity(viscy);
}
Esempio n. 7
0
double runSimulation(double arrivalRate, double serviceTime, double simTime)
{
	struct Simulation sim;
	struct Data temp;
	int e;

	sim = initSimulation(arrivalRate, serviceTime, simTime);

	while (sim.timeForNextDeparture < simTime) {
			if (sim.timeForNextArrival > sim.timeForNextDeparture && sim.buffer.currSize != 0) {
			sim.e = 1;
		}
		else {
			sim.e = 0;
		}
		e = sim.e;
		switch (e) {
/*Packet arriving*/
			case ARRIVAL:
				temp.arrivalTime = sim.timeForNextArrival;
				enqueue(&(sim.buffer), temp);
				sim.currTime = sim.timeForNextArrival;
				sim.timeForNextArrival += getRandTime(arrivalRate);
				break;
/*Packet departing*/						
			case DEPARTURE:
				temp = dequeue(&(sim.buffer));
				temp.departureTime = sim.timeForNextDeparture;
				sim.currTime = sim.timeForNextDeparture;
				if (sim.buffer.currSize != 0) {
					sim.timeForNextDeparture += serviceTime;
				}
				else {
					sim.timeForNextDeparture = sim.timeForNextArrival + serviceTime;
				}
				enqueue(&(sim.eventQueue), temp);
				break;
			}
		}
		
/*Freeing what was not departed from the queue*/
		while(sim.buffer.currSize > 0) {
			temp = dequeue(&(sim.buffer));
		}
/*Return average wait time*/
		return calcAverageWaitingTime(&sim);
		
}
Esempio n. 8
0
void fluidControlWidget::setForceFlux()
{
	if(mySimulation == NULL){
		initSimulation();

	}

	vector<tuple3f> & constr_dirs = Model::getModel()->getInputCollector().getFaceDir();
	vector<int> & constr_fcs = Model::getModel()->getInputCollector().getFaces();

	float strength = getForceStrength();
	for(int i = 0; i < constr_dirs.size(); i++){
		dirs[constr_fcs[i]] = constr_dirs[i] * strength;
	}

	mySimulation->setForce(dirs);
}
Esempio n. 9
0
void GLWidget::resetSimulation(bool hardReset)
{   
    
    Simulation *oldSim = NULL;
    HairObject *oldHairObject = NULL;
    if (hardReset){
        oldSim = m_testSimulation;
        oldHairObject = m_hairObject;
        m_testSimulation = NULL;
        m_hairObject = NULL;
    }
    initSimulation();
    initCamera();


    delete oldHairObject;
    delete oldSim;
}
Esempio n. 10
0
int main(int argc, char** argv)
{
   srand(time(0));
   config(&argc, argv);

   initNetwork();
   initSimulation();
   initDisplay(&argc, argv);

   for(;;)
   {
      stepNetwork();
      stepSimulation();
      stepDisplay();
   };

   return 0;
}
Esempio n. 11
0
void fluidControlWidget::flux2vort2flux()
{

	if(mySimulation == NULL){
		initSimulation();
	}

	//mySimulation->flux2Vorticity();

	updateViscosity();
	updateTimeStep();
	
//	mySimulation->addDiffusion2Vorticity();

	
//	mySimulation->vorticity2Flux();
//	mySimulation->showFlux2Vel();


/*	mesh & m = * Model::getModel()->getMesh();
	float temp = 0;
	for(int i = 0; i < m.getVertices().size(); i++){
		temp += Operator::aVornoi(i,m);
	}
	
	cout << "Overall Area: " << temp << "\n";*/

	meshMetaInfo & mesh = *Model::getModel()->getMeshInfo();
	pardisoMatrix dtstar1 = DDGMatrices::dual_d1(mesh) * DDGMatrices::star1(mesh) + DDGMatrices::dual_d1star1_borderdiff(mesh);
	nullForm harmonicVort(mesh);
	oneForm & flux = mySimulation->getHarmonicFlux();
	oneForm f2v2f(mesh);
	fluidTools::flux2Vorticity(flux, harmonicVort, mesh, dtstar1);

	mySimulation->vorticity2Flux(harmonicVort,f2v2f);
	
	fluidTools::flux2Velocity(f2v2f, debugVectors,mesh);

	Model::getModel()->setVectors(& mySimulation->getDualVertices(),&debugVectors);

}
int initCrashSimulationThread(rtSimulationThread_t *p_thread, inputThread_t *p_inputThread)
{
	int ret;
	pthread_mutexattr_t attr;
	
	ret = initRTMutexAttr(&attr);
	if(ret != 0) {
		PRINT_ERR("Failed to init rt mutex attributes (%d).\n", ret);
		return ret;
	}
	
	ret = pthread_mutex_init(&p_thread->simulationMutex, &attr);
	if(ret != 0) {
		PRINT_ERR("Failed to init mutex (%d).\n", ret);
		return ret;
	}
	
	ret = pthread_barrier_init(&p_thread->startBarrier, NULL, 2);
	if(ret != 0) {
		PRINT_ERR("Failed to init barrier (%d).\n", ret);
		return ret;
	}
	
	ret = initSimulation(&p_thread->simulation, DEF_DISTANCE);
	if(ret != 0) {
		PRINT_ERR("Failed to init simulation (%d).\n", ret);
		return ret;
	}
	p_thread->simulate = 0;
	p_thread->keepRunning = 0;
	p_thread->running = 0;
	p_thread->exitCode = 0;
	p_thread->inputThread = p_inputThread;
	
	pthread_mutexattr_destroy(&attr);
	
	return 0;
}
Esempio n. 13
0
double runSimulation(double arrivalRate, double serviceTime, double simTime)
{
    struct Simulation sim = initSimulation(arrivalRate, serviceTime, simTime);
    //int i = 0;
    while(sim.currTime < sim.totalSimTime)
    {
        if(sim.timeForNextArrival < sim.timeForNextDeparture)
        {
            sim.currTime = sim.timeForNextArrival;
            struct Data pktdata;
            pktdata.arrivalTime = sim.currTime;
            /* pktdata.departureTime = -1; */
            enqueue(&sim.buffer, pktdata);
            //printf("%d, arrival: %f \n", ++i, sim.currTime);
            sim.timeForNextArrival = sim.currTime + getRandTime(sim.arrivalRate);
        }
        else if(sim.buffer.currSize == 0)
        {
            sim.currTime = sim.timeForNextArrival;
            //printf("%d, skip: %f \n", i, sim.currTime);
            sim.timeForNextDeparture = sim.currTime + sim.serviceTime;
        }
        else if(sim.timeForNextArrival >= sim.timeForNextDeparture)
        {
            sim.currTime = sim.timeForNextDeparture;
            struct Data tempdata = dequeue(&sim.buffer);
            tempdata.departureTime = sim.currTime;
            enqueue(&sim.eventQueue, tempdata);
            //printf("%d, departure: %f \n", i, sim.currTime);
            if(sim.buffer.currSize == 0) sim.timeForNextDeparture = sim.timeForNextArrival + sim.serviceTime;
            else if(sim.buffer.currSize != 0) sim.timeForNextDeparture = sim.currTime + sim.serviceTime;
        }
    }
    double res = calcAverageWaitingTime(&sim);
    freeQueue(&sim.buffer);
    return res;
}
Esempio n. 14
0
void GLWidget::initializeGL()
{
    ResourceLoader::initializeGlew();
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glClearColor(0.5f, 0.5f, 0.5f, 0.0f);
    
    // Initialize shader programs.
    for (auto program = m_programs.begin(); program != m_programs.end(); ++program)
        (*program)->create();
    
    // Initialize textures.
    m_noiseTexture->createColorTexture(":/images/noise128.jpg", GL_LINEAR, GL_LINEAR);
    
    // Initialize framebuffers.
    int shadowMapRes = 2048;
    glm::vec2 finalSize = glm::vec2(2 * width(), 2 * height());
    for (auto framebuffer = m_framebuffers.begin(); framebuffer != m_framebuffers.end(); ++framebuffer)
        (*framebuffer)->create();
    m_hairShadowFramebuffer->generateDepthTexture(shadowMapRes, shadowMapRes, GL_NEAREST, GL_NEAREST);
    m_meshShadowFramebuffer->generateDepthTexture(shadowMapRes, shadowMapRes, GL_LINEAR, GL_LINEAR);
    m_opacityMapFramebuffer->generateColorTexture(shadowMapRes, shadowMapRes, GL_NEAREST, GL_NEAREST);
    m_opacityMapFramebuffer->generateDepthBuffer(shadowMapRes, shadowMapRes);
    m_finalFramebuffer->generateColorTexture(finalSize.x, finalSize.y, GL_LINEAR, GL_LINEAR);
    m_finalFramebuffer->generateDepthBuffer(finalSize.x, finalSize.y);
    m_depthPeel0Framebuffer->generateColorTexture(finalSize.x, finalSize.y, GL_LINEAR, GL_LINEAR);
    m_depthPeel0Framebuffer->generateDepthTexture(finalSize.x, finalSize.y, GL_NEAREST, GL_NEAREST);
    m_depthPeel1Framebuffer->generateColorTexture(finalSize.x, finalSize.y, GL_LINEAR, GL_LINEAR);
    m_depthPeel1Framebuffer->generateDepthBuffer(finalSize.x, finalSize.y);
    
    // Initialize simulation.
    initSimulation();
    
    initCamera();

    ErrorChecker::printGLErrors("end of initializeGL");
}
Esempio n. 15
0
void fluidControlWidget::doAnimation()
{

	if(mySimulation == NULL){
		initSimulation();
	}

	vector<tuple3f> & constr_dirs = Model::getModel()->getInputCollector().getFaceDir();
	vector<int> & constr_fcs = Model::getModel()->getInputCollector().getFaces();

	float strength = getForceStrength();
	if(constr_dirs.size() > 0){
		for(int i = 0; i < constr_dirs.size(); i++){
			dirs[constr_fcs[i]] = constr_dirs[i]*strength;
		}
		mySimulation->setForce(dirs);
		Model::getModel()->getInputCollector().clear();
		forceAge = 0;
		dirs_cleared = false;
	}


	mySimulation->oneStep();
	Model::getModel()->updateObserver(Model::DISPLAY_CHANGED);
	forceAge += 1;

	if(forceAge > maxForceAge && !dirs_cleared){
		for(int i = 0; i < dirs.size(); i++){
			dirs[i].set(0,0,0);
		}
		dirs_cleared = true;
		mySimulation->setForce(dirs);
	}

	updateAnimationLabel(mySimulation->getSimTime(), mySimulation->getFPS());
}
Esempio n. 16
0
void fluidControlWidget::debugSome()
{
#ifdef PRINTMAT
	meshMetaInfo * mesh = Model::getModel()->getMeshInfo();
	pardisoMatrix star0inv = DDGMatrices::star0(*mesh);
	star0inv.saveMatrix("C:/Users/bertholet/Dropbox/To Delete/ddgmatrixTests/star0.m");
	star0inv.elementWiseInv(0.000);

	pardisoMatrix star1 = DDGMatrices::star1(*mesh);
	star1.saveMatrix("C:/Users/bertholet/Dropbox/To Delete/ddgmatrixTests/star1.m");

	pardisoMatrix star2 = DDGMatrices::star2(*mesh);
	star2.saveMatrix("C:/Users/bertholet/Dropbox/To Delete/ddgmatrixTests/star2.m");

	pardisoMatrix d0 = DDGMatrices::d0(*mesh);
	d0.saveMatrix("C:/Users/bertholet/Dropbox/To Delete/ddgmatrixTests/d0.m");

	pardisoMatrix d1 = DDGMatrices::d1(*mesh);
	d1.saveMatrix("C:/Users/bertholet/Dropbox/To Delete/ddgmatrixTests/d1.m");

	pardisoMatrix delta1 = DDGMatrices::delta1(*mesh);
	delta1.saveMatrix("C:/Users/bertholet/Dropbox/To Delete/ddgmatrixTests/delta1.m");

	//pardisoMatrix borderDiff = DDGMatrices::dual_d1_borderdiff(*mesh);
	//borderDiff.saveMatrix("C:/Users/bertholet/Dropbox/To Delete/ddgmatrixTests/borderDiff.m");

	pardisoMatrix duald1_border = DDGMatrices::dual_d1(*mesh);// + DDGMatrices::dual_d1_borderdiff(*mesh);
	duald1_border = duald1_border  + DDGMatrices::dual_d1_borderdiff(*mesh);

	duald1_border.saveMatrix("C:/Users/bertholet/Dropbox/To Delete/ddgmatrixTests/dualD1Border.m");
	pardisoMatrix Lflux = pardisoMatrix::transpose(d1)*star2*d1 + star1*pardisoMatrix::transpose(duald1_border)*star0inv*duald1_border*star1;

	//set matrix to id on border
	/*tuple2i edge;
	int edgeId;
	oneForm fluxConstraint(*mesh);

	vector<double> & fluxConstr = fluxConstraint.getVals();
	vector<tuple3f> & verts = mesh->getBasicMesh().getVertices();
	vector<tuple2i> & edgs = * mesh->getHalfedges();
	vector<double> buff = fluxConstr;
	oneForm constFlux(*mesh);
	vector<double> ddelta_constFlux = constFlux.getVals();



	// setting flux constraints
	vector<vector<int>> & brdr = mesh->getBorder();
	int sz;
	float weight = 10000;
	for(int i = 0; i < brdr.size(); i++){
		sz =brdr[i].size();
		initToConstFlux(constFlux, borderConstrDirs[i]);
		Lflux.mult(constFlux.getVals(), ddelta_constFlux);
		for(int j = 0; j < sz;j++){
			edgeId =mesh->getHalfedgeId(brdr[i][j%sz], brdr[i][(j+1)%sz],&edge);
			assert(edgeId >=0);
			assert((edgs[edgeId].a == brdr[i][j%sz] && edgs[edgeId].b == brdr[i][(j+1)%sz] )||
				(edgs[edgeId].b == brdr[i][j%sz] && edgs[edgeId].a == brdr[i][(j+1)%sz]));


			Lflux.add(edgeId,edgeId,weight);
			fluxConstr[edgeId] = borderConstrDirs[i].dot(verts[edge.b] -verts[edge.a]) * weight + ddelta_constFlux[edgeId];

		}
	}



	pardisoSolver solver(pardisoSolver::MT_ANY, pardisoSolver::SOLVER_DIRECT,3);
	solver.setMatrix(Lflux,1);
	solver.setStoreResultInB(true);
	solver.solve(& (buff[0]), & (fluxConstr[0]));*/
#endif


	if(mySimulation ==  NULL){
		initSimulation();
	}
	
	oneForm harmonicFlux = mySimulation->setHarmonicFlow(borderConstrDirs);
	mySimulation->showHarmonicField();

#ifdef PRINTMAT
	std::vector<double> buff;
	d1.saveVector(harmonicFlux.getVals(),"harmo","C:/Users/bertholet/Dropbox/To Delete/harmonicFlowTest/harmonic.m");
	d1.mult(harmonicFlux.getVals(), buff, true);
	d1.saveVector(buff,"d1_harmo","C:/Users/bertholet/Dropbox/To Delete/harmonicFlowTest/d1_harmonic.m");
	if(mesh->getBorder().size() > 1){
		d1.saveVector(mesh->getBorder()[0],"border_0","C:/Users/bertholet/Dropbox/To Delete/harmonicFlowTest/border0.m");
		d1.saveVector(mesh->getBorder()[1],"border_1","C:/Users/bertholet/Dropbox/To Delete/harmonicFlowTest/border1.m");
	}
	//(duald1_border*star1).mult(harmonicFlux.getVals(), buff,true);
	(DDGMatrices::dual_d1(*mesh)*star1).mult(harmonicFlux.getVals(), buff,true);
	d1.saveVector(buff,"d1star_harmo","C:/Users/bertholet/Dropbox/To Delete/harmonicFlowTest/duald1star_harmonic.m");

	Lflux.mult(harmonicFlux.getVals(), buff,true);
	d1.saveVector(buff,"l_harmo","C:/Users/bertholet/Dropbox/To Delete/harmonicFlowTest/laplace_harmonic.m");
	//mySimulation->setFlux(mySimulation->getVelocities());
	/*mySimulation->setFlux(fluxConstraint);
	mySimulation->showFlux2Vel();*/

#endif

	
}
Esempio n. 17
0
int main(int argc, char** argv)
{
   // Prolog
   initParallel(&argc, &argv);
   profileStart(totalTimer);
   initSubsystems();
   timestampBarrier("Starting Initialization\n");

   yamlAppInfo(yamlFile);
   yamlAppInfo(screenOut);

   Command cmd = parseCommandLine(argc, argv);
   printCmdYaml(yamlFile, &cmd);
   printCmdYaml(screenOut, &cmd);

   SimFlat* sim = initSimulation(cmd);
   printSimulationDataYaml(yamlFile, sim);
   printSimulationDataYaml(screenOut, sim);

   Validate* validate = initValidate(sim); // atom counts, energy
   timestampBarrier("Initialization Finished\n");

   timestampBarrier("Starting simulation\n");

   // This is the CoMD main loop
   const int nSteps = sim->nSteps;
   const int printRate = sim->printRate;
   int iStep = 0;
   profileStart(loopTimer);
   for (; iStep<nSteps;)
   {
      startTimer(commReduceTimer);
      sumAtoms(sim);
      stopTimer(commReduceTimer);

      printThings(sim, iStep, getElapsedTime(timestepTimer));

      startTimer(timestepTimer);
      timestep(sim, printRate, sim->dt);
      stopTimer(timestepTimer);

      iStep += printRate;
   }
   profileStop(loopTimer);

   sumAtoms(sim);
   printThings(sim, iStep, getElapsedTime(timestepTimer));
   timestampBarrier("Ending simulation\n");

   // Epilog
   validateResult(validate, sim);
   profileStop(totalTimer);

   printPerformanceResults(sim->atoms->nGlobal);
   printPerformanceResultsYaml(yamlFile);

   destroySimulation(&sim);
   comdFree(validate);
   finalizeSubsystems();

   timestampBarrier("CoMD Ending\n");
   destroyParallel();

   return 0;
}
Esempio n. 18
0
double runSimulation(double arrivalRate, double serviceTime, double simTime)
{


	struct Simulation sim = initSimulation(arrivalRate, serviceTime, simTime);


	while(sim.currTime < sim.totalSimTime){

	if((sim.timeForNextArrival < sim.timeForNextDeparture) || (sim.buffer.currSize == 0)){
	sim.e = ARRIVAL;
	}
	else{
	sim.e = DEPARTURE;
	}

	//printf("Curr: %lf\n",sim.currTime);
	
	if(sim.e == ARRIVAL){


		sim.currTime = sim.timeForNextArrival;
		
		struct Data d;
		d.arrivalTime = sim.currTime;

		enqueue(&(sim.buffer), d); 

		sim.timeForNextArrival = sim.currTime + getRandTime(sim.arrivalRate);

		if(sim.buffer.currSize == 1){

		sim.timeForNextDeparture = sim.currTime + serviceTime;
		//printf("ok");
		}

	}

	else if(sim.e == DEPARTURE){

		sim.currTime = sim.timeForNextDeparture;
		
		struct Data packet = dequeue(&(sim.buffer));

		//printf("Depart: %lf\n", packet.arrivalTime);
		
		packet.departureTime = sim.currTime;
		//printf("Arrival: %lf\n", packet.arrivalTime);
		//printf("Depart: %lf\n", packet.departureTime);

		sim.timeForNextDeparture = sim.currTime + serviceTime;

		enqueue(&(sim.eventQueue), packet);
	}


	}
	
	return calcAverageWaitingTime(&sim);


}
Esempio n. 19
0
CoMD_return CoMD_lib(CoMD_input *inputStruct)
{

  // Prolog
  //profileStart(totalTimer);
  //initSubsystems();
  
  
  //Command cmd = parseCommandLine(argc, argv);
  
  Command cmd = parseInputStruct(inputStruct);
  
  
  //Ignore stressSuffix for now
  SimFlat* sim = initSimulation(cmd);
  
   Validate* validate = initValidate(sim); // atom counts, energy

	// This is the CoMD main loop
   const int nSteps = sim->nSteps;
   const int printRate = sim->printRate;
   
   double avgStress[9];
   int stressi;
   int iStep;
   for(stressi=0;stressi<9;stressi++) avgStress[stressi]=0;
   
   for (iStep=0; iStep<nSteps;iStep++)
   {
     sumAtoms(sim);
     //Find and intercept these to write to the struct
     //printThings(sim, iStep, getElapsedTime(timestepTimer));
     printTensor(iStep, sim->defInfo->stress);      
     timestep(sim, 1, sim->dt);
     if(iStep>500){
       for(stressi=0;stressi<9;stressi++) avgStress[stressi]+=sim->defInfo->stress[stressi]/(nSteps-500);
     }
   }
   
   sumAtoms(sim);
   //Find and intercept
   //printThings(sim, iStep, getElapsedTime(timestepTimer));
   CoMD_return retVal = printStuff(iStep, sim, avgStress);
   
   // Epilog
   //validateResult(validate, sim);
   //profileStop(totalTimer);
   
   /*
   if (sim->pot->dfEmbed!=NULL) {
     free(sim->pot->dfEmbed);
     sim->pot->dfEmbed=NULL;
   }
   if (sim->pot->rhobar!=NULL) {
     free(sim->pot->rhobar);
     sim->pot->rhobar=NULL;
   }
   if (sim->pot->forceExchangeData!=NULL) {
     free(sim->pot->forceExchangeData);
     sim->pot->forceExchangeData=NULL;
   }*/

   destroySimulation(&sim);
   comdFree(validate);
   //finalizeSubsystems();//???

   //destroyParallel();  //???
   
	return retVal;
}
Esempio n. 20
0
int main(int argc, char **argv)
{
	// TEST LES ARGUMENTS //
	if(argc < 5)
	{
		printf("Usage : vie_sdl width height nbCasesX nbCasesY\nExemple : ./vie_sdl 1920 1080 190 100\n");
		return -1;
	}
	printf("Dimensions de la fenetre : %dx%d\nDimensions de la surface de jeu : %dx%d\n", atoi(argv[1]), atoi(argv[2]), atoi(argv[3]), atoi(argv[4]));
	
	// VARIABLES //
	/// Dimensions de la fenetre
	int winWidth = atoi(argv[1]), winHeight = atoi(argv[2]);
	
	SDL_Surface *screen = NULL, *text = NULL;
	TTF_Font *police = NULL;
	SDL_Event event;
	SDL_Color couleurBlanche = {255, 255, 255};
	
	/// Titre de la fenêtre, infos à afficher
	char caption[64], infos[200];
	int continuer = 1, moving = 0, proliferation = 0, grid = 1;
	
	Fps fps = initFps();
	Simulation sim;
	
	// INITIALISATION //
	srand(time(NULL));
	/// Les arguments 3 et 4 sont les dimensions de la surface de jeu
	initSimulation(&sim, atoi(argv[3]), atoi(argv[4]));
	initSDL(&screen, &police, winWidth, winHeight);
	
	// BOUCLE PRINCIPALE //
	do
	{
		fps.realCpt++;
		/* Gère les évenements */
		while(SDL_PollEvent(&event))
		{
			
			switch(event.type)
			{
				// Clique droit = bouger la vue
				case SDL_MOUSEBUTTONDOWN:
					switch(event.button.button)
					{
						case SDL_BUTTON_RIGHT:
							moving = 1;
							break;
						default:
							break;
					}
					break;
				case SDL_MOUSEBUTTONUP:
					switch(event.button.button)
					{
						case SDL_BUTTON_RIGHT:
							moving = 0;
							break;
						default:
							break;
					}
					break;
				// Si la souris bouge et que le clique droit est enfoncé
				// On déplace la vue
				case SDL_MOUSEMOTION:
					if(moving)
					{
						sim.dispX += event.motion.xrel;
						sim.dispY += event.motion.yrel;
					}
					break;
				case SDL_KEYDOWN: // Gère l'appui sur une touche
					switch(event.key.keysym.sym)
					{
						// Bouge la surface
						case SDLK_a:
							moving = 1;
							break;
						case SDLK_g:
							grid = !grid;
							break;
						// Active la fonction ANTICONVERGENCE !!
						case SDLK_UP:
							proliferation = !proliferation;
							break;
						// Met en pause ou reprend la simulation
						case SDLK_SPACE:
							sim.pause = !sim.pause;
							break;
						// Zoom + et -
						case SDLK_KP_PLUS:
							sim.largeurCase++;
							break;
						case SDLK_KP_MINUS:
							if(sim.largeurCase > 1)
								sim.largeurCase--;
							break;
						// Mode plein écran
						case SDLK_F11:
							screen = SDL_SetVideoMode(winWidth, winHeight, 32, SDL_SWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN);
							break;
						case SDLK_ESCAPE:
							continuer = 0;
						default:
							break;
					}
					break;
				case SDL_KEYUP:
					switch(event.key.keysym.sym)
					{
						case SDLK_a:
							moving = 0;
							break;
						default:
							break;
					}
					break;
				// Redimensionnement de la fenêtre
				case SDL_VIDEORESIZE:
					winWidth = event.resize.w;
					winHeight = event.resize.h;
					screen = SDL_SetVideoMode(winWidth, winHeight, 32, SDL_SWSURFACE | SDL_DOUBLEBUF | SDL_RESIZABLE);
					break;
				case SDL_QUIT:
					continuer = 0;
			}
		}
		
		/* Calculs */
		if(!sim.pause)
		{
			computeFrame(&sim);
			/// ANTICONVERGENCE
			if(proliferation)
				sim.buffers[sim.actualBuffer][rand()%sim.nbCasesX][rand()%sim.nbCasesY] = 1;
		}
		
		/* Dessine l'écran */
		SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 50,50,50));
		/// Dessine les carrés et la grille sur la surface du jeu
		drawGameMatrix(screen, &sim, grid);
			
		/// Ecrit les infos
		sprintf(infos, "dispX = %d dispY = %d", sim.dispX, sim.dispY);
		text = TTF_RenderText_Blended(police, infos, couleurBlanche);
		SDL_BlitSurface(text,NULL, screen, NULL);
		
		// Change le buffer de travail
		if(!sim.pause)
			sim.actualBuffer = !sim.actualBuffer;

		// Régule les FPS
		tempoFps(&fps);
		// Calcul les vrais FPS
		computeTrueFps(&fps);
		
		// Met à jour le titre de la fenêtre
		sprintf(caption, "Game Of Life ! %d fps !", fps.real);
		SDL_WM_SetCaption(caption, NULL);

		
		SDL_Flip(screen);
	}while (continuer);
	
	
	free3DTab(&sim.buffers, 2, sim.nbCasesX);
	
	TTF_CloseFont(police);
	TTF_Quit();
	
	SDL_FreeSurface(screen);
	SDL_Quit();
	return 0;
}