コード例 #1
0
ファイル: RenderSceneA.cpp プロジェクト: sbowl/sbowlrep
void RenderSceneA::RenderScene()
{
	//big sphere
	//glPolygonMode(GL_FRONT,GL_LINE);
	//glPolygonMode(GL_BACK,GL_LINE);
	glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glColor3f( 1.0f, 1.0f, 1.0f );
    glVertexPointer( 3, GL_FLOAT, 0, afVertices ); // set pointer to vertex data
    glNormalPointer( GL_FLOAT, 0, afVertices ); // set pointer to normal data
    glEnableClientState( GL_VERTEX_ARRAY ); // enable vertex and normal pointer
    glEnableClientState( GL_NORMAL_ARRAY );
	float *auiTextureCoord = new float[2*m_iNoVertices];
	UpdateTextureCoord(auiTextureCoord);
	glTexCoordPointer(2, GL_FLOAT, 0, auiTextureCoord);
	glEnableClientState( GL_TEXTURE_COORD_ARRAY );
    glDrawElements( GL_TRIANGLES, m_iNoFaces*3, GL_UNSIGNED_INT, auiIndices );
	
	//small sphere
	glPolygonMode(GL_FRONT,GL_FILL);
	glPolygonMode(GL_BACK,GL_FILL);
	glVertexPointer( 3, GL_FLOAT, 0, afVerticesSphere );
	glMatrixMode(GL_MODELVIEW);
	float RadiusSphere = 2.0f;
	float vx = RadiusSphere * sin(SphereMove);
	float vz = RadiusSphere * cos(SphereMove);
	glTranslatef(vx,0.0f,vz);
	float radiusSphere = 0.3f;
	float multMatrix[16] =
	{
		radiusSphere,0.0f,0.0f,0.0f,
		0.0f,radiusSphere,0.0f,0.0f,
		0.0f,0.0f,radiusSphere,0.0f,
		0.0f,0.0f,0.0f,1.0f
	};
	glMultMatrixf(multMatrix);
	glDisableClientState( GL_TEXTURE_COORD_ARRAY );
    glDrawElements( GL_TRIANGLES, NO_FACES_SPHERE*3, GL_UNSIGNED_INT, auiIndicesSphere);

	 //Simple Plane by 4 Quads
	glPolygonMode(GL_FRONT,GL_LINE); // wireframe for the front side of the polygone
	glPolygonMode(GL_BACK,GL_LINE); //and for the back side
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();                                  
    glColor3f(0.5f,0.5f,1.0f);  
	glDisableClientState( GL_TEXTURE_COORD_ARRAY );

	/* quads generieren [4x4] */
	int qx,qy;
	for (qx = -2; qx < 2; qx++) {
		for (qy = -2; qy < 2; qy++) {
			glBegin(GL_QUADS);                         
				glVertex3f(1.0f * qx, -1.0f, 1.0f * qy);
				glVertex3f(1.0f * (qx + 1), -1.0f, 1.0f * qy);
				glVertex3f(1.0f * (qx + 1), -1.0f, 1.0f * (qy + 1));
				glVertex3f(1.0f * qx, -1.0f, 1.0f * (qy + 1));
			glEnd();
		}
	}

	//go back to the previous Texture Mode stored in TextureMode
	if (TextureMode == 1)
	{
		glDisable(GL_TEXTURE_2D);
		glPolygonMode(GL_FRONT,GL_FILL); // fill the front side of the polygone
		glPolygonMode(GL_BACK,GL_FILL); // and use wireframe for back side
	}
	else if (TextureMode == 2)
	{
		glEnable(GL_TEXTURE_2D);
		glPolygonMode(GL_FRONT,GL_FILL); // fill the front side of the polygone
		glPolygonMode(GL_BACK,GL_FILL); // and use wireframe for back side
	}
	else 
	{
		glDisable(GL_TEXTURE_2D);
		glPolygonMode(GL_FRONT,GL_LINE); // fill the front side of the polygone
		glPolygonMode(GL_BACK,GL_LINE); // and use wireframe for back side
	}
}
コード例 #2
0
ファイル: Graph.cpp プロジェクト: CowTard/16Factorial-OPENGL
void Node::createDisplayList(map<string, Node*>& grafo, map<string, Aparencia*>& aparencias, string referenciaApp, map<string, Textura*>& texturas,map<string, Animation*> anime){
	
	if (this->displayList){
		this->controlList = true;
		this->index = glGenLists(1);
		this->insideList = false;
		glNewList(this->index, GL_COMPILE);
		glPushMatrix();
		glMultMatrixf(&this->matrix[0]);

		if (this->appRef != "inherit"){
			aparencias[this->appRef]->apply();
		}
		else {
			aparencias[referenciaApp]->apply();
			this->appRef = referenciaApp;
		}
		unsigned int size = this->primitivas.size();
		for (unsigned int i = 0; i < size; i++){
			if (aparencias[appRef]->getTextRef() != "null"){
				float texS = texturas[aparencias[appRef]->getTextRef()]->getTexLenS();
				float texT = texturas[aparencias[appRef]->getTextRef()]->getTexLenT();
				primitivas[i]->draw(texS, texT);
			}
			else primitivas[i]->draw();
		}
		typedef vector<string>::iterator iter;
		for (iter it = this->getDescendencia().begin(); it != this->getDescendencia().end(); it++){
			glPushMatrix();
			grafo[*it]->createDisplayList(grafo, aparencias, this->appRef, texturas,anime);
			glPopMatrix();
		}
		glPopMatrix();
		glEndList();
	}
	else {
		glMultMatrixf(&this->matrix[0]);
		if (this->controlList) this->insideList = true; else this->insideList = false;
		if (this->appRef != "inherit"){
			aparencias[this->appRef]->apply();
		}
		else {
			aparencias[referenciaApp]->apply();
			this->appRef = referenciaApp;
		}
		unsigned int size = this->primitivas.size();
		for (unsigned int i = 0; i < size; i++){
			if (aparencias[appRef]->getTextRef() != "null"){
				float texS = texturas[aparencias[appRef]->getTextRef()]->getTexLenS();
				float texT = texturas[aparencias[appRef]->getTextRef()]->getTexLenT();
				primitivas[i]->draw(texS, texT);
			}
			else primitivas[i]->draw();
		}
		typedef std::vector<std::string>::iterator iter;
		for (iter it = this->getDescendencia().begin(); it != this->getDescendencia().end(); it++){
			glPushMatrix();
			grafo[*it]->createDisplayList(grafo, aparencias, this->appRef, texturas,anime);
			glPopMatrix();
		}
	}
}
コード例 #3
0
ファイル: Render.cpp プロジェクト: shirayukikitsune/xbeat
/* Render::renderScene: render scene */
void Render::renderScene(PMDObject *objs, const short *order, int num, Stage *stage, bool useMMDLikeCartoon, bool useCartoonRendering, float lightIntensity, const float *lightDirection, const float *lightColor, float shadowMappingFloorDensity)
{
   short i;
   bool toonLight = true;

   /* clear rendering buffer */
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

   glEnable(GL_CULL_FACE);
   glEnable(GL_BLEND);

   /* set model viwe matrix */
   glLoadIdentity();
   glMultMatrixf(m_rotMatrix);

   /* stage and shadhow */
   /* background */
   stage->renderBackground();
   /* enable stencil */
   glEnable(GL_STENCIL_TEST);
   glStencilFunc(GL_ALWAYS, 1, ~0);
   /* make stencil tag true */
   glStencilOp(GL_KEEP, GL_KEEP , GL_REPLACE);
   /* render floor */
   stage->renderFloor();
   /* render shadow stencil */
   glColorMask(0, 0, 0, 0) ;
   glDepthMask(0);
   glEnable(GL_STENCIL_TEST);
   glStencilFunc(GL_EQUAL, 1, ~0);
   /* increment 1 pixel stencil */
   glStencilOp(GL_KEEP, GL_KEEP, GL_INCR);
   /* render moodel */
   glDisable(GL_DEPTH_TEST);
   glPushMatrix();
   glMultMatrixf(stage->getShadowMatrix());
   for (i = 0; i < num; i++) {
      if (objs[order[i]].isEnable() == true) {
         objs[order[i]].getPMDModel()->renderForShadow();
      }
   }
   glPopMatrix();
   glEnable(GL_DEPTH_TEST);
   glColorMask(1, 1, 1, 1);
   glDepthMask(1);
   /* if stencil is 2, render shadow with blend on */
   glStencilFunc(GL_EQUAL, 2, ~0);
   glDisable(GL_LIGHTING);
   glColor4f(0.1f, 0.1f, 0.1f, shadowMappingFloorDensity);
   glDisable(GL_DEPTH_TEST);
   stage->renderFloor();
   glEnable(GL_DEPTH_TEST);
   glDisable(GL_STENCIL_TEST);
   glEnable(GL_LIGHTING);

   /* render model */
   for (i = 0; i < num; i++) {
      if (objs[order[i]].isEnable() == true) {
         if (objs[order[i]].getPMDModel()->getToonFlag() == false && toonLight == true) {
            /* disable toon lighting */
            updateLight(true, false, lightIntensity, lightDirection, lightColor);
            toonLight = false;
         } else if (objs[order[i]].getPMDModel()->getToonFlag() == true && toonLight == false) {
            /* enable toon lighting */
            updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor);
            toonLight = true;
         }
         objs[order[i]].getPMDModel()->renderModel();
         objs[order[i]].getPMDModel()->renderEdge();
      }
   }
   if (toonLight == false) {
      /* restore toon lighting */
      updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor);
   }
}
コード例 #4
0
ファイル: directstate.c プロジェクト: ptitSeb/glshim
void gl4es_glMatrixMultf(GLenum matrixMode, const GLfloat *m) {
    mat(glMultMatrixf(m));
}
コード例 #5
0
ファイル: ModelManager.c プロジェクト: devmario/IbizaEngine
bool ModelManagerDisplayBegin(ModelManager* manager, ModelManagerDisplayMode displayMode, Camera* camera, Light* light) {
	manager->lastBindTexture = 0;
	tt = 0;
	//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	manager->drawModelCount = 0;
	if(manager->displayMode != displayMode) {
		manager->displayMode = displayMode;
		if(displayMode == ModelManagerDisplayMode3D) {
			glMatrixMode(GL_PROJECTION);
			glMultMatrixf((float*)&manager->projection3D);
		} else if(displayMode == ModelManagerDisplayMode2D) {
			// switch to projection mode
			glMatrixMode(GL_PROJECTION);
			// save previous matrix which contains the 
			//settings for the perspective projection
			glPushMatrix();
			// reset matrix
			glLoadIdentity();
			// set a 2D orthographic projection
			

			glOrthof(0, (float)manager->width, (float)manager->height, 0, 1.0f, 30000.0f);

			// invert the y axis, down is positive
			glScalef(1, -1, 1);
			// mover the origin from the bottom left corner
			// to the upper left corner
			glTranslatef((float)manager->width * 0.5f, -(float)manager->height * 0.5f, 0);

		}
	}
	

     glMatrixMode(GL_MODELVIEW);
     glLoadIdentity();
	
	//float p[16];   // projection matrix
	//float mv[16];  // model-view matrix
	//float mvp[16]; // model-view-projection matrix
	//float t;
	
	//glGetFloatv( GL_PROJECTION_MATRIX, p );
	//glGetFloatv( GL_MODELVIEW_MATRIX, mv );
    
	
	//
	// Concatenate the projection matrix and the model-view matrix to produce 
	// a combined model-view-projection matrix.
	//
	
    /*
	mvp[ 0] = mv[ 0] * p[ 0] + mv[ 1] * p[ 4] + mv[ 2] * p[ 8] + mv[ 3] * p[12];
	mvp[ 1] = mv[ 0] * p[ 1] + mv[ 1] * p[ 5] + mv[ 2] * p[ 9] + mv[ 3] * p[13];
	mvp[ 2] = mv[ 0] * p[ 2] + mv[ 1] * p[ 6] + mv[ 2] * p[10] + mv[ 3] * p[14];
	mvp[ 3] = mv[ 0] * p[ 3] + mv[ 1] * p[ 7] + mv[ 2] * p[11] + mv[ 3] * p[15];
	
	mvp[ 4] = mv[ 4] * p[ 0] + mv[ 5] * p[ 4] + mv[ 6] * p[ 8] + mv[ 7] * p[12];
	mvp[ 5] = mv[ 4] * p[ 1] + mv[ 5] * p[ 5] + mv[ 6] * p[ 9] + mv[ 7] * p[13];
	mvp[ 6] = mv[ 4] * p[ 2] + mv[ 5] * p[ 6] + mv[ 6] * p[10] + mv[ 7] * p[14];
	mvp[ 7] = mv[ 4] * p[ 3] + mv[ 5] * p[ 7] + mv[ 6] * p[11] + mv[ 7] * p[15];
	
	mvp[ 8] = mv[ 8] * p[ 0] + mv[ 9] * p[ 4] + mv[10] * p[ 8] + mv[11] * p[12];
	mvp[ 9] = mv[ 8] * p[ 1] + mv[ 9] * p[ 5] + mv[10] * p[ 9] + mv[11] * p[13];
	mvp[10] = mv[ 8] * p[ 2] + mv[ 9] * p[ 6] + mv[10] * p[10] + mv[11] * p[14];
	mvp[11] = mv[ 8] * p[ 3] + mv[ 9] * p[ 7] + mv[10] * p[11] + mv[11] * p[15];
	
	mvp[12] = mv[12] * p[ 0] + mv[13] * p[ 4] + mv[14] * p[ 8] + mv[15] * p[12];
	mvp[13] = mv[12] * p[ 1] + mv[13] * p[ 5] + mv[14] * p[ 9] + mv[15] * p[13];
	mvp[14] = mv[12] * p[ 2] + mv[13] * p[ 6] + mv[14] * p[10] + mv[15] * p[14];
	mvp[15] = mv[12] * p[ 3] + mv[13] * p[ 7] + mv[14] * p[11] + mv[15] * p[15];
	
	//
	// Extract the frustum's right clipping plane and normalize it.
	//
	
	
	manager->g_frustumPlanes[0][0] = mvp[ 3] - mvp[ 0];
	manager->g_frustumPlanes[0][1] = mvp[ 7] - mvp[ 4];
	manager->g_frustumPlanes[0][2] = mvp[11] - mvp[ 8];
	manager->g_frustumPlanes[0][3] = mvp[15] - mvp[12];
	
	t = (float) sqrt(manager->g_frustumPlanes[0][0] * manager->g_frustumPlanes[0][0] + 
					 manager->g_frustumPlanes[0][1] * manager->g_frustumPlanes[0][1] + 
					 manager->g_frustumPlanes[0][2] * manager->g_frustumPlanes[0][2] );
	
	manager->g_frustumPlanes[0][0] /= t;
	manager->g_frustumPlanes[0][1] /= t;
	manager->g_frustumPlanes[0][2] /= t;
	manager->g_frustumPlanes[0][3] /= t;
	
	//
	// Extract the frustum's left clipping plane and normalize it.
	//
	
	manager->g_frustumPlanes[1][0] = mvp[ 3] + mvp[ 0];
	manager->g_frustumPlanes[1][1] = mvp[ 7] + mvp[ 4];
	manager->g_frustumPlanes[1][2] = mvp[11] + mvp[ 8];
	manager->g_frustumPlanes[1][3] = mvp[15] + mvp[12];
	
	t = (float) sqrt(manager->g_frustumPlanes[1][0] * manager->g_frustumPlanes[1][0] + 
					 manager->g_frustumPlanes[1][1] * manager->g_frustumPlanes[1][1] + 
					 manager->g_frustumPlanes[1][2] * manager->g_frustumPlanes[1][2] );
	
	manager->g_frustumPlanes[1][0] /= t;
	manager->g_frustumPlanes[1][1] /= t;
	manager->g_frustumPlanes[1][2] /= t;
	manager->g_frustumPlanes[1][3] /= t;
	
	//
	// Extract the frustum's bottom clipping plane and normalize it.
	//
	
	manager->g_frustumPlanes[2][0] = mvp[ 3] + mvp[ 1];
	manager->g_frustumPlanes[2][1] = mvp[ 7] + mvp[ 5];
	manager->g_frustumPlanes[2][2] = mvp[11] + mvp[ 9];
	manager->g_frustumPlanes[2][3] = mvp[15] + mvp[13];
	
	t = (float) sqrt(manager->g_frustumPlanes[2][0] * manager->g_frustumPlanes[2][0] + 
					 manager->g_frustumPlanes[2][1] * manager->g_frustumPlanes[2][1] + 
					 manager->g_frustumPlanes[2][2] * manager->g_frustumPlanes[2][2] );
	
	manager->g_frustumPlanes[2][0] /= t;
	manager->g_frustumPlanes[2][1] /= t;
	manager->g_frustumPlanes[2][2] /= t;
	manager->g_frustumPlanes[2][3] /= t;
	
	//
	// Extract the frustum's top clipping plane and normalize it.
	//
	
	manager->g_frustumPlanes[3][0] = mvp[ 3] - mvp[ 1];
	manager->g_frustumPlanes[3][1] = mvp[ 7] - mvp[ 5];
	manager->g_frustumPlanes[3][2] = mvp[11] - mvp[ 9];
	manager->g_frustumPlanes[3][3] = mvp[15] - mvp[13];
	
	t = (float) sqrt(manager->g_frustumPlanes[3][0] * manager->g_frustumPlanes[3][0] + 
					 manager->g_frustumPlanes[3][1] * manager->g_frustumPlanes[3][1] + 
					 manager->g_frustumPlanes[3][2] * manager->g_frustumPlanes[3][2] );
	
	manager->g_frustumPlanes[3][0] /= t;
	manager->g_frustumPlanes[3][1] /= t;
	manager->g_frustumPlanes[3][2] /= t;
	manager->g_frustumPlanes[3][3] /= t;
	
	//
	// Extract the frustum's far clipping plane and normalize it.
	//
	
	manager->g_frustumPlanes[4][0] = mvp[ 3] - mvp[ 2];
	manager->g_frustumPlanes[4][1] = mvp[ 7] - mvp[ 6];
	manager->g_frustumPlanes[4][2] = mvp[11] - mvp[10];
	manager->g_frustumPlanes[4][3] = mvp[15] - mvp[14];
	
	t = (float) sqrt(manager->g_frustumPlanes[4][0] * manager->g_frustumPlanes[4][0] +  
					 manager->g_frustumPlanes[4][1] * manager->g_frustumPlanes[4][1] + 
					 manager->g_frustumPlanes[4][2] * manager->g_frustumPlanes[4][2] );
	
	manager->g_frustumPlanes[4][0] /= t;
	manager->g_frustumPlanes[4][1] /= t;
	manager->g_frustumPlanes[4][2] /= t;
	manager->g_frustumPlanes[4][3] /= t;
	manager->drawModelCount = 0;
	//
	// Extract the frustum's near clipping plane and normalize it.
	//
	
	manager->g_frustumPlanes[5][0] = mvp[ 3] + mvp[ 2];
	manager->g_frustumPlanes[5][1] = mvp[ 7] + mvp[ 6];
	manager->g_frustumPlanes[5][2] = mvp[11] + mvp[10];
	manager->g_frustumPlanes[5][3] = mvp[15] + mvp[14];
	
	t = (float) sqrt(manager->g_frustumPlanes[5][0] * manager->g_frustumPlanes[5][0] + 
					 manager->g_frustumPlanes[5][1] * manager->g_frustumPlanes[5][1] + 
					 manager->g_frustumPlanes[5][2] * manager->g_frustumPlanes[5][2] );
	
	manager->g_frustumPlanes[5][0] /= t;
	manager->g_frustumPlanes[5][1] /= t;
	manager->g_frustumPlanes[5][2] /= t;
	manager->g_frustumPlanes[5][3] /= t;*/
	/*
	for(int i = 0; i < manager->touchArguments->length; i++) {
		ModelEventTouchArgument* touchArgument = ArrayObjectAtIndex(manager->touchArguments, i);
		
		float div = manager->multy3D.m33 == 0 ? 1.0 : manager->multy3D.m33;
		
		Vector4D screenVector = Vector4DInit((((touchArgument->touchVector.x - manager->view[0]) / manager->view[2]) * 2) - 1, 
											 
											 (((manager->view[3] - touchArgument->touchVector.y - manager->view[1]) / manager->view[3]) * 2) - 1, 
											 
											 -(manager->multy3D.m13 * touchArgument->touchVector.x + 
											   manager->multy3D.m23 * touchArgument->touchVector.y + 
											   manager->multy3D.m43) / div,
											 
											 1.0f);
		
		Vector4D object4D = Matrix3DMultiplyVector4D(manager->multy3D, screenVector);
		Vector3D object3D;
		if(object4D.w != 0.0) {
			object3D = Vector3DInit(object4D.x / object4D.w, 
									object4D.y / object4D.w, 
									object4D.z / object4D.w);
		} else {
			object3D = Vector3DInit(0.0f, 0.0f, 0.0f);
		}
		
		touchArgument->origin = Vector3DInit(0.0f, 0.0f, 0.0f);
		touchArgument->direction = Vector3DSubtract(object3D, touchArgument->origin);
		touchArgument->direction = Vector3DNormal(touchArgument->direction);
	}
     */
	glMultMatrixf((float*)camera->matrix);
	
	return true;
}
コード例 #6
0
ファイル: Model3D.cpp プロジェクト: eaquiroz/Verse
void Model3D::recursiveTextureLoad(const struct aiScene *sc, const struct aiNode* nd) {
	int i;
	unsigned int n = 0, t;
	struct aiMatrix4x4 m = nd->mTransformation;

	// update transform
	aiTransposeMatrix4(&m);
	glPushMatrix();
	glMultMatrixf((float*) &m);

	// draw all meshes assigned to this node
	for (; n < nd->mNumMeshes; ++n) {
		const struct aiMesh* mesh = sc->mMeshes[nd->mMeshes[n]];
		unsigned int cont = aiGetMaterialTextureCount(sc->mMaterials[mesh->mMaterialIndex], aiTextureType_AMBIENT);
		struct aiString* str = (aiString*) malloc(sizeof(struct aiString));

		if (cont > 0) {
			//aiGetMaterialString(sc->mMaterials[mesh->mMaterialIndex],AI_MATKEY_TEXTURE_DIFFUSE(0),str);
			aiGetMaterialTexture(sc->mMaterials[mesh->mMaterialIndex], aiTextureType_AMBIENT, 0, str, 0, 0, 0, 0, 0, 0);

			// See if another mesh is already using this texture, if so, just copy GLuint instead of remaking entire texture
			bool newTextureToBeLoaded = true;
			for (int x = 0; x < texturesAndPaths.size(); x++) {
				if (texturesAndPaths[x].pathName == *str) {
					TextureAndPath reusedTexture;
					reusedTexture.hTexture = texturesAndPaths[x].hTexture;
					reusedTexture.pathName = *str;
					//printf("%s pathnm \n", reusedTexture.pathName.data);
					texturesAndPaths.push_back(reusedTexture);
					newTextureToBeLoaded = false;

					std::cout << "Texture reused." << std::endl;

					break;
				}
			}

			if (newTextureToBeLoaded) {

				texturename.clear();
				texturename.append(foldername.c_str());
				texturename.append(str->data);

				std::cout << texturename.c_str() << " strname \n";
				Mat imagen=imread(texturename.c_str());
                                int w = imagen.cols;
				int h = imagen.rows;

                                int dataSize=imagen.cols*imagen.rows*3;
                                unsigned char* data=new unsigned char[dataSize];
                                int j=0;
                                for( int y = 0; y < imagen.rows; y++ )
                                { 
                                    for( int x = 0; x < imagen.cols; x++ )
                                             { 
                                                for( int c = 0; c < 3; c++ )
                                                {
                                                     data[j] = imagen.at<Vec3b>(y,x)[c];
                                                     j++;           
                                                }
                                             }
                                }

                                //Now generate the OpenGL texture object
				TextureAndPath newTexture;
				newTexture.pathName = *str;
				glGenTextures(1, &newTexture.hTexture);

				glBindTexture(GL_TEXTURE_2D, newTexture.hTexture);
				//glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA, w, h, 0, GL_BGR,GL_UNSIGNED_BYTE,(GLvoid*)pixeles );
				//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
                                gluBuild2DMipmaps(GL_TEXTURE_2D, 3, imagen.cols, imagen.rows, GL_BGR, GL_UNSIGNED_BYTE, data);
                                
				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_REPEAT);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

				glBindTexture(GL_TEXTURE_2D, newTexture.hTexture);

				GLenum huboError = glGetError();

				if (huboError) {
					std::cout << "There was an error loading the texture" << std::endl;
				}

				std::cout << "texture loaded." << std::endl;

				texturesAndPaths.push_back(newTexture);
			}
		}
	}

	// Get textures from all children
	for (n = 0; n < nd->mNumChildren; ++n)
		recursiveTextureLoad(sc, nd->mChildren[n]);
}
コード例 #7
0
ファイル: testApp.cpp プロジェクト: hanasaan/ofxNatNet
//--------------------------------------------------------------
void testApp::draw() {
	ofEnableAlphaBlending();

	cam.begin();
	
	ofDrawAxis(100);

	ofFill();

	// draw all markers set
	ofSetColor(255, 128);
	for (int i = 0; i < max(0, (int)natnet.getNumMarkersSet() - 1); i++) {
		for (int j = 0; j < natnet.getMarkersSetAt(i).size(); j++) {
			ofDrawBox(natnet.getMarkersSetAt(i)[j], 3);
		}
	}
	
	// draw all markers
	ofSetColor(255, 30);
	for (int i = 0; i < natnet.getNumMarker(); i++) {
		ofDrawBox(natnet.getMarker(i), 3);
	}

	ofNoFill();

	// draw filtered markers
	ofSetColor(255);
	for (int i = 0; i < natnet.getNumFilterdMarker(); i++) {
		ofDrawBox(natnet.getFilterdMarker(i), 10);
	}

	// draw rigidbodies
	for (int i = 0; i < natnet.getNumRigidBody(); i++) {
		const ofxNatNet::RigidBody &RB = natnet.getRigidBodyAt(i);

		if (RB.isActive())
			ofSetColor(0, 255, 0);
		else
			ofSetColor(255, 0, 0);

		ofPushMatrix();
		glMultMatrixf(RB.getMatrix().getPtr());
		ofDrawAxis(30);
		ofPopMatrix();

		glBegin(GL_LINE_LOOP);
		for (int n = 0; n < RB.markers.size(); n++) {
			glVertex3fv(RB.markers[n].getPtr());
		}
		glEnd();

		for (int n = 0; n < RB.markers.size(); n++) {
			ofDrawBox(RB.markers[n], 5);
		}
	}
	
	// draw skeletons
	for (int j = 0;  j < natnet.getNumSkeleton(); j++) {
		const ofxNatNet::Skeleton &S = natnet.getSkeletonAt(j);
		ofSetColor(0, 0, 255);
		
		for (int i = 0; i < S.joints.size(); i++) {
			const ofxNatNet::RigidBody &RB = S.joints[i];
			ofPushMatrix();
			glMultMatrixf(RB.getMatrix().getPtr());
			ofDrawBox(5);
			ofPopMatrix();
		}
	}

	cam.end();

	string str;
	str += "frames: " + ofToString(natnet.getFrameNumber()) + "\n";
	str += "data rate: " + ofToString(natnet.getDataRate()) + "\n";
	str += string("connected: ") + (natnet.isConnected() ? "YES" : "NO") + "\n";
	str += "num markers set: " + ofToString(natnet.getNumMarkersSet()) + "\n";
	str += "num marker: " + ofToString(natnet.getNumMarker()) + "\n";
	str += "num filtered (non regidbodies) marker: " +
		   ofToString(natnet.getNumFilterdMarker()) + "\n";
	str += "num rigidbody: " + ofToString(natnet.getNumRigidBody()) + "\n";
	str += "num skeleton: " + ofToString(natnet.getNumSkeleton()) + "\n";

	ofSetColor(255);
	ofDrawBitmapString(str, 10, 20);
}
コード例 #8
0
ファイル: BridgeCraft.cpp プロジェクト: jbs2/bridgecraft
void Draw (void)
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);				// Clear Screen And Depth Buffer
	glLoadIdentity();												// Reset The Current Modelview Matrix
//	glTranslatef(-1.5f,0.0f,-6.0f);									// Move Left 1.5 Units And Into The Screen 6.0
	glTranslatef(0.0f,0.0f,-35.0f);

    glPushMatrix();													// NEW: Prepare Dynamic Transform
    glMultMatrixf(Transform.M);										// NEW: Apply Dynamic Transform
	glColor3f(0.20f,1.00f,0.3f);
//	Torus(0.30f,1.00f);
//	Timber(2.0f,0.1f);

//	float stepSize=0.08;
//	float k=0.5;
//	for(float i=-4; i<0; i=i+stepSize) {
//		Timber4(0.10f,i,-k,i+stepSize,k);
//		k=k==-0.5?0.5:-0.5;
//	}

//	Timber4(0.2f,-3.0f,-1.0f,-2.0f,1.0f);
//	std::cout<<wwidth<<"  "<<wheight<<"\n";
	if(!state)
		Objects::grid();
//	grid2();

//	bridge.addNewNode(-3.0f,0.0f);
//	bridge.addNewNode(-1.0f,1.0f);
	//	bridge.addEdge(0.1f,-3.0f,0.0f,-1.0f,1.0f);
//	bridge.addNewNode(1.0f,0.0f);
	//	bridge.addEdge(0.1f,-1.0f,1.0f,1.0f,0.0f);
	if(state) {
		for(int i=bridge->nedges; i--;) {
			Edge& e=bridge->edges[i];
	//		std::cout<<"\n"<<e.stress;
			glColor3f(e.stress,1.0f-e.stress,0.1f);
			Objects::timber4(e.width, e.from->p.x, e.from->p.y, e.to->p.x, e.to->p.y);
		}
	}
	else {
		for(int i=bridge->nedges; i--;) {
			Edge& e=bridge->edges[i];
			glColor3f(0.6f,0.6f,0.6f);
			Objects::timber4(e.width, e.from->b.x, e.from->b.y, e.to->b.x, e.to->b.y);
		}
		if(bridge->tEdge) {
			glColor3f(0.4f,0.4f,0.4f);
			Objects::timber4(bridge->tEdge->width,bridge->tEdge->from->b.x, bridge->tEdge->from->b.y,bridge->tEdge->to->b.x,bridge->tEdge->to->b.y);
		}
		if(recycleState)
			glColor3f(0.2f,0.2f,0.2f);
		else {
			if(recyclingMode)
				glColor3f(0.3f,1.0f,0.3f);
			else
				glColor3f(1.0f,1.0f,1.0f);
		}
		Objects::square(3.2,0,-13);
		if(!recyclingMode)
			glColor3f(0.190196f,0.67255f,0.98627f);
			//glColor3f(0.090196f,0.57255f,0.88627f); from image
		Objects::upButton(1.2,22,-11,1);
		Objects::upButton(1.2,22,-13,-1);
//		ncol(0.1,0.8,17,-11, true, true, true, true, true, true, true);
//		drawDigit(0.1,0.8,11,-11,0);
		Number::drawNumber(0.1,0.8,10,-12,thickness,4);
/*		drawNumber(0.1,0.8,13,-11,2);
		drawNumber(0.1,0.8,14,-11,3);
		drawNumber(0.1,0.8,15,-11,4);
		drawNumber(0.1,0.8,16,-11,5);
		drawNumber(0.1,0.8,17,-11,6);
		drawNumber(0.1,0.8,18,-11,7);
		drawNumber(0.1,0.8,19,-11,8);
		drawNumber(0.1,0.8,20,-11,9);*/
/*		nbeam(0.3,0.8,19,-11,1,true);
		nbeam(0.3,0.8,18,-11,-1,false);
		nbeam(0.3,0.8,20,-11,-1,true);
		nbeam(0.3,0.8,21,-11,1,false);*/
		for(int i=level->amountOfFix; i--;) {
			glColor3f(0.1f,0.1f,1.0f);
			Objects::timber4(0.2f,level->fixPositions[i].x-0.10f,level->fixPositions[i].y,level->fixPositions[i].x+0.10f,level->fixPositions[i].y);
//			std::cout<< level->fixPositions[i].x-0.05f << "  "<<level->fixPositions[i].y <<"  "<< level->fixPositions[i].x+0.05f << "  "<< level->fixPositions[i].y <<"\n";
		}
	}

//	Timber3(0.2f,-4.0f,-1.0f,-3.0f,0.0f);
//	Timber3(0.2f,-3.0f,0.0f,-2.0f,-1.0f);
//	Timber3(0.2f,-2.0f,-1.0f,-1.0f,0.0f);
    glPopMatrix();													// NEW: Unapply Dynamic Transform

	glLoadIdentity();												// Reset The Current Modelview Matrix
	glTranslatef(1.5f,0.0f,-6.0f);									// Move Right 1.5 Units And Into The Screen 7.0

//    glPushMatrix();													// NEW: Prepare Dynamic Transform
//    glMultMatrixf(Transform.M);										// NEW: Apply Dynamic Transform
//	glColor3f(1.0f,0.75f,0.75f);
//	gluSphere(quadratic,1.3f,10,10);
//    glPopMatrix();													// NEW: Unapply Dynamic Transform

	glFlush();														// Flush The GL Rendering Pipeline
	if(state) {
		int detail = 100;
		for(int i=detail; i--;)
			bridge->oneTimeStep(1.0f/(60.0f*(float)detail), level);
	}
}
コード例 #9
0
ファイル: display.c プロジェクト: johnh530/electro
int draw_persp(unsigned int i, float N, float F, int e, const float p[3])
{
    struct tile *T = get_tile(i);

    const int L = (T->flags & TILE_LEFT_EYE)  ? 1 : 0;
    const int R = (T->flags & TILE_RIGHT_EYE) ? 1 : 0;

    if ((L == 0 && R == 0) || (L == 1 && e == 0) || (R == 1 && e == 1))
    {
        float r[3];
        float u[3];
        float n[3];
        float k;

        float M[16];
        float I[16];

        float p0[3];
        float p1[3];
        float p3[3];

        /* Compute the screen corners. */

        p0[0] = p[0] - T->o[0];
        p0[1] = p[1] - T->o[1];
        p0[2] = p[2] - T->o[2];

        p1[0] = p[0] - T->r[0] - T->o[0];
        p1[1] = p[1] - T->r[1] - T->o[1];
        p1[2] = p[2] - T->r[2] - T->o[2];

        p3[0] = p[0] - T->u[0] - T->o[0];
        p3[1] = p[1] - T->u[1] - T->o[1];
        p3[2] = p[2] - T->u[2] - T->o[2];

        /* Configure the viewport. */

        glViewport(T->win_x, T->win_y, T->win_w, T->win_h);
        glScissor (T->win_x, T->win_y, T->win_w, T->win_h);

        /* Compute the projection. */

        r[0] = T->r[0];
        r[1] = T->r[1];
        r[2] = T->r[2];

        u[0] = T->u[0];
        u[1] = T->u[1];
        u[2] = T->u[2];

        cross(n, r, u);
        normalize(r);
        normalize(u);
        normalize(n);

        k = n[0] * (T->o[0] - p[0]) + 
            n[1] * (T->o[1] - p[1]) +
            n[2] * (T->o[2] - p[2]);

        glMatrixMode(GL_PROJECTION);
        {
            double fL = N * (r[0] * p0[0] + r[1] * p0[1] + r[2] * p0[2]) / k;
            double fR = N * (r[0] * p1[0] + r[1] * p1[1] + r[2] * p1[2]) / k;
            double fB = N * (u[0] * p0[0] + u[1] * p0[1] + u[2] * p0[2]) / k;
            double fT = N * (u[0] * p3[0] + u[1] * p3[1] + u[2] * p3[2]) / k;

            /* Flip the projection if requested. */

            if (T->flags & TILE_FLIP_X) swap(fL, fR);
            if (T->flags & TILE_FLIP_Y) swap(fB, fT);

            /* Apply the projection. */

            glLoadIdentity();
            glFrustum(fL, fR, fB, fT, N, F);

            /* Account for the orientation of the display. */

            M[0] = r[0]; M[4] = u[0]; M[8]  = n[0]; M[12] = 0.0f;
            M[1] = r[1]; M[5] = u[1]; M[9]  = n[1]; M[13] = 0.0f;
            M[2] = r[2]; M[6] = u[2]; M[10] = n[2]; M[14] = 0.0f;
            M[3] = 0.0f; M[7] = 0.0f; M[11] = 0.0f; M[15] = 1.0f;

            load_inv(I, M);
            glMultMatrixf(I);

            /* Move the apex of the frustum to the origin. */

            glTranslatef(-p[0], -p[1], -p[2]);
        }
        glMatrixMode(GL_MODELVIEW);

        glLoadIdentity();

        /* Rewind polygons if necessary. */

        if (((T->flags & TILE_FLIP_X) ? 1 : 0) ^
            ((T->flags & TILE_FLIP_Y) ? 1 : 0))
            glFrontFace(GL_CW);
        else
            glFrontFace(GL_CCW);

        return 1;
    }
    return 0;
}
コード例 #10
0
ファイル: main.cpp プロジェクト: pauljnixon/Graphics
/*  ===============================================
      Desc: 
      Precondition:
      Postcondition:
    =============================================== */ 
void myGlutDisplay(void)
{
	static float scale = 0.1;
	// Set our background color that the screen refreshes too
	glClearColor(0.1f, 0.1f, 0.2f, 1.0f);
	// Which bit planes get cleared
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	// Set up
	glMatrixMode(GL_MODELVIEW);
	// Give us a default matrix to start our scene from
	glLoadIdentity();

	//glScalef(scale,scale,scale);
	if(startTheScene==false){
		glTranslatef( view_pos[0], view_pos[1]-2, -view_pos[2]-6 );
	}
	/* Perform camera transformations 
	   Each camera funtion will be called after
	   a certain amount of time has elapsed.
	
		You are free to implement your own camera functions!
		*** Be Creative! ***
	
	*/
	if(startTheScene==true){
		// Output the time to the console, just a a director would have time
		// running on the camera.
		cout << difftime(time(NULL),start) << "s : ";
		if(difftime(time(NULL),start) <= 2){
			std::cout << "orthogonal" << endl;
			camera1->orthogonal(-1,1,-1,1,1,10);	// Get a unit perspective from above
		}
		else if(difftime(time(NULL),start) > 2 && difftime(time(NULL),start) <= 6){
			std::cout << "Close Up" << endl;
			// Close up shot on the T-Rex
			camera1->closeUp(trex->getXPosition(), trex->getYPosition(),trex->getZPosition(),
							1,10);	
		}
		else if(difftime(time(NULL),start) > 6 && difftime(time(NULL),start) <= 10){
			std::cout << "follow cam" << endl;
			//camera1->perspective(105,.75,1,10);	// Get the regular perspective
			camera1->follow(jeep->getXPosition(), jeep->getYPosition(),jeep->getZPosition(),
				0, 0, 0,
				0, 0, 0); // attach the camera to the t-rex
		}
		else if(difftime(time(NULL),start) > 10 && difftime(time(NULL),start) <= 14){
			std::cout << "spin cam" << endl;
			// Spin around a point in space.
			// Radius is fixed, but could be adjusted.
			// Y height may also need to be adjusted.
			camera1->spinAroundPoint(jeep->getXPosition(),jeep->getYPosition()-2,jeep->getZPosition(),2);
		}
		else{
			startTheScene=false;
			resetScene();
		}
	}


	glMultMatrixf(view_rotate);

		if (filled) {
			glEnable(GL_POLYGON_OFFSET_FILL);
			glColor3f(0.5, 0.5, 0.5);
			glPolygonMode(GL_FRONT, GL_FILL);
			startScene();
		}
		// Set our scene to a wireframe mode.
		if (wireframe) {
			glDisable(GL_POLYGON_OFFSET_FILL);
			glColor3f(1.0, 1.0, 1.0);
			glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
			startScene();
		}

		if(grid){
			draw_grid();
		}


	glutSwapBuffers();
}
コード例 #11
0
ファイル: OBJObject.cpp プロジェクト: Luyao61/Graphic-final
void OBJObject::draw(DrawData& data)
{
    material.apply();
    
    glMatrixMode(GL_MODELVIEW);
    
    glPushMatrix();
    glMultMatrixf(toWorld.ptr());
    
    if (hasBBox) {
        drawBoundingBox();
    }
    
    glBegin(GL_TRIANGLES);
    
    
    //Loop through the faces
    //For each face:
    //  Look up the vertices, normals (if they exist), and texcoords (if they exist)
    //  Draw them as triplets:
    
    //      glNorm(normals->at(face.normalIndices[0]))
    //      glVert(vertices->at(face.vertexIndices[0]))
    //      Etc.
    //
    int i = 0;
    try {
        for ( i = 0; i < faces->size(); i++) {
            
            Vector3 vn1 = *normals -> at(faces->at(i)->normalIndices[0]);
            Vector3 vn2 = *normals -> at(faces->at(i)->normalIndices[1]);
            Vector3 vn3 = *normals -> at(faces->at(i)->normalIndices[2]);
            
            Vector3 v1 = *vertices -> at(faces->at(i)->vertexIndices[0]);
            Vector3 v2 = *vertices -> at(faces->at(i)->vertexIndices[1]);
            Vector3 v3 = *vertices -> at(faces->at(i)->vertexIndices[2]);
            
            // if it is bunny file, add color
            if (colors->size() == vertices ->size()) {
                Vector3 color1 = *colors -> at(faces->at(i)->vertexIndices[0]);
                Vector3 color2 = *colors -> at(faces->at(i)->vertexIndices[1]);
                Vector3 color3 = *colors -> at(faces->at(i)->vertexIndices[2]);
                
                
                glNormal3f(*vn1.ptr(), *(vn1.ptr()+1), *(vn1.ptr()+2));
                glColor3f(*color1.ptr(), *(color1.ptr()+1), *(color1.ptr()+2));
                glVertex3f(*v1.ptr(), *(v1.ptr()+1), *(v1.ptr()+2));
                
                glNormal3f(*vn2.ptr(), *(vn2.ptr()+1), *(vn2.ptr()+2));
                glColor3f(*color2.ptr(), *(color2.ptr()+1), *(color2.ptr()+2));
                glVertex3f(*v2.ptr(), *(v2.ptr()+1), *(v2.ptr()+2));
                
                glNormal3f(*vn3.ptr(), *(vn3.ptr()+1), *(vn3.ptr()+2));
                glColor3f(*color3.ptr(), *(color3.ptr()+1), *(color3.ptr()+2));
                glVertex3f(*v3.ptr(), *(v3.ptr()+1), *(v3.ptr()+2));
            }
            else{
                glNormal3f(*vn1.ptr(), *(vn1.ptr()+1), *(vn1.ptr()+2));
                glVertex3f(*v1.ptr(), *(v1.ptr()+1), *(v1.ptr()+2));
                glNormal3f(*vn2.ptr(), *(vn2.ptr()+1), *(vn2.ptr()+2));
                glVertex3f(*v2.ptr(), *(v2.ptr()+1), *(v2.ptr()+2));
                glNormal3f(*vn3.ptr(), *(vn3.ptr()+1), *(vn3.ptr()+2));
                glVertex3f(*v3.ptr(), *(v3.ptr()+1), *(v3.ptr()+2));
            }
        }
    } catch (const std::out_of_range& oor) {
        
        std::cerr << "Out of Range error: " << oor.what() <<" :" << i  <<"face.size:" << faces->size()<< '\n';
        exit(-1);
        
    }

    glEnd();
    
    glPopMatrix();
}
コード例 #12
0
ファイル: channel.cpp プロジェクト: dardok/Equalizer
void Channel::frameDraw( const eq::uint128_t& frameID )
{
    if( stopRendering( ))
        return;

    _initJitter();
    if( _isDone( ))
        return;

    Window* window = static_cast< Window* >( getWindow( ));
    VertexBufferState& state = window->getState();
    const Model* oldModel = _model;
    const Model* model = _getModel();

    if( oldModel != model )
        state.setFrustumCulling( false ); // create all display lists/VBOs

    if( model )
        _updateNearFar( model->getBoundingSphere( ));

    eq::Channel::frameDraw( frameID ); // Setup OpenGL state

    glLightfv( GL_LIGHT0, GL_POSITION, lightPosition );
    glLightfv( GL_LIGHT0, GL_AMBIENT,  lightAmbient  );
    glLightfv( GL_LIGHT0, GL_DIFFUSE,  lightDiffuse  );
    glLightfv( GL_LIGHT0, GL_SPECULAR, lightSpecular );

    glMaterialfv( GL_FRONT, GL_AMBIENT,   materialAmbient );
    glMaterialfv( GL_FRONT, GL_DIFFUSE,   materialDiffuse );
    glMaterialfv( GL_FRONT, GL_SPECULAR,  materialSpecular );
    glMateriali(  GL_FRONT, GL_SHININESS, materialShininess );

    const FrameData& frameData = _getFrameData();
    glPolygonMode( GL_FRONT_AND_BACK,
                   frameData.useWireframe() ? GL_LINE : GL_FILL );

    const eq::Vector3f& position = frameData.getCameraPosition();

    glMultMatrixf( frameData.getCameraRotation().array );
    glTranslatef( position.x(), position.y(), position.z() );
    glMultMatrixf( frameData.getModelRotation().array );

    if( frameData.getColorMode() == COLOR_DEMO )
    {
        const eq::Vector3ub color = getUniqueColor();
        glColor3ub( color.r(), color.g(), color.b() );
    }
    else
        glColor3f( .75f, .75f, .75f );

    if( model )
        _drawModel( model );
    else
    {
        glNormal3f( 0.f, -1.f, 0.f );
        glBegin( GL_TRIANGLE_STRIP );
        glVertex3f(  .25f, 0.f,  .25f );
        glVertex3f( -.25f, 0.f,  .25f );
        glVertex3f(  .25f, 0.f, -.25f );
        glVertex3f( -.25f, 0.f, -.25f );
        glEnd();
    }

    state.setFrustumCulling( true );
    Accum& accum = _accum[ lunchbox::getIndexOfLastBit( getEye()) ];
    accum.stepsDone = LB_MAX( accum.stepsDone,
                              getSubPixel().size * getPeriod( ));
    accum.transfer = true;
}
コード例 #13
0
ファイル: ARNativeOSG.cpp プロジェクト: AadityaDev/artoolkit5
JNIEXPORT void JNICALL JNIFUNCTION_NATIVE(nativeDrawFrame(JNIEnv* env, jobject obj))
{
	float width, height;
    
    if (!videoInited) {
#ifdef DEBUG
        LOGI("nativeDrawFrame !VIDEO\n");
#endif        
        return; // No point in trying to draw until video is inited.
    }
#ifdef DEBUG
    LOGI("nativeDrawFrame\n");
#endif        
    if (!gARViewInited) {
        if (!initARView()) return;
    }
    if (gARViewLayoutRequired) layoutARView();
    
    // Upload new video frame if required.
    if (videoFrameNeedsPixelBufferDataUpload) {
        arglPixelBufferDataUploadBiPlanar(gArglSettings, gVideoFrame, gVideoFrame + videoWidth*videoHeight);
        videoFrameNeedsPixelBufferDataUpload = false;
    }
    
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear the buffers for new frame.
    
    // Display the current frame
    arglDispImage(gArglSettings);
    
    // Set up 3D mode.
	glMatrixMode(GL_PROJECTION);
	glLoadMatrixf(cameraLens);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
    glStateCacheEnableDepthTest();

    // Set any initial per-frame GL state you require here.
    // --->

    // Lighting and geometry that moves with the camera should be added here.
    // (I.e. should be specified before camera pose transform.)
    // --->
    
    VirtualEnvironmentHandleARViewDrawPreCamera();
    
    if (cameraPoseValid) {
        
        glMultMatrixf(cameraPose);
        
        // All lighting and geometry to be drawn in world coordinates goes here.
        // --->
        VirtualEnvironmentHandleARViewDrawPostCamera();
    }

    // If you added external OpenGL code above, and that code doesn't use the glStateCache routines,
    // then uncomment the line below.
    //glStateCacheFlush();
    
    // Set up 2D mode.
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
	width = (float)viewPort[viewPortIndexWidth];
	height = (float)viewPort[viewPortIndexHeight];
	glOrthof(0.0f, width, 0.0f, height, -1.0f, 1.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glStateCacheDisableDepthTest();

    // Add your own 2D overlays here.
    // --->
    
    VirtualEnvironmentHandleARViewDrawOverlay();
    
    // If you added external OpenGL code above, and that code doesn't use the glStateCache routines,
    // then uncomment the line below.
    //glStateCacheFlush();

#ifdef DEBUG
    // Example of 2D drawing. It just draws a white border line. Change the 0 to 1 to enable.
    const GLfloat square_vertices [4][2] = { {0.5f, 0.5f}, {0.5f, height - 0.5f}, {width - 0.5f, height - 0.5f}, {width - 0.5f, 0.5f} };
    glStateCacheDisableLighting();
    glStateCacheDisableTex2D();
    glVertexPointer(2, GL_FLOAT, 0, square_vertices);
    glStateCacheEnableClientStateVertexArray();
    glColor4ub(255, 255, 255, 255);
    glDrawArrays(GL_LINE_LOOP, 0, 4);
#endif
}
コード例 #14
0
ファイル: GrassDrawer.cpp プロジェクト: nixtux/spring
void CGrassDrawer::SetupGlStateNear()
{
	// bind textures
	{
		glActiveTextureARB(GL_TEXTURE0_ARB);
			glBindTexture(GL_TEXTURE_2D, grassBladeTex);
		glActiveTextureARB(GL_TEXTURE1_ARB);
			glBindTexture(GL_TEXTURE_2D, readMap->GetGrassShadingTexture());
		glActiveTextureARB(GL_TEXTURE2_ARB);
			glBindTexture(GL_TEXTURE_2D, readMap->GetShadingTexture());
		glActiveTextureARB(GL_TEXTURE3_ARB);
			glBindTexture(GL_TEXTURE_2D, infoTextureHandler->GetCurrentInfoTexture());
		glActiveTextureARB(GL_TEXTURE5_ARB);
			glBindTexture(GL_TEXTURE_CUBE_MAP_ARB, cubeMapHandler->GetSpecularTextureID());
	}

	// bind shader
	if (globalRendering->haveGLSL) {
		EnableShader(GRASS_PROGRAM_NEAR);

		if (shadowHandler->ShadowsLoaded())
			shadowHandler->SetupShadowTexSampler(GL_TEXTURE4);

		glMatrixMode(GL_PROJECTION);
			glPushMatrix();
			glMultMatrixf(camera->GetViewMatrix());
		glMatrixMode(GL_MODELVIEW);
			glPushMatrix();
			glLoadIdentity();
	} else {
		// FPP enable textures
		glActiveTextureARB(GL_TEXTURE0_ARB);
			glEnable(GL_TEXTURE_2D);
		glActiveTextureARB(GL_TEXTURE1_ARB);
			glEnable(GL_TEXTURE_2D);
			glMultiTexCoord4f(GL_TEXTURE1_ARB, 1.0f,1.0f,1.0f,1.0f); // workaround a nvidia bug with TexGen
			SetTexGen(1.0f / (mapDims.mapx * SQUARE_SIZE), 1.0f / (mapDims.mapy * SQUARE_SIZE), 0.0f, 0.0f);
		glActiveTextureARB(GL_TEXTURE2_ARB);
			glEnable(GL_TEXTURE_2D);
			glMultiTexCoord4f(GL_TEXTURE2_ARB, 1.0f,1.0f,1.0f,1.0f); // workaround a nvidia bug with TexGen
			SetTexGen(1.0f / (mapDims.pwr2mapx * SQUARE_SIZE), 1.0f / (mapDims.pwr2mapy * SQUARE_SIZE), 0.0f, 0.0f);
			glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);
			glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB_ARB, GL_PREVIOUS_ARB);
			glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB_ARB, GL_TEXTURE);
			glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_MODULATE);
			glTexEnvi(GL_TEXTURE_ENV, GL_RGB_SCALE_ARB, 2);
		if (infoTextureHandler->IsEnabled()) {
			glActiveTextureARB(GL_TEXTURE3_ARB);
				glEnable(GL_TEXTURE_2D);
				glMultiTexCoord4f(GL_TEXTURE3_ARB, 1.0f,1.0f,1.0f,1.0f); // workaround a nvidia bug with TexGen
				SetTexGen(1.0f / (mapDims.pwr2mapx * SQUARE_SIZE), 1.0f / (mapDims.pwr2mapy * SQUARE_SIZE), 0.0f, 0.0f);
				glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB_ARB, GL_ADD_SIGNED_ARB);
				glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA_ARB, GL_MODULATE);
				glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA_ARB, GL_PREVIOUS_ARB);
				glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_ALPHA_ARB, GL_TEXTURE);
				glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_COMBINE_ARB);
		}
	}

	glActiveTextureARB(GL_TEXTURE0_ARB);
	glDisable(GL_BLEND);
	glDisable(GL_ALPHA_TEST);
	glDepthMask(GL_TRUE);
	sky->SetupFog();
}
コード例 #15
0
ファイル: arcball.cpp プロジェクト: egils/Grafika--3-u-duotis
// affect the arcball's orientation on openGL
void arcball_rotate() {
	glMultMatrixf(ab_quat);
}
コード例 #16
0
ファイル: ArmMuscledViz.cpp プロジェクト: buhrmann/dynmx
// Overwrite base class update
//----------------------------------------------------------------------------------------------------------------------
void ArmMuscledViz::update()
{
  // Let simple viz do its rendering first
  //ArmViz::update();
  
  glPushAttrib(GL_LIGHTING);
  glDisable(GL_LIGHTING);  
  glDisable(GL_DEPTH_TEST);  
  
  // Get shoulder and elbow TMs and other useful data
  const float shdAngle = m_arm->getJointAngle(JT_shoulder);
  const float elbAngle = m_arm->getJointAngle(JT_elbow);
  
  const ci::Vec3f elbPos = Vec3f(m_arm->getElbowPos());
  //const ci::Vec3f effPos = Vec3f(m_arm->getEffectorPos());
  const ci::Vec3f shdPos = Vec3f(0,0,0);
  
  const double elbRad = m_arm->getJointRadius(JT_elbow);
  const double shdRad = m_arm->getJointRadius(JT_shoulder);   

  ci::Matrix44f elbLimTM;
  elbLimTM.setToIdentity();
  elbLimTM.rotate(Vec3f(0.0f, 0.0f, 1.0f), shdAngle); 
  elbLimTM.setTranslate(elbPos);    
  
  ci::Matrix44f elbTM = elbLimTM;
  elbTM.rotate(Vec3f(0,0,1), elbAngle);
  
  ci::Matrix44f shdTM;
  shdTM.setToIdentity();
  shdTM.rotate(Vec3f(0.0f, 0.0f, 1.0f), shdAngle); 
  shdTM.setTranslate(shdPos);      

  // Overall position and orientation
  glPushMatrix();
  glMultMatrixf(*m_pTM);   
  glLineWidth(1.0);
  glColor3f(0,0,0);
  
  // Desired kinematic state
  if(m_drawDesiredState)
  {
    Pos p1, p2;    
    double desElbAngle = m_arm->getDesiredJointAngle(JT_elbow); 
    double desShdAngle = m_arm->getDesiredJointAngle(JT_shoulder); 
    m_arm->forwardKinematics(desElbAngle, desShdAngle, p1, p2);
    
    Vec3f desShdPos(0,0,0);
    Vec3f desElbPos(p1);
    Vec3f desEffPos(p2);
    ci::gl::color(m_colors.desired);
    // Draw bones
    glEnable(GL_LINE_STIPPLE);
    glLineStipple(2, 0xAAAA);
    ci::gl::drawLine(desShdPos, desElbPos);
    ci::gl::drawLine(desElbPos, desEffPos);
    glDisable(GL_LINE_STIPPLE);
    
    // Points indicating joints
    glPointSize(4.0);
    glBegin(GL_POINTS);
    glVertex3f(desShdPos.x, desShdPos.y, 0.0);
    glVertex3f(desElbPos.x, desElbPos.y, 0.0);
    glVertex3f(desEffPos.x, desEffPos.y, 0.0);
    glEnd();
  }    
  
  // Draw elbow joint and bone
  glPushMatrix();
  glMultMatrixf(elbTM);
  // bone triangle
  ci::gl::color(m_colors.boneFill);
  ci::Vec3f lt = -elbRad * ci::Vec3f(0,1,0);
  ci::Vec3f rt = elbRad * ci::Vec3f(0,1,0);
  ci::Vec3f bt = m_arm->getLength(JT_elbow) * ci::Vec3f(1,0,0);
  drawTriangle(rt, lt, bt);
  ci::gl::color(m_colors.boneOutline);
  drawTriangle(rt, lt, bt, GL_LINE);
  ci::gl::drawLine(ci::Vec2f(&bt.x), elbRad * ci::Vec2f(1,0));
  // joint disk
  ci::gl::color(m_colors.jointFill);
  ci::gl::drawSolidCircle(ci::Vec2f(0,0), elbRad, 32);
  ci::gl::color(m_colors.jointOutline);
  ci::gl::drawStrokedCircle(ci::Vec2f(0,0), elbRad, 32);

  glPopMatrix();
  
  // Draw elbow limits
  glPushMatrix();
  glMultMatrixf(elbLimTM);
  float limMin = radiansToDegrees(m_arm->getJointLimitLower(JT_elbow));
  float limMax = radiansToDegrees(m_arm->getJointLimitUpper(JT_elbow));
  ci::gl::color(m_colors.limitsFill);
  drawPartialDisk(elbRad, elbRad + 0.01, 16, 1, 90 - limMin, -(limMax - limMin));
  glPopMatrix();
  
  // Draw shoulder joint and bone
  glColor3f(0,0,0);  
  glPushMatrix();
  glMultMatrixf(shdTM);
  // bone triangle
  lt = -shdRad * ci::Vec3f(0,1,0);
  rt = shdRad * ci::Vec3f(0,1,0);
  bt = m_arm->getLength(JT_shoulder) * ci::Vec3f(1,0,0);  
  ci::gl::color(m_colors.boneFill);
  drawTriangle(rt, lt, bt);
  ci::gl::color(m_colors.boneOutline);
  drawTriangle(rt, lt, bt, GL_LINE);
  ci::gl::drawLine(m_arm->getLength(JT_shoulder) * ci::Vec2f(1,0), shdRad * ci::Vec2f(1,0));
  // joint disk
  ci::gl::color(m_colors.jointFill);
  ci::gl::drawSolidCircle(ci::Vec2f(0,0), shdRad, 32);
  ci::gl::color(m_colors.jointOutline);
  ci::gl::drawStrokedCircle(ci::Vec2f(0,0), shdRad, 32);
  glPopMatrix();
  
  // Draw shoulder limits
  limMin = m_arm->getJointLimitLower(JT_shoulder) * RAD_TO_DEG;
  limMax = m_arm->getJointLimitUpper(JT_shoulder) * RAD_TO_DEG;  
  ci::gl::color(m_colors.limitsFill);
  drawPartialDisk(shdRad, shdRad + 0.01, 16, 1, 90 - limMin, -(limMax - limMin));
  glLineWidth(1.0);    
  
  // Trajectory  
  if(m_drawOverlays)
  {
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);
    const std::deque<Pos>& effTrajectory = m_arm->getTrajectory();
    int numPoints =  effTrajectory.size();  
    float lineVerts[numPoints*2];
    float colors[numPoints*4];
    glVertexPointer(2, GL_FLOAT, 0, lineVerts); // 2d positions
    glColorPointer(4, GL_FLOAT, 0, colors);     // 4d colors
    
    for(size_t i = 0; i < numPoints; i++)
    {
      lineVerts[i*2 + 0] = effTrajectory[i].x;
      lineVerts[i*2 + 1] = effTrajectory[i].y;
      float a = 0.5 * (float)i / (float)numPoints;
      
      colors[i*4 + 0] = m_colors.trajectory[0];
      colors[i*4 + 1] = m_colors.trajectory[1];
      colors[i*4 + 2] = m_colors.trajectory[2];
      colors[i*4 + 3] = a;
    }
    glLineWidth(2.0);
    glDrawArrays( GL_LINE_STRIP, 0, numPoints);
    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
    glLineWidth(1.0);  
  }
  
  // Draw muscles
  for(size_t i = 0; i < m_arm->getNumMuscles(); ++i)
  {
    Muscle* muscle = m_arm->getMuscle(i);
    double act = muscle->getActivation();
    
    // Muscle line width dependent on activation
    float lineWidth = act * 32.0;
    glLineWidth(lineWidth);

    // Muscle colour dependent on length
    float l = muscle->getNormalisedLength() - 1;
    l = clamp(l, -1.0f, 1.0f);

    ci::ColorA col = m_colors.midMuscle;
    if(l >= 0)
    {
      col += (m_colors.longMuscle - m_colors.midMuscle) * l;
    }
    else
    {
      col -= (m_colors.shortMuscle - m_colors.midMuscle) * l;
    }    
    ci::gl::color(col);
    
    // Draw origin and insertion points
    Vec3f origin = Vec3f(muscle->getOriginWorld());
    Vec3f insertion = Vec3f(muscle->getInsertionWorld());    
    glPointSize(4.0);
    glBegin(GL_POINTS);
    glVertex3f(origin.x, origin.y, 0);
    glVertex3f(insertion.x, insertion.y, 0);
    glEnd();
    
    if(muscle->isMonoArticulate())
    {
      MuscleMonoWrap* m = ((MuscleMonoWrap*)muscle);        
      if(!m->m_muscleWraps)
      {
        //ci::Vec2f dir = m->getInsertionWorld() - m->getOriginWorld();
        //dir.normalize();
        // Only hold in the non-wrapping case. Otherwise we need to do a proper projection (dot product).
        //ci::Vec2f closestPoint = m->getOriginWorld() + dir * m->m_originCapsuleDist;
        //ci::Vec2f maVec = closestPoint - m_arm->getElbowPos();
        //float ma = maVec.length();
        //const bool muscleWraps = ma < r && m_arm->getJointAngle(JT_elbow) < PI_OVER_TWO;
        //ci::gl::drawLine(ci::Vec3f(closestPoint), ci::Vec3f(m_arm->getElbowPos())); 
        ci::gl::drawLine(origin, insertion); 
        // Indicate optimal length
        //ci::Vec3f l0Pos = origin + m->getOptimalLength() * (insertion - origin).normalized();
        //drawPoint(l0Pos, 4.0);
      }    
      else
      {
        // Upstream segment
        ci::Vec2f pathDir = (m->m_joint == JT_elbow) ? m_arm->getElbowPos() : ci::Vec2f(1, 0);
        float rotDir = m->m_isFlexor ? 1.0 : -1.0;
        pathDir.rotate(rotDir * (PI_OVER_TWO - m->m_originCapsuleAngle));
        pathDir.normalize();
        ci::Vec2f pathEnd = m->getOriginWorld() + (pathDir * m->m_originCapsuleDist);
        ci::gl::drawLine(origin, ci::Vec3f(pathEnd));
        
        // Downstream segment
        pathDir = (m->m_joint == JT_elbow) ? (m_arm->getElbowPos() - m_arm->getEffectorPos()) : ( -m_arm->getElbowPos());
        pathDir.rotate(-rotDir * (PI_OVER_TWO - m->m_insertCapsuleAngle));
        pathDir.normalize();
        pathEnd = m->getInsertionWorld() + (pathDir * m->m_insertCapsuleDist);
        ci::gl::drawLine(insertion, ci::Vec3f(pathEnd));     
      }
    } // is mono
    else 
    {
      glPushAttrib (GL_LINE_BIT);
      glEnable(GL_LINE_STIPPLE);
      glLineStipple (1, 0xAAAA);
      MuscleBiWrap* m = ((MuscleBiWrap*)muscle);
      if (m->wrapsElbow() && m->wrapsShoulder())
      {
        //glColor3f(0,0,1);
        // Upstream segment: always shoulder
        ci::Vec2f pathDir = ci::Vec2f(1, 0);
        float rotDir = m->m_isFlexor ? 1.0 : -1.0;
        pathDir.rotate(rotDir * (PI_OVER_TWO - m->m_originCapsuleAngle));
        pathDir.normalize();
        ci::Vec2f pathEnd = m->getOriginWorld() + (pathDir * m->m_originCapsuleDist);
        ci::gl::drawLine(origin, ci::Vec3f(pathEnd));        
        // Downstream segment: always elbow.
        pathDir = m_arm->getElbowPos() - m_arm->getEffectorPos();
        pathDir.rotate(-rotDir * (PI_OVER_TWO - m->m_insertCapsuleAngle));
        pathDir.normalize();
        pathEnd = m->getInsertionWorld() + (pathDir * m->m_insertCapsuleDist);
        ci::gl::drawLine(insertion, ci::Vec3f(pathEnd));
        // Middle segment
        pathDir = m_arm->getElbowPos();
        pathDir.rotate(rotDir * m->m_gammaAngle);
        pathDir.normalize();
        pathDir = pathDir * m->m_momentArms[JT_shoulder];
        ci::Vec2f pathStart = pathDir;
        
        pathDir = m_arm->getEffectorPos() - m_arm->getElbowPos();
        pathDir.rotate(rotDir * (m->m_insertCapsuleAngle + m->getWrapAngle(JT_elbow)));
        pathDir.normalize();
        pathDir = pathDir * m_arm->getJointRadius(JT_elbow);
        pathEnd = m_arm->getElbowPos() + pathDir;      
        ci::gl::drawLine(ci::Vec3f(pathStart), ci::Vec3f(pathEnd));          
      }
      else if (m->wrapsElbow())
      {
        //glColor3f(0,1,0);
        // Downstream segment: always elbow. Upstream segment from origin to capsule
        ci::Vec2f pathDir = ci::Vec2f(m_arm->getElbowPos() - m_arm->getEffectorPos());
        float rotDir = m->m_isFlexor ? 1.0 : -1.0;
        pathDir.rotate(-rotDir * (PI_OVER_TWO - m->m_insertCapsuleAngle));
        pathDir.normalize();
        ci::Vec2f pathEnd = m->getInsertionWorld() + (pathDir * m->m_insertCapsuleDist);
        ci::gl::drawLine(insertion, ci::Vec3f(pathEnd));
        
        pathDir = m_arm->getEffectorPos() - m_arm->getElbowPos();
        pathDir.rotate(rotDir * (m->m_insertCapsuleAngle + m->getWrapAngle(JT_elbow)));
        pathDir.normalize();
        pathDir = pathDir * m_arm->getJointRadius(JT_elbow);
        pathEnd = m_arm->getElbowPos() + pathDir;
        ci::gl::drawLine(origin, ci::Vec3f(pathEnd));
      }
      else if (m->wrapsShoulder())
      {
        //glColor3f(1,0,0);
        // Upstream segment: always shoulder
        ci::Vec2f pathDir = ci::Vec2f(1, 0);
        float rotDir = m->m_isFlexor ? 1.0 : -1.0;
        pathDir.rotate(rotDir * (PI_OVER_TWO - m->m_originCapsuleAngle));
        pathDir.normalize();
        ci::Vec2f pathEnd = m->getOriginWorld() + (pathDir * m->m_originCapsuleDist);
        ci::gl::drawLine(origin, ci::Vec3f(pathEnd));
        
        //Downstream segment: from capsule to insertion
        pathDir = m_arm->getElbowPos();
        pathDir.rotate(rotDir * m->m_gammaAngle);
        pathDir.normalize();
        pathDir = pathDir * m->m_momentArms[JT_shoulder];
        ci::Vec2f pathStart = pathDir;
        ci::gl::drawLine(ci::Vec3f(pathStart), insertion);
      }
      else
      {
        // No wrap
        //glColor3f(1,1,1);
        ci::gl::drawLine(origin, insertion);          
      }
      glPopAttrib();
    }
  } // for all muscles
  
  glLineWidth(1.0);
  
  glPopMatrix();
  glEnable(GL_DEPTH_TEST);    
  
  glPopAttrib();  
}
コード例 #17
0
ファイル: Model3D.cpp プロジェクト: eaquiroz/Verse
void Model3D::recursive_render(const struct aiScene *sc, const struct aiNode* nd) {
	int i;
	unsigned int n = 0, t;
	struct aiMatrix4x4 m = nd->mTransformation;

	// update transform
	aiTransposeMatrix4(&m);
	glPushMatrix();
	glMultMatrixf((float*) &m);

	// draw all meshes assigned to this node
	for (; n < nd->mNumMeshes; ++n) {
		const struct aiMesh* mesh = sc->mMeshes[nd->mMeshes[n]];

		if (n < texturesAndPaths.size())
			glBindTexture(GL_TEXTURE_2D, texturesAndPaths[n].hTexture);

		apply_material(sc->mMaterials[mesh->mMaterialIndex]);

		if (mesh->mNormals == NULL
		)
			glDisable(GL_LIGHTING);
		else
			glEnable(GL_LIGHTING);

		if (mesh->mColors[0] != NULL
		)
			glEnable(GL_COLOR_MATERIAL);
		else
			glDisable(GL_COLOR_MATERIAL);

		for (t = 0; t < mesh->mNumFaces; ++t) {
			const struct aiFace* face = &mesh->mFaces[t];
			GLenum face_mode;

			switch (face->mNumIndices) {
			case 1:
				face_mode = GL_POINTS;
				break;
			case 2:
				face_mode = GL_LINES;
				break;
			case 3:
				face_mode = GL_TRIANGLES;
				break;
			default:
				face_mode = GL_POLYGON;
				break;
			}

			glBegin(face_mode);

			for (i = 0; i < face->mNumIndices; i++) {
				int index = face->mIndices[i];
				if (mesh->mColors[0] != NULL
				)
					Color4f(&mesh->mColors[0][index]);
				if (mesh->mNormals != NULL
				)
					glNormal3fv(&mesh->mNormals[index].x);
				if (mesh->HasTextureCoords(0))
					glTexCoord2f(mesh->mTextureCoords[0][index].x, mesh->mTextureCoords[0][index].y);
				glVertex3fv(&mesh->mVertices[index].x);
			}

			glEnd();
		}
	}

	// draw all children
	for (n = 0; n < nd->mNumChildren; ++n)
		recursive_render(sc, nd->mChildren[n]);

	glPopMatrix();
}
コード例 #18
0
ファイル: Viewer.cpp プロジェクト: castoryan/QR_SLAM
    void Viewer::DrawKeyFrames(const bool bDrawKF, const bool bDrawGraph)
    {
        const float &w = mKeyFrameSize;
        const float h = w*0.75;
        const float z = w*0.6;

        const vector<KeyFrame*> vpKFs = kfs;

        if(bDrawKF)
        {
            for(size_t i=0; i<vpKFs.size(); i++)
            {
                KeyFrame* pKF = vpKFs[i];
                cv::Mat Twc = pKF->Twc.t();

                glPushMatrix();

                glMultMatrixf(Twc.ptr<GLfloat>(0));

                glLineWidth(mKeyFrameLineWidth);
                glColor3f(0.0f,0.0f,1.0f);
                glBegin(GL_LINES);
                glVertex3f(0,0,0);
                glVertex3f(w,h,z);
                glVertex3f(0,0,0);
                glVertex3f(w,-h,z);
                glVertex3f(0,0,0);
                glVertex3f(-w,-h,z);
                glVertex3f(0,0,0);
                glVertex3f(-w,h,z);

                glVertex3f(w,h,z);
                glVertex3f(w,-h,z);

                glVertex3f(-w,h,z);
                glVertex3f(-w,-h,z);

                glVertex3f(-w,h,z);
                glVertex3f(w,h,z);

                glVertex3f(-w,-h,z);
                glVertex3f(w,-h,z);
                glEnd();

                glPopMatrix();
            }
        }
/*
        if(bDrawGraph)
        {
            glLineWidth(mGraphLineWidth);
            glColor4f(0.0f,1.0f,0.0f,0.6f);
            glBegin(GL_LINES);

            for(size_t i=0; i<vpKFs.size(); i++)
            {
                // Covisibility Graph
                const vector<KeyFrame*> vCovKFs = vpKFs[i]->GetCovisiblesByWeight(100);
                cv::Mat Ow = vpKFs[i]->GetCameraCenter();
                if(!vCovKFs.empty())
                {
                    for(vector<KeyFrame*>::const_iterator vit=vCovKFs.begin(), vend=vCovKFs.end(); vit!=vend; vit++)
                    {
                        if((*vit)->mnId<vpKFs[i]->mnId)
                            continue;
                        cv::Mat Ow2 = (*vit)->GetCameraCenter();
                        glVertex3f(Ow.at<float>(0),Ow.at<float>(1),Ow.at<float>(2));
                        glVertex3f(Ow2.at<float>(0),Ow2.at<float>(1),Ow2.at<float>(2));
                    }
                }

                // Spanning tree
                KeyFrame* pParent = vpKFs[i]->GetParent();
                if(pParent)
                {
                    cv::Mat Owp = pParent->GetCameraCenter();
                    glVertex3f(Ow.at<float>(0),Ow.at<float>(1),Ow.at<float>(2));
                    glVertex3f(Owp.at<float>(0),Owp.at<float>(1),Owp.at<float>(2));
                }


            }

            glEnd();
        }
        */
    }
コード例 #19
0
void soundManagerApp::myDraw()
{
   //std::cout << "\n--- myDraw() ---\n";

   //std::cout << "HeadPos:" << vrj::Coord(*mHead->getData()).pos << "\t"
   //          << "WandPos:" << vrj::Coord(*mWand->getData()).pos << std::endl;

   glMatrixMode(GL_MODELVIEW);

      // -- Draw box on wand --- //
   gmtl::Matrix44f wandMatrix = mWand->getData();      // Get the wand matrix

   glPushMatrix();
      // cout << "wand:\n" << *wandMatrix << endl;
      glPushMatrix();
         glMultMatrixf(wandMatrix.mData);  // Push the wand matrix on the stack
         //glColor3f(1.0f, 0.0f, 1.0f);
         float wand_color[3];
         wand_color[0] = wand_color[1] = wand_color[2] = 0.0f;
         if(mButton0->getData() == gadget::Digital::ON)
            wand_color[0] += 0.5f;
         if(mButton1->getData() == gadget::Digital::ON)
            wand_color[1] += 0.5f;
         if(mButton2->getData() == gadget::Digital::ON)
            wand_color[2] += 0.5f;
         if(mButton3->getData() == gadget::Digital::ON)
            wand_color[0] += 0.5f;
         if(mButton4->getData() == gadget::Digital::ON)
            wand_color[1] += 0.5f;
         if(mButton5->getData() == gadget::Digital::ON)
            wand_color[2] += 0.5f;
         glColor3fv(wand_color);
         glScalef(0.25f, 0.25f, 0.25f);
         drawCube();
      glPopMatrix();

         // A little laser pointer
      glLineWidth(5.0f);



      // Draw Axis
      glDisable(GL_LIGHTING);
      glPushMatrix();
         glMultMatrixf(wandMatrix.mData);    // Goto wand position

         gmtl::Vec3f x_axis(7.0f,0.0f,0.0f);
         gmtl::Vec3f y_axis(0.0f, 7.0f, 0.0f);
         gmtl::Vec3f z_axis(0.0f, 0.0f, 7.0f);
         gmtl::Vec3f origin(0.0f, 0.0f, 0.0f);

         glBegin(GL_LINES);
            glColor3f(1.0f, 0.0f, 0.0f);
            glVertex3fv(origin.mData);
            glVertex3fv(x_axis.mData);

            glColor3f(0.0f, 1.0f, 0.0f);
            glVertex3fv(origin.mData);
            glVertex3fv(y_axis.mData);

            glColor3f(0.0f, 0.0f, 1.0f);
            glVertex3fv(origin.mData);
            glVertex3fv(z_axis.mData);
         glEnd();
      glPopMatrix();
      glEnable(GL_LIGHTING);
   glPopMatrix();

}
コード例 #20
0
ファイル: lwSprite.cpp プロジェクト: henyouqian/arrow
	void Sprite::draw(){
		ImageStaticData& d = g_imageStaticData;
		if ( d.vertexVec.empty() && d.batchInfoVec.empty() ){
			return;
		}
#ifdef USEVBO		
		if ( d.vbo == -1 ){
			glGenBuffers(1, &d.vbo);
		}
#endif

		glDisable(GL_LIGHTING);
		glDepthMask(GL_FALSE);

		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		const App::Config conf = App::getConfig();
		float w = (float)conf.width;
		float h = (float)conf.height;
#ifdef __APPLE__
		float rotDegree = 0;
		const App::Orientation orient = App::getConfig().orientation;
		switch (orient) {
			case App::ORIENTATION_LEFT:
				rotDegree = 90;
				break;
			case App::ORIENTATION_RIGHT:
				rotDegree = -90;
				break;
			default:
				break;
		}
		glRotatef(rotDegree, 0, 0, 1);
#endif
#ifdef WIN32
		int dOrient = (App::getConfig().orientation-App::getConfig().orientation0);
		float rotDegree = -dOrient * 90.f;
		glRotatef(rotDegree, 0, 0, 1);
		//if ( abs(dOrient) == 1 ){
		//	float temp = h;
		//	h = w;
		//	w = temp;
		//}
#endif
		cml::Matrix44 m;
		cml::matrix_orthographic_RH(m, 0.f, w, -h, 0.f, Z_BEGIN, Z_END, cml::z_clip_neg_one);
		glMultMatrixf(m.data());

		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();

		glEnable(GL_TEXTURE_2D);

		glEnableClientState(GL_VERTEX_ARRAY);
		glEnableClientState(GL_TEXTURE_COORD_ARRAY);

		glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

#ifdef USEVBO
		glBindBuffer(GL_ARRAY_BUFFER, d.vbo);
		glBufferData(GL_ARRAY_BUFFER, (int)d.vertexVec.size()*sizeof(Vertex), &(d.vertexVec[0]), GL_DYNAMIC_DRAW);
		glVertexPointer(3, GL_FLOAT, sizeof(Vertex), (GLvoid*)0);
		glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), (GLvoid*)(sizeof(float)*3));
#else
		if ( !d.vertexVec.empty() ){
			glVertexPointer(3, GL_FLOAT, sizeof(Vertex), &(d.vertexVec[0]));
			char* p = (char*)&(d.vertexVec[0]);
			glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), p+(sizeof(float)*3));
		}
#endif
		
		bool blendEnabled = false;
		for ( size_t i = 0; i < d.batchInfoVec.size(); ++i ){
			BatchInfo& batchInfo = d.batchInfoVec[i];
			glColor4f(batchInfo.color.r/255.f, batchInfo.color.g/255.f, batchInfo.color.b/255.f, batchInfo.color.a/255.f);
			if ( !batchInfo.rsObjs.empty() ){
				std::vector<RanderStateObj*>::iterator it = batchInfo.rsObjs.begin();
				std::vector<RanderStateObj*>::iterator itEnd = batchInfo.rsObjs.end();
				for ( ; it != itEnd; ++it ){
					(*it)->set();
				}
			}
			if ( batchInfo.vertexOffset == -2 ){
				if ( !batchInfo.rsObjs.empty() ){
					std::vector<RanderStateObj*>::iterator it = batchInfo.rsObjs.begin();
					std::vector<RanderStateObj*>::iterator itEnd = batchInfo.rsObjs.end();
					for ( ; it != itEnd; ++it ){
						delete (*it);
					}
				}
				batchInfo.rsObjs.clear();
				continue;
			}
			//model
			if ( batchInfo.vertexOffset == -1 ){
				batchInfo.pModle->drawAsSprite(batchInfo.nodeIndex);
				if ( blendEnabled ){
					glEnable(GL_BLEND);
					//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
				}else{
					glDisable(GL_BLEND);
				}
				if ( !d.vertexVec.empty() && i < d.batchInfoVec.size()-1 ){
					glEnable(GL_TEXTURE_2D);
					glEnableClientState(GL_VERTEX_ARRAY);
					glEnableClientState(GL_TEXTURE_COORD_ARRAY);
					glVertexPointer(3, GL_FLOAT, sizeof(Vertex), &(d.vertexVec[0]));
					char* p = (char*)&(d.vertexVec[0]);
					glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), p+(sizeof(float)*3));
				}

				if ( !batchInfo.rsObjs.empty() ){
					std::vector<RanderStateObj*>::iterator it = batchInfo.rsObjs.begin();
					std::vector<RanderStateObj*>::iterator itEnd = batchInfo.rsObjs.end();
					for ( ; it != itEnd; ++it ){
						delete (*it);
					}
				}
				batchInfo.rsObjs.clear();
				continue;
			}

			bool shouldBlend = batchInfo.hasAlpha || batchInfo.color.a != 255;
			if ( shouldBlend != blendEnabled ){
				blendEnabled = shouldBlend;
				if ( blendEnabled ){
					glEnable(GL_BLEND);
					//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
				}else{
					glDisable(GL_BLEND);
				}
			}
			
			glBindTexture(GL_TEXTURE_2D, batchInfo.textureId);
			lwassert(glGetError()==GL_NO_ERROR);
			//find next sprite batch
			int sz = 0;
			bool find = false;
			for ( size_t idx = i+1; idx < d.batchInfoVec.size(); ++idx ){
				if ( d.batchInfoVec[idx].vertexOffset != -1 ){
					sz = d.batchInfoVec[idx].vertexOffset - batchInfo.vertexOffset;
					find = true;
					break;
				}
			}
			if ( !find ){
				sz = (int)d.vertexVec.size()-batchInfo.vertexOffset;
			}
			//if ( i == d.batchInfoVec.size() - 1 ){
			//	sz = (int)d.vertexVec.size()-batchInfo.vertexOffset;
			//}else{
			//	sz = d.batchInfoVec[i+1].vertexOffset - batchInfo.vertexOffset;
			//}
			
			glDrawArrays(GL_TRIANGLES, batchInfo.vertexOffset, sz);

			if ( !batchInfo.rsObjs.empty() ){
				std::vector<RanderStateObj*>::iterator it = batchInfo.rsObjs.begin();
				std::vector<RanderStateObj*>::iterator itEnd = batchInfo.rsObjs.end();
				for ( ; it != itEnd; ++it ){
					delete (*it);
				}
				batchInfo.rsObjs.clear();
			}
		}

		glDepthMask(GL_TRUE);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		glDisable(GL_TEXTURE_2D);
		glBindTexture(GL_TEXTURE_2D, 0);
		glDisableClientState(GL_VERTEX_ARRAY);
		glDisableClientState(GL_TEXTURE_COORD_ARRAY);
		if ( blendEnabled ){
			glDisable(GL_BLEND);
		}
		d.vertexVec.clear();
		d.batchInfoVec.clear();
		d.currTextureId = -1;
		//float z = g_currZ;
		g_currZ = Z_BEGIN+1.f;
	}
コード例 #21
0
ファイル: halomagic.c プロジェクト: BioTesseract/Desktop
static void
redraw(void)
{
  int start, end;

  if (reportSpeed) {
    start = glutGet(GLUT_ELAPSED_TIME);
  }

  /* Clear; default stencil clears to zero. */
  if ((stencilReflection && renderReflection) || (stencilShadow && renderShadow) || (haloScale > 1.0)) {
    glStencilMask(0xffffffff);
    glClearStencil(0x4);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  } else {
    /* Avoid clearing stencil when not using it. */
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  }

  /* Reposition the light source. */
  lightPosition[0] = 15*cos(lightAngle);
  lightPosition[1] = lightHeight;
  lightPosition[2] = 15*sin(lightAngle);
  if (directionalLight) {
    lightPosition[3] = 0.0;
  } else {
    lightPosition[3] = 1.0;
  }

  shadowMatrix(floorShadow, floorPlane, lightPosition);

  glPushMatrix();
    /* Perform scene rotations based on user mouse input. */
    glRotatef(angle2, 1.0, 0.0, 0.0);
    glRotatef(angle, 0.0, 1.0, 0.0);
     
    /* Tell GL new light source position. */
    glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);

    if (renderReflection) {
      if (stencilReflection) {
        /* We can eliminate the visual "artifact" of seeing the "flipped"
  	   model underneath the floor by using stencil.  The idea is
	   draw the floor without color or depth update but so that 
	   a stencil value of one is where the floor will be.  Later when
	   rendering the model reflection, we will only update pixels
	   with a stencil value of 1 to make sure the reflection only
	   lives on the floor, not below the floor. */

        /* Don't update color or depth. */
        glDisable(GL_DEPTH_TEST);
        glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);

        /* Draw 1 into the stencil buffer. */
        glEnable(GL_STENCIL_TEST);
        glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
        glStencilFunc(GL_ALWAYS, 1, 0x1);
	glStencilMask(0x1);

        /* Now render floor; floor pixels just get their stencil set to 1. */
        drawFloor();

        /* Re-enable update of color and depth. */ 
        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
        glEnable(GL_DEPTH_TEST);

        /* Now, only render where stencil is set to 1. */
        glStencilFunc(GL_EQUAL, 1, 0x1);  /* draw if ==1 */
        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
      }

      glPushMatrix();

        /* The critical reflection step: Reflect 3D model through the floor
           (the Y=0 plane) to make a relection. */
        glScalef(1.0, -1.0, 1.0);

	/* Reflect the light position. */
        glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);

        /* To avoid our normals getting reversed and hence botched lighting
	   on the reflection, turn on normalize.  */
        glEnable(GL_NORMALIZE);
        glCullFace(GL_FRONT);

        /* Draw the reflected model. */
	glPushMatrix();
	  glTranslatef(0, 8.01, 0);
          drawModel();
	glPopMatrix();
	drawPillar();

        /* Disable noramlize again and re-enable back face culling. */
        glDisable(GL_NORMALIZE);
        glCullFace(GL_BACK);

      glPopMatrix();

      /* Switch back to the unreflected light position. */
      glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);

      if (stencilReflection) {
        glDisable(GL_STENCIL_TEST);
      }
    }

    /* Back face culling will get used to only draw either the top or the
       bottom floor.  This let's us get a floor with two distinct
       appearances.  The top floor surface is reflective and kind of red.
       The bottom floor surface is not reflective and blue. */

    /* Draw "bottom" of floor in blue. */
    glFrontFace(GL_CW);  /* Switch face orientation. */
    glColor4f(0.1, 0.1, 0.7, 1.0);
    drawFloor();
    glFrontFace(GL_CCW);

    if (renderShadow && stencilShadow) {
     /* Draw the floor with stencil value 2.  This helps us only 
	draw the shadow once per floor pixel (and only on the
        floor pixels). */
      glEnable(GL_STENCIL_TEST);
      glStencilFunc(GL_ALWAYS, 0x2, 0x2);
      glStencilMask(0x2);
      glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
    }

    /* Draw "top" of floor.  Use blending to blend in reflection. */
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glColor4f(1.0, 1.0, 1.0, 0.3);
    drawFloor();
    glDisable(GL_BLEND);

    if (renderShadow && stencilShadow) {
      glDisable(GL_STENCIL_TEST);
    }

    if (renderDinosaur) {
      drawPillar();

      if (haloScale > 1.0) {
	/* If halo effect is enabled, draw the model with its stencil set to 6
	   (arbitary value); later, we'll make sure not to update pixels tagged
	   as 6. */
        glEnable(GL_STENCIL_TEST);
        glStencilFunc(GL_ALWAYS, 0x0, 0x4);
        glStencilMask(0x4);
        glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
      } 

      /* Draw "actual" dinosaur (or other model), not its reflection. */
      glPushMatrix();
        glTranslatef(0, 8.01, 0);
        drawModel();
      glPopMatrix();
    }

    /* Begin shadow render. */
    if (renderShadow) {

      /* Render the projected shadow. */

      if (stencilShadow) {

        /* Now, only render where stencil is set above 5 (ie, 6 where
	   the top floor is).  Update stencil with 2 where the shadow
	   gets drawn so we don't redraw (and accidently reblend) the
	   shadow). */
	glEnable(GL_STENCIL_TEST);
        glStencilFunc(GL_NOTEQUAL, 0x0, 0x2);
        glStencilMask(0x2);
        glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
      }

      /* To eliminate depth buffer artifacts, we use polygon offset
	 to raise the depth of the projected shadow slightly so
	 that it does not depth buffer alias with the floor. */
      if (offsetShadow) {
	switch (polygonOffsetVersion) {
	case EXTENSION:
#ifdef GL_EXT_polygon_offset
	  glEnable(GL_POLYGON_OFFSET_EXT);
	  break;
#endif
#ifdef GL_VERSION_1_1
	case ONE_DOT_ONE:
          glEnable(GL_POLYGON_OFFSET_FILL);
	  break;
#endif
	case MISSING:
	  /* Oh well. */
	  break;
	}
      }

      /* Render 50% black shadow color on top of whatever the
         floor appareance is. */
      glEnable(GL_BLEND);
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
      glDisable(GL_LIGHTING);  /* Force the 50% black. */
      glColor4f(0.0, 0.0, 0.0, 0.5);

      glPushMatrix();
	/* Project the shadow. */
        glMultMatrixf((GLfloat *) floorShadow);
	glPushMatrix();
          glTranslatef(0, 8.01, 0);
          drawModel();
	glPopMatrix();
	drawPillar();
      glPopMatrix();

      glDisable(GL_BLEND);
      glEnable(GL_LIGHTING);

      if (offsetShadow) {
	switch (polygonOffsetVersion) {
#ifdef GL_EXT_polygon_offset
	case EXTENSION:
	  glDisable(GL_POLYGON_OFFSET_EXT);
	  break;
#endif
#ifdef GL_VERSION_1_1
	case ONE_DOT_ONE:
          glDisable(GL_POLYGON_OFFSET_FILL);
	  break;
#endif
	case MISSING:
	  /* Oh well. */
	  break;
	}
      }
      if (stencilShadow) {
        glDisable(GL_STENCIL_TEST);
      }
    } /* End shadow render. */

    /* Begin light source location render. */
    glPushMatrix();
      glDisable(GL_LIGHTING);
      glColor3f(1.0, 1.0, 0.0);
      if (directionalLight) {
        /* Draw an arrowhead. */
        glDisable(GL_CULL_FACE);
        glTranslatef(lightPosition[0], lightPosition[1], lightPosition[2]);
        glRotatef(lightAngle * -180.0 / M_PI, 0, 1, 0);
        glRotatef(atan(lightHeight/12) * 180.0 / M_PI, 0, 0, 1);
        glBegin(GL_TRIANGLE_FAN);
  	  glVertex3f(0, 0, 0);
	  glVertex3f(2, 1, 1);
	  glVertex3f(2, -1, 1);
	  glVertex3f(2, -1, -1);
	  glVertex3f(2, 1, -1);
	  glVertex3f(2, 1, 1);
        glEnd();
        /* Draw a white line from light direction. */
        glColor3f(1.0, 1.0, 1.0);
        glBegin(GL_LINES);
	  glVertex3f(0.1, 0, 0);
	  glVertex3f(5, 0, 0);
        glEnd();
        glEnable(GL_CULL_FACE);
      } else {
        /* Draw a yellow ball at the light source. */
        glTranslatef(lightPosition[0], lightPosition[1], lightPosition[2]);
        glutSolidSphere(1.0, 5, 5);
      }
      glEnable(GL_LIGHTING);
    glPopMatrix();
    /* End light source location render. */

    /* Add a halo effect around the 3D model. */
    if (haloScale > 1.0) {

      glDisable(GL_LIGHTING);

      if (blendedHalo) {
	/* If we are doing a nice blended halo, enable blending and
	   make sure we only blend a halo pixel once and that we do
	   not draw to pixels tagged as 6 (where the model is). */
	glEnable(GL_BLEND);
	glEnable(GL_STENCIL_TEST);
	glColor4f(0.8, 0.8, 0.0, 0.3);  /* 30% sorta yellow. */
        glStencilFunc(GL_EQUAL, 0x4, 0x4);
        glStencilMask(0x4);
        glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT);
      } else {
	/* Be cheap; no blending.  Just draw yellow halo but not updating
	   pixels where the model is.  We don't update stencil at all. */
        glDisable(GL_BLEND);
	glEnable(GL_STENCIL_TEST);
	glColor3f(0.5, 0.5, 0.0);  /* Half yellow. */
        glStencilFunc(GL_EQUAL, 0x4, 0x4);
        glStencilMask(0x4);
        glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT);
      }

      glPushMatrix();
        glTranslatef(0, 8.01, 0);
        glScalef(haloScale, haloScale, haloScale);
        drawModel();
      glPopMatrix();

      if (blendedHalo) {
        glDisable(GL_BLEND);
      }
      glDisable(GL_STENCIL_TEST);
      glEnable(GL_LIGHTING);
    }
    /* End halo effect render. */

  glPopMatrix();

  if (reportSpeed) {
    glFinish();
    end = glutGet(GLUT_ELAPSED_TIME);
    printf("Speed %.3g frames/sec (%d ms)\n", 1000.0/(end-start), end-start);
  }

  glutSwapBuffers();
}
コード例 #22
0
ファイル: g_render.c プロジェクト: aosm/X11
void __glXDisp_MultMatrixf(GLbyte *pc)
{
	glMultMatrixf( 
		(GLfloat  *)(pc + 0)
	);
}
コード例 #23
0
ファイル: ModelManager.c プロジェクト: devmario/IbizaEngine
bool ModelManagerDisplay(ModelManager* manager, Model* model, bool line) {
#else
bool ModelManagerDisplay(ModelManager* manager, Model* model) {
#endif
    if(model->isVisible)
	{
        
	if(model->ani) {
		if(model->ani->aniIsPlay) {
			if(model->ani->aniCurFrame < model->ani->aniTotalFrame - 1) {
				model->ani->aniCurFrame++;
				model->ani->aniIsUpdateFrame = true;
			} else {
				if(model->ani->aniIsLoop) {
					model->ani->aniCurFrame = 0;
					model->ani->aniIsUpdateFrame = true;
				}
			}
		}
		
		if(model->ani->aniIsUpdateFrame) {
			//모든 에니메이션 모델 삭제
			int i;
			for(i = 0; i < model->child->length; i++) {
				Model* child = ArrayObjectAtIndex(model->child, i);
				if(child->ani) {
					if(child->ani->instanceID) {
						ModelRemoveAt(model, i);
						i--;
					}
				}
			}
			
			//현제 프레임의 하위모델 셋팅후 매트릭스,칼라 셋팅
			if(model->ani->aniChildLength) {
				for(i = 0; i < model->ani->aniChildLength[model->ani->aniCurFrame]; i++) {
					ModelAddAt(model, model->ani->aniChild[model->ani->aniCurFrame][i], 0);
					ModelSetMatrix(model->ani->aniChild[model->ani->aniCurFrame][i], model->ani->aniMat[model->ani->aniCurFrame][i]);
					ModelSetColor(model->ani->aniChild[model->ani->aniCurFrame][i], model->ani->aniColor[model->ani->aniCurFrame][i]);
				}
			}
			
			model->ani->aniIsUpdateFrame = false;
		}
	}
	
	glPushMatrix();
	
	ModelUpdateMatrix(model);
	
	
	glMultMatrixf((float*)model->matrix);
	

	

	

		//glGetFloatv(GL_MODELVIEW_MATRIX, (float*)model->matrixGlobal);
		
		//model->globalPosition = Matrix3DMultiplyVector3D(*model->matrixGlobal, Vector3DInit(0.0, 0.0, 0.0));
		
		model->isRender = true;
		/*
		if(model->vertex) {
			Vector3D scale = Matrix3DGetScale(*model->matrixGlobal);
			Vector3D vec = Vector3DInit(model->maxLengthVertex.x * scale.x,
										model->maxLengthVertex.y * scale.y,
										model->maxLengthVertex.z * scale.z);
			model->globalRadius = Vector3DLength(vec);
			for(int i = 0; i < 6; i++ ) {
				if( manager->g_frustumPlanes[i][0] * model->globalPosition.x +
				   manager->g_frustumPlanes[i][1] * model->globalPosition.y +
				   manager->g_frustumPlanes[i][2] * model->globalPosition.z +
				   manager->g_frustumPlanes[i][3] <= -model->globalRadius ) {
					model->isRender = false;
				}
			}
		}
		*/
		//if(model->isRender) {
			
#ifdef ___MACSIMULATOR___
			if(model->mask) {
				ModelManagerDisplay(manager, model->mask, line);
			}
#else
			if(model->mask) {
				ModelManagerDisplay(manager, model->mask);
			}
#endif
			
			//if(model->renderEvent.event) {
			//	model->renderEvent.event(model->renderEvent.userReference, model->renderEvent.argument);
			//}
			/*
			if(model->touchEvent.event) {
				tt++;
				for(int i = 0; i < manager->touchArguments->length; i++) {
					ModelEventTouchArgument* touchArgumentCurrent = manager->touchArguments->data[i];
					bool hit = ModelGetIsVertexHitLineDirection(model, 
																touchArgumentCurrent->origin, touchArgumentCurrent->direction, 
																model->touchVector, model->touchVectorGlobal);
					
					model->touchEvent.argument.hitVector = model->touchVector;
					model->touchEvent.argument.hitVectorGlobal = model->touchVectorGlobal;
					model->touchEvent.argument.isHit = hit;
					model->touchEvent.argument.model = model;
					model->touchEvent.argument.touchID = touchArgumentCurrent->touchID;
					model->touchEvent.argument.touchTabCount = touchArgumentCurrent->touchTabCount;
					model->touchEvent.argument.touchType = touchArgumentCurrent->touchType;
					model->touchEvent.event(model->touchEvent.userReference, model->touchEvent.argument);
					touchArgumentCurrent->isChecked = true;
				}
			}
             */
			
			Model* _parent = ModelGetParent(model);
			for(int i = 0; i < model->mixColorLength; i++) {
				if(_parent) {
					model->mixColor[i].r = (unsigned char)(((float)_parent->mixColor[0].r / (float)0xFF) * (float)model->color[i].r);
					model->mixColor[i].g = (unsigned char)(((float)_parent->mixColor[0].g / (float)0xFF) * (float)model->color[i].g);
					model->mixColor[i].b = (unsigned char)(((float)_parent->mixColor[0].b / (float)0xFF) * (float)model->color[i].b);
					model->mixColor[i].a = (unsigned char)(((float)_parent->mixColor[0].a / (float)0xFF) * (float)model->color[i].a);
				} else {
					model->mixColor[i] = model->color[0];
				}
			}
			
			if(model->vertex)
			{

				
				//if(manager->lastBindVertex != model->vertex) {
				glVertexPointer(3, GL_FLOAT, 0, model->vertex);
				//	manager->lastBindVertex = model->vertex;
				//}
				
				if(model->texcoord) {
					glEnable(GL_TEXTURE_2D);
					glEnableClientState(GL_TEXTURE_COORD_ARRAY);
					if(manager->lastBindTexcoord != model->texcoord) {
					glTexCoordPointer(2, GL_FLOAT, 0, model->texcoord);
					manager->lastBindTexcoord = model->texcoord;
					}
					if(manager->lastBindTexture != model->textureID) {
						glBindTexture(GL_TEXTURE_2D, model->textureID);
						manager->lastBindTexture = model->textureID;
					}
					if(model->blendMode == ModelBlendModeNormal) {
						//	glDepthFunc(GL_LESS);
						glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
						
						
					} else if(model->blendMode == ModelBlendModeAdd) {
						//	glDepthFunc(GL_LESS);
						glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
						//	glBlendFunc(GL_SRC_ALPHA, GL_ONE);
					} else if(model->blendMode == ModelBlendModeNoAlpha) {
						//	glDepthFunc(GL_LESS);
						glBlendFunc(GL_ONE, GL_ZERO);
					} else if(model->blendMode == ModelBlendModeSubatract) {
						glBlendFunc(GL_SRC_ALPHA, GL_ONE);
					} else if(model->blendMode == ModelBlendModeDot) {
						glBlendFunc(GL_ZERO, GL_SRC_COLOR);
					} else if(model->blendMode == ModelBlendModePower) {
						glBlendFunc(GL_ZERO, GL_DST_COLOR);
					} else if(model->blendMode == ModelBlendModeInverse) {
						glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO);
					}
				} else {
					glDisable(GL_TEXTURE_2D);
					glDisableClientState(GL_TEXTURE_COORD_ARRAY);
				}
                
				/*
				if(model->isMask) {
					glColorMask(0, 0, 0, 0);
					//if(model->maskDepth == 0) {
					//glDisable(GL_DEPTH_TEST);
					glEnable(GL_STENCIL_TEST);
					glClear(GL_STENCIL_BUFFER_BIT);
					//}
					glStencilFunc(GL_ALWAYS, model->maskDepth, model->maskDepth);
					glStencilOp(GL_INCR, GL_INCR, GL_INCR);
				} else if(model->hasMask) {
					glColorMask(1, 1, 1, 1);
					glStencilFunc(GL_LEQUAL, model->maskDepth, model->maskDepth);
					glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);
				} else {
					glColorMask(1, 1, 1, 1);
					glDisable(GL_STENCIL_TEST);
					//if(model->isDepthTest) {
					//glEnable(GL_DEPTH_TEST);
					//} else {
					//	glDisable(GL_DEPTH_TEST);
					//}
				}
				*/
                
				/*
				 if(model->isLighting) {
				 glEnable(GL_LIGHTING);
				 } else {
				 glDisable(GL_LIGHTING);
				 }
				 */
				
				//if(model->colorMode == ModelColorModeNone) {
				//	glDisable(GL_COLOR_MATERIAL);
				//	glDisableClientState(GL_COLOR_ARRAY);
				//} else if(model->colorMode == ModelColorModeOneColor) {
				//glEnable(GL_COLOR_MATERIAL);
				//glDisableClientState(GL_COLOR_ARRAY);
				glColor4ub(model->mixColor->r, model->mixColor->g, model->mixColor->b, model->mixColor->a);
				//} else if(model->colorMode == ModelColorModeVertexColor) {
				//	glEnable(GL_COLOR_MATERIAL);
				//	glEnableClientState(GL_COLOR_ARRAY);
				//	glColorPointer(4, GL_UNSIGNED_BYTE, 0, model->mixColor);
				//}
				
				
				manager->drawModelCount++;
				//if(model->polygon) {
				//	glDrawElements(GL_TRIANGLES, model->polygonLength, GL_UNSIGNED_SHORT, model->polygon);
				//} else {
				if(model->isTriangleFanMode) {
#ifdef ___MACSIMULATOR___
					if(line){
						glDisable(GL_TEXTURE_2D);
						glLineWidth(1.0f);
						glColor4ub(lineR, lineG, lineB, 0xFF);
						glDrawArrays(GL_LINE_STRIP, 1, model->vertexLength - 2);
					}else
#endif
						glDrawArrays(GL_TRIANGLE_FAN, 0, model->vertexLength);
				}else{
#ifdef ___MACSIMULATOR___
					if(line)
					{
						glDisable(GL_TEXTURE_2D);
						glLineWidth(1.0);
						glColor4ub(lineR, lineG, lineB, 0xFF);
						glDrawArrays(GL_LINE_STRIP, 0, model->vertexLength);
						Vector3D vec[4];
						vec[0] = model->vertex[1];
						vec[1] = model->vertex[3];
						vec[2] = model->vertex[0];
						vec[3] = model->vertex[2];
						glVertexPointer(3, GL_FLOAT, 0, vec);
						glDrawArrays(GL_LINES, 0, 4);
					}
					else
#endif

						glDrawArrays(GL_TRIANGLE_STRIP, 0, model->vertexLength);
				}
				//}
				

				
				
			}
		//}
#ifdef ___MACSIMULATOR___
		for(int i = 0; i < model->child->length; i++)
			ModelManagerDisplay(manager, model->child->data[i], line);
#else

		for(int i = 0; i < model->child->length; i++)
			ModelManagerDisplay(manager, model->child->data[i]);
#endif
	
	
	glPopMatrix();
	}
	return true;
}

bool ModelManagerDisplayEnd(ModelManager* manager) {
	//printf("a %i\n", manager->touchArguments->length);
	while(manager->touchArguments->length) {
		ModelEventTouchArgument* touchArgument = ArrayObjectAtIndex(manager->touchArguments, 0);
		ArrayPopObjectAtIndex(manager->touchArguments, 0);
		free(touchArgument);
	}
	return true;
}

#pragma mark -
#pragma mark ModelManager 관리자 드바이스 이벤트 받는 함수

bool ModelManagerTouch(ModelManager* manager,
					   Vector2D touch, 
					   void* touchID, 
					   TouchType touchType, 
					   unsigned char tabCount) {
	ModelEventTouchArgument* touchArgument = (ModelEventTouchArgument*)calloc(1, sizeof(ModelEventTouchArgument));
	touchArgument->touchVector = touch;
	touchArgument->touchID = touchID;
	touchArgument->touchType = touchType;
	touchArgument->touchTabCount = tabCount;
	ArrayPushObject(manager->touchArguments, touchArgument);
	return true;
}
コード例 #24
0
ファイル: shPipeline.c プロジェクト: Chazzz/pyShiva
VG_API_CALL void vgDrawPath(VGPath path, VGbitfield paintModes)
{
  SHPath *p;
  SHMatrix3x3 mi;
  SHfloat mgl[16];
  SHPaint *fill, *stroke;
  SHRectangle *rect;
  
  VG_GETCONTEXT(VG_NO_RETVAL);
  
  VG_RETURN_ERR_IF(!shIsValidPath(context, path),
                   VG_BAD_HANDLE_ERROR, VG_NO_RETVAL);
  
  VG_RETURN_ERR_IF(paintModes & (~(VG_STROKE_PATH | VG_FILL_PATH)),
                   VG_ILLEGAL_ARGUMENT_ERROR, VG_NO_RETVAL);

  /* Check whether scissoring is enabled and scissor
     rectangle is valid */
  if (context->scissoring == VG_TRUE) {
    rect = &context->scissor.items[0];
    if (context->scissor.size == 0) VG_RETURN( VG_NO_RETVAL );
    if (rect->w <= 0.0f || rect->h <= 0.0f) VG_RETURN( VG_NO_RETVAL );
    glScissor( (GLint)rect->x, (GLint)rect->y, (GLint)rect->w, (GLint)rect->h );
    glEnable( GL_SCISSOR_TEST );
  }
  
  p = (SHPath*)path;
  
  /* If user-to-surface matrix invertible tessellate in
     surface space for better path resolution */
  if (shIsTessCacheValid( context, p ) == VG_FALSE)
  {
    if (shInvertMatrix(&context->pathTransform, &mi)) {
      shFlattenPath(p, 1);
      shTransformVertices(&mi, p);
    }else shFlattenPath(p, 0);
    shFindBoundbox(p);
  }
  
  /* TODO: Turn antialiasing on/off */
  glDisable(GL_LINE_SMOOTH);
  glDisable(GL_POLYGON_SMOOTH);
  glEnable(GL_MULTISAMPLE);
  
  /* Pick paint if available or default*/
  fill = (context->fillPaint ? context->fillPaint : &context->defaultPaint);
  stroke = (context->strokePaint ? context->strokePaint : &context->defaultPaint);
  
  /* Apply transformation */
  shMatrixToGL(&context->pathTransform, mgl);
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glMultMatrixf(mgl);
  
  if (paintModes & VG_FILL_PATH) {
    
    /* Tesselate into stencil */
    glEnable(GL_STENCIL_TEST);
    glStencilFunc(GL_ALWAYS, 0, 0);
    glStencilOp(GL_INVERT, GL_INVERT, GL_INVERT);
    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
    shDrawVertices(p, GL_TRIANGLE_FAN);
    
    /* Setup blending */
    updateBlendingStateGL(context,
                          fill->type == VG_PAINT_TYPE_COLOR &&
                          fill->color.a == 1.0f);
    
    /* Draw paint where stencil odd */
    glStencilFunc(GL_EQUAL, 1, 1);
    glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    shDrawPaintMesh(context, &p->min, &p->max, VG_FILL_PATH, GL_TEXTURE0);

    /* Clear stencil for sure */
    /* TODO: Is there any way to do this safely along
       with the paint generation pass?? */
    glDisable(GL_BLEND);
    glDisable(GL_MULTISAMPLE);
    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
    shDrawBoundBox(context, p, VG_FILL_PATH);
    
    /* Reset state */
    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    glDisable(GL_STENCIL_TEST);
    glDisable(GL_BLEND);
  }
  
  /* TODO: Turn antialiasing on/off */
  glDisable(GL_LINE_SMOOTH);
  glDisable(GL_POLYGON_SMOOTH);
  glEnable(GL_MULTISAMPLE);
  
  if ((paintModes & VG_STROKE_PATH) &&
      context->strokeLineWidth > 0.0f) {
    
    if (1) {/*context->strokeLineWidth > 1.0f) {*/

      if (shIsStrokeCacheValid( context, p ) == VG_FALSE)
      {
        /* Generate stroke triangles in user space */
        shVector2ArrayClear(&p->stroke);
        shStrokePath(context, p);
      }

      /* Stroke into stencil */
      glEnable(GL_STENCIL_TEST);
      glStencilFunc(GL_NOTEQUAL, 1, 1);
      glStencilOp(GL_KEEP, GL_INCR, GL_INCR);
      glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
      shDrawStroke(p);

      /* Setup blending */
      updateBlendingStateGL(context,
                            stroke->type == VG_PAINT_TYPE_COLOR &&
                            stroke->color.a == 1.0f);

      /* Draw paint where stencil odd */
      glStencilFunc(GL_EQUAL, 1, 1);
      glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO);
      glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
      shDrawPaintMesh(context, &p->min, &p->max, VG_STROKE_PATH, GL_TEXTURE0);
      
      /* Clear stencil for sure */
      glDisable(GL_BLEND);
      glDisable(GL_MULTISAMPLE);
      glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
      shDrawBoundBox(context, p, VG_STROKE_PATH);
      
      /* Reset state */
      glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
      glDisable(GL_STENCIL_TEST);
      glDisable(GL_BLEND);
      
    }else{
      
      /* Simulate thin stroke by alpha */
      SHColor c = stroke->color;
      if (context->strokeLineWidth < 1.0f)
        c.a *= context->strokeLineWidth;
      
      /* Draw contour as a line */
      glDisable(GL_MULTISAMPLE);
      glEnable(GL_BLEND);
      glEnable(GL_LINE_SMOOTH);
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
      glColor4fv((GLfloat*)&c);
      shDrawVertices(p, GL_LINE_STRIP);
      
      glDisable(GL_BLEND);
      glDisable(GL_LINE_SMOOTH);
    }
  }
  
  
  glPopMatrix();
  
  if (context->scissoring == VG_TRUE)
    glDisable( GL_SCISSOR_TEST );

  VG_RETURN(VG_NO_RETVAL);
}
コード例 #25
0
ファイル: Graph.cpp プロジェクト: CowTard/16Factorial-OPENGL
void Node::draw(map<string, Node*>& grafo, map<string, Aparencia*>& aparencias, string referenciaApp, map<string, Textura*>& texturas, map<string, Animation*> anime){

	if (this->firstTime){
		createDisplayList(grafo, aparencias, referenciaApp, texturas,anime);
		this->firstTime = false;
	}
	else if (this->displayList){
		glPushMatrix();
		glCallList(this->index);
		typedef vector<string>::iterator iter;
		for (iter it = this->getDescendencia().begin(); it != this->getDescendencia().end(); it++){
			glPushMatrix();
			grafo[*it]->draw(grafo, aparencias, this->appRef, texturas,anime);
			glPopMatrix();
		}
		glPopMatrix();
	}
	else if (!this->displayList && this->insideList && this->controlList){
		glPushMatrix();
		
		unsigned int size = this->primitivas.size();
		typedef vector<string>::iterator iter;
		for (iter it = this->getDescendencia().begin(); it != this->getDescendencia().end(); it++){
			glPushMatrix();
			grafo[*it]->draw(grafo, aparencias, this->appRef, texturas,anime);
			glPopMatrix();
		}
		glPopMatrix();
	}
	else {
		glPushMatrix();
		glMultMatrixf(&this->matrix[0]);
		if (this->appRef != "inherit"){
			aparencias[this->appRef]->apply();
		}
		else {
			aparencias[referenciaApp]->apply();
			this->appRef = referenciaApp;
		}

		if (this->animacoes.size() != 0){
			for (int i = 0; i < this->animacoes.size(); i++){ // alterar
				anime[animacoes[i]]->draw();
			}
		}

		unsigned int size = this->primitivas.size();
		for (unsigned int i = 0; i < size; i++){
			if (aparencias[appRef]->getTextRef() != "null"){
				float texS = texturas[aparencias[appRef]->getTextRef()]->getTexLenS();
				float texT = texturas[aparencias[appRef]->getTextRef()]->getTexLenT();
				primitivas[i]->draw(texS, texT);
			}
			else primitivas[i]->draw();
		}
		typedef std::vector<std::string>::iterator iter;
		for (iter it = this->getDescendencia().begin(); it != this->getDescendencia().end(); it++){
			glPushMatrix();
			grafo[*it]->draw(grafo, aparencias, this->appRef, texturas,anime);
			glPopMatrix();
		}
		glPopMatrix();
	}
}
コード例 #26
0
ファイル: shPipeline.c プロジェクト: Chazzz/pyShiva
VG_API_CALL void vgDrawImage(VGImage image)
{
  SHImage *i;
  SHfloat mgl[16];
  SHfloat texGenS[4] = {0,0,0,0};
  SHfloat texGenT[4] = {0,0,0,0};
  SHPaint *fill;
  SHVector2 min, max;
  SHRectangle *rect;
  
  VG_GETCONTEXT(VG_NO_RETVAL);
  
  VG_RETURN_ERR_IF(!shIsValidImage(context, image),
                   VG_BAD_HANDLE_ERROR, VG_NO_RETVAL);

  /* TODO: check if image is current render target */
  
  /* Check whether scissoring is enabled and scissor
     rectangle is valid */
  if (context->scissoring == VG_TRUE) {
    rect = &context->scissor.items[0];
    if (context->scissor.size == 0) VG_RETURN( VG_NO_RETVAL );
    if (rect->w <= 0.0f || rect->h <= 0.0f) VG_RETURN( VG_NO_RETVAL );
    glScissor( (GLint)rect->x, (GLint)rect->y, (GLint)rect->w, (GLint)rect->h );
    glEnable( GL_SCISSOR_TEST );
  }
  
  /* Apply image-user-to-surface transformation */
  i = (SHImage*)image;
  shMatrixToGL(&context->imageTransform, mgl);
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glMultMatrixf(mgl);
  
  /* Clamp to edge for proper filtering, modulate for multiply mode */
  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, i->texture);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  
  /* Adjust antialiasing to settings */
  if (context->imageQuality == VG_IMAGE_QUALITY_NONANTIALIASED) {
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glDisable(GL_MULTISAMPLE);
  }else{
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glEnable(GL_MULTISAMPLE);
  }
  
  /* Generate image texture coords automatically */
  texGenS[0] = 1.0f / i->texwidth;
  texGenT[1] = 1.0f / i->texheight;
  glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
  glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
  glTexGenfv(GL_S, GL_OBJECT_PLANE, texGenS);
  glTexGenfv(GL_T, GL_OBJECT_PLANE, texGenT);
  glEnable(GL_TEXTURE_GEN_S);
  glEnable(GL_TEXTURE_GEN_T);
  
  /* Pick fill paint */
  fill = (context->fillPaint ? context->fillPaint : &context->defaultPaint);
  
  /* Use paint color when multiplying with a color-paint */
  if (context->imageMode == VG_DRAW_IMAGE_MULTIPLY &&
      fill->type == VG_PAINT_TYPE_COLOR)
      glColor4fv((GLfloat*)&fill->color);
  else glColor4f(1,1,1,1);
  
  
  /* Check image drawing mode */
  if (context->imageMode == VG_DRAW_IMAGE_MULTIPLY &&
      fill->type != VG_PAINT_TYPE_COLOR) {
    
    /* Draw image quad into stencil */
    glDisable(GL_BLEND);
    glDisable(GL_TEXTURE_2D);
    glEnable(GL_STENCIL_TEST);
    glStencilFunc(GL_ALWAYS, 1, 1);
    glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);
    glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE);
    
    glBegin(GL_QUADS);
    glVertex2i(0, 0);
    glVertex2i(i->width, 0);
    glVertex2i(i->width, i->height);
    glVertex2i(0, i->height);
    glEnd();

    /* Setup blending */
    updateBlendingStateGL(context, 0);
    
    /* Draw gradient mesh where stencil 1*/
    glEnable(GL_TEXTURE_2D);
    glStencilFunc(GL_EQUAL, 1, 1);
    glStencilOp(GL_ZERO,GL_ZERO,GL_ZERO);
    glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);
    
    SET2(min,0,0);
    SET2(max, (SHfloat)i->width, (SHfloat)i->height);
    if (fill->type == VG_PAINT_TYPE_RADIAL_GRADIENT) {
      shDrawRadialGradientMesh(fill, &min, &max, VG_FILL_PATH, GL_TEXTURE1);
    }else if (fill->type == VG_PAINT_TYPE_LINEAR_GRADIENT) {
      shDrawLinearGradientMesh(fill, &min, &max, VG_FILL_PATH, GL_TEXTURE1);
    }else if (fill->type == VG_PAINT_TYPE_PATTERN) {
      shDrawPatternMesh(fill, &min, &max, VG_FILL_PATH, GL_TEXTURE1); }
    
    glActiveTexture(GL_TEXTURE0);
    glDisable(GL_TEXTURE_2D);
    glDisable(GL_STENCIL_TEST);
    
  }else if (context->imageMode == VG_DRAW_IMAGE_STENCIL) {
    
    
  }else{/* Either normal mode or multiplying with a color-paint */
    
    /* Setup blending */
    updateBlendingStateGL(context, 0);

    /* Draw textured quad */
    glEnable(GL_TEXTURE_2D);
    
    glBegin(GL_QUADS);
    glVertex2i(0, 0);
    glVertex2i(i->width, 0);
    glVertex2i(i->width, i->height);
    glVertex2i(0, i->height);
    glEnd();
    
    glDisable(GL_TEXTURE_2D);
  }
  
  
  glDisable(GL_TEXTURE_GEN_S);
  glDisable(GL_TEXTURE_GEN_T);
  glPopMatrix();

  if (context->scissoring == VG_TRUE)
    glDisable( GL_SCISSOR_TEST );
  
  VG_RETURN(VG_NO_RETVAL);
}
コード例 #27
0
ファイル: Render.cpp プロジェクト: shirayukikitsune/xbeat
/* Render::renderSceneShadowMap: shadow mapping */
void Render::renderSceneShadowMap(PMDObject *objs, const short *order, int num, Stage *stage, bool useMMDLikeCartoon, bool useCartoonRendering, float lightIntensity, const float *lightDirection, const float *lightColor, int shadowMappingTextureSize, bool shadowMappingLightFirst, float shadowMappingSelfDensity)
{
   short i;
   GLint viewport[4]; /* store viewport */
   GLdouble modelview[16]; /* store model view transform */
   GLdouble projection[16]; /* store projection transform */
   bool toonLight = true;

#ifdef RENDER_SHADOWAUTOVIEW
   float eyeDist;
   btVector3 v;
#endif /* RENDER_SHADOWAUTOVIEW */

   static GLfloat lightdim[] = { 0.2f, 0.2f, 0.2f, 1.0f };
   static const GLfloat lightblk[] = { 0.0f, 0.0f, 0.0f, 1.0f };

   /* render the depth texture */
   /* store the current viewport */
   glGetIntegerv(GL_VIEWPORT, viewport);

   /* store the current projection matrix */
   glGetDoublev(GL_PROJECTION_MATRIX, projection);

   /* switch to FBO for depth buffer rendering */
   glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_fboID);

   /* clear the buffer */
   /* clear only the depth buffer, since other buffers will not be used */
   glClear(GL_DEPTH_BUFFER_BIT);

   /* set the viewport to the required texture size */
   glViewport(0, 0, shadowMappingTextureSize, shadowMappingTextureSize);

   /* reset the projection matrix */
   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();

   /* set the model view matrix to make the light position as eye point and capture the whole scene in the view */
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();

#ifdef RENDER_SHADOWAUTOVIEW
   /* set the distance to cover all the model range */
   eyeDist = m_shadowMapAutoViewRadius / sinf(RENDER_SHADOWAUTOVIEWANGLE * 0.5f * 3.1415926f / 180.0f);
   /* set the perspective */
   gluPerspective(RENDER_SHADOWAUTOVIEWANGLE, 1.0, 1.0, eyeDist + m_shadowMapAutoViewRadius + 50.0f); /* +50.0f is needed to cover the background */
   /* the viewpoint should be at eyeDist far toward light direction from the model center */
   v = m_lightVec * eyeDist + m_shadowMapAutoViewEyePoint;
   gluLookAt(v.x(), v.y(), v.z(), m_shadowMapAutoViewEyePoint.x(), m_shadowMapAutoViewEyePoint.y(), m_shadowMapAutoViewEyePoint.z(), 0.0, 1.0, 0.0);
#else
   /* fixed view */
   gluPerspective(25.0, 1.0, 1.0, 120.0);
   gluLookAt(30.0, 77.0, 30.0, 0.0, 17.0, 0.0, 0.0, 1.0, 0.0);
#endif /* RENDER_SHADOWAUTOVIEW */

   /* keep the current model view for later process */
   glGetDoublev(GL_MODELVIEW_MATRIX, modelview);

   /* do not write into frame buffer other than depth information */
   glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);

   /* also, lighting is not needed */
   glDisable(GL_LIGHTING);

   /* disable rendering the front surface to get the depth of back face */
   glCullFace(GL_FRONT);

   /* disable alpha test */
   glDisable(GL_ALPHA_TEST);

   /* we are now writing to depth texture using FBO, so disable the depth texture mapping here */
   glActiveTextureARB(GL_TEXTURE3_ARB);
   glDisable(GL_TEXTURE_2D);
   glActiveTextureARB(GL_TEXTURE0_ARB);

   /* set polygon offset to avoid "moire" */
   glEnable(GL_POLYGON_OFFSET_FILL);
   glPolygonOffset(4.0, 4.0);

   /* render objects for depth */
   /* only objects that wants to drop shadow should be rendered here */
   for (i = 0; i < num; i++) {
      if (objs[order[i]].isEnable() == true) {
         objs[order[i]].getPMDModel()->renderForShadow();
      }
   }

   /* reset the polygon offset */
   glDisable(GL_POLYGON_OFFSET_FILL);

   /* switch to default FBO */
   glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);

   /* revert configurations to normal rendering */
   glViewport(viewport[0], viewport[1], viewport[2], viewport[3]);
   glMatrixMode(GL_PROJECTION);
   glLoadMatrixd(projection);
   glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
   glEnable(GL_LIGHTING);
   glCullFace(GL_BACK);
   glEnable(GL_ALPHA_TEST);

   /* clear all the buffers */
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

   /* render the full scene */
   /* set model view matrix, as the same as normal rendering */
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   glMultMatrixf(m_rotMatrix);

   /* render the whole scene */
   if (shadowMappingLightFirst) {
      /* render light setting, later render only the shadow part with dark setting */
      stage->renderBackground();
      stage->renderFloor();
      for (i = 0; i < num; i++) {
         if (objs[order[i]].isEnable() == true) {
            if (objs[order[i]].getPMDModel()->getToonFlag() == false && toonLight == true) {
               /* disable toon lighting */
               updateLight(true, false, lightIntensity, lightDirection, lightColor);
               toonLight = false;
            } else if (objs[order[i]].getPMDModel()->getToonFlag() == true && toonLight == false) {
               /* enable toon lighting */
               updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor);
               toonLight = true;
            }
            objs[order[i]].getPMDModel()->renderModel();
            objs[order[i]].getPMDModel()->renderEdge();
         }
      }
      if (toonLight == false) {
         /* restore toon lighting */
         updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor);
      }
   } else {
      /* render in dark setting, later render only the non-shadow part with light setting */
      /* light setting for non-toon objects */
      lightdim[0] = lightdim[1] = lightdim[2] = 0.55f - 0.2f * shadowMappingSelfDensity;
      glLightfv(GL_LIGHT0, GL_DIFFUSE, lightdim);
      glLightfv(GL_LIGHT0, GL_AMBIENT, lightdim);
      glLightfv(GL_LIGHT0, GL_SPECULAR, lightblk);

      /* render the non-toon objects (back, floor, non-toon models) */
      stage->renderBackground();
      stage->renderFloor();
      for (i = 0; i < num; i++) {
         if (objs[order[i]].isEnable() == true && objs[order[i]].getPMDModel()->getToonFlag() == false)
            objs[order[i]].getPMDModel()->renderModel();
      }

      /* for toon objects, they should apply the model-defined toon texture color at texture coordinates (0, 0) for shadow rendering */
      /* so restore the light setting */
      if (useCartoonRendering == true)
         updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor);
      /* render the toon objects */
      for (i = 0; i < num; i++) {
         if (objs[order[i]].isEnable() == true && objs[order[i]].getPMDModel()->getToonFlag() == true) {
            /* set texture coordinates for shadow mapping */
            objs[order[i]].getPMDModel()->updateShadowColorTexCoord(shadowMappingSelfDensity);
            /* tell model to render with the shadow corrdinates */
            objs[order[i]].getPMDModel()->setSelfShadowDrawing(true);
            /* render model and edge */
            objs[order[i]].getPMDModel()->renderModel();
            objs[order[i]].getPMDModel()->renderEdge();
            /* disable shadow rendering */
            objs[order[i]].getPMDModel()->setSelfShadowDrawing(false);
         }
      }
      if (useCartoonRendering == false)
         updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor);
   }

   /* render the part clipped by the depth texture */
   /* activate the texture unit for shadow mapping and make it current */
   glActiveTextureARB(GL_TEXTURE3_ARB);

   /* set texture matrix (note: matrices should be set in reverse order) */
   glMatrixMode(GL_TEXTURE);
   glLoadIdentity();
   /* move the range from [-1,1] to [0,1] */
   glTranslated(0.5, 0.5, 0.5);
   glScaled(0.5, 0.5, 0.5);
   /* multiply the model view matrix when the depth texture was rendered */
   glMultMatrixd(modelview);
   /* multiply the inverse matrix of current model view matrix */
   glMultMatrixf(m_rotMatrixInv);

   /* revert to model view matrix mode */
   glMatrixMode(GL_MODELVIEW);

   /* enable texture mapping with texture coordinate generation */
   glEnable(GL_TEXTURE_2D);
   glEnable(GL_TEXTURE_GEN_S);
   glEnable(GL_TEXTURE_GEN_T);
   glEnable(GL_TEXTURE_GEN_R);
   glEnable(GL_TEXTURE_GEN_Q);

   /* bind the depth texture rendered at the first step */
   glBindTexture(GL_TEXTURE_2D, m_depthTextureID);

   /* depth texture set up was done, now switch current texture unit to default */
   glActiveTextureARB(GL_TEXTURE0_ARB);

   /* set depth func to allow overwrite for the same surface in the following rendering */
   glDepthFunc(GL_LEQUAL);

   if (shadowMappingLightFirst) {
      /* the area clipped by depth texture by alpha test is dark part */
      glAlphaFunc(GL_GEQUAL, 0.1f);

      /* light setting for non-toon objects */
      lightdim[0] = lightdim[1] = lightdim[2] = 0.55f - 0.2f * shadowMappingSelfDensity;
      glLightfv(GL_LIGHT0, GL_DIFFUSE, lightdim);
      glLightfv(GL_LIGHT0, GL_AMBIENT, lightdim);
      glLightfv(GL_LIGHT0, GL_SPECULAR, lightblk);

      /* render the non-toon objects (back, floor, non-toon models) */
      stage->renderBackground();
      stage->renderFloor();
      for (i = 0; i < num; i++) {
         if (objs[order[i]].isEnable() == true && objs[order[i]].getPMDModel()->getToonFlag() == false)
            objs[order[i]].getPMDModel()->renderModel();
      }

      /* for toon objects, they should apply the model-defined toon texture color at texture coordinates (0, 0) for shadow rendering */
      /* so restore the light setting */
      if (useCartoonRendering == true)
         updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor);
      /* render the toon objects */
      for (i = 0; i < num; i++) {
         if (objs[order[i]].isEnable() == true && objs[order[i]].getPMDModel()->getToonFlag() == true) {
            /* set texture coordinates for shadow mapping */
            objs[order[i]].getPMDModel()->updateShadowColorTexCoord(shadowMappingSelfDensity);
            /* tell model to render with the shadow corrdinates */
            objs[order[i]].getPMDModel()->setSelfShadowDrawing(true);
            /* render model and edge */
            objs[order[i]].getPMDModel()->renderModel();
            /* disable shadow rendering */
            objs[order[i]].getPMDModel()->setSelfShadowDrawing(false);
         }
      }
      if (useCartoonRendering == false)
         updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor);
   } else {
      /* the area clipped by depth texture by alpha test is light part */
      glAlphaFunc(GL_GEQUAL, 0.001f);
      stage->renderBackground();
      stage->renderFloor();
      for (i = 0; i < num; i++) {
         if (objs[order[i]].isEnable() == true) {
            if (objs[order[i]].getPMDModel()->getToonFlag() == false && toonLight == true) {
               /* disable toon lighting */
               updateLight(true, false, lightIntensity, lightDirection, lightColor);
               toonLight = false;
            } else if (objs[order[i]].getPMDModel()->getToonFlag() == true && toonLight == false) {
               /* enable toon lighting */
               updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor);
               toonLight = true;
            }
            objs[order[i]].getPMDModel()->renderModel();
         }
      }
      if (toonLight == false) {
         /* restore toon lighting */
         updateLight(useMMDLikeCartoon, useCartoonRendering, lightIntensity, lightDirection, lightColor);
      }
   }

   /* reset settings */
   glDepthFunc(GL_LESS);
   glAlphaFunc(GL_GEQUAL, 0.05f);

   glActiveTextureARB(GL_TEXTURE3_ARB);
   glDisable(GL_TEXTURE_GEN_S);
   glDisable(GL_TEXTURE_GEN_T);
   glDisable(GL_TEXTURE_GEN_R);
   glDisable(GL_TEXTURE_GEN_Q);
   glDisable(GL_TEXTURE_2D);
   glActiveTextureARB(GL_TEXTURE0_ARB);
}
コード例 #28
0
ファイル: gl_rdev_mtx.cpp プロジェクト: jsccl1988/smartgis
	long SmtGLRenderDevice::MatrixMultiply(const Matrix& mtx)
	{
		glMultMatrixf( (float*)(&mtx) );

		return SMT_ERR_NONE;
	}
コード例 #29
0
ファイル: cSpace.cpp プロジェクト: jsj2008/roverSim
/////////////////////////////////////////
// Drawing the C-space objects 
/////////////
void cSpace::renderGLObject()
{
	int i;
// draws the golden outline for the c-space ghost objects
	btScalar	glm[16];

	glLineWidth(1.);
	glDisable(GL_LIGHTING);

	for(i = 0; i < m_ghostObjects.size(); ++i)
	{
		m_ghostObjects[i]->getWorldTransform().getOpenGLMatrix(glm);
		btCollisionShape* colisShape = m_ghostObjects[i]->getCollisionShape();
		
		switch(colisShape->getShapeType()){ 
			case BOX_SHAPE_PROXYTYPE: {
				glColor3f(0.99f,0.82f,0.1f); // golden C-Space
				if(m_ghostObjects[i]->getUserPointer()) glColor3f(0.8f,1,0.5);
				const btBoxShape* boxShape = static_cast<const btBoxShape*>(colisShape);
				btVector3 halfDims = boxShape->getHalfExtentsWithMargin();

				glPushMatrix();
				glMultMatrixf(glm);
				wireBox(halfDims.x(),halfDims.y(),halfDims.z());
				glPopMatrix();	
				break;
			}
			case CONVEX_HULL_SHAPE_PROXYTYPE: {
				glColor3f(0.99f,0.82f,0.1f); // golden C-Space
				if(m_ghostObjects[i]->getUserPointer()) glColor3f(0.8f,1,0.5);
				const btConvexHullShape* hullShape = static_cast<const btConvexHullShape*>(colisShape);
				const btVector3* ptlist = hullShape->getUnscaledPoints();
				int numPts = hullShape->getNumPoints();
				
				Vertex verts[numPts];
				for(int j=0;j<numPts;j++)
				{
					verts[j].x = ptlist[j].x();
					verts[j].y = ptlist[j].y();
					verts[j].z = ptlist[j].z();
				}
				
				glPushMatrix();
				glMultMatrixf(glm);
				wireSymmetricHull(verts,numPts);
				glPopMatrix();
				break;
			}
			case COMPOUND_SHAPE_PROXYTYPE: {
				glColor3f(0.f,1.f,0.f); //C-Space
				const btCompoundShape* shp = static_cast<const btCompoundShape*>(colisShape);
				for(int j=0; j<shp->getNumChildShapes(); j++){
					shp->getChildTransform(j).getOpenGLMatrix(glm);
					const btBoxShape* boxShape = static_cast<const btBoxShape*>(shp->getChildShape(j));
					btVector3 halfDims = boxShape->getHalfExtentsWithMargin();

					glPushMatrix();
					glMultMatrixf(glm);
					wireBox(halfDims.x(),halfDims.y(),halfDims.z());
					glPopMatrix();
				}
			}
			default:
			break;
		}
	}
	glEnable(GL_LIGHTING);
}
コード例 #30
0
ファイル: ObjMesh.cpp プロジェクト: 1Tom1/FYPManagement
// ----------------------------------------------------------------------
void ObjMesh::draw(unsigned int baseColor, bool wireframe, bool shadows)
{
	if (mVertices.size() == 0) 
		return;

	Renderer *renderer = Renderer::getInstance();
	renderer->setColor(baseColor);

	if (wireframe)
		renderer->wireframeMode(true);
		

	if (!mHasTextureCoords)
		renderer->deactivateTexture();

	int i;
	int materialNr = -1;
	TexCoord *texPointer = NULL;
	float textured = false;
	ObjMeshString fname;

	mDrawIndices.clear();

	if (!mHasTextureCoords) {
		for (i = 0; i < (int)mTriangles.size(); i++) {
			ObjMeshTriangle &t = mTriangles[i];
			mDrawIndices.push_back(t.vertexNr[0]);
			mDrawIndices.push_back(t.vertexNr[1]);
			mDrawIndices.push_back(t.vertexNr[2]);
		}

		renderer->drawTriangles(mTriangles.size(), mVertices.size() ,&mDrawIndices[0], &mVertices[0], &mNormals[0], NULL);

		if (shadows) {
			const static float ShadowMat[]={ 1,0,0,0, 0,0,0,0, 0,0,1,0, 0,0,0,1 };
			glPushMatrix();
			glMultMatrixf(ShadowMat);
			glDisable(GL_LIGHTING);

			glColor4f(0.05f, 0.1f, 0.15f,1.0f);

			renderer->drawTriangles(mTriangles.size(), mVertices.size() ,&mDrawIndices[0], &mVertices[0], &mNormals[0], NULL);
			
			renderer->setColor(baseColor);
			glEnable(GL_LIGHTING);
			glPopMatrix();
		}
		
		if (wireframe)
			renderer->wireframeMode(false);

		return;
	}

	for (i = 0; i < (int)mMaterials.size(); i++) {
		ObjMeshMaterial &m = mMaterials[i];
		if (strlen(m.texFilename) == 0)
			m.texNr = -1;
		else {
			sprintf(fname, "%s\\%s", mPath, m.texFilename);
			m.texNr = renderer->findTexture(fname);
			if (m.texNr < 0)
				m.texNr = renderer->addBmpTexture(fname);
		}
	}

	for (i = 0; i < (int)mTriangles.size(); i++) {
		ObjMeshTriangle &t = mTriangles[i];
		if (t.materialNr != materialNr) {
			if ((int)mDrawIndices.size() > 0) {

				renderer->drawTriangles(mDrawIndices.size()/3, mVertices.size(), &mDrawIndices[0], 
					&mVertices[0], &mNormals[0], textured ? &mTexCoords[0] : NULL);
		
			}

			mDrawIndices.clear();
			textured = false;

			materialNr = t.materialNr;
			if (materialNr >= 0) {
				int texNr = mMaterials[materialNr].texNr;
				if (texNr >= 0) {
					renderer->activateTexture(texNr);
					renderer->setColor(baseColor);
					textured = true;
				}
				else {
					renderer->deactivateTexture();
					renderer->setColor3r(mMaterials[materialNr].ambient);
				}
			}
		}

		mDrawIndices.push_back(t.vertexNr[0]);
		mDrawIndices.push_back(t.vertexNr[1]);
		mDrawIndices.push_back(t.vertexNr[2]);
	}
	if ((int)mDrawIndices.size() > 0) { 
		renderer->drawTriangles(mDrawIndices.size()/3, mVertices.size(), &mDrawIndices[0], 
			&mVertices[0], &mNormals[0], textured ? &mTexCoords[0] : NULL);
	}

	if (shadows) {
		const static float ShadowMat[]={ 1,0,0,0, 0,0,0,0, 0,0,1,0, 0,0,0,1 };
		glPushMatrix();
		glMultMatrixf(ShadowMat);
		glDisable(GL_LIGHTING);

		glColor4f(0.05f, 0.1f, 0.15f,1.0f);
	
		renderer->drawTriangles(mDrawIndices.size()/3, mVertices.size(), &mDrawIndices[0], 
			&mVertices[0], &mNormals[0], textured ? &mTexCoords[0] : NULL);
	
		renderer->setColor(baseColor);
		glEnable(GL_LIGHTING);
		glPopMatrix();
	}

	if (wireframe)
		renderer->wireframeMode(false);
}