Exemplo n.º 1
0
static void pie_Draw3DShape2(iIMDShape *shape, int frame, PIELIGHT colour, PIELIGHT teamcolour, WZ_DECL_UNUSED PIELIGHT specular, int pieFlag, int pieFlagData)
{
	iIMDPoly *pPolys;
	bool light = lighting;

	pie_SetAlphaTest(true);

	/* Set fog status */
	if (!(pieFlag & pie_FORCE_FOG) && 
		(pieFlag & pie_ADDITIVE || pieFlag & pie_TRANSLUCENT || pieFlag & pie_BUTTON))
	{
		pie_SetFogStatus(false);
	}
	else
	{
		pie_SetFogStatus(true);
	}

	/* Set tranlucency */
	if (pieFlag & pie_ADDITIVE)
	{
		pie_SetRendMode(REND_ADDITIVE);
		colour.byte.a = (UBYTE)pieFlagData;
		light = false;
	}
	else if (pieFlag & pie_TRANSLUCENT)
	{
		pie_SetRendMode(REND_ALPHA);
		colour.byte.a = (UBYTE)pieFlagData;
		light = false;
	}
	else
	{
		if (pieFlag & pie_BUTTON)
		{
			pie_SetDepthBufferStatus(DEPTH_CMP_LEQ_WRT_ON);
		}
		pie_SetRendMode(REND_OPAQUE);
	}

	if (light)
	{
		const float ambient[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
		const float diffuse[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
		const float specular[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
		const float shininess = 10;

		glEnable(GL_LIGHTING);
		glEnable(GL_NORMALIZE);

		glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient);
		glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse);
		glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular);
		glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess);
	}

	if (pieFlag & pie_HEIGHT_SCALED)	// construct
	{
		glScalef(1.0f, (float)pieFlagData / (float)pie_RAISE_SCALE, 1.0f);
	}
	if (pieFlag & pie_RAISE)		// collapse
	{
		glTranslatef(1.0f, (-shape->max.y * (pie_RAISE_SCALE - pieFlagData)) / pie_RAISE_SCALE, 1.0f);
	}

	glColor4ubv(colour.vector);	// Only need to set once for entire model
	pie_SetTexturePage(shape->texpage);

	// Activate TCMask if needed
	if (shape->flags & iV_IMD_TCMASK &&	rendStates.rendMode == REND_OPAQUE)
	{
#ifdef _DEBUG
	glErrors();
#endif
		if (pie_GetShadersStatus())
		{
			pie_ActivateShader_TCMask(teamcolour, shape->tcmaskpage);
		}
		else
		{
			//Set the environment colour with tcmask
			GLfloat tc_env_colour[4];  
			pal_PIELIGHTtoRGBA4f(&tc_env_colour[0], teamcolour);

			// TU0
			glActiveTexture(GL_TEXTURE0);
			glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,	GL_COMBINE);
			glTexEnvfv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_COLOR, tc_env_colour);

			// TU0 RGB
			glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB,		GL_ADD_SIGNED);
			glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB,		GL_TEXTURE);
			glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB,		GL_SRC_COLOR);
			glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB,		GL_CONSTANT);
			glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB,		GL_SRC_COLOR);

			// TU0 Alpha
			glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA,		GL_REPLACE);
			glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA,		GL_TEXTURE);
			glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA,	GL_SRC_ALPHA);

			// TU1
			glActiveTexture(GL_TEXTURE1);
			glEnable(GL_TEXTURE_2D);
			glBindTexture(GL_TEXTURE_2D, _TEX_PAGE[shape->tcmaskpage].id);
			glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE,	GL_COMBINE);

			// TU1 RGB
			glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_RGB,		GL_INTERPOLATE);
			glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_RGB,		GL_PREVIOUS);
			glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_RGB,		GL_SRC_COLOR);
			glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE1_RGB,		GL_TEXTURE0);
			glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND1_RGB,		GL_SRC_COLOR);
			glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE2_RGB,		GL_TEXTURE);
			glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND2_RGB,		GL_SRC_ALPHA);

			// TU1 Alpha
			glTexEnvi(GL_TEXTURE_ENV, GL_COMBINE_ALPHA,		GL_REPLACE);
			glTexEnvi(GL_TEXTURE_ENV, GL_SOURCE0_ALPHA,		GL_PREVIOUS);
			glTexEnvi(GL_TEXTURE_ENV, GL_OPERAND0_ALPHA,	GL_SRC_ALPHA);


			// This is why we are doing in opaque mode.
			glEnable(GL_BLEND);
			glBlendFunc(GL_CONSTANT_COLOR, GL_ZERO);
			glBlendColor(colour.byte.r / 255.0, colour.byte.g / 255.0,
						colour.byte.b / 255.0, colour.byte.a / 255.0);
		}
#ifdef _DEBUG
	glErrors();
#endif
	}

	for (pPolys = shape->polys; pPolys < shape->polys + shape->npolys; pPolys++)
	{
		Vector2f	texCoords[pie_MAX_VERTICES_PER_POLYGON];
		Vector3f	vertexCoords[pie_MAX_VERTICES_PER_POLYGON];
		unsigned int n;
		VERTEXID	*index;

		for (n = 0, index = pPolys->pindex;
				n < pPolys->npnts;
				n++, index++)
		{
			vertexCoords[n].x = shape->points[*index].x;
			vertexCoords[n].y = shape->points[*index].y;
			vertexCoords[n].z = shape->points[*index].z;
			texCoords[n].x = pPolys->texCoord[n].x;
			texCoords[n].y = pPolys->texCoord[n].y;
		}

		polyCount++;

		// Run TextureAnimation (exluding the new teamcoloured models)
		if (frame && pPolys->flags & iV_IMD_TEXANIM && !(shape->flags & iV_IMD_TCMASK))
		{
			frame %= shape->numFrames;

			if (frame > 0)
			{
				const int framesPerLine = OLD_TEXTURE_SIZE_FIX / (pPolys->texAnim.x * OLD_TEXTURE_SIZE_FIX);
				const int uFrame = (frame % framesPerLine) * (pPolys->texAnim.x * OLD_TEXTURE_SIZE_FIX);
				const int vFrame = (frame / framesPerLine) * (pPolys->texAnim.y * OLD_TEXTURE_SIZE_FIX);

				for (n = 0; n < pPolys->npnts; n++)
				{
					texCoords[n].x += uFrame / OLD_TEXTURE_SIZE_FIX;
					texCoords[n].y += vFrame / OLD_TEXTURE_SIZE_FIX;
				}
			}
		}

		glBegin(GL_TRIANGLE_FAN);

		if (light)
		{
			glNormal3fv((GLfloat*)&pPolys->normal);
		}

		for (n = 0; n < pPolys->npnts; n++)
		{
			glTexCoord2fv((GLfloat*)&texCoords[n]);
			if (shape->flags & iV_IMD_TCMASK && rendStates.rendMode == REND_OPAQUE &&
				!pie_GetShadersStatus())
			{
				glMultiTexCoord2fv(GL_TEXTURE1, (GLfloat*)&texCoords[n]);
			}
			glVertex3fv((GLfloat*)&vertexCoords[n]);
		}

		glEnd();
	}

	// Deactivate TCMask if it was previously enabled
	if (shape->flags & iV_IMD_TCMASK && rendStates.rendMode == REND_OPAQUE)
	{
		if (pie_GetShadersStatus())
		{
			pie_DeactivateShader();
		}
		else
		{
			glDisable(GL_BLEND);

			glActiveTexture(GL_TEXTURE1);
			glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
			glDisable(GL_TEXTURE_2D);

			glActiveTexture(GL_TEXTURE0);
			glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
		}
	}

	if (pieFlag & pie_BUTTON)
	{
		pie_SetDepthBufferStatus(DEPTH_CMP_ALWAYS_WRT_ON);
	}

	if (light)
	{
		glDisable(GL_LIGHTING);
		glDisable(GL_NORMALIZE);
	}
}
Exemplo n.º 2
0
/* draw lines for F-Curve handles only (this is only done in EditMode)
 * note: draw_fcurve_handles_check must be checked before running this. */
static void draw_fcurve_handles(SpaceIpo *sipo, FCurve *fcu)
{
	int sel, b;
	
	/* a single call to GL_LINES here around these calls should be sufficient to still
	 * get separate line segments, but which aren't wrapped with GL_LINE_STRIP every time we
	 * want a single line
	 */
	glBegin(GL_LINES);
	
	/* slightly hacky, but we want to draw unselected points before selected ones 
	 * so that selected points are clearly visible
	 */
	for (sel = 0; sel < 2; sel++) {
		BezTriple *bezt = fcu->bezt, *prevbezt = NULL;
		int basecol = (sel) ? TH_HANDLE_SEL_FREE : TH_HANDLE_FREE;
		float *fp;
		unsigned char col[4];
		
		for (b = 0; b < fcu->totvert; b++, prevbezt = bezt, bezt++) {
			/* if only selected keyframes can get their handles shown, 
			 * check that keyframe is selected
			 */
			if (sipo->flag & SIPO_SELVHANDLESONLY) {
				if (BEZSELECTED(bezt) == 0)
					continue;
			}
			
			/* draw handle with appropriate set of colors if selection is ok */
			if ((bezt->f2 & SELECT) == sel) {
				fp = bezt->vec[0];
				
				/* only draw first handle if previous segment had handles */
				if ((!prevbezt && (bezt->ipo == BEZT_IPO_BEZ)) || (prevbezt && (prevbezt->ipo == BEZT_IPO_BEZ))) {
					UI_GetThemeColor3ubv(basecol + bezt->h1, col);
					col[3] = fcurve_display_alpha(fcu) * 255;
					glColor4ubv((GLubyte *)col);
					
					glVertex2fv(fp); glVertex2fv(fp + 3);
				}
				
				/* only draw second handle if this segment is bezier */
				if (bezt->ipo == BEZT_IPO_BEZ) {
					UI_GetThemeColor3ubv(basecol + bezt->h2, col);
					col[3] = fcurve_display_alpha(fcu) * 255;
					glColor4ubv((GLubyte *)col);
					
					glVertex2fv(fp + 3); glVertex2fv(fp + 6);
				}
			}
			else {
				/* only draw first handle if previous segment was had handles, and selection is ok */
				if (((bezt->f1 & SELECT) == sel) &&
				    ((!prevbezt && (bezt->ipo == BEZT_IPO_BEZ)) || (prevbezt && (prevbezt->ipo == BEZT_IPO_BEZ))))
				{
					fp = bezt->vec[0];
					UI_GetThemeColor3ubv(basecol + bezt->h1, col);
					col[3] = fcurve_display_alpha(fcu) * 255;
					glColor4ubv((GLubyte *)col);
					
					glVertex2fv(fp); glVertex2fv(fp + 3);
				}
				
				/* only draw second handle if this segment is bezier, and selection is ok */
				if (((bezt->f3 & SELECT) == sel) &&
				    (bezt->ipo == BEZT_IPO_BEZ))
				{
					fp = bezt->vec[1];
					UI_GetThemeColor3ubv(basecol + bezt->h2, col);
					col[3] = fcurve_display_alpha(fcu) * 255;
					glColor4ubv((GLubyte *)col);
					
					glVertex2fv(fp); glVertex2fv(fp + 3);
				}
			}
		}
	}
	
	glEnd();  /* GL_LINES */
}
Exemplo n.º 3
0
static void Display( void )
{
   const struct interleave_info * const curr_info = info[ interleave_mode ];

   /* 4 floats for 12 verticies for 4 data elements.
    */
   char data[ (sizeof( GLfloat ) * 4) * 12 * 4 ];

   unsigned i;
   unsigned offset;
   GLenum err;
   GLenum format;
   GLsizei stride;


   glClearColor(0.2, 0.2, 0.8, 0);
   glClear( GL_COLOR_BUFFER_BIT );

   glPushMatrix();

   glTranslatef(-1.5, 0, 0);

   glColor3fv( c_f[0] );

   if ( curr_info[0].data != NULL ) {
      glEnable( GL_TEXTURE_2D );
   }
   else {
      glDisable( GL_TEXTURE_2D );
   }


   offset = 0;
   glBegin(GL_TRIANGLES);
   for ( i = 0 ; i < 12 ; i++ ) {
      const unsigned index = indicies[i];


      /* Handle the vertex texture coordinate.
       */
      if ( curr_info[0].data != NULL ) {
	 if ( curr_info[0].count == 2 ) {
	    glTexCoord2fv( DEREF(0, index) );
	 }
	 else {
	    glTexCoord4fv( DEREF(0, index) );
	 }

	 (void) memcpy( & data[ offset ], DEREF(0, index),
			curr_info[0].size );
	 offset += curr_info[0].size;
      }


      /* Handle the vertex color.
       */
      if ( curr_info[1].data != NULL ) {
	 if ( curr_info[1].type == GL_FLOAT ) {
	    if ( curr_info[1].count == 3 ) {
	       glColor3fv( DEREF(1, index) );
	    }
	    else {
	       glColor4fv( DEREF(1, index) );
	    }
	 }
	 else {
	    glColor4ubv( DEREF(1, index) );
	 }

	 (void) memcpy( & data[ offset ], DEREF(1, index), 
			curr_info[1].size );
	 offset += curr_info[1].size;
      }

      
      /* Handle the vertex normal.
       */
      if ( curr_info[2].data != NULL ) {
	 glNormal3fv( DEREF(2, index) );

	 (void) memcpy( & data[ offset ], DEREF(2, index),
			curr_info[2].size );
	 offset += curr_info[2].size;
      }


      switch( curr_info[3].count ) {
      case 2:
	 glVertex2fv( DEREF(3, index) );
	 break;
      case 3:
	 glVertex3fv( DEREF(3, index) );
	 break;
      case 4:
	 glVertex4fv( DEREF(3, index) );
	 break;
      }

      (void) memcpy( & data[ offset ], DEREF(3, index),
		     curr_info[3].size );
	 offset += curr_info[3].size;
   }
   glEnd();


   glTranslatef(3.0, 0, 0);

   /* The masking with ~0x2A00 is a bit of a hack to make sure that format
    * ends up with an invalid value no matter what rand() returns.
    */
   format = (use_invalid_mode)
     ? (rand() & ~0x2A00) : GL_V2F + interleave_mode;
   stride = (use_invalid_stride) ? -abs(rand()) : 0;

   (void) glGetError();
   glInterleavedArrays( format, stride, data );
   err = glGetError();
   if ( err ) {
      printf("glInterleavedArrays(0x%04x, %d, %p) generated the error 0x%04x\n",
	     format, stride, data, err );
   }
   else {
      glDrawArrays( GL_TRIANGLES, 0, 12 );
   }

   glPopMatrix();

   glutSwapBuffers();
}
Exemplo n.º 4
0
void LLDrawPoolGlow::pushBatch(LLDrawInfo& params, U32 mask, BOOL texture)
{
	glColor4ubv(params.mGlowColor.mV);
	LLRenderPass::pushBatch(params, mask, texture);
}
Exemplo n.º 5
0
void IDManager::setGLColor(int id) {
    col4 col = getColorFromId(id);
    glColor4ubv(col.elem);
}
Exemplo n.º 6
0
void DebugDrawGL::vertex(const float x, const float y, const float z, unsigned int color, const float u, const float v)
{
	glColor4ubv((GLubyte*)&color);
	glTexCoord2f(u,v);
	glVertex3f(x,y,z);
}
Exemplo n.º 7
0
void LLFacePool::LLOverrideFaceColor::setColor(const LLColor4U& color)
{
	glColor4ubv(color.mV);
}
Exemplo n.º 8
0
static void pie_Draw3DShape2(const iIMDShape *shape, int frame, PIELIGHT colour, PIELIGHT teamcolour, int pieFlag, int pieFlagData, glm::mat4 &matrix)
{
	bool light = true;

	glLoadMatrixf(&matrix[0][0]);

	/* Set fog status */
	if (!(pieFlag & pie_FORCE_FOG) && (pieFlag & pie_ADDITIVE || pieFlag & pie_TRANSLUCENT || pieFlag & pie_PREMULTIPLIED))
	{
		pie_SetFogStatus(false);
	}
	else
	{
		pie_SetFogStatus(true);
	}

	/* Set tranlucency */
	if (pieFlag & pie_ADDITIVE)
	{
		pie_SetRendMode(REND_ADDITIVE);
		colour.byte.a = (UBYTE)pieFlagData;
		light = false;
	}
	else if (pieFlag & pie_TRANSLUCENT)
	{
		pie_SetRendMode(REND_ALPHA);
		colour.byte.a = (UBYTE)pieFlagData;
		light = false;
	}
	else if (pieFlag & pie_PREMULTIPLIED)
	{
		pie_SetRendMode(REND_PREMULTIPLIED);
		light = false;
	}
	else
	{
		pie_SetRendMode(REND_OPAQUE);
	}

	if ((pieFlag & pie_PREMULTIPLIED) == 0)
	{
		glEnable(GL_ALPHA_TEST);
		glAlphaFunc(GL_GREATER, 0.001f);
	}

	if (pieFlag & pie_ECM)
	{
		pie_SetRendMode(REND_ALPHA);
		light = true;
		pie_SetShaderEcmEffect(true);
	}

	if (light)
	{
		if (shape->shaderProgram)
		{
			pie_ActivateShader(shape->shaderProgram, shape, teamcolour, colour);
		}
		else
		{
			pie_ActivateShader(SHADER_COMPONENT, shape, teamcolour, colour);
		}
	}
	else
	{
		pie_DeactivateShader();
	}

	glColor4ubv(colour.vector);     // Only need to set once for entire model
	pie_SetTexturePage(shape->texpage);

	frame %= MAX(1, shape->numFrames);

	glBindBuffer(GL_ARRAY_BUFFER, shape->buffers[VBO_VERTEX]); glVertexPointer(3, GL_FLOAT, 0, NULL);
	glBindBuffer(GL_ARRAY_BUFFER, shape->buffers[VBO_NORMAL]); glNormalPointer(GL_FLOAT, 0, NULL);
	glBindBuffer(GL_ARRAY_BUFFER, shape->buffers[VBO_TEXCOORD]); glTexCoordPointer(2, GL_FLOAT, 0, NULL);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, shape->buffers[VBO_INDEX]);
	glDrawElements(GL_TRIANGLES, shape->npolys * 3, GL_UNSIGNED_SHORT, BUFFER_OFFSET(frame * shape->npolys * 3 * sizeof(uint16_t)));

	polyCount += shape->npolys;

	pie_SetShaderEcmEffect(false);
	glDisable(GL_ALPHA_TEST);
}
Exemplo n.º 9
0
void iphoneMultiplayerMenu() {
	if ( gameSocket <= 0 ) {
		// no socket, so no multiplayer
		TerminateGameService();		// don't advertise for any more new players
		setupPacket.gameID = 0;		// stop sending packets
		menuState = IPM_MAIN;
		return;
	}

	boolean	server = ( setupPacket.gameID == localGameID );
	
	// different screen when selecting a map to play
	if ( netMenu == NM_MAP_SELECT ) {
		mapStart_t	map;
		if ( !iphoneMapSelectMenu( &map ) ) {
			// haven't selected anything yet
			return;
		}
		netMenu = NM_MAIN;
		if ( map.map != -1 ) {
			// selected something new, didn't hit the back arrow
			setupPacket.map = map;
		}
	}
	
	#ifndef IPAD
	else if ( netMenu == NM_OPTIONS ) {
		
		Cvar_SetValue( fragLimit->name, setupPacket.fraglimit );
		if ( iphoneSlider( 104, 64, 272, 40, "frag limit", fragLimit, 0, 20, SF_INTEGER ) ) {
			if ( server ) {
				setupPacket.fraglimit = fragLimit->value;
			}
		}
		
		Cvar_SetValue( timeLimit->name, setupPacket.timelimit );
		if ( iphoneSlider( 104, 64+56, 272, 40, "time limit", timeLimit, 0, 20, SF_INTEGER ) ) {
			if ( server ) {
				setupPacket.timelimit = timeLimit->value;
			}
		}
		if ( BackButton() ) {
			netMenu = NM_MAIN;
		}
		return;
	}
	#else
	Cvar_SetValue( fragLimit->name, setupPacket.fraglimit );
	if ( iphoneSlider( 314, 410, 400, 40, "frag limit", fragLimit, 0, 20, SF_INTEGER ) ) {
		if ( server ) {
			setupPacket.fraglimit = fragLimit->value;
		}
	}
	
	Cvar_SetValue( timeLimit->name, setupPacket.timelimit );
	if ( iphoneSlider( 314, 410+58, 400, 40, "time limit", timeLimit, 0, 20, SF_INTEGER ) ) {
		if ( server ) {
			setupPacket.timelimit = timeLimit->value;
		}
	}
	
	#endif
	
	if ( !btnDeathmatch.texture ) {
		// initial setup
		#ifdef IPAD
		SetButtonPicsAndSizes( &btnDeathmatch, "iphone/deathmatch.tga", "Deathmatch", 512-128-50, 150, 128, 128 );
		SetButtonPicsAndSizes( &btnCoop, "iphone/co-op.tga", "Cooperative", 512+50, 150, 128, 128 );
		#else
		SetButtonPicsAndSizes( &btnDeathmatch, "iphone/deathmatch.tga", "Deathmatch", 4+48, 64, 96, 96 );
		SetButtonPicsAndSizes( &btnCoop, "iphone/co-op.tga", "Cooperative", 480-148, 64, 96, 96 );		
		#endif
	}

	if ( BackButton() ) {
		if ( server ) {
			TerminateGameService();		// don't advertise for any more new players
			setupPacket.gameID = 0;		// stop sending packets
		}
		menuState = IPM_MAIN;
	}
	
	if ( !server ) {
		// we aren't the server
		// send our join packet every frame
		SendJoinPacket();
		
		if ( setupPacketFrameNum < iphoneFrameNum - 30 ) {
			// haven't received a current server packet
			char	str[1024];
			struct sockaddr_in *sin = (struct sockaddr_in *)&netServer.address;
			byte *ip = (byte *)&sin->sin_addr;
			sprintf( str, "Joining server at %i.%i.%i.%i:%i\n", ip[0], ip[1], ip[2], ip[3], 
					ntohs( sin->sin_port ) );
			#ifdef IPAD
			iphoneCenterText( 512, 384, 1, str );			
			#else	
			iphoneCenterText( 240, 160, 0.75, str );
			#endif
			return;
		}
	} else {
		// cull out any players that haven't given us a packet in a couple seconds
		int	now = SysIphoneMilliseconds();
		for ( int i = 1 ; i < MAXPLAYERS ; i++ ) {
			if ( setupPacket.playerID[i] && now - netPlayers[i].peer.lastPacketTime > 1000 ) {
				printf( "Dropping player %i: last:%i now:%i\n", i, netPlayers[i].peer.lastPacketTime, now );
				setupPacket.playerID[i] = 0;
			}
		}
	}
	
	// draw the level and allow clicking to change
	Cvar_SetValue( mpDataset->name, setupPacket.map.dataset );
	Cvar_SetValue( mpEpisode->name, setupPacket.map.episode );
	Cvar_SetValue( mpMap->name, setupPacket.map.map );
	Cvar_SetValue( mpSkill->name, setupPacket.map.skill );
	
	// map select button / display
	#ifdef IPAD
	if ( NewTextButton( &btnMap,  FindMapName( mpDataset->value, mpEpisode->value, mpMap->value ), 512 - 200, 80, 400, 48 ) ) {
	#else
	if ( NewTextButton( &btnMap,  FindMapName( mpDataset->value, mpEpisode->value, mpMap->value ), 64, 0, 480-128, 48 ) ) {	
	#endif
		
		if ( server ) {
			// clients can't go into this menu
			netMenu = NM_MAP_SELECT;
		}
	}

	
	if ( setupPacket.deathmatch ) {
		btnDeathmatch.buttonFlags = 0;
		btnCoop.buttonFlags = BF_DIMMED;
	} else {
		btnDeathmatch.buttonFlags = BF_DIMMED;
		btnCoop.buttonFlags = 0;
	}
	
	if ( HandleButton( &btnDeathmatch ) ) {
		if ( server ) {
			Cvar_SetValue( mpDeathmatch->name, 3 );	// weapons stay, items respawn rules
			setupPacket.deathmatch = mpDeathmatch->value;
		}
	}
	if ( HandleButton( &btnCoop ) ) {
		if ( server ) {
			Cvar_SetValue( mpDeathmatch->name, 0 );		
			setupPacket.deathmatch = mpDeathmatch->value;
		}
	}	
#ifndef IPAD
	if ( NewTextButton( &btnNetSettings, "Settings",  240-64, 64+24, 128, 48 ) ) {
		netMenu = NM_OPTIONS;
	}
#endif
			
	for ( int i = 0 ; i < 4 ; i ++ ) {
		#ifdef IPAD
		int x = 320 + ( 64+45) * i;
		int y = 64+260;
		#else
		int x = 45 + ( 64+45) * i;
		int y = 64+128;
		#endif
		// FIXME: show proper player colors
		byte	color[4][4] = { { 0, 255, 0, 255 }, { 128, 128, 128, 255 }, { 128,64,0, 255 }, {255,0,0, 255 } };
		glColor4ubv( color[i] );
		PK_DrawTexture( PK_FindTexture( "iphone/multi_backdrop.tga" ), x, y );
		glColor4f( 1, 1, 1, 1 );
		if ( setupPacket.playerID[i] == playerID ) {
			// bigger outline for your player slot
			PK_StretchTexture( PK_FindTexture( "iphone/multi_frame.tga" ), x, y, 64, 64 );
		}
		
		
		// draw doom guy face
		if ( setupPacket.playerID[i] != 0 ) {
			PK_DrawTexture( PK_FindTexture( "iphone/multi_face.tga" ), x, y );
#if 0			
			// temp display IP address
			byte *ip = (byte *)&setupPacket.address[i].sin_addr;
			iphoneDrawText( x-16, (i&1) ? y+16 : y+48, 0.75, va("%i.%i.%i.%i", ip[0], ip[1], ip[2], ip[3] ) );
#endif
		}
		
	}
	
	if ( server ) {
		// flash a tiny pic when transmitting
		if ( iphoneFrameNum & 1 ) {
			glColor4f( 1,1,1,1 );
		} else {
			glColor4f( 0.5,0.5,0.5,1 );
		}
		#ifdef IPAD
		iphoneCenterText( 1024 - 20, 768 - 20, 1, "*" );
		#else
		iphoneCenterText( 470, 310, 0.75, "*" );
		#endif
		glColor4f( 1,1,1,1 );
	}
	if ( setupPacketFrameNum == iphoneFrameNum ) {
	#ifdef IPAD
		iphoneCenterText( 1024 - 40, 768 - 20, 1, "*" );
	#else
		iphoneCenterText( 450, 310, 0.75, "*" );
	#endif
	}
//	iphoneDrawText( 0, 310, 0.75, va("%i:%i", localGameID, setupPacket.gameID ) );

	// only draw the start button if we have at least two players in game
	int	numPlayers = 0;
	for ( int i = 0 ; i < MAXPLAYERS ; i++ ) {
		if ( setupPacket.playerID[i] != 0 ) {
			numPlayers++;
		}
	}
	
	if ( numPlayers > 1 ) {
		if ( server ) {
			static ibutton_t btnStart;
			#ifdef IPAD
			if ( NewTextButton( &btnStart, "Start game", 512-80, 768-100, 160, 48) ) {
			#else
			if ( NewTextButton( &btnStart, "Start game", 240-80, 320-48, 160, 48 ) ) {
			#endif
				setupPacket.startGame = 1;
				StartNetGame();
				TerminateGameService();		// don't advertise for any more new players
				return;
			}
		} else {
		#ifdef IPAD	
			iphoneCenterText( 512, 68-25, 1, "Waiting for server to start the game" );
		#else
			iphoneCenterText( 240, 320-10, 0.60, "Waiting for server to start the game" );
		#endif
		}
	} else {
		byte *ip = (byte *)&gameSocketAddress.sin_addr;
		#ifdef IPAD
		iphoneCenterText( 512, 768-25, 1, va("Waiting for players on %i.%i.%i.%i", 
													ip[0], ip[1], ip[2], ip[3] ) );
		iphoneCenterText( 512, 27, 0.75, "Attention: Multiplayer requires a WiFi connection");
		iphoneCenterText( 512, 50, 0.75, "that doesn't block UDP port 14666");
		#else
		iphoneCenterText( 240, 320-8, 0.60, va("Waiting for players on %i.%i.%i.%i", 
											   ip[0], ip[1], ip[2], ip[3] ) );
		iphoneCenterText( 240, 320-50, 0.60, "Attention: Multiplayer requires a WiFi connection");
		iphoneCenterText( 240, 320-30, 0.60, "that doesn't block UDP port 14666");		
		#endif
	}
	//	static ibutton_t btnStart;
	//	NewTextButton( &btnStart, "Start game", 512-80, 768-100, 160, 48);
}

#ifndef IPAD
static ibutton_t	optionButtons[2][6];
static ibutton_t	defaultsButton;
boolean OptionButton( int col, int row, const char *title ) {
	assert( col >= 0 && col < 2 && row >= 0 && row < 6 );
	return NewTextButton( &optionButtons[col][row], title, 10 + 235 * col, 64 + 50 * row, 225, 48 );
}
#endif

/*
 ==================
 iphoneOptionsMenu
 
 ==================
 */
void iphoneOptionsMenu() {	
	if ( BackButton() ) {
		menuState = IPM_CONTROLS;
	}

	boolean musicState = music->value;
	if ( SysIPhoneOtherAudioIsPlaying() ) {
		// music always off when ipod music is playing
		musicState = false;
	}

	if ( NewTextButton( &defaultsButton, "Defaults", 240-225/2, 2, 225, 48 ) ) {
		// reset all cvars except the reverse-landscape mode value
		float value = revLand->value;
		Cvar_Reset_f();
		Cvar_SetValue( revLand->name, value );
		HudSetForScheme(0);
		iphoneStartMusic();
	}
	
	if ( OptionButton( 0, 0, autoUse->value ? "Auto use: ON" : "Auto use: OFF" ) ) {
		Cvar_SetValue( autoUse->name, !autoUse->value );
	}
	if ( OptionButton( 0, 1, statusBar->value ? "Status bar: ON" : "Status bar: OFF" ) ) {
		Cvar_SetValue( statusBar->name, !statusBar->value );
	}
	if ( OptionButton( 0, 2, touchClick->value ? "Touch click: ON" : "Touch click: OFF" ) ) {
		Cvar_SetValue( touchClick->name, !touchClick->value );
	}
	if ( OptionButton( 0, 3, messages->value ? "Text messages: ON" : "Text messages: OFF" ) ) {
		Cvar_SetValue( messages->name, !messages->value );
	}
	if ( OptionButton( 1, 0, drawControls->value ? "Draw controls: ON" : "Draw controls: OFF" ) ) {
		Cvar_SetValue( drawControls->name, !drawControls->value );
	}
	if ( OptionButton( 1, 1, musicState ? "Music: ON" : "Music: OFF" ) ) {
		if ( !SysIPhoneOtherAudioIsPlaying() ) {
			Cvar_SetValue( music->name, !music->value );
			if ( music->value ) {
				iphoneStartMusic();
			} else {
				iphoneStopMusic();
			}
		}
	}
	if ( OptionButton( 1, 2, centerSticks->value ? "Center sticks: ON" : "Center sticks: OFF" ) ) {
		Cvar_SetValue( centerSticks->name, !centerSticks->value );
	}
	if ( OptionButton( 1, 3, rampTurn->value ? "Ramp turn: ON" : "Ramp turn: OFF" ) ) {
		Cvar_SetValue( rampTurn->name, !rampTurn->value );
	}
}	

/*
 ===================
 iphoneIntermission
 
 The end-of-level switch was just hit, note the state and awards
 for the map select menu
 ===================
 */
void iphoneIntermission( wbstartstruct_t* wb ) {
	if ( deathmatch || netgame ) {
		// no achievements in deathmatch mode
		return;
	}
	
	// find the current episode / map combination 
	
	// if a mapStat_t doesn't exist for this yet, create one
	
	// mark this level / skill combination as tried
	mapStats_t *cms = FindMapStats( playState.map.dataset, playState.map.episode, playState.map.map, true );
	if ( !cms ) {
		return;
	}
	
	int skill = playState.map.skill;
	cms->completionFlags[skill] |= MF_COMPLETED;
	
	// add the awards
	if ( wb->plyr[0].stime < wb->partime ) {
		cms->completionFlags[skill] |= MF_TIME;
	}
	
	int numkills = 0;
	int numsecrets = 0;
	int numitems = 0;
	for ( int i = 0 ; i < MAXPLAYERS ; i++ ) {
		if ( wb->plyr[i].in ) {
			numkills += wb->plyr[i].skills;
			numitems += wb->plyr[i].sitems;
			numsecrets += wb->plyr[i].ssecret;
		}
	}
	if ( numkills >= wb->maxkills ) {
		cms->completionFlags[skill] |= MF_KILLS;
	}
	if ( numitems >= wb->maxitems ) {
		cms->completionFlags[skill] |= MF_TREASURE;
	}
	if ( numsecrets >= wb->maxsecret ) {
		cms->completionFlags[skill] |= MF_SECRETS;
	}	
}

/*
 ===================
 iphoneStartLevel
 
 Do a savegame with the current state
 ===================
 */
void iphoneStartLevel() {
	if ( deathmatch || netgame ) {
		// no achievements in deathmatch mode
		
		// reset the levelTimer
		if ( levelTimer && setupPacket.timelimit > 0 ) {
			// 30 hz, minutes
			levelTimeCount = setupPacket.timelimit * 30 * 60;
		}
		
		return;
	}
	playState.map.map = gamemap;

	// automatic save game
	G_SaveGame( 0, "entersave" );
	G_DoSaveGame(true);

	// mark this level as tried
	mapStats_t *cms = FindMapStats( playState.map.dataset, playState.map.episode, playState.map.map, true );
	if ( cms ) {
		cms->completionFlags[playState.map.skill] |= MF_TRIED;
	}
}


/*
 ===================
 DrawLiveBackground
 
 Draw a randomish moving cloudy background
 ===================
 */
void DrawLiveBackground() {
	static float	bgVectors[2][2] = { { 0.01, 0.015 }, { -0.01, -0.02 } };
	float	fade[2];
	
	// slide and fade a couple textures around
	static float	tc[2][4][2];
	for ( int i = 0 ; i < 2 ; i++ ) {		
		int		ofs = iphoneFrameNum + i * 32;
		float	dist = ( ofs & 63 );
		for ( int j = 0 ; j < 2 ; j ++ ) {
			for ( int k = 0 ; k < 2 ; k++ ) {
				if ( rand()&1 ) {
					if ( bgVectors[j][k] < 0.03 ) {
						bgVectors[j][k] += 0.0001;
					}
				} else {
					if ( bgVectors[j][k] > -0.03 ) {
						bgVectors[j][k] -= 0.0001;
					}
				}
			}
		}
		fade[i] = sin( ( dist - 16 ) / 32.0 * M_PI ) * 0.5 + 0.5;
		fade[i] *= 0.7;
		
		for ( int j = 0 ; j < 2 ; j++ ) {
			tc[i][0][j] += bgVectors[i][j];
			tc[i][0][j] -= floor( tc[i][0][j] );
		}
		tc[i][1][0] = tc[i][0][0]+1;
		tc[i][1][1] = tc[i][0][1]+0;
		
		tc[i][2][0] = tc[i][0][0]+0;
		tc[i][2][1] = tc[i][0][1]+1;
		
		tc[i][3][0] = tc[i][0][0]+1;
		tc[i][3][1] = tc[i][0][1]+1;
	}
	
	
	
	// Fill rate performance is an issue just for two scrolling layers under
	// modest GUI objects.  Using a PVR2 texture and a single multitexture
	// pass helps.  If all the GUI objects were drawn with depth buffering,
	// the surface rejection would help out, but bumping depth after every
	// draw would be a bit of a chore.
	
#if 0	
	glClear( GL_DEPTH_BUFFER_BIT );
	glDepthMask( 1 );	// write the depth buffer
	glEnable( GL_DEPTH_TEST );	// depth test this background
#endif
	
	PK_BindTexture( PK_FindTexture( "iphone/livetile_1.tga" ) );
	
	glDisable( GL_BLEND );
	glDisable( GL_DEPTH_TEST );

	// multitexture setup
	glActiveTexture( GL_TEXTURE1 );
	glClientActiveTexture( GL_TEXTURE1 );
	glEnable( GL_TEXTURE_2D );
	PK_BindTexture( PK_FindTexture( "iphone/livetile_1.tga" ) );	
	glTexCoordPointer( 2, GL_FLOAT, 8, tc[1][0] );
	glEnableClientState( GL_TEXTURE_COORD_ARRAY );
	
	glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD );
//	glColor4f( fade[0], fade[0], fade[0], fade[1] );
	glBegin( GL_TRIANGLE_STRIP );
	
#ifdef IPAD
	glTexCoord2f( tc[0][0][0], tc[0][0][1] );	glVertex3f( 0, 0, 0.5 );
	glTexCoord2f( tc[0][1][0], tc[0][1][1] );	glVertex3f( 1024, 0, 0.5 );
	glTexCoord2f( tc[0][2][0], tc[0][2][1]+1 );	glVertex3f( 0, 768, 0.5 );
	glTexCoord2f( tc[0][3][0], tc[0][3][1]+1 );	glVertex3f( 1024, 768, 0.5 );
#else
	glTexCoord2f( tc[0][0][0], tc[0][0][1] );	glVertex3f( 0, 0, 0.5 );
	glTexCoord2f( tc[0][1][0], tc[0][1][1] );	glVertex3f( 480, 0, 0.5 );
	glTexCoord2f( tc[0][2][0], tc[0][2][1]+1 );	glVertex3f( 0, 320, 0.5 );
	glTexCoord2f( tc[0][3][0], tc[0][3][1]+1 );	glVertex3f( 480, 320, 0.5 );
#endif
	glEnd();
	
	// unbind the second texture
	glBindTexture( GL_TEXTURE_2D, 0 );
	glDisable( GL_TEXTURE_2D );
	glDisableClientState( GL_TEXTURE_COORD_ARRAY );
	glActiveTexture( GL_TEXTURE0 );
	glClientActiveTexture( GL_TEXTURE0 );

	glColor4f( 1, 1, 1, 1 );
	glEnable( GL_BLEND );	
#if 0	
	// Enable depth test, but not depth writes, so the tile dorting
	// minimizes the amount of time drawing the background when it
	// is mostly covered.
	glEnable( GL_DEPTH_TEST );
	glDepthMask( 0 );
#endif	
}

#define MAX_PACKET_LOG	64
int	currentPacketLog;
int	packetLogMsec[MAX_PACKET_LOG];

void iphonePacketTester() {
	glClear( GL_COLOR_BUFFER_BIT );
	
	if ( BackButton() ) {
		menuState = IPM_MAIN;
		return;
	}
	
	struct sockaddr_in sender;
	unsigned senderLen = sizeof( sender );
	byte	buffer[1024];
	while( 1 ) {
		int r = recvfrom( gameSocket, buffer, sizeof( buffer ), 0, (struct sockaddr *)&sender, &senderLen );
		if ( r == -1 ) {
			break;
		}
		packetSetup_t *sp = (packetSetup_t *)buffer;
		if ( sp->sendCount == setupPacket.sendCount ) {
			Com_Printf( "Duplicated receive: %i\n", sp->sendCount );
		} else if ( sp->sendCount < setupPacket.sendCount ) {
			Com_Printf( "Out of order receive: %i < %i\n", sp->sendCount, setupPacket.sendCount );
		} else if ( sp->sendCount > setupPacket.sendCount + 1 ) {
			Com_Printf( "Dropped %i packets before %i\n", sp->sendCount - 1 - setupPacket.sendCount, sp->sendCount );
		}
		setupPacket = *sp;
		packetLogMsec[currentPacketLog&(MAX_PACKET_LOG-1)] = SysIphoneMilliseconds();
		currentPacketLog++;
	}
	
	color4_t activeColor = { 0, 255, 0, 255 };
	for ( int i = 1 ; i < MAX_PACKET_LOG ; i++ ) {
		int	t1 = packetLogMsec[(currentPacketLog - i)&(MAX_PACKET_LOG-1)];
		int	t2 = packetLogMsec[(currentPacketLog - i - 1)&(MAX_PACKET_LOG-1)];
		int	msec = t1 - t2;
		R_Draw_Fill( 0, i * 4, msec, 2, activeColor );
	}
}
Exemplo n.º 10
0
static void pie_Draw3DShape2(iIMDShape *shape, int frame, PIELIGHT colour, PIELIGHT teamcolour, int pieFlag, int pieFlagData)
{
	iIMDPoly *pPolys;
	bool light = true;
	bool shaders = pie_GetShaderUsage();

	pie_SetAlphaTest((pieFlag & pie_PREMULTIPLIED) == 0);

	/* Set fog status */
	if (!(pieFlag & pie_FORCE_FOG) && 
		(pieFlag & pie_ADDITIVE || pieFlag & pie_TRANSLUCENT || pieFlag & pie_BUTTON || pieFlag & pie_PREMULTIPLIED))
	{
		pie_SetFogStatus(false);
	}
	else
	{
		pie_SetFogStatus(true);
	}

	/* Set tranlucency */
	if (pieFlag & pie_ADDITIVE)
	{
		pie_SetRendMode(REND_ADDITIVE);
		colour.byte.a = (UBYTE)pieFlagData;
		light = false;
	}
	else if (pieFlag & pie_TRANSLUCENT)
	{
		pie_SetRendMode(REND_ALPHA);
		colour.byte.a = (UBYTE)pieFlagData;
		light = false;
	}
	else if (pieFlag & pie_PREMULTIPLIED)
	{
		pie_SetRendMode(REND_PREMULTIPLIED);
		light = false;
	}
	else
	{
		if (pieFlag & pie_BUTTON)
		{
			pie_SetDepthBufferStatus(DEPTH_CMP_LEQ_WRT_ON);
			light = false;
			if (shaders)
			{
				pie_ActivateShader(SHADER_BUTTON, shape, teamcolour, colour);
			}
			else
			{
				pie_ActivateFallback(SHADER_BUTTON, shape, teamcolour, colour);
			}
		}
		pie_SetRendMode(REND_OPAQUE);
	}
	if (pieFlag & pie_ECM)
	{
		pie_SetRendMode(REND_ALPHA);
		light = true;
		pie_SetShaderEcmEffect(true);
	}

	if (light)
	{
		glMaterialfv(GL_FRONT, GL_AMBIENT, shape->material[LIGHT_AMBIENT]);
		glMaterialfv(GL_FRONT, GL_DIFFUSE, shape->material[LIGHT_DIFFUSE]);
		glMaterialfv(GL_FRONT, GL_SPECULAR, shape->material[LIGHT_SPECULAR]);
		glMaterialf(GL_FRONT, GL_SHININESS, shape->shininess);
		glMaterialfv(GL_FRONT, GL_EMISSION, shape->material[LIGHT_EMISSIVE]);
		if (shaders)
		{
			pie_ActivateShader(SHADER_COMPONENT, shape, teamcolour, colour);
		}
		else
		{
			pie_ActivateFallback(SHADER_COMPONENT, shape, teamcolour, colour);
		}
	}

	if (pieFlag & pie_HEIGHT_SCALED)	// construct
	{
		glScalef(1.0f, (float)pieFlagData / (float)pie_RAISE_SCALE, 1.0f);
	}
	if (pieFlag & pie_RAISE)		// collapse
	{
		glTranslatef(1.0f, (-shape->max.y * (pie_RAISE_SCALE - pieFlagData)) * (1.0f / pie_RAISE_SCALE), 1.0f);
	}

	glColor4ubv(colour.vector);     // Only need to set once for entire model
	pie_SetTexturePage(shape->texpage);

	frame %= MAX(1, shape->numFrames);

	glBegin(GL_TRIANGLES);
	for (pPolys = shape->polys; pPolys < shape->polys + shape->npolys; pPolys++)
	{
		Vector3f	vertexCoords[3];
		unsigned int	n, frameidx = frame;
		int	*index;

		if (!(pPolys->flags & iV_IMD_TEXANIM))
		{
			frameidx = 0;
		}

		for (n = 0, index = pPolys->pindex;
				n < pPolys->npnts;
				n++, index++)
		{
			vertexCoords[n].x = shape->points[*index].x;
			vertexCoords[n].y = shape->points[*index].y;
			vertexCoords[n].z = shape->points[*index].z;
		}

		polyCount++;

		glNormal3fv((GLfloat*)&pPolys->normal);
		for (n = 0; n < pPolys->npnts; n++)
		{
			GLfloat* texCoord = (GLfloat*)&pPolys->texCoord[frameidx * pPolys->npnts + n];
			glTexCoord2fv(texCoord);
			if (!shaders)
			{
				glMultiTexCoord2fv(GL_TEXTURE1, texCoord);
			}
			glVertex3fv((GLfloat*)&vertexCoords[n]);
		}
	}
	glEnd();

	if (light || (pieFlag & pie_BUTTON))
	{
		if (shaders)
		{
			pie_DeactivateShader();
		}
		else
		{
			pie_DeactivateFallback();
		}
	}
	pie_SetShaderEcmEffect(false);

	if (pieFlag & pie_BUTTON)
	{
		pie_SetDepthBufferStatus(DEPTH_CMP_ALWAYS_WRT_ON);
	}
}
void LocationEditor::RenderUnit(InstantUnit *_iu)
{
	char *typeName = Entity::GetTypeName(_iu->m_type);
	
	float landHeight = g_app->m_location->m_landscape.m_heightMap->GetValue(_iu->m_posX, _iu->m_posZ);
	glColor4f( 1.0, 1.0, 1.0, 1.0 );
    g_editorFont.DrawText3DCentre(Vector3(_iu->m_posX, landHeight + 15.0, _iu->m_posZ),
								  15.0, "%d %s(s)", _iu->m_number, typeName);


	// Render troops
	int maxX = (int)iv_sqrt(_iu->m_number);
	int maxZ = _iu->m_number / maxX;
	float pitch = 10.0;
	float offsetX = -maxX * pitch * 0.5;
	float offsetZ = -maxZ * pitch * 0.5;
	RGBAColour colour;
    if( _iu->m_teamId >= 0 ) colour = g_app->m_location->m_teams[_iu->m_teamId]->m_colour;
	colour.a = 200;
    glColor4ubv(colour.GetData());
    
    Vector3 camUp = g_app->m_camera->GetUp() * 5.0;
    Vector3 camRight = g_app->m_camera->GetRight() * 5.0;

    glDisable   (GL_CULL_FACE );
    glEnable    (GL_BLEND);
    glBlendFunc (GL_SRC_ALPHA, GL_ONE);
    glDepthMask (false);
	glBegin     (GL_QUADS);
    
    //
    // Render dots for the number and team of the unit

	for (int x = 0; x < maxX; ++x)
	{
		for (int z = 0; z < maxZ; ++z)
		{
			Vector3 pos(_iu->m_posX + offsetX + x * pitch, 0,
						_iu->m_posZ + offsetZ + z * pitch);
			pos.y = g_app->m_location->m_landscape.m_heightMap->GetValue(pos.x, pos.z) + 2.0;
			glVertex3dv( (pos - camUp - camRight).GetData() );
            glVertex3dv( (pos - camUp + camRight).GetData() );
            glVertex3dv( (pos + camUp + camRight).GetData() );
            glVertex3dv( (pos + camUp - camRight).GetData() );
		}
	}

    glEnd();


    //
    // Render our spread circle

    if( m_mode == ModeInstantUnit )
    {
        int numSteps = 30;
        float angle = 0.0;

        colour.a = 100;
        glColor4ubv(colour.GetData() );
        glLineWidth( 2.0 );
        glBegin( GL_LINE_LOOP );
        for( int i = 0; i <= numSteps; ++i )
        {
            float xDiff = _iu->m_spread * iv_sin(angle);
            float zDiff = _iu->m_spread * iv_cos(angle);
            Vector3 pos = Vector3(_iu->m_posX, 0.0, _iu->m_posZ) + Vector3(xDiff,5,zDiff);
	        pos.y = g_app->m_location->m_landscape.m_heightMap->GetValue(pos.x, pos.z) + 10.0;
            if( pos.y < 2 ) pos.y = 2;
            glVertex3dv( pos.GetData() );
            angle += 2.0 * M_PI / (float) numSteps;
        }
        glEnd();
    }
    

    glDisable   (GL_BLEND);
    glDepthMask (true);
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable    (GL_CULL_FACE );

}
Exemplo n.º 12
0
void cc2DLabel::drawMeOnly2D(CC_DRAW_CONTEXT& context)
{
	if (!m_dispIn2D)
		return;

	assert(!m_points.empty());

	//standard case: list names pushing
	bool pushName = MACRO_DrawEntityNames(context);
	if (pushName)
		glPushName(getUniqueID());

	//we should already be in orthoprojective & centered omde
	//glOrtho(-halfW,halfW,-halfH,halfH,-maxS,maxS);

	//label title
	const int precision = context.dispNumberPrecision;
	QString title = getTitle(precision);

#define DRAW_CONTENT_AS_TAB
#ifdef DRAW_CONTENT_AS_TAB
	//draw contents as an array
	Tab tab(4);
	int rowHeight = 0;
#else
//simply display the content as text
	QStringList body;
#endif

	//render zoom
	int margin        = static_cast<int>(c_margin        * context.renderZoom);
	int tabMarginX    = static_cast<int>(c_tabMarginX    * context.renderZoom);
	int tabMarginY    = static_cast<int>(c_tabMarginY    * context.renderZoom);
	int arrowBaseSize = static_cast<int>(c_arrowBaseSize * context.renderZoom);
	
	int titleHeight = 0;
	GLdouble arrowDestX = -1.0, arrowDestY = -1.0;
	QFont bodyFont,titleFont;
	if (!pushName)
	{
		/*** line from 2D point to label ***/

		//compute arrow head position
		CCVector3 arrowDest;
		m_points[0].cloud->getPoint(m_points[0].index,arrowDest);
		for (unsigned i=1; i<m_points.size(); ++i)
			arrowDest += *m_points[i].cloud->getPointPersistentPtr(m_points[i].index);
		arrowDest /= static_cast<PointCoordinateType>(m_points.size());

		//project it in 2D screen coordinates
		int VP[4];
		context._win->getViewportArray(VP);
		const double* MM = context._win->getModelViewMatd(); //viewMat
		const double* MP = context._win->getProjectionMatd(); //projMat
		GLdouble zp;
		gluProject(arrowDest.x,arrowDest.y,arrowDest.z,MM,MP,VP,&arrowDestX,&arrowDestY,&zp);

		/*** label border ***/
		bodyFont = context._win->getLabelDisplayFont(); //takes rendering zoom into account!
		titleFont = bodyFont; //takes rendering zoom into account!
		//titleFont.setBold(true);

		QFontMetrics titleFontMetrics(titleFont);
		titleHeight = titleFontMetrics.height();

		QFontMetrics bodyFontMetrics(bodyFont);
		rowHeight = bodyFontMetrics.height();

		//get label box dimension
		int dx = 100;
		int dy = 0;
		//int buttonSize    = static_cast<int>(c_buttonSize * context.renderZoom);
		{
			//base box dimension
			dx = std::max(dx,titleFontMetrics.width(title));
			dy += margin;		//top vertical margin
			dy += titleHeight;	//title

			if (m_showFullBody)
			{
#ifdef DRAW_CONTENT_AS_TAB
				try
				{
					size_t labelCount = m_points.size();
					if (labelCount == 1)
					{
						LabelInfo1 info;
						getLabelInfo1(info);

						bool isShifted = info.cloud->isShifted();
						//1st block: X, Y, Z (local)
						{
							int c = tab.add2x3Block();
							QChar suffix;
							if (isShifted)
								suffix = 'l'; //'l' for local
							const CCVector3* P = info.cloud->getPoint(info.pointIndex);
							tab.colContent[c] << QString("X") + suffix; tab.colContent[c+1] << QString::number(P->x,'f',precision);
							tab.colContent[c] << QString("Y") + suffix; tab.colContent[c+1] << QString::number(P->y,'f',precision);
							tab.colContent[c] << QString("Z") + suffix; tab.colContent[c+1] << QString::number(P->z,'f',precision);
						}
						//next block:  X, Y, Z (global)
						if (isShifted)
						{
							int c = tab.add2x3Block();
							CCVector3d P = info.cloud->toGlobal3d(*info.cloud->getPoint(info.pointIndex));
							tab.colContent[c] << "Xg"; tab.colContent[c+1] << QString::number(P.x,'f',precision);
							tab.colContent[c] << "Yg"; tab.colContent[c+1] << QString::number(P.y,'f',precision);
							tab.colContent[c] << "Zg"; tab.colContent[c+1] << QString::number(P.z,'f',precision);
						}
						//next block: normal
						if (info.hasNormal)
						{
							int c = tab.add2x3Block();
							tab.colContent[c] << "Nx"; tab.colContent[c+1] << QString::number(info.normal.x,'f',precision);
							tab.colContent[c] << "Ny"; tab.colContent[c+1] << QString::number(info.normal.y,'f',precision);
							tab.colContent[c] << "Nz"; tab.colContent[c+1] << QString::number(info.normal.z,'f',precision);
						}

						//next block: RGB color
						if (info.hasRGB)
						{
							int c = tab.add2x3Block();
							tab.colContent[c] <<"R"; tab.colContent[c+1] << QString::number(info.rgb.x);
							tab.colContent[c] <<"G"; tab.colContent[c+1] << QString::number(info.rgb.y);
							tab.colContent[c] <<"B"; tab.colContent[c+1] << QString::number(info.rgb.z);
						}
					}
					else if (labelCount == 2)
					{
						LabelInfo2 info;
						getLabelInfo2(info);

						//1st block: dX, dY, dZ
						{
							int c = tab.add2x3Block();
							tab.colContent[c] << MathSymbolDelta + QString("X"); tab.colContent[c+1] << QString::number(info.diff.x,'f',precision);
							tab.colContent[c] << MathSymbolDelta + QString("Y"); tab.colContent[c+1] << QString::number(info.diff.y,'f',precision);
							tab.colContent[c] << MathSymbolDelta + QString("Z"); tab.colContent[c+1] << QString::number(info.diff.z,'f',precision);
						}
						//2nd block: dXY, dXZ, dZY
						{
							int c = tab.add2x3Block();
							PointCoordinateType dXY = sqrt(info.diff.x*info.diff.x + info.diff.y*info.diff.y);
							PointCoordinateType dXZ = sqrt(info.diff.x*info.diff.x + info.diff.z*info.diff.z);
							PointCoordinateType dZY = sqrt(info.diff.z*info.diff.z + info.diff.y*info.diff.y);
							tab.colContent[c] << MathSymbolDelta + QString("XY"); tab.colContent[c+1] << QString::number(dXY,'f',precision);
							tab.colContent[c] << MathSymbolDelta + QString("XZ"); tab.colContent[c+1] << QString::number(dXZ,'f',precision);
							tab.colContent[c] << MathSymbolDelta + QString("ZY"); tab.colContent[c+1] << QString::number(dZY,'f',precision);
						}
					}
					else if (labelCount == 3)
					{
						LabelInfo3 info;
						getLabelInfo3(info);
						tab.setMaxBlockPerRow(2); //square tab (2x2 blocks)

						//next block: indexes
						{
							int c = tab.add2x3Block();
							tab.colContent[c] << "index.A"; tab.colContent[c+1] << QString::number(info.point1Index);
							tab.colContent[c] << "index.B"; tab.colContent[c+1] << QString::number(info.point2Index);
							tab.colContent[c] << "index.C"; tab.colContent[c+1] << QString::number(info.point3Index);
						}
						//next block: edges length
						{
							int c = tab.add2x3Block();
							tab.colContent[c] << "AB"; tab.colContent[c+1] << QString::number(info.edges.u[0],'f',precision);
							tab.colContent[c] << "BC"; tab.colContent[c+1] << QString::number(info.edges.u[1],'f',precision);
							tab.colContent[c] << "CA"; tab.colContent[c+1] << QString::number(info.edges.u[2],'f',precision);
						}
						//next block: angles
						{
							int c = tab.add2x3Block();
							tab.colContent[c] << "angle.A"; tab.colContent[c+1] << QString::number(info.angles.u[0],'f',precision);
							tab.colContent[c] << "angle.B"; tab.colContent[c+1] << QString::number(info.angles.u[1],'f',precision);
							tab.colContent[c] << "angle.C"; tab.colContent[c+1] << QString::number(info.angles.u[2],'f',precision);
						}
						//next block: normal
						{
							int c = tab.add2x3Block();
							tab.colContent[c] << "Nx"; tab.colContent[c+1] << QString::number(info.normal.x,'f',precision);
							tab.colContent[c] << "Ny"; tab.colContent[c+1] << QString::number(info.normal.y,'f',precision);
							tab.colContent[c] << "Nz"; tab.colContent[c+1] << QString::number(info.normal.z,'f',precision);
						}
					}
				}
				catch (const std::bad_alloc&)
				{
					//not enough memory
					return;
				}

				//compute min width of each column
				int totalWidth = tab.updateColumnsWidthTable(bodyFontMetrics);

				int tabWidth = totalWidth + tab.colCount * (2*tabMarginX); //add inner margins
				dx = std::max(dx,tabWidth);
				dy += tab.rowCount * (rowHeight + 2*tabMarginY); //add inner margins
				//we also add a margin every 3 rows
				dy += std::max(0,(tab.rowCount/3)-1) * margin;
				dy += margin;		//bottom vertical margin
#else
				body = getLabelContent(precision);
				if (!body.empty())
				{
					dy += margin;	//vertical margin above separator
					for (int j=0; j<body.size(); ++j)
					{
						dx = std::max(dx,bodyFontMetrics.width(body[j]));
						dy += rowHeight; //body line height
					}
					dy += margin;	//vertical margin below text
				}
#endif //DRAW_CONTENT_AS_TAB
			}

			dx += margin*2;	// horizontal margins
		}

		//main rectangle
		m_labelROI = QRect(0,0,dx,dy);

		//close button
		//m_closeButtonROI.right()   = dx-margin;
		//m_closeButtonROI.left()    = m_closeButtonROI.right()-buttonSize;
		//m_closeButtonROI.bottom()  = margin;
		//m_closeButtonROI.top()     = m_closeButtonROI.bottom()+buttonSize;

		//automatically elide the title
		//title = titleFontMetrics.elidedText(title,Qt::ElideRight,m_closeButtonROI[0]-2*margin);
	}

	int halfW = (context.glW >> 1);
	int halfH = (context.glH >> 1);

	//draw label rectangle
	int xStart = static_cast<int>(static_cast<float>(context.glW) * m_screenPos[0]);
	int yStart = static_cast<int>(static_cast<float>(context.glH) * (1.0f-m_screenPos[1]));

	m_lastScreenPos[0] = xStart;
	m_lastScreenPos[1] = yStart - m_labelROI.height();

	//colors
	bool highlighted = (!pushName && isSelected());
	//default background color
	unsigned char alpha = static_cast<unsigned char>((context.labelOpacity/100.0) * 255);
	ccColor::Rgbaub defaultBkgColor(context.labelDefaultBkgCol,alpha);
	//default border color (mustn't be totally transparent!)
	ccColor::Rgbaub defaultBorderColor(ccColor::red);
	if (!highlighted)
	{
		//apply only half of the transparency
		unsigned char halfAlpha = static_cast<unsigned char>((50.0 + context.labelOpacity/200.0) * 255);
		defaultBorderColor = ccColor::Rgbaub(context.labelDefaultBkgCol,halfAlpha);
	}

	glPushAttrib(GL_COLOR_BUFFER_BIT);
	glEnable(GL_BLEND);

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glTranslatef(static_cast<GLfloat>(-halfW+xStart),static_cast<GLfloat>(-halfH+yStart),0);

	if (!pushName)
	{
		//compute arrow base position relatively to the label rectangle (for 0 to 8)
		int arrowBaseConfig = 0;
		int iArrowDestX = static_cast<int>(arrowDestX)-xStart;
		int iArrowDestY = static_cast<int>(arrowDestY)-yStart;
		{
			if (iArrowDestX < m_labelROI.left()) //left
				arrowBaseConfig += 0;
			else if (iArrowDestX > m_labelROI.right()) //Right
				arrowBaseConfig += 2;
			else  //Middle
				arrowBaseConfig += 1;

			if (iArrowDestY > -m_labelROI.top()) //Top
				arrowBaseConfig += 0;
			else if (iArrowDestY < -m_labelROI.bottom()) //Bottom
				arrowBaseConfig += 6;
			else  //Middle
				arrowBaseConfig += 3;
		}

		//we make the arrow base start from the nearest corner
		if (arrowBaseConfig != 4) //4 = label above point!
		{
			glColor4ubv(defaultBorderColor.rgba);
			glBegin(GL_TRIANGLE_FAN);
			glVertex2d(arrowDestX-xStart,arrowDestY-yStart);
			switch(arrowBaseConfig)
			{
			case 0: //top-left corner
				glVertex2i(m_labelROI.left(), -m_labelROI.top()-2*arrowBaseSize);
				glVertex2i(m_labelROI.left(), -m_labelROI.top());
				glVertex2i(m_labelROI.left()+2*arrowBaseSize, -m_labelROI.top());
				break;
			case 1: //top-middle edge
				glVertex2i(std::max(m_labelROI.left(),iArrowDestX-arrowBaseSize), -m_labelROI.top());
				glVertex2i(std::min(m_labelROI.right(),iArrowDestX+arrowBaseSize), -m_labelROI.top());
				break;
			case 2: //top-right corner
				glVertex2i(m_labelROI.right(), -m_labelROI.top()-2*arrowBaseSize);
				glVertex2i(m_labelROI.right(), -m_labelROI.top());
				glVertex2i(m_labelROI.right()-2*arrowBaseSize, -m_labelROI.top());
				break;
			case 3: //middle-left edge
				glVertex2i(m_labelROI.left(), std::min(-m_labelROI.top(),iArrowDestY+arrowBaseSize));
				glVertex2i(m_labelROI.left(), std::max(-m_labelROI.bottom(),iArrowDestY-arrowBaseSize));
				break;
			case 4: //middle of rectangle!
				break;
			case 5: //middle-right edge
				glVertex2i(m_labelROI.right(), std::min(-m_labelROI.top(),iArrowDestY+arrowBaseSize));
				glVertex2i(m_labelROI.right(), std::max(-m_labelROI.bottom(),iArrowDestY-arrowBaseSize));
				break;
			case 6: //bottom-left corner
				glVertex2i(m_labelROI.left(), -m_labelROI.bottom()+2*arrowBaseSize);
				glVertex2i(m_labelROI.left(), -m_labelROI.bottom());
				glVertex2i(m_labelROI.left()+2*arrowBaseSize, -m_labelROI.bottom());
				break;
			case 7: //bottom-middle edge
				glVertex2i(std::max(m_labelROI.left(),iArrowDestX-arrowBaseSize), -m_labelROI.bottom());
				glVertex2i(std::min(m_labelROI.right(),iArrowDestX+arrowBaseSize), -m_labelROI.bottom());
				break;
			case 8: //bottom-right corner
				glVertex2i(m_labelROI.right(), -m_labelROI.bottom()+2*arrowBaseSize);
				glVertex2i(m_labelROI.right(), -m_labelROI.bottom());
				glVertex2i(m_labelROI.right()-2*arrowBaseSize, -m_labelROI.bottom());
				break;
			}
			glEnd();
		}
	}

	//main rectangle
	glColor4ubv(defaultBkgColor.rgba);
	glBegin(GL_QUADS);
	glVertex2i(m_labelROI.left(),  -m_labelROI.top());
	glVertex2i(m_labelROI.left(),  -m_labelROI.bottom());
	glVertex2i(m_labelROI.right(), -m_labelROI.bottom());
	glVertex2i(m_labelROI.right(), -m_labelROI.top());
	glEnd();

	//if (highlighted)
	{
		glPushAttrib(GL_LINE_BIT);
		glLineWidth(3.0f * context.renderZoom);
		glColor4ubv(defaultBorderColor.rgba);
		glBegin(GL_LINE_LOOP);
		glVertex2i(m_labelROI.left(),  -m_labelROI.top());
		glVertex2i(m_labelROI.left(),  -m_labelROI.bottom());
		glVertex2i(m_labelROI.right(), -m_labelROI.bottom());
		glVertex2i(m_labelROI.right(), -m_labelROI.top());
		glEnd();
		glPopAttrib();
	}

	//draw close button
	/*glColor3ubv(ccColor::black);
	glBegin(GL_LINE_LOOP);
	glVertex2i(m_closeButtonROI.left(),-m_closeButtonROI.top());
	glVertex2i(m_closeButtonROI.left(),-m_closeButtonROI.bottom());
	glVertex2i(m_closeButtonROI.right(),-m_closeButtonROI.bottom());
	glVertex2i(m_closeButtonROI.right(),-m_closeButtonROI.top());
	glEnd();
	glBegin(GL_LINES);
	glVertex2i(m_closeButtonROI.left()+2,-m_closeButtonROI.top()+2);
	glVertex2i(m_closeButtonROI.right()-2,-m_closeButtonROI.bottom()-2);
	glVertex2i(m_closeButtonROI.right()-2,-m_closeButtonROI.top()+2);
	glVertex2i(m_closeButtonROI.left()+2,-m_closeButtonROI.bottom()-2);
	glEnd();
	//*/

	//display text
	if (!pushName)
	{
		int xStartRel = margin;
		int yStartRel = 0;
		yStartRel -= titleHeight;

		ccColor::Rgbub defaultTextColor;
		if (context.labelOpacity < 40)
		{
			//under a given opacity level, we use the default text color instead!
			defaultTextColor = context.textDefaultCol;
		}
		else
		{
			defaultTextColor = ccColor::Rgbub(	255 - context.labelDefaultBkgCol.r,
												255 - context.labelDefaultBkgCol.g,
												255 - context.labelDefaultBkgCol.b);
		}

		//label title
		context._win->displayText(	title,
									xStart+xStartRel,
									yStart+yStartRel,
									ccGenericGLDisplay::ALIGN_DEFAULT,
									0,
									defaultTextColor.rgb,
									&titleFont);
		yStartRel -= margin;
		
		if (m_showFullBody)
		{
#ifdef DRAW_CONTENT_AS_TAB
			int xCol = xStartRel;
			for (int c=0; c<tab.colCount; ++c)
			{
				int width = tab.colWidth[c] + 2*tabMarginX;
				int height = rowHeight + 2*tabMarginY;

				int yRow = yStartRel;
				int actualRowCount = std::min(tab.rowCount,tab.colContent[c].size());

				bool labelCol = ((c & 1) == 0);
				const unsigned char* textColor = labelCol ? ccColor::white.rgba : defaultTextColor.rgb;
				
				for (int r=0; r<actualRowCount; ++r)
				{
					if (r && (r % 3) == 0)
						yRow -= margin;

					if (labelCol)
					{
						//draw background
						int rgbIndex = (r % 3);
						if (rgbIndex == 0)
							glColor3ubv(ccColor::red.rgba);
						else if (rgbIndex == 1)
							glColor3ubv(c_darkGreen.rgba);
						else if (rgbIndex == 2)
							glColor3ubv(ccColor::blue.rgba);

						glBegin(GL_QUADS);
						glVertex2i(m_labelROI.left() + xCol, -m_labelROI.top() + yRow);
						glVertex2i(m_labelROI.left() + xCol, -m_labelROI.top() + yRow - height);
						glVertex2i(m_labelROI.left() + xCol + width, -m_labelROI.top() + yRow - height);
						glVertex2i(m_labelROI.left() + xCol + width, -m_labelROI.top() + yRow);
						glEnd();
					}

					const QString& str = tab.colContent[c][r];

					int xShift = 0;
					if (labelCol)
					{
						//align characters in the middle
						xShift = (tab.colWidth[c] - QFontMetrics(bodyFont).width(str)) / 2;
					}
					else
					{
						//align digits on the right
						xShift = tab.colWidth[c] - QFontMetrics(bodyFont).width(str);
					}

					context._win->displayText(	str,
												xStart+xCol+tabMarginX+xShift,
												yStart+yRow-rowHeight,ccGenericGLDisplay::ALIGN_DEFAULT,0,textColor,&bodyFont);

					yRow -= height;
				}

				xCol += width;
			}
#else
			if (!body.empty())
			{
				//display body
				yStartRel -= margin;
				for (int i=0; i<body.size(); ++i)
				{
					yStartRel -= rowHeight;
					context._win->displayText(body[i],xStart+xStartRel,yStart+yStartRel,ccGenericGLDisplay::ALIGN_DEFAULT,0,defaultTextColor.rgb,&bodyFont);
				}
			}
#endif //DRAW_CONTENT_AS_TAB
		}
	}

	glPopAttrib();

	glPopMatrix();

	if (pushName)
		glPopName();
}
Exemplo n.º 13
0
int cQuake3BSPFile::Draw (cVector *position)
/////////////////////////////////////////////////////////////////////////////////////
{
	cBezier bezier;
	cVertex points[9];
	static cVector lastPoint = cVector (0, 500, -100);
	int vertex;
	int offset;

	cNode *node;

	ZeroMemory (m_drawn, sizeof(bool) * m_numFace);

	node = m_tree[0].GetNode (*position);
	/*if (node->cluster < 0)
	{
		*position = lastPoint;
		node = m_tree[0].GetNode (*position);
	}

	lastPoint = *position;*/

	for ( int i = 0; i < m_numFace; i++ )
	{
		int face = i;
		if (!m_drawn[face])
		{
			m_drawn[face] = true;
			if (m_face[face].type == 1)
			{
				glBegin (GL_POLYGON);
				for (int j = 0; j < m_face[face].numVertex; j++)
				{
					glColor4ubv (m_vertex[m_face[face].vertex + j].color);
					glVertex3fv (m_vertex[m_face[face].vertex + j].position);
				}
				glEnd ();
			}

			else if (m_face[face].type == 2)
			{
				for (int x = 0; x < (m_face[face].size[0] - 1) / 2; x++)
				{
					for (int y = 0; y < (m_face[face].size[1] - 1) / 2; y++)
					{
						for (int z = 0; z < 9; z++)
						{
							int pos = (y * m_face[face].size[0] * 2 + x * 2) + (z / 3 * m_face[face].size[0]) + z % 3;
							points[z] = m_vertex[pos + m_face[face].vertex];
						}

						bezier.SetControlPoints (points);
						bezier.Draw();
					}
				}
			}
			else if (m_face[face].type == 3)
			{
				glBegin (GL_TRIANGLES);
				for (int j = m_face[face].meshVert; j < m_face[face].meshVert + m_face[face].numMeshVert; j++)
				{				
					vertex = m_meshVert[j].offset + m_face[face].vertex;
					//glTexCoord2fv (m_vertex[vertex].texcoord[0]);
					glColor4ubv (m_vertex[vertex].color);
					glVertex3fv (m_vertex[vertex].position);
				}
				glEnd();

			}
		}
	}
	return node->cluster;

}
Exemplo n.º 14
0
static void drawPolygon(const float* coords, unsigned numCoords, float r, unsigned int col)
{
	if (numCoords > TEMP_COORD_COUNT) numCoords = TEMP_COORD_COUNT;

	for (unsigned i = 0, j = numCoords-1; i < numCoords; j=i++)
	{
		const float* v0 = &coords[j*2];
		const float* v1 = &coords[i*2];
		float dx = v1[0] - v0[0];
		float dy = v1[1] - v0[1];
		float d = sqrtf(dx*dx+dy*dy);
		if (d > 0)
		{
			d = 1.0f/d;
			dx *= d;
			dy *= d;
		}
		g_tempNormals[j*2+0] = dy;
		g_tempNormals[j*2+1] = -dx;
	}

	for (unsigned i = 0, j = numCoords-1; i < numCoords; j=i++)
	{
		float dlx0 = g_tempNormals[j*2+0];
		float dly0 = g_tempNormals[j*2+1];
		float dlx1 = g_tempNormals[i*2+0];
		float dly1 = g_tempNormals[i*2+1];
		float dmx = (dlx0 + dlx1) * 0.5f;
		float dmy = (dly0 + dly1) * 0.5f;
		float	dmr2 = dmx*dmx + dmy*dmy;
		if (dmr2 > 0.000001f)
		{
			float	scale = 1.0f / dmr2;
			if (scale > 10.0f) scale = 10.0f;
			dmx *= scale;
			dmy *= scale;
		}
		g_tempCoords[i*2+0] = coords[i*2+0]+dmx*r;
		g_tempCoords[i*2+1] = coords[i*2+1]+dmy*r;
	}

	unsigned int colTrans = RGBA(col&0xff, (col>>8)&0xff, (col>>16)&0xff, 0);

	glBegin(GL_TRIANGLES);

	glColor4ubv((GLubyte*)&col);

	for (unsigned i = 0, j = numCoords-1; i < numCoords; j=i++)
	{
		glVertex2fv(&coords[i*2]);
		glVertex2fv(&coords[j*2]);
		glColor4ubv((GLubyte*)&colTrans);
		glVertex2fv(&g_tempCoords[j*2]);

		glVertex2fv(&g_tempCoords[j*2]);
		glVertex2fv(&g_tempCoords[i*2]);

		glColor4ubv((GLubyte*)&col);
		glVertex2fv(&coords[i*2]);
	}

	glColor4ubv((GLubyte*)&col);
	for (unsigned i = 2; i < numCoords; ++i)
	{
		glVertex2fv(&coords[0]);
		glVertex2fv(&coords[(i-1)*2]);
		glVertex2fv(&coords[i*2]);
	}

	glEnd();
}
Exemplo n.º 15
0
void DebugDrawGL::vertex(const float x, const float y, const float z, unsigned int color)
{
	glColor4ubv((GLubyte*)&color);
	glVertex3f(x,y,z);
}
Exemplo n.º 16
0
 void  BlotScaledImageSizedEx ( ImageFile *pifDest, ImageFile *pifSrc
                                    , int32_t xd, int32_t yd
                                    , uint32_t wd, uint32_t hd
                                    , int32_t xs, int32_t ys
                                    , uint32_t ws, uint32_t hs
                                    , uint32_t nTransparent
                                    , uint32_t method, ... )
     // integer scalar... 0x10000 = 1
{
	CDATA *po, *pi;
	static uint32_t lock;
	uint32_t  oo;
	uint32_t srcwidth;
	int errx, erry;
	uint32_t dhd, dwd, dhs, dws;
	va_list colors;
	va_start( colors, method );
	//lprintf( WIDE("Blot enter (%d,%d)"), _wd, _hd );
	if( nTransparent > ALPHA_TRANSPARENT_MAX )
	{
		return;
	}
	if( !pifSrc ||  !pifDest
	   || !pifSrc->image //|| !pifDest->image
	   || !wd || !hd || !ws || !hs )
	{
		return;
	}

	if( ( xd > ( pifDest->x + pifDest->width ) )
	  || ( yd > ( pifDest->y + pifDest->height ) )
	  || ( ( xd + (signed)wd ) < pifDest->x )
		|| ( ( yd + (signed)hd ) < pifDest->y ) )
	{
		return;
	}
	dhd = hd;
	dhs = hs;
	dwd = wd;
	dws = ws;

	// ok - how to figure out how to do this
	// need to update the position and width to be within the 
	// the bounds of pifDest....
	//lprintf(" begin scaled output..." );
	errx = -(signed)dwd;
	erry = -(signed)dhd;

	if( xd < pifDest->x )
	{
		while( xd < pifDest->x )
		{
			errx += (signed)dws;
			while( errx >= 0 )
			{
	            errx -= (signed)dwd;
				ws--;
				xs++;
			}
			wd--;
			xd++;
		}
	}
	//Log8( WIDE("Blot scaled params: %d %d %d %d / %d %d %d %d "), 
	//       xs, ys, ws, hs, xd, yd, wd, hd );
	if( yd < pifDest->y )
	{
		while( yd < pifDest->y )
		{
			erry += (signed)dhs;
			while( erry >= 0 )
			{
				erry -= (signed)dhd;
				hs--;
				ys++;
			}
			hd--;
			yd++;
		}
	}
	//Log8( WIDE("Blot scaled params: %d %d %d %d / %d %d %d %d "), 
	//       xs, ys, ws, hs, xd, yd, wd, hd );
	if( ( xd + (signed)wd ) > ( pifDest->x + pifDest->width) )
	{
		//int newwd = TOFIXED(pifDest->width);
		//ws -= ((int64_t)( (int)wd - newwd)* (int64_t)ws )/(int)wd;
		wd = ( pifDest->x + pifDest->width ) - xd;
	}
	//Log8( WIDE("Blot scaled params: %d %d %d %d / %d %d %d %d "), 
	//       xs, ys, ws, hs, xd, yd, wd, hd );
	if( ( yd + (signed)hd ) > (pifDest->y + pifDest->height) )
	{
		//int newhd = TOFIXED(pifDest->height);
		//hs -= ((int64_t)( hd - newhd)* hs )/hd;
		hd = (pifDest->y + pifDest->height) - yd;
	}
	if( (int32_t)wd <= 0 ||
       (int32_t)hd <= 0 ||
       (int32_t)ws <= 0 ||
		 (int32_t)hs <= 0 )
	{
		return;
	}
   
	//Log9( WIDE("Image locations: %d(%d %d) %d(%d) %d(%d) %d(%d)")
	//          , xs, FROMFIXED(xs), FIXEDPART(xs)
	//          , ys, FROMFIXED(ys)
	//          , xd, FROMFIXED(xd)
	//          , yd, FROMFIXED(yd) );
#ifdef _INVERT_IMAGE
	// set pointer in to the starting x pixel
	// on the last line of the image to be copied 
	pi = IMG_ADDRESS( pifSrc, (xs), (ys) );
	po = IMG_ADDRESS( pifDest, (xd), (yd) );
	oo = 4*(-((signed)wd) - (pifDest->pwidth) ); // w is how much we can copy...
	// adding in multiple of 4 because it's C...
	srcwidth = -(4* pifSrc->pwidth);
#else
	// set pointer in to the starting x pixel
	// on the first line of the image to be copied...
	pi = IMG_ADDRESS( pifSrc, (xs), (ys) );
	po = IMG_ADDRESS( pifDest, (xd), (yd) );
	oo = 4*(pifDest->pwidth - (wd)); // w is how much we can copy...
	// adding in multiple of 4 because it's C...
	srcwidth = 4* pifSrc->pwidth;
#endif
	while( LockedExchange( &lock, 1 ) )
		Relinquish();
   //Log8( WIDE("Do blot work...%d(%d),%d(%d) %d(%d) %d(%d)")
   //    , ws, FROMFIXED(ws), hs, FROMFIXED(hs) 
	//    , wd, FROMFIXED(wd), hd, FROMFIXED(hd) );

	if( ( pifDest->flags & IF_FLAG_FINAL_RENDER )
		&& !( pifDest->flags & IF_FLAG_IN_MEMORY ) )
	{
		int updated = 0;
		Image topmost_parent;

		// closed loop to get the top imgae size.
		for( topmost_parent = pifSrc; topmost_parent->pParent; topmost_parent = topmost_parent->pParent );

		ReloadOpenGlTexture( pifSrc, 0 );
		if( !pifSrc->glActiveSurface )
		{
			lprintf( WIDE( "gl texture hasn't downloaded or went away?" ) );
			lock = 0;
			return;
		}
		//lprintf( WIDE( "use regular texture %p (%d,%d)" ), pifSrc, pifSrc->width, pifSrc->height );

		{
			int glDepth = 1;
			VECTOR v1[2], v3[2], v4[2], v2[2];
			int v = 0;
			double x_size, x_size2, y_size, y_size2;
			/*
			 * only a portion of the image is actually used, the rest is filled with blank space
			 *
			 */
			TranslateCoord( pifDest, &xd, &yd );
			TranslateCoord( pifSrc, &xs, &ys );

			v1[v][0] = xd;
			v1[v][1] = yd;
			v1[v][2] = 0.0;

			v2[v][0] = xd;
			v2[v][1] = yd+hd;
			v2[v][2] = 0.0;

			v3[v][0] = xd+wd;
			v3[v][1] = yd+hd;
			v3[v][2] = 0.0;

			v4[v][0] = xd+wd;
			v4[v][1] = yd;
			v4[v][2] = 0.0;

			x_size = (double) xs/ (double)topmost_parent->width;
			x_size2 = (double) (xs+ws)/ (double)topmost_parent->width;
			y_size = (double) ys/ (double)topmost_parent->height;
			y_size2 = (double) (ys+hs)/ (double)topmost_parent->height;

			while( pifDest && pifDest->pParent )
			{
				glDepth = 0;
				if( pifDest->transform )
				{
					Apply( pifDest->transform, v1[1-v], v1[v] );
					Apply( pifDest->transform, v2[1-v], v2[v] );
					Apply( pifDest->transform, v3[1-v], v3[v] );
					Apply( pifDest->transform, v4[1-v], v4[v] );
					v = 1-v;
				}
				pifDest = pifDest->pParent;
			}
			if( pifDest->transform )
			{
				Apply( pifDest->transform, v1[1-v], v1[v] );
				Apply( pifDest->transform, v2[1-v], v2[v] );
				Apply( pifDest->transform, v3[1-v], v3[v] );
				Apply( pifDest->transform, v4[1-v], v4[v] );
				v = 1-v;
			}
#if 0
			if( glDepth )
			{
				//lprintf( WIDE( "enqable depth..." ) );
				glEnable( GL_DEPTH_TEST );
			}
			else
			{
				//lprintf( WIDE( "disable depth..." ) );
				glDisable( GL_DEPTH_TEST );
			}
#endif
			glBindTexture(GL_TEXTURE_2D, pifSrc->glActiveSurface);				// Select Our Texture
			if( method == BLOT_COPY )
				glColor4ub( 255,255,255,255 );
			else if( method == BLOT_SHADED )
			{
				CDATA tmp = va_arg( colors, CDATA );
				glColor4ubv( (GLubyte*)&tmp );
			}
			else if( method == BLOT_MULTISHADE )
			{
#if !defined( __ANDROID__ )
				InitShader();
				if( glUseProgram && l.glActiveSurface->shader.multi_shader )
				{
					int err;
					CDATA r = va_arg( colors, CDATA );
					CDATA g = va_arg( colors, CDATA );
					CDATA b = va_arg( colors, CDATA );
		 			glEnable(GL_FRAGMENT_PROGRAM_ARB);
					glUseProgram( l.glActiveSurface->shader.multi_shader );
					err = glGetError();
					glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 0, (float)GetRedValue( r )/255.0f, (float)GetGreenValue( r )/255.0f, (float)GetBlueValue( r )/255.0f, (float)GetAlphaValue( r )/255.0f );
					err = glGetError();
					glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 1, (float)GetRedValue( g )/255.0f, (float)GetGreenValue( g )/255.0f, (float)GetBlueValue( g )/255.0f, (float)GetAlphaValue( g )/255.0f );
					err = glGetError();
					glProgramLocalParameter4fARB( GL_FRAGMENT_PROGRAM_ARB, 2, (float)GetRedValue( b )/255.0f, (float)GetGreenValue( b )/255.0f, (float)GetBlueValue( b )/255.0f, (float)GetAlphaValue( b )/255.0f );					
					err = glGetError();
				}
				else
#endif
				{
					Image output_image;
					CDATA r = va_arg( colors, CDATA );
					CDATA g = va_arg( colors, CDATA );
					CDATA b = va_arg( colors, CDATA );
					output_image = GetShadedImage( pifSrc, r, g, b );
					glBindTexture( GL_TEXTURE_2D, output_image->glActiveSurface );
					glColor4ub( 255,255,255,255 );
				}
			}
			else if( method == BLOT_INVERTED )
			{
#if !defined( __ANDROID__ )
				InitShader();
				if( l.glActiveSurface->shader.inverse_shader )
				{
					int err;
					//lprintf( WIDE( "HAVE SHADER %d" ), l.glActiveSurface->shader.inverse_shader );
					glEnable(GL_FRAGMENT_PROGRAM_ARB);
					glUseProgram( l.glActiveSurface->shader.inverse_shader );
					err = glGetError();
				}
				else
#endif
				{
					Image output_image;
					//lprintf( WIDE( "DID NOT HAVE SHADER" ) );
					output_image = GetInvertedImage( pifSrc );
					glBindTexture( GL_TEXTURE_2D, output_image->glActiveSurface );
					glColor4ub( 255,255,255,255 );
				}
			}

			glBegin(GL_TRIANGLE_STRIP);
			//glBegin(GL_QUADS);
			// Front Face
			//glColor4ub( 255,120,32,192 );
			scale( v1[v], v1[v], l.scale );
			scale( v2[v], v2[v], l.scale );
			scale( v3[v], v3[v], l.scale );
			scale( v4[v], v4[v], l.scale );
			glTexCoord2f(x_size, y_size); glVertex3fv(v1[v]);	// Bottom Left Of The Texture and Quad
			glTexCoord2f(x_size, y_size2); glVertex3fv(v2[v]);	// Bottom Right Of The Texture and Quad
			glTexCoord2f(x_size2, y_size); glVertex3fv(v4[v]);	// Top Left Of The Texture and Quad
			glTexCoord2f(x_size2, y_size2); glVertex3fv(v3[v]);	// Top Right Of The Texture and Quad
			// Back Face
			glEnd();
#if !defined( __ANDROID__ )
			if( method == BLOT_MULTISHADE )
			{
				if( l.glActiveSurface->shader.multi_shader )
				{
 					glDisable(GL_FRAGMENT_PROGRAM_ARB);
				}
			}
			else if( method == BLOT_INVERTED )
			{
				if( l.glActiveSurface->shader.inverse_shader )
				{
 					glDisable(GL_FRAGMENT_PROGRAM_ARB);
				}
			}
#endif
			glBindTexture(GL_TEXTURE_2D, 0);				// Select Our Texture
		}
	}

	else switch( method )
	{
	case BLOT_COPY:
		if( !nTransparent )
			cBlotScaledT0( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth );       
		else if( nTransparent == 1 )
			cBlotScaledT1( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth );       
		else if( nTransparent & ALPHA_TRANSPARENT )
			cBlotScaledTImgA( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, nTransparent&0xFF );
		else if( nTransparent & ALPHA_TRANSPARENT_INVERT )
			cBlotScaledTImgAI( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, nTransparent&0xFF );        
		else
			cBlotScaledTA( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, nTransparent );        
		break;
	case BLOT_SHADED:
		if( !nTransparent )
			cBlotScaledShadedT0( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, va_arg( colors, CDATA ) );
		else if( nTransparent == 1 )
			cBlotScaledShadedT1( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, va_arg( colors, CDATA ) );
		else if( nTransparent & ALPHA_TRANSPARENT )
			cBlotScaledShadedTImgA( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, nTransparent&0xFF, va_arg( colors, CDATA ) );
		else if( nTransparent & ALPHA_TRANSPARENT_INVERT )
			cBlotScaledShadedTImgAI( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, nTransparent&0xFF, va_arg( colors, CDATA ) );
		else
			cBlotScaledShadedTA( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth, nTransparent, va_arg( colors, CDATA ) );
		break;
	case BLOT_MULTISHADE:
		{
			CDATA r,g,b;
			r = va_arg( colors, CDATA );
			g = va_arg( colors, CDATA );
			b = va_arg( colors, CDATA );
			if( !nTransparent )
				cBlotScaledMultiT0( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth
									  , r, g, b );
			else if( nTransparent == 1 )
				cBlotScaledMultiT1( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth
									  , r, g, b );
			else if( nTransparent & ALPHA_TRANSPARENT )
				cBlotScaledMultiTImgA( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth
										  , nTransparent & 0xFF
										  , r, g, b );
			else if( nTransparent & ALPHA_TRANSPARENT_INVERT )
				cBlotScaledMultiTImgAI( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth
											, nTransparent & 0xFF
											, r, g, b );
			else
				cBlotScaledMultiTA( po, pi, errx, erry, wd, hd, dwd, dhd, dws, dhs, oo, srcwidth
									  , nTransparent
									  , r, g, b );
		}
		break;
	}
	lock = 0;
//   Log( WIDE("Blot done") );
}
Exemplo n.º 17
0
void DebugDrawGL::vertex(const float* pos, unsigned int color, const float* uv)
{
	glColor4ubv((GLubyte*)&color);
	glTexCoord2fv(uv);
	glVertex3fv(pos);
}
Exemplo n.º 18
0
/** Display radar texture using the given height and width, depending on zoom level. */
void pie_RenderRadar()
{
	pie_SetRendMode(REND_ALPHA);
	glColor4ubv(WZCOL_WHITE.vector); // hack
	radarGfx->draw();
}
void LLDrawPoolAlpha::renderAlpha(U32 mask)
{
	BOOL initialized_lighting = FALSE;
	BOOL light_enabled = TRUE;
	S32 diffuse_channel = 0;

	//BOOL is_particle = FALSE;
	BOOL use_shaders = (LLPipeline::sUnderWaterRender && gPipeline.canUseVertexShaders())
		|| gPipeline.canUseWindLightShadersOnObjects();
	
	// check to see if it's a particle and if it's "close"
	{
		if (LLPipeline::sImpostorRender)
		{
			gGL.setAlphaRejectSettings(LLRender::CF_GREATER, 0.5f);
		}
		else
		{
			gGL.setAlphaRejectSettings(LLRender::CF_DEFAULT);
		}
	}

	for (LLCullResult::sg_list_t::iterator i = gPipeline.beginAlphaGroups(); i != gPipeline.endAlphaGroups(); ++i)
	{
		LLSpatialGroup* group = *i;
		llassert(group);
		llassert(group->mSpatialPartition);

		if (group->mSpatialPartition->mRenderByGroup &&
		    !group->isDead())
		{
			bool draw_glow_for_this_partition = mVertexShaderLevel > 0 && // no shaders = no glow.
				// All particle systems seem to come off the wire with texture entries which claim that they glow.  This is probably a bug in the data.  Suppress.
				group->mSpatialPartition->mPartitionType != LLViewerRegion::PARTITION_PARTICLE &&
				group->mSpatialPartition->mPartitionType != LLViewerRegion::PARTITION_CLOUD &&
				group->mSpatialPartition->mPartitionType != LLViewerRegion::PARTITION_HUD_PARTICLE;

			LLSpatialGroup::drawmap_elem_t& draw_info = group->mDrawMap[LLRenderPass::PASS_ALPHA];

			for (LLSpatialGroup::drawmap_elem_t::iterator k = draw_info.begin(); k != draw_info.end(); ++k)	
			{
				LLDrawInfo& params = **k;

				LLRenderPass::applyModelMatrix(params);

				{
					if (params.mFullbright)
					{
						// Turn off lighting if it hasn't already been so.
						if (light_enabled || !initialized_lighting)
						{
							initialized_lighting = TRUE;
							if (use_shaders) 
							{
								target_shader = fullbright_shader;
							}
							else
							{
								gPipeline.enableLightsFullbright(LLColor4(1,1,1,1));
							}
							light_enabled = FALSE;
						}
					}
					// Turn on lighting if it isn't already.
					else if (!light_enabled || !initialized_lighting)
					{
						initialized_lighting = TRUE;
						if (use_shaders) 
						{
							target_shader = simple_shader;
						}
						else
						{
							gPipeline.enableLightsDynamic();
						}
						light_enabled = TRUE;
					}

					// If we need shaders, and we're not ALREADY using the proper shader, then bind it
					// (this way we won't rebind shaders unnecessarily).
					if(use_shaders && (current_shader != target_shader))
					{
						llassert(target_shader != NULL);
						if (deferred_render && current_shader != NULL)
						{
							gPipeline.unbindDeferredShader(*current_shader);
							diffuse_channel = 0;
						}
						current_shader = target_shader;
						if (deferred_render)
						{
							gPipeline.bindDeferredShader(*current_shader);
							diffuse_channel = current_shader->enableTexture(LLViewerShaderMgr::DIFFUSE_MAP);
						}
						else
						{
							current_shader->bind();
						}
					}
					else if (!use_shaders && current_shader != NULL)
					{
						if (deferred_render)
						{
							gPipeline.unbindDeferredShader(*current_shader);
							diffuse_channel = 0;
						}
						LLGLSLShader::bindNoShader();
						current_shader = NULL;
					}

					if (params.mGroup)
					{
						params.mGroup->rebuildMesh();
					}

					
					if (params.mTexture.notNull())
					{
						gGL.getTexUnit(diffuse_channel)->bind(params.mTexture.get());
						if(params.mTexture.notNull())
						{
							params.mTexture->addTextureStats(params.mVSize);
						}
						if (params.mTextureMatrix)
						{
							gGL.getTexUnit(0)->activate();
							glMatrixMode(GL_TEXTURE);
							glLoadMatrixf((GLfloat*) params.mTextureMatrix->mMatrix);
							gPipeline.mTextureMatrixOps++;
						}
					}
				}
				params.mVertexBuffer->setBuffer(mask);
				params.mVertexBuffer->drawRange(LLRender::TRIANGLES, params.mStart, params.mEnd, params.mCount, params.mOffset);
				gPipeline.addTrianglesDrawn(params.mCount/3);
				
				// If this alpha mesh has glow, then draw it a second time to add the destination-alpha (=glow).  Interleaving these state-changing calls could be expensive, but glow must be drawn Z-sorted with alpha.
				if (draw_glow_for_this_partition &&
				    params.mGlowColor.mV[3] > 0)
				{
					// install glow-accumulating blend mode
					gGL.blendFunc(LLRender::BF_ZERO, LLRender::BF_ONE, // don't touch color
						      LLRender::BF_ONE, LLRender::BF_ONE); // add to alpha (glow)

					// glow doesn't use vertex colors from the mesh data
					params.mVertexBuffer->setBuffer(mask & ~LLVertexBuffer::MAP_COLOR);
					glColor4ubv(params.mGlowColor.mV);

					// do the actual drawing, again
					params.mVertexBuffer->drawRange(LLRender::TRIANGLES, params.mStart, params.mEnd, params.mCount, params.mOffset);
					gPipeline.addTrianglesDrawn(params.mCount/3);

					// restore our alpha blend mode
					gGL.blendFunc(mColorSFactor, mColorDFactor, mAlphaSFactor, mAlphaDFactor);
				}
			
				if (params.mTextureMatrix && params.mTexture.notNull())
				{
					gGL.getTexUnit(0)->activate();
					glLoadIdentity();
					glMatrixMode(GL_MODELVIEW);
				}
			}
		}
	}

	if (deferred_render && current_shader != NULL)
	{
		gPipeline.unbindDeferredShader(*current_shader);
		LLVertexBuffer::unbind();	
		LLGLState::checkStates();
		LLGLState::checkTextureChannels();
		LLGLState::checkClientArrays();
	}
	
	if (!light_enabled)
	{
		gPipeline.enableLightsDynamic();
	}
}
void RocketStatusPanel::Render()
{
    //
    // Determine our rocket status

    EscapeRocket *rocket = GetMyRocket();
    if( !rocket ) return;

    Team *team = g_app->m_location->m_teams[ m_teamId ];
    if( !team ) return;

    float fuelPercent = rocket->m_fuel / 100.0f;
    int darwiniansInside = rocket->m_passengers;

    if( rocket->m_damage > m_lastDamage )
    {
        m_damageTimer = GetHighResTime();
    }
    m_lastDamage = rocket->m_damage;

    if( fuelPercent > 1.0f ) fuelPercent = 1.0f;

    double refuelRate = rocket->m_fuel - m_previousFuelLevel;
    m_previousFuelLevel = rocket->m_fuel;

    float h = m_w * 1.5f;
    glShadeModel( GL_SMOOTH );


    //
    // Background team colour

    glColor4ub( team->m_colour.r*0.2f, team->m_colour.g*0.2f, team->m_colour.b*0.2f, 200 );

    glBegin( GL_QUADS );
        glVertex2f( m_x, m_y );
        glVertex2f( m_x + m_w, m_y );
        glVertex2f( m_x + m_w, m_y + h );
        glVertex2f( m_x, m_y + h );
    glEnd();


    //
    // Refueling effect

    float fuelBase = m_y + h * 0.97f;
    float fuelFullH = h * 0.95f;
    float fuelH = fuelFullH * fuelPercent;
    int refuelAlpha = 128;

    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

    glEnable        ( GL_TEXTURE_2D );
    glBindTexture   ( GL_TEXTURE_2D, g_app->m_resource->GetTexture( "textures/laser.bmp" ) );
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
    glTexParameterf ( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );


    if( fuelPercent < 1.0f )
    {
        glColor4ub( team->m_colour.r, team->m_colour.g, team->m_colour.b, refuelAlpha );

        float texY = fuelPercent * -100 + 0.5f;
        float texH = 1.0f;

        glBegin( GL_QUADS );
            glTexCoord2f(0,texY);       glVertex2f( m_x, fuelBase );
            glTexCoord2f(1,texY);       glVertex2f( m_x + m_w, fuelBase );
            glTexCoord2f(1,texY+texH);  glVertex2f( m_x + m_w, fuelBase - fuelFullH );
            glTexCoord2f(0,texY+texH);  glVertex2f( m_x, fuelBase - fuelFullH );
        glEnd();

    }


    //
    // Fuel level

    glBindTexture   ( GL_TEXTURE_2D, g_app->m_resource->GetTexture( "textures/laser-long.bmp" ) );
    glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
    int fuelAlpha = 200;

    glBegin( GL_QUADS );
        glColor4ub( 0,0,0, fuelAlpha );
        glTexCoord2f( 0, 0.3f );       glVertex2f( m_x, fuelBase );
        glTexCoord2f( 0, 0.7f );       glVertex2f( m_x + m_w, fuelBase );
        
        glColor4ub( team->m_colour.r, team->m_colour.g, team->m_colour.b, fuelAlpha );
        glTexCoord2f( 1, 0.7f );       glVertex2f( m_x + m_w, fuelBase - fuelH );
        glTexCoord2f( 1, 0.3f );       glVertex2f( m_x, fuelBase - fuelH );
    glEnd();

    glDisable( GL_TEXTURE_2D );


    //
    // Shadow above fuel level

    glBegin( GL_QUADS );
        glColor4ub( 0,0,0, fuelAlpha*0.5f );
        glVertex2f( m_x, fuelBase - fuelH );
        glVertex2f( m_x + m_w, fuelBase - fuelH );
        glColor4ub( 0,0,0, 0 );
        glVertex2f( m_x + m_w, fuelBase - fuelH - h * 0.05f );
        glVertex2f( m_x, fuelBase - fuelH - 10 - h * 0.05f );
    glEnd();


    //
    // Rocket bitmap overlay

    glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );

    glBlendFunc     ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
    glEnable        ( GL_TEXTURE_2D );
    glBindTexture   ( GL_TEXTURE_2D, g_app->m_resource->GetTexture( "icons/rocketstatuspanel.bmp" ) );
    
    glBegin( GL_QUADS );
        glTexCoord2i(0,1);      glVertex2f( m_x, m_y );
        glTexCoord2i(1,1);      glVertex2f( m_x + m_w, m_y );
        glTexCoord2i(1,0);      glVertex2f( m_x + m_w, m_y + h );
        glTexCoord2i(0,0);      glVertex2f( m_x, m_y + h );
    glEnd();
    
    glDisable       ( GL_TEXTURE_2D );



    //
    // Damage effect

    glColor4f( 1.0f, 1.0f, 1.0f, rocket->m_damage/100.0f );

    glBlendFunc     ( GL_SRC_ALPHA, GL_ONE );
    glEnable        ( GL_TEXTURE_2D );
    glBindTexture   ( GL_TEXTURE_2D, g_app->m_resource->GetTexture( "icons/rocketcracked.bmp" ) );

    glBegin( GL_QUADS );
    glTexCoord2i(0,1);      glVertex2f( m_x, m_y );
    glTexCoord2i(1,1);      glVertex2f( m_x + m_w, m_y );
    glTexCoord2i(1,0);      glVertex2f( m_x + m_w, m_y + h );
    glTexCoord2i(0,0);      glVertex2f( m_x, m_y + h );
    glEnd();

    glDisable       ( GL_TEXTURE_2D );



    //
    // Darwinians inside
    
    glBlendFunc     ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

    if( fuelPercent >= 1.0f || darwiniansInside > 0 )
    {
        float dwX = m_x + m_w * 0.25f;
        float dwW = m_w * 0.45f;
        float dwY = m_y + h * 0.225f;
        float dwH = h * 0.55f;
        float s = h * 0.04f;
        int astronautAlpha = 255;

        glEnable        ( GL_TEXTURE_2D );
        glBindTexture   ( GL_TEXTURE_2D, g_app->m_resource->GetTexture( "sprites/darwinian.bmp" ) );

        for( int i = 99; i >= 0; i-- )
        {
            int xIndex = ( i % 10 );
            int yIndex = 9 - int( i / 10 );
            float xPos = dwX + dwW * xIndex/10;
            float yPos = dwY + dwH * yIndex/10;

            if( yIndex % 2 == 0 ) xPos += dwW/20.0f;

            RGBAColour astronautCol = team->m_colour;
            astronautCol.AddWithClamp( RGBAColour(50,50,50,255) );
            astronautCol.a = astronautAlpha;

            if( i <  darwiniansInside )     glColor4ub( team->m_colour.r, team->m_colour.g, team->m_colour.b, astronautAlpha );
            else                            glColor4ub( team->m_colour.r*0.3f, team->m_colour.g*0.3f, team->m_colour.b*0.3f, astronautAlpha*0.2f );

            Vector3 pos( xPos+s/2.0f, yPos+s/2.0f, 0 );
            pos.x += sinf(i + GetHighResTime()) * 1.0f;
            pos.y += cosf(i + i + GetHighResTime()) * 1.0f;

            Vector3 offset( -s/2.0f, -s, 0 );
            
            glBegin( GL_QUADS );
                glTexCoord2f(0,1);      glVertex2dv( (pos+offset).GetData() );      offset.RotateAroundZ(0.5f * M_PI);
                glTexCoord2f(1,1);      glVertex2dv( (pos+offset).GetData() );      offset.RotateAroundZ(0.5f * M_PI);
                glTexCoord2f(1,0);      glVertex2dv( (pos+offset).GetData() );      offset.RotateAroundZ(0.5f * M_PI);
                glTexCoord2f(0,0);      glVertex2dv( (pos+offset).GetData() );      offset.RotateAroundZ(0.5f * M_PI);
            glEnd();
        }

        glDisable( GL_TEXTURE_2D );
    }


    //
    // Engine effect

    if( rocket->m_state == EscapeRocket::StateReady ||
        rocket->m_state == EscapeRocket::StateCountdown ||
        rocket->m_state == EscapeRocket::StateFlight)
    {
        float flameX = m_x + m_w * 0.35f;
        float flameY = m_y + h * 0.8f;
        float flameW = m_w * 0.3f;
        float flameH = m_w * 0.3f;

        glBlendFunc     ( GL_SRC_ALPHA, GL_ONE );

        glEnable( GL_TEXTURE_2D );
        glBindTexture( GL_TEXTURE_2D, g_app->m_resource->GetTexture("textures/muzzleflash.bmp" ) );

        if( fmodf( GetHighResTime()*30, 1.0f ) < 0.5f ) glColor4f( 1.0f, 1.0f, 1.0f, 1.0f );
        else                                             glColor4f( 1.0f, 1.0f, 1.0f, 0.2f );

        glBegin( GL_QUADS );
            glTexCoord2i(0,0);      glVertex2f( flameX, flameY );
            glTexCoord2i(0,1);      glVertex2f( flameX+flameW, flameY );
            glTexCoord2i(1,1);      glVertex2f( flameX+flameW, flameY+flameH );
            glTexCoord2i(1,0);      glVertex2f( flameX, flameY+flameH );
        glEnd();

        glDisable( GL_TEXTURE_2D );
    }


    //
    // Captions at the bottom
    // Determine our caption

    float mainCaptionY = m_y + h * 0.6f;
    float mainCaptionH = h * 0.05f;
    float mainCaptionG = mainCaptionH * 0.1f;

    bool timeFlashEffect = (fmodf( GetHighResTime() * 2, 1.0f ) > 0.55f);

    UnicodeString caption;
    RGBAColour captionColour(255,255,255,255);

    if( GetHighResTime() - m_damageTimer < 10.0f && 
        rocket->m_state != EscapeRocket::StateExploding )
    {
        char damage[256];
        sprintf( damage, "%d%%", int(rocket->m_damage) );
        caption = LANGUAGEPHRASE("multiwinia_rr_status_c");
        caption.ReplaceStringFlag( L'T', damage );

        captionColour.Set(255,0,0,255);  
        if( timeFlashEffect ) captionColour.a *= 0.5f;
    }
    else if( rocket->m_state == EscapeRocket::StateCountdown )
    {        
        char captionC[256];
        sprintf( captionC, "%d", (int)rocket->m_countdown + 1 );
        caption = captionC;
        mainCaptionH *= 4;
    }
    else if( rocket->m_state == EscapeRocket::StateFlight )
    {
        caption = LANGUAGEPHRASE("multiwinia_rr_status_d" );
        mainCaptionH *= 1.5f;
        if( timeFlashEffect ) captionColour.a *= 0.25f;
    }
    else if( rocket->m_state == EscapeRocket::StateExploding )
    {
        caption = LANGUAGEPHRASE("multiwinia_rr_status_e" );
        if( timeFlashEffect ) captionColour.a *= 0.25f;
    }
    else if( fuelPercent >= 1.0f && darwiniansInside < 5 )
    {
        caption = LANGUAGEPHRASE("multiwinia_rr_status_b");
        if( timeFlashEffect ) captionColour.a *= 0.25f;
    } 
    else if( rocket->m_refuelRate < 0.05f && fuelPercent < 0.01f )
    {
        caption = LANGUAGEPHRASE("multiwinia_rr_status_a");        
        if( timeFlashEffect ) captionColour.a *= 0.25f;
    }
    else if( fuelPercent < 1.0f )
    {
        char captionC[256];
        sprintf( captionC, "%2.1f%%", fuelPercent * 100 );
        
        caption = LANGUAGEPHRASE("multiwinia_rr_status_f");
        caption.ReplaceStringFlag( L'T', captionC );

        captionColour.a *= 0.75f;
    }
       


    //
    // Render our caption

    if( caption.Length() )
    {
        LList<UnicodeString *> *wrapped = WordWrapText( caption, 1000, mainCaptionH, false, false );

        for( int i = 0; i < wrapped->Size(); ++i )
        {
            UnicodeString *thisString = wrapped->GetData(i);

            glColor4ub( captionColour.a, captionColour.a, captionColour.a, 0 );
            g_titleFont.SetRenderOutline(true);
            g_titleFont.DrawText2DCentre( m_x + m_w/2, mainCaptionY, mainCaptionH, *thisString );

            glColor4ubv( captionColour.GetData() );
            g_titleFont.SetRenderOutline(false);
            g_titleFont.DrawText2DCentre( m_x + m_w/2, mainCaptionY, mainCaptionH, *thisString );

            mainCaptionY += mainCaptionH;
            mainCaptionY += mainCaptionG;
        }

        wrapped->EmptyAndDelete();
        delete wrapped;
    }


    //
    // White border

    glColor4f( 1.0f, 1.0f, 1.0f, 0.2f );

    glBegin( GL_LINE_LOOP );
        glVertex2f( m_x, m_y );
        glVertex2f( m_x + m_w, m_y );
        glVertex2f( m_x + m_w, m_y + h );
        glVertex2f( m_x, m_y + h );
    glEnd();

    glShadeModel( GL_FLAT );
}
Exemplo n.º 21
0
static void ruler_info_draw_pixel(const struct bContext *C, ARegion *ar, void *arg)
{
	Scene *scene = CTX_data_scene(C);
	UnitSettings *unit = &scene->unit;
	RulerItem *ruler_item;
	RulerInfo *ruler_info = arg;
	RegionView3D *rv3d = ruler_info->ar->regiondata;
//	ARegion *ar = ruler_info->ar;
	const float cap_size = 4.0f;
	const float bg_margin = 4.0f * U.pixelsize;
	const float bg_radius = 4.0f * U.pixelsize;
	const float arc_size = 64.0f * U.pixelsize;
#define ARC_STEPS 24
	const int arc_steps = ARC_STEPS;
	int i;
	//unsigned int color_act = 0x666600;
	unsigned int color_act = 0xffffff;
	unsigned int color_base = 0x0;
	unsigned char color_back[4] = {0xff, 0xff, 0xff, 0x80};
	unsigned char color_text[3];
	unsigned char color_wire[3];

	/* anti-aliased lines for more consistent appearance */
	glEnable(GL_LINE_SMOOTH);

	BLF_enable(blf_mono_font, BLF_ROTATION);
	BLF_size(blf_mono_font, 14 * U.pixelsize, U.dpi);
	BLF_rotation(blf_mono_font, 0.0f);

	UI_GetThemeColor3ubv(TH_TEXT, color_text);
	UI_GetThemeColor3ubv(TH_WIRE, color_wire);

	for (ruler_item = ruler_info->items.first, i = 0; ruler_item; ruler_item = ruler_item->next, i++) {
		const bool is_act = (i == ruler_info->item_active);
		float dir_ruler[2];
		float co_ss[3][2];
		int j;

		/* should these be checked? - ok for now not to */
		for (j = 0; j < 3; j++) {
			ED_view3d_project_float_global(ar, ruler_item->co[j], co_ss[j], V3D_PROJ_TEST_NOP);
		}

		glEnable(GL_BLEND);

		cpack(is_act ? color_act : color_base);

		if (ruler_item->flag & RULERITEM_USE_ANGLE) {
			glBegin(GL_LINE_STRIP);
			for (j = 0; j < 3; j++) {
				glVertex2fv(co_ss[j]);
			}
			glEnd();
			cpack(0xaaaaaa);
			setlinestyle(3);
			glBegin(GL_LINE_STRIP);
			for (j = 0; j < 3; j++) {
				glVertex2fv(co_ss[j]);
			}
			glEnd();
			setlinestyle(0);

			/* arc */
			{
				float dir_tmp[3];
				float co_tmp[3];
				float arc_ss_coords[ARC_STEPS + 1][2];

				float dir_a[3];
				float dir_b[3];
				float quat[4];
				float axis[3];
				float angle;
				const float px_scale = (ED_view3d_pixel_size(rv3d, ruler_item->co[1]) *
				                        min_fff(arc_size,
				                                len_v2v2(co_ss[0], co_ss[1]) / 2.0f,
				                                len_v2v2(co_ss[2], co_ss[1]) / 2.0f));

				sub_v3_v3v3(dir_a, ruler_item->co[0], ruler_item->co[1]);
				sub_v3_v3v3(dir_b, ruler_item->co[2], ruler_item->co[1]);
				normalize_v3(dir_a);
				normalize_v3(dir_b);

				cross_v3_v3v3(axis, dir_a, dir_b);
				angle = angle_normalized_v3v3(dir_a, dir_b);

				axis_angle_to_quat(quat, axis, angle / arc_steps);

				copy_v3_v3(dir_tmp, dir_a);

				glColor3ubv(color_wire);

				for (j = 0; j <= arc_steps; j++) {
					madd_v3_v3v3fl(co_tmp, ruler_item->co[1], dir_tmp, px_scale);
					ED_view3d_project_float_global(ar, co_tmp, arc_ss_coords[j], V3D_PROJ_TEST_NOP);
					mul_qt_v3(quat, dir_tmp);
				}

				glEnableClientState(GL_VERTEX_ARRAY);
				glVertexPointer(2, GL_FLOAT, 0, arc_ss_coords);
				glDrawArrays(GL_LINE_STRIP, 0, arc_steps + 1);
				glDisableClientState(GL_VERTEX_ARRAY);
			}

			/* text */
			{
				char numstr[256];
				float numstr_size[2];
				float pos[2];
				const int prec = 2;  /* XXX, todo, make optional */

				ruler_item_as_string(ruler_item, unit, numstr, sizeof(numstr), prec);

				BLF_width_and_height(blf_mono_font, numstr, sizeof(numstr), &numstr_size[0], &numstr_size[1]);

				pos[0] = co_ss[1][0] + (cap_size * 2.0f);
				pos[1] = co_ss[1][1] - (numstr_size[1] / 2.0f);

				/* draw text (bg) */
				glColor4ubv(color_back);
				uiSetRoundBox(UI_CNR_ALL);
				uiRoundBox(pos[0] - bg_margin,                  pos[1] - bg_margin,
				           pos[0] + bg_margin + numstr_size[0], pos[1] + bg_margin + numstr_size[1],
				           bg_radius);
				/* draw text */
				glColor3ubv(color_text);
				BLF_position(blf_mono_font, pos[0], pos[1], 0.0f);
				BLF_rotation(blf_mono_font, 0.0f);
				BLF_draw(blf_mono_font, numstr, sizeof(numstr));
			}

			/* capping */
			{
				float rot_90_vec_a[2];
				float rot_90_vec_b[2];
				float cap[2];

				sub_v2_v2v2(dir_ruler, co_ss[0], co_ss[1]);
				rot_90_vec_a[0] = -dir_ruler[1];
				rot_90_vec_a[1] =  dir_ruler[0];
				normalize_v2(rot_90_vec_a);

				sub_v2_v2v2(dir_ruler, co_ss[1], co_ss[2]);
				rot_90_vec_b[0] = -dir_ruler[1];
				rot_90_vec_b[1] =  dir_ruler[0];
				normalize_v2(rot_90_vec_b);

				glEnable(GL_BLEND);

				glColor3ubv(color_wire);

				glBegin(GL_LINES);

				madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec_a, cap_size);
				glVertex2fv(cap);
				madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec_a, -cap_size);
				glVertex2fv(cap);

				madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec_b, cap_size);
				glVertex2fv(cap);
				madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec_b, -cap_size);
				glVertex2fv(cap);

				/* angle vertex */
				glVertex2f(co_ss[1][0] - cap_size, co_ss[1][1] - cap_size);
				glVertex2f(co_ss[1][0] + cap_size, co_ss[1][1] + cap_size);
				glVertex2f(co_ss[1][0] - cap_size, co_ss[1][1] + cap_size);
				glVertex2f(co_ss[1][0] + cap_size, co_ss[1][1] - cap_size);
				glEnd();

				glDisable(GL_BLEND);
			}
		}
		else {
			glBegin(GL_LINE_STRIP);
			for (j = 0; j < 3; j += 2) {
				glVertex2fv(co_ss[j]);
			}
			glEnd();
			cpack(0xaaaaaa);
			setlinestyle(3);
			glBegin(GL_LINE_STRIP);
			for (j = 0; j < 3; j += 2) {
				glVertex2fv(co_ss[j]);
			}
			glEnd();
			setlinestyle(0);

			sub_v2_v2v2(dir_ruler, co_ss[0], co_ss[2]);

			/* text */
			{
				char numstr[256];
				float numstr_size[2];
				const int prec = 6;  /* XXX, todo, make optional */
				float pos[2];

				ruler_item_as_string(ruler_item, unit, numstr, sizeof(numstr), prec);

				BLF_width_and_height(blf_mono_font, numstr, sizeof(numstr), &numstr_size[0], &numstr_size[1]);

				mid_v2_v2v2(pos, co_ss[0], co_ss[2]);

				/* center text */
				pos[0] -= numstr_size[0] / 2.0f;
				pos[1] -= numstr_size[1] / 2.0f;

				/* draw text (bg) */
				glColor4ubv(color_back);
				uiSetRoundBox(UI_CNR_ALL);
				uiRoundBox(pos[0] - bg_margin,                  pos[1] - bg_margin,
				           pos[0] + bg_margin + numstr_size[0], pos[1] + bg_margin + numstr_size[1],
				           bg_radius);
				/* draw text */
				glColor3ubv(color_text);
				BLF_position(blf_mono_font, pos[0], pos[1], 0.0f);
				BLF_draw(blf_mono_font, numstr, sizeof(numstr));
			}

			/* capping */
			{
				float rot_90_vec[2] = {-dir_ruler[1], dir_ruler[0]};
				float cap[2];

				normalize_v2(rot_90_vec);

				glEnable(GL_BLEND);
				glColor3ubv(color_wire);

				glBegin(GL_LINES);
				madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec, cap_size);
				glVertex2fv(cap);
				madd_v2_v2v2fl(cap, co_ss[0], rot_90_vec, -cap_size);
				glVertex2fv(cap);

				madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec, cap_size);
				glVertex2fv(cap);
				madd_v2_v2v2fl(cap, co_ss[2], rot_90_vec, -cap_size);
				glVertex2fv(cap);
				glEnd();

				glDisable(GL_BLEND);
			}
		}
	}

	glDisable(GL_LINE_SMOOTH);

	BLF_disable(blf_mono_font, BLF_ROTATION);

#undef ARC_STEPS

	/* draw snap */
	if ((ruler_info->snap_flag & RULER_SNAP_OK) && (ruler_info->state == RULER_STATE_DRAG)) {
		ruler_item = ruler_item_active_get(ruler_info);
		if (ruler_item) {
			/* size from drawSnapping */
			const float size = 2.5f * UI_GetThemeValuef(TH_VERTEX_SIZE);
			float co_ss[3];
			ED_view3d_project_float_global(ar, ruler_item->co[ruler_item->co_index], co_ss, V3D_PROJ_TEST_NOP);

			cpack(color_act);
			circ(co_ss[0], co_ss[1], size * U.pixelsize);
		}
	}

}
Exemplo n.º 22
0
static void draw_single_handle(const MaskLayer *mask_layer, const MaskSplinePoint *point,
                               const eMaskWhichHandle which_handle, const int draw_type,
                               const float handle_size, const float xscale, const float yscale,
                               const float point_pos[2], const float handle_pos[2])
{
	const BezTriple *bezt = &point->bezt;
	char handle_type;

	if (which_handle == MASK_WHICH_HANDLE_STICK || which_handle == MASK_WHICH_HANDLE_LEFT) {
		handle_type = bezt->h1;
	}
	else {
		handle_type = bezt->h2;
	}

	if (handle_type == HD_VECT) {
		return;
	}

	/* this could be split into its own loop */
	if (draw_type == MASK_DT_OUTLINE) {
		const unsigned char rgb_gray[4] = {0x60, 0x60, 0x60, 0xff};
		glLineWidth(3);
		glColor4ubv(rgb_gray);
		glBegin(GL_LINES);
		glVertex2fv(point_pos);
		glVertex2fv(handle_pos);
		glEnd();
	}

	switch (handle_type) {
		case HD_FREE:
			UI_ThemeColor(TH_HANDLE_FREE);
			break;
		case HD_AUTO:
			UI_ThemeColor(TH_HANDLE_AUTO);
			break;
		case HD_ALIGN:
		case HD_ALIGN_DOUBLESIDE:
			UI_ThemeColor(TH_HANDLE_ALIGN);
			break;
	}

	glLineWidth(1);
	glBegin(GL_LINES);
	glVertex2fv(point_pos);
	glVertex2fv(handle_pos);
	glEnd();

	/* draw handle points */
	if (MASKPOINT_ISSEL_HANDLE(point, which_handle)) {
		if (point == mask_layer->act_point)
			glColor3f(1.0f, 1.0f, 1.0f);
		else
			UI_ThemeColor(TH_HANDLE_VERTEX_SELECT);
	}
	else {
		UI_ThemeColor(TH_HANDLE_VERTEX);
	}

	draw_circle(handle_pos[0], handle_pos[1], handle_size, false, xscale, yscale);
}
/* PsychSetArrayColor()

   Helper routine, called from the different batch drawing functions of Screen():
*/
void PsychSetArrayColor(PsychWindowRecordType *windowRecord, int i, int mc, double* colors, unsigned char *bytecolors)
{
	GLdouble currentColor[4];
	
	if (windowRecord->defaultDrawShader) {
		// Draw shader assigned. Need to feed color values into high-precision
		// alternative channel for unclamped, high-precision color handling:
		if (mc==3) {
			i=i * 3;
			if (colors) {
				// RGB double:
				currentColor[0]=colors[i++];
				currentColor[1]=colors[i++];
				currentColor[2]=colors[i++];
				currentColor[3]=1.0;
			}
			else {
				// RGB uint8:
				currentColor[0]=((double) bytecolors[i++] / 255.0);
				currentColor[1]=((double) bytecolors[i++] / 255.0);
				currentColor[2]=((double) bytecolors[i++] / 255.0);
				currentColor[3]=1.0;
			}
		}
		else {
			i=i * 4;
			if (colors) {
				// RGBA double:
				currentColor[0]=colors[i++];
				currentColor[1]=colors[i++];
				currentColor[2]=colors[i++];
				currentColor[3]=colors[i++];
			}
			else {
				// RGBA uint8:
				currentColor[0]=((double) bytecolors[i++] / 255.0);
				currentColor[1]=((double) bytecolors[i++] / 255.0);
				currentColor[2]=((double) bytecolors[i++] / 255.0);
				currentColor[3]=((double) bytecolors[i++] / 255.0);
			}					
		}					

		HDRglColor4dv(currentColor);
	}
	else {
		// Standard fixed-function pipeline assigned: Feed into standard glColorXXX() calls:
		if (mc==3) {
			if (colors) {
				// RGB double:
				glColor3dv(&(colors[i*3]));
			}
			else {
				// RGB uint8:
				glColor3ubv(&(bytecolors[i*3]));
			}
		}
		else {
			if (colors) {
				// RGBA double:
				glColor4dv(&(colors[i*4]));
			}
			else {
				// RGBA uint8:
				glColor4ubv(&(bytecolors[i*4]));
			}					
		}
	}
	
	return;
}
Exemplo n.º 24
0
static void mask_draw_curve_type(const bContext *C, MaskSpline *spline, float (*orig_points)[2], int tot_point,
                                 const bool is_feather, const bool is_smooth, const bool is_active,
                                 const unsigned char rgb_spline[4], const char draw_type)
{
	const int draw_method = (spline->flag & MASK_SPLINE_CYCLIC) ? GL_LINE_LOOP : GL_LINE_STRIP;
	const unsigned char rgb_black[4] = {0x00, 0x00, 0x00, 0xff};
//	const unsigned char rgb_white[4] = {0xff, 0xff, 0xff, 0xff};
	unsigned char rgb_tmp[4];
	SpaceClip *sc = CTX_wm_space_clip(C);
	float (*points)[2] = orig_points;

	if (sc) {
		const bool undistort = sc->clip && (sc->user.render_flag & MCLIP_PROXY_RENDER_UNDISTORT);

		if (undistort) {
			int i;

			points = MEM_callocN(2 * tot_point * sizeof(float), "undistorthed mask curve");

			for (i = 0; i < tot_point; i++) {
				mask_point_undistort_pos(sc, points[i], orig_points[i]);
			}
		}
	}

	glEnableClientState(GL_VERTEX_ARRAY);
	glVertexPointer(2, GL_FLOAT, 0, points);

	switch (draw_type) {

		case MASK_DT_OUTLINE:
			glLineWidth(3);

			mask_color_active_tint(rgb_tmp, rgb_black, is_active);
			glColor4ubv(rgb_tmp);

			glDrawArrays(draw_method, 0, tot_point);

			glLineWidth(1);
			mask_color_active_tint(rgb_tmp, rgb_spline, is_active);
			glColor4ubv(rgb_tmp);
			glDrawArrays(draw_method, 0, tot_point);

			break;

		case MASK_DT_DASH:
		default:
			GPU_basic_shader_bind_enable(GPU_SHADER_LINE | GPU_SHADER_STIPPLE);
			GPU_basic_shader_line_stipple(3, 0xAAAA);

#ifdef USE_XOR
			glEnable(GL_COLOR_LOGIC_OP);
			glLogicOp(GL_OR);
#endif
			mask_color_active_tint(rgb_tmp, rgb_spline, is_active);
			glColor4ubv(rgb_tmp);
			glEnableClientState(GL_VERTEX_ARRAY);
			glVertexPointer(2, GL_FLOAT, 0, points);
			glDrawArrays(draw_method, 0, tot_point);

#ifdef USE_XOR
			glDisable(GL_COLOR_LOGIC_OP);
#endif
			mask_color_active_tint(rgb_tmp, rgb_black, is_active);
			glColor4ubv(rgb_tmp);
			GPU_basic_shader_line_stipple(3, 0x5555);
			glDrawArrays(draw_method, 0, tot_point);

			GPU_basic_shader_bind_disable(GPU_SHADER_LINE | GPU_SHADER_STIPPLE);
			break;


		case MASK_DT_BLACK:
		case MASK_DT_WHITE:
			if (draw_type == MASK_DT_BLACK) { rgb_tmp[0] = rgb_tmp[1] = rgb_tmp[2] = 0;   }
			else                            { rgb_tmp[0] = rgb_tmp[1] = rgb_tmp[2] = 255; }
			/* alpha values seem too low but gl draws many points that compensate for it */
			if (is_feather) { rgb_tmp[3] = 64; }
			else            { rgb_tmp[3] = 128; }

			if (is_feather) {
				rgb_tmp[0] = (unsigned char)(((short)rgb_tmp[0] + (short)rgb_spline[0]) / 2);
				rgb_tmp[1] = (unsigned char)(((short)rgb_tmp[1] + (short)rgb_spline[1]) / 2);
				rgb_tmp[2] = (unsigned char)(((short)rgb_tmp[2] + (short)rgb_spline[2]) / 2);
			}

			if (is_smooth == false && is_feather) {
				glEnable(GL_BLEND);
				glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
			}

			mask_color_active_tint(rgb_tmp, rgb_tmp, is_active);
			glColor4ubv(rgb_tmp);

			glEnableClientState(GL_VERTEX_ARRAY);
			glVertexPointer(2, GL_FLOAT, 0, points);
			glDrawArrays(draw_method, 0, tot_point);

			if (is_smooth == false && is_feather) {
				glDisable(GL_BLEND);
			}

			break;
	}

	glDisableClientState(GL_VERTEX_ARRAY);

	if (points != orig_points)
		MEM_freeN(points);
}
Exemplo n.º 25
0
/* /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// */
static void mat_livedb_draw_tree_element(bContext *C, uiBlock *block, ARegion *ar, SpaceLDB *slivedb, LiveDbTreeElement *te, int startx, int *starty, int *row_num)
{
    LiveDbTreeElement   *ten;
    float               ufac = UI_UNIT_X / 20.0f;
    int                 offsx = 0, active = 0;
    int                 CUR_UNIT_Y;

    if(TE_GET_TYPE(te->item->type) == MAT_LDB_TREE_ITEM_TYPE_CATEGORY)
        CUR_UNIT_Y = UI_UNIT_Y;
    else
        CUR_UNIT_Y = MAT_LIVEDB_UI_UNIT_Y;

    *starty -= CUR_UNIT_Y;
    ++ *row_num;

    if (*starty + 2 * CUR_UNIT_Y >= ar->v2d.cur.ymin && *starty <= ar->v2d.cur.ymax) {
        int xmax = ar->v2d.cur.xmax;
        unsigned char alpha = 128;

        /* icons can be ui buts, we don't want it to overlap with material previews */
        if(TE_GET_TYPE(te->item->type) == MAT_LDB_TREE_ITEM_TYPE_MATERIAL)
            xmax -= MAT_LIVEDB_UI_UNIT_Y;

        glEnable(GL_BLEND);

        if(*row_num % 2) {
            UI_ThemeColorShade(TH_BACK, 6);
            glRecti(0, *starty + 1, ar->v2d.cur.xmax, *starty + CUR_UNIT_Y - 1);
        }

        if (*te->flag & TE_SELECTED) {
            float           col[4];
            unsigned char   col_circle[4];

            UI_GetThemeColor3fv(TH_SELECT_HIGHLIGHT, col);
            glColor3fv(col);
            glRecti(0, *starty + 1, (int)ar->v2d.cur.xmax, *starty + CUR_UNIT_Y - 1);

            /* active circle */
            UI_GetThemeColorType4ubv(TH_ACTIVE, SPACE_VIEW3D, col_circle);
            col_circle[3] = alpha;
            glColor4ubv((GLubyte *)col_circle);

            UI_draw_roundbox_corner_set(UI_CNR_ALL);
            UI_draw_roundbox((float)startx + UI_UNIT_X - ufac,
                       (float)*starty + (TE_GET_TYPE(te->item->type) == MAT_LDB_TREE_ITEM_TYPE_CATEGORY ? 1.0f : UI_UNIT_Y * 3),
                       (float)startx + 2.0f * UI_UNIT_X - 2.0f * ufac,
                       (float)*starty + CUR_UNIT_Y - 1.0f * ufac,
                       UI_UNIT_Y / 2.0f - 1.0f * ufac);
            glEnable(GL_BLEND); /* roundbox disables it */
        }

        /* start by highlighting search matches */
        if (SEARCHING_MAT_LIVEDB(slivedb) && (*te->flag & TE_SEARCHMATCH))
        {
            char col[4];
            UI_GetThemeColorType4ubv(TH_MATCH, SPACE_MAT_LIVEDB, col);
            col[3] = alpha;
            glColor4ubv((GLubyte *)col);
            glRecti(startx, *starty + 1, ar->v2d.cur.xmax, *starty + CUR_UNIT_Y - 1);
        }

        /* open/close icon, only when sublevels */
        if (te->subtree.first || (*te->flag & TE_LAZY_CLOSED)) {
            int icon_x;
            if (TE_GET_TYPE(te->item->type) == MAT_LDB_TREE_ITEM_TYPE_CATEGORY)
                icon_x = startx;
            else
                icon_x = startx + 5 * ufac;

            if (MAT_LIVEDB_ELEM_OPEN(te, slivedb))
                UI_icon_draw((float)icon_x, (float)*starty + 2 * ufac, ICON_DISCLOSURE_TRI_DOWN);
            else
                UI_icon_draw((float)icon_x, (float)*starty + 2 * ufac, ICON_DISCLOSURE_TRI_RIGHT);
        }
        offsx += UI_UNIT_X;

        /* Element type icon */
        if(TE_GET_TYPE(te->item->type) == MAT_LDB_TREE_ITEM_TYPE_CATEGORY)
            mat_livedb_elem_draw_icon((float)startx + offsx, (float)*starty, te);
        else
            mat_livedb_elem_draw_icon((float)startx + offsx, (float)*starty + UI_UNIT_X * 3, te);

        offsx += UI_UNIT_X;

        glDisable(GL_BLEND);

        /* name */
        if (active == 1) UI_ThemeColor(TH_TEXT_HI);
        else UI_ThemeColor(TH_TEXT);

        if(TE_GET_TYPE(te->item->type) == MAT_LDB_TREE_ITEM_TYPE_CATEGORY)
            UI_fontstyle_draw_simple(UI_FSTYLE_WIDGET, startx + offsx, *starty + 5 * ufac, te->name);
        else {
            uiBut *bt;

            UI_fontstyle_draw_simple(UI_FSTYLE_WIDGET, startx + offsx, *starty + UI_UNIT_X * 3 + 5 * ufac, te->name);
            UI_fontstyle_draw_simple(UI_FSTYLE_WIDGET, startx + offsx, *starty + UI_UNIT_X * 2 + 5 * ufac, te->nick_name);
            UI_fontstyle_draw_simple(UI_FSTYLE_WIDGET, startx + offsx, *starty + UI_UNIT_X + 5 * ufac, te->copyright);

            bt = uiDefIconBut(block, UI_BTYPE_ICON_TOGGLE, 0, ICON_WORLD,
                                xmax - UI_UNIT_X - 3, *starty + 1 * ufac, UI_UNIT_X, UI_UNIT_Y,
                                NULL, 0.0, 0.0, 1.0, 0.5f, "Get item");
            UI_but_func_set(bt, get_material_cb, (void*)slivedb->server_address, (void*)te->item->mat_item.id);
            UI_but_flag_enable(bt, UI_BUT_DRAG_LOCK);
        }

        offsx += (int)(UI_UNIT_X + UI_fontstyle_string_width(UI_FSTYLE_WIDGET, te->name));

        /* Closed item, we draw the category-info icons */
        if (TE_GET_TYPE(te->item->type) == MAT_LDB_TREE_ITEM_TYPE_CATEGORY && !MAT_LIVEDB_ELEM_OPEN(te, slivedb)) {
            if (te->subtree.first) {
                int tempx = startx + offsx;

                /* divider */
                UI_ThemeColorShade(TH_BACK, -40);
                glRecti(tempx   - 10.0f * ufac,
                        *starty +  4.0f * ufac,
                        tempx   -  8.0f * ufac,
                        *starty + CUR_UNIT_Y - 4.0f * ufac);

                glEnable(GL_BLEND);
                glPixelTransferf(GL_ALPHA_SCALE, 0.5);

                mat_livedb_draw_content_count_icons(&te->subtree, xmax, &tempx, *starty);

                glPixelTransferf(GL_ALPHA_SCALE, 1.0);
                glDisable(GL_BLEND);
            }
        }
    }
    /* store coord and continue, we need coordinates for elements outside view too */
    te->xs   = (float)startx;
    te->ys   = (float)*starty;
    te->xend = startx + offsx;

    if (MAT_LIVEDB_ELEM_OPEN(te, slivedb)) {
        for (ten = te->subtree.first; ten; ten = ten->next)
            mat_livedb_draw_tree_element(C, block, ar, slivedb, ten, startx + UI_UNIT_X, starty, row_num);
    }
    else {
        for (ten = te->subtree.first; ten; ten = ten->next)
            mat_livedb_set_coord_tree_element(slivedb, te, startx, starty);
    }
} /* mat_livedb_draw_tree_element() */
Exemplo n.º 26
0
/* draws uv's in the image space */
static void draw_uvs(SpaceImage *sima, Scene *scene, Object *obedit)
{
	ToolSettings *ts;
	Mesh *me= obedit->data;
	EditMesh *em;
	EditFace *efa, *efa_act;
	MTFace *tf, *activetf = NULL;
	DerivedMesh *finaldm, *cagedm;
	char col1[4], col2[4];
	float pointsize;
	int drawfaces, interpedges, lastsel, sel;
	Image *ima= sima->image;
 	
	em= BKE_mesh_get_editmesh(me);
	activetf= EM_get_active_mtface(em, &efa_act, NULL, 0); /* will be set to NULL if hidden */

	ts= scene->toolsettings;

	drawfaces= draw_uvs_face_check(scene);
	if(ts->uv_flag & UV_SYNC_SELECTION)
		interpedges= (ts->selectmode & SCE_SELECT_VERTEX);
	else
		interpedges= (ts->uv_selectmode == UV_SELECT_VERTEX);
	
	/* draw other uvs */
	if(sima->flag & SI_DRAW_OTHER)
		draw_uvs_other(sima, scene, obedit, activetf);

	/* 1. draw shadow mesh */
	
	if(sima->flag & SI_DRAWSHADOW) {
		/* first try existing derivedmesh */
		if(!draw_uvs_dm_shadow(em->derivedFinal)) {
			/* create one if it does not exist */
			cagedm = editmesh_get_derived_cage_and_final(scene, obedit, em, &finaldm, CD_MASK_BAREMESH|CD_MASK_MTFACE);

			/* when sync selection is enabled, all faces are drawn (except for hidden)
			 * so if cage is the same as the final, theres no point in drawing this */
			if(!((ts->uv_flag & UV_SYNC_SELECTION) && (cagedm == finaldm)))
				draw_uvs_dm_shadow(finaldm);
			
			/* release derivedmesh again */
			if(cagedm != finaldm) cagedm->release(cagedm);
			finaldm->release(finaldm);
		}
	}
	
	/* 2. draw colored faces */
	
	if(sima->flag & SI_DRAW_STRETCH) {
		draw_uvs_stretch(sima, scene, em, activetf);
	}
	else if(me->drawflag & ME_DRAWFACES) {
		/* draw transparent faces */
		UI_GetThemeColor4ubv(TH_FACE, col1);
		UI_GetThemeColor4ubv(TH_FACE_SELECT, col2);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glEnable(GL_BLEND);
		
		for(efa= em->faces.first; efa; efa= efa->next) {
			tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);
			
			if(uvedit_face_visible(scene, ima, efa, tf)) {
				efa->tmp.p = tf;
				if(tf==activetf) continue; /* important the temp pointer is set above */

				if(uvedit_face_selected(scene, efa, tf))
					glColor4ubv((GLubyte *)col2);
				else
					glColor4ubv((GLubyte *)col1);
					
				glBegin(efa->v4?GL_QUADS:GL_TRIANGLES);
					glVertex2fv(tf->uv[0]);
					glVertex2fv(tf->uv[1]);
					glVertex2fv(tf->uv[2]);
					if(efa->v4) glVertex2fv(tf->uv[3]);
				glEnd();
			}
			else {
				if(tf == activetf)
					activetf= NULL;
				efa->tmp.p = NULL;
			}
		}
		glDisable(GL_BLEND);
	}
	else {
		/* would be nice to do this within a draw loop but most below are optional, so it would involve too many checks */
		for(efa= em->faces.first; efa; efa= efa->next) {
			tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE);

			if(uvedit_face_visible(scene, ima, efa, tf)) {		
				efa->tmp.p = tf;
			}
			else {
				if(tf == activetf)
					activetf= NULL;
				efa->tmp.p = NULL;
			}
		}
		
	}
	
	/* 3. draw active face stippled */

	if(activetf) {
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		UI_ThemeColor4(TH_EDITMESH_ACTIVE);

		glEnable(GL_POLYGON_STIPPLE);
		glPolygonStipple(stipple_quarttone);

		glBegin(efa_act->v4? GL_QUADS: GL_TRIANGLES);
			glVertex2fv(activetf->uv[0]);
			glVertex2fv(activetf->uv[1]);
			glVertex2fv(activetf->uv[2]);
			if(efa_act->v4) glVertex2fv(activetf->uv[3]);
		glEnd();

		glDisable(GL_POLYGON_STIPPLE);
		glDisable(GL_BLEND);
	}
	
	/* 4. draw edges */

	if(sima->flag & SI_SMOOTH_UV) {
		glEnable(GL_LINE_SMOOTH);
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}
	
	switch(sima->dt_uv) {
		case SI_UVDT_DASH:
			for(efa= em->faces.first; efa; efa= efa->next) {
				tf= (MTFace *)efa->tmp.p; /* visible faces cached */

				if(tf) {
					cpack(0x111111);

					glBegin(GL_LINE_LOOP);
						glVertex2fv(tf->uv[0]);
						glVertex2fv(tf->uv[1]);
						glVertex2fv(tf->uv[2]);
						if(efa->v4) glVertex2fv(tf->uv[3]);
					glEnd();
				
					setlinestyle(2);
					cpack(0x909090);

					glBegin(GL_LINE_STRIP);
						glVertex2fv(tf->uv[0]);
						glVertex2fv(tf->uv[1]);
					glEnd();
		
					glBegin(GL_LINE_STRIP);
						glVertex2fv(tf->uv[0]);
						if(efa->v4) glVertex2fv(tf->uv[3]);
						else glVertex2fv(tf->uv[2]);
					glEnd();
		
					glBegin(GL_LINE_STRIP);
						glVertex2fv(tf->uv[1]);
						glVertex2fv(tf->uv[2]);
						if(efa->v4) glVertex2fv(tf->uv[3]);
					glEnd();

					setlinestyle(0);
				}
			}
			break;
		case SI_UVDT_BLACK: /* black/white */
		case SI_UVDT_WHITE: 
			if(sima->dt_uv==SI_UVDT_WHITE) glColor3f(1.0f, 1.0f, 1.0f);
			else glColor3f(0.0f, 0.0f, 0.0f);

			for(efa= em->faces.first; efa; efa= efa->next) {
				tf= (MTFace *)efa->tmp.p; /* visible faces cached */

				if(tf) {
					glBegin(GL_LINE_LOOP);
						glVertex2fv(tf->uv[0]);
						glVertex2fv(tf->uv[1]);
						glVertex2fv(tf->uv[2]);
						if(efa->v4) glVertex2fv(tf->uv[3]);
					glEnd();
				}
			}
			break;
		case SI_UVDT_OUTLINE:
			glLineWidth(3);
			cpack(0x0);
			
			for(efa= em->faces.first; efa; efa= efa->next) {
				tf= (MTFace *)efa->tmp.p; /* visible faces cached */

				if(tf) {
					glBegin(GL_LINE_LOOP);
						glVertex2fv(tf->uv[0]);
						glVertex2fv(tf->uv[1]);
						glVertex2fv(tf->uv[2]);
						if(efa->v4) glVertex2fv(tf->uv[3]);
					glEnd();
				}
			}
			
			glLineWidth(1);
			col2[0] = col2[1] = col2[2] = 192; col2[3] = 255;
			glColor4ubv((unsigned char *)col2); 
			
			if(me->drawflag & ME_DRAWEDGES) {
				UI_GetThemeColor4ubv(TH_VERTEX_SELECT, col1);
				lastsel = sel = 0;

				if(interpedges) {
					glShadeModel(GL_SMOOTH);

					for(efa= em->faces.first; efa; efa= efa->next) {
						tf= (MTFace *)efa->tmp.p; /* visible faces cached */

						if(tf) {
							glBegin(GL_LINE_LOOP);
							sel = (uvedit_uv_selected(scene, efa, tf, 0)? 1 : 0);
							if(sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
							glVertex2fv(tf->uv[0]);
							
							sel = uvedit_uv_selected(scene, efa, tf, 1)? 1 : 0;
							if(sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
							glVertex2fv(tf->uv[1]);
							
							sel = uvedit_uv_selected(scene, efa, tf, 2)? 1 : 0;
							if(sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
							glVertex2fv(tf->uv[2]);
							
							if(efa->v4) {
								sel = uvedit_uv_selected(scene, efa, tf, 3)? 1 : 0;
								if(sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
								glVertex2fv(tf->uv[3]);
							}
							
							glEnd();
						}
					}

					glShadeModel(GL_FLAT);
				}
				else {
					for(efa= em->faces.first; efa; efa= efa->next) {
						tf= (MTFace *)efa->tmp.p; /* visible faces cached */

						if(tf) {
							glBegin(GL_LINES);
							sel = (uvedit_edge_selected(scene, efa, tf, 0)? 1 : 0);
							if(sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
							glVertex2fv(tf->uv[0]);
							glVertex2fv(tf->uv[1]);
							
							sel = uvedit_edge_selected(scene, efa, tf, 1)? 1 : 0;
							if(sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
							glVertex2fv(tf->uv[1]);
							glVertex2fv(tf->uv[2]);
							
							sel = uvedit_edge_selected(scene, efa, tf, 2)? 1 : 0;
							if(sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
							glVertex2fv(tf->uv[2]);
							
							if(efa->v4) {
								glVertex2fv(tf->uv[3]);

								sel = uvedit_edge_selected(scene, efa, tf, 3)? 1 : 0;
								if(sel != lastsel) { glColor4ubv(sel ? (GLubyte *)col1 : (GLubyte *)col2); lastsel = sel; }
								glVertex2fv(tf->uv[3]);
							}

							glVertex2fv(tf->uv[0]);
							
							glEnd();
						}
					}
				}
			}
			else {
				/* no nice edges */
				for(efa= em->faces.first; efa; efa= efa->next) {
					tf= (MTFace *)efa->tmp.p; /* visible faces cached */

					if(tf) {
						glBegin(GL_LINE_LOOP);
							glVertex2fv(tf->uv[0]);
							glVertex2fv(tf->uv[1]);
							glVertex2fv(tf->uv[2]);
							if(efa->v4) glVertex2fv(tf->uv[3]);
						glEnd();
					}
				}
			}
			
			break;
	}

	if(sima->flag & SI_SMOOTH_UV) {
		glDisable(GL_LINE_SMOOTH);
		glDisable(GL_BLEND);
	}

	/* 5. draw face centers */

	if(drawfaces) {
		float cent[2];
		
		pointsize = UI_GetThemeValuef(TH_FACEDOT_SIZE);
		glPointSize(pointsize); // TODO - drawobject.c changes this value after - Investigate!
		
	    /* unselected faces */
		UI_ThemeColor(TH_WIRE);

		bglBegin(GL_POINTS);
		for(efa= em->faces.first; efa; efa= efa->next) {
			tf= (MTFace *)efa->tmp.p; /* visible faces cached */

			if(tf && !uvedit_face_selected(scene, efa, tf)) {
				uv_center(tf->uv, cent, efa->v4 != NULL);
				bglVertex2fv(cent);
			}
		}
		bglEnd();

		/* selected faces */
		UI_ThemeColor(TH_FACE_DOT);

		bglBegin(GL_POINTS);
		for(efa= em->faces.first; efa; efa= efa->next) {
			tf= (MTFace *)efa->tmp.p; /* visible faces cached */

			if(tf && uvedit_face_selected(scene, efa, tf)) {
				uv_center(tf->uv, cent, efa->v4 != NULL);
				bglVertex2fv(cent);
			}
		}
		bglEnd();
	}

	/* 6. draw uv vertices */
	
	if(drawfaces != 2) { /* 2 means Mesh Face Mode */
	    /* unselected uvs */
		UI_ThemeColor(TH_VERTEX);
		pointsize = UI_GetThemeValuef(TH_VERTEX_SIZE);
		glPointSize(pointsize);
	
		bglBegin(GL_POINTS);
		for(efa= em->faces.first; efa; efa= efa->next) {
			tf= (MTFace *)efa->tmp.p; /* visible faces cached */

			if(tf) {
				if(!uvedit_uv_selected(scene, efa, tf, 0))
					bglVertex2fv(tf->uv[0]);
				if(!uvedit_uv_selected(scene, efa, tf, 1))
					bglVertex2fv(tf->uv[1]);
				if(!uvedit_uv_selected(scene, efa, tf, 2))
					bglVertex2fv(tf->uv[2]);
				if(efa->v4 && !uvedit_uv_selected(scene, efa, tf, 3))
					bglVertex2fv(tf->uv[3]);
			}
		}
		bglEnd();
	
		/* pinned uvs */
		/* give odd pointsizes odd pin pointsizes */
	    glPointSize(pointsize*2 + (((int)pointsize % 2)? (-1): 0));
		cpack(0xFF);
	
		bglBegin(GL_POINTS);
		for(efa= em->faces.first; efa; efa= efa->next) {
			tf= (MTFace *)efa->tmp.p; /* visible faces cached */

			if(tf) {
				if(tf->unwrap & TF_PIN1)
					bglVertex2fv(tf->uv[0]);
				if(tf->unwrap & TF_PIN2)
					bglVertex2fv(tf->uv[1]);
				if(tf->unwrap & TF_PIN3)
					bglVertex2fv(tf->uv[2]);
				if(efa->v4 && (tf->unwrap & TF_PIN4))
					bglVertex2fv(tf->uv[3]);
			}
		}
		bglEnd();
	
		/* selected uvs */
		UI_ThemeColor(TH_VERTEX_SELECT);
	    glPointSize(pointsize);
	
		bglBegin(GL_POINTS);
		for(efa= em->faces.first; efa; efa= efa->next) {
			tf= (MTFace *)efa->tmp.p; /* visible faces cached */

			if(tf) {
				if(uvedit_uv_selected(scene, efa, tf, 0))
					bglVertex2fv(tf->uv[0]);
				if(uvedit_uv_selected(scene, efa, tf, 1))
					bglVertex2fv(tf->uv[1]);
				if(uvedit_uv_selected(scene, efa, tf, 2))
					bglVertex2fv(tf->uv[2]);
				if(efa->v4 && uvedit_uv_selected(scene, efa, tf, 3))
					bglVertex2fv(tf->uv[3]);
			}
		}
		bglEnd();	
	}

	glPointSize(1.0);
	BKE_mesh_end_editmesh(obedit->data, em);
}
Exemplo n.º 27
0
// Main
int main() 
{
    GLFWvidmode mode;   // GLFW video mode
    TwBar *bar;         // Pointer to a tweak bar
    
    double time = 0, dt;// Current time and enlapsed time
    double turn = 0;    // Model turn counter
    double speed = 0.3; // Model rotation speed
    int wire = 0;       // Draw model in wireframe?
    float bgColor[] = { 0.1f, 0.2f, 0.4f };         // Background color 
    unsigned char cubeColor[] = { 255, 0, 0, 128 }; // Model color (32bits RGBA)

    // Intialize GLFW   
    if( !glfwInit() )
    {
        // An error occured
        fprintf(stderr, "GLFW initialization failed\n");
        return 1;
    }

    // Create a window
    glfwGetDesktopMode(&mode);
    if( !glfwOpenWindow(640, 480, mode.RedBits, mode.GreenBits, mode.BlueBits, 
                        0, 16, 0, GLFW_WINDOW /* or GLFW_FULLSCREEN */) )
    {
        // A fatal error occured    
        fprintf(stderr, "Cannot open GLFW window\n");
        glfwTerminate();
        return 1;
    }
    glfwEnable(GLFW_MOUSE_CURSOR);
    glfwEnable(GLFW_KEY_REPEAT);
    glfwSetWindowTitle("AntTweakBar simple example using GLFW");

    // Initialize AntTweakBar
    TwInit(TW_OPENGL, NULL);

    // Create a tweak bar
    bar = TwNewBar("TweakBar");
    TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with GLFW and OpenGL.' "); // Message added to the help bar.

    // Add 'speed' to 'bar': it is a modifable (RW) variable of type TW_TYPE_DOUBLE. Its key shortcuts are [s] and [S].
    TwAddVarRW(bar, "speed", TW_TYPE_DOUBLE, &speed, 
               " label='Rot speed' min=0 max=2 step=0.01 keyIncr=s keyDecr=S help='Rotation speed (turns/second)' ");

    // Add 'wire' to 'bar': it is a modifable variable of type TW_TYPE_BOOL32 (32 bits boolean). Its key shortcut is [w].
    TwAddVarRW(bar, "wire", TW_TYPE_BOOL32, &wire, 
               " label='Wireframe mode' key=w help='Toggle wireframe display mode.' ");

    // Add 'time' to 'bar': it is a read-only (RO) variable of type TW_TYPE_DOUBLE, with 1 precision digit
    TwAddVarRO(bar, "time", TW_TYPE_DOUBLE, &time, " label='Time' precision=1 help='Time (in seconds).' ");         

    // Add 'bgColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR3F (3 floats color)
    TwAddVarRW(bar, "bgColor", TW_TYPE_COLOR3F, &bgColor, " label='Background color' ");

    // Add 'cubeColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR32 (32 bits color) with alpha
    TwAddVarRW(bar, "cubeColor", TW_TYPE_COLOR32, &cubeColor, 
               " label='Cube color' alpha help='Color and transparency of the cube.' ");

    // Set GLFW event callbacks
    // - Redirect window size changes to the callback function WindowSizeCB
    glfwSetWindowSizeCallback(WindowSizeCB);
    // - Directly redirect GLFW mouse button events to AntTweakBar
    glfwSetMouseButtonCallback((GLFWmousebuttonfun)TwEventMouseButtonGLFW);
    // - Directly redirect GLFW mouse position events to AntTweakBar
    glfwSetMousePosCallback((GLFWmouseposfun)TwEventMousePosGLFW);
    // - Directly redirect GLFW mouse wheel events to AntTweakBar
    glfwSetMouseWheelCallback((GLFWmousewheelfun)TwEventMouseWheelGLFW);
    // - Directly redirect GLFW key events to AntTweakBar
    glfwSetKeyCallback((GLFWkeyfun)TwEventKeyGLFW);
    // - Directly redirect GLFW char events to AntTweakBar
    glfwSetCharCallback((GLFWcharfun)TwEventCharGLFW);


    // Initialize time
    time = glfwGetTime();

    // Main loop (repeated while window is not closed and [ESC] is not pressed)
    while( glfwGetWindowParam(GLFW_OPENED) && !glfwGetKey(GLFW_KEY_ESC) )
    {
        // Clear frame buffer using bgColor
        glClearColor(bgColor[0], bgColor[1], bgColor[2], 1);
        glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT );

        // Rotate model
        dt = glfwGetTime() - time;
        if( dt < 0 ) dt = 0;
        time += dt;
        turn += speed*dt;
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glRotated(360.0*turn, 0.4, 1, 0.2);
        glTranslated(-0.5, -0.5, -0.5);     
    
        // Set color and draw model
        glColor4ubv(cubeColor);
        DrawModel(wire);
        
        // Draw tweak bars
        TwDraw();

        // Present frame buffer
        glfwSwapBuffers();
    }

    // Terminate AntTweakBar and GLFW
    TwTerminate();
    glfwTerminate();

    return 0;
}
Exemplo n.º 28
0
		void OpenGL_DebugFont::SetDrawColor(Gwen::Color color)
		{
			glColor4ubv( (GLubyte*)&color );
			m_Color = color;
		}
Exemplo n.º 29
0
static inline gboolean handler_src_dst_ip_render_3d_node(gpointer node_in, gpointer null, gpointer data)
{
	tree_node_t *node = node_in;

	// only draw the node if it is between the thresholds
	if (!viz->handler.check_visibility(node)) {
		return FALSE;
	}

	// precalculate these to avoid redundant calculations
	GLfloat src_y_width = node->src_dst_ip.src_coords.y_coord + node->src_dst_ip.src_coords.x_width;
	GLfloat src_z_width = node->src_dst_ip.src_coords.z_coord + node->src_dst_ip.src_coords.y_width;
	GLfloat dst_y_width = node->src_dst_ip.dst_coords.y_coord + node->src_dst_ip.dst_coords.x_width;
	GLfloat dst_z_width = node->src_dst_ip.dst_coords.z_coord + node->src_dst_ip.dst_coords.y_width;

	// define our array of quadrilaterals
	GLfloat quads_v[] =     {
					// node on left side of cube cube
					-1.0 + Z_HEIGHT_ADJ, node->src_dst_ip.src_coords.y_coord, node->src_dst_ip.src_coords.z_coord,
					-1.0 + Z_HEIGHT_ADJ, src_y_width, node->src_dst_ip.src_coords.z_coord,
					-1.0 + Z_HEIGHT_ADJ, src_y_width, src_z_width,
					-1.0 + Z_HEIGHT_ADJ, node->src_dst_ip.src_coords.y_coord, src_z_width,

					// node on right side of cube cube
					1.0 - Z_HEIGHT_ADJ, node->src_dst_ip.dst_coords.y_coord, node->src_dst_ip.dst_coords.z_coord,
					1.0 - Z_HEIGHT_ADJ, dst_y_width, node->src_dst_ip.dst_coords.z_coord,
					1.0 - Z_HEIGHT_ADJ, dst_y_width, dst_z_width,
					1.0 - Z_HEIGHT_ADJ, node->src_dst_ip.dst_coords.y_coord, dst_z_width
				};

	// set color and alpha transparency
	if (!viz->transparent) {
		node->src_dst_ip.src_coords.color[3] = 255;
		node->src_dst_ip.dst_coords.color[3] = 255;
	}

	// render our source node on the left side of the cube
	glColor4ubv(node->src_dst_ip.src_coords.color);
	glNormalPointer(GL_FLOAT, 0, viz->quads_normal_3d + 12);
	glVertexPointer(3, GL_FLOAT, 0, quads_v);
	glDrawArrays(GL_QUADS, 0, 4);

	// render our dst node on the right side of the cube
	glColor4ubv(node->src_dst_ip.dst_coords.color);
	glNormalPointer(GL_FLOAT, 0, viz->quads_normal_3d + 24);
	glVertexPointer(3, GL_FLOAT, 0, quads_v + 12);
	glDrawArrays(GL_QUADS, 0, 4);

	// draw our line connecting the src to dst
	glDisable(GL_LIGHTING);
	glLineWidth((node->volume * gtk_range_get_value(GTK_RANGE(viz->line_scale_range)) + .01) / 5000.0);
	glBegin(GL_LINES);
		glColor3ubv(node->src_dst_ip.src_coords.color);
		glVertex3f(-1.0 + Z_HEIGHT_ADJ, node->src_dst_ip.src_coords.y_coord + (node->src_dst_ip.src_coords.x_width / 2), node->src_dst_ip.src_coords.z_coord + (node->src_dst_ip.src_coords.y_width / 2));
		glVertex3f(1.0 - Z_HEIGHT_ADJ, node->src_dst_ip.dst_coords.y_coord + (node->src_dst_ip.dst_coords.x_width / 2), node->src_dst_ip.dst_coords.z_coord + (node->src_dst_ip.dst_coords.y_width / 2));
	glEnd();
	if (!viz->disable_lighting) {
		glEnable(GL_LIGHTING);
	}

	// draw labels if necessary
	if (viz->draw_labels) {
		glDisable(GL_LIGHTING);

		gchar *src_node_label = g_strdup_printf("%s/%d", inet_ntoa(node->src_dst_ip.src_addr), node->src_dst_ip.src_network_bits);
		gchar *dst_node_label = g_strdup_printf("%s/%d", inet_ntoa(node->src_dst_ip.dst_addr), node->src_dst_ip.dst_network_bits);

		// output the source nodes label
		glColor3ubv(node->src_dst_ip.src_coords.color);
		glRasterPos3f(-1.0 + (Z_HEIGHT_ADJ * 10), node->src_dst_ip.src_coords.y_coord + (node->src_dst_ip.src_coords.x_width / 2), node->src_dst_ip.src_coords.z_coord + (node->src_dst_ip.src_coords.y_width / 2) + Z_LABEL_ADJ);
		glListBase(viz->font_list_3d);
		glCallLists(strlen(src_node_label), GL_UNSIGNED_BYTE, src_node_label);

		// output the dst nodes label
		glColor3ubv(node->src_dst_ip.dst_coords.color);
		glRasterPos3f(1.0 - (Z_HEIGHT_ADJ * 10), node->src_dst_ip.dst_coords.y_coord + (node->src_dst_ip.dst_coords.x_width / 2), node->src_dst_ip.dst_coords.z_coord + (node->src_dst_ip.dst_coords.y_width / 2) + Z_LABEL_ADJ);
		glListBase(viz->font_list_3d);
		glCallLists(strlen(dst_node_label), GL_UNSIGNED_BYTE, dst_node_label);

		g_free(src_node_label);
		g_free(dst_node_label);

		if (!viz->disable_lighting) {
			glEnable(GL_LIGHTING);
		}
	}

	return FALSE;
}
Exemplo n.º 30
0
void LLHUDEffectBeam::render()
{
	if (!mSourceObject)
	{
		markDead();
		return;
	}
	if (mSourceObject->isDead())
	{
		markDead();
		return;
	}

	F32 time = mTimer.getElapsedTimeF32();

	// Kill us if our time is over...
	if (mKillTime < time)
	{
		markDead();
		return;
	}

	LLGLSPipelineAlpha gls_pipeline_alpha;
	LLImageGL::unbindTexture(0, GL_TEXTURE_2D);


	// Interpolate the global fade alpha
	mFadeInterp.update(time);

	if (mTargetObject.notNull() && mTargetObject->mDrawable.notNull())
	{
		// use viewer object position on freshly created objects
		if (mTargetObject->mDrawable->getGeneration() == -1)
		{
			mTargetPos = mTargetObject->getPositionGlobal();
		}
		// otherwise use drawable
		else
		{
			mTargetPos = gAgent.getPosGlobalFromAgent(mTargetObject->mDrawable->getPositionAgent());
		}
	}


	// Init the color of the particles
	LLColor4U coloru = mColor;

	// Draw the particles
	S32 i;
	for (i = 0; i < NUM_POINTS; i++)
	{
		mInterp[i].update(time);
		if (!mInterp[i].isActive())
		{
			continue;
		}
		mInterpFade[i].update(time);

		if (mInterp[i].isDone())
		{
			// Reinitialize the particle when the particle has finished its animation.
			setupParticle(i);
		}

		F32 frac = mInterp[i].getCurFrac();
		F32 scale = 0.025f + fabs(0.05f*sin(2.f*F_PI*(frac - time)));
		scale *= mInterpFade[i].getCurVal();

		LLVector3 pos_agent = gAgent.getPosAgentFromGlobal(mInterp[i].getCurVal());

		F32 alpha = mFadeInterp.getCurVal()*mColor.mV[3];
		alpha *= mInterpFade[i].getCurVal();
		coloru.mV[3] = (U8)alpha;
		glColor4ubv(coloru.mV);

		glPushMatrix();
		glTranslatef(pos_agent.mV[0], pos_agent.mV[1], pos_agent.mV[2]);
		glScalef(scale, scale, scale);
		gSphere.render(0);
		glPopMatrix();
	}
}