/**
* Just the current frame in the display.
*/
void Engine::DrawFrame()
{
    float fFPS;
    if( monitor_.Update( fFPS ) )
    {
        UpdateFPS( fFPS );
    }
    //renderer_.Update( monitor_.GetCurrentTime() );

    static Timer Timer;
    static double PrevTime = Timer.GetElapsedTime();
    auto CurrTime = Timer.GetElapsedTime();
    auto ElapsedTime = CurrTime - PrevTime;
    PrevTime = CurrTime;
    sample_->Update(CurrTime, ElapsedTime);

    //renderer_.Render();
    sample_->Render();

    // Draw tweak bars
    TwDraw();

    // Swap
    pSwapChain_->Present();
    //if( EGL_SUCCESS != pRenderDevice_->Present() )
    //{
    //    UnloadResources();
    //    LoadResources();
    //}
}
Ejemplo n.º 2
0
void idleCB(void)
{
	animTcl::checkEvents() ;
	if( g_state == STATE_ANIMATE )
	{
		if( g_frameDumping == 0 )
			GlobalResourceManager::use()->setActualTime( g_globalTimer.GetElapsedTime() );
		else 
		{

			GlobalResourceManager::use()->advanceActualTime( 0.33 );

		}
		glutPostRedisplay() ; 
	}
	else if( g_state == STATE_SIMULATE )
	{

		GlobalResourceManager::use()->setActualTime( g_globalTimer.GetElapsedTime() );

		SimulationStep() ;
		glutPostRedisplay() ; 
	}
	myIdleCB() ;
}
Ejemplo n.º 3
0
void Test(TopSpin &tse, const char *prefix)
{
	TopSpinState s(16, 4);
	TopSpinState g(16, 4);
	g.Reset();
	tse.StoreGoal(g);
	tse.SetPruneSuccessors(true);
	
	IDAStar<TopSpinState, TopSpinAction> ida;
	ida.SetUseBDPathMax(true);
	std::vector<TopSpinAction> path1;
	TopSpinState start;
	Timer t1;
	t1.StartTimer();
	uint64_t nodes = 0;
	double totaltime = 0;
	for (int x = 0; x < 100; x++)
	{
		s = GetInstance(x, tse.GetWeighted());
		g.Reset();
		printf("Problem %d of %d\n", x+1, 100);
		std::cout << "Searching from: " << std::endl << s << std::endl << g << std::endl;
		Timer t;
		t.StartTimer();
		ida.GetPath(&tse, s, g, path1);
		t.EndTimer();
		totaltime += t.GetElapsedTime();
		std::cout << "Path found, length " << path1.size() << " time:" << t.GetElapsedTime() << std::endl;
		nodes += ida.GetNodesExpanded();
	}
	printf("%s: %1.2fs elapsed; %llu nodes expanded\n", prefix, t1.EndTimer(), nodes);
}
Ejemplo n.º 4
0
void runProblemSet2(char *problems, int multiplier)
{
	Map *map = new Map(gDefaultMap);
	map->Scale(512, 512);
	msa = new MapSectorAbstraction(map, 8, multiplier);
	
	Graph *g = msa->GetAbstractGraph(1);
	GraphAbstractionHeuristic gah1(msa, 1);
	GraphDistanceHeuristic localGDH(g);
	localGDH.SetPlacement(kAvoidPlacement);
	for (unsigned int x = 0; x < 10; x++)
		localGDH.AddHeuristic();

	GraphHeuristicContainer ghc(g);
	
	GraphRefinementEnvironment env1(msa, 1, &localGDH);
	GraphRefinementEnvironment env2(msa, 1, 0);
//	ghc.AddHeuristic(&localGDH);
//	ghc.AddHeuristic(&gah1);
	env1.SetDirected(false);
	
	FILE *f = fopen(problems, "r");
	if (f == 0)
	{
		printf("Cannot open file: '%s'\n", problems);
		exit(0);
	}
	Timer t;
	printf("len\tnodes\ttoucht\tlen\ttime\tdiff_n\tdiff_t\tdiff_l\ttime\n");
	while (!feof(f))
	{
		int from, to, cost;
		if (fscanf(f, "%d\t%d\t%d\n", &from, &to, &cost) != 3)
			break;
		node *s1 = g->GetNode(from);
		node *g1 = g->GetNode(to);
		graphState gs, gg;
		gs = s1->GetNum();
		gg = g1->GetNum();
		std::vector<graphState> thePath;
		t.StartTimer();
		astar.GetPath(&env2, gs, gg, thePath);
		t.EndTimer();
		printf("%d\t", cost);
		printf("%llu\t%llu\t%1.2f\t%e\t",
			   astar.GetNodesExpanded(), astar.GetNodesTouched(),
			   env1.GetPathLength(thePath), t.GetElapsedTime());
		t.StartTimer();
		astar.GetPath(&env1, gs, gg, thePath);
		t.EndTimer();
		printf("%llu\t%llu\t%1.2f\t%e",
			   astar.GetNodesExpanded(), astar.GetNodesTouched(),
			   env1.GetPathLength(thePath), t.GetElapsedTime());
		printf("\n");
	}
	fclose(f);
	exit(0);
}
Ejemplo n.º 5
0
// Updates the application state once per frame.
void SampleAppMain::Update()
{
	// Update scene objects.
	m_timer.Tick([&]()
	{
        static Timer timer;
        static double PrevTime = timer.GetElapsedTime();
        auto CurrTime = timer.GetElapsedTime();
        auto ElapsedTime = CurrTime - PrevTime;
        PrevTime = CurrTime;
        m_pSample->Update(CurrTime, ElapsedTime);
	});
}
Ejemplo n.º 6
0
void STPTest(unsigned long , tKeyboardModifier , char)
{
	MNPuzzleState tmp(4, 4);
	mnp->StoreGoal(tmp);

	IDAStar<MNPuzzleState, slideDir> ida;
	std::vector<slideDir> path1;
	MNPuzzleState s(4, 4);
	MNPuzzleState g(4, 4);
	//ida.SetUseBDPathMax(true);
	Timer t;
	t.StartTimer();
	uint64_t nodes = 0;
	for (int x = 0; x < 100; x++)
	{
		s = GetKorfInstance(x);
		g.Reset();

		std::cout << "Searching from: " << std::endl << s << std::endl << g << std::endl;
		Timer t;
		t.StartTimer();
		ida.GetPath(mnp, s, g, path1);
		t.EndTimer();
		std::cout << "Path found, length " << path1.size() << " time:" << t.GetElapsedTime() << std::endl;
		nodes += ida.GetNodesExpanded();
	}
	printf("%1.2fs elapsed; %llu nodes expanded\n", t.EndTimer(), nodes);
//	for (int x = 0; x < mnp->histogram.size(); x++)
//	{
//		printf("%2d  %d\n", x, mnp->histogram[x]);
//	}
//
//	mnp->PrintHStats();
	
}
Ejemplo n.º 7
0
// ----------------------------------------------------------------------------
// Timer.h
bool Test_Timer()
{
    TTRACE(_T("====================================================="));
    {
        Timer t;
        t.Start();
        Sleep(500);
        TTRACE(_T("time=%f, elapsed=%f"), t.GetTime(), t.GetElapsedTime());
        t.Stop();
        Sleep(500);
        TTRACE(_T("time=%f, elapsed=%f"), t.GetTime(), t.GetElapsedTime());
        t.Start();
        Sleep(500);
        TTRACE(_T("time=%f, elapsed=%f"), t.GetTime(), t.GetElapsedTime());
    }

    return true;
}
Ejemplo n.º 8
0
void MyDisplayHandler(unsigned long windowID, tKeyboardModifier mod, char key)
{
	switch (key)
	{
		case 'r': recording = !recording; break;
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			ts->ApplyAction(s, key-'0');
			break;
		case '\t':
			if (mod != kShiftDown)
				SetActivePort(windowID, (GetActivePort(windowID)+1)%GetNumPorts(windowID));
			else
			{
				SetNumPorts(windowID, 1+(GetNumPorts(windowID)%MAXPORTS));
			}
			break;
		case 'p':
			break;
		case 'o':
		{
			if (!ts) break;
			if (mod == kShiftDown)
			{
				IDAStar<TopSpinState, TopSpinAction> ida;
				std::vector<TopSpinAction> path1;
				std::vector<TopSpinState> path2;
				TopSpinState s(4, 4);
				TopSpinState g(4, 4);
				for (unsigned int x = 0; x < 500; x++)
				{
					std::vector<TopSpinAction> acts;
					ts->GetActions(s, acts);
					ts->ApplyAction(s, acts[random()%acts.size()]);
				}
				std::cout << "Searching from: " << std::endl << s << std::endl << g << std::endl;
				Timer t;
				t.StartTimer();
				ida.GetPath(ts, s, g, path1);
				t.EndTimer();
				std::cout << "Path found, length " << path1.size() << " time:" << t.GetElapsedTime() << std::endl;
			}
		}
			break;
		default:
			break;
	}
}
Ejemplo n.º 9
0
// resets time to 0.
void resetTime(void)
{
	g_globalTimer.GetElapsedTime() ;
	// reset the timer to point the current time	
	g_globalTimer.Reset() ;

	GlobalResourceManager::use()->setActualTime( 0.0 );
	GlobalResourceManager::use()->setSimulationTime( 0.0 );

}
Ejemplo n.º 10
0
	void DoBFS()
	{
		// By default, starts at goal state
		SlidingPuzzleState s;
		LList<int> moves;
		
		uint8_t *stateDepths = new uint8_t[s.GetMaxRank()];
		
		// set all values to 255
		memset(stateDepths, 255, s.GetMaxRank());
		uint32_t seenStates = 1;
		stateDepths[s.Rank()] = 0;
		int currDepth = 0;
		
		Timer fullTimer;
		
		std::cout.setf( std::ios::fixed, std:: ios::floatfield ); // floatfield set to fixed
		std::cout.precision(2);
		
		while (seenStates != s.GetMaxRank())
		{
			Timer roundTimer;
			for (int x = 0; x < s.GetMaxRank(); x++)
			{
				if (stateDepths[x] == currDepth)
				{
					s.Unrank(x);
					s.GetMoves(moves);
					while (moves.IsEmpty() == false)
					{
						s.ApplyMove(moves.PeekFront());
						uint32_t rank = s.Rank();
						s.UndoMove(moves.PeekFront());
						moves.RemoveFront();
						
						if (stateDepths[rank] == 255)
						{
							stateDepths[rank] = currDepth+1;
							seenStates++;
						}
					}
				}
			}
			std::cout << roundTimer.GetElapsedTime() << "s elapsed. ";
			std::cout << "Depth " << currDepth;
			std::cout << " complete. " << seenStates << " of " << s.GetMaxRank();
			std::cout << " total states seen.\n";
			currDepth++;
		}
		std::cout << fullTimer.EndTimer() << "s elapsed\n";
		delete [] stateDepths;
	}
Ejemplo n.º 11
0
static void display_func ( void )
{	
	fps_time += timer.GetElapsedTime();
    rot_time += timer.GetElapsedTime();
	timer.Reset();
	frames++;

	if(fps_time >= 10.0 && rate)
	{
		cout<<"Framerate:"<<(frames/fps_time)<<endl;
		frames = 0;
		fps_time = 0;
	}
	pre_display ();

		if      ( dvel==0 ) draw_velocity ();
		else if	( dvel==1 )	draw_density ();
        else if ( dvel==2 ) draw_points ();
        else if ( dvel==3 ) draw_particles ();

	post_display ();
}
Ejemplo n.º 12
0
void runProblemSet3(char *scenario)
{
	printf("Loading scenario %s\n", scenario);
	ScenarioLoader sl(scenario);
	
	printf("Loading map %s\n", sl.GetNthExperiment(0).GetMapName());
	Map *map = new Map(sl.GetNthExperiment(0).GetMapName());
	map->Scale(sl.GetNthExperiment(0).GetXScale(), 
			   sl.GetNthExperiment(0).GetYScale());
	
	PEAStar<xyLoc, tDirection, MapEnvironment> pea;
	TemplateAStar<xyLoc, tDirection, MapEnvironment> astar;
	std::vector<xyLoc> thePath;
	MapEnvironment ma(map);
	ma.SetFourConnected();
	
	for (int x = 0; x < sl.GetNumExperiments(); x++)
	{
		if (sl.GetNthExperiment(x).GetBucket() != 127)
			continue;
		xyLoc from, to;
		printf("%d\t", sl.GetNthExperiment(x).GetBucket());
		from.x = sl.GetNthExperiment(x).GetStartX();
		from.y = sl.GetNthExperiment(x).GetStartY();
		to.x = sl.GetNthExperiment(x).GetGoalX();
		to.y = sl.GetNthExperiment(x).GetGoalY();
		Timer t;
		t.StartTimer();
		pea.GetPath(&ma, from, to, thePath);
		t.EndTimer();
		printf("pea\t%ld\t%1.6f\t%llu\t%u", thePath.size(), t.GetElapsedTime(), pea.GetNodesExpanded(), pea.GetNumOpenItems());
		t.StartTimer();
		astar.GetPath(&ma, from, to, thePath);
		t.EndTimer();
		printf("\tastar\t%ld\t%1.6f\t%llu\t%u\n", thePath.size(), t.GetElapsedTime(), astar.GetNodesExpanded(), astar.GetNumOpenItems());
	}

	exit(0);
}
Ejemplo n.º 13
0
/*******************************************************************************
Function that gets called for any keypresses.
*******************************************************************************/
void myKey(unsigned char key, int x, int y)
{
	float time;
	const double speed = 1.0;
	switch (key) 
	{
		case 'q':
		case 27:
			exit(0); 
		case 's':
			g_frameSaver.DumpPPM(g_width,g_height);
			break;
		case 'x':
			addRandomFoodParticle( 100, &World, &Space );
			animator.scanForFood( animator.foodParticles.back() );
			break;
		case 'r':
			resetArcball();
			break;
		case '1':
			animator.active = !animator.active;
			break;
		case 'a':
			g_animate = 1 - g_animate;
			//Reset the timer to point to the current time.		
			time = g_timer.GetElapsedTime();
			g_timer.Reset();
			break;
		case '0':
			//Reset your object.
			break ;
		case 'm':
			if( g_recording == 1 )
			{
				std::cout << "Frame recording disabled." << std::endl;
				g_recording = 0;
			}
			else
			{
				std::cout << "Frame recording enabled." << std::endl;
				g_recording = 1 ;
			}
			g_frameSaver.Toggle();
			break ;
		case 'h':
		case '?':
			GDrawing::plotInstructions();
			break;
	}
	glutPostRedisplay();
}
Ejemplo n.º 14
0
void idleCB(void)
{
    if( Animate == 1 )
    {
        // TM.Reset() ; // commenting out this will make the time run from 0
        // leaving 'Time' counts the time interval between successive calls to idleCB
        if( Recording == 0 )
            TIME = TM.GetElapsedTime() ;
        else
            TIME += 0.033 ; // save at 30 frames per second.
        printf("TIME %f\n", TIME) ;
        glutPostRedisplay() ; 
    }
}
Ejemplo n.º 15
0
void CreateSomeFiles_And_ListTheFiles(size_t fileNum, size_t loopCount, ApiStatistics* pStatistics)
{
    DEF_TESTLOG_T("CreateSomeFiles_And_ListTheFiles, ");

    wstring dirpath(GetTestFileName(L"filelisting"));

    // Create files
    vector<wstring> vCreateFiles;
    TouchManyFiles(log, fileNum, GetWidTestBasePath() + L"\\" + dirpath, vCreateFiles, false);

    WaitUntilStartTime();
    
    // List files
    for(size_t i = 0; i < loopCount; ++i)
    {
        Timer t;
        ListFiles(log, GetWidTestBasePath() + L"\\" + dirpath);
        double d = t.GetElapsedTime();

        if(pStatistics)
        {
            pStatistics->InsertData(d);
        }

        if(IsTimeToEnd())
            break;
    }

    // Delete files   
    for(size_t i = 0; i < vCreateFiles.size(); ++i)
    {
        BOOL fOk = uDeleteFile((GetWidTestBasePath() + L"\\" + dirpath + L"\\" + vCreateFiles[i]).c_str());
        if(!fOk)
        {
            log.GetStream(TestLog::MT_ERROR) << L"FindNextFile error. Error is " << GetLastErrorStr() << std::endl;
            break;
        }
    }

    uRemoveDirectory((GetWidTestBasePath() + L"\\" + dirpath).c_str());

    PrintStatistics(L"CreateSomeFiles_And_ListTheFiles", pStatistics);
    
    log.Ok();
}
Ejemplo n.º 16
0
void myKey(unsigned char key, int x, int y)
{
    float time ;
    switch (key) {
        case 'q':
        case 27:
            exit(0); 
        case 's':
            FrSaver.DumpPPM(Width,Height) ;
            break;
        case 'r':
            resetArcball() ;
            glutPostRedisplay() ;
            break ;
        case 'a': // togle animation
            Animate = 1 - Animate ;
            // reset the timer to point to the current time		
            time = TM.GetElapsedTime() ;
            TM.Reset() ;
            // printf("Elapsed time %f\n", time) ;
            break ;
        case '0':
            //reset your object
            break ;
        case 'm':
            if( Recording == 1 )
            {
                printf("Frame recording disabled.\n") ;
                Recording = 0 ;
            }
            else
            {
                printf("Frame recording enabled.\n") ;
                Recording = 1  ;
            }
            FrSaver.Toggle(Width);
            break ;
        case 'h':
        case '?':
            instructions();
            break;
    }
    glutPostRedisplay() ;

}
Ejemplo n.º 17
0
double TestFindKthSmallest(Func findFunc, const char* funcName) {
	static const int NumIterations = 100;
	double totalTime = 0.0f;
	for (int i = 0; i != NumIterations; ++i) {
		vector<uint32_t> v(NumElements);
		iota(begin(v), end(v), 0);
		random_shuffle(begin(v), end(v));

		Timer timer;
		auto kthSmallest = findFunc(&v[0]);
		auto time = timer.GetElapsedTime();
		totalTime += time;
		assert(kthSmallest == K - 1);

		cout << funcName << "(): kth smallest value: " << kthSmallest << ", took " << (time * 1000.0f) << "ms." << endl;
	}
	return totalTime / NumIterations;
}
Ejemplo n.º 18
0
/** NOT USED (Simulated Annealing is Superior) **/
Puzzle PuzzleGenerator::HillClimbing(double timelimit, Puzzle p)
{
	// Function that uses hillclimbing algorithm to find best value puzzle.
	// Returns best puzzle found after timelimit or local max when if it is found before time limit

	Puzzle bestPuzzle = p;

	// Keep track of the time so we don't exceed it.
	Timer t;
	t.StartTimer();

	while (t.GetElapsedTime() < timelimit-0.1)
	{
		// Generate all successors of bestPuzzle
		vector<Puzzle> successors;
		bestPuzzle.GetAllSuccessors(successors);

		Puzzle bestSuccessor = successors[0];

		// Determine highest valued successor and save as new best puzzle
		for (vector<Puzzle>::size_type i = 0; i != successors.size(); i++)
		{
			if (successors[i].GetValue() > bestSuccessor.GetValue())
			{
				bestSuccessor = successors[i];
			}
		}

		// Make sure that best successor is better than its parent (bestPuzzle), save it as the new best puzzle, and loop.
		if (bestSuccessor.GetValue() > bestPuzzle.GetValue())
		{
			bestPuzzle = bestSuccessor;
		}
		else 
		{
			// If it's not better, we found a local maximum. Save it and
			return bestPuzzle;
		}
	}

	printf("time limit reached\n");
	return bestPuzzle;
}
Ejemplo n.º 19
0
	int Window::Loop()
	{
		Timer timer;
		timer.UpdateStartPoint();
		MSG msg;
		WindowAdapter* adapter = reinterpret_cast<WindowAdapter*>(GetWindowLongPtr(m_windowHandle, GWLP_USERDATA));
		if (!adapter)
			throw PunkInvalidArgumentException(L"Can't get window adapter interface");

		while (1)
		{
			while (PeekMessage(&msg, 0, 0, 0, PM_NOREMOVE))
			{
				if (GetMessage(&msg, 0, 0, 0))
				{
					TranslateMessage(&msg);
					DispatchMessage(&msg);
				}
				else
				{
					return 0;
				}
			}

			//Sleep(10);
			IdleEvent* e = new IdleEvent;
			e->elapsed_time_s = timer.GetElapsedTime();
			timer.UpdateStartPoint();
			adapter->OnIdleEvent(e);
			
			/****************************************
			//EventManager::Instance()->FixEvent(e);
			//EventManager::Instance()->Process();			
			/****************************************

			/*std::multimap<UINT, Handler>::iterator lb = m_handlers.lower_bound(WM_IDLE);
			std::multimap<UINT, Handler>::iterator ub = m_handlers.upper_bound(WM_IDLE);
			for (std::multimap<UINT, Handler>::iterator i = lb; i != ub; i++)
			{
			(*i).second(Parameters(0, WM_IDLE, 0, 0));
			}/**/
		}
	}
Ejemplo n.º 20
0
	void	RenderWindow::Show()
	{
		ShowWindow(m_hWnd,SW_HIDE);
		UpdateWindow(m_hWnd);
		MSG		msg;
		Timer	t;
		t.Init();
		float fTimeSinceLastFrame=0.0f;
		while(!m_bQuit)
		{
			if(PeekMessage(&msg,NULL,0,0,PM_REMOVE))
			{
				if(msg.message==WM_QUIT)
				{
					cout<<"quit message "<<endl;
					break;
				}
				TranslateMessage(&msg);
				DispatchMessage(&msg);
			}
			else
			{
				//frustun culling then
				fTimeSinceLastFrame+=t.GetElapsedTime(true);
				if(fTimeSinceLastFrame>0.033f)
				{
					fTimeSinceLastFrame=0.0f;
					FrustumCulling();
					m_pRenderWindow->RenderOneFrame();
					SwapBuffers(m_hDC);
				}
				else
				{
					Sleep((0.033f-fTimeSinceLastFrame)*1000);
				}
			}
		}
	}
Ejemplo n.º 21
0
/** NOT USED (Example Code provided by professor) **/
Puzzle PuzzleGenerator::RandomWalk(double timelimit)
{
	// A very simple function that start at a random configuration and keeps randomly modifying it
	// until it hits the time limit. Returns the best solution found so far.

	Puzzle p(nRows, nColumns, minVal, maxVal);	// Generate a random puzzle with the specified values.
	
	// Keep track of the best puzzle found so far (and its value).
	Puzzle bestPuzzle = p;			
	int bestValue = p.GetValue();
	
	// Keep track of the time so we don't exceed it.
	Timer t;
	t.StartTimer();
	
	// Loop until we hit the time limit.
	while (t.GetElapsedTime() < timelimit-0.1)	// To make sure that we don't exceed the time limit, we stop just before we hit the time limit.
	{
		// Generate a successor of p by randomly changing the value of a random cell 
		// (since we are doing a random walk, we just replace p with its successor).
		p = p.GetRandomSuccessor();	
		
		// Update the current best solution.
		if (p.GetValue() > bestValue)	// Calling GetValue() for the first time is costly
										// since the puzzle has to be evaluated first.
		{
			bestValue = p.GetValue();	// Calling it a second time simply returns the value that was computed before.
			bestPuzzle = p;
		}
	}
	
	return bestPuzzle;
	
	// The following code is not executed in this function. It exists just as an example for getting all the successors of a puzzle.
	vector<Puzzle> successors;
	bestPuzzle.GetAllSuccessors(successors);
}
Ejemplo n.º 22
0
	void ApplicationWindows::StartInternal()
	{
		m_working = true;
		Timer::Sync();
		MSG msg;
		Timer timer;
		float dt = 0.01f;
		while (m_working)
		{
			timer.Start();
			// process messages
			while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
			{
				TranslateMessage(&msg);
				DispatchMessage(&msg);

				if (msg.message == WM_QUIT)
				{
					/*ApplicationCore * appCore = Core::Instance()->GetApplicationCore();
					if (appCore && appCore->OnQuit())
					{
					exit(0);
					}
					else
					{
					m_working = true;
					}*/
					m_working = false;
				}
			} // peek message cycle
			
			Core::Update(dt);
			Core::Draw();
			dt = timer.GetElapsedTime();
		} // main cycle
	}
int main(int argc, char **argv)
{
	char filename[255];
	std::vector<xyLoc> thePath;
	std::vector<bool> mapData;
	int width, height;
	bool pre = false;
	bool run = false;

/*
	if (argc != 4)
	{
		printf("Invalid Arguments\nUsage %s <flag> <map> <scenario>\n", argv[0]);
		printf("Flags:\n");
		printf("\t-full : Preprocess map and run scenario\n");
		printf("\t-pre : Preprocess map\n");
		printf("\t-run : Run scenario without preprocessing\n");
		exit(0);
	}
	if (strcmp(argv[1], "-full") == 0)
	{
		pre = run = true;
	}
	else if (strcmp(argv[1], "-pre") == 0)
	{
		pre = true;
	}
	else if (strcmp(argv[1], "-run") == 0)
	{
		run = true;
	}
	else {
        printf("Invalid Arguments\nUsage %s <flag> <map> <scenario>\n", argv[0]);
		printf("Flags:\n");
        printf("\t-full : Preprocess map and run scenario\n");
        printf("\t-pre : Preprocess map\n");
        printf("\t-run : Run scenario without preprocessing\n");
        exit(0);
	}

	LoadMap(argv[2], mapData, width, height);
	sprintf(filename, "%s-%s.txt", GetName(), argv[2]);
*/
	// Testing area
	LoadMap("ca_cave.map", mapData, width, height);
	sprintf(filename, "%s-%s.txt", GetName(), "TEST");

	pre = run = true;
	if (pre)
	{
		PreprocessMap(mapData, width, height, filename);
	}

	if (!run)
	{
		return 0;
	}

	void *reference = PrepareForSearch(mapData, width, height, filename);

	//ScenarioLoader scen(argv[3]);
	ScenarioLoader scen("ca_cave.map.scen");


	Timer t;
	std::vector<stats> experimentStats;
	for (int x = 0; x < scen.GetNumExperiments(); x++)
    {
		printf("%d of %d\n", x+1, scen.GetNumExperiments());
		thePath.resize(0);
		experimentStats.resize(x+1);
		bool done;
		xyLoc s, g;
		s.x = scen.GetNthExperiment(x).GetStartX();
		s.y = scen.GetNthExperiment(x).GetStartY();
		g.x = scen.GetNthExperiment(x).GetGoalX();
		g.y = scen.GetNthExperiment(x).GetGoalY();
		SetFirstSearch(true);
		InitializeSearch();
		do {
			t.StartTimer();
			done = GetPath(reference, s, g, thePath);
			t.EndTimer();

			experimentStats[x].times.push_back(t.GetElapsedTime());
			experimentStats[x].lengths.push_back(thePath.size());
			for (unsigned int t = experimentStats[x].path.size(); t < thePath.size(); t++)
				experimentStats[x].path.push_back(thePath[t]);
		} while (done == false);
    }

	for (unsigned int x = 0; x < experimentStats.size(); x++)
	{
		printf("%s\ttotal-time\t%f\tmax-time-step\t%f\ttime-20-moves\t%f\ttotal-len\t%f\tsubopt\t%f\t", argv[3],
			   experimentStats[x].GetTotalTime(), experimentStats[x].GetMaxTimestep(), experimentStats[x].Get20MoveTime(),
			   experimentStats[x].GetPathLength(), experimentStats[x].GetPathLength()/scen.GetNthExperiment(x).GetDistance());
		if (experimentStats[x].path.size() == 0 ||
			(experimentStats[x].ValidatePath(width, height, mapData) &&
			 scen.GetNthExperiment(x).GetStartX() == experimentStats[x].path[0].x &&
			 scen.GetNthExperiment(x).GetStartY() == experimentStats[x].path[0].y &&
			 scen.GetNthExperiment(x).GetGoalX() == experimentStats[x].path.back().x &&
			 scen.GetNthExperiment(x).GetGoalY() == experimentStats[x].path.back().y))
		{
			printf("valid\n");
		}
		else {
			printf("invalid\n");
		}
	}
/*
	// Testing section...
//131	233	163	50
	xyLoc s, g;
	s.x = 95;
	s.y = 146;
	g.x = 92;
	g.y = 189;
	InitializeSearch();
	Timer t;
	t.StartTimer();
	bool done = false;
	while (!done)
	{
		done = GetPath(reference, s, g, thePath);
	}
	t.EndTimer();
	printf("(%d,%d)->(%d,%d)\n",s.x,s.y,g.x,g.y);
	printf("time: %fs\n",t.GetElapsedTime());
	write_map(mapData, width, height, s, g, thePath);
	stats st;
	st.path = thePath;
	bool k = (st.ValidatePath(width, height, mapData)
			&& s.x == thePath[0].x
			&& s.y == thePath[0].y
			&& g.x == thePath.back().x
			&& g.y == thePath.back().y
			);
	if (k)
		printf("valid\n");
	else
		printf("invalid\n");

	return 0;*/
}
Ejemplo n.º 24
0
void runProblemSet(char *problems, int multiplier)
{
	Map *map = new Map(gDefaultMap);
	map->Scale(512, 512);
	msa = new MapSectorAbstraction(map, 8, multiplier);

	Graph *g = msa->GetAbstractGraph(1);
	GraphAbstractionHeuristic gah2(msa, 2);
	GraphAbstractionHeuristic gah1(msa, 1);
	
	GraphRefinementEnvironment env2(msa, 2, &gah2);
	GraphRefinementEnvironment env1(msa, 1, &gah1);
	env1.SetDirected(false);
	env2.SetDirected(false);
	
	FILE *f = fopen(problems, "r");
	if (f == 0)
	{
		printf("Cannot open file: '%s'\n", problems);
		exit(0);
	}
	printf("len\tlvl2n\tlvl2nt\tlvl2len\tlvl2tim\tlvl1nf\tlvl1ntf\tlvl1tn\tlvl1tt\tlvl1len_f\ttot\ttott\ttot_len\n");
	Timer t;
	while (!feof(f))
	{
		int from, to, cost;
		if (fscanf(f, "%d\t%d\t%d\n", &from, &to, &cost) != 3)
			break;
		node *s1 = g->GetNode(from);
		node *g1 = g->GetNode(to);
		node *s2 = msa->GetParent(s1);
		node *g2 = msa->GetParent(g1);
		uint64_t nodesExpanded = 0;
		uint64_t nodesTouched = 0;
		double totalTime = 0;
		//		printf("Searching from %d to %d in level 1; %d to %d in level 2\n",
		//			   s1->GetNum(), g1->GetNum(), s2->GetNum(), g2->GetNum());
		graphState gs1, gs2;
		gs1 = s2->GetNum();
		gs2 = g2->GetNum();
		std::vector<graphState> thePath;
		std::vector<graphState> abstractPath;
		t.StartTimer();
		astar.GetPath(&env2, gs1, gs2, abstractPath);
		totalTime = t.EndTimer();
		printf("%d\t", cost);
		printf("%llu\t%llu\t%1.2f\t%f\t", astar.GetNodesExpanded(), astar.GetNodesTouched(), env2.GetPathLength(abstractPath), totalTime);
		if (abstractPath.size() == 0)
		{
			printf("%llu\t%llu\t%llu\t%llu\t%1.2f\t%f\t", (uint64_t)0, (uint64_t)0, astar.GetNodesExpanded(), astar.GetNodesTouched(), 0.0, 0.0);
			printf("%llu\t%llu\t%1.2f\t%f\t%d\t%d\n", astar.GetNodesExpanded(), astar.GetNodesTouched(), 0.0, 0.0, 0, 0);
//			printf("\n");
			continue;
		}

		nodesExpanded += astar.GetNodesExpanded();
		nodesTouched += astar.GetNodesTouched();

		env1.SetPlanningCorridor(abstractPath, 2);
		gs1 = s1->GetNum();
		gs2 = g1->GetNum();
		t.StartTimer();
		astar.GetPath(&env1, gs1, gs2, thePath);
		t.EndTimer();
		printf("%llu\t%llu\t%llu\t%llu\t%1.2f\t%f\t",
			   astar.GetNodesExpanded(), astar.GetNodesTouched(),
			   astar.GetNodesExpanded()+nodesExpanded, astar.GetNodesTouched()+nodesTouched,
			   env1.GetPathLength(thePath), totalTime+t.GetElapsedTime());
		
		int abstractStart = 0;
		gs1 = s1->GetNum();
		double totalLength = 0;
		int refineAmt = 2;
		int refinedPathNodes = 0;
		do { // not working yet -- fully check!
			env1.SetPlanningCorridor(abstractPath, 2, abstractStart);
			gs2 = g1->GetNum();
			if (abstractPath.size()-abstractStart > refineAmt)
			{
				env1.SetUseAbstractGoal(true, 2);
				gs2 = abstractPath[abstractStart+refineAmt];
			}
			else {
				env1.SetUseAbstractGoal(false, 0);
			}
			t.StartTimer();
			astar.GetPath(&env1, gs1, gs2, thePath);
			t.EndTimer();
			refinedPathNodes += thePath.size();
			totalTime+=t.GetElapsedTime();
			abstractStart += refineAmt;
			gs1 = thePath.back();
			
			nodesExpanded += astar.GetNodesExpanded();
			nodesTouched += astar.GetNodesTouched();
			totalLength += env1.GetPathLength(thePath);
			if (thePath.back() == gs2)
				break;
		} while (thePath.back() != g1->GetNum());
		
//		printf("%llu\t%llu\t%1.2f\t", astar.GetNodesExpanded(), astar.GetNodesTouched(), env1.GetPathLength(thePath));
		thePath.resize(0);
		printf("%llu\t%llu\t%1.2f\t%f\t%d\t%d\n", nodesExpanded, nodesTouched, totalLength, totalTime, abstractPath.size(), refinedPathNodes);
		
//		gs1 = s1->GetNum();
//		gs2 = g1->GetNum();
//		env1.SetPlanningCorridor(abstractPath, 2);
//		astar.GetPath(&env1, gs1, gs2, thePath);
//		printf("%llu\t%1.2f\n", astar.GetNodesExpanded(), env1.GetPathLength(thePath));
	}
	fclose(f);
	exit(0);
}
Ejemplo n.º 25
0
int testEncode(const std::string & fileName, int qcoord, int qtexCoord, int qnormal, O3DGCSC3DMCStreamType streamType)
{
    std::string folder;
    long found = (long) fileName.find_last_of(PATH_SEP);
    if (found != -1)
    {
        folder = fileName.substr(0,found);
    }
    if (folder == "")
    {
        folder = ".";
    }
    std::string file(fileName.substr(found+1));
    std::string outFileName = folder + PATH_SEP + file.substr(0, file.find_last_of(".")) + ".s3d";
    std::vector< Vec3<Real> > points;
    std::vector< Vec3<Real> > normals;
    std::vector< Vec2<Real> > texCoords;
    std::vector< Vec3<Index> > triangles;
    std::vector< unsigned long > matIDs;
    std::vector< Material > materials;
    std::string materialLib;
    std::cout << "Loading " << fileName << " ..." << std::endl;
    bool ret = LoadOBJ(fileName, points, texCoords, normals, triangles, matIDs, materials, materialLib);
    if (!ret)
    {
        std::cout << "Error: LoadOBJ()\n" << std::endl;
        return -1;
    }
    if (points.size() == 0 || triangles.size() == 0)
    {
        std::cout <<  "Error: points.size() == 0 || triangles.size() == 0 \n" << std::endl;
        return -1;
    }
    std::cout << "Done." << std::endl;

    if (materials.size() > 0)
    {
        std::string matFileName = folder + PATH_SEP + file.substr(0, file.find_last_of(".")) + ".mat";
        ret = SaveMaterials(matFileName.c_str(), materials, materialLib);
    }
    if (!ret)
    {
        std::cout << "Error: SaveMatrials()\n" << std::endl;
        return -1;
    }
/*
    ret = SaveOBJ("debug.obj", points, texCoords, normals, triangles, materials, matIDs, materialLib);
    if (!ret)
    {
        std::cout << "Error: SaveOBJ()\n" << std::endl;
        return -1;
    }
*/
    SC3DMCEncodeParams params;
    params.SetStreamType(streamType);
    IndexedFaceSet<Index> ifs;
    params.SetCoordQuantBits(qcoord);
    params.SetNormalQuantBits(qnormal);
    params.SetTexCoordQuantBits(qtexCoord);

    ifs.SetNCoord((unsigned long) points.size());
    ifs.SetNNormal((unsigned long)normals.size());
    ifs.SetNTexCoord((unsigned long)texCoords.size());
    ifs.SetNCoordIndex((unsigned long)triangles.size());

    std::cout << "Mesh info "<< std::endl;
    std::cout << "\t# coords    " << ifs.GetNCoord() << std::endl;
    std::cout << "\t# normals   " << ifs.GetNNormal() << std::endl;
    std::cout << "\t# texcoords " << ifs.GetNTexCoord() << std::endl;
    std::cout << "\t# triangles " << ifs.GetNCoordIndex() << std::endl;

    ifs.SetCoord((Real * const) & (points[0]));
    ifs.SetCoordIndex((Index * const ) &(triangles[0]));
    if (materials.size() > 1)
    {
        ifs.SetMatID((unsigned long * const ) &(matIDs[0]));
    }
    if (normals.size() > 0)
    {
        ifs.SetNormal((Real * const) & (normals[0]));
    }
    if (texCoords.size() > 0)
    {
        ifs.SetTexCoord((Real * const ) & (texCoords[0]));
    }

    // compute min/max
    ifs.ComputeMinMax(O3DGC_SC3DMC_MAX_ALL_DIMS); // O3DGC_SC3DMC_DIAG_BB

    BinaryStream bstream((unsigned long)points.size()*8);

    
    SC3DMCEncoder<Index> encoder;
    Timer timer;
    timer.Tic();
    encoder.Encode(params, ifs, bstream);
    timer.Toc();
    std::cout << "Encode time (ms) " << timer.GetElapsedTime() << std::endl;

    FILE * fout = fopen(outFileName.c_str(), "wb");
    if (!fout)
    {
        return -1;
    }
    fwrite(bstream.GetBuffer(), 1, bstream.GetSize(), fout);
    fclose(fout);
    std::cout << "Bitstream size (bytes) " << bstream.GetSize() << std::endl;

    std::cout << "Details" << std::endl;
    const SC3DMCStats & stats = encoder.GetStats();
    std::cout << "\t CoordIndex         " << stats.m_timeCoordIndex     << " ms, " << stats.m_streamSizeCoordIndex     <<" bytes (" << 8.0 * stats.m_streamSizeCoordIndex     / ifs.GetNCoord() <<" bpv)" <<std::endl;
    std::cout << "\t Coord              " << stats.m_timeCoord          << " ms, " << stats.m_streamSizeCoord          <<" bytes (" << 8.0 * stats.m_streamSizeCoord          / ifs.GetNCoord() <<" bpv)" <<std::endl;
    std::cout << "\t Normal             " << stats.m_timeNormal         << " ms, " << stats.m_streamSizeNormal         <<" bytes (" << 8.0 * stats.m_streamSizeNormal         / ifs.GetNCoord() <<" bpv)" <<std::endl;
    std::cout << "\t TexCoord           " << stats.m_timeTexCoord       << " ms, " << stats.m_streamSizeTexCoord       <<" bytes (" << 8.0 * stats.m_streamSizeTexCoord       / ifs.GetNCoord() <<" bpv)" <<std::endl;
    std::cout << "\t Color              " << stats.m_timeColor          << " ms, " << stats.m_streamSizeColor          <<" bytes (" << 8.0 * stats.m_streamSizeColor          / ifs.GetNCoord() <<" bpv)" <<std::endl;
    std::cout << "\t Float Attributes   " << stats.m_timeFloatAttribute << " ms, " << stats.m_streamSizeFloatAttribute <<" bytes (" << 8.0 * stats.m_streamSizeFloatAttribute / ifs.GetNCoord() <<" bpv)" <<std::endl;
    std::cout << "\t Integer Attributes " << stats.m_timeFloatAttribute << " ms, " << stats.m_streamSizeFloatAttribute <<" bytes (" << 8.0 * stats.m_streamSizeFloatAttribute / ifs.GetNCoord() <<" bpv)" <<std::endl;

    return 0;
}
Ejemplo n.º 26
0
void TSTest(unsigned long , tKeyboardModifier , char)
{
	int N = 16, k = 4;
	std::vector<int> tiles;

	TopSpin tse(N, k);
	TopSpinState s(N, k);
	TopSpinState g(N, k);

//	if (ts->PDB.size() == 0)
//	{
//		tse.Load_Regular_PDB("/Users/nathanst/Desktop/TS_0-5.pdb", g, true);
//		tse.Load_Regular_PDB("/Users/nathanst/Desktop/TS_12-15.pdb", g, true);
//		tse.Load_Regular_PDB("/Users/nathanst/Desktop/TS_6-11.pdb", g, true);
//		tse.lookups.push_back({kMaxNode, 3, 1, 0});
//		tse.lookups.push_back({kLeafNode, 0, 0, 0});
//		tse.lookups.push_back({kLeafNode, 0, 0, 1});
//		tse.lookups.push_back({kLeafNode, 0, 0, 2});
//	}

	if (ts->PDB.size() == 0)
	{
		tse.Load_Regular_PDB("/Users/nathanst/Desktop/TS_0-3.pdb", g, true);
		tse.Load_Regular_PDB("/Users/nathanst/Desktop/TS_0-5+.pdb", g, true);
		tse.Load_Regular_PDB("/Users/nathanst/Desktop/TS_6-9.pdb", g, true);
		tse.Load_Regular_PDB("/Users/nathanst/Desktop/TS_6-11+.pdb", g, true);
		tse.Load_Regular_PDB("/Users/nathanst/Desktop/TS_12-15.pdb", g, true);
		tse.lookups.push_back({kMaxNode, 3, 1, 0});
		tse.lookups.push_back({kAddNode, 2, 4, 0});
		tse.lookups.push_back({kAddNode, 2, 6, 0});
		tse.lookups.push_back({kLeafNode, 0, 0, 4});
		tse.lookups.push_back({kLeafNode, 0, 0, 0});
		tse.lookups.push_back({kLeafNode, 0, 0, 1});
		tse.lookups.push_back({kLeafNode, 0, 0, 2});
		tse.lookups.push_back({kLeafNode, 0, 0, 3});
	}

	
	IDAStar<TopSpinState, TopSpinAction> ida;
	std::vector<TopSpinAction> path1;


	tse.SetPruneSuccessors(true);
	for (int x = 0; x < 100; x++)
	{
		GetTSInstance(tse, s, x);
		std::cout << "Problem " << x << std::endl;
		std::cout << "Searching from: " << std::endl << s << std::endl << g << std::endl;
		Timer t;
		t.StartTimer();
		ida.GetPath(&tse, s, g, path1);
		t.EndTimer();
		std::cout << "Path found, length " << path1.size() << " time:" << t.GetElapsedTime() << " ";
		std::cout << ida.GetNodesExpanded() << " nodes expanded" << std::endl;
//		for (int x = 0; x < ts->histogram.size(); x++)
//		{
//			printf("%2d  %d\n", x, ts->histogram[x]);
//		}
		
//		tse.PrintHStats();
	}
}
Ejemplo n.º 27
0
int testDecode(std::string & fileName)
{
    std::string folder;
    long found = (long)fileName.find_last_of(PATH_SEP);
    if (found != -1)
    {
        folder = fileName.substr(0,found);
    }
    if (folder == "")
    {
        folder = ".";
    }
    std::string file(fileName.substr(found+1));
    std::string outFileName = folder + PATH_SEP + file.substr(0, file.find_last_of(".")) + "_dec.obj";


    std::vector< Vec3<Real> > points;
    std::vector< Vec3<Real> > normals;
    std::vector< Vec2<Real> > colors;
    std::vector< Vec2<Real> > texCoords;
    std::vector< Vec3<Index> > triangles;
    std::vector< unsigned long > matIDs;
    std::vector< Material > materials;
    std::string materialLib;

    std::string matFileName = folder + PATH_SEP + file.substr(0, file.find_last_of(".")) + ".mat";
    bool ret = LoadMaterials(matFileName.c_str(), materials, materialLib);
    if (ret)
    {
        const size_t numMaterials = materials.size();
        unsigned long n, shift = 0;
        for(size_t i = 0; i < numMaterials; ++i)
        {
            n = materials[i].m_numTriangles + shift;
            matIDs.resize(n, materials[i].m_id);
            shift = n;
        }
    }
    

    BinaryStream bstream;
    IndexedFaceSet<Index> ifs;


    FILE * fin = fopen(fileName.c_str(), "rb");
    if (!fin)
    {
        return -1;
    }
    fseek(fin, 0, SEEK_END);
    unsigned long size = ftell(fin);
    bstream.Allocate(size);
    rewind(fin);
    unsigned long nread = (unsigned long)fread((void *) bstream.GetBuffer(), 1, size, fin);
    bstream.SetSize(size);
    if (nread != size)
    {
        return -1;
    }
    fclose(fin);
    std::cout << "Bitstream size (bytes) " << bstream.GetSize() << std::endl;

    SC3DMCDecoder<Index> decoder;
    // load header
    Timer timer;
    timer.Tic();
    decoder.DecodeHeader(ifs, bstream);
    timer.Toc();
    std::cout << "DecodeHeader time (ms) " << timer.GetElapsedTime() << std::endl;

    // allocate memory
    triangles.resize(ifs.GetNCoordIndex());
    ifs.SetCoordIndex((Index * const ) &(triangles[0]));    

    points.resize(ifs.GetNCoord());
    ifs.SetCoord((Real * const ) &(points[0]));    

    if (ifs.GetNNormal() > 0)
    {
        normals.resize(ifs.GetNNormal());
        ifs.SetNormal((Real * const ) &(normals[0]));  
    }
    if (ifs.GetNColor() > 0)
    {
        colors.resize(ifs.GetNColor());
        ifs.SetColor((Real * const ) &(colors[0]));  
    }
    if (ifs.GetNTexCoord() > 0)
    {
        texCoords.resize(ifs.GetNTexCoord());
        ifs.SetTexCoord((Real * const ) &(texCoords[0]));
    }

    std::cout << "Mesh info "<< std::endl;
    std::cout << "\t# coords    " << ifs.GetNCoord() << std::endl;
    std::cout << "\t# normals   " << ifs.GetNNormal() << std::endl;
    std::cout << "\t# texcoords " << ifs.GetNTexCoord() << std::endl;
    std::cout << "\t# triangles " << ifs.GetNCoordIndex() << std::endl;

    // decode mesh
    timer.Tic();
    decoder.DecodePlayload(ifs, bstream);
    timer.Toc();
    std::cout << "DecodePlayload time (ms) " << timer.GetElapsedTime() << std::endl;

    std::cout << "Details" << std::endl;
    const SC3DMCStats & stats = decoder.GetStats();
    std::cout << "\t CoordIndex         " << stats.m_timeCoordIndex     << " ms, " << stats.m_streamSizeCoordIndex     <<" bytes (" << 8.0*stats.m_streamSizeCoordIndex     / ifs.GetNCoord() <<" bpv)" <<std::endl;
    std::cout << "\t Coord              " << stats.m_timeCoord          << " ms, " << stats.m_streamSizeCoord          <<" bytes (" << 8.0*stats.m_streamSizeCoord          / ifs.GetNCoord() <<" bpv)" <<std::endl;
    std::cout << "\t Normal             " << stats.m_timeNormal         << " ms, " << stats.m_streamSizeNormal         <<" bytes (" << 8.0*stats.m_streamSizeNormal         / ifs.GetNCoord() <<" bpv)" <<std::endl;
    std::cout << "\t TexCoord           " << stats.m_timeTexCoord       << " ms, " << stats.m_streamSizeTexCoord       <<" bytes (" << 8.0*stats.m_streamSizeTexCoord       / ifs.GetNCoord() <<" bpv)" <<std::endl;
    std::cout << "\t Color              " << stats.m_timeColor          << " ms, " << stats.m_streamSizeColor          <<" bytes (" << 8.0*stats.m_streamSizeColor          / ifs.GetNCoord() <<" bpv)" <<std::endl;
    std::cout << "\t Float Attributes   " << stats.m_timeFloatAttribute << " ms, " << stats.m_streamSizeFloatAttribute <<" bytes (" << 8.0*stats.m_streamSizeFloatAttribute / ifs.GetNCoord() <<" bpv)" <<std::endl;
    std::cout << "\t Integer Attributes " << stats.m_timeFloatAttribute << " ms, " << stats.m_streamSizeFloatAttribute <<" bytes (" << 8.0*stats.m_streamSizeFloatAttribute / ifs.GetNCoord() <<" bpv)" <<std::endl;
    std::cout << "\t Reorder            " << stats.m_timeReorder        << " ms,  " << 0 <<" bytes (" << 0.0 <<" bpv)" <<std::endl;

    std::cout << "Saving " << outFileName << " ..." << std::endl;

    ret = SaveOBJ(outFileName.c_str(), points, texCoords, normals, triangles, materials, matIDs, materialLib);
    if (!ret)
    {
        std::cout << "Error: SaveOBJ()\n" << std::endl;
        return -1;
    }
    std::cout << "Done." << std::endl;
    return 0;
}
Ejemplo n.º 28
0
void WriteFileTest_(size_t sizeKB, size_t buffersizeKB, ApiStatistics* pStatistics, INT64& jWrittenBytes)
{
    DEF_TESTLOG_T("WriteFileTest, ");
    std::wstring fileName = GetTestFileName(L"WriteFileTest");

    jWrittenBytes = 0;  

    BOOL fOk = FALSE;
    //////////////////////////////////////////////////////////////////////////
    {
        File f(fileName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_READ, CREATE_ALWAYS);

        if(!f.IsValidHandle())
        {
            log.GetStream(TestLog::MT_ERROR) << L"CreateFile" << endl;
            fOk = FALSE;
            goto END;
        }

        if(buffersizeKB == 0)
        {
            buffersizeKB = 1;
        }

        char* buffer = new char[buffersizeKB * 1024];

        for(size_t i = 0; i < buffersizeKB; i++)
        {
            memcpy_s(buffer + (1024 * i), 1024, "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
                "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
                "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
                "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
                "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
                "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
                "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
                "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
                "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
                "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"
                "ABCDEFGHIJKLMNOPQRSTUV\r\n", 1024 );
        }

        DWORD writeBytes = 0;

        for(size_t x = 0; x < sizeKB; x += buffersizeKB)
        {        
            Timer t;
            double d = t.GetElapsedTime();
            if(uWriteFile(f, buffer, buffersizeKB * 1024, &writeBytes, 0) == FALSE)
            {
                log.GetStream(TestLog::MT_ERROR) << L"WriteFile" << endl;
                delete[] buffer;
                fOk = FALSE;
                goto END;
            }

            d = t.GetElapsedTime();
            if(pStatistics)
            {
                pStatistics->InsertData(d);
            }

            jWrittenBytes += writeBytes;

            if(IsTimeToEnd())
            {
                delete[] buffer;
                fOk = TRUE;
                goto END;
            }

            if(writeBytes != buffersizeKB * 1024)
            {
                log.GetStream(TestLog::MT_ERROR) << L"WriteFile: writeBytes Error." << endl;
                delete[] buffer;
                fOk = FALSE;
                goto END;
            }
        } // main loop end.

        delete[] buffer;

        log.GetStream(TestLog::MT_MESSAGE) << L"<" << fileName << L"> file created." << endl;
        fOk = TRUE;
    } // The file handle be closed automatically.

END:
    uDeleteFile(fileName.c_str());

    if(!fOk)
    {
        log.GetStream(TestLog::MT_ERROR) << L"Failed to create a file" << endl;
        return;
    }

    log.Ok();
}
Ejemplo n.º 29
0
void ReadFileTest_(size_t sizeKB, size_t buffersizeKB, ApiStatistics* pStatistics, INT64& jReadBytes)
{
    DEF_TESTLOG_T("ReadFileTest_, ");
    std::vector<wstring> v;
    for( size_t t = 1; t <= 50; ++t)
    {
        std::wostringstream oss;
        oss << t;
        v.push_back(oss.str());
    }

    std::wstring fileName = L"Z:\\ReadFileTest";

    jReadBytes = 0;

    BOOL fOk = FALSE;
    //////////////////////////////////////////////////////////////////////////
    for(size_t i = 0; ; ++i)
    {
        File f(fileName + v[i % v.size()], GENERIC_READ, 0, OPEN_EXISTING);

        if(!f.IsValidHandle())
        {
            continue;
            //log.GetStream(TestLog::MT_ERROR) << L"The File not exist." << endl;
            //fOk = FALSE;
            //goto END;
        }

        if(buffersizeKB == 0)
        {
            buffersizeKB = 1;
        }

        char* buffer = new char[buffersizeKB * 1024];

        DWORD readBytes = 0;

        for(size_t x = 0; x < sizeKB; x += buffersizeKB)
        {        
            Timer t;
            double d = t.GetElapsedTime();
            if(uReadFile(f, buffer, buffersizeKB * 1024, &readBytes, 0) == FALSE)
            {
                log.GetStream(TestLog::MT_ERROR) << L"ReadFile" << endl;
                delete[] buffer;
                fOk = FALSE;
                goto END;
            }

            d = t.GetElapsedTime();
            
            if(pStatistics)
            {
                pStatistics->InsertData(d);
            }

            if(buffersizeKB*1024 != readBytes)
            {
                log.GetStream(TestLog::MT_ERROR) << L"ReadFile Size Error" << endl;
                delete[] buffer;
                fOk = FALSE;
                goto END;
            }

            jReadBytes += readBytes;

            if(IsTimeToEnd())
            {
                delete[] buffer;
                fOk = TRUE;
                goto END;
            }

            if(readBytes != buffersizeKB * 1024)
            {
                log.GetStream(TestLog::MT_ERROR) << L"WriteFile: writeBytes Error." << endl;
                delete[] buffer;
                fOk = FALSE;
                goto END;
            }
        } // main loop end.

        delete[] buffer;

        log.GetStream(TestLog::MT_MESSAGE) << L"<" << fileName << L"> file created." << endl;
        fOk = TRUE;
        break;
    } // The file handle be closed automatically.

END:
//    uDeleteFile(fileName.c_str());

    if(!fOk)
    {
        log.GetStream(TestLog::MT_ERROR) << L"Failed to a create file." << endl;
        return;
    }

    log.Ok();
}
Ejemplo n.º 30
0
int main(int argc, char** argv) {
    Timer timer;
    string filenameScene = "./boxArea.xml";
    string filenameImage = "./image.exr";
	string filenameLight;
    uint32_t width = 512; 
    uint32_t height = 512;
    uint32_t indirect = 8192;
    uint32_t samples = 1;
    uint32_t iterations = 4;
    uint32_t seedNum = 300;

	bool outputSample = false;
    uint32_t budget = 600;
    bool log = false;
    CmdLine cmd("comat: ", ' ', "none", false);
    try {
        SwitchArg helpArg("?", "help", "help message", cmd, false);
        ValueArg<int> widthArg("w", "width", "image width", false, width, "int", cmd);
        ValueArg<int> heightArg("h", "height", "image height", false, height, "int", cmd);

        UnlabeledValueArg<string> filenameSceneArg("scene", "scene filename", true, filenameScene, "string", cmd);
        UnlabeledValueArg<string> filenameImageArg("image", "image filename", true, filenameImage, "string", cmd);

		SwitchArg sampleImgArg("c", "sampleimage", "sample image", cmd, false);
		ValueArg<string> filenameLightArg("f", "lights", "virtual light filename", false, filenameLight, "string", cmd);
        ValueArg<int> indirectArg("i", "indirect", "indirect virtual light number", false, indirect, "int", cmd);
        ValueArg<int> samplesArg("s", "samples", "pixel row samples", false, samples, "int", cmd);
        ValueArg<int> seedArg("r", "seeds", "seedings", false, seedNum, "int", cmd);
        ValueArg<int> clusterArg("k", "clusters", "cluster number", false, budget, "int", cmd);
        SwitchArg logArg("l", "log", "write lot to file", cmd, log);

        //cmd.parse(argc, argv);

        //if(helpArg.getValue()) StdOutput().usage(cmd);

        log = logArg.getValue();
		outputSample = sampleImgArg.getValue();
        filenameScene = filenameSceneArg.getValue();
        filenameImage = filenameImageArg.getValue();
		filenameLight = filenameLightArg.getValue();
        seedNum = seedArg.getValue();
        budget = clusterArg.getValue();
        width = widthArg.getValue();
        height = heightArg.getValue();
        indirect = indirectArg.getValue();
        samples = samplesArg.getValue();
    } catch(ArgException &e) {
        StdOutput().usage(cmd);
        cerr << "error: " << e.error() << endl << " for arg " << e.argId() << endl;
        return 1;
    }    

    //task_scheduler_init init(task_scheduler_init::deferred);
    //init.initialize(1);

    // reporting
    shared_ptr<ReportHandler> reportHandler;
    if (log)
        reportHandler = shared_ptr<ReportHandler>(new FileReportHandler(filenameImage + ".log.txt"));
    else
        reportHandler = shared_ptr<ReportHandler>(new PrintReportHandler());

    // load scene
    if(reportHandler) reportHandler->beginActivity("loading scene - " + filenameScene);
    shared_ptr<Scene> scene = SceneArchive::load(filenameScene);
    if(reportHandler) reportHandler->endActivity();

    // build engine
    if(reportHandler) reportHandler->beginActivity("build ray engine");
    shared_ptr<RayEngine> engine = RayEngine::BuildDefault(scene->Surfaces(), scene->Instances(), 0.0f, 0);
    if(reportHandler) reportHandler->endActivity();

	shared_ptr<VirtualLightGenerator> generator;
	if (filenameLight.empty())
		generator = shared_ptr<VirtualLightGenerator>(new VirtualPointLightDiffuseGenerator(scene.get(), engine.get()));
	else
		generator = shared_ptr<VirtualLightGenerator>(new LightSerializeGenerator(filenameLight));

	shared_ptr<PathSampler> sampler = shared_ptr<PathSampler>(new StratifiedPathSamplerStd());

	Image<Vec3f> image(width, height);
	shared_ptr<Image<uint32_t> > sampleImage;
	if (outputSample)
		sampleImage = shared_ptr<Image<uint32_t> >(new Image<uint32_t>(width, height));

    KnnMatrix knnMat(scene.get(), engine.get(), generator.get(), reportHandler.get());

	timer.Reset();
	timer.Start();
    knnMat.Render(&image, sampleImage.get(), samples, indirect, seedNum, budget);
	timer.Stop();

	Image<Vec3f> gpImage(width, height);
	knnMat.RenderGatherGroup(&gpImage);
	ImageIO::Save(filenameImage + ".gpg.exr", gpImage);
	cout << "************************************************************" << endl;
    if (outputSample)
    {
        ImageIO::Save(filenameImage + "sample.exr", sampleImage);
        uint32_t avgSampleNum = (uint32_t)AverageSampleNum(sampleImage.get());
        stringstream sout;
        sout << "." << avgSampleNum;
        ImageIO::Save(filenameImage + sout.str() + ".exr", image);
    }
    else
    {
        ImageIO::Save(filenameImage + ".exr", image);
    }

    stringstream sout;
    sout << "total Rendering time: " << timer.GetElapsedTime() << endl;
    if(reportHandler) reportHandler->message(sout.str());

    // stats printing
    StatsManager stats;
    scene->CollectStats(stats);
    stats.Print(cout);


    // done
    return 0;
}