Exemple #1
0
VFIO(timer_write, file, data, size)
{
        TIMER *timer = (TIMER*)data;
        unsigned char cnf = 1, i = 1;
        timer->config = timer->config & 0x7;
        while(timer->config)
        {
                cnf &= timer->config;
                switch(cnf)
                {
                        case 0x4:
                                timer->set_mode(timer);
                                break;
                        case 0x2:
                                timer->set_frq(timer);
                                break;
                        case 0x1:
                                /* get the tick offset */
                                if(size <= sizeof(void*))
                                        return 0;
                                uint64_t offset = *((uint64_t*)(data+
                                                                sizeof(void*)));
                                timer->set_tick(timer, offset);
                                break;

                        default: /* unknown config word.. reset bits set? */
                                break;
                }
                timer->config &= (~cnf); /* disable just checked bit */
                cnf = (++i)<<1;
                if(cnf >= 1>>3)
                        break;
        }
        return E_SUCCESS;
}
Exemple #2
0
IRQ(timer_irq, irq, stack)
{
        struct irq_data *data = get_irq_data(irq);
        struct device *dev = (struct device *)(data->irq_data);

        TIMER *timer = dev->device_data;
        timer->tick++;
        timer->tick_handle(timer);

        return;
}
Exemple #3
0
//Perform per-frame updates
void UpdateFrame()
{
	//set currentTime and timePassed
	static double lastTime=timer.GetTime();
	double currentTime=timer.GetTime();
	double timePassed=currentTime-lastTime;
	lastTime=currentTime;

	//Update window
	WINDOW::Instance()->Update();

	//Update the lights
	for(int i=0; i<numLights; ++i)
	{
		lights[i].position+=lights[i].velocity*float(timePassed)/1000;

		//bounce off the borders
		if(lights[i].position.x>1.0f && lights[i].velocity.x>0.0f)
			lights[i].velocity.x=-lights[i].velocity.x;
		if(lights[i].position.x<-1.0f && lights[i].velocity.x<0.0f)
			lights[i].velocity.x=-lights[i].velocity.x;

		if(lights[i].position.z>1.0f && lights[i].velocity.z>0.0f)
			lights[i].velocity.z=-lights[i].velocity.z;
		if(lights[i].position.z<-1.0f && lights[i].velocity.z<0.0f)
			lights[i].velocity.z=-lights[i].velocity.z;
	}
	
	//Toggle vertex program/fixed function
	if(WINDOW::Instance()->IsKeyPressed('1') && GLEE_NV_vertex_program)
	{
		useVP1=true;
		useVP2=false;
		useFixedFunction=false;
	}
	
	if(WINDOW::Instance()->IsKeyPressed('2') && GLEE_NV_vertex_program2)
	{
		useVP1=false;
		useVP2=true;
		useFixedFunction=false;
	}

	if(WINDOW::Instance()->IsKeyPressed('3'))
	{
		useVP1=false;
		useVP2=false;
		useFixedFunction=true;
	}

	//Render frame
	RenderFrame(currentTime, timePassed);
}
Exemple #4
0
//Called when a key is pressed
void Keyboard(unsigned char key, int x, int y)
{
	//If escape is pressed, exit
	if(key==27)
		exit(0);

	//Use P to pause the animation and U to unpause
	if(key=='P' || key=='p')
		timer.Pause();

	if(key=='U' || key=='u')
		timer.Unpause();
}
Exemple #5
0
void LocalClient::KeystateTaskThread::task() {
	
	#define KEYSTATE_GRANULARITY_MS 46.66	// aiming for as low a rate as possible
	static TIMER keystate_timer;
	keystate_timer.begin();
	while (LocalClient::KeystateTaskThread::is_running() && LocalClient::is_connected()) {
		if (keystate_timer.get_ms() > KEYSTATE_GRANULARITY_MS) {
			update_keystate(keys);
			post_keystate();
			keystate_timer.begin();
			long wait_ms = KEYSTATE_GRANULARITY_MS - keystate_timer.get_ms();
			if (wait_ms > 1) { SLEEP_MS(wait_ms); }
		}
	}
}
Exemple #6
0
//Set up variables
bool DemoInit()
{
	if(!window.Init("Metaballs", 512, 512, 32, 24, 8, WINDOWED_SCREEN))
		return 0;											//quit if not created
	
	//set up grid
	if(!cubeGrid.CreateMemory())
		return false;
	if(!cubeGrid.Init(gridSize))
		return false;

	//set up metaballs
	for(int i=0; i<numMetaballs; i++)
		metaballs[i].Init(VECTOR3D(0.0f, 0.0f, 0.0f), 5.0f+float(i));

	//Set Up Colors
	diffuseColors[0].Set(0.345f, 0.843f, 0.902f, 1.0f);
	diffuseColors[1].Set(0.047f, 0.839f, 0.271f, 1.0f);
	diffuseColors[2].Set(0.976f, 0.213f, 0.847f, 1.0f);	

	//reset timer for start
	timer.Reset();
	
	return true;
}
Exemple #7
0
//Set up variables
bool DemoInit()
{
    if(!window.Init("Project Template", 640, 480, 32, 24, 8, WINDOWED_SCREEN))
        return 0;											//quit if not created

    SetUpARB_multitexture();
    SetUpEXT_texture3D();
    SetUpEXT_texture_edge_clamp();
    SetUpNV_register_combiners();
    SetUpNV_texture_shader();
    SetUpNV_vertex_program();

    if(	!EXT_texture_edge_clamp_supported || !ARB_multitexture_supported ||
            !NV_vertex_program_supported || !NV_register_combiners_supported)
        return false;

    //Check we have at least 3 texture units
    GLint maxTextureUnitsARB;
    glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &maxTextureUnitsARB);

    if(maxTextureUnitsARB<3)
    {
        errorLog.OutputError("I require at least 3 texture units");
        return false;
    }

    //Set light colors
    lightColors[0].Set(1.0f, 1.0f, 1.0f, 1.0f);
    lightColors[1].Set((float)47/255, (float)206/255, (float)240/255, 1.0f);
    lightColors[2].Set((float)254/255, (float)48/255, (float)18/255, 1.0f);
    lightColors[3].Set((float)83/255, (float)243/255, (float)29/255, 1.0f);



    //Load textures
    //Decal image
    decalImage.Load("decal.tga");
    glGenTextures(1, &decalTexture);
    glBindTexture(GL_TEXTURE_2D, decalTexture);
    glTexImage2D(	GL_TEXTURE_2D, 0, GL_RGBA8, decalImage.width, decalImage.height,
                    0, decalImage.format, GL_UNSIGNED_BYTE, decalImage.data);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);


    //Create light textures
    if(!InitLightTextures(	atten1DTexture, atten2DTexture, atten3DTexture,
                            gaussian1DTexture, gaussian2DTexture))
        return false;


    camera.Init(VECTOR3D(0.0f, 0.0f, 3.5f));

    //reset timer for start
    timer.Reset();

    return true;
}
Exemple #8
0
//Perform per-frame updates
void UpdateFrame()
{
	//set currentTime and timePassed
	static double lastTime=timer.GetTime();
	double currentTime=timer.GetTime();
	double timePassed=currentTime-lastTime;
	lastTime=currentTime;

	//Update window
	WINDOW::Instance()->Update();


	
	//Render frame
	RenderFrame(currentTime, timePassed);
}
Exemple #9
0
void LocalClient::ListenTaskThread::task() {
	
	struct sockaddr_in from;

	static TIMER ping_timer;	// seems like a waste to actually create another thread for this
	ping_timer.begin();

#define PING_GRANULARITY_MS 2000
	
	while (LocalClient::ListenTaskThread::is_running() && LocalClient::is_connected()) {
		int bytes = socket.receive_data(buffer, &from);
		if (bytes > 0) { handle_current_packet(); }
	}

	post_quit_message();

}
void StateGraphicsNext(int state)
{
	if (StateGraphics == state)
	{
		return;
	}

	StateGraphicsTimer.Reset();
	StateGraphicsLast = StateGraphics;
	StateGraphics = state;

	// The visual target first appears in this state, so set graphics sync timer.
	if (StateGraphics == STATE_GO)
	{
		// Set graphics sync timer relative to offset of next vertical retrace.
		GraphicsTargetTimer.Reset(-GRAPHICS_VerticalRetraceOffsetTimeUntilNext());
	}
}
void GraphicsScene(void) // this is created by shyeo, isolating the gl routines only from GraphicsDisplay
{
	int attr;
	static matrix posn;

	// Display text.
	strncpy(GraphicsString, StateText[StateGraphics], STRLEN);
	GraphicsDisplayText();
	
	// Display rotating teapot during rest period.
	if (StateGraphics == STATE_REST)
	{
		glPushMatrix();
		GRAPHICS_ColorSet(GREEN);
		glRotated(ExperimentTimer.ElapsedSeconds() * 10.0 * PI, 1.0, 1.0, 1.0);
		glutWireTeapot(10.0);
		glPopMatrix();
		return;
	}
	
	// Display home position at start of trial.
	if ((StateGraphics >= STATE_SETUP) && (StateGraphics <= STATE_MOVING))
	{
		attr = RobotHome() ? HomeColor : NotHomeColor;
		//GRAPHICS_Circle(&StartPosition, HomeRadius, attr);
		GRAPHICS_Sphere(&StartPosition, HomeRadius, attr);
	}
	
	// Display target spheres when trial running.
	if ((StateGraphics >= STATE_GO) && (StateGraphics <= STATE_FINISH))
	{
		// Display target for movement.
		GRAPHICS_Sphere(&TargetPosition, TargetRadius, TargetColor);

		// Display graphics sync target for phototransistor.
		if (!GraphicsSyncPosition.iszero())
		{
			GRAPHICS_Sphere(&GraphicsSyncPosition, GraphicsSyncRadius, GraphicsSyncColor);
		}
	}

	// Display finish position.
	if ((StateGraphics > STATE_MOVING) && (StateGraphics <= STATE_INTERTRIAL))
	{
		attr = RobotHome() ? HomeColor : NotHomeColor;
		GRAPHICS_Sphere(&FinishPosition, HomeRadius, attr);
	}

	// Display robot position cursor.
	if ((StateGraphics != STATE_ERROR) && (VisualFeedback || RobotHome()))
	{
		posn = CursorPosition;
		posn(3, 1) += 2.0*HomeRadius;
		GRAPHICS_Sphere(&posn, CursorRadius, CursorColor);
	}
}
Exemple #12
0
 stopwatch_event(uint32_t waitms,
                 std::function<void(void)>&& d,
                 const TIMER& in_ms_timer) :
     ms_timer([&in_ms_timer]() { return in_ms_timer.milliseconds(); }),
     _canceled(IS_NOT_CANCELED),
     _step(IS_NOT_STARTED),
     waitms(waitms),
     d(std::move(d)),
     lastms(ms_timer())
 { }
Exemple #13
0
//Set up variables
bool DemoInit()
{
	//Demo initialisation here


	
	//reset timer
	timer.Reset();

	return true;
}
Exemple #14
0
	/**
	 * Reduce all server timers to server master.
	 * @param timer
	 */
	void mpi_reduce_timers(TIMER& timer){
		sip::SIPMPIAttr &attr = sip::SIPMPIAttr::get_instance();
		sip::check(attr.is_server(), "Trying to reduce timer on a non-server rank !");
		long long * timers = timer.get_timers();
		long long * timer_counts = timer.get_timer_count();

		// Data to send to reduce
		long long * sendbuf = new long long[2*timer.max_slots + 1];
		sendbuf[0] = timer.max_slots;
		// The data will be structured as
		// Length of arrays 1 & 2
		// Array1 -> timer_switched_ array
		// Array2 -> timer_list_ array
		std::copy(timer_counts + 0, timer_counts + timer.max_slots, sendbuf+1);
		std::copy(timers + 0, timers + timer.max_slots, sendbuf+1+ timer.max_slots);

		long long * recvbuf = new long long[2*timer.max_slots + 1]();

		int server_master = attr.COMPANY_MASTER_RANK;
		MPI_Comm server_company = attr.company_communicator();

		MPI_Datatype server_timer_reduce_dt; // MPI Type for timer data to be reduced.
		MPI_Op server_timer_reduce_op;	// MPI OP to reduce timer data.
		SIPMPIUtils::check_err(MPI_Type_contiguous(timer.max_slots*2+1, MPI_LONG_LONG, &server_timer_reduce_dt));
		SIPMPIUtils::check_err(MPI_Type_commit(&server_timer_reduce_dt));
		SIPMPIUtils::check_err(MPI_Op_create((MPI_User_function *)server_timer_reduce_op_function, 1, &server_timer_reduce_op));

		SIPMPIUtils::check_err(MPI_Reduce(sendbuf, recvbuf, 1, server_timer_reduce_dt, server_timer_reduce_op, server_master, server_company));

		if (attr.is_company_master()){
			std::copy(recvbuf+1, recvbuf+1+timer.max_slots, timer_counts);
			std::copy(recvbuf+1+timer.max_slots, recvbuf+1+2*timer.max_slots, timers);
		}

		// Cleanup
		delete [] sendbuf;
		delete [] recvbuf;

		SIPMPIUtils::check_err(MPI_Type_free(&server_timer_reduce_dt));
		SIPMPIUtils::check_err(MPI_Op_free(&server_timer_reduce_op));
	}
void StateNext(int state)
{
	if (State == state)
	{
		return;
	}

	printf("STATE: %s[%d] > %s[%d] (%.0lf msec).\n", StateText[State], State, StateText[state], state, StateTimer.Elapsed());
	StateTimer.Reset();
	StateLast = State;
	State = state;
}
Exemple #16
0
void CheckTimers()
{
    //50 msecs were elasped
    std::list<TIMER*>::iterator itr;

    for(itr = gTimerList.begin(); itr != gTimerList.end();)
    {
        TIMER* curr = *itr;
        curr->current += 50;
        if ( curr->current >= curr->period )	{
            if (curr->routine(curr->period)) {
                curr->current -= curr->period;
            }
            else {
                delete curr;
                itr=gTimerList.erase(itr);
            }
        }
        else
            ++itr;
    }
}
Exemple #17
0
	virtual void execute(TIMER& timer) {
		void ** tau_timers = timer.get_tau_timers();

		std::vector<std::string>::const_iterator it = line_to_str_.begin();
		for (int line_num = 0; it!= line_to_str_.end(); ++it, ++line_num){
			const std::string &line_str = *it;
			if (line_str != ""){

				int total_time_timer_offset = line_num + sialx_lines_ * static_cast<int>(ServerTimer::TOTALTIME);
				if (tau_timers[total_time_timer_offset] != NULL){
					// Set total time string
					std::stringstream tot_sstr;
					tot_sstr << sip::GlobalState::get_program_num() << ": " << line_num << ": "  << " Total " << line_str;
					const char *tau_string = tot_sstr.str().c_str();
					TAU_PROFILE_TIMER_SET_NAME(tau_timers[total_time_timer_offset], tau_string);
				}

				int block_wait_timer_offset = line_num + sialx_lines_ * static_cast<int>(ServerTimer::BLOCKWAITTIME);
				if (tau_timers[block_wait_timer_offset] != NULL){
					// Set block wait time string
					std::stringstream blkw_sstr;
					blkw_sstr << sip::GlobalState::get_program_num() << ":" << line_num <<":" << " Blkwait " << line_str ;
					const char *tau_string = blkw_sstr.str().c_str();
					TAU_PROFILE_TIMER_SET_NAME(tau_timers[block_wait_timer_offset], tau_string);
				}

				int read_timer_offset = line_num + sialx_lines_ * static_cast<int>(ServerTimer::READTIME);
				if (tau_timers[read_timer_offset] != NULL){
					// Set disk read time string
					std::stringstream readd_sstr;
					readd_sstr << sip::GlobalState::get_program_num() << ":" << line_num <<":" << " ReadDisk " << line_str ;
					const char *tau_string = readd_sstr.str().c_str();
					TAU_PROFILE_TIMER_SET_NAME(tau_timers[read_timer_offset], tau_string);
				}

				int write_timer_offset = line_num + sialx_lines_ * static_cast<int>(ServerTimer::WRITETIME);
				if (tau_timers[write_timer_offset] != NULL){
					// Set disk write time string
					std::stringstream writed_sstr;
					writed_sstr << sip::GlobalState::get_program_num() << ":" << line_num <<":" << " WriteDisk " << line_str ;
					const char *tau_string = writed_sstr.str().c_str();
					TAU_PROFILE_TIMER_SET_NAME(tau_timers[write_timer_offset], tau_string);
				}

			}
		}
	}
Exemple #18
0
//draw a frame
void RenderFrame()
{
	//Clear buffers
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();										//reset modelview matrix


	glEnable(GL_LIGHTING);
	glTranslatef(0.0f, 0.0f, -30.0f);
	glRotatef((float)timer.GetTime()/30, 1.0f, 0.0f, 1.0f);
	cubeGrid.DrawSurface(threshold);
	glDisable(GL_LIGHTING);

	
	fpsCounter.Update();											//update frames per second counter
	glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
	window.StartTextMode();
	window.Print(0, 28, "FPS: %.2f", fpsCounter.GetFps());			//print the fps
	glColor4f(1.0f, 1.0f, 0.0f, 1.0f);
	window.Print(0, 48, "Grid Size: %d", gridSize);
	window.Print(0, 68, "%d triangles drawn", cubeGrid.numFacesDrawn);
	window.EndTextMode();
	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

	if(window.isKeyPressed(VK_F1))
	{
		window.SaveScreenshot();
		window.SetKeyReleased(VK_F1);
	}

	window.SwapBuffers();									//swap buffers

	//check for any opengl errors
	window.CheckGLError();

	//quit if necessary
	if(window.isKeyPressed(VK_ESCAPE))
		PostQuitMessage(0);
}
Exemple #19
0
//Perform per frame updates
void UpdateFrame(unsigned char key, int x, int y)
{
	angle=(float)timer.GetTime()/25;

	objectLightDirection=worldLightDirection.GetRotatedY(-angle);
	objectViewDirection=worldViewDirection.GetRotatedY(-angle);

	//update vertex program registers
	//Light direction in c[4]
	glProgramParameter4fvNV(GL_VERTEX_PROGRAM_NV, 4, VECTOR4D(objectLightDirection.GetNormalized()));
	//view direction in c[5]
	glProgramParameter4fvNV(GL_VERTEX_PROGRAM_NV, 5, VECTOR4D(objectViewDirection.GetNormalized()));

//	//pause & unpause
//	if(window.isKeyPressed('P'))
//		timer.Pause();
//
//	if(window.isKeyPressed('U'))
//		timer.Unpause();
//
//	//change technique
//	if(window.isKeyPressed('1') && paths1And2Supported)
//		currentTechnique=SINGLE_PASS;
//
//	if(window.isKeyPressed('2') && paths1And2Supported)
//		currentTechnique=TEXTURE_LOOKUP;
//
//	if(window.isKeyPressed('3'))
//		currentTechnique=FALLBACK;
//
//	//toggle bumpy
//	if(window.isKeyPressed('B'))
//		showBumps=true;
//
//	if(window.isKeyPressed('F'))
//		showBumps=false;
}
Exemple #20
0
//Set up variables
bool DemoInit()
{
	if(!window.Init("Render To Texture", 640, 480, 32, 24, 8, WINDOWED_SCREEN))
		return 0;											//quit if not created

	camera.Init(VECTOR3D(0.0f, 0.0f, -2.5f), 2.0f, 100.0f);

	//Set up extensions
	if(	!SetUpWGL_ARB_extensions_string())
		return false;

	SetUpEXT_texture_filter_anisotropic();
	SetUpSGIS_generate_mipmap();
		
	//Get the WGL extensions string
	const char * wglExtensions;
	wglExtensions=wglGetExtensionsStringARB(window.hDC);

	//Set up wgl extensions
	if(	!SetUpWGL_ARB_pbuffer(wglExtensions) || !SetUpWGL_ARB_pixel_format(wglExtensions) ||
		!SetUpWGL_ARB_render_texture(wglExtensions))
		return false;


	//Init the pbuffer
	int pbufferExtraIAttribs[]={WGL_BIND_TO_TEXTURE_RGBA_ARB, true,
								0};

	int pbufferFlags[]={WGL_TEXTURE_FORMAT_ARB, WGL_TEXTURE_RGBA_ARB,
						WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB,
						
						//request mipmap space if mipmaps are to be used
						SGIS_generate_mipmap_supported ? WGL_MIPMAP_TEXTURE_ARB : 0,
						SGIS_generate_mipmap_supported ? true : 0,

						0};

	if(!pbuffer.Init(pbufferSize, pbufferSize, 32, 24, 8, 1, pbufferExtraIAttribs, pbufferFlags))
		return false;
	

	//Create the texture object to relate to the pbuffer
	glGenTextures(1, &pbufferTexture);
	glBindTexture(GL_TEXTURE_2D, pbufferTexture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	//Use generated mipmaps if supported
	if(SGIS_generate_mipmap_supported)
	{
		glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, true);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glHint(GL_GENERATE_MIPMAP_HINT_SGIS, GL_NICEST);
		useMipmapFilter=true;
	}

	//Use maximum anisotropy if supported
	if(EXT_texture_filter_anisotropic_supported)
	{
		glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxAnisotropy);
		currentAnisotropy=maxAnisotropy;
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, currentAnisotropy);
	}



	//Load the decal texture
	//Note: This MUST be done when the pbuffer is the current context
	pbuffer.MakeCurrent();
	
	IMAGE decalImage;
	decalImage.Load("decal.bmp");

	glGenTextures(1, &decalTexture);
	glBindTexture(GL_TEXTURE_2D, decalTexture);
	glTexImage2D(	GL_TEXTURE_2D, 0, GL_RGBA8, decalImage.width, decalImage.height,
					0, decalImage.format, GL_UNSIGNED_BYTE, decalImage.data);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);


	
	//reset timer for start
	timer.Reset();
	
	return true;
}
Exemple #21
0
//draw a frame
void RenderFrame()
{
	//Draw to pbuffer
	pbuffer.MakeCurrent();
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();										//reset modelview matrix

	gluLookAt(	0.0f, 0.0f, 4.0f,
				0.0f, 0.0f, 0.0f,
				0.0f, 1.0f, 0.0f);

	//Draw scene
	if(drawTextured)
	{
		glBindTexture(GL_TEXTURE_2D, decalTexture);
		glEnable(GL_TEXTURE_2D);
		
		glPushMatrix();
		glRotatef(timer.GetTime()/20, 0.0f, 1.0f, 0.0f);

		glutSolidTeapot(0.8f);
		
		glPopMatrix();

		glDisable(GL_TEXTURE_2D);
	}
	else
	{
		glPushMatrix();
		glRotatef(timer.GetTime()/20, 0.0f, 1.0f, 0.0f);
		glRotatef(55.0f, 1.0f, 0.0f, 0.0f);
		glutWireTorus(0.3f, 1.0f, 12, 24);
		glPopMatrix();

		glPushMatrix();
		glRotatef(timer.GetTime()/20, 0.0f, 1.0f, 0.0f);
		glRotatef(-55.0f, 1.0f, 0.0f, 0.0f);
		glutWireTorus(0.3f, 1.0f, 12, 24);
		glPopMatrix();
	}


	
	//Draw to window
	window.MakeCurrent();
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	camera.SetupViewMatrix();
	glLoadMatrixf(camera.viewMatrix);


	glBindTexture(GL_TEXTURE_2D, pbufferTexture);
	//use the pbuffer as the texture
	wglBindTexImageARB(pbuffer.hBuffer, WGL_FRONT_LEFT_ARB);


	//Draw simple rectangle
	glBegin(GL_TRIANGLE_STRIP);
	{
		glTexCoord2f(0.0f, 0.0f);
		glVertex3f(-1.0f, -1.0f, 0.0f);
		glTexCoord2f(0.0f, 1.0f);
		glVertex3f(-1.0f,  1.0f, 0.0f);
		glTexCoord2f(1.0f, 0.0f);
		glVertex3f( 1.0f, -1.0f, 0.0f);
		glTexCoord2f(1.0f, 1.0f);
		glVertex3f( 1.0f,  1.0f, 0.0f);
	}
	glEnd();

	//release the pbuffer for further rendering
	wglReleaseTexImageARB(pbuffer.hBuffer, WGL_FRONT_LEFT_ARB);



	fpsCounter.Update();											//update frames per second counter
	glColor4f(1.0f, 1.0f, 0.0f, 1.0f);
	window.StartTextMode();
	window.Print(0, 28, "FPS: %.2f", fpsCounter.GetFps());			//print the fps
	glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
	window.Print(0, 48, "%dx Anisotropy", currentAnisotropy);
	glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
	window.Print(0, 68, "%s", useMipmapFilter ?	"LINEAR_MIPMAP_LINEAR filtering" :
												"LINEAR filtering");
	window.EndTextMode();
	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

	if(window.isKeyPressed(VK_F1))
	{
		window.SaveScreenshot();
		window.SetKeyReleased(VK_F1);
	}

	window.SwapBuffers();									//swap buffers

	//check for any opengl errors
	window.CheckGLError();

	//quit if necessary
	if(window.isKeyPressed(VK_ESCAPE))
		PostQuitMessage(0);
}
Exemple #22
0
//Perform per frame updates
void UpdateFrame()
{
	window.Update();
	camera.Update();

	//Change anisotropy level
	if(	window.isKeyPressed(VK_UP) && EXT_texture_filter_anisotropic_supported &&
		currentAnisotropy<maxAnisotropy)
	{
		window.MakeCurrent();
		currentAnisotropy*=2;
		glBindTexture(GL_TEXTURE_2D, pbufferTexture);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, currentAnisotropy);
		window.SetKeyReleased(VK_UP);
	}
	
	if(	window.isKeyPressed(VK_DOWN) && EXT_texture_filter_anisotropic_supported &&
		currentAnisotropy>1)
	{
		window.MakeCurrent();
		currentAnisotropy/=2;
		glBindTexture(GL_TEXTURE_2D, pbufferTexture);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, currentAnisotropy);
		window.SetKeyReleased(VK_DOWN);
	}

	//toggle mipmaps
	if( window.isKeyPressed('M') && useMipmapFilter==false && SGIS_generate_mipmap_supported)
	{
		window.MakeCurrent();
		glBindTexture(GL_TEXTURE_2D, pbufferTexture);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, true);
		useMipmapFilter=true;
	}

	if( window.isKeyPressed('L') && useMipmapFilter==true && SGIS_generate_mipmap_supported)
	{
		window.MakeCurrent();
		glBindTexture(GL_TEXTURE_2D, pbufferTexture);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS, false);
		useMipmapFilter=false;
	}

	//Pause/unpause
	if(window.isKeyPressed('P'))
		timer.Pause();

	if(window.isKeyPressed('U'))
		timer.Unpause();

	//Swap between scenes in the pbuffer
	if(window.isKeyPressed('1') && drawTextured)
	{
		//Draw wire tori
		drawTextured=false;
	}

	if(window.isKeyPressed('2') && !drawTextured)
	{
		//draw textured sphere
		drawTextured=true;
	}
}
Exemple #23
0
//Set up variables
bool DemoInit()
{
	if(!window.Init("Project Template", 640, 480, 32, 24, 8, WINDOWED_SCREEN))
		return 0;											//quit if not created

	SetUpARB_multitexture();
	SetUpARB_texture_cube_map();
	SetUpEXT_texture_edge_clamp();
	SetUpNV_register_combiners();
	SetUpNV_register_combiners2();
	SetUpNV_vertex_program();

	//Check for necessary extensions
	if(	!ARB_multitexture_supported || !ARB_texture_cube_map_supported ||
		!EXT_texture_edge_clamp_supported || !NV_register_combiners_supported ||
		!NV_vertex_program_supported)
		return false;

	//Check for single-pass chromatic aberration states
	GLint maxTextureUnits;
	glGetIntegerv(GL_MAX_TEXTURE_UNITS_ARB, &maxTextureUnits);
	if( NV_register_combiners2_supported && maxTextureUnits>=4)
	{
		errorLog.OutputSuccess("Single Pass Chromatic Aberration Supported!");
		pathOneSupported=true;
		renderPath=CHROMATIC_SINGLE;
	}

	camera.Init(VECTOR3D(0.0f, 0.0f, 4.0f), 2.5f, 10.0f);

	if(	!cubeMapPosX.Load("cube_face_posx.tga") ||
		!cubeMapNegX.Load("cube_face_negx.tga") ||
		!cubeMapPosY.Load("cube_face_posy.tga") ||
		!cubeMapNegY.Load("cube_face_negy.tga") ||
		!cubeMapPosZ.Load("cube_face_posz.tga") ||
		!cubeMapNegZ.Load("cube_face_negz.tga"))
		return false;

	//Build a texture from the data
	glGenTextures(1, &cubeMapTexture);								//Generate Texture ID
	glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, cubeMapTexture);					//Bind texture
	
	glTexImage2D(	GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
					0, GL_RGBA8, cubeMapPosX.width, cubeMapPosX.height, 0,
					cubeMapPosX.format, GL_UNSIGNED_BYTE, cubeMapPosX.data);
	
	glTexImage2D(	GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB,
					0, GL_RGBA8, cubeMapNegX.width, cubeMapNegX.height, 0,
					cubeMapNegX.format, GL_UNSIGNED_BYTE, cubeMapNegX.data);

	glTexImage2D(	GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB,
					0, GL_RGBA8, cubeMapPosY.width, cubeMapPosY.height, 0,
					cubeMapPosY.format, GL_UNSIGNED_BYTE, cubeMapPosY.data);
	
	glTexImage2D(	GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB,
					0, GL_RGBA8, cubeMapNegY.width, cubeMapNegY.height, 0,
					cubeMapNegY.format, GL_UNSIGNED_BYTE, cubeMapNegY.data);

	glTexImage2D(	GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB,
					0, GL_RGBA8, cubeMapPosZ.width, cubeMapPosZ.height, 0,
					cubeMapPosZ.format, GL_UNSIGNED_BYTE, cubeMapPosZ.data);
	
	glTexImage2D(	GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB,
					0, GL_RGBA8, cubeMapNegZ.width, cubeMapNegZ.height, 0,
					cubeMapNegZ.format, GL_UNSIGNED_BYTE, cubeMapNegZ.data);

	glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);

	
	//reset timer for start
	timer.Reset();
	
	return true;
}
MDA_TASK_RETURN_CODE MDA_TASK_PATH:: run_task() {
    puts("Press q to quit");

    MDA_VISION_MODULE_PATH path_vision;
    MDA_VISION_MODULE_GATE gate_vision;
    MDA_TASK_RETURN_CODE ret_code = TASK_MISSING;
    
    TASK_STATE state = STARTING_GATE;
    bool done_gate = false;
    bool done_path = false;

    // read the starting orientation
    int starting_yaw = attitude_input->yaw();
    printf("Starting yaw: %d\n", starting_yaw);
    
    int GATE_DEPTH;
    read_mv_setting ("hacks.csv", "GATE_DEPTH", GATE_DEPTH);

    // gate depth
    if (HARDCODED_DEPTH > 350)
        set (DEPTH, 350);
    if (HARDCODED_DEPTH > 400)
        set (DEPTH, 400);
    set (DEPTH, GATE_DEPTH);
    //set(DEPTH, 100);

    // go to the starting orientation in case sinking changed it
    set (YAW, starting_yaw);

    //TIMER master_timer;
    TIMER timer;
    timer.restart();

    while (1) {

        IplImage* frame = NULL;
        MDA_VISION_RETURN_CODE vision_code = NO_TARGET;
        MDA_VISION_RETURN_CODE gate_vision_code = NO_TARGET;
        (void) gate_vision_code;
        /*if (!done_gate) {
            frame = image_input->get_image(FWD_IMG);
            if (!frame) {
                ret_code = TASK_ERROR;
                break;
            }
            gate_vision_code = gate_vision.filter(frame);
        }*/

        frame = image_input->get_image(DWN_IMG);
        if (!frame) {
            ret_code = TASK_ERROR;
            break;
        }
        vision_code = path_vision.filter(frame);
        
        // clear fwd image. RZ - do we need this?
        // This ensures the other camera is properly logged
        // and that the webcam cache is cleared so it stays in sync - VZ
        //image_input->ready_image(FWD_IMG);

        /**
        * Basic Algorithm:
        *  - Go to path
        *  - Align with path
        */

        if (!done_gate) {
            if (state == STARTING_GATE) {
                printf ("Starting Gate: Moving Foward at High Speed\n");
                set (SPEED, 5);

                if (timer.get_time() > MASTER_TIMEOUT) {
                    printf ("Starting Gate: Master Timer Timeout!!\n");
                    return TASK_MISSING;
                }
                /*else if (gate_vision_code == FULL_DETECT) {
                    printf ("Starting Gate: Full Detect\n");
                    int ang_x = gate_vision.get_angular_x();
                    set_yaw_change(ang_x);

                    if (gate_vision.get_range() < 420) { // finished the gate
                        printf ("Range = %d, Approaching Gate\n", gate_vision.get_range());
                        timer.restart();
                        while (timer.get_time() < 3) {
                            set(SPEED, 6);
                        }
                        set(SPEED, 0);
                        printf ("Gate Task Done!!\n");

                        // get ready for path task
                        done_gate = true;
                        set(YAW, starting_yaw);
                        state = STARTING_PATH;
                    }

                    timer.restart();
                }*/

                // if path vision saw something, go do the path task
                if (vision_code != NO_TARGET) {
                    printf ("\nSaw Path! Going to Path vision!");
                    done_gate = true;
                    set(SPEED, 0);
                    set(YAW, starting_yaw);
                    timer.restart();
                    while (timer.get_time() < 2);
                    state = STARTING_PATH;
                }
            }
        }


        else if (!done_path) {
            // calculate some values that we will need
            float xy_ang = path_vision.get_angular_x(); // angle equal to atan(x/y)
            float pos_angle = path_vision.get_angle();  // PA, equal to orientation of the thing
            int pix_x = path_vision.get_pixel_x();
            int pix_y = path_vision.get_pixel_y();
            int pix_distance = sqrt(pow(pix_y,2) + pow(pix_x,2));

            printf("xy_distance = %d    xy_angle = %5.2f\n==============================\n", pix_distance, pos_angle);

            if (state == STARTING_PATH) {
                if (vision_code == NO_TARGET) {
                    printf ("Starting: No target\n");
                    set(SPEED,3);
                    if (timer.get_time() > MASTER_TIMEOUT) { // timeout
                        printf ("Master Timeout\n");
                        return TASK_MISSING;
                    }
                }
                else if (vision_code == UNKNOWN_TARGET) {
                    printf ("Starting: Unknown target\n");
                    timer.restart();
                }
                else {
                    printf ("Starting: Good\n");
                    set(SPEED, 0);
                    timer.restart();
                    state = AT_SEARCH_DEPTH;
                }
            }
            else if (state == AT_SEARCH_DEPTH){
                if (vision_code == NO_TARGET) {
                    if (timer.get_time() < 1) {
                        continue;
                    }
                    printf ("Searching: No target\n");
                    if (timer.get_time() > 11) { // timeout, go back to starting state
                        printf ("Timeout\n");
                        //set (YAW, starting_yaw);
                        timer.restart();
                        path_vision.clear_frames();
                        state = STARTING_PATH;
                    }
                    else if (timer.get_time() % 2 == 0) { // spin around a bit to try to re-aquire?
                        //move (RIGHT, 45);
                    }
                    else { // just wait
                    }
                }
                else if (vision_code == UNKNOWN_TARGET) {
                    printf ("Searching: Unknown target\n");
                    timer.restart();
                }
                else {
                    timer.restart();
                    printf ("Searching: Good\n");
                    if(pix_distance > frame->height/5){ // move over the path
                        if (abs(xy_ang) < 10) {
                            // go fowards or backwards depending on the pix_y value 
                            if (pix_y >= 0) { 
                                printf ("Set speed foward\n");
                                set(SPEED, 3);
                            } else { 
                                printf ("Set speed reverse\n");
                                set(SPEED, -3);
                            }
                        }
                        else {
                            if (abs(xy_ang) > 90 ) {
                                // turn different direction based on pix_y value
                                xy_ang = (xy_ang > 0) ? xy_ang - 180 : xy_ang + 180; 
                            } 
                            printf("Turning %s %d degrees (xy_ang)\n", (abs(xy_ang) > 0) ? "Right" : "Left", static_cast<int>(abs(xy_ang)));
                            set(SPEED, 0);
                            move(RIGHT, xy_ang);
                            path_vision.clear_frames();
                        }
                    }
                    else {                              // we are over the path, sink and try align state
                        set(SPEED, 0);
                        move(SINK, ALIGN_DELTA_DEPTH);
                        timer.restart();
                        path_vision.clear_frames();
                        state = AT_ALIGN_DEPTH;
                    }
                }   
            }
            else if (state == AT_ALIGN_DEPTH) {
                if (vision_code == NO_TARGET) {     // wait for timeout
                    printf ("Aligning: No target\n");
                    if (timer.get_time() > 6) { // timeout
                        printf ("Timeout\n");
                        move(RISE, ALIGN_DELTA_DEPTH);
                        timer.restart();
                        path_vision.clear_frames();
                        state = AT_SEARCH_DEPTH;
                    }
                }
                else if (vision_code == UNKNOWN_TARGET) {
                    printf ("Aligning: Unknown target\n");
                    timer.restart();
                }
                else {
                    if (abs(pos_angle) >= 10) {
                        move(RIGHT, pos_angle);
                        path_vision.clear_frames();
                        timer.restart();
                    }
                    else {
                        done_path = true;
                    }
                }
            }
        } // done_path
        else {
            // wait foward 2 secs, then charge foward for 2 secs
            timer.restart();
            while (timer.get_time() < 2) {
                set(SPEED, 0);
            }
            while (timer.get_time() < 2) {
                set(SPEED, 4);
            }
            set(SPEED, 0);
            printf ("Path Task Done!!\n");
            return TASK_DONE;

        }

        // Ensure debug messages are printed
        fflush(stdout);
        // Exit if instructed to
        char c = cvWaitKey(TASK_WK);
        if (c != -1) {
            CharacterStreamSingleton::get_instance().write_char(c);
        }
        if (CharacterStreamSingleton::get_instance().wait_key(1) == 'q'){
            stop();
            ret_code = TASK_QUIT;
            break;
        }
    }

    if(done_path){
        ret_code = TASK_DONE;
    }

    return ret_code;
}
MDA_TASK_RETURN_CODE MDA_TASK_PATH_SKIP:: run_task() {
    puts("Press q to quit");

    MDA_VISION_MODULE_PATH path_vision;
    MDA_TASK_RETURN_CODE ret_code = TASK_MISSING;

    bool done_skip = false;

    TIMER t;

    // sink to starting depth
    //set (DEPTH, MDA_TASK_BASE::starting_depth+PATH_DELTA_DEPTH);
    set (DEPTH, 500);
    set (DEPTH, 600);
    set (DEPTH, 750);

    t.restart();
    while (t.get_time() < 6) {
        set (SPEED, 10);
    }
    set (SPEED, 0);
/*
    while (1) {
        IplImage* frame = image_input->get_image(DWN_IMG);
        if (!frame) {
            ret_code = TASK_ERROR;
            break;
        }
        MDA_VISION_RETURN_CODE vision_code = path_vision.filter(frame);

        // clear fwd image
        image_input->ready_image(FWD_IMG);

        if (vision_code == FULL_DETECT) {
            // Get path out of vision
            move(FORWARD, 1);
            // Reset back to 0
            images_checked = 0;
        } else {
            images_checked++;
            if (images_checked >= num_images_to_check) {
                done_skip = true;
                break;
            }
        }

        // Ensure debug messages are printed
        fflush(stdout);
        // Exit if instructed to
        char c = cvWaitKey(TASK_WK);
        if (c != -1) {
            CharacterStreamSingleton::get_instance().write_char(c);
        }
        if (CharacterStreamSingleton::get_instance().wait_key(1) == 'q'){
            ret_code = TASK_QUIT;
            break;
        }
    }
*/
    stop();

    if(done_skip){
        ret_code = TASK_DONE;
    }

    return ret_code;
}
Exemple #26
0
MDA_TASK_RETURN_CODE MDA_TASK_GATE:: run_task() {
    puts("Press q to quit");

    MDA_VISION_MODULE_GATE gate_vision;
    TASK_STATE state = STARTING;

    bool done_gate = false;
    MDA_TASK_RETURN_CODE ret_code = TASK_MISSING;

    // read the starting orientation
    int starting_yaw = attitude_input->yaw();
    printf("Starting yaw: %d\n", starting_yaw);
    
    MDA_TASK_BASE::starting_depth = attitude_input->depth();
    // gate depth
    set (DEPTH, HARDCODED_DEPTH-50/*MDA_TASK_BASE::starting_depth+GATE_DELTA_DEPTH*/);
    set (DEPTH, HARDCODED_DEPTH/*MDA_TASK_BASE::starting_depth+GATE_DELTA_DEPTH*/);

    // go to the starting orientation in case sinking changed it
    set (YAW, starting_yaw);

    static TIMER timer; // keeps track of time spent in each state
    static TIMER master_timer; // keeps track of time spent not having found the target
    static TIMER full_detect_timer; // keeps track of time since the last full detect
    timer.restart();
    master_timer.restart();
    full_detect_timer.restart();

    while (1) {
        IplImage* frame = image_input->get_image();
        if (!frame) {
            ret_code = TASK_ERROR;
            break;
        }
        MDA_VISION_RETURN_CODE vision_code = gate_vision.filter(frame);

        // clear dwn image. RZ - do we need this?
        // This ensures the other camera is properly logged
        // and that the webcam cache is cleared so it stays in sync - VZ
        image_input->ready_image(DWN_IMG);

        // static
        //static int prev_t = -1;

        /**
        * Basic Algorithm: (repeat)
        *  - Go straight foward in STARTING state until we see anything
        *  
        *    - If we saw a ONE_SEGMENT, calculate the course we should take to allow the segment to remain in view.
        *    - If we saw a FULL_DETECT, change course to face it
        *  - Always go forwards in increments and stop for 1 seconds to stare each time.
        */
        if (!done_gate) {
            if (state == STARTING) {
                printf ("Starting: Moving Foward at High Speed\n");
                set (SPEED, 9);

                if (master_timer.get_time() > MASTER_TIMEOUT) {
                    printf ("Master Timer Timeout!!\n");
                    return TASK_MISSING;
                }
                else if (vision_code == FULL_DETECT) {
                    printf ("FAST Foward: Full Detect\n");
                    //int ang_x = gate_vision.get_angular_x();
                    //set_yaw_change(ang_x);

                    if (gate_vision.get_range() < 420) {
                        done_gate = true;
                        printf ("Range = %d, Approaching Gate\n", gate_vision.get_range());
                    }

                    timer.restart();
                    full_detect_timer.restart();
                    master_timer.restart();
                }
                /*if (gate_vision.latest_frame_is_valid()) {
                    set (SPEED, 0);
                    master_timer.restart();
                    timer.restart();
                    gate_vision.clear_frames();
                    state = SLOW_FOWARD;
                }*/
            }
            else if (state == SLOW_FOWARD) {
                printf ("Slow Foward: Moving foward a little\n");
                set (SPEED, 4);

                if (timer.get_time() > 3) {
                    timer.restart();
                    gate_vision.clear_frames();
                    state = PANNING;
                }
                else if (vision_code == FULL_DETECT) {
                    printf ("Slow Foward: Full Detect\n");
                    int ang_x = gate_vision.get_angular_x();
                    set_yaw_change(ang_x);

                    if (gate_vision.get_range() < 420) {
                        done_gate = true;
                        printf ("Range = %d, Approaching Gate\n", gate_vision.get_range());
                    }

                    timer.restart();
                    full_detect_timer.restart();
                    master_timer.restart();
                }
                if (master_timer.get_time() > MASTER_TIMEOUT) {
                    printf ("Master Timer Timeout!!\n");
                    return TASK_MISSING;
                }
            }
            else if (state == STOPPED) {
                // if havent spent 1 second in this state, keep staring
                /*if (timer.get_time() < 1) {
                    printf ("Stopped: Collecting Frames\n");
                }
                else {*/
                    if (vision_code == NO_TARGET) {
                        printf ("Stopped: No target\n");
                        if (master_timer.get_time() > 60) { // we've seen nothing for 60 seconds
                            printf ("Master Timer Timeout!!\n");
                            return TASK_MISSING;
                        }
                        if (timer.get_time() > 3) {
                            printf ("Stopped: Timeout\n");
                            timer.restart();
                            state = SLOW_FOWARD;
                        }
                    }
                    else if (vision_code == ONE_SEGMENT) {
                        printf ("Stopped: One Segment\n");
                        //int ang_x = gate_vision.get_angular_x();

                        // if segment too close just finish
                        if (gate_vision.get_range() < 240) {
                            printf ("One Segment with range too low. Ending task.\n");
                            done_gate = true;
                        }
                        else if (gate_vision.get_range() < 470 && full_detect_timer.get_time() > 10) {
                            timer.restart();
                            master_timer.restart();
                            //prev_t = -1;
                            //state = PANNING;
                        }
                        // only execute turn if the segment is close to out of view and no other options
                        /*else if (ang_x >= 40) {
                            ang_x -= 20;
                            printf ("Moving Left on One Segment %d Degrees\n", ang_x);
                            move (RIGHT, ang_x);
                            gate_vision.clear_frames();
                        }
                        else if (ang_x <= -40) {
                            ang_x += 20;
                            printf ("Moving Left on One Segment %d Degrees\n", ang_x);
                            move (RIGHT, ang_x);
                            gate_vision.clear_frames();
                        }*/

                        if (timer.get_time() > 2) {
                            timer.restart();
                            master_timer.restart();
                            state = SLOW_FOWARD;
                        }
                    }
                    else if (vision_code == FULL_DETECT) {
                        printf ("Stopped: Full Detect\n");
                        int ang_x = gate_vision.get_angular_x();
                        move (RIGHT, ang_x);

                        if (gate_vision.get_range() < 420) {
                            done_gate = true;
                            printf ("Range = %d, Approaching Gate\n", gate_vision.get_range());
                        }

                        timer.restart();
                        full_detect_timer.restart();
                        master_timer.restart();
                        state = SLOW_FOWARD;
                    }
                    else {
                        printf ("Error: %s: line %d\ntask module recieved an unhandled vision code.\n", __FILE__, __LINE__);
                        exit(1);
                    }
                //} // collecting frames
            } // state
            else if (state == PANNING) { // pan and look for a frame with 2 segments
                /*printf ("Panning\n");
                int t = timer.get_time();
                if (t < PAN_TIME_HALF && t != prev_t) { // pan left for first 6 secs
                    set_yaw_change (-20);
                    prev_t = timer.get_time();
                }
                else if (t < 3*PAN_TIME_HALF && t != prev_t) { // pan right for next 10 secs
                    set_yaw_change (20);
                    prev_t = timer.get_time();
                }
                else if (t >= 3*PAN_TIME_HALF) { // stop pan and reset
                    printf ("Pan completed\n");
                    set (YAW, starting_yaw);
                    gate_vision.clear_frames();
                    master_timer.restart();
                    timer.restart();
                    state = STOPPED;
                }
                else if (gate_vision.latest_frame_is_two_segment()) {
                    printf ("Two segment frame found - stopping pan\n");
                    set_yaw_change (0);
                    gate_vision.clear_frames();
                    master_timer.restart();
                    full_detect_timer.restart();
                    timer.restart();
                    state = STOPPED;
                }*/
            }
            else if (state == APPROACH) {
            }
        } // done_gate
        else {
            // charge foward for 2 secs
            //set(YAW, starting_yaw);
            timer.restart();
            while (timer.get_time() < 2) {
                set(SPEED, 6);
            }
            set(SPEED, 0);
            printf ("Gate Task Done!!\n");
            return TASK_DONE;
        }

        // Ensure debug messages are printed
        fflush(stdout);
        // Exit if instructed to
        char c = cvWaitKey(TASK_WK);
        if (c != -1) {
            CharacterStreamSingleton::get_instance().write_char(c);
        }
        if (CharacterStreamSingleton::get_instance().wait_key(1) == 'q'){
            stop();
            ret_code = TASK_QUIT;
            break;
        }
    }

    return ret_code;
}
Exemple #27
0
//Called to draw scene
void Display(void)
{
	//angle of spheres in scene. Calculate from time
	float angle=timer.GetTime()/10;	



	//First pass - from light's point of view
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	
	glMatrixMode(GL_PROJECTION);
	glLoadMatrixf(lightProjectionMatrix);

	glMatrixMode(GL_MODELVIEW);
	glLoadMatrixf(lightViewMatrix);

	//Use viewport the same size as the shadow map
	glViewport(0, 0, shadowMapSize, shadowMapSize);

	//Draw back faces into the shadow map
	glCullFace(GL_FRONT);

	//Disable color writes, and use flat shading for speed
	glShadeModel(GL_FLAT);
	glColorMask(0, 0, 0, 0);
	
	//Draw the scene
	DrawScene(angle);

	//Read the depth buffer into the shadow map texture
	glBindTexture(GL_TEXTURE_2D, shadowMapTexture);
	glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, shadowMapSize, shadowMapSize);

	//restore states
	glCullFace(GL_BACK);
	glShadeModel(GL_SMOOTH);
	glColorMask(1, 1, 1, 1);
	

	

	//2nd pass - Draw from camera's point of view
	glClear(GL_DEPTH_BUFFER_BIT);

	glMatrixMode(GL_PROJECTION);
	glLoadMatrixf(cameraProjectionMatrix);
	
	glMatrixMode(GL_MODELVIEW);
	glLoadMatrixf(cameraViewMatrix);

	glViewport(0, 0, windowWidth, windowHeight);

	//Use dim light to represent shadowed areas
	glLightfv(GL_LIGHT1, GL_POSITION, VECTOR4D(lightPosition));
	glLightfv(GL_LIGHT1, GL_AMBIENT, white*0.2f);
	glLightfv(GL_LIGHT1, GL_DIFFUSE, white*0.2f);
	glLightfv(GL_LIGHT1, GL_SPECULAR, black);
	glEnable(GL_LIGHT1);
	glEnable(GL_LIGHTING);

	DrawScene(angle);
	


	//3rd pass
	//Draw with bright light
	glLightfv(GL_LIGHT1, GL_DIFFUSE, white);
	glLightfv(GL_LIGHT1, GL_SPECULAR, white);

	//Calculate texture matrix for projection
	//This matrix takes us from eye space to the light's clip space
	//It is postmultiplied by the inverse of the current view matrix when specifying texgen
	static MATRIX4X4 biasMatrix(0.5f, 0.0f, 0.0f, 0.0f,
								0.0f, 0.5f, 0.0f, 0.0f,
								0.0f, 0.0f, 0.5f, 0.0f,
								0.5f, 0.5f, 0.5f, 1.0f);	//bias from [-1, 1] to [0, 1]
	MATRIX4X4 textureMatrix=biasMatrix*lightProjectionMatrix*lightViewMatrix;
	//MATRIX4X4 textureMatrix=lightProjectionMatrix*lightViewMatrix;
	//Set up texture coordinate generation.
	glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
	glTexGenfv(GL_S, GL_EYE_PLANE, textureMatrix.GetRow(0));
	glEnable(GL_TEXTURE_GEN_S);

	glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
	glTexGenfv(GL_T, GL_EYE_PLANE, textureMatrix.GetRow(1));
	glEnable(GL_TEXTURE_GEN_T);

	glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
	glTexGenfv(GL_R, GL_EYE_PLANE, textureMatrix.GetRow(2));
	glEnable(GL_TEXTURE_GEN_R);

	glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
	glTexGenfv(GL_Q, GL_EYE_PLANE, textureMatrix.GetRow(3));
	glEnable(GL_TEXTURE_GEN_Q);

	//Bind & enable shadow map texture
	glBindTexture(GL_TEXTURE_2D, shadowMapTexture);
	glEnable(GL_TEXTURE_2D);

	//Enable shadow comparison
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE_ARB, GL_COMPARE_R_TO_TEXTURE);

	//Shadow comparison should be true (ie not in shadow) if r<=texture
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC_ARB, GL_LEQUAL);

	//Shadow comparison should generate an INTENSITY result
	glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE_ARB, GL_INTENSITY);

	//Set alpha test to discard false comparisons
	glAlphaFunc(GL_GEQUAL, 0.99f);
	glEnable(GL_ALPHA_TEST);

	DrawScene(angle);

	//Disable textures and texgen
	glDisable(GL_TEXTURE_2D);

	glDisable(GL_TEXTURE_GEN_S);
	glDisable(GL_TEXTURE_GEN_T);
	glDisable(GL_TEXTURE_GEN_R);
	glDisable(GL_TEXTURE_GEN_Q);

	//Restore other states
	glDisable(GL_LIGHTING);
	glDisable(GL_ALPHA_TEST);



	//Update frames per second counter
	fpsCounter.Update();

	//Print fps
	static char fpsString[32];
	sprintf(fpsString, "%.2f", fpsCounter.GetFps());
	
	//Set matrices for ortho
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	gluOrtho2D(-1.0f, 1.0f, -1.0f, 1.0f);

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();

	//Print text
	glRasterPos2f(-1.0f, 0.9f);
	for(unsigned int i=0; i<strlen(fpsString); ++i)
		glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, fpsString[i]);

	//reset matrices
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();

	glFinish();
	glutSwapBuffers();
	glutPostRedisplay();
}
Exemple #28
0
	virtual void execute(TIMER& timer){

		mpi_reduce_timers(timer); // Reduce timers to server master.

		// Print from the server master.
		if (SIPMPIAttr::get_instance().is_company_master()){

			std::cout << "Timers for Program " << GlobalState::get_program_name() << std::endl;

			long long * timers = timer.get_timers();
			long long * timer_counts = timer.get_timer_count();
			const int LW = 10;	// Line num
			const int CW = 15;	// Time
			const int SW = 20;	// String

			assert(timer.check_timers_off());
			std::cout<<"Timers"<<std::endl
				<<std::setw(LW)<<std::left<<"Line"
				<<std::setw(SW)<<std::left<<"Type"
				<<std::setw(CW)<<std::left<<"Avg"
				<<std::setw(CW)<<std::left<<"AvgBlkWait"
				<<std::setw(CW)<<std::left<<"AvgDiskRead"
				<<std::setw(CW)<<std::left<<"AvgDiskWrite"
				<<std::setw(CW)<<std::left<<"Tot"
				<<std::endl;

			for (int i=1; i<sialx_lines_; i++){

				int tot_time_offset = i + static_cast<int>(ServerTimer::TOTALTIME) * sialx_lines_;
				if (timer_counts[tot_time_offset] > 0L){
					double tot_time = timer.to_seconds(timers[tot_time_offset]);	// Microsecond to second
					double avg_time = tot_time / timer_counts[tot_time_offset];

					double tot_blk_wait = 0;
					double avg_blk_wait = 0;
					double tot_disk_read = 0;
					double avg_disk_read = 0;
					double tot_disk_write = 0;
					double avg_disk_write = 0;

					int blk_wait_offset = i + static_cast<int>(ServerTimer::BLOCKWAITTIME) * sialx_lines_;
					if (timer_counts[blk_wait_offset] > 0L){
						tot_blk_wait = timer.to_seconds(timers[blk_wait_offset]);
						avg_blk_wait = tot_blk_wait / timer_counts[blk_wait_offset];
					}

					int read_timer_offset = i + static_cast<int>(ServerTimer::READTIME) * sialx_lines_;
					if (timer_counts[read_timer_offset] > 0L){
						tot_disk_read = timer.to_seconds(timers[read_timer_offset]);
						avg_disk_read = tot_disk_read / timer_counts[read_timer_offset];
					}

					int write_timer_offset = i + static_cast<int>(ServerTimer::WRITETIME) * sialx_lines_;
					if (timer_counts[write_timer_offset] > 0L){
						tot_disk_write = timer.to_seconds(timers[write_timer_offset]);
						avg_disk_write = tot_disk_write / timer_counts[write_timer_offset];
					}

					std::cout<<std::setw(LW)<<std::left << i
							<< std::setw(SW)<< std::left << line_to_str_.at(i)
							<< std::setw(CW)<< std::left << avg_time
							<< std::setw(CW)<< std::left << avg_blk_wait
							<< std::setw(CW)<< std::left << avg_disk_read
							<< std::setw(CW)<< std::left << avg_disk_write
							<< std::setw(CW)<< std::left << tot_time
							<< std::endl;
				}
			}
			std::cout<<std::endl;
		}
	}
Exemple #29
0
//Called for initiation
bool Init(void)
{
	//Check for necessary extensions
	if(!GLEE_ARB_depth_texture || !GLEE_ARB_shadow)
	{
		printf("I require ARB_depth_texture and ARB_shadow extensionsn\n");
		return false;
	}
	
	//Load identity modelview
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	//Shading states
	glShadeModel(GL_SMOOTH);
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
	glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

	//Depth states
	glClearDepth(1.0f);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_DEPTH_TEST);

	glEnable(GL_CULL_FACE);

	//We use glScale when drawing the scene
	glEnable(GL_NORMALIZE);

	//Create the shadow map texture
	glGenTextures(1, &shadowMapTexture);
	glBindTexture(GL_TEXTURE_2D, shadowMapTexture);
	glTexImage2D(	GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, shadowMapSize, shadowMapSize, 0,
					GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);

	//Use the color as the ambient and diffuse material
	glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
	glEnable(GL_COLOR_MATERIAL);
	
	//White specular material color, shininess 16
	glMaterialfv(GL_FRONT, GL_SPECULAR, white);
	glMaterialf(GL_FRONT, GL_SHININESS, 16.0f);

	//Calculate & save matrices
	glPushMatrix();
	
	glLoadIdentity();
	gluPerspective(45.0f, (float)windowWidth/windowHeight, 1.0f, 100.0f);
	glGetFloatv(GL_MODELVIEW_MATRIX, cameraProjectionMatrix);
	
	glLoadIdentity();
	gluLookAt(cameraPosition.x, cameraPosition.y, cameraPosition.z,
				0.0f, 0.0f, 0.0f,
				0.0f, 1.0f, 0.0f);
	glGetFloatv(GL_MODELVIEW_MATRIX, cameraViewMatrix);
	
	glLoadIdentity();
	gluPerspective(45.0f, 1.0f, 2.0f, 8.0f);
	glGetFloatv(GL_MODELVIEW_MATRIX, lightProjectionMatrix);
	
	glLoadIdentity();
	gluLookAt(	lightPosition.x, lightPosition.y, lightPosition.z,
				0.0f, 0.0f, 0.0f,
				0.0f, 1.0f, 0.0f);
	glGetFloatv(GL_MODELVIEW_MATRIX, lightViewMatrix);
	
	glPopMatrix();

	//Reset timer
	timer.Reset();

	return true;
}
Exemple #30
0
BOOL PeekMessageEx (PMSG pMsg, HWND hWnd, int iMsgFilterMin, int iMsgFilterMax, 
                          BOOL bWait, UINT uRemoveMsg)
{
    PMSGQUEUE pMsgQueue;
    PQMSG phead;

    if (!pMsg || (hWnd != HWND_DESKTOP && !MG_IS_MAIN_WINDOW(hWnd)))
        return FALSE;

#ifndef _LITE_VERSION
    if (!(pMsgQueue = GetMsgQueueThisThread ()))
            return FALSE;
#else
    pMsgQueue = __mg_dsk_msg_queue;
#endif

    memset (pMsg, 0, sizeof(MSG));

checkagain:

    LOCK_MSGQ (pMsgQueue);

    if (pMsgQueue->dwState & QS_QUIT) {
        pMsg->hwnd = hWnd;
        pMsg->message = MSG_QUIT;
        pMsg->wParam = 0;
        pMsg->lParam = 0;
        SET_PADD (NULL);

        if (uRemoveMsg == PM_REMOVE) {
            pMsgQueue->loop_depth --;
            if (pMsgQueue->loop_depth == 0)
                pMsgQueue->dwState &= ~QS_QUIT;
        }
 
        UNLOCK_MSGQ (pMsgQueue);
        return FALSE;
    }

    /* Dealing with sync messages before notify messages is better ? */
#ifndef _LITE_VERSION
    if (pMsgQueue->dwState & QS_SYNCMSG) {
        if (pMsgQueue->pFirstSyncMsg) {
            *pMsg = pMsgQueue->pFirstSyncMsg->Msg;
            SET_PADD (pMsgQueue->pFirstSyncMsg);
            if (IS_MSG_WANTED(pMsg->message)) {
              if (uRemoveMsg == PM_REMOVE) {
                  pMsgQueue->pFirstSyncMsg = pMsgQueue->pFirstSyncMsg->pNext;
              }

              UNLOCK_MSGQ (pMsgQueue);
              return TRUE;
            }
        }
        else
            pMsgQueue->dwState &= ~QS_SYNCMSG;
    }
#endif

    if (pMsgQueue->dwState & QS_NOTIFYMSG) {
        if (pMsgQueue->pFirstNotifyMsg) {
            phead = pMsgQueue->pFirstNotifyMsg;
            *pMsg = phead->Msg;
            SET_PADD (NULL);

            if (IS_MSG_WANTED(pMsg->message)) {
              if (uRemoveMsg == PM_REMOVE) {
                  pMsgQueue->pFirstNotifyMsg = phead->next;
                  FreeQMSG (phead);
              }

              UNLOCK_MSGQ (pMsgQueue);
              return TRUE;
            }
        }
        else
            pMsgQueue->dwState &= ~QS_NOTIFYMSG;
    }

    if (pMsgQueue->dwState & QS_POSTMSG) {
        if (pMsgQueue->readpos != pMsgQueue->writepos) {
            *pMsg = pMsgQueue->msg[pMsgQueue->readpos];
            SET_PADD (NULL);
            if (IS_MSG_WANTED(pMsg->message)) {
                CheckCapturedMouseMessage (pMsg);
                if (uRemoveMsg == PM_REMOVE) {
                    pMsgQueue->readpos++;
                    if (pMsgQueue->readpos >= pMsgQueue->len)
                        pMsgQueue->readpos = 0;
                }

                UNLOCK_MSGQ (pMsgQueue);
                return TRUE;
            }
        }
        else
            pMsgQueue->dwState &= ~QS_POSTMSG;
    }

    /*
     * check invalidate region of the windows
     */

    if (pMsgQueue->dwState & QS_PAINT && IS_MSG_WANTED(MSG_PAINT)) {
        PMAINWIN pHostingRoot;
        HWND hNeedPaint;
        PMAINWIN pWin;
 
#ifndef _LITE_VERSION
        /* REMIND this */
        if (hWnd == HWND_DESKTOP) {
            pMsg->hwnd = hWnd;
            pMsg->message = MSG_PAINT;
            pMsg->wParam = 0;
            pMsg->lParam = 0;
            SET_PADD (NULL);

            if (uRemoveMsg == PM_REMOVE) {
                pMsgQueue->dwState &= ~QS_PAINT;
            }
            UNLOCK_MSGQ (pMsgQueue);
            return TRUE;
        }
#endif

        pMsg->message = MSG_PAINT;
        pMsg->wParam = 0;
        pMsg->lParam = 0;
        SET_PADD (NULL);

#ifdef _LITE_VERSION
        pHostingRoot = __mg_dsk_win;
#else
        pHostingRoot = pMsgQueue->pRootMainWin;
#endif

        if ( (hNeedPaint = msgCheckHostedTree (pHostingRoot)) ) {
            pMsg->hwnd = hNeedPaint;
            pWin = (PMAINWIN) hNeedPaint;
            pMsg->lParam = (LPARAM)(&pWin->InvRgn.rgn);
            UNLOCK_MSGQ (pMsgQueue);
            return TRUE;
        }
 
        /* no paint message */
        pMsgQueue->dwState &= ~QS_PAINT;
    }

    /*
     * handle timer here
     */
#ifdef _LITE_VERSION
    if (pMsgQueue->dwState & QS_DESKTIMER) {
        pMsg->hwnd = HWND_DESKTOP;
        pMsg->message = MSG_TIMER;
        pMsg->wParam = 0;
        pMsg->lParam = 0;

        if (uRemoveMsg == PM_REMOVE) {
            pMsgQueue->dwState &= ~QS_DESKTIMER;
        }
        return TRUE;
    }
#endif

    if (pMsgQueue->TimerMask && IS_MSG_WANTED(MSG_TIMER)) {
        int slot;
        TIMER* timer;

#ifndef _LITE_VERSION
        if (hWnd == HWND_DESKTOP) {
            pMsg->hwnd = hWnd;
            pMsg->message = MSG_TIMER;
            pMsg->wParam = 0;
            pMsg->lParam = 0;
            SET_PADD (NULL);

            if (uRemoveMsg == PM_REMOVE) {
                pMsgQueue->TimerMask = 0;
            }
            UNLOCK_MSGQ (pMsgQueue);
            return TRUE;
        }
#endif

        /* get the first expired timer slot */
        slot = pMsgQueue->FirstTimerSlot;
        do {
            if (pMsgQueue->TimerMask & (0x01 << slot))
                break;

            slot ++;
            slot %= DEF_NR_TIMERS;
            if (slot == pMsgQueue->FirstTimerSlot) {
                slot = -1;
                break;
            }
        } while (TRUE);

        pMsgQueue->FirstTimerSlot ++;
        pMsgQueue->FirstTimerSlot %= DEF_NR_TIMERS;

        if ((timer = __mg_get_timer (slot))) {

            unsigned int tick_count = timer->tick_count;

            timer->tick_count = 0;
            pMsgQueue->TimerMask &= ~(0x01 << slot);

            if (timer->proc) {
                BOOL ret_timer_proc;

                /* unlock the message queue when calling timer proc */
                UNLOCK_MSGQ (pMsgQueue);

                /* calling the timer callback procedure */
                ret_timer_proc = timer->proc (timer->hWnd, 
                        timer->id, tick_count);

                /* lock the message queue again */
                LOCK_MSGQ (pMsgQueue);

                if (!ret_timer_proc) {
                    /* remove the timer */
                    __mg_remove_timer (timer, slot);
                }
            }
            else {
                pMsg->message = MSG_TIMER;
                pMsg->hwnd = timer->hWnd;
                pMsg->wParam = timer->id;
                pMsg->lParam = tick_count;
                SET_PADD (NULL);

                UNLOCK_MSGQ (pMsgQueue);
                return TRUE;
            }
        }
    }

    UNLOCK_MSGQ (pMsgQueue);

#ifndef _LITE_VERSION
    if (bWait) {
        /* no message, wait again. */
        sem_wait (&pMsgQueue->wait);
        goto checkagain;
    }
#else
    /* no message, idle */
    if (bWait) {
         pMsgQueue->OnIdle (pMsgQueue);
         goto checkagain;
    }
#endif

    /* no message */
    return FALSE;
}