Esempio n. 1
0
int main() {
    Randomize();

    int voters;
    while(true) {
        cout << "Enter number of voters: ";
        voters = GetInteger();
        if (voters > 0) break;
        cout << "Please enter a positive number." << endl;
    }
    
    double spread;
    while(true) {
        cout << "Enter percentage spread between candidates: ";
        spread = GetReal();
        if (spread >= 0 && spread <= 1) break;
        cout << "Spread must be between 0 and 1.0" << endl;
    }

    double error;
    while(true) {
        cout << "Enter voting error percentage: ";
        error = GetReal();
        if (error >= 0 && error <= 1) break;
        cout << "Error percentage must be between 0 and 1.0 " << endl;
    }

    cout << endl << "Chance of an invalid election result after " 
            << NUM_TRIALS << " trials = " 
            << CalculateError(voters, spread, error) << "%" << endl;
    return 0;
}
Esempio n. 2
0
	bool RegulaFalsiMethod::Solve()
	{
		do
		{
			c = ( A*Evaluate(B) - B*Evaluate(A) ) / ( Evaluate(B)-Evaluate(A) );
			_iterations.push_back(*(new Iteration(c, Evaluate(c), CalculateError())));
			(Evaluate(c)*Evaluate(A)<0) ? B = c : A = c;
		} while (ShouldContinue());
		return true;
	}
Esempio n. 3
0
void Masseuse::PrintErrorStatistics(const Values& values){
  // calclate the error
  Error err;
  if(!CalculateError(err, values)){
    std::cerr << "Unable to calculate error metrics." << std::endl;
    return;
  }

  std::cerr << "======================ERROR REPORT=====================" <<
               std::endl;
  std::cerr << "Average trans error (m): " << err.GetAverageTransError() <<
               std::endl;

  std::cerr << "Average rot error (deg): " << err.GetAverageRotError() <<
               std::endl;

  std::cerr << "Total distance traveled (m): " << err.DistanceTraveled() <<
               std::endl;

  std::cerr << "% Avg. trans error: " << err.GetPercentAverageTansError()
               * 100 << " %" << std::endl;

  std::cerr << "Max trans error (m): " << err.MaxTransError() << std::endl;

  std::cerr << "Max rot error (deg): " << err.MaxRotError() << std::endl;

  if(options.enable_switchable_constraints){
    int num_disabled_constraints = 0;
    int num_lcc = 0;
    for(const Factor& f : *graph){
      if(f.isLCC){
        num_lcc++;
        if(f.switch_variable < 0.1){
          num_disabled_constraints++;
        }
      }
    }
    fprintf(stderr, "Number of LCC that were disabled: %d ( %f%% )\n",
            num_disabled_constraints,
            (float)num_disabled_constraints/(float)num_lcc * 100.0f
            );

  }

  std::cerr << "======================================================" <<
               std::endl;

}
Esempio n. 4
0
void CMsgImOutboxSend::CleanUpOnDestructL()
    {
	if(!iSetDisconnected)
		{
		DisconnectUnsentMessagesL();
		}

	if (iStatus.Int() != KErrNone)
		{
		if ((iCurrentMessageNo != -1) && (iCurrentMessageNo<iTotalMessages))
			{
			TInt err=iServerEntry.SetEntry(iEntrySelection.At(iCurrentMessageNo));
			if(err == KErrNotFound)
				{
				User::Leave(KErrNotFound);
				}
			__ASSERT_DEBUG(err == KErrNone, gPanic(EImsmServerError));
			TMsvEntry entry = iServerEntry.Entry();

			RestoreBccRecipientsToHeaderL();

			//	Set date info and completion data..update the iServerEntry with this data..
			TInt errorCode = (TSmtpSessionError)iStatus.Int();
			entry.iDate.UniversalTime();
			if(errorCode!=KErrCancel)
				{
				entry.SetFailed(errorCode != KErrNone);
				entry.SetSendingState(errorCode==KErrNone? KMsvSendStateSent: KMsvSendStateWaiting);  //set it to send agian.
				if (errorCode)
					entry.iError=CalculateError(errorCode);
				}
			else
				{
				entry.SetFailed(EFalse);
				entry.SetSendingState(KMsvSendStateSuspended);
				entry.iError=KErrNone;
				}
			entry.SetConnected(EFalse);
		#ifdef _DEBUG
			err = 
		#endif
			iServerEntry.ChangeEntry(entry);
			__ASSERT_DEBUG(err == KErrNone, gPanic(EImsmServerError));
			}
		}
	}
Esempio n. 5
0
File: ex5.c Progetto: fengyuqi/petsc
int main(int Argc,char **Args)
{
  PetscInt       x_mesh = 15,levels = 3,cycles = 1,use_jacobi = 0;
  PetscInt       i,smooths = 1,*N,its;
  PetscErrorCode ierr;
  PCMGType       am = PC_MG_MULTIPLICATIVE;
  Mat            cmat,mat[20],fmat;
  KSP            cksp,ksp[20],kspmg;
  PetscReal      e[3];  /* l_2 error,max error, residual */
  const char     *shellname;
  Vec            x,solution,X[20],R[20],B[20];
  PC             pcmg,pc;
  PetscBool      flg;

  PetscInitialize(&Argc,&Args,(char*)0,help);

  ierr = PetscOptionsGetInt(NULL,"-x",&x_mesh,NULL);CHKERRQ(ierr);
  ierr = PetscOptionsGetInt(NULL,"-l",&levels,NULL);CHKERRQ(ierr);
  ierr = PetscOptionsGetInt(NULL,"-c",&cycles,NULL);CHKERRQ(ierr);
  ierr = PetscOptionsGetInt(NULL,"-smooths",&smooths,NULL);CHKERRQ(ierr);
  ierr = PetscOptionsHasName(NULL,"-a",&flg);CHKERRQ(ierr);

  if (flg) am = PC_MG_ADDITIVE;
  ierr = PetscOptionsHasName(NULL,"-f",&flg);CHKERRQ(ierr);
  if (flg) am = PC_MG_FULL;
  ierr = PetscOptionsHasName(NULL,"-j",&flg);CHKERRQ(ierr);
  if (flg) use_jacobi = 1;

  ierr = PetscMalloc1(levels,&N);CHKERRQ(ierr);
  N[0] = x_mesh;
  for (i=1; i<levels; i++) {
    N[i] = N[i-1]/2;
    if (N[i] < 1) SETERRQ(PETSC_COMM_WORLD,1,"Too many levels");
  }

  ierr = Create1dLaplacian(N[levels-1],&cmat);CHKERRQ(ierr);

  ierr = KSPCreate(PETSC_COMM_WORLD,&kspmg);CHKERRQ(ierr);
  ierr = KSPGetPC(kspmg,&pcmg);CHKERRQ(ierr);
  ierr = KSPSetFromOptions(kspmg);CHKERRQ(ierr);
  ierr = PCSetType(pcmg,PCMG);CHKERRQ(ierr);
  ierr = PCMGSetLevels(pcmg,levels,NULL);CHKERRQ(ierr);
  ierr = PCMGSetType(pcmg,am);CHKERRQ(ierr);

  ierr = PCMGGetCoarseSolve(pcmg,&cksp);CHKERRQ(ierr);
  ierr = KSPSetOperators(cksp,cmat,cmat);CHKERRQ(ierr);
  ierr = KSPGetPC(cksp,&pc);CHKERRQ(ierr);
  ierr = PCSetType(pc,PCLU);CHKERRQ(ierr);
  ierr = KSPSetType(cksp,KSPPREONLY);CHKERRQ(ierr);

  /* zero is finest level */
  for (i=0; i<levels-1; i++) {
    ierr = PCMGSetResidual(pcmg,levels - 1 - i,residual,(Mat)0);CHKERRQ(ierr);
    ierr = MatCreateShell(PETSC_COMM_WORLD,N[i+1],N[i],N[i+1],N[i],(void*)0,&mat[i]);CHKERRQ(ierr);
    ierr = MatShellSetOperation(mat[i],MATOP_MULT,(void (*)(void))restrct);CHKERRQ(ierr);
    ierr = MatShellSetOperation(mat[i],MATOP_MULT_TRANSPOSE_ADD,(void (*)(void))interpolate);CHKERRQ(ierr);
    ierr = PCMGSetInterpolation(pcmg,levels - 1 - i,mat[i]);CHKERRQ(ierr);
    ierr = PCMGSetRestriction(pcmg,levels - 1 - i,mat[i]);CHKERRQ(ierr);
    ierr = PCMGSetCyclesOnLevel(pcmg,levels - 1 - i,cycles);CHKERRQ(ierr);

    /* set smoother */
    ierr = PCMGGetSmoother(pcmg,levels - 1 - i,&ksp[i]);CHKERRQ(ierr);
    ierr = KSPGetPC(ksp[i],&pc);CHKERRQ(ierr);
    ierr = PCSetType(pc,PCSHELL);CHKERRQ(ierr);
    ierr = PCShellSetName(pc,"user_precond");CHKERRQ(ierr);
    ierr = PCShellGetName(pc,&shellname);CHKERRQ(ierr);
    ierr = PetscPrintf(PETSC_COMM_WORLD,"level=%D, PCShell name is %s\n",i,shellname);CHKERRQ(ierr);

    /* this is a dummy! since KSP requires a matrix passed in  */
    ierr = KSPSetOperators(ksp[i],mat[i],mat[i]);CHKERRQ(ierr);
    /*
        We override the matrix passed in by forcing it to use Richardson with
        a user provided application. This is non-standard and this practice
        should be avoided.
    */
    ierr = PCShellSetApplyRichardson(pc,gauss_seidel);CHKERRQ(ierr);
    if (use_jacobi) {
      ierr = PCShellSetApplyRichardson(pc,jacobi);CHKERRQ(ierr);
    }
    ierr = KSPSetType(ksp[i],KSPRICHARDSON);CHKERRQ(ierr);
    ierr = KSPSetInitialGuessNonzero(ksp[i],PETSC_TRUE);CHKERRQ(ierr);
    ierr = KSPSetTolerances(ksp[i],PETSC_DEFAULT,PETSC_DEFAULT,PETSC_DEFAULT,smooths);CHKERRQ(ierr);

    ierr = VecCreateSeq(PETSC_COMM_SELF,N[i],&x);CHKERRQ(ierr);

    X[levels - 1 - i] = x;
    if (i > 0) {
      ierr = PCMGSetX(pcmg,levels - 1 - i,x);CHKERRQ(ierr);
    }
    ierr = VecCreateSeq(PETSC_COMM_SELF,N[i],&x);CHKERRQ(ierr);

    B[levels -1 - i] = x;
    if (i > 0) {
      ierr = PCMGSetRhs(pcmg,levels - 1 - i,x);CHKERRQ(ierr);
    }
    ierr = VecCreateSeq(PETSC_COMM_SELF,N[i],&x);CHKERRQ(ierr);

    R[levels - 1 - i] = x;

    ierr = PCMGSetR(pcmg,levels - 1 - i,x);CHKERRQ(ierr);
  }
  /* create coarse level vectors */
  ierr = VecCreateSeq(PETSC_COMM_SELF,N[levels-1],&x);CHKERRQ(ierr);
  ierr = PCMGSetX(pcmg,0,x);CHKERRQ(ierr); X[0] = x;
  ierr = VecCreateSeq(PETSC_COMM_SELF,N[levels-1],&x);CHKERRQ(ierr);
  ierr = PCMGSetRhs(pcmg,0,x);CHKERRQ(ierr); B[0] = x;

  /* create matrix multiply for finest level */
  ierr = MatCreateShell(PETSC_COMM_WORLD,N[0],N[0],N[0],N[0],(void*)0,&fmat);CHKERRQ(ierr);
  ierr = MatShellSetOperation(fmat,MATOP_MULT,(void (*)(void))amult);CHKERRQ(ierr);
  ierr = KSPSetOperators(kspmg,fmat,fmat);CHKERRQ(ierr);

  ierr = CalculateSolution(N[0],&solution);CHKERRQ(ierr);
  ierr = CalculateRhs(B[levels-1]);CHKERRQ(ierr);
  ierr = VecSet(X[levels-1],0.0);CHKERRQ(ierr);

  ierr = residual((Mat)0,B[levels-1],X[levels-1],R[levels-1]);CHKERRQ(ierr);
  ierr = CalculateError(solution,X[levels-1],R[levels-1],e);CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_SELF,"l_2 error %g max error %g resi %g\n",(double)e[0],(double)e[1],(double)e[2]);CHKERRQ(ierr);

  ierr = KSPSolve(kspmg,B[levels-1],X[levels-1]);CHKERRQ(ierr);
  ierr = KSPGetIterationNumber(kspmg,&its);CHKERRQ(ierr);
  ierr = residual((Mat)0,B[levels-1],X[levels-1],R[levels-1]);CHKERRQ(ierr);
  ierr = CalculateError(solution,X[levels-1],R[levels-1],e);CHKERRQ(ierr);
  ierr = PetscPrintf(PETSC_COMM_SELF,"its %D l_2 error %g max error %g resi %g\n",its,(double)e[0],(double)e[1],(double)e[2]);CHKERRQ(ierr);

  ierr = PetscFree(N);CHKERRQ(ierr);
  ierr = VecDestroy(&solution);CHKERRQ(ierr);

  /* note we have to keep a list of all vectors allocated, this is
     not ideal, but putting it in MGDestroy is not so good either*/
  for (i=0; i<levels; i++) {
    ierr = VecDestroy(&X[i]);CHKERRQ(ierr);
    ierr = VecDestroy(&B[i]);CHKERRQ(ierr);
    if (i) {ierr = VecDestroy(&R[i]);CHKERRQ(ierr);}
  }
  for (i=0; i<levels-1; i++) {
    ierr = MatDestroy(&mat[i]);CHKERRQ(ierr);
  }
  ierr = MatDestroy(&cmat);CHKERRQ(ierr);
  ierr = MatDestroy(&fmat);CHKERRQ(ierr);
  ierr = KSPDestroy(&kspmg);CHKERRQ(ierr);
  ierr = PetscFinalize();
  return 0;
}
Esempio n. 6
0
void CMsgImOutboxSend::SetLastMessageStatusL(const TTime& aTimeNow, TInt aCompletionReason)
	{
	//	If its the first message && there are messages to be sent change status..
	if (iTotalMessages>0) 
		{ 
		iProgress.SetStatus(EMsgOutboxProgressSending); 
		} 

	// Store the file progress for the last file sent. This will be used in
	// the situation where we cancel the operation to do a bearer migration
	// so that the progress information is for the last file completed as
	// opposed to the one we have just cancelled.
	if (iSession)
		{
		iProgress.iSendFileProgress = iSession->FileProgress();
		}

	//	Fill in the iServerEntry details with data from the last message
    //  IMCV may had left this inconsistent... so reset the iServerEntry
    //  explicitly....
	if (iCurrentMessageNo != -1)
		{     
		TInt err;
        err = iServerEntry.SetEntry(iEntrySelection.At(iCurrentMessageNo));
		__ASSERT_DEBUG( err == KErrNone, gPanic(EImsmServerError));
		TMsvEntry entry = iServerEntry.Entry();

		//	Set date info and completion data..update the iServerEntry with this data..
		entry.iDate=aTimeNow;
		if(aCompletionReason!=KErrCancel)
			{
			entry.SetFailed(aCompletionReason != KErrNone);
			entry.SetSendingState(aCompletionReason==KErrNone? KMsvSendStateSent: KMsvSendStateWaiting);  //set it to send agian.
			if (aCompletionReason)
				entry.iError=CalculateError(aCompletionReason);
			}
		else
			{
			entry.SetFailed(EFalse);
			entry.SetSendingState(KMsvSendStateSuspended);
			entry.iError=KErrNone;
			}

//		if (aCompletionReason<=KErrNone)
	//		{
			// ignore any +ve errors which may leak from the SMTP code
//			entry.iError=aCompletionReason;
//			entry.SetSendingState(aCompletionReason==KErrNone? KMsvSendStateSent: KMsvSendStateWaiting);  //set it to send agian.
//			}
		RestoreBccRecipientsToHeaderL();

        entry.SetConnected(EFalse);
		err = iServerEntry.ChangeEntry(entry);
		__ASSERT_DEBUG( err == KErrNone, gPanic(EImsmServerError));
		UpdateSummaryInfo(aCompletionReason);

        //  If it went move to the "Sent" folder..
        if(!entry.Failed() && aCompletionReason!=KErrCancel)
            {
            TMsvId id = entry.Id();
            err = iServerEntry.SetEntry(KMsvSentEntryIdValue);
            if(err == KErrNone)
                {
                err = iServerEntry.SetEntry(KMsvGlobalOutBoxIndexEntryId);
                if(err == KErrNone)
                    {
                    // Move it....
                    err = iServerEntry.MoveEntryWithinService(id, KMsvSentEntryIdValue);
                    }
                }
            }
		}
	}
Esempio n. 7
0
void FceApplication::SimulationRun(void) {
	try {
		if (running == true) {
			bool edgeChanged = vehicle.requestCurrentEdge(Simulator::Now().GetSeconds());
			string currentEdge = vehicle.getItinerary().getCurrentEdge().getId();
			double now = Simulator::Now().GetSeconds();

			// if a vehicle is entering a new edge it has already traced the time on its itinerary
			// broadcast information about it and about travel time on the last edge
			if (edgeChanged) {
				Edge lastEdge = vehicle.getItinerary().getLastEdge();
				double travelTimeOnLastEdge = lastEdge.getTravelTime();
				string lastEdgeId = lastEdge.getId();
				Vector position = mobilityModel->GetPosition();
				TIS::getInstance().reportEdgePosition(lastEdge.getId(), position.x, position.y);
//				Log::getInstance().getStream("") << now << "\t" <<lastEdgeId << "\t" << position.x << "," << position.y << "\n" ;
				Ptr<Packet> p = OvnisPacket::BuildChangedEdgePacket(now, vehicle.getId(), position.x, position.y, CHANGED_EDGE_PACKET_ID, lastEdgeId, travelTimeOnLastEdge, currentEdge);
				SendPacket(p);
			}

			// if approaching an intersection
			// take decision which route to takefrom current to destination edge based on the collected knowledge about travel times on edges
			bool isDecisionPoint = find(vehicle.getScenario().getDecisionEdges().begin(), vehicle.getScenario().getDecisionEdges().end(), currentEdge) != vehicle.getScenario().getDecisionEdges().end();
			if (isDecisionPoint && !decisionTaken) {

				// centralised TIS
				map<string, double> globalCosts = TIS::getInstance().getCosts(vehicle.getScenario().getAlternativeRoutes(), currentEdge, vehicle.getDestinationEdgeId());
				string global_minTravelTimeChoice = TIS::getInstance().chooseMinCostRoute(globalCosts);
				string global_proportionalProbabilisticChoice = TIS::getInstance().chooseProbTravelTimeRoute(globalCosts);
				string global_flowAwareChoice =  TIS::getInstance().chooseFlowAwareRoute(flow, globalCosts);

				// VANETs
				Vector position = mobilityModel->GetPosition();
				Log::getInstance().getStream("vanets_knowledge") << now << "\t" << position.x << "\t" << position.y << "\t" << currentEdge << "\t" << vehicle.getDestinationEdgeId() << "\t";
				map<string, double> vanetCosts =  vanetsKnowledge.getCosts(vehicle.getScenario().getAlternativeRoutes(), currentEdge, vehicle.getDestinationEdgeId());
				string vanet_minTravelTimeChoice =  TIS::getInstance().chooseMinCostRoute(vanetCosts);
				string vanet_proportionalProbabilisticChoice =  TIS::getInstance().chooseProbTravelTimeRoute(vanetCosts);
				string vanet_flowAwareChoice =  TIS::getInstance().chooseFlowAwareRoute(flow, vanetCosts);

				CalculateError(currentEdge);

				// centralized
				string centralizedSelfishRouteChoice = global_minTravelTimeChoice;
				string centralizedSystemRouteChoice = global_proportionalProbabilisticChoice;
				double centralizedSelfishTravelTime = globalCosts[centralizedSelfishRouteChoice];
				double centralizedSystemTravelTIme = globalCosts[centralizedSystemRouteChoice];

//				// vanets
				string selfishRouteChoice = vanet_minTravelTimeChoice;
				string systemRouteChoice = vanet_proportionalProbabilisticChoice;
				double selfishTravelTime = vanetCosts[selfishRouteChoice];
				double systemTravelTIme = vanetCosts[systemRouteChoice];

				// default is centralised
				string routeChoice = centralizedSelfishRouteChoice;
				selfishExpectedTravelTime = centralizedSelfishTravelTime;
				expectedTravelTime = centralizedSelfishTravelTime;

				if (isVanet) {
					routeChoice = selfishRouteChoice;
					selfishExpectedTravelTime = selfishTravelTime;
					expectedTravelTime = selfishTravelTime;

					double capacityDrop = vanetsKnowledge.isCapacityDrop(vehicle.getScenario().getAlternativeRoutes(), currentEdge, vehicle.getDestinationEdgeId());
					TIS::getInstance().setCongestion(capacityDrop);

					if (strategy == PROBABILISTIC_ROUTING) {
						routeChoice = systemRouteChoice;
						expectedTravelTime = systemTravelTIme;
					}

					// faster selfish
					else if (strategy == FASTER_SELFISH_ROUTING && capacityDrop) {
						string fasterSelfishRouteChoice = TIS::getInstance().chooseMinCostRoute(vanetsKnowledge.getCongestedLengthOnRoutes());
						routeChoice = fasterSelfishRouteChoice;
						expectedTravelTime = vanetCosts[fasterSelfishRouteChoice];
					}

					// hybrid
					else if (strategy == HYBRID_ROUTING && capacityDrop) {
						routeChoice = systemRouteChoice;
						expectedTravelTime = systemTravelTIme;
					}
				}

				// Cheaters
				double r = (double)(rand()%RAND_MAX)/(double)RAND_MAX;
				if (cheatersRatio > 0 && r < cheatersRatio) {
					if (routeChoice != selfishRouteChoice) {
						routeChoice = selfishRouteChoice;
						isCheater = true;
					}
				}
				if (cheatersRatio < 0 && -r > cheatersRatio) {
					if (routeChoice != systemRouteChoice) {
						routeChoice = systemRouteChoice;
						isCheater = true;
					}
				}
//				string routeChoice = vehicle.getItinerary().getId();

				vehicle.reroute(routeChoice);
				decisionEdgeId = currentEdge;
				TIS::getInstance().reportStartingRoute(routeChoice, currentEdge, vehicle.getDestinationEdgeId());
				decisionTaken = true;
			}

			// if approaching the point that we want to evaluate
			// report to TIS the total travel time on the route between the decision edge and the current edge
			bool isReportingPoint = find(vehicle.getScenario().getNotificationEdges().begin(), vehicle.getScenario().getNotificationEdges().end(), currentEdge) != vehicle.getScenario().getNotificationEdges().end();
			if (isReportingPoint && !notificationSent) {
				string routeId = vehicle.getItinerary().getId();
				double travelTime = vehicle.getItinerary().computeTravelTime(decisionEdgeId, currentEdge);
				cout << Simulator::Now().GetSeconds() << "\t" << routeId << "\t" << travelTime << "\t" << vehicle.getItinerary().computeStaticCost(decisionEdgeId, currentEdge) << "\t" << vehicle.getItinerary().computeStaticCost() << "\t" << vehicle.getItinerary().computeLength(decisionEdgeId, currentEdge) << "\t" << vehicle.getItinerary().computeLength() << endl;
				TIS::getInstance().reportEndingRoute(routeId, decisionEdgeId, currentEdge, travelTime, isCheater, selfishExpectedTravelTime, expectedTravelTime);
				notificationSent = true;
			}

			m_simulationEvent = Simulator::Schedule(Seconds(SIMULATION_STEP_INTERVAL), &FceApplication::SimulationRun, this);
		}
	}
	catch (TraciException & ex) {
		running = false;
	}
}
Esempio n. 8
0
void Terrain::GenerateHeightMap(int Iterations, double Height, double HDecay)
{
	HeightMap.calculate(Iterations, Height, HDecay);	
	int Select = 1 + rand() % (4 - 1 + 1);		
	// Load .3DS file into model structure	
	if(Select == 1)
	{
		GenerateTerrainObjects(50, 2 , 40, 10);
		g_Load3ds.Import3DS(&g_3DModel, "Textures/Tilesets/Desert/Models/PILLAR.3DS");
		double Ratio = 0.25;
		O1Offset = 0.0f;
		BuildLists(Ratio, 1, g_3DModel);		
		for(int i = 0; i < g_3DModel.numOfObjects; i++)
		{
			// Free the faces, normals, vertices, and texture coordinates.
			delete [] g_3DModel.pObject[i].pFaces;
			delete [] g_3DModel.pObject[i].pNormals;
			delete [] g_3DModel.pObject[i].pVerts;
			delete [] g_3DModel.pObject[i].pTexVerts;
		}	
		
		g_Load3ds.Import3DS(&g_3DModel1, "Textures/Tilesets/Desert/Models/STATUE.3DS");
		Ratio = 0.25;
		O1Offset = 0.0f;
		BuildLists(Ratio, 2, g_3DModel1);

		// Go through all the objects in the scene
		for(int i = 0; i < g_3DModel1.numOfObjects; i++)
		{
			// Free the faces, normals, vertices, and texture coordinates.
			delete [] g_3DModel1.pObject[i].pFaces;
			delete [] g_3DModel1.pObject[i].pNormals;
			delete [] g_3DModel1.pObject[i].pVerts;
			delete [] g_3DModel1.pObject[i].pTexVerts;
		}			
	}
	else if(Select == 2)
	{		
		GenerateTerrainObjects(100, 2 , 50, 50);
		g_Load3ds.Import3DS(&g_3DModel, "Textures/Tilesets/Mountains/Models/PINE.3DS");
		double Ratio = 0.25;
		O1Offset = 15.5f;
		BuildLists(Ratio, 1, g_3DModel);		
		for(int i = 0; i < g_3DModel.numOfObjects; i++)
		{
			// Free the faces, normals, vertices, and texture coordinates.
			delete [] g_3DModel.pObject[i].pFaces;
			delete [] g_3DModel.pObject[i].pNormals;
			delete [] g_3DModel.pObject[i].pVerts;
			delete [] g_3DModel.pObject[i].pTexVerts;
		}	
		
		g_Load3ds.Import3DS(&g_3DModel1, "Textures/Tilesets/Mountains/Models/MAPLE.3DS");
		Ratio = 5.0;
		O2Offset = 0.0f;
		BuildLists(Ratio, 2, g_3DModel1);

		// Go through all the objects in the scene
		for(int i = 0; i < g_3DModel1.numOfObjects; i++)
		{
			// Free the faces, normals, vertices, and texture coordinates.
			delete [] g_3DModel1.pObject[i].pFaces;
			delete [] g_3DModel1.pObject[i].pNormals;
			delete [] g_3DModel1.pObject[i].pVerts;
			delete [] g_3DModel1.pObject[i].pTexVerts;
		}		
	}
	else if(Select == 3)
	{
		GenerateTerrainObjects(100, 2 , 50, 50);
		g_Load3ds.Import3DS(&g_3DModel, "Textures/Tilesets/Tropics/Models/TREE3.3DS");
		double Ratio = 0.5;
		O1Offset = 0.0f;
		BuildLists(Ratio, 1, g_3DModel);		
		for(int i = 0; i < g_3DModel.numOfObjects; i++)
		{
			// Free the faces, normals, vertices, and texture coordinates.
			delete [] g_3DModel.pObject[i].pFaces;
			delete [] g_3DModel.pObject[i].pNormals;
			delete [] g_3DModel.pObject[i].pVerts;
			delete [] g_3DModel.pObject[i].pTexVerts;
		}	
		
		g_Load3ds.Import3DS(&g_3DModel1, "Textures/Tilesets/Tropics/Models/PALM.3DS");
		Ratio = 0.75;
		O2Offset = 10.0f;
		BuildLists(Ratio, 2, g_3DModel1);

		// Go through all the objects in the scene
		for(int i = 0; i < g_3DModel1.numOfObjects; i++)
		{
			// Free the faces, normals, vertices, and texture coordinates.
			delete [] g_3DModel1.pObject[i].pFaces;
			delete [] g_3DModel1.pObject[i].pNormals;
			delete [] g_3DModel1.pObject[i].pVerts;
			delete [] g_3DModel1.pObject[i].pTexVerts;
		}		
	
	}
	else if(Select == 4)
	{		
		GenerateTerrainObjects(100, 2 , 75, 15);
		g_Load3ds.Import3DS(&g_3DModel, "Textures/Tilesets/Volcanic/Models/DEADTREE.3DS");
		double Ratio = 0.1;
		O1Offset = -1.0f;
		BuildLists(Ratio, 1, g_3DModel);		
		for(int i = 0; i < g_3DModel.numOfObjects; i++)
		{
			// Free the faces, normals, vertices, and texture coordinates.
			delete [] g_3DModel.pObject[i].pFaces;
			delete [] g_3DModel.pObject[i].pNormals;
			delete [] g_3DModel.pObject[i].pVerts;
			delete [] g_3DModel.pObject[i].pTexVerts;
		}	
		
		g_Load3ds.Import3DS(&g_3DModel1, "Textures/Tilesets/Volcanic/Models/TREE1.3DS");
		Ratio = 0.15;
		O2Offset = 2.0f;
		BuildLists(Ratio, 2, g_3DModel1);

		// Go through all the objects in the scene
		for(int i = 0; i < g_3DModel1.numOfObjects; i++)
		{
			// Free the faces, normals, vertices, and texture coordinates.
			delete [] g_3DModel1.pObject[i].pFaces;
			delete [] g_3DModel1.pObject[i].pNormals;
			delete [] g_3DModel1.pObject[i].pVerts;
			delete [] g_3DModel1.pObject[i].pTexVerts;
		}	
	
	}
	SurfaceCreator s1 = SurfaceCreator(HeightMap.Height_Map, HeightMap.getTerrainSize() - 1, static_cast<float>(Height), Select);
	multitextureSupported = initMultitexture();

	TriangleTree.ExpandNode(TriangleTree.root);
	Node* Current = TriangleTree.root;
	
	//Create Triangle t1	
	Vector Apex = Vector(0, 0, HeightMap.Height_Map[0][0]);
	Vector Left = Vector(0, static_cast<float>(HeightMap.getTerrainSize() - 1), HeightMap.Height_Map[0][HeightMap.getTerrainSize() - 1]);
	Vector Right = Vector(static_cast<float>(HeightMap.getTerrainSize() - 1), 0,HeightMap.Height_Map[HeightMap.getTerrainSize() - 1][0] );
	Triangle t = Triangle(Apex, Left, Right);
	for(int i = 0; i < 100; i++)
	{	
		if(PointInTriangle(Vector(Forests[i].x, Forests[i].y), Apex, Left, Right))	
		{
			t.Tree.push_back(Forests[i]);
		}
	}
	double E = CalculateError(Left, Right);		
	Current->LeftChild->BaseNeighbour = Current->RightChild;
	TriangleTree.InsertAtNode(Current->LeftChild, t, E);	

	// Create Triangle t2	
	Apex.set(static_cast<float>(HeightMap.getTerrainSize() - 1) , static_cast<float>(HeightMap.getTerrainSize() - 1), HeightMap.Height_Map[HeightMap.getTerrainSize() - 1][HeightMap.getTerrainSize() - 1]);
	Left.set(static_cast<float>(HeightMap.getTerrainSize() - 1), 0, HeightMap.Height_Map[HeightMap.getTerrainSize() - 1][0]);
	Right.set(0, static_cast<float>(HeightMap.getTerrainSize() - 1), HeightMap.Height_Map[0][HeightMap.getTerrainSize() - 1]);
	Triangle t2 = Triangle(Apex, Left, Right);	
	for(int i = 0; i < 100; i++)
	{	
		if(PointInTriangle(Vector(Forests[i].x, Forests[i].y), Apex, Left, Right))
		{
			t2.Tree.push_back(Forests[i]);
		}
	}	
	Current->RightChild->BaseNeighbour = Current->LeftChild;
	TriangleTree.InsertAtNode(Current->RightChild, t2, E);	

	LoadTGA(&SkyBoxTexture, "SkyBox/CLOUDS.tga");
	LoadGLTextures(&WaterTexture, "Textures/WATER1.bmp");
	LoadGLTextures(&SurfaceTexture , "Data/Surface.bmp");
	LoadGLTextures(&ShadowTexture  , "Data/Shadows.bmp");	
}
Esempio n. 9
0
void Terrain::SplitTriangle(Node* T)
{
	Triangle t = TriangleTree.getCurrentNode(T);
	TriangleTree.ExpandNode(T);
	
	// Step 1 : Get the old triangles points		
	Vector Apex = t.Apex;
	Vector Left = t.Left;
	Vector Right = t.Right;

	// Step 2 : Get new Apex point which is the midpoint between Left and Right		
	int lx = static_cast<int>(Left.x);
	int ly = static_cast<int>(Left.y);
	int rx = static_cast<int>(Right.x);
	int ry = static_cast<int>(Right.y);
	Vector newApex = Vector(static_cast<float>((lx + rx) / 2), static_cast<float>((ly + ry) / 2));    

	// Step 3 : Create first triangle and add to tree ( This is left half of old triangle )	
	double TriangleLeft = CalculateError(Apex , Left);				
	Triangle NewTLeft = Triangle(newApex, Apex, Left); // Apex = new Apex, Left = old Left, Right = Old Apex			
	for(int i = 0; (unsigned)i < t.Tree.size(); i++)
	{	
		Vector Current = t.Tree[i];
		if(PointInTriangle(Vector(Current.x, Current.y), Vector(newApex.x, newApex.y), Vector(Apex.x, Apex.y), Vector(Left.x, Left.y)))		
		{
			NewTLeft.Tree.push_back(Current);			
		}
	}

	// Step 4 : Create the second triangle and add to tree	
	double TriangleRight = CalculateError(Right , Apex);				
	Triangle NewTRight = Triangle(newApex, Right, Apex);	
	for(int i = 0; (unsigned)i < t.Tree.size(); i++)
	{	
		Vector Current = t.Tree[i];
		if(PointInTriangle(Vector(Current.x, Current.y), Vector(newApex.x, newApex.y), Vector(Right.x, Right.y), Vector(Apex.x, Apex.y) ))	
		{
			NewTRight.Tree.push_back(Current);			
		}
	}


	T->LeftChild->LeftNeighbour = T->RightChild;
	T->RightChild->RightNeighbour = T->LeftChild;	
	T->LeftChild->BaseNeighbour = T->LeftNeighbour;	
	T->RightChild->BaseNeighbour = T->RightNeighbour;
	
	if(T->LeftNeighbour != NULL)
	{		    
	   	if(T->LeftNeighbour->BaseNeighbour == T)
		{	
          	T->LeftNeighbour->BaseNeighbour = T->LeftChild;
			T->LeftNeighbour->Parent->RightNeighbour = T->LeftChild;		
		}
		else
		{		 
			T->LeftNeighbour->RightNeighbour = T->LeftChild;
		}
	}
	if(T->RightNeighbour != NULL)
	{
		if(T->RightNeighbour->BaseNeighbour == T)
		{		    
			T->RightNeighbour->BaseNeighbour = T->RightChild;
			T->RightNeighbour->Parent->LeftNeighbour = T->RightChild;
		}
		else
		{ 			    
			T->RightNeighbour->LeftNeighbour = T->RightChild;
		}
	}	
	TriangleTree.InsertAtNode(T->LeftChild, NewTLeft, TriangleLeft);
	TriangleTree.InsertAtNode(T->RightChild, NewTRight, TriangleRight);	
}
Esempio n. 10
0
void  RFace::CreateFace(void * lpData)
{
    FaceData Data;
    memset(&Data, 0, sizeof(FaceData));

    double Error = MAX_ERROR;
    double CurError = MAX_ERROR;

    FaceData * lpFaceData = (FaceData*)lpData;

    int im = 0;//mouth was find
    int jl = 0;//left eye was find
    int kr = 0;//right eye was find

    long MouthNumber = 0;
    long LeftEyeNumber = 0;
    long RightEyeNumber = 0;

    for (int i = 0;i < m_lplFaceFeaturesCount[0] + 1;i ++)
    {

        if ( !m_lplFaceFeaturesCount[0] )
            Data.MouthRect = *(CvRect*)m_lpIdealFace[0].GetContour();
        else
        {
            if ( i != m_lplFaceFeaturesCount[0] )
                Data.MouthRect = *(CvRect*)m_lppFoundedFaceFeatures[0][i].GetContour();
            im = 1;
        }


        for (int j = 0;j < m_lplFaceFeaturesCount[1] + 1;j ++)
        {

            if ( !m_lplFaceFeaturesCount[1] )
                Data.LeftEyeRect = *(CvRect*)m_lpIdealFace[1].GetContour();
            else
            {
                if (j != m_lplFaceFeaturesCount[1] )
                    Data.LeftEyeRect = *(CvRect*)m_lppFoundedFaceFeatures[1][j].GetContour();
                jl = 1;
            }


            for (int k = 0;k < m_lplFaceFeaturesCount[2] + 1;k ++)
            {

                if ( !m_lplFaceFeaturesCount[2] )
                    Data.RightEyeRect = *(CvRect*)m_lpIdealFace[2].GetContour();
                else
                {
                    if (k != m_lplFaceFeaturesCount[2] )
                        Data.RightEyeRect = *(CvRect*)m_lppFoundedFaceFeatures[2][k].GetContour();
                    kr = 1;
                }

                CalculateError(&Data);

                if ( (im + jl + kr) )
                {
                    Error = Data.Error/(im + jl + kr);
                }else
                    Error = MAX_ERROR;

                if (CurError > Error)
                {
                    CurError = Error;
                    MouthNumber = i;
                    LeftEyeNumber = j;
                    RightEyeNumber = k;
                }

            }


        }

    }

    if ( m_lplFaceFeaturesCount[0] )
        lpFaceData->MouthRect = *(CvRect*)m_lppFoundedFaceFeatures[0][MouthNumber].GetContour();
    else
        lpFaceData->MouthRect = *(CvRect*)m_lpIdealFace[0].GetContour();

    if ( m_lplFaceFeaturesCount[1] )
        lpFaceData->LeftEyeRect = *(CvRect*)m_lppFoundedFaceFeatures[1][LeftEyeNumber].GetContour();
    else
        lpFaceData->LeftEyeRect = *(CvRect*)m_lpIdealFace[1].GetContour();

    if ( m_lplFaceFeaturesCount[2] )
        lpFaceData->RightEyeRect = *(CvRect*)m_lppFoundedFaceFeatures[2][RightEyeNumber].GetContour();
    else
        lpFaceData->RightEyeRect = *(CvRect*)m_lpIdealFace[2].GetContour();

    lpFaceData->Error = CurError;

}//void * RFace::CreateFace()