Exemplo n.º 1
0
StopWatch::StopWatch()
{
	timer.start.QuadPart = 0;
	timer.stop.QuadPart = 0; 
	QueryPerformanceFrequency(&frequency);
}
Exemplo n.º 2
0
void InitCPUTicks()
{
    QueryPerformanceFrequency( &lfreq );
}
Exemplo n.º 3
0
BOOL CSoundDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	

	ant_k_freq = _k_freq = 1;
	m_freq.SetRange(0,100);
	m_freq.SetPos(100-_k_freq*50);

	_volumen = 1;
	_left = 0.5;
	_right = 0.5;
	m_vol.SetRange(0,100);
	m_vol.SetPos((1-_volumen)*100);
	m_left.SetRange(0,100);
	m_left.SetPos((1-_left)*100);
	m_right.SetRange(0,100);
	m_right.SetPos((1-_right)*100);



	// Cargo el wav que voy a usar de muestreo
	char wav = QUE_WAV;
	switch(wav)
	{
		case 0:
			_cant_samples = generateWav("jet.wav",&_pcm);
			break;
		case 1:
			_cant_samples = generateWav("engine1.wav",&_pcm);
			break;
		case 2:
			_cant_samples = generateWav("spaceship.wav",&_pcm)*0.5;
			break;
	}
			

	_index = 0;
	WAVEFORMATEX   Format; 
	Format.cbSize = sizeof(WAVEFORMATEX);
	Format.wFormatTag = WAVE_FORMAT_PCM;
	Format.nChannels = 2;
	Format.nSamplesPerSec = SAMPLE_RATE;
	Format.wBitsPerSample = 16;
	Format.nBlockAlign = 4;
	Format.nAvgBytesPerSec = Format.nSamplesPerSec*Format.nBlockAlign;

	if(waveOutOpen(&hWaveOut, WAVE_MAPPER, &Format, (DWORD)GetSafeHwnd() , 
			0L,CALLBACK_WINDOW)!=MMSYSERR_NOERROR)
	{       
		return TRUE;
	}


	QueryPerformanceFrequency(&F);
	QueryPerformanceCounter(&T0);

	// Genereo el timer 
	SetTimer(999,lap=TIME_LAP,NULL);


	return TRUE;  // return TRUE  unless you set the focus to a control
}
Exemplo n.º 4
0
void TEST_SPEED_FILE_IO()
{
	LARGE_INTEGER freq, perf_start, perf_end;
	float freqms;
	QueryPerformanceFrequency(&freq);
	freqms = freq.QuadPart / 1000.0f;

	std::cout << "Testing file read" << '\n';
	float arr1[10267 * 3];
	float arr2[10267 * 3];
	float arr3[10267 * 3];


	// C style
	QueryPerformanceCounter(&perf_start);
	FILE* fr = fopen("test.bufa", "r");
	for (int i = 0; i < 10267 * 3; i++)
	{
		float temp;
		fscanf(fr, "%f", &temp);
		arr1[i] = temp;
	}
	QueryPerformanceCounter(&perf_end);
	float elapsedC = (perf_end.QuadPart - perf_start.QuadPart) / freqms;
	std::cout << "C style read\n";
	std::cout << "Total duration = " << elapsedC << "ms\n";
	fclose(fr);

	// C buffer style
	QueryPerformanceCounter(&perf_start);
	fr = fopen("test.bufa", "r");
	fseek(fr, 0, SEEK_END);
	long lSize = ftell(fr);
	rewind(fr);
	char* buffer = (char*)malloc(sizeof(char)*lSize);
	fread(buffer, 1, lSize, fr);
	std::stringstream ss(buffer);
	for (int i = 0; i < 10267 * 3; i++)
	{
		float temp;
		ss >> temp;
		arr2[i] = temp;
	}
	QueryPerformanceCounter(&perf_end);
	float elapsedCbuf = (perf_end.QuadPart - perf_start.QuadPart) / freqms;
	std::cout << "C buffer with stringstream style read\n";
	std::cout << "Total duration = " << elapsedCbuf << "ms\n";
	fclose(fr);

	// C++ style
	std::ifstream f;
	const int N = sizeof(float) * 10267 * 3;
	char buff[N];
	f.rdbuf()->pubsetbuf(buff, N);
	f.open("test.bufa", std::ios::in | std::ios::binary);
	QueryPerformanceCounter(&perf_start);
	for (int i = 0; i < 10267 * 3; i++)
	{
		float temp;
		f >> temp;
		arr3[i] = temp;
	}
	QueryPerformanceCounter(&perf_end);
	float elapsedCpp = (perf_end.QuadPart - perf_start.QuadPart) / freqms;
	std::cout << "C++ style read\n";
	std::cout << "Total duration = " << elapsedCpp << "ms\n";
	f.close();
}
Exemplo n.º 5
0
//程序运行  
int CCApplication::run()  
{  
    //设置注册表PVRFrame隐藏  
    PVRFrameEnableControlWindow(false);  
    //主消息循环  
    MSG msg;  
    LARGE_INTEGER nFreq;  
    LARGE_INTEGER nLast;  
    LARGE_INTEGER nNow;  
//WINDOWS高精度定时器的用法,先获取频率  
QueryPerformanceFrequency(&nFreq);  
//获取当前的计数值,即频率x当前时间  
    QueryPerformanceCounter(&nLast);  
	//initInstance函数为虚函数,由派生类AppDelegate进行了重载。此段代码在调用AppDelegate重载的initInstance函数之后调用applicationDidFinishLaunching函数完成一些初始化处理。  
	//注:AppDelegate重载initInstance函数做了什么我们暂且只先认为它如平时我们WINDOWS基本框架程序一样创建了一个Windows窗口。【伏笔1后面会有讲解】。  
    if (! initInstance() || ! applicationDidFinishLaunching())  
    {  
        return 0;  
    }  
//取得当前使用的OPENGL窗口管理实例对象  
CCEGLView& mainWnd = CCEGLView::sharedOpenGLView();  
//将窗口居中显示  
    mainWnd.centerWindow();  
    ShowWindow(mainWnd.getHWnd(), SW_SHOW);  
//非常熟悉!进入WINDOWS消息循环  
    while (1)  
{  
   //如果没有获取到WINDOWS消息  
        if (! PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))  
        {  
            // 取得当前的计数值,即频率x当前时间  
            QueryPerformanceCounter(&nNow);  
            //m_nAnimationInterval.QuadPart的值 为setAnimationInterval函数进行设置的固定值。此处是为了判断时间流逝了多久,是否应该更新显示设备  
            if (nNow.QuadPart - nLast.QuadPart > m_nAnimationInterval.QuadPart)  
            {  
  //如果时间流逝达到了设定的FPS时间差,则更新计数值。  
                nLast.QuadPart = nNow.QuadPart;  
  //这里是设备渲染场景的函数,【伏笔2后面会有讲解】   
                CCDirector::sharedDirector()->mainLoop();  
            }  
            else  
            {  
  //sleep0秒的意义是让CPU做下时间片切换,防止死循环而使系统其它程序得不到响应。  
                Sleep(0);  
            }  
            continue;  
        }  
   //有消息获取到  
        if (WM_QUIT == msg.message)  
        {  
   // 如果获取的消息是退出则退出循环。  
            break;  
        }  
        // 如果没有定义加速键或者处理完加速键信息  
        if (! m_hAccelTable || ! TranslateAccelerator(msg.hwnd, m_hAccelTable, &msg))  
        {  
   //处理Windows消息  
            TranslateMessage(&msg);  
            DispatchMessage(&msg);  
        }  
    }  
    return (int) msg.wParam;  
}  
Exemplo n.º 6
0
PaError PaHost_OpenStream( internalPortAudioStream   *past )
{
    HRESULT          hr;
    PaError          result = paNoError;
    PaHostSoundControl *pahsc;
    int              numBytes, maxChannels;
    unsigned int     minNumBuffers;
    internalPortAudioDevice *pad;
    DSoundWrapper   *dsw;
    /* Allocate and initialize host data. */
    pahsc = (PaHostSoundControl *) PaHost_AllocateFastMemory(sizeof(PaHostSoundControl)); /* MEM */
    if( pahsc == NULL )
    {
        result = paInsufficientMemory;
        goto error;
    }
    memset( pahsc, 0, sizeof(PaHostSoundControl) );
    past->past_DeviceData = (void *) pahsc;
    pahsc->pahsc_TimerID = 0;
    dsw = &pahsc->pahsc_DSoundWrapper;
    DSW_Init( dsw );
    /* Allocate native buffer. */
    maxChannels = ( past->past_NumOutputChannels > past->past_NumInputChannels ) ?
                  past->past_NumOutputChannels : past->past_NumInputChannels;
    pahsc->pahsc_BytesPerBuffer = past->past_FramesPerUserBuffer * maxChannels * sizeof(short);
    if( maxChannels > 0 )
    {
        pahsc->pahsc_NativeBuffer = (short *) PaHost_AllocateFastMemory(pahsc->pahsc_BytesPerBuffer); /* MEM */
        if( pahsc->pahsc_NativeBuffer == NULL )
        {
            result = paInsufficientMemory;
            goto error;
        }
    }
    else
    {
        result = paInvalidChannelCount;
        goto error;
    }

    DBUG(("PaHost_OpenStream: pahsc_MinFramesPerHostBuffer = %d\n", pahsc->pahsc_MinFramesPerHostBuffer ));
    minNumBuffers = Pa_GetMinNumBuffers( past->past_FramesPerUserBuffer, past->past_SampleRate );
    past->past_NumUserBuffers = ( minNumBuffers > past->past_NumUserBuffers ) ? minNumBuffers : past->past_NumUserBuffers;
    numBytes = pahsc->pahsc_BytesPerBuffer * past->past_NumUserBuffers;
    if( numBytes < DSBSIZE_MIN )
    {
        result = paBufferTooSmall;
        goto error;
    }
    if( numBytes > DSBSIZE_MAX )
    {
        result = paBufferTooBig;
        goto error;
    }
    pahsc->pahsc_FramesPerDSBuffer = past->past_FramesPerUserBuffer * past->past_NumUserBuffers;
    {
        int msecLatency = (int) ((pahsc->pahsc_FramesPerDSBuffer * 1000) / past->past_SampleRate);
        PRINT(("PortAudio on DirectSound - Latency = %d frames, %d msec\n", pahsc->pahsc_FramesPerDSBuffer, msecLatency ));
    }
    /* ------------------ OUTPUT */
    if( (past->past_OutputDeviceID >= 0) && (past->past_NumOutputChannels > 0) )
    {
        DBUG(("PaHost_OpenStream: deviceID = 0x%x\n", past->past_OutputDeviceID));
        pad = Pa_GetInternalDevice( past->past_OutputDeviceID );
        hr = DirectSoundCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSound,   NULL );
        /* If this fails, then try each output device until we find one that works. */
        if( hr != DS_OK )
        {
            int i;
            ERR_RPT(("Creation of requested Audio Output device '%s' failed.\n",
                     ((pad->pad_lpGUID == NULL) ? "Default" : pad->pad_Info.name) ));
            for( i=0; i<Pa_CountDevices(); i++ )
            {
                pad = Pa_GetInternalDevice( i );
                if( pad->pad_Info.maxOutputChannels >= past->past_NumOutputChannels )
                {
                    DBUG(("Try device '%s' instead.\n", pad->pad_Info.name ));
                    hr = DirectSoundCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSound,   NULL );
                    if( hr == DS_OK )
                    {
                        ERR_RPT(("Using device '%s' instead.\n", pad->pad_Info.name ));
                        break;
                    }
                }
            }
        }
        if( hr != DS_OK )
        {
            ERR_RPT(("PortAudio: DirectSoundCreate() failed!\n"));
            result = paHostError;
            sPaHostError = hr;
            goto error;
        }
        hr = DSW_InitOutputBuffer( dsw,
                                   (unsigned long) (past->past_SampleRate + 0.5),
                                   past->past_NumOutputChannels, numBytes );
        DBUG(("DSW_InitOutputBuffer() returns %x\n", hr));
        if( hr != DS_OK )
        {
            result = paHostError;
            sPaHostError = hr;
            goto error;
        }
        past->past_FrameCount = pahsc->pahsc_DSoundWrapper.dsw_FramesWritten;
    }
#if SUPPORT_AUDIO_CAPTURE
    /* ------------------ INPUT */
    if( (past->past_InputDeviceID >= 0) && (past->past_NumInputChannels > 0) )
    {
        pad = Pa_GetInternalDevice( past->past_InputDeviceID );
        hr = DirectSoundCaptureCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSoundCapture,   NULL );
        /* If this fails, then try each input device until we find one that works. */
        if( hr != DS_OK )
        {
            int i;
            ERR_RPT(("Creation of requested Audio Capture device '%s' failed.\n",
                     ((pad->pad_lpGUID == NULL) ? "Default" : pad->pad_Info.name) ));
            for( i=0; i<Pa_CountDevices(); i++ )
            {
                pad = Pa_GetInternalDevice( i );
                if( pad->pad_Info.maxInputChannels >= past->past_NumInputChannels )
                {
                    PRINT(("Try device '%s' instead.\n", pad->pad_Info.name ));
                    hr = DirectSoundCaptureCreate( pad->pad_lpGUID, &dsw->dsw_pDirectSoundCapture,   NULL );
                    if( hr == DS_OK ) break;
                }
            }
        }
        if( hr != DS_OK )
        {
            ERR_RPT(("PortAudio: DirectSoundCaptureCreate() failed!\n"));
            result = paHostError;
            sPaHostError = hr;
            goto error;
        }
        hr = DSW_InitInputBuffer( dsw,
                                  (unsigned long) (past->past_SampleRate + 0.5),
                                  past->past_NumInputChannels, numBytes );
        DBUG(("DSW_InitInputBuffer() returns %x\n", hr));
        if( hr != DS_OK )
        {
            ERR_RPT(("PortAudio: DSW_InitInputBuffer() returns %x\n", hr));
            result = paHostError;
            sPaHostError = hr;
            goto error;
        }
    }
#endif /* SUPPORT_AUDIO_CAPTURE */
    /* Calculate scalar used in CPULoad calculation. */
    {
        LARGE_INTEGER frequency;
        if( QueryPerformanceFrequency( &frequency ) == 0 )
        {
            pahsc->pahsc_InverseTicksPerUserBuffer = 0.0;
        }
        else
        {
            pahsc->pahsc_InverseTicksPerUserBuffer = past->past_SampleRate /
                    ( (double)frequency.QuadPart * past->past_FramesPerUserBuffer );
            DBUG(("pahsc_InverseTicksPerUserBuffer = %g\n", pahsc->pahsc_InverseTicksPerUserBuffer ));
        }
    }
    return result;
error:
    PaHost_CloseStream( past );
    return result;
}
Exemplo n.º 7
0
//Main Program
int main() {
	try {
		std::cout<<CL_DEVICE_MAX_MEM_ALLOC_SIZE<<std::endl;
		//const unsigned int
		size_t k=4; //number of clusters to find
		size_t n=256*1000000; //1024; //number of data points (MUST BE MULTIPLE OF 256)
		size_t d=2; //dimensionality of each data point i.e. data[n][d] or n vectors of length d
		float *data=new float[n*d];
		float *centroid=new float[k*d];
		//float *dist2=new float[n*k]; //distance squared from each centroid
		int *clusterI=new int[n]; //index of closest cluster centroid for each point (i.e. which cluster does point belong to?)

		//make some random data
		//std::srand((unsigned int)std::time(0));
		std::srand(123456); //pick a fixed seed for consistency
		for (int i=0; i<n*d; i++) {
			data[i]=(float)std::rand()/(float)RAND_MAX;
			//std::cout<<"data="<<data[i]<<std::endl;
		}

		//pick initial cluster points - use first k points in the data for now - need to check Witten for what the best practice is
		for (int i=0; i<k*d; i++) {
			centroid[i]=data[i]; //this is really obtuse - both arrays laid out the same way, so only have to copy k vectors of length d
			//std::cout<<"centroid="<<centroid[i]<<std::endl;
		}

		//OpenCL part

		//query for platforms
		cl::vector<cl::Platform> platforms;
		cl::Platform::get(&platforms);

		//get a list of devices on this platform
		cl::vector<cl::Device> devices;
		platforms[0].getDevices(CL_DEVICE_TYPE_GPU,&devices);

		//create a context for the devices
		cl::Context context(devices);

		//create a command queue for the first device
		cl::CommandQueue queue = cl::CommandQueue(context,devices[0],CL_QUEUE_PROFILING_ENABLE); //PROFILING ENABLED

		//create memory buffers
		cl::Buffer bufferD=cl::Buffer(context,CL_MEM_READ_ONLY,n*d*sizeof(float)); //data buffer
		cl::Buffer bufferC=cl::Buffer(context,CL_MEM_READ_ONLY,k*d*sizeof(float)); //centroid buffer
		//cl::Buffer bufferDS=cl::Buffer(context,CL_MEM_WRITE_ONLY,n*k*sizeof(float)); //distance squared from centroids
		cl::Buffer bufferClusterI=cl::Buffer(context,CL_MEM_WRITE_ONLY,n*sizeof(int)); //index of closest cluster centroid

		//copy the input data to the input buffers using the command queue for the first device
		queue.enqueueWriteBuffer(bufferD,CL_TRUE,0,n*d*sizeof(float),data);
		queue.enqueueWriteBuffer(bufferC,CL_TRUE,0,d*k*sizeof(float),centroid);

		//read the program source
		std::ifstream sourceFile("kmeans_kernel.cl");
		std::string sourceCode(std::istreambuf_iterator<char>(sourceFile),(std::istreambuf_iterator<char>()));
		cl::Program::Sources source(1,std::make_pair(sourceCode.c_str(),sourceCode.length()+1));

		//make program from source code
		cl::Program program=cl::Program(context,source);

		//build the program for the devices
		program.build(devices);

		//make kernel
		//cl::Kernel vecadd_kernel(program,"kmeans");
		cl::Kernel vecadd_kernel(program,"kmeans2");

		//set the kernel arguments
		vecadd_kernel.setArg(0,bufferD);
		vecadd_kernel.setArg(1,bufferC);
		//vecadd_kernel.setArg(2,bufferDS); //kmeans
		vecadd_kernel.setArg(2,bufferClusterI); //kmeans2
		vecadd_kernel.setArg(3,n);
		vecadd_kernel.setArg(4,d);
		vecadd_kernel.setArg(5,k);

		//execute the kernel
		cl::NDRange global(n);
		cl::NDRange local(256);
		cl::Event timing_event; //perf
		//cl_int err_code; //perf
		queue.enqueueNDRangeKernel(vecadd_kernel,cl::NullRange,global,local,NULL,&timing_event);
		queue.finish();

		cl_ulong gpu_starttime;
		cl_ulong gpu_endtime;
		gpu_starttime = timing_event.getProfilingInfo<CL_PROFILING_COMMAND_START>();
		gpu_endtime = timing_event.getProfilingInfo<CL_PROFILING_COMMAND_END>();

		double gpu_ms = 1e-6 * (gpu_endtime-gpu_starttime); //not sure where the 1e-6 came from, but AMD used 1e-9 for seconds
		std::cout<<"GPU kmeans time="<<gpu_ms<<" milliseconds"<<std::endl;

		//copy the output data back to the host
		//queue.enqueueReadBuffer(bufferDS,CL_TRUE,0,n*k*sizeof(float),dist2); //kmeans
		queue.enqueueReadBuffer(bufferClusterI,CL_TRUE,0,n*sizeof(int),clusterI); //kmeans2

		//check the output - kmeans
		//for (int i=0; i<n; i++) { //loop through all data lines
		//	std::cout<<"dist2 i="<<i<<" : ";
		//	for (int c=0; c<k; c++) { //loop through all centroids and compare this line to each
		//		float sum=0;
		//		for (int j=0; j<d; j++) { //loop through all values on each data line (dimensionality of data points)
		//			sum+=pow(data[i*d+j]-centroid[c*d+j],2);
		//		}
		//		float gpu_value = dist2[i*k+c];
		//		float error = gpu_value-sum; //error between this data point and centroid c location
		//		std::cout<<error<<"  ";
		//	}
		//	std::cout<<std::endl;
		//}

		//Do a CPU version of kmeans to check the GPU data against
		int *cpu_clusterI=new int[n];
		LARGE_INTEGER frequency,counter1,counter2;
		QueryPerformanceFrequency(&frequency); //returns counts per second
		QueryPerformanceCounter(&counter1);
		kmeans_cpu(data,centroid,cpu_clusterI,n,d,k);
		QueryPerformanceCounter(&counter2);
		float t_ms=((float)(counter2.LowPart-counter1.LowPart))/(float)(frequency.LowPart)*1000; //milliseconds
		std::cout<<"CPU kmeans time="<<t_ms<<" milliseconds"<<std::endl;

		//check output - kmeans2
		bool result=true;
		for (int i=0; i<n; i++) { //loop through all data lines
			int gpu_index = clusterI[i]; //cluster index as calculated by the gpu
			int cpu_index = cpu_clusterI[i]; //cluster index as calculated by the cpu
			//std::cout<<"output i="<<i<<" : "<<gpu_index<<" "<<cpu_index<<std::endl;
			if (gpu_index!=cpu_index) {
				std::cout<<"Failed: "<<"output i="<<i<<" : "<<gpu_index<<" "<<cpu_index<<std::endl;
				result=false;
				break;
			}
		}
		if (result)
			std::cout<<"Success"<<std::endl;

		//and don't forget to clean up here
		delete [] data;
		delete [] centroid;
		//delete [] dist2;
		delete [] clusterI;
		delete [] cpu_clusterI;

	}
	catch (cl::Error error) {
		std::cout<<error.what()<<"("<<error.err()<<")"<<std::endl;
	}
	return 0;
}
Exemplo n.º 8
0
int main()
{
	Input input;
	IrrlichtDevice *device = createDevice(video::EDT_DIRECT3D9, dimension2d<u32>(800, 600), 16, false, true, false, &input);
	device->setWindowCaption(L"Seas of Gold");
	IVideoDriver* driver = device->getVideoDriver();
	ISceneManager* smgr = device->getSceneManager();
	IGUIEnvironment* guienv = device->getGUIEnvironment();
	E_DRIVER_TYPE driverType = driverChoiceConsole();
	EffectHandler *effect = new EffectHandler(device, driver->getScreenSize(), false, true);
	E_FILTER_TYPE filterType = (E_FILTER_TYPE)core::clamp<u32>((u32)3 - '1', 0, 4);

	int skyR = 30, skyG = 30, skyB = 70;
	int timer = 0;
	SColor sky = SColor(255, skyR, skyG, skyB);
	float plPos_x = 0.0f, plPos_y = 0.0f, plPos_z = 0.0f;
	bool updateCam = true;
	bool menu1 = false;
	int state = Main;
	LoadMap loadMap;
	Player player;
	Interface playerInterface(driver);
	ITriangleSelector* selector = 0;
	ISceneNodeAnimator* anim = 0;

	// Load the map scene
	//loadMap.Load(smgr, device, Map_Africa);
	//loadMap.Load(smgr, device, Map_India);
	//loadMap.Load(smgr, device, selector, plyrNode, anim, Map_England);

	IAnimatedMeshSceneNode* plyrNode = player.loadPlayerNode(device, smgr);
	//plyrNode->setDebugDataVisible((scene::E_DEBUG_SCENE_TYPE)(plyrNode->isDebugDataVisible() ^ scene::EDS_BBOX));

	ICameraSceneNode* camera = smgr->addCameraSceneNode(0, plyrNode->getPosition() + vector3df(0, 2, 2), vector3df(0, 0, 100));

	loadMap.Load(smgr, device, selector, plyrNode, anim, Map_England);

	//loadMap.setCollisions(smgr, selector, plyrNode, anim);

	if (loadMap.CollNode)
	{
		selector = smgr->createOctreeTriangleSelector(loadMap.CollNode->getMesh(), loadMap.CollNode, 32);
		for (int i = 0; i < loadMap.CollNode->getMaterialCount(); i++)
		{
			loadMap.CollNode->getMaterial(i).NormalizeNormals = true;
		}
		loadMap.CollNode->setTriangleSelector(selector);
	}

	if (selector)
	{
		anim = smgr->createCollisionResponseAnimator(selector, plyrNode, vector3df(0.6f, 0.75f, 0.4f), core::vector3df(0.0f, -0.05f, 0.0f),
			core::vector3df(0.0f, -0.725f, 0.0f));
		plyrNode->addAnimator(anim);
	}

	ISceneCollisionManager* collMan = smgr->getSceneCollisionManager();

	////////////// The Sun ////////////
	ILightSceneNode *sun_node;
	SLight sun_data;
	ISceneNode *sun_billboard;
	float sun_angle = 0;
	video::SColorf Diffuse_Night = video::SColorf(0.0f, 0.0f, 0.0f, 1.0f);
	video::SColorf Diffuse_Day = video::SColorf(1.0f, 1.0f, 1.0f, 1.0f);

	sun_node = smgr->addLightSceneNode();
	sun_data.Direction = vector3df(0, 0, 0);
	sun_data.Type = video::ELT_DIRECTIONAL;
	sun_data.AmbientColor = video::SColorf(0.1f, 0.1f, 0.1f, 1);
	sun_data.SpecularColor = video::SColorf(0, 0, 0, 0);
	sun_data.DiffuseColor = Diffuse_Day;
	sun_data.CastShadows = true;
	sun_node->setLightData(sun_data);
	sun_node->setPosition(vector3df(0, 0, 0));
	sun_node->setRotation(vector3df(0, 0, 0));

	sun_billboard = smgr->addBillboardSceneNode(sun_node, core::dimension2d<f32>(60, 60));
	if (sun_billboard)
	{
		sun_billboard->setPosition(vector3df(0, 0, -100));
		sun_billboard->setMaterialFlag(video::EMF_LIGHTING, false);
		sun_billboard->setMaterialFlag(video::EMF_ZWRITE_ENABLE, false);
		sun_billboard->setMaterialType(video::EMT_TRANSPARENT_ADD_COLOR);
		sun_billboard->setMaterialTexture(0, driver->getTexture("Assets/particlewhite.bmp"));
	}
	/////////// End ////////////

	//------- candleLight -----//
	ILightSceneNode *candleLight = smgr->addLightSceneNode();
	SLight candleLight_data;

	candleLight_data.Type = video::ELT_POINT;
	candleLight_data.DiffuseColor = SColorf(1.0f, 0.546f, 0.016f, 1.0f);
	candleLight_data.SpecularColor = video::SColorf(0, 0, 0, 0);
	candleLight->setPosition(vector3df(2.43467f, 1.55795f, -3.94657));
	candleLight_data.Radius = 1.5f;
	candleLight->setLightData(candleLight_data);
	//------- end -----//

	// Make the player
	player.AddGold(1000);
	player.SetCurrentPort(eMapDest::South);
	Item* itemCi = new Item("Iron Ore", 1);
	player.getItems()->addItem(itemCi);
	Item* itemCb = new Item("Bronze Ore", 1);
	player.getItems()->addItem(itemCb);

	Vendor vN;
	Item* itemG = new Item("Gold Ore", 1000);
	vN.getItems()->addItem(itemG);
	Vendor vS;
	Item* itemI = new Item("Iron Ore", 1000);
	vS.getItems()->addItem(itemI);
	Vendor vE;
	Item* itemB = new Item("Bronze Ore", 1000);
	vE.getItems()->addItem(itemB);

	// Make the menus
	MainMenu mainMenu(device);

	MapMenu mapMenu(device, driver);
	mapMenu.SetPlayer(&player);

	TradeMenu tradeMenu(device, driver);
	tradeMenu.SetPlayer(&player);
	tradeMenu.SetVendor(&vS);

	CraftingMenu craftMenu(device, driver);
	craftMenu.SetPlayer(&player);

	//////////////////////////////////////////////////////////////////////////
	// Initialize timer to compute elapsed time between frames
	//////////////////////////////////////////////////////////////////////////
	__int64 cntsPerSec = 0;
	QueryPerformanceFrequency((LARGE_INTEGER*)&cntsPerSec);
	float secsPerCnt = 1.0f / (float)cntsPerSec;

	__int64 prevTimeStamp = 0;
	QueryPerformanceCounter((LARGE_INTEGER*)&prevTimeStamp);

	while (device->run())
	{
		//for scaling animation by time, not by frame
		__int64 currTimeStamp = 0;
		QueryPerformanceCounter((LARGE_INTEGER*)&currTimeStamp);
		float dt = (currTimeStamp - prevTimeStamp) * secsPerCnt;

		sun_node->setRotation(vector3df(sun_angle, 0.0f, 0.0f));
		sun_angle += dt;
		if ((sun_angle > 0 && sun_angle < 109) || (sun_angle>350))
		{
			timer++;
			if (timer > 10)
			{
				if (skyR < 100) skyR += 1;
				if (skyG < 100) skyG += 1;
				if (skyB < 140) skyB += 1;
				timer = 0;
			}
		}
		if (sun_angle > 170 && sun_angle < 330)
		{
			timer++;
			if (timer > 10)
			{
				if (skyR > 0) skyR -= 1;
				if (skyG > 0) skyG -= 1;
				if (skyB > 40) skyB -= 1;
				timer = 0;
			}
		}

		player.updatePlayer(plyrNode, dt, collMan, selector);
		playerInterface.update(plyrNode, loadMap, driver, device, input, updateCam, state);

		int test = state;
		int test2 = 0;

		switch (state)
		{
		case Map:
		{
			int out = mapMenu.Update(&input);

			switch (out)
			{
			case eMapDest::Exit:
			{
				state = None;
				break;
			}
			case eMapDest::East:
			{
				state = None;
				Item* itemB = new Item("Bronze Ore", 1000);
				vE.getItems()->addItem(itemB);
				tradeMenu.SetVendor(&vE);
				loadMap.Load(smgr, device, selector, plyrNode, anim, Map_India);
				if (loadMap.CollNode)
				{
					selector = smgr->createOctreeTriangleSelector(loadMap.CollNode->getMesh(), loadMap.CollNode, 32);

					for (int i = 0; i < loadMap.CollNode->getMaterialCount(); i++)
					{
						loadMap.CollNode->getMaterial(i).NormalizeNormals = true;
					}
					loadMap.CollNode->setTriangleSelector(selector);
				}

				if (selector)
				{
					anim = smgr->createCollisionResponseAnimator(selector, plyrNode, vector3df(0.6f, 0.75f, 0.4f), core::vector3df(0.0f, -0.05f, 0.0f),
						core::vector3df(0.0f, -0.725f, 0.0f));
					plyrNode->addAnimator(anim);
				}
				collMan = smgr->getSceneCollisionManager();
				break;
			}
			case eMapDest::North:
			{
				state = None;
				Item *itemG = new Item("Gold Ore", 1000);
				vN.getItems()->addItem(itemG);
				tradeMenu.SetVendor(&vN);
				loadMap.Load(smgr, device, selector, plyrNode, anim, Map_England);
				if (loadMap.CollNode)
				{
					selector = smgr->createOctreeTriangleSelector(loadMap.CollNode->getMesh(), loadMap.CollNode, 32);

					for (int i = 0; i < loadMap.CollNode->getMaterialCount(); i++)
					{
						loadMap.CollNode->getMaterial(i).NormalizeNormals = true;
					}
					loadMap.CollNode->setTriangleSelector(selector);
				}

				if (selector)
				{
					anim = smgr->createCollisionResponseAnimator(selector, plyrNode, vector3df(0.6f, 0.75f, 0.4f), core::vector3df(0.0f, -0.05f, 0.0f),
						core::vector3df(0.0f, -0.725f, 0.0f));
					plyrNode->addAnimator(anim);
				}
				collMan = smgr->getSceneCollisionManager();
				break;
			}
			case eMapDest::South:
			{
				state = None;
				Item *itemI = new Item("Iron Ore", 1000);
				vS.getItems()->addItem(itemI);
				tradeMenu.SetVendor(&vS);
				loadMap.Load(smgr, device, selector, plyrNode, anim, Map_Africa);
				if (loadMap.CollNode)
				{
					selector = smgr->createOctreeTriangleSelector(loadMap.CollNode->getMesh(), loadMap.CollNode, 32);

					for (int i = 0; i < loadMap.CollNode->getMaterialCount(); i++)
					{
						loadMap.CollNode->getMaterial(i).NormalizeNormals = true;
					}
					loadMap.CollNode->setTriangleSelector(selector);
				}

				if (selector)
				{
					anim = smgr->createCollisionResponseAnimator(selector, plyrNode, vector3df(0.6f, 0.75f, 0.4f), core::vector3df(0.0f, -0.05f, 0.0f),
						core::vector3df(0.0f, -0.725f, 0.0f));
					plyrNode->addAnimator(anim);
				}
				collMan = smgr->getSceneCollisionManager();
				break;
			}
			default:
				break;
			}

			break;
		}
		case Trade:
		{
			bool out = tradeMenu.Update(&input);
			if (out)
				state = None;
			break;
		}
		case Main:
		{
			int out = mainMenu.Update(&input);

			switch (out)
			{
			case MSstart:
			{
				state = None;
				break;
			}
			case MSexit:
			{
				device->closeDevice();
				break;
			}
			default:
				break;
			}

			break;
		}
		case Craft:
		{
			bool out = craftMenu.Update(&input);
			if (out)
				state = None;
			break;
		}
		default:
			// Do nothing
			break;
		}

		if (updateCam) moveCameraControl(plyrNode, device, camera);

		////////////////////////////////////////////////////////

		if (sun_angle > 360) sun_angle = 0;
		if (sun_angle < 180) sun_data.DiffuseColor = Diffuse_Day; else sun_data.DiffuseColor = Diffuse_Night;
		sun_node->setLightData(sun_data);

		sky.setRed(skyR);
		sky.setGreen(skyG);
		sky.setBlue(skyB);
		driver->beginScene(true, true, sky);

		smgr->drawAll();

		playerInterface.render(driver, state);

		// Draw the menu
		switch (state)
		{
		case Map:
		{
			mapMenu.Draw(driver);
			break;
		}
		case Trade:
		{
			tradeMenu.Draw(driver);
			break;
		}
		case Main:
		{
			mainMenu.Draw(driver);
			break;
		}
		case Craft:
		{
			craftMenu.Draw(driver);
			break;
		}
		default:
			// Do nothing
			break;
		}

		driver->endScene();
		
		// Update the prev time stamp to current
		prevTimeStamp = currTimeStamp;

	}

	//device->drop();

	return 0;
}
Exemplo n.º 9
0
int __cdecl main(int argc,char *argv[])
{
	int i,arg, currit, modes, modenr;
	paramT *p;

#ifdef SHAREDMEM
	int shmid;
#endif

#ifdef WIN32
	DWORD procID;
	HANDLE hProcess;
	HANDLE hThread[10];
	DWORD IDThread;
	LARGE_INTEGER lpFrequency;
#endif

	p = (paramT*) malloc(MXPROC*sizeof(paramT));

	/* default initialisation */
	modes=0;
	p[0].mode=0;
	p[0].npes=NPES;
	p[0].mxsize=MXRUNSZ;
	p[0].minsize=MINRUNSZ;
	p[0].mxstrds=MXSTRDS;
	p[0].mxiters=MXIT;
	p[0].currentrep=1;
#ifdef HAVEOPT
	p[0].useoptasm=OPTASM;
#else
	p[0].useoptasm=0;
#endif
	arg=1;
	chartrev=CHARTREV;
	printf("\nECT memperf - Extended Copy Transfer Characterization\n");
	printf("Memory Performance Characterization Toolkit %s\n\n",VERSION);

#ifdef WIN32
	/* lookup clock frequency */
	QueryPerformanceFrequency(&lpFrequency);
	tic = (lpFrequency.LowPart / 1000000.0);
	tic += (lpFrequency.HighPart * (2^32) / 1000000.0);
#else
	tic=getcpufrequency();
#endif

	if (argc<2) {
#ifdef WIN32
		printf("Usage: %s -m <mode> [-p] [-s] [-n] [-r] [-i] [-c] [-o]\n",argv[0]);
#elif defined HAVEOPT
		printf("Usage: %s -m <mode> [-p] [-s] [-n] [-r] [-i] [-t] [-c] [-a] [-o]\n",argv[0]);
#else
		printf("Usage: %s -m <mode> [-p] [-s] [-n] [-r] [-i] [-t] [-c] [-o]\n",argv[0]);
#endif /*WIN32*/
		printf("       -m <mode>    :   0 = load sum test\n");
		printf("                        1 = const store test\n");
		printf("                        2 = load copy test\n");
		printf("                        3 = copy store test\n");
		printf("                        9 = all tests\n");
		printf("       [-c <nofrep> ]   Default: %d\n", NROFREP);
#ifdef HAVEOPT
		printf("       [-a <optasm> ]   0/1 = use/don't use special instructions\n");
		printf("                        2 = both methods, Default: %d\n", OPTASM);
#endif
		printf("       [-p <nProc>  ]   Default: %d\n",NPES);
		printf("       [-s <mxstrds>]   Default: %d\n",MXSTRDS);
		printf("       [-n <mxsize> ]   Default: %d (%d Bytes)\n",MXRUNSZ,8<<MXRUNSZ);
		printf("       [-r <minsize>]   Default: %d (%d Bytes)\n",MINRUNSZ,8<<MINRUNSZ);
		printf("       [-i <mxiters>]   Default: %d\n",MXIT);
		printf("       [-o          ]   Reversed Output\n");
#ifdef WIN32
		printf("       Evaluated clock resolution [MHz]: %.2f\n",tic);
#else
		printf("       [-t <tics/us>]   Default: %.2f\n",tic);
#endif
		exit(2);
	}

	while (arg<argc) {
		if (argv[arg][0]=='-') {
			if (argv[arg][1]=='p' && (arg+1)<argc) {
				arg++; p[0].npes=atoi(argv[arg]);
			}
			if (argv[arg][1]=='s' && (arg+1)<argc) {
				arg++; p[0].mxstrds=atoi(argv[arg]);
			}
			if (argv[arg][1]=='m' && (arg+1)<argc) {
				arg++; modes=atoi(argv[arg]);
			}
			if (argv[arg][1]=='n' && (arg+1)<argc) {
				arg++; p[0].mxsize=atoi(argv[arg]);
			}
			if (argv[arg][1]=='r' && (arg+1)<argc) {
				arg++; p[0].minsize=atoi(argv[arg]);
			}
			if (argv[arg][1]=='i' && (arg+1)<argc) {
				arg++; p[0].mxiters=atoi(argv[arg]);
			}
			if (argv[arg][1]=='o') {
				chartrev=1;
			}
			if (argv[arg][1]=='a' && (arg+1)<argc) {
				arg++;
#ifdef HAVEOPT
				p[0].useoptasm=atoi(argv[arg]);
#endif
			}
			if (argv[arg][1]=='c' && (arg+1)<argc) {
				arg++; nrofrep=atoi(argv[arg]);
			}
			if (argv[arg][1]=='t' && (arg+1)<argc) {
				arg++;
#ifndef WIN32
				tic=atof(argv[arg]);
#endif
			}
		}
		arg++;
	}

	p[0].mxsize=1<<p[0].mxsize;
	p[0].minsize=1<<p[0].minsize;

	/* set high process priority */
#ifdef WIN32
	procID = GetCurrentProcessId ();
	hProcess = OpenProcess(PROCESS_ALL_ACCESS,TRUE,procID);
	SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS);
#else /* unix */
	setpriority(PRIO_PROCESS, 0,-20);    /* linux has no bind_to_cpu call */
#endif


#ifdef WIN32
	printf(  "Evaluated Clock Resolution: %.2f MHz\n\n",tic);
#else
	printf(  "Specified/Evaluated Clock Resolution (Option -t): %.2f MHz\n\n",tic);
#endif

	/* allocate shared memory (only once for all repetitions/modes */
#ifdef SHAREDMEM
	printf("Allocation of Shared Memory!\n");
	if ((shmid=shmget(IPC_PRIVATE,sizeof(double)*p[0].mxsize,IPC_CREAT | 0666))
		==-1) {perror("shmget");exit(99);}
	if ((shared = (double *) shmat(shmid,0,SHM_RND))==(double *) -1) {
		perror("shmat\n"); exit(99);
	}
#endif /* SHAREDMEM */

	for (modenr=0;modenr<=3;modenr++) {
		if ((modenr==modes) || (modes==9)) {
			p[0].mode=modenr;

			for (currit=1;currit<=nrofrep;currit++) {
				p[0].currentrep=currit;
				for (i=1;i<MXPROC;i++) {
					memcpy (&p[i],&p[0], sizeof(paramT));
				}

				switch (p[0].mode) {
				case 0:
					printf("Load Sum (%d)    - Working Set: %.0f KByte; Strides: %d\n",currit, (float) p[0].mxsize*8/1024,p[0].mxstrds);
					break;
				case 1:
					printf("Const Store (%d) - Working Set: %.0f KByte; Strides: %d\n",currit, (float) p[0].mxsize*8/1024,p[0].mxstrds);
					break;
				case 2:
					printf("Load Copy (%d)   - Working Set: 2*%.0f KByte; Strides: %d\n",currit, (float) p[0].mxsize*8/1024,p[0].mxstrds);
					break;
				case 3:
					printf("Copy Store (%d)  - Working Set: 2*%.0f KByte; Strides: %d\n",currit, (float) p[0].mxsize*8/1024,p[0].mxstrds);
					break;
				}
				if (p[0].npes==1)
					printf("                  Starting 1 process...\n                  Test running...\n");
				else
					printf("                  Starting %d processes...\n                  Tests running...\n", p[0].npes );

	/* start parallel execution */
#ifdef WIN32
				for (i=0;i<p[0].npes;i++) {

					p[i].par_cid=i;
				/*printf("Proc: %d, parcid: %d\n",i,p[i].par_cid);
				printf("Address %d\n",&p[i]);
				fflush(stdout);
				*/
					hThread[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)memop,&p[i],0,&IDThread);

					if (hThread[i]==NULL) {
						fprintf(stderr, "Create Thread error\n");
						exit(0);
					}
				}

			/* wait for termination of child-threads */
				WaitForMultipleObjects (p[0].npes, hThread, TRUE, INFINITE);

#else  /* unix */

			/* init semaphores for barrier */
				sem_init();

				begin_parallel(p[0].npes);
				p[par_cid].par_cid=par_cid;

   /*
			printf("Proc: %d, parcid: %d\n",par_cid,p[par_cid].par_cid);
			printf("Address %d\n",&p[par_cid]);
			*/

				memop(&p[par_cid]);
				barrier();
				end_parallel();

				sem_deinit();

#endif /* WIN32 */
			}
		 analyze_rep(&p[0]);
		}
	}

	/* detach & destroy shared memory */
#ifdef SHAREDMEM
	if ((shmdt(shared))==-1) {
		perror("shmdt\n"); exit(99);
	}
	if ((shmctl(shmid,IPC_RMID,0))==-1) {
		perror("ShmRelease"); exit(99);
	}
#endif /* SHAREDMEM */

	free(p);
	return 0;
}
Exemplo n.º 10
0
// utilities
double claw_get_seconds (void) {
	LARGE_INTEGER count, frequency;
	QueryPerformanceFrequency (&frequency);
	QueryPerformanceCounter (&count);
	return (double)count.QuadPart/frequency.QuadPart;
}
Exemplo n.º 11
0
RakNetTimeNS RakNet::GetTimeNS( void )
{
#if defined(_PS3)
	uint64_t curTime;
	if ( initialized == false)
	{
		ticksPerSecond = _PS3_GetTicksPerSecond();
		// Use the function to get elapsed ticks, this is a macro.
		_PS3_GetElapsedTicks(curTime);
		uint64_t quotient, remainder;
		quotient=(curTime / ticksPerSecond);
		remainder=(curTime % ticksPerSecond);
		initialTime = (RakNetTimeNS) quotient*(RakNetTimeNS)1000000 + (remainder*(RakNetTimeNS)1000000 / ticksPerSecond);
		initialized = true;
	}
#elif defined(_WIN32)
	// Win32
	if ( initialized == false)
	{
		initialized = true;

#if !defined(_WIN32_WCE)
		// Save the current process
		HANDLE mProc = GetCurrentProcess();

		// Get the current Affinity
#if _MSC_VER >= 1400 && defined (_M_X64)
		GetProcessAffinityMask(mProc, (PDWORD_PTR)&mProcMask, (PDWORD_PTR)&mSysMask);
#else
		GetProcessAffinityMask(mProc, &mProcMask, &mSysMask);
#endif

		mThread = GetCurrentThread();

#endif // !defined(_WIN32_WCE)

		QueryPerformanceFrequency( &yo );
	}
	// 01/12/08 - According to the docs "The frequency cannot change while the system is running." so this shouldn't be necessary
	/*
	if (++queryCount==200)
	{
		// Set affinity to the first core
		SetThreadAffinityMask(mThread, 1);

		QueryPerformanceFrequency( &yo );

		// Reset affinity
		SetThreadAffinityMask(mThread, mProcMask);

		queryCount=0;
	}
	*/

#elif (defined(__GNUC__)  || defined(__GCCXML__))
	if ( initialized == false)
	{
		gettimeofday( &tp, 0 );
		initialized=true;
		// I do this because otherwise RakNetTime in milliseconds won't work as it will underflow when dividing by 1000 to do the conversion
		initialTime = ( tp.tv_sec ) * (RakNetTimeNS) 1000000 + ( tp.tv_usec );
	}
#endif

#if defined(_PS3)
	// Use the function to get elapsed ticks, this is a macro.
	_PS3_GetElapsedTicks(curTime);
	uint64_t quotient, remainder;
	quotient=(curTime / ticksPerSecond);
	remainder=(curTime % ticksPerSecond);
	curTime = (RakNetTimeNS) quotient*(RakNetTimeNS)1000000 + (remainder*(RakNetTimeNS)1000000 / ticksPerSecond);
	// Subtract from initialTime so the millisecond conversion does not underflow
	return curTime - initialTime;
#elif defined(_WIN32)

	RakNetTimeNS curTime;
	static RakNetTimeNS lastQueryVal=(RakNetTimeNS)0;
//	static unsigned long lastTickCountVal = GetTickCount();

	LARGE_INTEGER PerfVal;

#if !defined(_WIN32_WCE)
	// Set affinity to the first core
	SetThreadAffinityMask(mThread, 1);
#endif // !defined(_WIN32_WCE)

	// Docs: On a multiprocessor computer, it should not matter which processor is called.
	// However, you can get different results on different processors due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer (HAL). To specify processor affinity for a thread, use the SetThreadAffinityMask function.
	// Query the timer
	QueryPerformanceCounter( &PerfVal );

#if !defined(_WIN32_WCE)
	// Reset affinity
	SetThreadAffinityMask(mThread, mProcMask);
#endif // !defined(_WIN32_WCE)

	__int64 quotient, remainder;
	quotient=((PerfVal.QuadPart) / yo.QuadPart);
	remainder=((PerfVal.QuadPart) % yo.QuadPart);
	curTime = (RakNetTimeNS) quotient*(RakNetTimeNS)1000000 + (remainder*(RakNetTimeNS)1000000 / yo.QuadPart);

	// 08/26/08 - With the below workaround, the time seems to jump forward regardless.
	// Just make sure the time doesn't go backwards
	if (curTime < lastQueryVal)
		return lastQueryVal;
	lastQueryVal=curTime;

	/*
#if !defined(_WIN32_WCE)
	if (lastQueryVal==0)
	{
		// First call
		lastQueryVal=curTime;
		return curTime;
	}

	// To workaround http://support.microsoft.com/kb/274323 where the timer can sometimes jump forward by hours or days
	unsigned long curTickCount = GetTickCount();
	unsigned long elapsedTickCount = curTickCount - lastTickCountVal;
	RakNetTimeNS elapsedQueryVal = curTime - lastQueryVal;
	if (elapsedQueryVal/1000 > elapsedTickCount+100)
	{
		curTime=(RakNetTimeNS)lastQueryVal+(RakNetTimeNS)elapsedTickCount*(RakNetTimeNS)1000;
	}

	lastTickCountVal=curTickCount;
	lastQueryVal=curTime;
#endif
	*/

	return curTime;

#elif (defined(__GNUC__)  || defined(__GCCXML__))
	// GCC
	RakNetTimeNS curTime;
	gettimeofday( &tp, 0 );

	curTime = ( tp.tv_sec ) * (RakNetTimeNS) 1000000 + ( tp.tv_usec );
	// Subtract from initialTime so the millisecond conversion does not underflow
	return curTime - initialTime;
#endif
}
 CStopwatch() { QueryPerformanceFrequency(&m_liPerfFreq); Start(); }
Exemplo n.º 13
0
CmcDateTime CmcDateTime::GetTimeNow ()
  {
static bool bFirstTime = true;

static CmcDateTime last_date;
static LARGE_INTEGER last_time;
static LONGLONG iCounterFrequency = 0;

  if (bFirstTime)
    {
    bFirstTime = false;
    LARGE_INTEGER large_int_frequency;
    if (QueryPerformanceFrequency (&large_int_frequency))
      {
      iCounterFrequency = large_int_frequency.QuadPart;
      QueryPerformanceCounter (&last_time);
      }
    }

  double secs = 0;
  LARGE_INTEGER time_now;

  if (iCounterFrequency)
    {
    QueryPerformanceCounter (&time_now);

    LONGLONG offset = time_now.QuadPart - last_time.QuadPart;
    secs = (double) offset / (double) iCounterFrequency;
//    TRACE ("Secs = %10.4f\n", secs);
    }
  else
    {
    time_now.QuadPart = 0;
    time_now.QuadPart = 0;
    }


  // if no high-performance counter, just query the time each time
  if (iCounterFrequency == 0 || 
      last_date.m_dt == 0 ||
      secs > RESYNC_EVERY_SECS)
    {
    SYSTEMTIME systime;
    GetLocalTime (&systime);
 	  last_date = CmcDateTime(systime.wYear, systime.wMonth,
		                  systime.wDay, systime.wHour, systime.wMinute,
		                  (double) systime.wSecond + ( (double) systime.wMilliseconds / 1000.0) );
    secs = 0;
    last_time = time_now;
    }

  CmcDateTime this_date (last_date);

  this_date.m_dt += secs / SECS_IN_DAY;

  // ---- debugging
#if 0
    {
    SYSTEMTIME systime;
    GetSystemTime (&systime);
 	  CmcDateTime test = CmcDateTime(systime.wYear, systime.wMonth,
		                  systime.wDay, systime.wHour, systime.wMinute,
		                  (double) systime.wSecond + ( (double) systime.wMilliseconds / 1000.0) );
    double diff = test.m_dt - this_date.m_dt;

    TRACE1 ("Time difference = %10.8f\n", diff);
    }

#endif
  // --- end debugging

  return this_date; 

  }
Exemplo n.º 14
0
		PerformanceFreqHolder()
		{
			LARGE_INTEGER freq;
			QueryPerformanceFrequency(&freq);
			value = freq.QuadPart;
		}
Exemplo n.º 15
0
int gettimeofday(struct timeval* tp, int* /*tz*/) {
  static LARGE_INTEGER tickFrequency, epochOffset;

  static Boolean isInitialized = False;

  LARGE_INTEGER tickNow;

#if !defined(_WIN32_WCE)
  QueryPerformanceCounter(&tickNow);
#else
  tickNow.QuadPart = GetTickCount();
#endif
 
  if (!isInitialized) {
    if(1 == InterlockedIncrement(&initializeLock_gettimeofday)) {
#if !defined(_WIN32_WCE)
      // For our first call, use "ftime()", so that we get a time with a proper epoch.
      // For subsequent calls, use "QueryPerformanceCount()", because it's more fine-grain.
      struct timeb tb;
      ftime(&tb);
      tp->tv_sec = tb.time;
      tp->tv_usec = 1000*tb.millitm;

      // Also get our counter frequency:
      QueryPerformanceFrequency(&tickFrequency);
#else
      /* FILETIME of Jan 1 1970 00:00:00. */
      const LONGLONG epoch = 116444736000000000LL;
      FILETIME fileTime;
      LARGE_INTEGER time;
      GetSystemTimeAsFileTime(&fileTime);

      time.HighPart = fileTime.dwHighDateTime;
      time.LowPart = fileTime.dwLowDateTime;

      // convert to from 100ns time to unix timestamp in seconds, 1000*1000*10
      tp->tv_sec = (long)((time.QuadPart - epoch) / 10000000L);

      /*
        GetSystemTimeAsFileTime has just a seconds resolution,
        thats why wince-version of gettimeofday is not 100% accurate, usec accuracy would be calculated like this:
        // convert 100 nanoseconds to usec
        tp->tv_usec= (long)((time.QuadPart - epoch)%10000000L) / 10L;
      */
      tp->tv_usec = 0;

      // resolution of GetTickCounter() is always milliseconds
      tickFrequency.QuadPart = 1000;
#endif     
      // compute an offset to add to subsequent counter times, so we get a proper epoch:
      epochOffset.QuadPart
          = tp->tv_sec * tickFrequency.QuadPart + (tp->tv_usec * tickFrequency.QuadPart) / 1000000L - tickNow.QuadPart;
      
      // next caller can use ticks for time calculation
      isInitialized = True; 
      return 0;
    } else {
        InterlockedDecrement(&initializeLock_gettimeofday);
        // wait until first caller has initialized static values
        while(!isInitialized){
          Sleep(1);
        }
    }
  }

  // adjust our tick count so that we get a proper epoch:
  tickNow.QuadPart += epochOffset.QuadPart;

  tp->tv_sec =  (long)(tickNow.QuadPart / tickFrequency.QuadPart);
  tp->tv_usec = (long)(((tickNow.QuadPart % tickFrequency.QuadPart) * 1000000L) / tickFrequency.QuadPart);

  return 0;
}
Exemplo n.º 16
0
		//-----------------------------------------
		//-----------------------------------------
		PlatformSystem::PlatformSystem() 
		{
			QueryPerformanceFrequency(&g_frequency);
		}
Exemplo n.º 17
0
Clock::Clock(bool autoStart)
{
	QueryPerformanceFrequency(&clockSpeed);
	if ( autoStart )Start();
}
Exemplo n.º 18
0
double getHighPerformanceFrequency()
{
	LARGE_INTEGER counter;
	QueryPerformanceFrequency( &counter );
	return static_cast< double >( counter.QuadPart );
}
Exemplo n.º 19
0
//
// Init GL
//
int InitGL(GLvoid)										// All Setup For OpenGL Goes Here
{
	// seed rand generator
	srand(getclock());

#if 0
	QueryPerformanceFrequency(&timerFrequency);
	QueryPerformanceCounter(&lastTime);
#endif

	// use the mouse only
	// for camera movement
	// disable the cursor 
	ShowCursor(FALSE);

	Super_LoadGlobals();

	Load_ConfigFile();

	// Now load main variables
	Super_LoadBots();	
	Super_FireAnts();
	
	Create_Col_List();

	Create_Wall_List();

	// enable all the goodies
	//glEnable(GL_TEXTURE_2D);		   // enable texture mapping
	
	glShadeModel(GL_SMOOTH);							// Enable Smooth Shading
	glClearColor(0.0f, 0.0f, 0.0f, 0.5f);				// Black Background
	glClearDepth(1.0f);									// Depth Buffer Setup


	glEnable(GL_NORMALIZE);
	glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

	glShadeModel(GL_SMOOTH);


	glEnable(GL_DEPTH_TEST);							// Enables Depth Testing
	glDepthFunc(GL_LEQUAL);								// The Type Of Depth Testing To Do
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations


	// have to load the quadrice to be used
	quadric=gluNewQuadric();							// Create A Pointer To The Quadric Object (Return 0 If No Memory) (NEW)
	gluQuadricNormals(quadric, GLU_SMOOTH);			// Create Smooth Normals (NEW)
	gluQuadricTexture(quadric, GL_TRUE);				// Create Texture Coords (NEW)


#if ENABLE_LIGHTS
//	InitMaterial();
#endif


	GenerateBots();

	GenerateFireAnts();			// a new breed of warrior

	CreateWorld();

	LoadCameras();

	BuildFont();										// Build The Font

	// Load the objects
	InitObjects();

	GenerateLights();

	InitGlobals();		// for printing data, etc

	// generate the nest objects
	nest.generate();
	garden.generate();

	trail_set.generate();

	// give the ant food
	InitFood();

	Build_ParticleSet();

	Reset_FontID();


	// load the title screen text
	Load_Titles();

	// the text library
	Super_MainText();

	CreateWalls();

	//
	// Load the collision test for the wall
	// very easy test
	// 4 different walls
	//

	// front wall
	InsertColSegment(world_ptr->x_min, world_ptr->y_max, 
		world_ptr->x_max, world_ptr->y_max);

	// right wall
	InsertColSegment(world_ptr->x_max, world_ptr->y_min, 
		world_ptr->x_max, world_ptr->y_max);

	// back wall (top)
	InsertColSegment(world_ptr->x_min, world_ptr->y_min, 
		world_ptr->x_max, world_ptr->y_min);

	// left wall 
	InsertColSegment(world_ptr->x_min, world_ptr->y_min, 
		world_ptr->x_min, world_ptr->y_max);

	// end insertion --


	//
	// The first thing to do is begin in paused mode
	//
	Super_BeginPaused();



	mSuper_Loaded  = LOADED_TRUE;

	return TRUE;			// Initialization Went OK

} // end of the function
Exemplo n.º 20
0
float actual_main(int argc, TCHAR* argv[], int DIMENSION){
    cl_int err;
    ocl_args_d_t ocl;
    cl_device_type deviceType = CL_DEVICE_TYPE_GPU;

    LARGE_INTEGER perfFrequency;
    LARGE_INTEGER performanceCountNDRangeStart;
    LARGE_INTEGER performanceCountNDRangeStop;

	
    cl_uint arrayWidth  = DIMENSION;
    cl_uint arrayHeight = DIMENSION;

    //initialize Open CL objects (context, queue, etc.)
    if (CL_SUCCESS != SetupOpenCL(&ocl, deviceType))
    {
        return -1;
    }

    // allocate working buffers. 
    // the buffer should be aligned with 4K page and size should fit 64-byte cached line
    cl_uint optimizedSize = ((sizeof(cl_int) * arrayWidth * arrayHeight - 1)/64 + 1) * 64;
    cl_int* inputA  = (cl_int*)_aligned_malloc(optimizedSize, 4096);
    cl_int* inputB  = (cl_int*)_aligned_malloc(optimizedSize, 4096);
    cl_int* outputC = (cl_int*)_aligned_malloc(optimizedSize, 4096);
    if (NULL == inputA || NULL == inputB || NULL == outputC)
    {
        LogError("Error: _aligned_malloc failed to allocate buffers.\n");
        return -1;
    }

    //random input
    generateInput(inputA, arrayWidth, arrayHeight);
    generateInput(inputB, arrayWidth, arrayHeight);

    // Create OpenCL buffers from host memory
    // These buffers will be used later by the OpenCL kernel
    if (CL_SUCCESS != CreateBufferArguments(&ocl, inputA, inputB, outputC, arrayWidth, arrayHeight))
    {
        return -1;
    }

     // Create and build the OpenCL program
    if (CL_SUCCESS != CreateAndBuildProgram(&ocl))
    {
        return -1;
    }

    // Program consists of kernels.
    // Each kernel can be called (enqueued) from the host part of OpenCL application.
    // To call the kernel, you need to create it from existing program.
    ocl.kernel = clCreateKernel(ocl.program, "Mul", &err);
    if (CL_SUCCESS != err)
    {
        LogError("Error: clCreateKernel returned %s\n", TranslateOpenCLError(err));
        return -1;
    }

    // Passing arguments into OpenCL kernel.
    if (CL_SUCCESS != SetKernelArguments(&ocl))
    {
        return -1;
    }

    // Regularly you wish to use OpenCL in your application to achieve greater performance results
    // that are hard to achieve in other ways.
    // To understand those performance benefits you may want to measure time your application spent in OpenCL kernel execution.
    // The recommended way to obtain this time is to measure interval between two moments:
    //   - just before clEnqueueNDRangeKernel is called, and
    //   - just after clFinish is called
    // clFinish is necessary to measure entire time spending in the kernel, measuring just clEnqueueNDRangeKernel is not enough,
    // because this call doesn't guarantees that kernel is finished.
    // clEnqueueNDRangeKernel is just enqueue new command in OpenCL command queue and doesn't wait until it ends.
    // clFinish waits until all commands in command queue are finished, that suits your need to measure time.
    bool queueProfilingEnable = true;
    if (queueProfilingEnable)
        QueryPerformanceCounter(&performanceCountNDRangeStart);
    // Execute (enqueue) the kernel
    if (CL_SUCCESS != ExecuteAddKernel(&ocl, arrayWidth, arrayHeight))
    {
        return -1;
    }
    if (queueProfilingEnable)
        QueryPerformanceCounter(&performanceCountNDRangeStop);

    // The last part of this function: getting processed results back.
    // use map-unmap sequence to update original memory area with output buffer.
    ReadAndVerify(&ocl, arrayWidth, arrayHeight, inputA, inputB);

    // retrieve performance counter frequency
    if (queueProfilingEnable)
    {
        QueryPerformanceFrequency(&perfFrequency);
        //LogInfo("NDRange performance counter time %f ms.\n",
          //  1000.0f*(float)(performanceCountNDRangeStop.QuadPart - performanceCountNDRangeStart.QuadPart) / (float)perfFrequency.QuadPart);
    }

    _aligned_free(inputA);
    _aligned_free(inputB);
    _aligned_free(outputC);

	return 1e6*(float)(performanceCountNDRangeStop.QuadPart - performanceCountNDRangeStart.QuadPart) / (float)perfFrequency.QuadPart;
}
Exemplo n.º 21
0
Arquivo: larson.c Projeto: d-b/CSC469
void runthreads(long sleep_cnt, int min_threads, int max_threads, int chperthread, int num_rounds)
{
  thread_data  de_area[MAX_THREADS] ;
  int           nperthread ;
  int           sum_threads ;
  int           sum_allocs ;
  int           sum_frees ;
  double        duration ;
  long ticks_per_sec ;
  long start_cnt, end_cnt ;
  _int64        ticks ;
  double        rate_1=0, rate_n ;
  double        reqd_space ;
  ptrdiff_t     used_space ;
  int           prevthreads ;
  int           i ;

  QueryPerformanceFrequency( &ticks_per_sec ) ;

  memset(&de_area[0], 0, sizeof(thread_data)) ;

  prevthreads = 0 ;
  for(num_threads=min_threads; num_threads <= max_threads; num_threads++ )
    {

      warmup(&blkp[prevthreads*chperthread], (num_threads-prevthreads)*chperthread );

      nperthread = chperthread ;
      stopflag   = FALSE ;
		
      for(i=0; i< num_threads; i++){
	de_area[i].threadno    = i+1 ;
	de_area[i].NumBlocks   = num_rounds*nperthread;
	de_area[i].array       = &blkp[i*nperthread] ;
	de_area[i].blksize     = &blksize[i*nperthread] ;
	de_area[i].asize       = nperthread ;
	de_area[i].min_size    = min_size ;
	de_area[i].max_size    = max_size ;
	de_area[i].seed        = lran2(&rgen) ; ;
	de_area[i].finished    = 0 ;
	de_area[i].cAllocs     = 0 ;
	de_area[i].cFrees      = 0 ;
	de_area[i].cThreads    = 0 ;
	de_area[i].finished    = FALSE ;
	lran2_init(&de_area[i].rgen, de_area[i].seed) ;

	_beginthread(exercise_heap, 0, &de_area[i]) ;  

      }

      QueryPerformanceCounter( &start_cnt) ;

      //printf ("Sleeping for %ld seconds.\n", sleep_cnt);
      Sleep(sleep_cnt * 1000L) ;
      stopflag = TRUE ;

      for(i=0; i<num_threads; i++){
	while( !de_area[i].finished ){
		sched_yield();
	}
      }


      QueryPerformanceCounter( &end_cnt) ;

      sum_frees = sum_allocs =0  ;
      sum_threads = 0 ;
      for(i=0;i< num_threads; i++){
	sum_allocs    += de_area[i].cAllocs ;
	sum_frees     += de_area[i].cFrees ;
	sum_threads   += de_area[i].cThreads ;
	printf("area %d: %d allocs, %d threads\n",i,de_area[i].cAllocs,de_area[i].cThreads);
	de_area[i].cAllocs = de_area[i].cFrees = 0;
      }

 
      ticks = end_cnt - start_cnt ;
     duration = (double)ticks/ticks_per_sec ;

      for( i=0; i<num_threads; i++){
	if( !de_area[i].finished )
	  printf("Thread at %d not finished\n", i) ;
      }


      rate_n = sum_allocs/duration ;
      if( rate_1 == 0){
	rate_1 = rate_n ;
      }
		
      reqd_space = (0.5*(min_size+max_size)*num_threads*chperthread) ;
      used_space = mem_usage();
      
      printf ("Throughput = %8.0f operations per second.\n", sum_allocs / duration);
      printf ("Memory used = %ld bytes, required %.0lf, ratio %lf\n",used_space,reqd_space,used_space/reqd_space);

#if 0
      printf("%2d ", num_threads ) ;
      printf("%6.3f", duration  ) ;
      printf("%6.3f", rate_n/rate_1 ) ;
      printf("%8.0f", sum_allocs/duration ) ;
      printf(" %6.3f %.3f", (double)used_space/(1024*1024), used_space/reqd_space) ;
      printf("\n") ;
#endif

      Sleep(5000L) ; // wait 5 sec for old threads to die

      prevthreads = num_threads ;

      printf ("Done sleeping...\n");

    }
}
Exemplo n.º 22
0
void Timer::Clear()
{
	begin = end = elapsed = 0;
	QueryPerformanceFrequency(&Freq);
	Freq.QuadPart /= 1000;
}
Exemplo n.º 23
0
/*
 * Opens the specified adapter and binds the protocol to it
 *
 * Arguments
 *		AdapterName		- The name of the adapter with which binding should happen
 *
 * Return Value
 *		Return TRUE if successfully bound otherwise returns FALSE
 *
 */
BOOL PKTOpenAdapter (PNDIS_STRING pAdapterName)
{
	POPEN_INSTANCE	pOI;
	NDIS_STATUS		nsOpen;
	NDIS_STATUS		nsError;
	SYSTEMTIME		SystemTime;
	FILETIME		FileTime;
	LARGE_INTEGER	liSysTime;
	LARGE_INTEGER	TimeFreq;
	LARGE_INTEGER	PTime;
	UINT			uiMedium;


	// Check if an instance is already opened
	if (g_pDeviceExtension->pOpenInstance) {
		SetLastError (ERROR_ALREADY_INITIALIZED);
		return FALSE;
	}

	// Time initialization
	GetSystemTime (&SystemTime);
	if (! (SystemTimeToFileTime (&SystemTime, &FileTime) &&
		QueryPerformanceCounter (&PTime) && QueryPerformanceFrequency (&TimeFreq))) {
		return FALSE;
	}
	NdisMoveMemory (&liSysTime, &FileTime, sizeof (LARGE_INTEGER));
	
	
	
	// allocate an instance that describes the adapter
	NdisAllocateMemory (&pOI, sizeof (OPEN_INSTANCE), 0, NDIS_ADDR_M1);
	if (pOI == NULL) {
		return FALSE;
	}
	NdisZeroMemory (pOI, sizeof (OPEN_INSTANCE));

	// init struct variables
	pOI->bpfprogram			= NULL;		//set an accept-all filter
	pOI->bpfprogramlen		= 0;
	pOI->BufSize			= 0;		//set an empty buffer
	pOI->Buffer				= NULL;		//reset the buffer
	pOI->Bhead				= 0;
	pOI->Btail				= 0;
	pOI->BLastByte			= 0;
	pOI->TimeOut			= 0;		//reset the timeouts


	// create the shared name read event
	pOI->ReadEvent = CreateEvent (NULL, FALSE, FALSE, SH_EVENT_NAME);
	if (pOI->ReadEvent == NULL) {
		NdisFreeMemory (pOI, sizeof (OPEN_INSTANCE), 0);
		return FALSE;
	}

	// set time values
	pOI->StartTime.QuadPart = (((liSysTime.QuadPart) % 10000000) * TimeFreq.QuadPart)/10000000;
	liSysTime.QuadPart = liSysTime.QuadPart / 10000000 - 11644473600;
	pOI->StartTime.QuadPart += (liSysTime.QuadPart) * TimeFreq.QuadPart - PTime.QuadPart;


	// allocate pool for the packet headers
	NdisAllocatePacketPool (&nsError, &(pOI->PacketPool), 
		TRANSMIT_PACKETS, sizeof (PACKET_RESERVED));
	if (nsError != NDIS_STATUS_SUCCESS) {
		CloseHandle (pOI->ReadEvent);
		NdisFreeMemory (pOI, sizeof (OPEN_INSTANCE), 0);
		return FALSE;
	}


	// allocate buffer pool for the packet data
	NdisAllocateBufferPool (&nsError, &(pOI->BufferPool), TRANSMIT_PACKETS);
	if (nsError != NDIS_STATUS_SUCCESS) {
		CloseHandle (pOI->ReadEvent);
		NdisFreePacketPool (pOI->PacketPool);
		NdisFreeMemory (pOI, sizeof (OPEN_INSTANCE), 0);
		return FALSE;
	}

	// set status pending
	pOI->Status = NDIS_STATUS_PENDING;

	// open the MAC driver
	NdisOpenAdapter (&nsOpen, &nsError, &pOI->AdapterHandle, &uiMedium, MediumArray,
		NUM_NDIS_MEDIA, g_pDeviceExtension->NdisProtocolHandle, pOI, pAdapterName, 0, NULL);


	if (nsOpen == NDIS_STATUS_PENDING) {
		SuspendExecution (pOI);
	} else {
		PacketOpenAdapterComplete (pOI, nsOpen, nsError);
	}

	// free the packet instance if not successful
	if (pOI->Status != NDIS_STATUS_SUCCESS) {
		CloseHandle (pOI->ReadEvent);
		NdisFreeMemory (pOI, sizeof (OPEN_INSTANCE), 0);
		return FALSE;
	}

	return TRUE;
}
Exemplo n.º 24
0
void Application::setAnimationInterval(double interval)
{
    LARGE_INTEGER nFreq;
    QueryPerformanceFrequency(&nFreq);
    _animationInterval.QuadPart = (LONGLONG)(interval * nFreq.QuadPart);
}
Exemplo n.º 25
0
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpszCmdLine, int nCmdShow) {
	wchar_t progname[] = L"CerealBox";


	windata.gameoutput.graphic.width = 1920/2;
	windata.gameoutput.graphic.height = 1080/2;

	windata.running = ootrue;
	windata.gameMemory = (void *) calloc((size_t)gameMemorySize(), 1L);

	oouint audioBufferSize = win32AudioBufferSize();
    windata.gameoutput.audio.buffer = (ooshort *) calloc((size_t)audioBufferSize, 1L);
	oouint audioFramesPerSecond = win32AudioFramesPerSecond();

	WNDCLASSEXW winclass;
	ZeroMemory(&winclass, sizeof(WNDCLASSEXW));

	
	MSG msg;

	winclass.cbSize = sizeof(WNDCLASSEXW);
	winclass.style = CS_DBLCLKS;
	winclass.lpfnWndProc = &winproc;
	winclass.cbClsExtra = 0;
	winclass.cbWndExtra = 0;
	winclass.hInstance = hInst;
	winclass.hIcon = LoadIcon(NULL,IDI_WINLOGO);
	winclass.hCursor = LoadCursor(NULL,IDC_ARROW);
	winclass.lpszClassName = progname;


	if(!RegisterClassExW(&winclass)) {
		return 0;
	}

	oouint startX = 100;
	oouint startY = 100;

	DWORD windowStyle =  WS_SYSMENU|WS_CAPTION|WS_BORDER|WS_OVERLAPPED|WS_VISIBLE|WS_MINIMIZEBOX;

#ifdef OO_FULLSCREEN
	windowStyle = WS_EX_TOPMOST | WS_POPUP;
	win32GetScreenResolution(&windata.gameoutput.graphic.width, &windata.gameoutput.graphic.height);
	startX = 0;
	startY = 0;
#endif
	RECT wr = {0, 0, windata.gameoutput.graphic.width, windata.gameoutput.graphic.height};
	AdjustWindowRect(&wr, windowStyle, FALSE);

	windata.window = CreateWindowW(
		progname,
		progname,
		windowStyle,
		startX,
		startY,
		wr.right - wr.left,
		wr.bottom - wr.top,
		NULL,
		NULL,
		hInst,
		NULL);

	initGraphics(&windata);
	win32AudioInit(windata.window);

	ShowWindow(windata.window,nCmdShow);
	UpdateWindow(windata.window);

	LARGE_INTEGER timeFrequency;
	QueryPerformanceFrequency(&timeFrequency);

	LARGE_INTEGER lastTime;
	ZeroMemory(&lastTime, sizeof(LARGE_INTEGER) );
	LARGE_INTEGER time;
	windata.gameinput.dt = 1.f/60.f;

	windata.windowDC = GetDC(windata.window);

	ooint monitorRefreshHz = 60;
	oofloat frameMs = 1.f / (oofloat)monitorRefreshHz;
	ooint win32RefreshRate = GetDeviceCaps(windata.windowDC, VREFRESH);
	if( win32RefreshRate>1 ) {
		monitorRefreshHz = win32RefreshRate;
		frameMs = 1.f / (oofloat)monitorRefreshHz;
	}

	while( windata.running ) {
		PeekMessage(&msg,NULL,0,0,PM_REMOVE);
		if(msg.message == WM_QUIT) {
			break;
		}


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

		win32ProcessMouseEvents(windata.window, &windata);

		QueryPerformanceCounter(&time);
		if( lastTime.QuadPart>0 ) {
			windata.gameinput.dt = (oofloat)(time.QuadPart - lastTime.QuadPart);
			windata.gameinput.dt /= timeFrequency.QuadPart;

			windata.gameoutput.audio.framesToWrite = (oouint)(windata.gameinput.dt*audioFramesPerSecond);
			if(windata.gameoutput.audio.framesToWrite>audioBufferSize) {
				windata.gameoutput.audio.framesToWrite = audioBufferSize;
			}

			advanceGame(windata.gameMemory,&windata.gameinput,&windata.gameoutput);

			win32AudioOutput(windata.gameoutput.audio.buffer, windata.gameoutput.audio.framesToWrite);
			renderGraphics(&windata);
		}
		
		lastTime = time;
		
	}

	ReleaseDC(windata.window, windata.windowDC);

	destroyGraphics(&windata);
	win32AudioDestroy();
	free(windata.gameMemory);
	free(windata.gameoutput.audio.buffer);

	return (msg.wParam);
}
Exemplo n.º 26
0
bool getProcessorInfoFromOS(int& cpus, int& cores, int& logicalCores, double& clockSpeed)
{
    cpus = 0;
    cores = 0;
    logicalCores = 0;
    clockSpeed = 0;

    // Clock speed
    HKEY hKey;
    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"), 0, KEY_EXECUTE, &hKey) == ERROR_SUCCESS) {
        DWORD type = REG_DWORD;
        DWORD val;
        DWORD cbData = sizeof(val);
        if (RegQueryValueEx(hKey, TEXT("~MHz"), NULL, &type, (LPBYTE)&val, &cbData) == ERROR_SUCCESS) {
            if (type == REG_DWORD && cbData == sizeof(DWORD)) {
                clockSpeed = val / 1000.0;
            }
        }

    }
    if (clockSpeed == 0) {
        // Can't access registry, try QueryPerformanceFrequency (nearly always same speed as CPU)
        LARGE_INTEGER f;
        if (!QueryPerformanceFrequency(&f)) {
            return false;
        }
        clockSpeed = f.QuadPart / 1000.0 / 1000.0;
    }

    // Everything else
    LPFN_GLPI glpi;
    glpi = (LPFN_GLPI)GetProcAddress(GetModuleHandle(TEXT("kernel32")), "GetLogicalProcessorInformation");
    if (glpi == NULL) {
        return false;
    }

    PSYSTEM_LOGICAL_PROCESSOR_INFORMATION buffer = NULL;
    DWORD bufferLength = 0;
    if (glpi(buffer, &bufferLength) == TRUE) {
        return false;
    }

    while (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
        if (buffer != NULL) {
            std::free(buffer);
        }
        buffer = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)std::malloc(bufferLength);
        if (buffer == NULL) {
            return false;
        }
        if (glpi(buffer, &bufferLength) == TRUE) {
            if (bufferLength / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) * sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) != bufferLength) {
                // sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION) must have changed (different from at compile time)
                std::free(buffer);
                return false;
            }

            auto end = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION)((char*)buffer + bufferLength);
            for (auto ptr = buffer; ptr != end; ++ptr) {
                switch (ptr->Relationship) {
                case RelationProcessorCore:
                    ++cores;
                    logicalCores += countBitsSet(ptr->ProcessorMask);
                    break;
                case RelationProcessorPackage:
                    ++cpus;
                    break;
                default:
                    break;
                }
            }

            std::free(buffer);
            return true;
        }
    }
    if (buffer != NULL) {
        std::free(buffer);
    }
    return false;
}
Exemplo n.º 27
0
/* Windows SYSTEMTIME only has 10 millisecond resolution, so we
 * also need to use a high resolution timer to get microseconds.
 * This is pretty clunky.
 */
void
ldap_pvt_gettime( struct lutil_tm *tm )
{
	static LARGE_INTEGER cFreq;
	static LARGE_INTEGER prevCount;
	static int subs;
	static int offset;
	LARGE_INTEGER count;
	SYSTEMTIME st;

	GetSystemTime( &st );
	QueryPerformanceCounter( &count );

	/* It shouldn't ever go backwards, but multiple CPUs might
	 * be able to hit in the same tick.
	 */
	LDAP_MUTEX_LOCK( &ldap_int_gettime_mutex );
	if ( count.QuadPart <= prevCount.QuadPart ) {
		subs++;
	} else {
		subs = 0;
		prevCount = count;
	}
	LDAP_MUTEX_UNLOCK( &ldap_int_gettime_mutex );

	/* We assume Windows has at least a vague idea of
	 * when a second begins. So we align our microsecond count
	 * with the Windows millisecond count using this offset.
	 * We retain the submillisecond portion of our own count.
	 *
	 * Note - this also assumes that the relationship between
	 * the PerformanceCouunter and SystemTime stays constant;
	 * that assumption breaks if the SystemTime is adjusted by
	 * an external action.
	 */
	if ( !cFreq.QuadPart ) {
		long long t;
		int usec;
		QueryPerformanceFrequency( &cFreq );

		/* just get sub-second portion of counter */
		t = count.QuadPart % cFreq.QuadPart;

		/* convert to microseconds */
		t *= 1000000;
		usec = t / cFreq.QuadPart;

		offset = usec - st.wMilliseconds * 1000;
	}

	tm->tm_usub = subs;

	/* convert to microseconds */
	count.QuadPart %= cFreq.QuadPart;
	count.QuadPart *= 1000000;
	count.QuadPart /= cFreq.QuadPart;
	count.QuadPart -= offset;

	tm->tm_usec = count.QuadPart % 1000000;
	if ( tm->tm_usec < 0 )
		tm->tm_usec += 1000000;

	/* any difference larger than microseconds is
	 * already reflected in st
	 */

	tm->tm_sec = st.wSecond;
	tm->tm_min = st.wMinute;
	tm->tm_hour = st.wHour;
	tm->tm_mday = st.wDay;
	tm->tm_mon = st.wMonth - 1;
	tm->tm_year = st.wYear - 1900;
}
Exemplo n.º 28
0
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

//DIL Interface
extern CBaseDIL_CAN* g_pouDIL_CAN_Interface;
// Initialise the static members

// Initialise absolute Time
int CTimeManager::m_nAbsoluteTime = 0;
// Init System time and reference tick
static LARGE_INTEGER s_Temp;
BOOL bDummy = QueryPerformanceCounter(&s_Temp);
const LARGE_INTEGER CTimeManager::m_sSysRefTickCount = s_Temp;
// Init the frequency
const int CTimeManager::m_nSysRefTime = CTimeManager::nCalculateCurrTimeStamp(FALSE);
BOOL bDummy0001 = QueryPerformanceFrequency((LARGE_INTEGER *) &s_Temp);
const __int64 CTimeManager::m_n64Frequency = s_Temp.QuadPart;

// **** Start of USB related Code **** //
int CTimeManager::m_nOffsetTimeValue =
                                CTimeManager::nCalculateOffsetTime();

// **** End of USB Related Code **** //

/*******************************************************************************
 Function Name  : CTimeManager
 Description    : Standard default constructor for dialog box
 Member of      : CTimeManager
 Functionality  : -
 Author(s)      : Raja N
 Date Created   : 23.06.2004
Exemplo n.º 29
0
/*
* $URL$
* $Date$
* $Rev$
*/

#include "itime.hpp"

#ifdef WIN32

LARGE_INTEGER ITime::freq;
bool ITime::freqInitialized = QueryPerformanceFrequency(&ITime::freq);

#endif
Exemplo n.º 30
0
void InitPerfClockFrequency()
{
    QueryPerformanceFrequency((LARGE_INTEGER *)&frequency);
    frequency /= 1000;
}