Exemplo n.º 1
0
    void RaceSelectionPreview::onSetup ()
    {
        mAnimation->play("idle", 1, Animation::Group_All, false, 1.0f, "start", "stop", 0.0f, 0);

        updateCamera();
    }
Exemplo n.º 2
0
void Game::onInit()
{
	m_factory.setResources(this);
	m_factory.setWorld(&m_world);
	m_factory.setGame(this);
	m_factory.init();

	m_background = loadTexture("textures/background.png");

	glGenFramebuffers(1, &m_lightFB);
	glGenTextures(1, &m_lightTexture);

	// Setup light texture

	glBindFramebuffer(GL_FRAMEBUFFER, m_lightFB);
	glBindTexture(GL_TEXTURE_2D, m_lightTexture);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 800, 600, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, m_lightTexture, 0);
	glBindTexture(GL_TEXTURE_2D, 0);
	glBindFramebuffer(GL_FRAMEBUFFER, 0);

	const float width = 800;
	const float height = 2400;

	// Light
	{
		std::unique_ptr<Entities::Light> light(m_factory.createLight());
		light->setActive(true);
		//light->setPos(b2Vec2(width*0.5f, 150));
		light->init();
		light->body()->SetTransform(worldToPhysics(b2Vec2(70, 200)), 0);
		m_defaultLight = light.get();
		m_renderables.push_back(std::unique_ptr<Renderable>(light.release()));
	}

	// Left
	{
		std::unique_ptr<Entities::Box> testBox(m_factory.createBricks(b2Vec2(60, height), true));
		testBox->body()->SetTransform(worldToPhysics(b2Vec2(0, height*0.5f)), 0);

		m_ground = testBox.get()->body().body();
		m_renderables.push_back(std::unique_ptr<Renderable>(testBox.release()));
	}
	
	// Right
	{
		std::unique_ptr<Entities::Box> testBox(m_factory.createBricks(b2Vec2(60, height), true));
		testBox->body()->SetTransform(worldToPhysics(b2Vec2(width, height*0.5f)), 0);
		m_renderables.push_back(std::unique_ptr<Renderable>(testBox.release()));
	}

	// Bottom
	{
		std::unique_ptr<Entities::Box> testBox(m_factory.createBricks(b2Vec2(width, 60), true));
		testBox->body()->SetTransform(worldToPhysics(b2Vec2(width*0.5f, height)), 0);
		m_renderables.push_back(std::unique_ptr<Renderable>(testBox.release()));
	}	

	// Light joint
	{
		b2DistanceJointDef jointDef;
		jointDef.Initialize(m_ground, m_defaultLight->body().body(),
							b2Vec2(0, m_defaultLight->body()->GetPosition().y),
							m_defaultLight->body()->GetPosition());
		jointDef.collideConnected = true;
		m_world.CreateJoint(&jointDef);
	}

	// Supports
	for(int i = 0; i < 20; i++)
	{
		std::unique_ptr<Entities::Box> testBox(m_factory.createHalfBricks(b2Vec2(200, 20)));
		testBox->body()->SetTransform(worldToPhysics(b2Vec2(-80, -40 - 40*i)), 0);

		b2MouseJointDef jointDef;
		jointDef.maxForce = 100;
		jointDef.collideConnected = true;
		jointDef.bodyA = m_ground;
		jointDef.bodyB = testBox->body().body();
		jointDef.target = testBox->body()->GetPosition();
		testBox->setDragJoint(m_world.CreateJoint(&jointDef));

		testBox->body()->SetFixedRotation(true);

		m_renderables.push_back(std::unique_ptr<Renderable>(testBox.release()));
	}

	// Boxes
	for(int i = 0; i < 500; i++)
	{
		int row = i / 3;
		int col = i % 3;

		int xoff = col - 1;

		float xmod = (row & 1) ? 0 : 30;

		b2Vec2 pos = worldToPhysics(b2Vec2(400 + xmod + xoff*55, row*-60));

		if(!(i % 36))
		{
			std::unique_ptr<Entities::Light> light(m_factory.createLight());
			light->setScale(0.3f);
			light->init();
			light->body()->SetTransform(pos, 0);
			m_renderables.push_back(std::unique_ptr<Renderable>(light.release()));
		}
		else if((rand() / float(RAND_MAX)) > 0.99f)
		{
			std::unique_ptr<Entities::Box> testBox(m_factory.createChest());
			testBox->body()->SetTransform(pos, 0);
			addRenderable(testBox.release());	
		}
		else
		{
			std::unique_ptr<Entities::Box> testBox(m_factory.createDirt());
			testBox->body()->SetTransform(pos, 0);
			addRenderable(testBox.release());
		}
	}

	updateCamera();

	for(int i = 0; i < 600; i++)
		m_world.Step(1/60.f, 6, 2);
}
Exemplo n.º 3
0
void Camera::setPosition(btVector3 position)
{
	m_bPositionChanged = true;
    this->m_position = position;
    updateCamera();
}
void	bulletBaseApp::mouseMotionFunc(int x,int y)
{
	
	if (m_pickConstraint)
	{
		//move the constraint pivot
		btPoint2PointConstraint* p2p = static_cast<btPoint2PointConstraint*>(m_pickConstraint);
		if (p2p)
		{
			//keep it at the same picking distance
			
			btVector3 newRayTo = getRayTo(x,y);
			btVector3 rayFrom;
			btVector3 oldPivotInB = p2p->getPivotInB();
			btVector3 newPivotB;
			if (m_ortho)
			{
				newPivotB = oldPivotInB;
				newPivotB.setX(newRayTo.getX());
				newPivotB.setY(newRayTo.getY());
			} else
			{
				rayFrom = m_cameraPosition;
				btVector3 dir = newRayTo-rayFrom;
				dir.normalize();
				dir *= gOldPickingDist;
				
				newPivotB = rayFrom + dir;
			}
			
			
			
			p2p->setPivotB(newPivotB);
		}
		
	}
	
	float dx, dy;
    dx = x - m_mouseOldX;
    dy = y - m_mouseOldY;
	
	
	///only if ALT key is pressed (Maya style)
	if (m_modifierKeys& BT_ACTIVE_ALT)
	{
		if(m_mouseButtons & 2)
		{
			btVector3 hor = getRayTo(0,0)-getRayTo(1,0);
			btVector3 vert = getRayTo(0,0)-getRayTo(0,1);
			btScalar multiplierX = 0.01;
			btScalar multiplierY = 0.01;
			if (m_ortho)
			{
				multiplierX = 1;
				multiplierY = 1;
			}
			
			
			m_cameraTargetPosition += hor* dx * multiplierX;
			m_cameraTargetPosition += vert* dy * multiplierY;
		}
		
		if(m_mouseButtons & (2 << 2) && m_mouseButtons & 1)
		{
		}
		else if(m_mouseButtons & 1) 
		{
			m_azi += dx * 0.2;
			m_azi = fmodf(m_azi, 180.f);
			m_ele += dy * 0.2;
			m_ele = fmodf(m_ele, 180.f);
		} 
		else if(m_mouseButtons & 4) 
		{
			m_cameraDistance -= dy * 0.2f;
			if (m_cameraDistance<0.1)
				m_cameraDistance = 0.1;
			
			
		} 
	}
	
	
	m_mouseOldX = x;
    m_mouseOldY = y;
	updateCamera();
	
	
}
Exemplo n.º 5
0
int main() {
	// INIT

	glfwSetErrorCallback( error_callback );

	/* Initialize the library */
	if ( !glfwInit() ) {
		return -1;
	}

	// must use exactly version 3
	glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 3 );
	glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 );
	glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
	glfwWindowHint( GLFW_RESIZABLE, GL_FALSE );

	/* Create a windowed mode window and its OpenGL context */
	window = glfwCreateWindow( WIDTH, HEIGHT, "Hello World", NULL, NULL );
	if ( !window ) {
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent( window );

	glfwSetKeyCallback( window, key_callback );
	//glfwSetCursorPosCallback(window, cursor_position_callback);
	glfwSetScrollCallback(window, scroll_callback);
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
	int count;
	//printf( "%s\n", glfwGetVideoModes( glfwGetPrimaryMonitor(), &count ) );

	glewExperimental = GL_TRUE;
	if( glewInit() != GLEW_OK ) {
		fprintf( stderr, "glewInit() failed\n" );
	}

	glViewport( 0, 0, WIDTH, HEIGHT );

	glClearColor( 0.2f, 0.3f, 0.3f, 1.0f );
	glEnable( GL_DEPTH_TEST );

	// SHADER
	Shader shader( "./vertexShader.glsl", "./fragmentShader.glsl" );







	// Set up vertex data (and buffer(s)) and attribute pointers
	GLfloat vertices[] = {
		-1.0f, -1.0f, -1.0f,  1.0f, 0.0f,
		-1.0f, -1.0f,  1.0f,  0.0f, 0.0f,
		-1.0f,  1.0f, -1.0f,  1.0f, 1.0f,
		-1.0f,  1.0f,  1.0f,  0.0f, 1.0f,
		 1.0f, -1.0f, -1.0f,  0.0f, 0.0f,
		 1.0f, -1.0f,  1.0f,  1.0f, 0.0f,
		 1.0f,  1.0f, -1.0f,  0.0f, 1.0f,
		 1.0f,  1.0f,  1.0f,  1.0f, 1.0f,
	};
    GLuint indices[] = {
		0, 1, 2,
		1, 2, 3,
		1, 3, 5,
		3, 5, 7,
		4, 5, 7,
		4, 6, 7,
		0, 4, 6,
		0, 2, 6,
		2, 3, 7,
		2, 6, 7,
		0, 1, 5,
		0, 4, 5
    };
	// vertex buffer object (VBO)
	// vertex array object (VAO)
	GLuint VAO, VBO, EBO;
	glGenVertexArrays( 1, &VAO );
	glGenBuffers( 1, &VBO );
	glGenBuffers( 1, &EBO );
	// BIND the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
	glBindVertexArray( VAO );
		glBindBuffer( GL_ARRAY_BUFFER, VBO );
		glBufferData( GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW );
		glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, EBO );
		glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW );

		// void glVertexAttribPointer( GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid * pointer);
		// the 0 for index comes from location = 0 in the vertex shader
		glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0 );
		glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)) );
		glEnableVertexAttribArray( 0 );
		glEnableVertexAttribArray( 1 );
	glBindVertexArray( 0 );








	stbi_set_flip_vertically_on_load(1);
	// TEXTURE
    GLuint texture;
    glGenTextures(1, &texture);
	//printf( "texture: %d\n", texture );
    glBindTexture(GL_TEXTURE_2D, texture); // All upcoming GL_TEXTURE_2D operations now have effect on our texture object
    // Set our texture parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);	// Set texture wrapping to GL_REPEAT
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // Set texture filtering
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // Load, create texture and generate mipmaps
    int width, height, comp;
    unsigned char* image = stbi_load("./images/container.jpg", &width, &height, &comp, 3);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    stbi_image_free(image);
    glBindTexture(GL_TEXTURE_2D, 0);


    GLuint texture1;
    glGenTextures(1, &texture1);
	//printf( "texture1: %d\n", texture1 );
    glBindTexture(GL_TEXTURE_2D, texture1);
    // Set our texture parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);	// Set texture wrapping to GL_REPEAT
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // Set texture filtering
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // Load, create texture and generate mipmaps
    image = stbi_load("./images/awesomeface.png", &width, &height, &comp, 3 );
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    stbi_image_free(image);
    glBindTexture(GL_TEXTURE_2D, 0);







	glm::mat4 projection;
	projection = glm::perspective( 45.0f, (GLfloat)WIDTH/HEIGHT, 0.1f, 100.0f );

	/*
	for( int y = 0; y < 4; ++y ) {
		for( int x = 0; x < 4; ++x ) {
			printf( "%f ", test[x][y] );
		}
		printf("\n");
	}
	*/

	// Game loop
	while( !glfwWindowShouldClose( window ) ) {
	//for( int iter = 1; iter; --iter ) {
		glfwPollEvents();
		glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );


		glActiveTexture( GL_TEXTURE0 );
		glBindTexture(GL_TEXTURE_2D, texture);
		glUniform1i( glGetUniformLocation(shader.Program, "texture"), 0 );

		glActiveTexture( GL_TEXTURE1 );
		glBindTexture(GL_TEXTURE_2D, texture1);
		glUniform1i( glGetUniformLocation(shader.Program, "texture1"), 1 );

		glUseProgram( shader.Program );


		glm::mat4 models[2];
		
		
		models[0] = glm::translate( models[0], glm::vec3( 4.0f, 4.0f, -10.0f ) );
		//models[1] = glm::translate( models[1], glm::vec3( -4.0f, -4.0f, -10.0f ) );
		models[1] = glm::scale( models[1], glm::vec3( 50.0f, 50.0f, 50.0f ) );

		updateCamera();
		//glm::mat4 rotatedView = camera[1] * camera[0] * view;
		printf( "rotation x %f, y %f, z %f\n", rotation.x, rotation.y, rotation.z );
		glm::mat4 rotatedView;
		rotatedView = glm::rotate( rotatedView, rotation.x, glm::vec3(1, 0, 0) ) ;
		rotatedView = glm::rotate( rotatedView, rotation.y, glm::vec3(0, 1, 0) ) ;
		rotatedView = glm::rotate( rotatedView, rotation.z, glm::vec3(0, 0, 1) ) ;
		rotatedView *= view;
		//view = glm::translate( view, position );
		//glm::mat4 rotatedView;
		
		//projection = glm::rotate( projection, glm::radians(cameraOrientation[1]), glm::vec3(1.0f, 0.0f, 0.0f) );
		//projection = glm::rotate( projection, glm::radians(cameraOrientation[0]), glm::vec3(0.0f, 1.0f, 0.0f) );
		//projection = projection * (cameraPosition / 10.0f);
		glUniformMatrix4fv( glGetUniformLocation(shader.Program, "view" ), 1, GL_FALSE, glm::value_ptr(rotatedView) );
		glUniformMatrix4fv( glGetUniformLocation(shader.Program, "projection" ), 1, GL_FALSE, glm::value_ptr(projection) );

		for( int numBoxes = 0; numBoxes < 3; ++numBoxes ) {
			glUniformMatrix4fv( glGetUniformLocation(shader.Program, "model" ), 1, GL_FALSE, glm::value_ptr(models[numBoxes]) );
			glBindVertexArray( VAO );
			//glDrawArrays( GL_TRIANGLES, 0, 3 );
			glDrawElements( GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0 );
			glBindVertexArray( 0 );
		}

		glfwSwapBuffers( window );
		fps();
		printf("\n");
	}

	glDeleteVertexArrays( 1, &VAO );
	glDeleteBuffers( 1, &VBO );

	glfwDestroyWindow( window );
	glfwTerminate();
	return 0;
}
void bulletBaseApp::stepRight() 
{ 
	m_azi += STEPSIZE; if (m_azi >= 360) m_azi -= 360; updateCamera(); 
}
void bulletBaseApp::stepBack() 
{ 
	m_ele -= STEPSIZE; if (m_ele < 0) m_ele += 360; updateCamera(); 
}
Exemplo n.º 8
0
void DemoApplication::renderme()
{
	myinit();

	updateCamera();

	if (m_dynamicsWorld)
	{			
		if(m_enableshadows)
		{
			glClear(GL_STENCIL_BUFFER_BIT);
			glEnable(GL_CULL_FACE);
			renderscene(0);

			glDisable(GL_LIGHTING);
			glDepthMask(GL_FALSE);
			glDepthFunc(GL_LEQUAL);
			glEnable(GL_STENCIL_TEST);
			glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE);
			glStencilFunc(GL_ALWAYS,1,0xFFFFFFFFL);
			glFrontFace(GL_CCW);
			glStencilOp(GL_KEEP,GL_KEEP,GL_INCR);
			renderscene(1);
			glFrontFace(GL_CW);
			glStencilOp(GL_KEEP,GL_KEEP,GL_DECR);
			renderscene(1);
			glFrontFace(GL_CCW);

			glPolygonMode(GL_FRONT,GL_FILL);
			glPolygonMode(GL_BACK,GL_FILL);
			glShadeModel(GL_SMOOTH);
			glEnable(GL_DEPTH_TEST);
			glDepthFunc(GL_LESS);
			glEnable(GL_LIGHTING);
			glDepthMask(GL_TRUE);
			glCullFace(GL_BACK);
			glFrontFace(GL_CCW);
			glEnable(GL_CULL_FACE);
			glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);

			glDepthFunc(GL_LEQUAL);
			glStencilFunc( GL_NOTEQUAL, 0, 0xFFFFFFFFL );
			glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
			glDisable(GL_LIGHTING);
			renderscene(2);
			glEnable(GL_LIGHTING);
			glDepthFunc(GL_LESS);
			glDisable(GL_STENCIL_TEST);
			glDisable(GL_CULL_FACE);
		}
		else
		{
			glDisable(GL_CULL_FACE);
			renderscene(0);
		}

		int	xOffset = 10;
		int yStart = 20;
		int yIncr = 20;


		glDisable(GL_LIGHTING);
		glColor3f(0, 0, 0);

		if ((m_debugMode & btIDebugDraw::DBG_NoHelpText)==0)
		{
			setOrthographicProjection();

			showProfileInfo(xOffset,yStart,yIncr);

#ifdef USE_QUICKPROF

		
			if ( getDebugMode() & btIDebugDraw::DBG_ProfileTimings)
			{
				static int counter = 0;
				counter++;
				std::map<std::string, hidden::ProfileBlock*>::iterator iter;
				for (iter = btProfiler::mProfileBlocks.begin(); iter != btProfiler::mProfileBlocks.end(); ++iter)
				{
					char blockTime[128];
					sprintf(blockTime, "%s: %lf",&((*iter).first[0]),btProfiler::getBlockTime((*iter).first, btProfiler::BLOCK_CYCLE_SECONDS));//BLOCK_TOTAL_PERCENT));
					glRasterPos3f(xOffset,yStart,0);
					GLDebugDrawString(BMF_GetFont(BMF_kHelvetica10),blockTime);
					yStart += yIncr;

				}

			}
#endif //USE_QUICKPROF


			

			resetPerspectiveProjection();
		}

		glEnable(GL_LIGHTING);


	}

	updateCamera();

}
Exemplo n.º 9
0
void DemoApplication::stepLeft() 
{ 
	m_azi -= STEPSIZE; if (m_azi < 0) m_azi += 360; updateCamera(); 
}
Exemplo n.º 10
0
void DemoApplication::zoomOut() 
{ 
	m_cameraDistance += btScalar(m_zoomStepSize); updateCamera(); 

}
Exemplo n.º 11
0
void Raytracer::displayCallback() 
{

	updateCamera();

	for (int i=0;i<numObjects;i++)
	{
		transforms[i].setIdentity();
		btVector3	pos(0.f,0.f,-(2.5* numObjects * 0.5)+i*2.5f);
		transforms[i].setOrigin( pos );
		btQuaternion orn;
		if (i < 2)
		{
			orn.setEuler(yaw,pitch,roll);
			transforms[i].setRotation(orn);
		}
	}

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); 
	glDisable(GL_LIGHTING);
	if (!m_initialized)
	{
		m_initialized = true;
		glGenTextures(1, &glTextureId);
	}
	
	glBindTexture(GL_TEXTURE_2D,glTextureId );
	
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	
	glDisable(GL_TEXTURE_2D);
	glDisable(GL_BLEND);


	btVector4 rgba(1.f,0.f,0.f,0.5f);

	float top = 1.f;
	float bottom = -1.f;
	float nearPlane = 1.f;

	float tanFov = (top-bottom)*0.5f / nearPlane;

	float fov = 2.0 * atanf (tanFov);


	btVector3	rayFrom = getCameraPosition();
	btVector3 rayForward = getCameraTargetPosition()-getCameraPosition();
	rayForward.normalize();
	float farPlane = 600.f;
	rayForward*= farPlane;

	btVector3 rightOffset;
	btVector3 vertical(0.f,1.f,0.f);
	btVector3 hor;
	hor = rayForward.cross(vertical);
	hor.normalize();
	vertical = hor.cross(rayForward);
	vertical.normalize();

	float tanfov = tanf(0.5f*fov);

	hor *= 2.f * farPlane * tanfov;
	vertical *= 2.f * farPlane * tanfov;

	btVector3 rayToCenter = rayFrom + rayForward;

	btVector3 dHor = hor * 1.f/float(screenWidth);
	btVector3 dVert = vertical * 1.f/float(screenHeight);

	btTransform rayFromTrans;
	rayFromTrans.setIdentity();
	rayFromTrans.setOrigin(rayFrom);

	btTransform rayFromLocal;
	btTransform	rayToLocal;




	int x;

	///clear texture
	for (x=0;x<screenWidth;x++)
	{
		for (int y=0;y<screenHeight;y++)
		{
			btVector4 rgba(0.2f,0.2f,0.2f,1.f);
			raytracePicture->setPixel(x,y,rgba);
		}
	}

#if 1
	btVector3 rayTo;
	btTransform colObjWorldTransform;
	colObjWorldTransform.setIdentity();

	int	mode = 0;

	for (x=0;x<screenWidth;x++)
	{
		for (int y=0;y<screenHeight;y++)
		{

			rayTo = rayToCenter - 0.5f * hor + 0.5f * vertical;
			rayTo += x * dHor;
			rayTo -= y * dVert;
			btVector3	worldNormal(0,0,0);
			btVector3	worldPoint(0,0,0);



			bool hasHit = false;
			int mode = 0;
			switch (mode)
			{
			case 0:
				hasHit = lowlevelRaytest(rayFrom,rayTo,worldNormal,worldPoint);
				break;
			case 1:
				hasHit = singleObjectRaytest(rayFrom,rayTo,worldNormal,worldPoint);
				break;
			case 2:
				hasHit = worldRaytest(rayFrom,rayTo,worldNormal,worldPoint);
				break;
			default:
				{
				}
			}

			if (hasHit)
			{
				float lightVec0 = worldNormal.dot(btVector3(0,-1,-1));//0.4f,-1.f,-0.4f));
				float lightVec1= worldNormal.dot(btVector3(-1,0,-1));//-0.4f,-1.f,-0.4f));


				rgba = btVector4(lightVec0,lightVec1,0,1.f);
				rgba.setMin(btVector3(1,1,1));
				rgba.setMax(btVector3(0.2,0.2,0.2));
				rgba[3] = 1.f;
				raytracePicture->setPixel(x,y,rgba);
			} else
				btVector4 rgba = raytracePicture->getPixel(x,y);
			if (!rgba.length2())
			{
				raytracePicture->setPixel(x,y,btVector4(1,1,1,1));
			}
		}
	}
#endif

extern unsigned char sFontData[];
	if (0)
	{

		char* text="ABC abc 123 !@#";
			int x=0;
		for (int cc = 0;cc<strlen(text);cc++)
		{
		
			char testChar = text[cc];//'b';
			char ch = testChar-32;
			int startx=ch%16;
			int starty=ch/16;


			//for (int i=0;i<256;i++)
			for (int i=startx*16;i<(startx*16+16);i++)
			{
				int y=0;
				//for (int j=0;j<256;j++)
				//for (int j=0;j<256;j++)
				for (int j=starty*16;j<(starty*16+16);j++)
				{
					
					btVector4 rgba(0,0,0,1);
					rgba[0] = (sFontData[i*3+255*256*3-(256*j)*3])/255.f;
					//rgba[0] += (sFontData[(i+1)*3+255*256*3-(256*j)*3])/255.*0.25f;
					//rgba[0] += (sFontData[(i)*3+255*256*3-(256*j+1)*3])/255.*0.25f;
					//rgba[0] += (sFontData[(i+1)*3+255*256*3-(256*j+1)*3])/255.*0.25;

					//if (rgba[0]!=0.f)
					{
						rgba[1]=rgba[0];
						rgba[2]=rgba[0];
						rgba[3]=1.f;

						//raytracePicture->setPixel(x,y,rgba);
						raytracePicture->addPixel(x,y,rgba);
					}
					y++;
				}
				x++;
			}
		}
	}


	//raytracePicture->grapicalPrintf("CCD RAYTRACER",sFontData);
	char buffer[256];
	sprintf(buffer,"%d rays",screenWidth*screenHeight*numObjects);
	//sprintf(buffer,"Toggle",screenWidth*screenHeight*numObjects);
	//sprintf(buffer,"TEST",screenWidth*screenHeight*numObjects);
	//raytracePicture->grapicalPrintf(buffer,sFontData,0,10);//&BMF_font_helv10,0,10);
	raytracePicture->grapicalPrintf(buffer,sFontData,0,0);//&BMF_font_helv10,0,10);


	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	glFrustum(-1.0,1.0,-1.0,1.0,3,2020.0);

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();									// reset The Modelview Matrix
	glTranslatef(0.0f,0.0f,-3.1f);						// Move Into The Screen 5 Units



	glEnable(GL_TEXTURE_2D);
	glBindTexture(GL_TEXTURE_2D,glTextureId );

	const unsigned char *ptr = raytracePicture->getBuffer();
	glTexImage2D(GL_TEXTURE_2D, 
		0, 
		GL_RGBA, 
		raytracePicture->getWidth(),raytracePicture->getHeight(), 
		0, 
		GL_RGBA, 
		GL_UNSIGNED_BYTE, 
		ptr);


	glEnable (GL_BLEND);
	glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glColor4f (1,1,1,1); // alpha=0.5=half visible

	glBegin(GL_QUADS);
	glTexCoord2f(0.0f, 0.0f);
	glVertex2f(-1,1);
	glTexCoord2f(1.0f, 0.0f);
	glVertex2f(1,1);
	glTexCoord2f(1.0f, 1.0f);
	glVertex2f(1,-1);
	glTexCoord2f(0.0f, 1.0f);
	glVertex2f(-1,-1);
	glEnd();



	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);


	glDisable(GL_TEXTURE_2D);
	glDisable(GL_DEPTH_TEST);

	GL_ShapeDrawer::drawCoordSystem();



	{
		for (int i=0;i<numObjects;i++)
		{
			btVector3 aabbMin,aabbMax;
			shapePtr[i]->getAabb(transforms[i],aabbMin,aabbMax);
		}
	}

	glPushMatrix();




	glPopMatrix();

	pitch += 0.005f;
	yaw += 0.01f;
	m_azi += 1.f;

	glFlush();
	glutSwapBuffers();
}
Exemplo n.º 12
0
bool SceneService::onInit()
{
    _scene.reset(gameplay::Scene::create());
    _scene->setAmbientColor(0.1f, 0.1f, 0.1f);

    _camera.reset(gameplay::Camera::createPerspective(30.0f, gameplay::Game::getInstance()->getAspectRatio(), 5.0f, 30.0f));
    _scene->setActiveCamera(_camera.get());

    _light.reset(gameplay::Light::createDirectional(0.9f, 0.9f, 0.9f));

    gameplay::Node * cameraNode = _scene->addNode("Camera");
    cameraNode->setCamera(_camera.get());

    gameplay::Node * lightNode = _scene->addNode("Light");
    lightNode->setLight(_light);
    lightNode->setRotation(gameplay::Vector3(1.0f, 0.0f, 0.0f), -MATH_PIOVER4);

    ServiceManager::getInstance()->signals.inputTouchEvent.connect(10, sigc::mem_fun(this, &SceneService::onTouchEvent));
    ServiceManager::getInstance()->signals.inputMouseEvent.connect(10, sigc::mem_fun(this, &SceneService::onMouseEvent));
    ServiceManager::getInstance()->signals.inputGesturePinchEvent.connect(10, sigc::mem_fun(this, &SceneService::onGesturePinchEvent));

    getSettings()->sidebarWidthChangedSignal.connect(sigc::mem_fun(this, &SceneService::onSidebarWidthChanged));

    _renderService = _manager->findService<RenderService>();

    gameplay::Game::getInstance()->registerGesture(gameplay::Gesture::GESTURE_PINCH);

    PrimitivesPool::getInstance()->generatePrimitives();

    _moleculeModel.reset(MoleculeModel::create(getSettings()->getMolecule()));
    insertNode(_moleculeModel->getRootNode());
    _moleculeModel->modelChangedSignal.connect(sigc::mem_fun(this, &SceneService::moleculeChanged));

    updateCamera();
    _lastTime = static_cast< float >(gameplay::Game::getInstance()->getGameTime() * 0.001f);

    float vpwidth = static_cast<float>(gameplay::Game::getInstance()->getWidth());
    float vpheight = static_cast<float>(gameplay::Game::getInstance()->getHeight());
    float sidebarWidth = getSettings()->getSidebarWidth();
    _camera->setAspectRatio((vpwidth - sidebarWidth) / vpheight);

    gameplay::Vector3 axisX[] = { gameplay::Vector3::zero(), gameplay::Vector3::unitX() };
    gameplay::Vector3 axisY[] = { gameplay::Vector3::zero(), gameplay::Vector3::unitY() };
    gameplay::Vector3 axisZ[] = { gameplay::Vector3::zero(), gameplay::Vector3::unitZ() };
    gameplay::Mesh * axisXMesh = gameplay::Mesh::createLines(axisX, 2);
    gameplay::Mesh * axisYMesh = gameplay::Mesh::createLines(axisY, 2);
    gameplay::Mesh * axisZMesh = gameplay::Mesh::createLines(axisZ, 2);
    _axisXModel.reset(gameplay::Model::create(axisXMesh));
    _axisYModel.reset(gameplay::Model::create(axisYMesh));
    _axisZModel.reset(gameplay::Model::create(axisZMesh));
    _axisXModel->setMaterial("materials/models/line.material");
    _axisYModel->setMaterial("materials/models/line.material");
    _axisZModel->setMaterial("materials/models/line.material");
    _axisXModel->getMaterial()->getParameter("u_modulateColor")->setVector4(gameplay::Vector4(1.0f, 0.0f, 0.0f, 1.0f));
    _axisYModel->getMaterial()->getParameter("u_modulateColor")->setVector4(gameplay::Vector4(0.0f, 1.0f, 0.0f, 1.0f));
    _axisZModel->getMaterial()->getParameter("u_modulateColor")->setVector4(gameplay::Vector4(0.0f, 0.0f, 1.0f, 1.0f));
    SAFE_RELEASE(axisXMesh);
    SAFE_RELEASE(axisYMesh);
    SAFE_RELEASE(axisZMesh);

    gameplay::Node * axisXNode = _scene->addNode("AxisX");
    gameplay::Node * axisYNode = _scene->addNode("AxisY");
    gameplay::Node * axisZNode = _scene->addNode("AxisZ");
    axisXNode->setDrawable(_axisXModel.get());
    axisYNode->setDrawable(_axisYModel.get());
    axisZNode->setDrawable(_axisZModel.get());

    return true;
}
Exemplo n.º 13
0
void updateFunc(const timeStruct_t time, const inputStruct_t input)
{
	updateSampleMesh(time, input);

	updateCamera(input);
}
Exemplo n.º 14
0
PclCameraWrapper::PclCameraWrapper(const pcl::visualization::Camera &camera)
{
    updateCamera(camera);
}
void bulletBaseApp::renderme()
{
	myinit();
	
	updateCamera();
	
	if (m_dynamicsWorld)
	{			
		if(m_enableshadows)
		{
			glClear(GL_STENCIL_BUFFER_BIT);
			glEnable(GL_CULL_FACE);
			renderscene(0);
			
			glDisable(GL_LIGHTING);
			glDepthMask(GL_FALSE);
			glDepthFunc(GL_LEQUAL);
			glEnable(GL_STENCIL_TEST);
			glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE);
			glStencilFunc(GL_ALWAYS,1,0xFFFFFFFFL);
			glFrontFace(GL_CCW);
			glStencilOp(GL_KEEP,GL_KEEP,GL_INCR);
			renderscene(1);
			glFrontFace(GL_CW);
			glStencilOp(GL_KEEP,GL_KEEP,GL_DECR);
			renderscene(1);
			glFrontFace(GL_CCW);
			
			glPolygonMode(GL_FRONT,GL_FILL);
			glPolygonMode(GL_BACK,GL_FILL);
			glShadeModel(GL_SMOOTH);
			glEnable(GL_DEPTH_TEST);
			glDepthFunc(GL_LESS);
			glEnable(GL_LIGHTING);
			glDepthMask(GL_TRUE);
			glCullFace(GL_BACK);
			glFrontFace(GL_CCW);
			glEnable(GL_CULL_FACE);
			glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);
			
			glDepthFunc(GL_LEQUAL);
			glStencilFunc( GL_NOTEQUAL, 0, 0xFFFFFFFFL );
			glStencilOp( GL_KEEP, GL_KEEP, GL_KEEP );
			glDisable(GL_LIGHTING);
			renderscene(2);
			glEnable(GL_LIGHTING);
			glDepthFunc(GL_LESS);
			glDisable(GL_STENCIL_TEST);
			glDisable(GL_CULL_FACE);
		}
		else
		{
			glDisable(GL_CULL_FACE);
			renderscene(0);
		}
		
		int	xOffset = 10;
		int yStart = 20;
		int yIncr = 20;
		char buf[124];
		
		glDisable(GL_LIGHTING);
		glColor3f(0, 0, 0);
		
		if ((m_debugMode & btIDebugDraw::DBG_NoHelpText)==0)
		{
			setOrthographicProjection();
			
			showProfileInfo(xOffset,yStart,yIncr);
			
#ifdef USE_QUICKPROF
			
			
			if ( getDebugMode() & btIDebugDraw::DBG_ProfileTimings)
			{
				static int counter = 0;
				counter++;
				std::map<std::string, hidden::ProfileBlock*>::iterator iter;
				for (iter = btProfiler::mProfileBlocks.begin(); iter != btProfiler::mProfileBlocks.end(); ++iter)
				{
					char blockTime[128];
					sprintf(blockTime, "%s: %lf",&((*iter).first[0]),btProfiler::getBlockTime((*iter).first, btProfiler::BLOCK_CYCLE_SECONDS));//BLOCK_TOTAL_PERCENT));
					glRasterPos3f(xOffset,yStart,0);
					GLDebugDrawString(BMF_GetFont(BMF_kHelvetica10),blockTime);
					yStart += yIncr;
					
				}
				
			}
#endif //USE_QUICKPROF
			
			
			sprintf(buf,"mouse to interact");
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			sprintf(buf,"ALT + mouse to move camera");
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			sprintf(buf,"space to reset");
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			sprintf(buf,"cursor keys and z,x to navigate");
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			sprintf(buf,"i to toggle simulation, s single step");
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			sprintf(buf,"q to quit");
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			sprintf(buf,". to shoot box");
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			// not yet hooked up again after refactoring...
			
			sprintf(buf,"d to toggle deactivation");
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			
			sprintf(buf,"g to toggle mesh animation (ConcaveDemo)");
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			
			sprintf(buf,"h to toggle help text");
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			sprintf(buf,"o to toggle orthogonal/perspective view");
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			
			//bool useBulletLCP = !(getDebugMode() & btIDebugDraw::DBG_DisableBulletLCP);
			//bool useCCD = (getDebugMode() & btIDebugDraw::DBG_EnableCCD);
			//glRasterPos3f(xOffset,yStart,0);
			//sprintf(buf,"1 CCD mode (adhoc) = %i",useCCD);
			//GLDebugDrawString(BMF_GetFont(BMF_kHelvetica10),buf);
			//yStart += yIncr;
			
			
			
			sprintf(buf,"+- shooting speed = %10.2f",m_ShootBoxInitialSpeed);
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
#ifdef SHOW_NUM_DEEP_PENETRATIONS
			
			
			sprintf(buf,"gNumDeepPenetrationChecks = %d",gNumDeepPenetrationChecks);
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			sprintf(buf,"gNumGjkChecks= %d",gNumGjkChecks);
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			sprintf(buf,"gNumClampedCcdMotions = %d",gNumClampedCcdMotions);
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			sprintf(buf,"gNumSplitImpulseRecoveries= %d",gNumSplitImpulseRecoveries);
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			sprintf(buf,"gNumAlignedAllocs = %d",gNumAlignedAllocs);
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			sprintf(buf,"gNumAlignedFree= %d",gNumAlignedFree);
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			sprintf(buf,"# alloc-free = %d",gNumAlignedAllocs-gNumAlignedFree);
			GLDebugDrawString(xOffset,yStart,buf);
			yStart += yIncr;
			
			//enable BT_DEBUG_MEMORY_ALLOCATIONS define in Bullet/src/LinearMath/btAlignedAllocator.h for memory leak detection
#ifdef BT_DEBUG_MEMORY_ALLOCATIONS
			glRasterPos3f(xOffset,yStart,0);
			sprintf(buf,"gTotalBytesAlignedAllocs = %d",gTotalBytesAlignedAllocs);
			GLDebugDrawString(BMF_GetFont(BMF_kHelvetica10),buf);
			yStart += yIncr;
#endif //BT_DEBUG_MEMORY_ALLOCATIONS
			
			if (getDynamicsWorld())
			{
				glRasterPos3f(xOffset,yStart,0);
				sprintf(buf,"# objects = %d",getDynamicsWorld()->getNumCollisionObjects());
				GLDebugDrawString(xOffset,yStart,buf);
				yStart += yIncr;
				glRasterPos3f(xOffset,yStart,0);
				sprintf(buf,"# pairs = %d",getDynamicsWorld()->getBroadphase()->getOverlappingPairCache()->getNumOverlappingPairs());
				GLDebugDrawString(xOffset,yStart,buf);
				yStart += yIncr;
				sprintf(buf,"# hitPos = %f,%f,%f",gHitPos.getX(),gHitPos.getY(),gHitPos.getZ());
				GLDebugDrawString(xOffset,yStart,buf);
				yStart += yIncr;
				
			}
			
			
#endif //SHOW_NUM_DEEP_PENETRATIONS
			
			resetPerspectiveProjection();
		}
		
		glEnable(GL_LIGHTING);
		
		
	}
	
	updateCamera();
	
}
Exemplo n.º 16
0
void DemoApplication::stepRight() 
{ 
	m_azi += STEPSIZE; if (m_azi >= 360) m_azi -= 360; updateCamera(); 
}
void bulletBaseApp::stepLeft() 
{ 
	m_azi -= STEPSIZE; if (m_azi < 0) m_azi += 360; updateCamera(); 
}
Exemplo n.º 18
0
void DemoApplication::stepFront() 
{ 
	m_ele += STEPSIZE; if (m_ele >= 360) m_ele -= 360; updateCamera(); 
}
void bulletBaseApp::stepFront() 
{ 
	m_ele += STEPSIZE; if (m_ele >= 360) m_ele -= 360; updateCamera(); 
}
Exemplo n.º 20
0
void DemoApplication::stepBack() 
{ 
	m_ele -= STEPSIZE; if (m_ele < 0) m_ele += 360; updateCamera(); 
}
void bulletBaseApp::zoomOut() 
{ 
	m_cameraDistance += 0.4; updateCamera(); 
	
}
Exemplo n.º 22
0
void DemoApplication::zoomOut() 
{ 
	m_cameraDistance += btScalar(0.4); updateCamera(); 

}
Exemplo n.º 23
0
void Gource::logic(float t, float dt) {

    if(draw_loading) return;

    if(message_timer>0.0f) message_timer -= dt;
    if(splash>0.0f)        splash -= dt;

    //init log file
    if(commitlog == 0) {

        try {

            commitlog = determineFormat(logfile);

        } catch(SeekLogException& exception) {
            throw SDLAppException("unable to read log file");
        }

        if(commitlog == 0) {
            //if not in a git dir and no log file, show help
            if(logfile.size() == 0 || logfile == ".") {
                SDL_Quit();
                throw SDLAppException("", true);
            } else if(SDLAppDirExists(logfile)) {
                throw SDLAppException("directory not supported");
            } else {
                throw SDLAppException("unsupported log format (you may need to regenerate your log file)");
            }
        }

        if(gGourceSettings.start_position>0.0) {
            seekTo(gGourceSettings.start_position);
        }
    }

    slider.logic(dt);

    //apply rotation
    if(rotate_angle != 0.0f) {

        float s = sinf(rotate_angle);
        float c = cosf(rotate_angle);

        root->rotate(s, c);

        for(std::map<std::string,RUser*>::iterator it = users.begin(); it!=users.end(); it++) {
            RUser* user = it->second;

            vec2f userpos = user->getPos();

            user->setPos(userpos.rotate(s, c));
        }

        rotate_angle = 0.0f;
    }

    //still want to update camera while paused
    if(paused) {
        updateBounds();
        updateQuadTree();
        updateCamera(dt);
        return;
    }

    // get more entries
    if(commitqueue.size() == 0) {
        readLog();
    }

    //loop in attempt to find commits
    if(commitqueue.size()==0 && commitlog->isSeekable() && gGourceSettings.loop) {
        first_read=true;
        seekTo(0.0);
        readLog();
    }

    if(currtime==0 && commitqueue.size()) {
        currtime   = lasttime = commitqueue[0].timestamp;
        subseconds = 0.0;
    }

    //set current time
    float time_inc = (dt * 86400.0 * gGourceSettings.days_per_second);
    int seconds    = (int) time_inc;

    subseconds += time_inc - ((float) seconds);

    if(subseconds >= 1.0) {
        currtime   += (int) subseconds;
        subseconds -= (int) subseconds;
    }

    currtime += seconds;

    // delete files
    for(std::vector<RFile*>::iterator it = gGourceRemovedFiles.begin(); it != gGourceRemovedFiles.end(); it++) {
        deleteFile(*it);
    }

    gGourceRemovedFiles.clear();


    //add commits up until the current time
    while(commitqueue.size() > 0) {

        RCommit commit = commitqueue[0];

        if(gGourceSettings.auto_skip_seconds>=0.0 && idle_time >= gGourceSettings.auto_skip_seconds) {
            currtime = lasttime = commit.timestamp;
            idle_time = 0.0;
        }

        if(commit.timestamp > currtime) break;

        processCommit(commit, t);

        currtime = lasttime = commit.timestamp;
        subseconds = 0.0;

        commitqueue.pop_front();
    }

    //reset loop counters
    gGourceUserInnerLoops = 0;
    gGourceDirNodeInnerLoops = 0;
    gGourceFileInnerLoops = 0;

    interactUsers();
    updateUsers(t, dt);

    updateQuadTree();
    updateBounds();
    updateDirs(dt);

    updateCamera(dt);

    updateTime(commitqueue.size() > 0 ? currtime : lasttime);
}
Exemplo n.º 24
0
void	DemoApplication::mouseMotionFunc(int x,int y)
{

	if (m_pickConstraint)
	{
		//move the constraint pivot

		if (m_pickConstraint->getConstraintType() == D6_CONSTRAINT_TYPE)
		{
			btGeneric6DofConstraint* pickCon = static_cast<btGeneric6DofConstraint*>(m_pickConstraint);
			if (pickCon)
			{
				//keep it at the same picking distance

				btVector3 newRayTo = getRayTo(x,y);
				btVector3 rayFrom;
				btVector3 oldPivotInB = pickCon->getFrameOffsetA().getOrigin();

				btVector3 newPivotB;
				if (m_ortho)
				{
					newPivotB = oldPivotInB;
					newPivotB.setX(newRayTo.getX());
					newPivotB.setY(newRayTo.getY());
				} else
				{
					rayFrom = m_cameraPosition;
					btVector3 dir = newRayTo-rayFrom;
					dir.normalize();
					dir *= gOldPickingDist;

					newPivotB = rayFrom + dir;
				}
				pickCon->getFrameOffsetA().setOrigin(newPivotB);
			}

		} else
		{
			btPoint2PointConstraint* pickCon = static_cast<btPoint2PointConstraint*>(m_pickConstraint);
			if (pickCon)
			{
				//keep it at the same picking distance

				btVector3 newRayTo = getRayTo(x,y);
				btVector3 rayFrom;
				btVector3 oldPivotInB = pickCon->getPivotInB();
				btVector3 newPivotB;
				if (m_ortho)
				{
					newPivotB = oldPivotInB;
					newPivotB.setX(newRayTo.getX());
					newPivotB.setY(newRayTo.getY());
				} else
				{
					rayFrom = m_cameraPosition;
					btVector3 dir = newRayTo-rayFrom;
					dir.normalize();
					dir *= gOldPickingDist;

					newPivotB = rayFrom + dir;
				}
				pickCon->setPivotB(newPivotB);
			}
		}
	}

	float dx, dy;
    dx = btScalar(x) - m_mouseOldX;
    dy = btScalar(y) - m_mouseOldY;


	///only if ALT key is pressed (Maya style)
	if (m_modifierKeys& BT_ACTIVE_ALT)
	{
		if(m_mouseButtons & 2)
		{
			btVector3 hor = getRayTo(0,0)-getRayTo(1,0);
			btVector3 vert = getRayTo(0,0)-getRayTo(0,1);
			btScalar multiplierX = btScalar(0.01);
			btScalar multiplierY = btScalar(0.01);
			if (m_ortho)
			{
				multiplierX = 1;
				multiplierY = 1;
			}


			m_cameraTargetPosition += hor* dx * multiplierX;
			m_cameraTargetPosition += vert* dy * multiplierY;
		}

		if(m_mouseButtons & (2 << 2) && m_mouseButtons & 1)
		{
		}
		else if(m_mouseButtons & 1) 
		{
			m_azi += dx * btScalar(0.2);
			m_azi = fmodf(m_azi, btScalar(360.f));
			m_ele += dy * btScalar(0.2);
			m_ele = fmodf(m_ele, btScalar(180.f));
		} 
		else if(m_mouseButtons & 4) 
		{
			m_cameraDistance -= dy * btScalar(0.2f);
			if (m_cameraDistance<btScalar(0.1))
				m_cameraDistance = btScalar(0.1);

			
		} 
	}


	m_mouseOldX = x;
    m_mouseOldY = y;
	updateCamera();


}
Exemplo n.º 25
0
int BasicSceneExample::execute()
{	
	roll = 0.0f;

	while (isOpen())
	{
		Vector<3, float> movement(0.0f, 0.0f, 0.0f);
		const float moveSpeed = 0.06f;
		
		if (moveForward->isTriggered())
			movement += camera.getLook() * moveSpeed;
		if (moveBack->isTriggered())
			movement -= camera.getLook() * moveSpeed;
		if (strafeLeft->isTriggered())
			movement -= camera.getRight() * moveSpeed;
		if (strafeRight->isTriggered())
			movement += camera.getRight() * moveSpeed;

		const float rollSpeed = 2.0f;

		if (rollCCW->isTriggered())
			roll += rollSpeed;

		if (rollCW->isTriggered())
			roll -= rollSpeed;

		if (object->getSkeleton() && object->getSkeleton()->isLoaded())
		{
			// Pose
			const Skeleton* skeleton = object->getSkeleton().get();

			for (std::size_t i = 0; i < skeleton->getBoneCount(); ++i)
			{
				pose->setRelativeTransform(i, skeleton->getBindPose()->getRelativeTransform(i));
			}

			Quaternion<float> leftFemurRotation, leftTibiaRotation, rightFemurRotation, rightTibiaRotation;
			leftFemurRotation = Quaternion<float>::fromAxisAngle({0.0f, 1.0f, 0.0f}, math::radians<float>(roll * 0.25f));
			leftTibiaRotation = Quaternion<float>::fromAxisAngle({0.0f, 1.0f, 0.0f}, math::radians<float>(roll));
			rightFemurRotation = Quaternion<float>::fromAxisAngle({0.0f, 0.0f, 1.0f}, math::radians<float>(45.0f));
			rightTibiaRotation = Quaternion<float>::fromAxisAngle({0.0f, 0.0f, 1.0f}, math::radians<float>(-75.0f));

			const Bone* bone = skeleton->getBone("anterior_abdomen");
			if (bone)
			{
				std::size_t index = bone->getIndex();
				
				Transform<float> transform = pose->getRelativeTransform(index);
				transform.setRotation(transform.getRotation() * leftTibiaRotation);
				pose->setRelativeTransform(index, transform);
			}

			bone = skeleton->getBone("posterior_abdomen");
			if (bone)
			{
				std::size_t index = bone->getIndex();
				
				Transform<float> transform = pose->getRelativeTransform(index);
				transform.setRotation(transform.getRotation() * leftFemurRotation);
				pose->setRelativeTransform(index, transform);
			}

			/*
			bone = skeleton->getBone("right_midleg_femur");
			if (bone)
			{
				std::size_t index = bone->getIndex();
				
				Transform<float> transform = pose->getRelativeTransform(index);
				transform.setRotation(transform.getRotation() * rightFemurRotation);
				pose->setRelativeTransform(index, transform);
			}

			bone = skeleton->getBone("right_midleg_tibia");
			if (bone)
			{
				std::size_t index = bone->getIndex();
				
				Transform<float> transform = pose->getRelativeTransform(index);
				transform.setRotation(transform.getRotation() * rightTibiaRotation);
				pose->setRelativeTransform(index, transform);
			}
			*/

			pose->concatenate();
		}


			if (0 && roll != 0.0f)
			{
				Quaternion<float> rotation = Quaternion<float>::fromAxisAngle(camera.getLook(), roll).normalized();

				up = rotation * up;

				updateCamera();
			}

			camera.setAspectRatio(window->getViewport().getAspectRatio());
			camera.lookAt(
				camera.getPosition() + movement,
				camera.getPosition() + movement + camera.getLook(),
				camera.getUp());
			camera.update();

			float paramInc = 0.004f;
			if (increaseAction->isTriggered())
			{
				layerParam->setRoughness(std::min(1.0f, layerParam->getRoughness() + paramInc));
				std::cout << "roughness: " << layerParam->getRoughness() << '\n';
			}
			if (decreaseAction->isTriggered())
			{
				layerParam->setRoughness(std::max(0.0f, layerParam->getRoughness() - paramInc));
				std::cout << "roughness: " << layerParam->getRoughness() << '\n';
			}
			
			//light.setPosition(camera.getPosition());
			//light.setDirection(camera.getLook());
			//plight.setPosition(light.getPosition());
			//sun.setDirection(camera.getLook());
			
			graphicsContext->setViewport(window->getViewport());
			graphicsContext->clear(ClearOption::COLOR_BUFFER | ClearOption::DEPTH_BUFFER);
			renderer->render(&scene, &camera);
			renderer->render(&gui, &orthoCamera);
			
			window->swapBuffers();
	}

	return EXIT_SUCCESS;
}
Exemplo n.º 26
0
int main() {
	// INIT

	glfwSetErrorCallback( error_callback );

	/* Initialize the library */
	if ( !glfwInit() ) {
		return -1;
	}

	// must use exactly version 3
	glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 3 );
	glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 );
	glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
	glfwWindowHint( GLFW_RESIZABLE, GL_FALSE );

	/* Create a windowed mode window and its OpenGL context */
	window = glfwCreateWindow( WIDTH, HEIGHT, "Hello World", NULL, NULL );
	if ( !window ) {
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent( window );

	glfwSetKeyCallback( window, key_callback );
	//glfwSetCursorPosCallback(window, cursor_position_callback);
	glfwSetScrollCallback(window, scroll_callback);
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
	int count;
	//printf( "%s\n", glfwGetVideoModes( glfwGetPrimaryMonitor(), &count ) );

	glewExperimental = GL_TRUE;
	if( glewInit() != GLEW_OK ) {
		fprintf( stderr, "glewInit() failed\n" );
	}

	glViewport( 0, 0, WIDTH, HEIGHT );

	glClearColor( 0.2f, 0.3f, 0.3f, 1.0f );
	glEnable( GL_DEPTH_TEST );

	// SHADER
	Shader shader( "./primitive_restart.vs.glsl", "./primitive_restart.fs.glsl" );

    static const GLfloat cube_positions[] =
    {
        -1.0f, -1.0f, -1.0f,
        -1.0f, -1.0f,  1.0f,
        -1.0f,  1.0f, -1.0f,
        -1.0f,  1.0f,  1.0f,
         1.0f, -1.0f, -1.0f,
         1.0f, -1.0f,  1.0f,
         1.0f,  1.0f, -1.0f,
         1.0f,  1.0f,  1.0f
    };
    static const GLfloat cube_colors[] =
    {
        1.0f, 1.0f, 1.0f,
        1.0f, 1.0f, 0.0f,
        1.0f, 0.0f, 1.0f,
        1.0f, 0.0f, 0.0f,
        0.0f, 1.0f, 1.0f,
        0.0f, 1.0f, 0.0f,
        0.0f, 0.0f, 1.0f,
        0.5f, 0.5f, 0.5f
    };
    static const GLushort cube_indices[] =
    {
        0, 1, 2, 3, 6, 7, 4, 5,
        0xFFFF,
        2, 6, 0, 4, 1, 5, 3, 7
    };
    GLuint VBO;
	glGenBuffers( 1, &VBO );
    glBindBuffer( GL_ARRAY_BUFFER, VBO );
    glBufferData( GL_ARRAY_BUFFER, sizeof(cube_positions) + sizeof(cube_colors), NULL, GL_STATIC_DRAW );
    glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(cube_positions), cube_positions);
    glBufferSubData( GL_ARRAY_BUFFER, sizeof(cube_positions), sizeof(cube_colors), cube_colors);
    GLuint EBO;
    glGenBuffers( 1, &EBO );
    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, EBO );
    glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(cube_indices), cube_indices, GL_STATIC_DRAW );
	GLuint VAO;
	glGenVertexArrays( 1, &VAO );
	glBindVertexArray( VAO );
    glEnableVertexAttribArray( 0 );
    glEnableVertexAttribArray( 1 );
    glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, NULL );
    glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)sizeof(cube_positions) );

    glClearColor( 0.6f, 0.8f, 0.8f, 1.0f );




	glm::mat4 projection;
	projection = glm::perspective( 45.0f, (GLfloat)WIDTH/HEIGHT, 0.1f, 100.0f );

	// Game loop
	while( !glfwWindowShouldClose( window ) ) {
	//for( int iter = 1; iter; --iter ) {
		glfwPollEvents();
		glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

		glUseProgram( shader.Program );
		glm::mat4 models[2];
		
		updateCamera();
		//glm::mat4 rotatedView = camera[1] * camera[0] * view;
		printf( "rotation x %f, y %f, z %f\n", rotation.x, rotation.y, rotation.z );
		glm::mat4 rotatedView;
		rotatedView = glm::rotate( rotatedView, rotation.x, glm::vec3(1, 0, 0) ) ;
		rotatedView = glm::rotate( rotatedView, rotation.y, glm::vec3(0, 1, 0) ) ;
		rotatedView = glm::rotate( rotatedView, rotation.z, glm::vec3(0, 0, 1) ) ;
		rotatedView *= view;
		//view = glm::translate( view, position );
		//glm::mat4 rotatedView;
		
		//projection = glm::rotate( projection, glm::radians(cameraOrientation[1]), glm::vec3(1.0f, 0.0f, 0.0f) );
		//projection = glm::rotate( projection, glm::radians(cameraOrientation[0]), glm::vec3(0.0f, 1.0f, 0.0f) );
		//projection = projection * (cameraPosition / 10.0f);
		glUniformMatrix4fv( glGetUniformLocation(shader.Program, "view" ), 1, GL_FALSE, glm::value_ptr(rotatedView) );
		glUniformMatrix4fv( glGetUniformLocation(shader.Program, "projection" ), 1, GL_FALSE, glm::value_ptr(projection) );

        glBindVertexArray( VAO );
        glBindBuffer( GL_ARRAY_BUFFER, VBO );
        glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, EBO );
        //glDrawArrays( GL_TRIANGLES, 0, 6 );
        glEnable(GL_PRIMITIVE_RESTART);
        glPrimitiveRestartIndex(0xFFFF);
        glDrawElements(GL_TRIANGLE_STRIP, 17, GL_UNSIGNED_SHORT, NULL);
        //glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, NULL);
        //glBindVertexArray( 0 );
        glFlush();
		glfwSwapBuffers( window );
		fps();
		printf("\n");
	}

	glDeleteVertexArrays( 1, &VAO );
	glDeleteBuffers( 1, &VBO );
	glDeleteBuffers( 1, &EBO );

	glfwDestroyWindow( window );
	glfwTerminate();
	return 0;
}
Exemplo n.º 27
0
void SpaceshipGame::update(long elapsedTime)
{
    // Calculate elapsed time in seconds
    float t = (float)elapsedTime / 1000.0;
    
    if (!_finished)
    {
        _time += t;

        // Play the background track
        if (_backgroundSound->getState() != AudioSource::PLAYING)
            _backgroundSound->play();
    }
    else
    {
        // Stop the background track
        if (_backgroundSound->getState() != AudioSource::STOPPED)
            _backgroundSound->stop();

        _throttle = 0.0f;
    }

    // Set initial force due to gravity
    _force.set(0, -GRAVITATIONAL_FORCE);

    // While we are pushing/touching the screen, apply a push force vector based on the distance from
    // the touch point to the center of the space ship.
    if (_pushing)
    {
        // Get the center point of the space ship in screen coordinates
        Vector3 shipCenterScreen;
        _scene->getActiveCamera()->project(getViewport(), _shipGroupNode->getBoundingSphere().center, &shipCenterScreen.x, &shipCenterScreen.y);

        // Compute a screen-space vector between the center point of the ship and the touch point.
        // We will use this vector to apply a "pushing" force to the space ship, similar to what
        // happens when you hold a magnet close to an object with opposite polarity.
        Vector2 pushForce((shipCenterScreen.x - _pushPoint.x), -(shipCenterScreen.y - _pushPoint.y));
        
        // Transform the vector so that a smaller magnitude emits a larger force and applying the
        // maximum touch distance.
        float distance = (std::max)(TOUCH_DISTANCE_MAX - pushForce.length(), 0.0f);
        pushForce.normalize();
        pushForce.scale(distance * FORCE_SCALE);
        _force.add(pushForce);

        // Compute a throttle value based on our force vector, minus gravity
        Vector2 throttleVector(_force.x, _force.y + GRAVITATIONAL_FORCE);
        _throttle += throttleVector.length() / FORCE_MAX * t;
    }
    else
    {
        // Gradually decrease the throttle
        if (_throttle > 0.0f)
        {
            _throttle *= 1.0f - t;
        }
    }

    // Clamp the throttle
    _throttle = CLAMP(_throttle, 0.0f, 1.0f);

    // Update acceleration (a = F/m)
    _acceleration.set(_force.x / MASS, _force.y / MASS);

    // Update velocity (v1 = v0 + at)
    _velocity.x += _acceleration.x * t;
    _velocity.y += _acceleration.y * t;

    // Clamp velocity to its maximum range
    _velocity.x = CLAMP(_velocity.x, -VELOCITY_MAX, VELOCITY_MAX);
    _velocity.y = CLAMP(_velocity.y, -VELOCITY_MAX, VELOCITY_MAX);

    // Move the spaceship based on its current velocity (x1 = x0 + vt)
    _shipGroupNode->translate(_velocity.x * t, _velocity.y * t, 0);

    // Check for collisions
    handleCollisions(t);

    // Update camera
    updateCamera();

    // Reset ship rotation
    _shipGroupNode->setRotation(_initialShipRot);

    // Apply ship tilt
    if (_force.x != 0 && fabs(_velocity.x) > 0.1f)
    {
        // Compute an angle based on the dot product between the force vector and the Y axis
        Vector2 fn;
        _force.normalize(&fn);
        float angle = MATH_RAD_TO_DEG(acos(Vector2::dot(Vector2(0, 1), fn)));
        if (_force.x > 0)
            angle = -angle;
        angle *= _throttle * t;
        _shipTilt += angle;
        _shipTilt = _shipTilt < -SHIP_TILT_MAX ? -SHIP_TILT_MAX : (_shipTilt > SHIP_TILT_MAX ? SHIP_TILT_MAX : _shipTilt);
    }
    else
    {
        // Interpolate tilt back towards zero when no force is applied
        _shipTilt = (_shipTilt + ((0 - _shipTilt) * t * 2.0f));
    }
    _shipGroupNode->rotateZ(MATH_DEG_TO_RAD(_shipTilt));

    if (_throttle > MATH_EPSILON)
    {
        // Apply ship spin
        _shipNode->rotateY(MATH_DEG_TO_RAD(SHIP_ROTATE_SPEED_MAX * t * _throttle));

        // Play sound effect
        if (_spaceshipSound->getState() != AudioSource::PLAYING)
            _spaceshipSound->play();
        
        // Set the pitch based on the throttle
        _spaceshipSound->setPitch(_throttle * SOUND_PITCH_SCALE);
    }
    else
    {
        // Stop sound effect
        _spaceshipSound->stop();
    }

    // Modify ship glow effect based on the throttle
    _glowDiffuseParameter->setValue(Vector4(1, 1, 1, _throttle * ENGINE_POWER));
    _shipSpecularParameter->setValue(SPECULAR - ((SPECULAR-2.0f) * _throttle));
}
Exemplo n.º 28
0
void animatePositions(Scene* scene, const bool updateCam) {
	if (updateCam)
		updateCamera(scene);

	// update sphere positions
	const float JUGGLE_X0 = -182.0f;
	const float JUGGLE_X1 = -108.0f;
	const float JUGGLE_Y0 = 88.0f;
	const float JUGGLE_H_Y = 184.0f;

	const float JUGGLE_H_VX = (JUGGLE_X0 - JUGGLE_X1) / 60.0f;
	const float JUGGLE_L_VX = (JUGGLE_X1 - JUGGLE_X0) / 30.0f;

	const float JUGGLE_H_H = JUGGLE_H_Y - JUGGLE_Y0;
	const float JUGGLE_H_VY = 4.0f * JUGGLE_H_H / 60.0f;
	const float JUGGLE_G = JUGGLE_H_VY * JUGGLE_H_VY / (2.0f * JUGGLE_H_H);

	const float JUGGLE_L_VY = 0.5f * JUGGLE_G * 30.0f;

	const float HIPS_MAX_Y = 85.0f;
	const float HIPS_MIN_Y = 81.0f;

	const float HIPS_ANGLE_MULTIPLIER = 2.0f * M_PI / 30.0f;

	double time = WallClockTime() - sceneTimeOffset;
	time -= floor(time);

	// mirrored juggling balls
	float t = 30.0f + 30.0f * float(time);
	Sphere* sphere = &(scene->spheres[1]);
	sphere->center.s[2] = 0.1f * (JUGGLE_X1 + JUGGLE_H_VX * t);
	sphere->center.s[1] = 0.1f * (JUGGLE_Y0 + (JUGGLE_H_VY - 0.5f * JUGGLE_G * t) * t);

	t -= 30.0f;
	sphere = &(scene->spheres[2]);
	sphere->center.s[2] = 0.1f * (JUGGLE_X1 + JUGGLE_H_VX * t);
	sphere->center.s[1] = 0.1f * (JUGGLE_Y0 + (JUGGLE_H_VY - 0.5f * JUGGLE_G * t) * t);

	sphere = &(scene->spheres[0]);
	sphere->center.s[2] = 0.1f * (JUGGLE_X0 + JUGGLE_L_VX * t);
	sphere->center.s[1] = 0.1f * (JUGGLE_Y0 + (JUGGLE_L_VY - 0.5f * JUGGLE_G * t) * t);

	// body (hips to chest) 3 .. 10
	float angle = HIPS_ANGLE_MULTIPLIER*t;
	float oscillation = 0.5f * (1.0f + cosf(angle));

	cl_float3 o;
	vecInit(o, 151.0f,
			HIPS_MIN_Y + (HIPS_MAX_Y - HIPS_MIN_Y) * oscillation,
			-151.0f);
	cl_float3 v;
	vecInit(v, 0.0f, 70.0f, (HIPS_MIN_Y - HIPS_MAX_Y) * sinf(angle));
	vecNormalize(v);

	cl_float3 u;
	vecInit(u, 0.0f, v.s[2], -v.s[1]);

	cl_float3 w;
	vecInit(w, 1.0f, 0.0f, 0.0f);

	for (int i = 3; i <= 10; i++) {
		float fraction = float(i - 3) / 7.0f;
		sphere = &(scene->spheres[i]);
		sphere->center = o;
		vecScaledAdd(sphere->center, 32.0f * fraction, v);
		vecScale(sphere->center, 0.1f);
	}

	// head
	sphere = &(scene->spheres[11]);
	sphere->center = o;
	vecScaledAdd(sphere->center, 70.0f, v);
	vecScale(sphere->center, 0.1f);

	// neck
	sphere = &(scene->spheres[12]);
	sphere->center = o;
	vecScaledAdd(sphere->center, 55.0f, v);
	vecScale(sphere->center, 0.1f);

	// left leg (13 .. 29)
	cl_float3 p;
	vecInit(p, 159.0f, 2.5f, -133.0f);
	cl_float3 q = o;
	vecScaledAdd(q, -9.0f, v);
	vecScaledAdd(q, -16.0f, u);
	updateAppendage(scene, 13, p, q, u, 42.58f, 34.07f, 8, 8);

	// right leg (30 .. 46)
	vecInit(p, 139.0f, 2.5f, -164.0f);
	q = o;
	vecScaledAdd(q, -9.0f, v);
	vecScaledAdd(q, 16.0f, u);
	updateAppendage(scene, 30, p, q, u, 42.58f, 34.07f, 8, 8);

	// left arm (47 .. 63)
	cl_float3 n;
	float armAngle = -0.35f * oscillation;
	vecInit(p, 69.0f + 41.0f * cosf(armAngle),
			60.0f - 41.0f * sinf(armAngle),
			-108.0f);
	q = o;
	vecScaledAdd(q, 45.0f, v);
	vecScaledAdd(q, -19.0f, u);
	n = o;
	vecScaledAdd(n, 45.41217f, v);
	vecScaledAdd(n, -19.91111f, u);
	vecSub(n, q);
	updateAppendage(scene, 47, p, q, n, 44.294f, 46.098f, 8, 8);

	// right arm (64 .. 80)
	p.s[2] = -182.0f;
	q = o;
	vecScaledAdd(q, 45.0f, v);
	vecScaledAdd(q, 19.0f, u);
	n = o;
	vecScaledAdd(n, 45.41217f, v);
	vecScaledAdd(n, 19.91111f, u);
	vecSub(n, q);
	vecScale(n, -1.0f);
	updateAppendage(scene, 64, p, q, n, 44.294f, 46.098f, 8, 8);

	// left eye (81)
	sphere = &(scene->spheres[81]);
	sphere->center = o;
	vecScaledAdd(sphere->center, 69.0f, v);
	vecScaledAdd(sphere->center, -7.0f, u);
	sphere->center.s[0] = 142.0f;
	vecScale(sphere->center, 0.1f);

	// left eye (82)
	sphere = &(scene->spheres[82]);
	sphere->center = o;
	vecScaledAdd(sphere->center, 69.0f, v);
	vecScaledAdd(sphere->center, 7.0f, u);
	sphere->center.s[0] = 142.0f;
	vecScale(sphere->center, 0.1f);

	// hair (83)
	sphere = &(scene->spheres[83]);
	sphere->center = o;
	vecScaledAdd(sphere->center, 71.0f, v);
	sphere->center.s[0] = 152.0f;
	vecScale(sphere->center, 0.1f);
}
Exemplo n.º 29
0
void Camera::setUpVector(btVector3 m_upVector)
{
	m_bUpVectorChanged = true;
	this->m_upVector = m_upVector;
    updateCamera();
}
Exemplo n.º 30
0
int main(void)
{
    GLFWwindow* window;

    window = init("Billboards", 640, 480);
    if(!window)
    {
        return -1;
    }

    glEnable(GL_DEPTH_TEST);

    Camera camera(CAMERA_PERSPECTIVE, 45.0f, 0.1f, 1000.0f, 640.0f, 480.0f);
    camera.setPosition(0.0f, 0.0f, -3.0f);
    setCamera(&camera); // The camera updating is handled in ../common/util.cpp

    glm::mat4 model;

    GLuint program;
    {
        GLuint vertex = createShader(VERTEX_SRC, GL_VERTEX_SHADER);
        GLuint fragment = createShader(FRAGMENT_SRC, GL_FRAGMENT_SHADER);
        program = createShaderProgram(vertex, fragment);
        linkShader(program);
        validateShader(program);
        glDetachShader(program, vertex);
        glDeleteShader(vertex);
        glDetachShader(program, fragment);
        glDeleteShader(fragment);
    }
    GLuint billboardProgram;
    {
        GLuint vertex = createShader(VERTEX_BB_SRC, GL_VERTEX_SHADER);
        GLuint fragment = createShader(FRAGMENT_BB_SRC, GL_FRAGMENT_SHADER);
        billboardProgram = createShaderProgram(vertex, fragment);
        linkShader(billboardProgram);
        validateShader(billboardProgram);
        glDetachShader(program, vertex);
        glDeleteShader(vertex);
        glDetachShader(program, fragment);
        glDeleteShader(fragment);
    }

    glUseProgram(program);

    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    GLuint vbo;
    glGenBuffers(1, &vbo);

    float vertices[] =
    {
        // x   y      z     r     g     b     u     v
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
         0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
        -0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
    
        -0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
        -0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
    
        -0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
        -0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
        -0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
    
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
         0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
    
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
         0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
        -0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
    
        -0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
        -0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
        -0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f
    };

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0); // position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), 0);
    glEnableVertexAttribArray(1); // color
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(2); // texture coordinates
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void*)(6 * sizeof(GLfloat)));

    float verts_bb[] =
    {
        -0.5f, -0.5f,
        0.5f,  -0.5f,
        -0.5f, 0.5f,
        0.5f, 0.5f
    };
    GLuint vbo_bb;
    glGenBuffers(1, &vbo_bb);
    GLuint vao_bb;
    glGenVertexArrays(1, &vao_bb);
    glBindVertexArray(vao_bb);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_bb);
    glBufferData(GL_ARRAY_BUFFER, sizeof(verts_bb), verts_bb, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);

    glUseProgram(billboardProgram);
    glUniform3f(glGetUniformLocation(billboardProgram, "center"), 0.0f, 2.0f, 0.0f);
    glUniform2f(glGetUniformLocation(billboardProgram, "size"), 0.5f, 0.5f);

    int w, h;
    GLuint texture = loadImage("image.png", &w, &h, 0, false);
    glUniform1i(glGetUniformLocation(billboardProgram, "tex"), 0);
    glUseProgram(program);
    glUniform1i(glGetUniformLocation(program, "tex"), 0);
    
    glClearColor(0.75f, 0.75f, 0.75f, 1.0f);

    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    while(!glfwWindowShouldClose(window))
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        updateCamera(640, 480, window);

        // Draw the cube
        glUseProgram(program);
        glBindVertexArray(vao);

        GLint modelUL = glGetUniformLocation(program, "model");
        glUniformMatrix4fv(modelUL, 1, GL_FALSE, glm::value_ptr(model));
        GLint viewUL = glGetUniformLocation(program, "view");
        glUniformMatrix4fv(viewUL, 1, GL_FALSE, glm::value_ptr(camera.getView()));
        GLint projUL = glGetUniformLocation(program, "projection");
        glUniformMatrix4fv(projUL, 1, GL_FALSE, glm::value_ptr(camera.getProjection()));

        glDrawArrays(GL_TRIANGLES, 0, 36);

        // Draw the billboard
        glBindVertexArray(vao_bb);
        glUseProgram(billboardProgram);

        viewUL = glGetUniformLocation(billboardProgram, "view");
        glUniformMatrix4fv(viewUL, 1, GL_FALSE, glm::value_ptr(camera.getView()));
        projUL = glGetUniformLocation(billboardProgram, "proj");
        glUniformMatrix4fv(projUL, 1, GL_FALSE, glm::value_ptr(camera.getProjection()));
        glUniform1i(glGetUniformLocation(billboardProgram, "fixedSize"), 0);
        glUniform3f(glGetUniformLocation(billboardProgram, "camRight"), camera.getRightVector().x, camera.getRightVector().y, camera.getRightVector().z);
        glUniform3f(glGetUniformLocation(billboardProgram, "camUp"), camera.getUpVector().x, camera.getUpVector().y, camera.getUpVector().z);

        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // Clean up
    glDeleteBuffers(1, &vbo);
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo_bb);
    glDeleteVertexArrays(1, &vao_bb);
    glDeleteProgram(program);
    glDeleteProgram(billboardProgram);
    glDeleteTextures(1, &texture);

    glfwTerminate();
    return 0;
}