Exemplo n.º 1
0
void Route::DrawGL( ViewPort &VP )
{
#ifdef ocpnUSE_GL
    if( m_nPoints < 1 || !m_bVisible ) return;

    //  Hiliting first
    //  Being special case to draw something for a 1 point route....
    ocpnDC dc;
    if(m_hiliteWidth) {
        wxColour y = GetGlobalColor( _T ( "YELO1" ) );
        wxColour hilt( y.Red(), y.Green(), y.Blue(), 128 );

        wxPen HiPen( hilt, m_hiliteWidth, wxPENSTYLE_SOLID );

        ocpnDC dc;
        dc.SetPen( HiPen );

        wxRoutePointListNode *node = pRoutePointList->GetFirst();
        RoutePoint *prp0 = node->GetData();
        wxPoint r0;

        bool r0valid = cc1->GetCanvasPointPix( prp0->m_lat, prp0->m_lon, &r0);

        int lines = 0;
        node = node->GetNext();
        while( node ) {

            RoutePoint *prp = node->GetData();
            wxPoint r1;
            bool r1valid = cc1->GetCanvasPointPix( prp->m_lat, prp->m_lon, &r1);

            if(r0valid && r1valid) {
                dc.StrokeLine( r0.x, r0.y, r1.x, r1.y );
                lines++;
            }

            r0valid = r1valid;
            r0 = r1;
            node = node->GetNext();

        }

        if(lines == 0 &&
                cc1->GetCanvasPointPix( prp0->m_lat, prp0->m_lon, &r0)) {
            dc.StrokeLine( r0.x, r0.y, r0.x + 2, r0.y + 2 );
            return;
        }
    }

//    if( m_nPoints < 2  )
//        return;

    /* determine color and width */
    wxColour col;

    int width = g_pRouteMan->GetRoutePen()->GetWidth(); //g_route_line_width;
    if( m_width != wxPENSTYLE_INVALID )
        width = m_width;
    if(m_bIsTrack)
        width = g_pRouteMan->GetTrackPen()->GetWidth();

    if( m_bRtIsActive )
    {
        col = g_pRouteMan->GetActiveRoutePen()->GetColour();
    } else if( m_bRtIsSelected ) {
        col = g_pRouteMan->GetSelectedRoutePen()->GetColour();
    } else {
        if( m_Colour == wxEmptyString ) {
            col = g_pRouteMan->GetRoutePen()->GetColour();

            //  For tracks, establish colour based on first icon name
            if(m_bIsTrack) {
                wxRoutePointListNode *node = pRoutePointList->GetFirst();
                RoutePoint *prp = node->GetData();

                if( prp->GetIconName().StartsWith( _T("xmred") ) )
                    col = GetGlobalColor( _T ( "URED" ) );
                else if( prp->GetIconName().StartsWith( _T("xmblue") ) )
                    col = GetGlobalColor( _T ( "BLUE3" ) );
                else if( prp->GetIconName().StartsWith( _T("xmgreen") ) )
                    col = GetGlobalColor( _T ( "UGREN" ) );
                else
                    col = GetGlobalColor( _T ( "CHMGD" ) );
            }
        } else {
            for( unsigned int i = 0; i < sizeof( ::GpxxColorNames ) / sizeof(wxString); i++ ) {
                if( m_Colour == ::GpxxColorNames[i] ) {
                    col = ::GpxxColors[i];
                    break;
                }
            }
        }
    }

    int style = wxSOLID;
    if( m_style != wxPENSTYLE_INVALID ) style = m_style;
    dc.SetPen( *wxThePenList->FindOrCreatePen( col, width, style ) );

    glColor3ub(col.Red(), col.Green(), col.Blue());
    glLineWidth( wxMax( g_GLMinSymbolLineWidth, width ) );

    dc.SetGLStipple();
    glBegin(GL_LINE_STRIP);
    float lastlon = 0;
    float lastlat = 0;
    unsigned short int FromSegNo = 1;
    for(wxRoutePointListNode *node = pRoutePointList->GetFirst();
            node; node = node->GetNext()) {
        RoutePoint *prp = node->GetData();
        unsigned short int ToSegNo = prp->m_GPXTrkSegNo;

        /* crosses IDL? if so break up into two segments */
        int dir = 0;
        if(prp->m_lon > 150 && lastlon < -150)
            dir = -1;
        else if(prp->m_lon < -150 && lastlon > 150)
            dir = 1;

        wxPoint r;
        if (FromSegNo != ToSegNo)
        {
            glEnd();
            FromSegNo = ToSegNo;
            glBegin(GL_LINE_STRIP);
        }
        if(dir)
        {
            double crosslat = lat_rl_crosses_meridian(lastlat, lastlon, prp->m_lat, prp->m_lon, 180.0);
            if(cc1->GetCanvasPointPix( crosslat, dir*180, &r))
                glVertex2i(r.x, r.y);
            glEnd();
            glBegin(GL_LINE_STRIP);
            if(cc1->GetCanvasPointPix( crosslat, -dir*180, &r))
                glVertex2i(r.x, r.y);
        }
        lastlat=prp->m_lat;
        lastlon=prp->m_lon;

        if(cc1->GetCanvasPointPix( prp->m_lat, prp->m_lon, &r))
            glVertex2i(r.x, r.y);
        else {
            glEnd();
            glBegin(GL_LINE_STRIP);
        }
    }
    glEnd();
    glDisable (GL_LINE_STIPPLE);

    /* direction arrows.. could probably be further optimized for opengl */
    if( !m_bIsTrack ) {
        wxRoutePointListNode *node = pRoutePointList->GetFirst();
        wxPoint rpt1, rpt2;
        while(node) {
            RoutePoint *prp = node->GetData();
            cc1->GetCanvasPointPix( prp->m_lat, prp->m_lon, &rpt2 );
            if(node != pRoutePointList->GetFirst())
                RenderSegmentArrowsGL( rpt1.x, rpt1.y, rpt2.x, rpt2.y, cc1->GetVP() );
            rpt1 = rpt2;
            node = node->GetNext();
        }
    }

    /*  Route points  */
    for(wxRoutePointListNode *node = pRoutePointList->GetFirst(); node; node = node->GetNext()) {
        RoutePoint *prp = node->GetData();
        if ( !m_bVisible && prp->m_bKeepXRoute )
            prp->DrawGL( VP );
        else if (m_bVisible)
            prp->DrawGL( VP );

    }

#endif
}
Exemplo n.º 2
0
static void ddDrawPlane(const Plane& plane, const AABB& bounds, const Color& color)
{
	vec3 points[6];
	struct edge_t
	{
		int start;
		int end;
	};

	static const edge_t edges[12] =
	{
		// bottom
		{0, 1},
		{1, 3},
		{3, 2},
		{2, 0},

		// top
		{4, 5},
		{5, 7},
		{7, 6},
		{6, 4},

		// top to bottom sides
		{0, 4},
		{1, 5},
		{2, 6},
		{3, 7},
	};

	// clip plane to bounds and render a quad
	vec3 corners[8];
	const vec3 *minmax[2] = { &bounds.m_min, &bounds.m_max };       
	for(int j = 0; j < 8; ++j)
	{
		int iz = j & 1;
		int ix = (j >> 1) & 1;
		int iy = (j >> 2) & 1;
		corners[j].Set(minmax[ix]->x, minmax[iy]->y, minmax[iz]->z);
	}

	int numPoints = 0;

	// add corners as points if they are close to the plane
	for(int j = 0; j < 8; ++j)
	{
		float planeDist = PlaneDist(plane, corners[j]);
		if(fabs(planeDist) < EPSILON)
			points[numPoints++] = corners[j];
	}

	// add edge intersections 
	for(int j = 0; j < 12; ++j)
	{
		vec3 a = corners[edges[j].start], 
			b = corners[edges[j].end], 
			ab = b - a;

		// intersect edge with plane
		float t = (-plane.m_d - Dot(plane.m_n, a)) / Dot(plane.m_n, ab);
		if(t >= 0.f && t <= 1.f)
		{
			vec3 pt = a + t * ab, 
				ptA = a - pt, 
				ptB = b - pt;

			float distSqA = LengthSq(ptA);
			float distSqB = LengthSq(ptB);
			if(distSqA > EPSILON_SQ && distSqB > EPSILON_SQ)
			{
				points[numPoints++] = pt;
				if(numPoints == 6)
					break;
			}       
		}
	}

	if(numPoints < 3)
		return;

	// Sort results
	const float inv_num = 1.f / numPoints;
	vec3 center = {0,0,0};
	for(int j = 0; j < numPoints; ++j)
		center += inv_num * points[j];

	vec3 sideVec = Normalize(points[0] - center);
	vec3 upVec = Normalize(Cross(plane.m_n, sideVec));

	for(int j = 1; j < numPoints; ++j)
	{    
		vec3 toPointJ = points[j] - center;

		float angleJ = AngleWrap(atan2(Dot(upVec, toPointJ), Dot(sideVec, toPointJ)));
		for(int k = j+1; k < numPoints; ++k)
		{
			vec3 toPointK = points[k] - center;
			float angleK = AngleWrap(atan2(Dot(upVec, toPointK), Dot(sideVec, toPointK)));
			if(angleK < angleJ) 
			{
				angleJ = angleK;
				std::swap(points[j], points[k]);
			}
		}
	}

	// Draw outline
	const ShaderInfo* shader = g_dbgdrawShader.get();
	GLint posLoc = shader->m_attrs[GEOM_Pos];
	GLint colorLoc = shader->m_attrs[GEOM_Color];
	glVertexAttrib3fv(colorLoc, &color.r);

	glLineWidth(2.f);
	glBegin(GL_LINES);
	for(int j = 0; j < numPoints; ++j)
	{
		int next = (j + 1) % numPoints;
		glVertexAttrib3fv(posLoc, &points[j].x);
		glVertexAttrib3fv(posLoc, &points[next].x);
	}
	glEnd();
	glLineWidth(1.f);

	// Draw triangles
	glVertexAttrib3fv(colorLoc, &color.r);
	glBegin(GL_TRIANGLE_FAN);
	glVertexAttrib3fv(posLoc, &center.x);
	for(int j = 0; j < numPoints; ++j)
		glVertexAttrib3fv(posLoc, &points[j].x);
	glVertexAttrib3fv(posLoc, &points[0].x);
	glEnd();

	glBegin(GL_TRIANGLE_FAN);
	glVertexAttrib3fv(posLoc, &center.x);
	for(int j = numPoints-1; j >= 0; --j)
		glVertexAttrib3fv(posLoc, &points[j].x);
	glVertexAttrib3fv(posLoc, &points[numPoints-1].x);
	glEnd();

}
Exemplo n.º 3
0
void SetLineWidth(int widthInPixels)
/*****************************************************************************/
{
   glLineWidth(widthInPixels);
}
Exemplo n.º 4
0
/* CTextureCanvas::drawTexture
 * Draws the currently opened composite texture
 *******************************************************************/
void CTextureCanvas::drawTexture()
{
	// Push matrix
	glPushMatrix();

	// Translate to middle of the canvas
	glTranslated(GetSize().x * 0.5, GetSize().y * 0.5, 0);

	// Zoom
	double yscale = (tx_arc ? scale * 1.2 : scale);
	glScaled(scale, yscale, 1);

	// Draw offset guides if needed
	drawOffsetLines();

	// Apply texture scale
	double tscalex = 1;
	double tscaley = 1;
	if (tex_scale)
	{
		tscalex = texture->getScaleX();
		if (tscalex == 0) tscalex = 1;
		tscaley = texture->getScaleY();
		if (tscaley == 0) tscaley = 1;
		glScaled(1.0 / tscalex, 1.0 / tscaley, 1);
	}

	// Calculate top-left position of texture (for glScissor, since it ignores the current translation/scale)
	point2_t screen_tl = texToScreenPosition(0, 0);
	int left = screen_tl.x;
	int top = screen_tl.y;

	// Translate by offsets if needed
	if (view_type == 0) // No offsets
		glTranslated(texture->getWidth() * -0.5, texture->getHeight() * -0.5, 0);
	if (view_type >= 1) // Sprite offsets
		glTranslated(-texture->getOffsetX(), -texture->getOffsetY(), 0);
	if (view_type == 2) // HUD offsets
		glTranslated(-160 * tscalex, -100 * tscaley, 0);

	// Draw the texture border
	drawTextureBorder();

	// Enable textures
	glEnable(GL_TEXTURE_2D);

	// First, draw patches semitransparently (for anything outside the texture)
	// But only if we are drawing stuff outside the texture area
	if (draw_outside)
	{
		for (uint32_t a = 0; a < texture->nPatches(); a++)
			drawPatch(a, true);
	}

	// Reset colouring
	OpenGL::setColour(COL_WHITE);

	// If we're currently dragging, draw a 'basic' preview of the texture using opengl
	if (dragging)
	{
		glEnable(GL_SCISSOR_TEST);
		glScissor(left, top, texture->getWidth() * scale * (1.0 / tscalex), texture->getHeight() * yscale * (1.0 / tscaley));
		for (uint32_t a = 0; a < texture->nPatches(); a++)
			drawPatch(a);
		glDisable(GL_SCISSOR_TEST);
	}

	// Otherwise, draw the fully generated texture
	else
	{
		// Generate if needed
		if (!tex_preview.isLoaded())
		{
			// Determine image type
			SIType type = PALMASK;
			if (blend_rgba) type = RGBA;

			// CTexture -> temp Image -> GLTexture
			SImage temp(type);
			texture->toImage(temp, parent, &palette, blend_rgba);
			tex_preview.loadImage(&temp, &palette);
		}

		// Draw it
		tex_preview.draw2d();
	}

	// Disable textures
	glDisable(GL_TEXTURE_2D);

	// Now loop through selected patches and draw selection outlines
	OpenGL::setColour(70, 210, 220, 255, BLEND_NORMAL);
	glEnable(GL_LINE_SMOOTH);
	glLineWidth(1.5f);
	for (size_t a = 0; a < selected_patches.size(); a++)
	{
		// Skip if not selected
		if (!selected_patches[a])
			continue;

		// Get patch
		CTPatch* patch = texture->getPatch(a);
		CTPatchEx* epatch = (CTPatchEx*)patch;

		// Check for rotation
		if (texture->isExtended() && (epatch->getRotation() == 90 || epatch->getRotation() == -90))
		{
			// Draw outline, width/height swapped
			glBegin(GL_LINE_LOOP);
			glVertex2i(patch->xOffset(), patch->yOffset());
			glVertex2i(patch->xOffset(), patch->yOffset() + (int)patch_textures[a]->getWidth());
			glVertex2i(patch->xOffset() + (int)patch_textures[a]->getHeight(), patch->yOffset() + (int)patch_textures[a]->getWidth());
			glVertex2i(patch->xOffset() + (int)patch_textures[a]->getHeight(), patch->yOffset());
			glEnd();
		}
		else
		{
			// Draw outline
			glBegin(GL_LINE_LOOP);
			glVertex2i(patch->xOffset(), patch->yOffset());
			glVertex2i(patch->xOffset(), patch->yOffset() + (int)patch_textures[a]->getHeight());
			glVertex2i(patch->xOffset() + (int)patch_textures[a]->getWidth(), patch->yOffset() + (int)patch_textures[a]->getHeight());
			glVertex2i(patch->xOffset() + (int)patch_textures[a]->getWidth(), patch->yOffset());
			glEnd();
		}
	}

	// Finally, draw a hilight outline if anything is hilighted
	if (hilight_patch >= 0 && hilight_patch < (int)texture->nPatches())
	{
		// Set colour
		OpenGL::setColour(255, 255, 255, 150, BLEND_ADDITIVE);

		// Get patch
		CTPatch* patch = texture->getPatch(hilight_patch);
		CTPatchEx* epatch = (CTPatchEx*)patch;
		GLTexture* patch_texture = patch_textures[hilight_patch];

		// Check for rotation
		if (texture->isExtended() && (epatch->getRotation() == 90 || epatch->getRotation() == -90))
		{
			// Draw outline, width/height swapped
			glBegin(GL_LINE_LOOP);
			glVertex2i(patch->xOffset(), patch->yOffset());
			glVertex2i(patch->xOffset(), patch->yOffset() + (int)patch_texture->getWidth());
			glVertex2i(patch->xOffset() + (int)patch_texture->getHeight(), patch->yOffset() + (int)patch_texture->getWidth());
			glVertex2i(patch->xOffset() + (int)patch_texture->getHeight(), patch->yOffset());
			glEnd();
		}
		else
		{
			// Draw outline
			glBegin(GL_LINE_LOOP);
			glVertex2i(patch->xOffset(), patch->yOffset());
			glVertex2i(patch->xOffset(), patch->yOffset() + (int)patch_texture->getHeight());
			glVertex2i(patch->xOffset() + (int)patch_texture->getWidth(), patch->yOffset() + (int)patch_texture->getHeight());
			glVertex2i(patch->xOffset() + (int)patch_texture->getWidth(), patch->yOffset());
			glEnd();
		}
	}
	glDisable(GL_LINE_SMOOTH);
	glLineWidth(1.0f);

	// Pop matrix
	glPopMatrix();
}
Exemplo n.º 5
0
void Lines::draw()
{
  //Draw, calls update when required
  Geometry::draw();
  if (drawcount == 0) return;

  // Undo any scaling factor for arrow drawing...
  glPushMatrix();
  if (view->scale[0] != 1.0 || view->scale[1] != 1.0 || view->scale[2] != 1.0)
    glScalef(1.0/view->scale[0], 1.0/view->scale[1], 1.0/view->scale[2]);

  //Draw any 3d rendered tubes
  tris->draw();

  // Re-Apply scaling factors
  glPopMatrix();

  // Draw using vertex buffer object
  glPushAttrib(GL_ENABLE_BIT);
  clock_t t0 = clock();
  double time;
  int stride = 3 * sizeof(float) + sizeof(Colour);   //3+3+2 vertices, normals, texCoord + 32-bit colour
  int offset = 0;
  if (geom.size() > 0 && elements > 0 && glIsBuffer(vbo))
  {
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glVertexPointer(3, GL_FLOAT, stride, (GLvoid*)0); // Load vertex x,y,z only
    glColorPointer(4, GL_UNSIGNED_BYTE, stride, (GLvoid*)(3*sizeof(float)));   // Load rgba, offset 3 float
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);

    //Disable depth test on 2d models
    if (view->is3d)
      glEnable(GL_DEPTH_TEST);
    else
      glDisable(GL_DEPTH_TEST);

    for (unsigned int i=0; i<geom.size(); i++)
    {
      Properties& props = geom[i]->draw->properties;
      if (drawable(i) && props.getBool("flat", true) && !props["tubes"])
      {
        //Set draw state
        setState(i, drawstate.prog[lucLineType]);

        //Lines specific state
        float scaling = props["scalelines"];
        //Don't apply object scaling to internal lines objects
        if (!internal) scaling *= (float)props["scaling"];
        float lineWidth = (float)props["linewidth"] * scaling * view->scale2d; //Include 2d scale factor
        if (lineWidth <= 0) lineWidth = scaling;
        glLineWidth(lineWidth);

        if (props["link"])
          glDrawArrays(GL_LINE_STRIP, offset, counts[i]);
        else
          glDrawArrays(GL_LINES, offset, counts[i]);
      }

      offset += counts[i];
    }

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_COLOR_ARRAY);
  }
  glBindBuffer(GL_ARRAY_BUFFER, 0);
  GL_Error_Check;

  //Restore state
  glPopAttrib();
  glBindTexture(GL_TEXTURE_2D, 0);

  time = ((clock()-t0)/(double)CLOCKS_PER_SEC);
  if (time > 0.05)
    debug_print("  %.4lf seconds to draw %d lines\n", time, offset);
  GL_Error_Check;
}
Exemplo n.º 6
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);

	int strHeight = 0;
	int titleHeight = 0;
	QString title(getName());
	QStringList body;
	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 /= (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->getTextDisplayFont(); //takes rendering zoom into account!
		titleFont = QFont(context._win->getTextDisplayFont()); //takes rendering zoom into account!
		titleFont.setBold(true);
		QFontMetrics titleFontMetrics(titleFont);
		QFontMetrics bodyFontMetrics(bodyFont);

		strHeight = bodyFontMetrics.height();
		titleHeight = titleFontMetrics.height();

		if (m_showFullBody)
			body = getLabelContent(context.dispNumberPrecision);

		//base box dimension
		int dx = 150;
		dx = std::max(dx,titleFontMetrics.width(title));

		int dy = c_margin;	//top vertical margin
		dy += titleHeight;	//title
		if (!body.empty())
		{
			dy += c_margin;	//vertical margin above separator
			for (int j=0; j<body.size(); ++j)
			{
				dx = std::max(dx,bodyFontMetrics.width(body[j]));
				dy += strHeight; //body line height
			}
			dy += c_margin;	//vertical margin below text
		}
		else
		{
			dy += c_margin;	// vertical margin (purely for aesthetics)
		}
		dy += c_margin;		// bottom vertical margin
		dx += c_margin*2;	// horizontal margins

		//main rectangle
		m_labelROI[0]=0;
		m_labelROI[1]=0;
		m_labelROI[2]=dx;
		m_labelROI[3]=dy;

		//close button
		/*m_closeButtonROI[2]=dx-c_margin;
		m_closeButtonROI[0]=m_closeButtonROI[2]-c_buttonSize;
		m_closeButtonROI[3]=c_margin;
		m_closeButtonROI[1]=m_closeButtonROI[3]+c_buttonSize;
		//*/

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

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

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

	//colors
	bool highlighted = (!pushName && isSelected());
	//default background color
	colorType defaultBkgColor[4];
	memcpy(defaultBkgColor,context.labelDefaultCol,sizeof(colorType)*3);
	defaultBkgColor[3] = (colorType)((float)context.labelsTransparency*(float)MAX_COLOR_COMP/100.0f);
	//default border color (mustn't be totally transparent!)
	colorType defaultBorderColor[4];
	if (highlighted)
		memcpy(defaultBorderColor,ccColor::red,sizeof(colorType)*3);
	else
		memcpy(defaultBorderColor,context.labelDefaultCol,sizeof(colorType)*3);
	defaultBorderColor[3] = (colorType)((float)(50+context.labelsTransparency/2)*(float)MAX_COLOR_COMP/100.0f);

	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 = (int)arrowDestX-xStart;
		int iArrowDestY = (int)arrowDestY-yStart;
		{
			if (iArrowDestX < m_labelROI[0]) //left
				arrowBaseConfig += 0;
			else if (iArrowDestX > m_labelROI[2]) //Right
				arrowBaseConfig += 2;
			else  //Middle
				arrowBaseConfig += 1;

			if (iArrowDestY > -m_labelROI[1]) //Top
				arrowBaseConfig += 0;
			else if (iArrowDestY < -m_labelROI[3]) //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);
			glBegin(GL_TRIANGLE_FAN);
			glVertex2d(arrowDestX-xStart,arrowDestY-yStart);
			switch(arrowBaseConfig)
			{
			case 0: //top-left corner
				glVertex2i(m_labelROI[0], -m_labelROI[1]-2*c_arrowBaseSize);
				glVertex2i(m_labelROI[0], -m_labelROI[1]);
				glVertex2i(m_labelROI[0]+2*c_arrowBaseSize, -m_labelROI[1]);
				break;
			case 1: //top-middle edge
				glVertex2i(std::max(m_labelROI[0],iArrowDestX-c_arrowBaseSize), -m_labelROI[1]);
				glVertex2i(std::min(m_labelROI[2],iArrowDestX+c_arrowBaseSize), -m_labelROI[1]);
				break;
			case 2: //top-right corner
				glVertex2i(m_labelROI[2], -m_labelROI[1]-2*c_arrowBaseSize);
				glVertex2i(m_labelROI[2], -m_labelROI[1]);
				glVertex2i(m_labelROI[2]-2*c_arrowBaseSize, -m_labelROI[1]);
				break;
			case 3: //middle-left edge
				glVertex2i(m_labelROI[0], std::min(-m_labelROI[1],iArrowDestY+c_arrowBaseSize));
				glVertex2i(m_labelROI[0], std::max(-m_labelROI[3],iArrowDestY-c_arrowBaseSize));
				break;
			case 4: //middle of rectangle!
				break;
			case 5: //middle-right edge
				glVertex2i(m_labelROI[2], std::min(-m_labelROI[1],iArrowDestY+c_arrowBaseSize));
				glVertex2i(m_labelROI[2], std::max(-m_labelROI[3],iArrowDestY-c_arrowBaseSize));
				break;
			case 6: //bottom-left corner
				glVertex2i(m_labelROI[0], -m_labelROI[3]+2*c_arrowBaseSize);
				glVertex2i(m_labelROI[0], -m_labelROI[3]);
				glVertex2i(m_labelROI[0]+2*c_arrowBaseSize, -m_labelROI[3]);
				break;
			case 7: //bottom-middle edge
				glVertex2i(std::max(m_labelROI[0],iArrowDestX-c_arrowBaseSize), -m_labelROI[3]);
				glVertex2i(std::min(m_labelROI[2],iArrowDestX+c_arrowBaseSize), -m_labelROI[3]);
				break;
			case 8: //bottom-right corner
				glVertex2i(m_labelROI[2], -m_labelROI[3]+2*c_arrowBaseSize);
				glVertex2i(m_labelROI[2], -m_labelROI[3]);
				glVertex2i(m_labelROI[2]-2*c_arrowBaseSize, -m_labelROI[3]);
				break;
			}
			glEnd();
		}
	}

	//main rectangle
	glColor4ubv(defaultBkgColor);
    glBegin(GL_QUADS);
    glVertex2i(m_labelROI[0], -m_labelROI[1]);
    glVertex2i(m_labelROI[0], -m_labelROI[3]);
    glVertex2i(m_labelROI[2], -m_labelROI[3]);
    glVertex2i(m_labelROI[2], -m_labelROI[1]);
    glEnd();

	//if (highlighted)
	{
		glPushAttrib(GL_LINE_BIT);
		glLineWidth(3.0f);
		glColor4ubv(defaultBorderColor);
		glBegin(GL_LINE_LOOP);
		glVertex2i(m_labelROI[0], -m_labelROI[1]);
		glVertex2i(m_labelROI[0], -m_labelROI[3]);
		glVertex2i(m_labelROI[2], -m_labelROI[3]);
		glVertex2i(m_labelROI[2], -m_labelROI[1]);
		glEnd();
		glPopAttrib();
	}

	//draw close button
	/*glColor3ubv(ccColor::black);
    glBegin(GL_LINE_LOOP);
    glVertex2i(m_closeButtonROI[0],-m_closeButtonROI[1]);
    glVertex2i(m_closeButtonROI[0],-m_closeButtonROI[3]);
    glVertex2i(m_closeButtonROI[2],-m_closeButtonROI[3]);
    glVertex2i(m_closeButtonROI[2],-m_closeButtonROI[1]);
    glEnd();
    glBegin(GL_LINES);
    glVertex2i(m_closeButtonROI[0]+2,-m_closeButtonROI[1]+2);
    glVertex2i(m_closeButtonROI[2]-2,-m_closeButtonROI[3]-2);
    glVertex2i(m_closeButtonROI[2]-2,-m_closeButtonROI[1]+2);
    glVertex2i(m_closeButtonROI[0]+2,-m_closeButtonROI[3]-2);
    glEnd();
	//*/

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

		const colorType* defaultTextColor = (context.labelsTransparency<40 ? context.textDefaultCol : ccColor::darkBlue);

		context._win->displayText(title,xStart+xStartRel,yStart+yStartRel,ccGenericGLDisplay::ALIGN_DEFAULT,0,defaultTextColor,&titleFont);
		yStartRel -= c_margin;

		if (!body.empty())
		{
			//line separation
			glColor4ubv(defaultBorderColor);
			glBegin(GL_LINES);
			glVertex2i(xStartRel,yStartRel);
			glVertex2i(xStartRel+m_labelROI[2]-m_labelROI[0]-2*c_margin,yStartRel);
			glEnd();

			//display body
			yStartRel -= c_margin;
			for (int i=0; i<body.size(); ++i)
			{
				yStartRel -= strHeight;
				context._win->displayText(body[i],xStart+xStartRel,yStart+yStartRel,ccGenericGLDisplay::ALIGN_DEFAULT,0,defaultTextColor,&bodyFont);
			}
		}
	}

	glPopAttrib();

	glPopMatrix();

	if (pushName)
		glPopName();
}
Exemplo n.º 7
0
/**
 * This method is call on press of key
 */
void Visualizer::onKeyboard(unsigned char key, int, int)
{
  	if (key>='A' && key<='Z') key+='a'-'A';       /* convert upper char on lower */

  	switch (key) {                                /* press key */
    		case '1' :                                  	/* show vertex */
      			glPolygonMode(GL_FRONT, GL_POINT);
      			glPolygonMode(GL_BACK, GL_POINT);
      			glutPostRedisplay();
      			break;
    		case '2' :                                  	/* show wireframe */
      			glPolygonMode(GL_FRONT, GL_LINE);
      			glPolygonMode(GL_BACK, GL_LINE);
      			glutPostRedisplay();
     			break;
    		case '3' :                                  	/* show fill polygons */
      			glPolygonMode(GL_FRONT, GL_FILL);
      			glPolygonMode(GL_BACK, GL_FILL);
      			glutPostRedisplay();
      			break;
    		case '5' :                                  	/* decrease vision angle */
      			if (fov>0) fov--;
      			onReshape(WindowWidth, WindowHeight);
      			glutPostRedisplay();
     			break;
    		case '6' :
      			if (fov<180) fov++;                     /* increase vision angle */
      			onReshape(WindowWidth, WindowHeight);
      			glutPostRedisplay();
      			break;
    		case '7' :                                  	/* zoom in trim plain */
      			if (line_width > 0) line_width -= 0.5;	
		  	glLineWidth(line_width);                
		  	glPointSize(line_width);                
      			onReshape(WindowWidth, WindowHeight);
      			glutPostRedisplay();
      			break;
    		case '8' :                                  	/* zoom out trim plain */
      			if (line_width < 10) line_width += 0.5;
		  	glLineWidth(line_width);                
		  	glPointSize(line_width);                
      			onReshape(WindowWidth, WindowHeight);
      			glutPostRedisplay();
      			break;
		case 's' :				    	/* print to bitmap - screenshot */
			saveScreenshot(screenshotFileName);
			break;
    		case 27 :                                   	/* Escape */
    		case 'q' :
      			exit(0);                                /* exit */
      			break;
    		case 'm' :
			colorInput = INTERPOLATE_RADIOSITY;	/* interpolate radiosity */
			createCallList();
			glutPostRedisplay();
			break;
    		case 'b' :
			colorInput = INTERPOLATE_RADIOSITY_RAW;	/* interpolate radiosity */
			createCallList();
			glutPostRedisplay();
			break;
    		case 'v' :
			colorInput = RADIOSITY;	/* radiosity */
			createCallList();
			glutPostRedisplay();
			break;
    		case 'n' :
			colorInput = RADIOSITY_LAST;	/* radiosity */
			createCallList();
			glutPostRedisplay();
			break;
		case 'z' :
			colorInput = REFLECTIVITY;	/* reflectivity + emission */
			createCallList();
			glutPostRedisplay();
			break;
		case 'x' :
			colorInput = EMISSION;	/* reflectivity */
			createCallList();
			glutPostRedisplay();
			break;
		case 'c' :
			colorInput = REFLECT_EMISS;	/* emission */
			createCallList();
			glutPostRedisplay();
			break;
   		case 'f' :
      			glutFullScreen();                      	/* fullscrean */
      			break;
    		case 'w' :
      			glutReshapeWindow(WindowWidth, WindowHeight);              /* go back to window */
      			break;
    		default:
      			break;
  	}
}
Exemplo n.º 8
0
void UVWidget::paintGL()
{
	glPushAttrib( GL_ALL_ATTRIB_BITS );
	
	glMatrixMode( GL_PROJECTION );
	glPushMatrix();
	glLoadIdentity();

	setupViewport( width(), height() );

	glMatrixMode( GL_MODELVIEW );
	glPushMatrix();
	glLoadIdentity();
	
	qglClearColor( Options::bgColor() );
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
	
	glDisable( GL_DEPTH_TEST );
	glDepthMask( GL_FALSE );
	
	// draw texture

	glPushMatrix();
	glLoadIdentity();
	
	glEnable( GL_TEXTURE_2D );
	
	if ( aTextureBlend->isChecked() )
		glEnable( GL_BLEND );
	else
		glDisable( GL_BLEND );

	if( !texfile.isEmpty() )
		bindTexture( texfile );
	else
		bindTexture( texsource );


	glTranslatef( -0.5f, -0.5f, 0.0f );

	glTranslatef( -1.0f, -1.0f, 0.0f );
	for( int i = 0; i < 3; i++ )
	{
		for( int j = 0; j < 3; j++ )
		{
			if( i == 1 && j == 1 ) {
				glColor4f( 0.75f, 0.75f, 0.75f, 1.0f );
			}
			else {
				glColor4f( 0.5f, 0.5f, 0.5f, 1.0f );
			}

			glDrawArrays( GL_QUADS, 0, 4 );

			glTranslatef( 1.0f, 0.0f, 0.0f );
		}

		glTranslatef( -3.0f, 1.0f, 0.0f );
	}
	glTranslatef( 1.0f, -2.0f, 0.0f );
	
	glDisable( GL_TEXTURE_2D );
	
	glPopMatrix();

	
	// draw grid

	glPushMatrix();
	glLoadIdentity();
	
	glEnable( GL_BLEND );

	glLineWidth( 0.8f );
	glBegin( GL_LINES );
	int glGridMinX	= qRound( qMin( glViewRect[0], glViewRect[1] ) / glGridD );
	int glGridMaxX	= qRound( qMax( glViewRect[0], glViewRect[1] ) / glGridD );
	int glGridMinY	= qRound( qMin( glViewRect[2], glViewRect[3] ) / glGridD );
	int glGridMaxY	= qRound( qMax( glViewRect[2], glViewRect[3] ) / glGridD );
	for( int i = glGridMinX; i < glGridMaxX; i++ )
	{
		GLdouble glGridPos = glGridD * i;
		
		if( ( i % ( GRIDSEGS * GRIDSEGS ) ) == 0 ) {
			glLineWidth( 1.4f );
			glColor4f( 1.0f, 1.0f, 1.0f, 0.4f );
		}
		else if( zoom > ( GRIDSEGS * GRIDSEGS / 2.0 ) ) {
			continue;
		}
		else if( ( i % GRIDSEGS ) == 0 ) {
			glLineWidth( 1.2f );
			glColor4f( 1.0f, 1.0f, 1.0f, 0.2f );
		}
		else if( zoom > ( GRIDSEGS / 2.0 ) ) {
			continue;
		}
		else {
			glLineWidth( 0.8f );
			glColor4f( 1.0f, 1.0f, 1.0f, 0.1f );
		}
		
		glVertex2d( glGridPos, glViewRect[2] );
		glVertex2d( glGridPos, glViewRect[3] );
	}
	for( int i = glGridMinY; i < glGridMaxY; i++ )
	{
		GLdouble glGridPos = glGridD * i;
		
		if( ( i % ( GRIDSEGS * GRIDSEGS ) ) == 0 ) {
			glLineWidth( 1.4f );
			glColor4f( 1.0f, 1.0f, 1.0f, 0.4f );
		}
		else if( zoom > ( GRIDSEGS * GRIDSEGS / 2.0 ) ) {
			continue;
		}
		else if( ( i % GRIDSEGS ) == 0 ) {
			glLineWidth( 1.2f );
			glColor4f( 1.0f, 1.0f, 1.0f, 0.2f );
		}
		else if( zoom > ( GRIDSEGS / 2.0 ) ) {
			continue;
		}
		else {
			glLineWidth( 0.8f );
			glColor4f( 1.0f, 1.0f, 1.0f, 0.1f );
		}
		
		glVertex2d( glViewRect[0], glGridPos );
		glVertex2d( glViewRect[1], glGridPos );
	}
	glEnd();

	glPopMatrix();



	drawTexCoords();

	
	glDisable( GL_DEPTH_TEST );
	glDepthMask( GL_FALSE );

	if( ! selectRect.isNull() )
	{
		glLoadIdentity();
		glHighlightColor();
		glBegin( GL_LINE_LOOP );
		glVertex( mapToContents( selectRect.topLeft() ) );
		glVertex( mapToContents( selectRect.topRight() ) );
		glVertex( mapToContents( selectRect.bottomRight() ) );
		glVertex( mapToContents( selectRect.bottomLeft() ) );
		glEnd();
	}
	
	if ( ! selectPoly.isEmpty() )
	{
		glLoadIdentity();
		glHighlightColor();
		glBegin( GL_LINE_LOOP );
		foreach ( QPoint p, selectPoly )
		{
			glVertex( mapToContents( p ) );
		}
Exemplo n.º 9
0
        static void glInit()
        {
                // Enable Texture Mapping
                glEnable(GL_TEXTURE_2D);
                // Use trilinear interpolation (GL_LINEAR_MIPMAP_LINEAR)
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

                glClearColor( 1.f, 0.f, 1.f, 1.f ); //0.15f, 0.15f, 0.20f, 1.f);
                glClearDepth(1.0f);                                 // Depth Buffer Setup
                glEnable(GL_DEPTH_TEST);                            // Enables Depth Testing
                glDepthFunc(GL_LEQUAL);                             // The Type Of Depth Testing To Do
                glDepthMask(GL_TRUE);

                if( 1 )
                {
                    /*
                    GLfloat light_ambient[] = { 0.0, 0.0, 0.0, 1.0 };
                    GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
                    GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 };
                    GLfloat light_position[] = { 1.0, 1.0, 0.0, 0.0 };

                    glLightfv (GL_LIGHT0, GL_AMBIENT, light_ambient);
                    glLightfv (GL_LIGHT0, GL_DIFFUSE, light_diffuse);
                    glLightfv (GL_LIGHT0, GL_SPECULAR, light_specular);
                    glLightfv (GL_LIGHT0, GL_POSITION, light_position);
*/
                    GLfloat global_ambient[] = { 0.6f, 0.6f, 1.0, 1.0 };
                    glLightModelfv (GL_LIGHT_MODEL_AMBIENT, global_ambient);

                    // Enable Lighting
                    glDisable(GL_LIGHTING);
                    glDisable(GL_LIGHT0);

                    //glLightfv(GL_LIGHT0, GL_POSITION, lightpos);
                    // Enable Material Coloring (color texture maps)
                    //glMaterial will control the polygon's specular and emission colours and the ambient and diffuse will both be set using glColor
                    glEnable(GL_COLOR_MATERIAL);
                    glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);
                }


                glShadeModel(GL_SMOOTH);                            // Enable Smooth Shading


                glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);  // Nice Perspective Correction

                glEnable( GL_LINE_SMOOTH );
                glHint( GL_LINE_SMOOTH_HINT, GL_NICEST );
                glLineWidth( 1.0f );
                glEnable( GL_BLEND );
                glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );

                /* decal */
                glEnable(GL_LIGHTING);
                glEnable(GL_LIGHT0);
                glEnable(GL_CULL_FACE);
                glCullFace(GL_BACK);

                glDisable( GL_CULL_FACE ); //glDisable
                //glCullFace( GL_FRONT );
                //glCullFace( GL_BACK );

                /* small opt */

                glEnable(GL_CULL_FACE);
                glCullFace(GL_BACK);
                glFrontFace(GL_CCW);
        }
Exemplo n.º 10
0
/* draw the paddle */
int  draw_paddle( ARPaddleInfo *paddleInfo, PaddleItemInfo *paddleItemInfo )
{
    double  gl_para[16];
    int     i;

    argDrawMode3D();
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    
    argDraw3dCamera( 0, 0 );
    argConvGlpara(paddleInfo->trans, gl_para);
      
    glMatrixMode(GL_MODELVIEW);
    glLoadMatrixd( gl_para );

    glColor3f( 1.0, 0.0, 0.0 );
    glLineWidth(4.0);
    glBegin(GL_LINE_LOOP);
        glVertex2f( -25.0, -25.0 );
        glVertex2f(  25.0, -25.0 );
        glVertex2f(  25.0,  25.0 );
        glVertex2f( -25.0,  25.0 );
    glEnd();

    glColor3f( 0.0, 0.0, 1.0);
    glBegin(GL_LINE_LOOP);
    for( i = 0; i < 16; i++ ) {
        double  x, y;
        x = PADDLE_RADIUS * cos(i*3.141592*2/16);
        y = PADDLE_RADIUS * sin(i*3.141592*2/16);
        glVertex2d( x, y );
    }
    glEnd();
    glBegin(GL_LINE_LOOP);
        glVertex2f( -7.5,    0.0 );
        glVertex2f(  7.5,    0.0 );
        glVertex2f(  7.5, -105.0 );
        glVertex2f( -7.5, -105.0 );
    glEnd();

    glEnable(GL_BLEND);
    glBlendFunc(GL_ZERO,GL_ONE);
    
    glColor4f(1,1,1,0);    
	glBegin(GL_POLYGON);
    for( i = 0; i < 16; i++ ) {
        double  x, y;
        x = 40.0 * cos(i*3.141592*2/16);
        y = 40.0 * sin(i*3.141592*2/16);
        glVertex2d( x, y );    
	}
    glEnd();
    glBegin(GL_POLYGON);
        glVertex2f( -7.5,    0.0 );
        glVertex2f(  7.5,    0.0 );
        glVertex2f(  7.5, -105.0 );
        glVertex2f( -7.5, -105.0 );
    glEnd();
    glDisable(GL_BLEND);

	/* draw any objects on the paddle */
	if( (i=paddleItemInfo->item) !=-1) {

        glPushMatrix();
        glTranslatef( paddleItemInfo->x, paddleItemInfo->y, 10.0 );
        glRotatef( paddleItemInfo->angle * 180.0/3.141592, 0.0, 0.0, 1.0 );
	glColor3f(0.0,1.0,0.0);
	glutSolidSphere(10,10,10);
	//	glutSolidTeapot(10.);
        glPopMatrix();
	}

    glDisable(GL_DEPTH_TEST);
	argDrawMode2D();
    return 0;
}
Exemplo n.º 11
0
/*************************************************************************************
**
** drawGroundGrid - draws a ground plane
**
***************************************************************************************/
int drawGroundGrid( double trans[3][4], int divisions, float x, float y, float height)
{
	double        gl_para[16];
    int           i;
	float x0,x1,y0,y1;
	float deltaX, deltaY;

	argDrawMode3D();
    argDraw3dCamera( 0, 0 );
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    
    /* load the camera transformation matrix */
    glMatrixMode(GL_MODELVIEW);
    argConvGlpara(trans, gl_para);
    glLoadMatrixd( gl_para );
	
    glTranslatef(x/2.,-y/2.,0.);
	//draw the grid
    glColor3f(1,0,0);
	glLineWidth(6.0);
	glBegin(GL_LINE_LOOP);
	glVertex3f( -x, y, height );
	glVertex3f(  x, y, height );  
	glVertex3f(  x, -y, height );
	glVertex3f( -x, -y, height );
	glEnd();
	glLineWidth(3.0);
	
	//draw a grid of lines
	//X direction
	x0 = -x; x1 = -x;
	y0 = -y; y1 = y;
	deltaX = (2*x)/divisions;

	for(i=0;i<divisions;i++){
		x0 = x0 + deltaX;
		glBegin(GL_LINES);
		glVertex3f(x0,y0,height);
		glVertex3f(x0,y1,height);
		glEnd();
	}

	x0 = -x; x1 = x;
	deltaY = (2*y)/divisions;

	for(i=0;i<divisions;i++){
		y0 = y0 + deltaY;
		glBegin(GL_LINES);
		glVertex3f(x0,y0,height);
		glVertex3f(x1,y0,height);
		glEnd();
	}

	glLineWidth(1.0);

	glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glLightfv(GL_LIGHT0, GL_POSITION, light_position);
    glLightfv(GL_LIGHT0, GL_AMBIENT, ambi);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, lightZeroColor);

	glDisable( GL_LIGHTING );
    glDisable( GL_DEPTH_TEST );    
    argDrawMode2D();
    return 0;
}
Exemplo n.º 12
0
/* main loop */
static void mainLoop(void)
{
    ARUint8         *dataPtr;
    ARMarkerInfo    *marker_info;
    int             marker_num;
	float curPaddlePos[3];
    int             i;
    double          err;
    double			angle;

	err=0.;
    /* grab a video frame */
    if( (dataPtr = (ARUint8 *)arVideoGetImage()) == NULL ) {
        arUtilSleep(2); 
        return;
    }
	
    if( count == 0 ) arUtilTimerReset();  
    count++;
   
	/* detect the markers in the video frame */
    if( arDetectMarkerLite(dataPtr, thresh, &marker_info, &marker_num) < 0 ) {
        cleanup();
        exit(0);
    }

    argDrawMode2D();
    if( !arDebug ) {
        argDispImage( dataPtr, 0,0 );
    }
    else {
        argDispImage( dataPtr, 1, 1 );
        if( arImageProcMode == AR_IMAGE_PROC_IN_HALF )
            argDispHalfImage( arImage, 0, 0 );
        else
            argDispImage( arImage, 0, 0);

        glColor3f( 1.0, 0.0, 0.0 );
        glLineWidth( 1.0 );
        for( i = 0; i < marker_num; i++ ) {
            argDrawSquare( marker_info[i].vertex, 0, 0 );
        }
        glLineWidth( 1.0 );
    }

    arVideoCapNext();

	for( i = 0; i < marker_num; i++ ) 
		marker_flag[i] = 0;
  
	/* get the paddle position */
	paddleGetTrans(paddleInfo, marker_info, marker_flag, 
				marker_num, &cparam);
	/* draw the 3D models */
	glClearDepth( 1.0 );
	glClear(GL_DEPTH_BUFFER_BIT);


	/* get the translation from the multimarker pattern */
	if( (err=arMultiGetTransMat(marker_info, marker_num, config)) < 0 ) {
        argSwapBuffers();
        return;
    }	
	
	//    printf("err = %f\n", err);
    if(err > 100.0 ) {
        argSwapBuffers();
        return;
    }
	
	//draw a red ground grid
	drawGroundGrid( config->trans, 15, 150.0, 110.0, 0.0);

	/* find the paddle position relative to the base */
	if (paddleInfo->active)
		findPaddlePosition(curPaddlePos,paddleInfo->trans,config->trans);

	/* checking for paddle gesture */
	if( paddleInfo->active) 
	  {
	    int findItem=-1;
	    if (myPaddleItem.item!=-1)
	      {

		  if( check_incline(paddleInfo->trans, config->trans, &angle) ) {
		      myPaddleItem.x += 2.0 * cos(angle);
		      myPaddleItem.y += 2.0 * sin(angle);
		      if( myPaddleItem.x*myPaddleItem.x + 
			  myPaddleItem.y*myPaddleItem.y > 900.0 ) {
			  myPaddleItem.x -= 2.0 * cos(angle);
			  myPaddleItem.y -= 2.0 * sin(angle);
			  myListItem.item[myPaddleItem.item].onpaddle=0;		     
			  myListItem.item[myPaddleItem.item].pos[0]=curPaddlePos[0]; 
			  myListItem.item[myPaddleItem.item].pos[1]=curPaddlePos[1];  
			  myPaddleItem.item = -1;
			}
		  }
	      }
	    else
	      {
		if ((findItem=check_pickup(paddleInfo->trans, config->trans,&myListItem, &angle))!=-1)  {
		    
		    myPaddleItem.item=findItem;
		    myPaddleItem.x =0.0;
		    myPaddleItem.y =0.0;
		    myPaddleItem.angle = 0.0;
		    myListItem.item[myPaddleItem.item].onpaddle=1;
		  }
	      }
	  }

	/* draw the item */
	drawItems(config->trans,&myListItem);

	/* draw the paddle */
	if( paddleInfo->active ){ 
	  draw_paddle(paddleInfo,&myPaddleItem);
	}
	
	argSwapBuffers();
}
Exemplo n.º 13
0
Arquivo: Audio.cpp Projeto: tschw/hifi
void Audio::render(int screenWidth, int screenHeight) {
    if (_stream) {
        glLineWidth(2.0);
        glBegin(GL_LINES);
        glColor3f(1,1,1);
        
        int startX = 20.0;
        int currentX = startX;
        int topY = screenHeight - 40;
        int bottomY = screenHeight - 20;
        float frameWidth = 20.0;
        float halfY = topY + ((bottomY - topY) / 2.0);
        
        // draw the lines for the base of the ring buffer
        
        glVertex2f(currentX, topY);
        glVertex2f(currentX, bottomY);
        
        for (int i = 0; i < RING_BUFFER_LENGTH_FRAMES / 2; i++) {
            glVertex2f(currentX, halfY);
            glVertex2f(currentX + frameWidth, halfY);
            currentX += frameWidth;
            
            glVertex2f(currentX, topY);
            glVertex2f(currentX, bottomY);
        }
        glEnd();
        
        //  Show a bar with the amount of audio remaining in ring buffer beyond current playback
        float remainingBuffer = 0;
        timeval currentTime;
        gettimeofday(&currentTime, NULL);
        float timeLeftInCurrentBuffer = 0;
        if (_lastCallbackTime.tv_usec > 0) {
            timeLeftInCurrentBuffer = AUDIO_CALLBACK_MSECS - diffclock(&_lastCallbackTime, &currentTime);
        }
        
        if (_ringBuffer.getEndOfLastWrite() != NULL)
            remainingBuffer = _ringBuffer.diffLastWriteNextOutput() / PACKET_LENGTH_SAMPLES * AUDIO_CALLBACK_MSECS;
        
        if (_wasStarved == 0) {
            glColor3f(0, 1, 0);
        } else {
            glColor3f(0.5 + (_wasStarved / 20.0f), 0, 0);
            _wasStarved--;
        }
        
        glBegin(GL_QUADS);
        glVertex2f(startX, topY + 2);
        glVertex2f(startX + (remainingBuffer + timeLeftInCurrentBuffer)/AUDIO_CALLBACK_MSECS*frameWidth, topY + 2);
        glVertex2f(startX + (remainingBuffer + timeLeftInCurrentBuffer)/AUDIO_CALLBACK_MSECS*frameWidth, bottomY - 2);
        glVertex2f(startX, bottomY - 2);
        glEnd();
        
        if (_averagedLatency == 0.0) {
            _averagedLatency = remainingBuffer + timeLeftInCurrentBuffer;
        } else {
            _averagedLatency = 0.99f * _averagedLatency + 0.01f * (remainingBuffer + timeLeftInCurrentBuffer);
        }
        
        //  Show a yellow bar with the averaged msecs latency you are hearing (from time of packet receipt)
        glColor3f(1,1,0);
        glBegin(GL_QUADS);
        glVertex2f(startX + _averagedLatency / AUDIO_CALLBACK_MSECS * frameWidth - 2, topY - 2);
        glVertex2f(startX + _averagedLatency / AUDIO_CALLBACK_MSECS * frameWidth + 2, topY - 2);
        glVertex2f(startX + _averagedLatency / AUDIO_CALLBACK_MSECS * frameWidth + 2, bottomY + 2);
        glVertex2f(startX + _averagedLatency / AUDIO_CALLBACK_MSECS * frameWidth - 2, bottomY + 2);
        glEnd();
        
        char out[40];
        sprintf(out, "%3.0f\n", _averagedLatency);
        drawtext(startX + _averagedLatency / AUDIO_CALLBACK_MSECS * frameWidth - 10, topY - 9, 0.10, 0, 1, 0, out, 1,1,0);
        
        //  Show a red bar with the 'start' point of one frame plus the jitter buffer
        
        glColor3f(1, 0, 0);
        int jitterBufferPels = (1.f + (float)getJitterBufferSamples() / (float)PACKET_LENGTH_SAMPLES_PER_CHANNEL) * frameWidth;
        sprintf(out, "%.0f\n", getJitterBufferSamples() / SAMPLE_RATE * 1000.f);
        drawtext(startX + jitterBufferPels - 5, topY - 9, 0.10, 0, 1, 0, out, 1, 0, 0);
        sprintf(out, "j %.1f\n", _measuredJitter);
        if (Application::getInstance()->shouldDynamicallySetJitterBuffer()) {
            drawtext(startX + jitterBufferPels - 5, bottomY + 12, 0.10, 0, 1, 0, out, 1, 0, 0);
        } else {
            drawtext(startX, bottomY + 12, 0.10, 0, 1, 0, out, 1, 0, 0);
        }
    
        glBegin(GL_QUADS);
        glVertex2f(startX + jitterBufferPels - 2, topY - 2);
        glVertex2f(startX + jitterBufferPels + 2, topY - 2);
        glVertex2f(startX + jitterBufferPels + 2, bottomY + 2);
        glVertex2f(startX + jitterBufferPels - 2, bottomY + 2);
        glEnd();

    }
}
Exemplo n.º 14
0
void CUnitManager::render()
{


    float shift_un = 640/units.size();
    glBegin(GL_TRIANGLES);
    for(unsigned int i = 0 ; i < units.size(); i++)
    {

        if(units[i].health > 0)
        {
            float curr_x,curr_y;
            float last_x,last_y;
            float surf_x,surf_y;

            curr_x = units[i].x*32;
            curr_y = units[i].y*32;

            last_x = units[i].lx*32;
            last_y = units[i].ly*32;

            surf_x = ((curr_x - last_x)/SimSpeed) * Accum;
            surf_y = ((curr_y - last_y)/SimSpeed) * Accum;

            last_x += surf_x;
            last_y += surf_y;


            glColor3ub(units[i].Rcolor,units[i].Gcolor,units[i].Bcolor);
            switch(units[i].r)
            {
            case 1:
                glVertex3f(last_x+8,last_y+8,0);
                glVertex3f(last_x+24,last_y+8,0);
                glVertex3f(last_x+16,last_y+24,0);
                break;
            case 2:
                glVertex3f(last_x+8,last_y+24,0);
                glVertex3f(last_x+8,last_y+8,0);
                glVertex3f(last_x+24,last_y+16,0);
                break;
            case 3:
                glVertex3f(last_x+8,last_y+24,0);
                glVertex3f(last_x+24,last_y+24,0);
                glVertex3f(last_x+16,last_y+8,0);
                break;
            case 4:
                glVertex3f(last_x+24,last_y+24,0);
                glVertex3f(last_x+24,last_y+8,0);
                glVertex3f(last_x+8,last_y+16,0);
                break;
            default:
                break;
            }
            glVertex3f(660+16  ,16 + shift_un * i,0);
            glVertex3f(660+48 ,16 + shift_un * i,0);
            glVertex3f(660+32 ,48+ shift_un * i,0);

            glEnd();

            glColor3ub(255,255,0);

            glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
            glLineWidth(units[i].arrmor);
            if(units[i].arrmor != 0)
            {
                glBegin(GL_QUADS);
                glVertex2f(last_x+4,last_y+4);
                glVertex2f(last_x+28,last_y+4);
                glVertex2f(last_x+28,last_y+28);
                glVertex2f(last_x+4,last_y+28);
                glEnd();
            }
            glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
            glBegin(GL_TRIANGLES);

            glColor3ub(255,0,0);
            float shift_hp = 36 / units[i].health;
            for(unsigned int h = 0; h < units[i].health; h++)
            {
                glVertex3f(716+8 + shift_hp * h ,8 + shift_un * i,0);
                glVertex3f(716+8 + shift_hp * h ,24 + shift_un * i,0);
                glVertex3f(716+24+ shift_hp * h ,16  + shift_un * i,0);
            }


            glColor3ub(255,255,0);
            if(units[i].arrmor > 0)
            {
            float shift_ar = 36 / units[i].arrmor;
            for(unsigned int h = 0; h < units[i].arrmor; h++)
            {
                glVertex3f(716+8 + shift_ar * h ,34 + shift_un * i,0);
                glVertex3f(716+8 + shift_ar * h ,50 + shift_un * i,0);
                glVertex3f(716+24+ shift_ar * h ,42 + shift_un * i,0);
            }
            }
            glColor3ub(0,0,255);

            if(units[i].kills > 0)
            {
            float shift_kl = 36 / units[i].kills;
            for(unsigned int h = 0; h < units[i].kills; h++)
            {

            if(units[i].kills < 4)
            glColor3ub(255,0,0);
            else if(units[i].kills >= 4 and units[i].kills < 8)
            glColor3ub(204,204,255);
            else if(units[i].kills >= 8 and units[i].kills < 12)
            glColor3ub(0,0,255);
            else if(units[i].kills >= 12)
            glColor3ub(125,255,0);

                glVertex3f(716-40  ,24 + shift_un * i + shift_kl*h,0);
                glVertex3f(716-54  ,24 + shift_un * i + shift_kl*h,0);
                glVertex3f(716-54  ,8  + shift_un * i + shift_kl*h,0);
            }
            }


        }
    }
    //player

    glEnd();
}
Exemplo n.º 15
0
void MyFrameHandler(unsigned long windowID, unsigned int viewport, void *)
{
	glLineWidth(8.0);
	glColor3f(1, 1, 1);
	glBegin(GL_LINES);
	glVertex3f(-1, 0, 0);
	glVertex3f(1, 0, 0);
	glVertex3f(0, 1, 0);
	glVertex3f(0, -1, 0);
	
	for (unsigned int x = 0; x < points.size(); x++)
	{
		if (points[x].val)
			glColor3f(0, 1, 0);
		else
			glColor3f(1, 0, 0);
		glVertex3f(points[x].loc.x-0.02, points[x].loc.y-0.02, 0);
		glVertex3f(points[x].loc.x+0.02, points[x].loc.y+0.02, 0);
		glVertex3f(points[x].loc.x-0.02, points[x].loc.y+0.02, 0);
		glVertex3f(points[x].loc.x+0.02, points[x].loc.y-0.02, 0);
	}
	glEnd();
	
	if (!CLASSIFIER)
	{
		glBegin(GL_LINE_STRIP);
		for (double x = -1; x <= 1; x += 1.0/64.0)
		{
			glColor3f(1, 1, 0);
			std::vector<double> in(2);
			in[0] = x;
			in[1] = x*x;
			double res = *l->test(in);
			res = (res-0.5)*scale;
			glVertex3f(x, res, 0);
		}
		glEnd();
	}
	else {
		glPointSize(4.0);
		glBegin(GL_POINTS);
		std::vector<double> in(3);
		for (double x = -1; x <= 1; x += 0.03125*0.5)
		{
			for (double y = -1; y <= 1; y += 0.03125*0.5)
			{
				in[0] = x;
				in[1] = y;
				in[2] = x*y;//sqrt(x*x+y*y);//x*y;
				double res = *cl->test(in);
				if (threshold)
				{
					if (res > 0.5)
						glColor4f(0, 1, 0, 0.75);
					else
						glColor4f(1, 0, 0, 0.75);
				}
				else {
					glColor3f((1-res)*(1-res), res*res, 0);
				}
				glVertex3f(x, y, 0);
			}
		}
		glEnd();
	}
}
Exemplo n.º 16
0
void GLUTRedraw(void)
{
  // Check scene
  if (!scene) return;

  // Set viewing transformation
  viewer->Camera().Load();

  // Clear window
  RNRgb background = scene->Background();
  glClearColor(background.R(), background.G(), background.B(), 1.0);
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

  // Load lights
  LoadLights(scene);

  // Draw camera
  if (show_camera) {
    glDisable(GL_LIGHTING);
    glColor3d(1.0, 1.0, 1.0);
    glLineWidth(5);
    DrawCamera(scene);
    glLineWidth(1);
  }

  // Draw lights
  if (show_lights) {
    glDisable(GL_LIGHTING);
    glColor3d(1.0, 1.0, 1.0);
    glLineWidth(5);
    DrawLights(scene);
    glLineWidth(1);
  }

  // Draw rays
  if (show_rays) {
    glDisable(GL_LIGHTING);
    glColor3d(0.0, 1.0, 0.0);
    glLineWidth(3);
    DrawRays(scene);
    glLineWidth(1);
  }

  // Draw rays
  if (show_photons) {
    glDisable(GL_LIGHTING);
    glColor3d(1.0, 1.0, 1.0);
    glLineWidth(1);
    DrawPhotonPaths(scene);
    glLineWidth(1);
  }

  // Draw rays
  if (show_global_samples) {
    glDisable(GL_LIGHTING);
    glColor3d(1.0, 1.0, 1.0);
    glLineWidth(1);
    DrawGlobalSamples(scene);
    glLineWidth(1);
  }

  // Draw rays
  if (show_caustic_samples) {
    glDisable(GL_LIGHTING);
    glColor3d(1.0, 1.0, 1.0);
    glLineWidth(1);
    DrawCausticSamples(scene);
    glLineWidth(1);
  }

  // Draw scene nodes
  if (show_shapes) {
    glEnable(GL_LIGHTING);
    R3null_material.Draw();
    DrawShapes(scene, scene->Root());
    R3null_material.Draw();
  }

  // Draw bboxes
  if (show_bboxes) {
    glDisable(GL_LIGHTING);
    glColor3d(1.0, 0.0, 0.0);
    DrawBBoxes(scene, scene->Root());
  }

  // Draw frame time
  if (show_frame_rate) {
    char buffer[128];
    static RNTime last_time;
    double frame_time = last_time.Elapsed();
    last_time.Read();
    if ((frame_time > 0) && (frame_time < 10)) {
      glDisable(GL_LIGHTING);
      glColor3d(1.0, 1.0, 1.0);
      sprintf(buffer, "%.1f fps", 1.0 / frame_time);
      DrawText(R2Point(100, 100), buffer);
    }
  }

  // Capture screenshot image
  if (screenshot_image_name) {
    if (print_verbose) printf("Creating image %s\n", screenshot_image_name);
    R2Image image(GLUTwindow_width, GLUTwindow_height, 3);
    image.Capture();
    image.Write(screenshot_image_name);
    screenshot_image_name = NULL;
  }

  // Swap buffers
  glutSwapBuffers();
}
Exemplo n.º 17
0
void cc2DLabel::drawMeOnly3D(CC_DRAW_CONTEXT& context)
{
	assert(!m_points.empty());

	//standard case: list names pushing
	bool pushName = MACRO_DrawEntityNames(context);
	if (pushName)
	{
		//not particularily fast
		if (MACRO_DrawFastNamesOnly(context))
			return;
		glPushName(getUniqueIDForDisplay());
	}

    const float c_sizeFactor = 4.0f;
    bool loop = false;

	size_t count = m_points.size();
    switch (count)
    {
    case 3:
		{
			glPushAttrib(GL_COLOR_BUFFER_BIT);
			glEnable(GL_BLEND);

			//we draw the triangle
			glColor4ub(255,255,0,128);
			glBegin(GL_TRIANGLES);
			for (unsigned i=0; i<count; ++i)
				ccGL::Vertex3v(m_points[i].cloud->getPoint(m_points[i].index)->u);
			glEnd();

			glPopAttrib();
			loop=true;
		}
    case 2:
		{
			//segment width
			glPushAttrib(GL_LINE_BIT);
			glLineWidth(c_sizeFactor);

			//we draw the segments
			if (isSelected())
				glColor3ubv(ccColor::red);
			else
				glColor3ubv(ccColor::green);
			glBegin(GL_LINES);
			for (unsigned i=0; i<count; i++)
			{
				if (i+1<count || loop)
				{
					ccGL::Vertex3v(m_points[i].cloud->getPoint(m_points[i].index)->u);
					ccGL::Vertex3v(m_points[(i+1)%count].cloud->getPoint(m_points[(i+1)%count].index)->u);
				}
			}
			glEnd();
			glPopAttrib();
		}

    case 1:
		{
			//display point marker as spheres
			{
				if (!c_unitPointMarker)
				{
					c_unitPointMarker = QSharedPointer<ccSphere>(new ccSphere(1.0f,0,"PointMarker",12));
					c_unitPointMarker->showColors(true);
					c_unitPointMarker->setVisible(true);
					c_unitPointMarker->setEnabled(true);
				}
			
				//build-up point maker own 'context'
				CC_DRAW_CONTEXT markerContext = context;
				markerContext.flags &= (~CC_DRAW_ENTITY_NAMES); //we must remove the 'push name flag' so that the sphere doesn't push its own!
				markerContext._win = 0;

				if (isSelected() && !pushName)
					c_unitPointMarker->setTempColor(ccColor::red);
				else
					c_unitPointMarker->setTempColor(ccColor::magenta);

				for (unsigned i=0; i<count; i++)
				{
					glMatrixMode(GL_MODELVIEW);
					glPushMatrix();
					const CCVector3* P = m_points[i].cloud->getPoint(m_points[i].index);
					ccGL::Translate(P->x,P->y,P->z);
					glScalef(context.pickedPointsRadius,context.pickedPointsRadius,context.pickedPointsRadius);
					c_unitPointMarker->draw(markerContext);
					glPopMatrix();
				}
			}

			if (m_dispIn3D && !pushName) //no need to display label in point picking mode
			{
				QFont font(context._win->getTextDisplayFont()); //takes rendering zoom into account!
				//font.setPointSize(font.pointSize()+2);
				font.setBold(true);

				//draw their name
				glPushAttrib(GL_DEPTH_BUFFER_BIT);
				glDisable(GL_DEPTH_TEST);
				for (unsigned j=0; j<count; j++)
				{
					const CCVector3* P = m_points[j].cloud->getPoint(m_points[j].index);
					QString title = (count == 1 ? getName() : QString("P#%0").arg(m_points[j].index));
					context._win->display3DLabel(	title,
													*P + CCVector3(	context.pickedPointsTextShift,
																	context.pickedPointsTextShift,
																	context.pickedPointsTextShift),
													ccColor::magenta,
													font );
				}
				glPopAttrib();
			}
		}
    }

	if (pushName)
		glPopName();
}
Exemplo n.º 18
0
void CglList::Draw()
{
	// dont call Mouse[XY] if we're being used in CPreGame (when gu or mouse is still NULL)
	float mx = (gu && mouse) ? MouseX(mouse->lastx) : 0;
	float my = (gu && mouse) ? MouseY(mouse->lasty) : 0;

	glDisable(GL_TEXTURE_2D);
	glDisable(GL_ALPHA_TEST);
	glEnable(GL_BLEND);
	glLoadIdentity();
	glColor4f(0.2f,0.2f,0.2f,guiAlpha);
	DrawBox(box);

	glColor4f(1,1,0.4f,0.8f);
	font->glPrintAt(box.x1 + 0.01f, box.y2 - 0.05f, itemFontScale*0.7f, name.c_str());

	/****************************************
	* Insert Robert Diamond's section here *
	* <*****@*****.**> *
	****************************************/

	/****************************************
	* TODO: *
	* *
	* This part of the code will need some *
	* math, and it's been a while since I *
	* did any 3D coding... the idea is to *
	* keep the selected item in the middle *
	* 60% of the screen, but don't scroll *
	* till we reach one end, or the other *
	* of that boundary. We'd also need the *
	* "oldPlace" variable to do this *
	* properly. *
	* *
	****************************************
	// Get screen res, so that the selected item is always within the middle 60% of screen
	int iResX = configHandler.GetInt("XResolution", 1024);
	int iResY = configHandler.GetInt("YResolution", 768);

	// Keep tabs on the last place. change this ONLY AFTER a scroll
	static int siOldPlace = place;

	if (we're scrolling up) siOldPlace = place;
	if (we're scrolling down) siOldPlace = place;
	if (we're not scrolling) siOldPlace = siOldPlace;

	**************************************
	* Hey remove me when TODO is done XD *
	**************************************/

	int nCurIndex = 0; // The item we're on
	int nDrawOffset = 0; // The offset to the first draw item
	ContainerBox b = box;

	b.x1 += 0.01f;
	b.x2 -= 0.01f;

	// Get list started up here
	std::vector<std::string>::iterator ii = filteredItems->begin();
	// Skip to current selection - 3; ie: scroll
	while ((nCurIndex + 7) <= place && nCurIndex+13 <= filteredItems->size()) { ii++; nCurIndex++; }

	for (/*ii = items.begin()*/; ii != filteredItems->end() && nDrawOffset < 12; ii++)
	{
		glLoadIdentity();

		b.y2 = box.y2 - 0.06f - (nDrawOffset * 0.06f);
		b.y1 = b.y2 - 0.05f;

		// TODO lots of this should really be merged with GuiHandler.cpp
		// (as in, factor out the common code...)

		glColor4f(1,1,1,0.1f);
		DrawBox(b, GL_LINE_LOOP);

		if (nCurIndex == place) {
			glBlendFunc(GL_ONE, GL_ONE); // additive blending
			glColor4f(0.2f,0,0,1);
			DrawBox(b);
			glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
			glColor4f(1,0,0,0.5f);
			glLineWidth(1.49f);
			DrawBox(b, GL_LINE_LOOP);
			glLineWidth(1.0f);
		} else if (InBox(mx, my, b)) {
			glBlendFunc(GL_ONE, GL_ONE); // additive blending
			glColor4f(0,0,0.2f,1);
			DrawBox(b);
			glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
			glColor4f(1,1,1,0.5f);
			glLineWidth(1.49f);
			DrawBox(b, GL_LINE_LOOP);
			glLineWidth(1.0f);
		}

		const float dShadow = 0.002f;
		const float xStart = box.x1 + itemXMargin;
		const float yStart = b.y1 + 0.002f;

		glColor4f(0.0f, 0.0f, 0.0f, 0.8f);
		font->glPrintAt(xStart + dShadow, yStart - dShadow, itemFontScale, ii->c_str());

		glColor4f(1,1,1,0.8f);
		font->glPrintAt(xStart, yStart, itemFontScale, ii->c_str());

		// Up our index's
		nCurIndex++; nDrawOffset++;
	}
	/**************
	* End insert *
	**************/
	glLoadIdentity();
}
Exemplo n.º 19
0
void CylinderPrimitive::initContext(GLContextData& contextData) const
	{
	/* Create a data item and store it in the context: */
	DataItem* dataItem=new DataItem;
	contextData.addDataItem(this,dataItem);
	
	/* Create a coordinate system for the cylinder: */
	Vector cx=Geometry::normal(axis);
	cx.normalize();
	Vector cy=Geometry::cross(axis,cx);
	cy.normalize();
	Vector cz=axis*(length/Scalar(2));
	
	/* Create the cylinder rendering display lists: */
	glNewList(dataItem->displayListId,GL_COMPILE);
	
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	glDisable(GL_CULL_FACE);
	glBegin(GL_QUAD_STRIP);
	glNormal(1.0,0.0,0.0);
	glVertex(center+cx*radius+cz);
	glVertex(center+cx*radius-cz);
	for(int x=1;x<72;++x)
		{
		Scalar angle=Math::rad(Scalar(x)*Scalar(360/72));
		Vector d=cx*Math::cos(angle)+cy*Math::sin(angle);
		glNormal(d);
		d*=radius;
		glVertex(center+d+cz);
		glVertex(center+d-cz);
		}
	glNormal(1.0,0.0,0.0);
	glVertex(center+cx*radius+cz);
	glVertex(center+cx*radius-cz);
	glEnd();
	
	glEndList();
	
	glNewList(dataItem->displayListId+1,GL_COMPILE);
	
	glBlendFunc(GL_ONE,GL_ONE);
	glLineWidth(1.0f);
	glBegin(GL_LINES);
	for(int x=0;x<numX;++x)
		{
		Scalar angle=Math::rad(Scalar(x)*Scalar(360)/Scalar(numX));
		Vector d=cx*Math::cos(angle)+cy*Math::sin(angle);
		d*=radius;
		glVertex(center+d+cz);
		glVertex(center+d-cz);
		}
	glEnd();
	for(int y=0;y<=numY;++y)
		{
		Point center2=center+axis*((Scalar(y)/Scalar(numY)-Scalar(0.5))*length);
		glBegin(GL_LINE_LOOP);
		for(int x=0;x<72;++x)
			{
			Scalar angle=Math::rad(Scalar(x)*Scalar(360/72));
			Vector d=cx*Math::cos(angle)+cy*Math::sin(angle);
			d*=radius;
			glVertex(center2+d);
			}
		glEnd();
		}
	
	glEndList();
	}
Exemplo n.º 20
0
//
// Draw_Title
//
void Draw_Title(void)
{
	float offset = 34.0f;
	float begin = 120.0f;


	// Also draw game over
	// if it is turned on
	if (ant_globals->_menu_state == MENU_DEAD_MODE) {

		Draw_GameOver();
	} // end of the  if 


	switch(ant_globals->menu_mode)
	{

		case MENU_HELP_MODE:
			
			glLineWidth(2.0f);

			Title_Begin();
			
			Draw_HelpScreen();
			
	
			glDisable(GL_LIGHTING);

			Draw_IntroScreen();

			glEnable(GL_LIGHTING);


			Title_End();
			glLineWidth(1.0f);

			
		break;

		case MENU_TITLE_MODE:
			glLineWidth(2.0f);

			Title_Begin();

			Draw_Shadow();

			glColor4ub(255,255,255,255);
			
			// title, newgame, exit, demo
			if (cursor_index == 0)
				glColor4ub(255,255,0,255);
				Render_BText(6, 192.0f, begin+(0*offset), 0.03f);

			glColor4ub(255,255,255,255);
			if (cursor_index == 1)
				glColor4ub(255,255,0,255);
			Render_BText(5, 192.0f, begin+(1*offset), 0.016f);

			glColor4ub(255,255,255,255);
			if (cursor_index == 2)
				glColor4ub(255,255,0,255);
			Render_BText(4, 192.0f, begin+(2*offset), -0.015f);

			glColor4ub(255,255,255,255);
			if (cursor_index == 3)
				glColor4ub(255,255,0,255);
			Render_BText(3, 192.0f, begin+(3*offset), -0.041f);

			glColor4ub(255,255,255,255);
			if (cursor_index == 4)
				glColor4ub(255,255,0,255);
			Render_BText(1, 192.0f, begin+(4*offset), 0.01f);

			// draw the selection tool --
			Draw_Cursor(cursor_heights[cursor_index]);

			//Draw_HelpScreen();
			Draw_IntroScreen();

			Title_End();

			glLineWidth(1.0f);

		break;

		default: break;
	};
		
} // end of the function
Exemplo n.º 21
0
/**
 * Method for create a window
 */
void Visualizer::createWindow(const char * title)
{
        xnew=0; ynew=0; znew=0;                   /* actual position */
        xold=0; yold=0; zold=0;                   /* old position */
        xx1=0; yy1=0; zz1=0;                      /* mouse position*/
        mouseState=0;                             /* mouse button state */
        xshift=0; yshift=0;                       /* shifting in space*/

        xnew=0; ynew=0; znew=0;                   /* actual position */
        xold=0; yold=0; zold=0;                   /* old position */
        xx1=0; yy1=0; zz1=0;                      /* mouse position*/
        mouseState=0;                             /* mouse button state */
        xshift=0; yshift=0;                       /* shifting in space*/

	fov=45.0;                                 /* field of view */
	near_plane=1;                             /* trim plain */
	far_plane=1000.0;                         /* farther trim plain */
	line_width=1.0;                           /* width of line */
	WindowWidth=1024;                         /* width and height of window */
	WindowHeight=768;
	ObjectType=0;                             /* type of paint object */
	Solid=1;                                  /* fill or wireframe model */

	char * dummy_argv[1];
	dummy_argv[0] = const_cast<char *>("run");
	int dummy_argc = 1;

	glutInit(&dummy_argc, dummy_argv);

	glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE ); /* graphic mod of window */

        glutInitWindowSize(WindowWidth,WindowHeight); /* original window size */
        glutInitWindowPosition(10,10);                /* original window position */
        glutCreateWindow(title);                      /* create window */

        glutDisplayFunc(onDisplay);                   /* set function for redisplay */
        glutReshapeFunc(onReshape);                   /* set function for change of size window */
        glutKeyboardFunc(onKeyboard);                 /* set function for press key */
        glutSpecialFunc(onSpecial);
        glutMouseFunc(onMouseClick);                  /* set function for press mouse button */
        glutMotionFunc(onMouseMotion);                /* set function for mouse move */

        glClearColor(0.0, 0.0, 0.0, 0.0);             /* color for clearing of color-buffer */
        glClearDepth(1.0f);                           /* color for clearing of z-buffer */
        glEnable(GL_DEPTH_TEST);                      /* configure function for testing value in z-buffer */
        glDepthFunc(GL_LESS);                         /* select function */
        glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); /* improvement display */

        glEnable(GL_CULL_FACE);
        glPolygonMode(GL_FRONT, GL_FILL);             /* configure draw of fill polygons */
        //glCullFace(GL_FRONT);

        glLineWidth(line_width);                      /* line width */
	glPointSize(line_width);

	//glEnable(GL_MULTISAMPLE);
#ifdef FREEGLUT
    #ifdef GLUT_AUX
	int *sampleNumbers = NULL;
	int sampleNumbersSize = 0;
	sampleNumbers = glutGetModeValues(GLUT_MULTISAMPLE, &sampleNumbersSize);
	if(sampleNumbers != NULL)
	{
		glutSetOption(GLUT_MULTISAMPLE, sampleNumbers[sampleNumbersSize - 1]);
		printf("Multisampling with %i samples.\n", sampleNumbers[sampleNumbersSize - 1]);
		free(sampleNumbers);
	}
	else
	{
		printf("Multisampling is not available.\n");
	}
    #endif
#endif

        scene_ = glGenLists(1);                        /* get number of calllist */
        createCallList();                             /* initialization */

	glutMainLoop();
}
Exemplo n.º 22
0
// Affichage de la scène
void SceneToon::Render()
{
	ResourceManager& res = ResourceManager::getInstance();
	VarManager& var = VarManager::getInstance();

	glPushAttrib(GL_ENABLE_BIT | GL_POLYGON_BIT | GL_LINE_BIT);

		vec4 white(1.0f, 1.0f, 1.0f, 1.0f);
		vec4 red(1.0f, 0.0f, 0.0f, 1.0f);
		vec4 blue(0.0f, 0.0f, 1.0f, 1.0f);
		vec4 zeros(0.0f, 0.0f, 0.0f, 0.0f);
		vec4 marron(0.95, 0.6, 0.25,1.0);
		vec4 jaune(1.0, 0.8, 0.0,1.0);

		glColor3f(1.0f, 1.0f, 1.0f);
		glPushMatrix();
			glDisable(GL_LIGHTING);
			glTranslatef(m_vLightPos.x, m_vLightPos.y, m_vLightPos.z);
			glutSolidSphere(0.1, 16, 16);
		glPopMatrix();

		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
		glLightfv(GL_LIGHT0, GL_POSITION, m_vLightPos);
		glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, zeros);
		glLightfv(GL_LIGHT0, GL_AMBIENT, &white.r);
		glLightfv(GL_LIGHT0, GL_DIFFUSE, white);
		glLightfv(GL_LIGHT0, GL_SPECULAR, white);
		glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 1.0f/512);
		glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, 1.0f/512);


	//	glDisable(GL_CULL_FACE);
		
	

		m_shadeToon->Activate();
		{
			m_shadeToon->UniformTexture("myText", 0);
			m_shadeToon->Uniform("enable_texture", true);


			glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, white/4);
			glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, white/2);
			glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, zeros);
			glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 60.0f);
			
			// Le sol
			m_pMyTexGround->Bind(0);
			m_pScene->Draw(0);
			m_pMyTexGround->Unbind(0);	

			//Les murs
			m_pMyTexWall->Bind(0);
			m_pScene->Draw(3);
			m_pMyTexWall->Unbind(0);	

			// Le plafond
			m_pMyTexTop->Bind(0);
			m_pScene->Draw(1);
			m_pMyTexTop->Unbind(0);

			m_shadeToon->Uniform("enable_texture", false);
			
			glPushMatrix();
			{
				glTranslatef(0.0,4.0,0.0);
				// TORE
				glPushMatrix();
				{
					glRotatef(m_fAngle, 1.0f, 1.0f, 0.0f);
					glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, red/4);
					glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, red/2);
					glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white);
					glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 60.0f);
					glutSolidTorus(1.0,3.0,100,100);
				}
				glPopMatrix();

				// TEAPOT
				glPushMatrix();
				{
					glTranslatef(0.0,0.0,-12.0);
					glRotatef(m_fAngle, 0.0f, 1.0f, 0.0f);
					glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, marron/4);
					glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, marron/2);
					glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white);
					glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 60.0f);
					m_teapot->Draw();
				}
				glPopMatrix();

				// LAPIN
				glPushMatrix();
				{
					glTranslatef(0.0,2.0,9.0);
					glScalef(25.0,25.0,25.0);
					glRotatef(m_fAngle, 0.0f, 1.0f, 0.0f);
					glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, jaune/4);
					glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, jaune/2);
					glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white);
					glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 60.0f);				
					m_objHomer->Draw();
				}
				glPopMatrix();
			}
			glPopMatrix();
		}
		m_shadeToon->Deactivate();


	// Affichage des contours

	glDisable(GL_LIGHTING);
	glLineWidth(5.0);
	glPolygonMode(GL_BACK, GL_LINE);
	glDepthFunc(GL_LEQUAL);
	glCullFace(GL_FRONT);
	glColor3f(0.0,0.0,0.0);


			glPushMatrix();
			{
				glTranslatef(0.0,4.0,0.0);
				// TORE
				glPushMatrix();
				{
					glRotatef(m_fAngle, 1.0f, 1.0f, 0.0f);
					glutSolidTorus(1.0,3.0,100,100);
				}
				glPopMatrix();

				// TEAPOT
				glPushMatrix();
				{
					glTranslatef(0.0,0.0,-12.0);
					glRotatef(m_fAngle, 0.0f, 1.0f, 0.0f);
					m_teapot->Draw();
				}
				glPopMatrix();

				// LAPIN
				glPushMatrix();
				{
					glTranslatef(0.0,2.0,9.0);
					glScalef(25.0,25.0,25.0);
					glRotatef(m_fAngle, 0.0f, 1.0f, 0.0f);			
					m_objHomer->Draw();
				}
				glPopMatrix();
			}
			glPopMatrix();


	glPopAttrib();

}
Exemplo n.º 23
0
/* CTextureCanvas::drawTextureBorder
 * Draws a black border around the texture
 *******************************************************************/
void CTextureCanvas::drawTextureBorder()
{
	// Draw the texture border
	double ext = 0.11;
	glLineWidth(2.0f);
	OpenGL::setColour(COL_BLACK);
	glBegin(GL_LINE_LOOP);
	glVertex2d(-ext, -ext);
	glVertex2d(-ext, texture->getHeight()+ext);
	glVertex2d(texture->getWidth()+ext, texture->getHeight()+ext);
	glVertex2d(texture->getWidth()+ext, -ext);
	glEnd();
	glLineWidth(1.0f);

	// Draw vertical ticks
	int y = 0;
	glColor4f(0.0f, 0.0f, 0.0f, 0.6f);
	while (y <= texture->getHeight())
	{
		glBegin(GL_LINES);
		glVertex2i(-4, y);
		glVertex2i(0, y);
		glVertex2i(texture->getWidth(), y);
		glVertex2i(texture->getWidth() + 4, y);
		glEnd();

		y += 8;
	}

	// Draw horizontal ticks
	int x = 0;
	while (x <= texture->getWidth())
	{
		glBegin(GL_LINES);
		glVertex2i(x, -4);
		glVertex2i(x, 0);
		glVertex2i(x, texture->getHeight());
		glVertex2i(x, texture->getHeight() + 4);
		glEnd();

		x += 8;
	}

	// Draw grid
	if (show_grid)
	{
		// Draw inverted grid lines
		glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO);
		glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

		// Vertical
		y = 8;
		while (y <= texture->getHeight() - 8)
		{
			glBegin(GL_LINES);
			glVertex2i(0, y);
			glVertex2i(texture->getWidth(), y);
			glEnd();

			y += 8;
		}

		// Horizontal
		x = 8;
		while (x <= texture->getWidth() - 8)
		{
			glBegin(GL_LINES);
			glVertex2i(x, 0);
			glVertex2i(x, texture->getHeight());
			glEnd();

			x += 8;
		}


		// Darken grid lines
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glColor4f(0.0f, 0.0f, 0.0f, 0.5f);

		// Vertical
		y = 8;
		while (y <= texture->getHeight() - 8)
		{
			glBegin(GL_LINES);
			glVertex2i(0, y);
			glVertex2i(texture->getWidth(), y);
			glEnd();

			y += 8;
		}

		// Horizontal
		x = 8;
		while (x <= texture->getWidth() - 8)
		{
			glBegin(GL_LINES);
			glVertex2i(x, 0);
			glVertex2i(x, texture->getHeight());
			glEnd();

			x += 8;
		}
	}
}
Exemplo n.º 24
0
void TableMap3D::paintGL()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();
	glTranslatef(0,0,-2.4); //Move back 3 units
	glRotatef(m_xrot, 1.0, 0.0, 0.0); //Rotate it up/down
	glRotatef(m_yrot, 0.0, 0.0, 1.0); //Rotate it left/right
	glTranslatef(-0.5,-1+(0.5 * ((double)m_tableData->yAxis().size() / (double)m_tableData->xAxis().size())),-0.5); //Center the graph in view
	//float minx = 0;
	float maxx = 1;
	float miny = 0;
	float maxy = 1;
	if (m_tableData->xAxis().size() < m_tableData->yAxis().size())
	{
		maxx = maxy * ((float)m_tableData->yAxis().size()/(float)m_tableData->xAxis().size());
	}
	else
	{
		maxy = maxx * ((float)m_tableData->xAxis().size() / (float)m_tableData->yAxis().size());
	}
	Q_UNUSED(miny);
	glColor4f(1,1,1,1);


	//Draw 10 horizontal lines for VE values
	for (int i=0;i<=10;i++)
	{
		glBegin(GL_LINE_STRIP);
		glVertex3f(maxx/*-(((float)1)/((float)m_tableData->xAxis().size()))*/,0,(float)i/10.0);
		glVertex3f(maxx/*-(((float)1)/((float)m_tableData->xAxis().size()))*/,maxy/*+((float)2)/((float)m_tableData->xAxis().size())*/,(float)i/10.0);
		glVertex3f(0,maxy/*+((float)2)/((float)m_tableData->xAxis().size())*/,(float)i/10.0);
		glEnd();
		this->renderText(-0.1,maxy + 0.1,(float)i/10.0,QString::number((m_tableData->maxZAxis()) * (i/10.0),'f',2));
	}


	//Longer X axis (RPM)
	for (int i=0;i<m_tableData->xAxis().size();i+=1)
	{
		glBegin(GL_LINES);
		float tmpf2=0;
		tmpf2 = (float)(i * maxy)/((float)m_tableData->xAxis().size());
		glVertex3f(maxx,tmpf2 * (maxx / 1.0),0);
		glVertex3f(maxx,tmpf2 * (maxx / 1.0),1);
		glEnd();
		//this->renderText(0,tmpf2,-0.05,QString::number(m_tableData->xAxis()[i]));
	}

	//Shorter Y Axis (KPA)
	for (int i=0;i<m_tableData->yAxis().size();i+=1)
	{
		glBegin(GL_LINES);
		float tmpf1 = (float)(i * maxx)/((float)m_tableData->yAxis().size());
		glVertex3f(tmpf1 * (maxx / 1.0),maxy,0);
		glVertex3f(tmpf1 * (maxx / 1.0),maxy,1);
		glEnd();
		//this->renderText(0,tmpf1,-0.05,QString::number(m_tableData->yAxis()[i]));
	}

	//Middle vertical
	glBegin(GL_LINES);
	glVertex3f(maxx,maxy,0);
	glVertex3f(maxx,maxy,1);
	glEnd();

	//Line around the top of the graph
	glBegin(GL_LINE_STRIP);
	glVertex3f(0,maxy,1);
	glVertex3f(maxx,maxy,1);
	glVertex3f(maxx,0,1);
	glEnd();


	//Square outline around the bottom of the graph
	glBegin(GL_LINE_STRIP);
	glVertex3f(0,maxy,0);
	glVertex3f(0,0,0);
	glVertex3f(maxx,0,0);
	glVertex3f(maxx,maxy,0);
	glVertex3f(0,maxy,0);
	glEnd();
	for(int x=0;x<m_tableData->xAxis().size()-1;x++)
	{
		for (int i=0;i<3;i++)
		{
			if (i == 0 || i == 2)
			{
				glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
				//glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
				glBlendFunc(GL_ONE, GL_ZERO);
				glLineWidth(1.25);
			}
			else if (i == 1)
			{
				glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
				glBlendFunc(GL_ONE, GL_ZERO);
				glLineWidth(1.25);
			}
			glBegin(GL_QUADS);
			for(int y=0;y<m_tableData->yAxis().size()-1;y++)
			{
				double r=0;
				double g=0;
				double b=0;
				double val = m_tableData->values()[y][x];
				if (val < m_tableData->maxZAxis()/4)
				{
					r=0;
					g=(255*((val)/(m_tableData->maxZAxis()/4.0)));
					b=255;
				}
				else if (val < ((m_tableData->maxZAxis()/4)*2))
				{
					r=0;
					g=255;
					b=255-(255*((val-((m_tableData->maxZAxis()/4.0)))/(m_tableData->maxZAxis()/4.0)));
				}
				else if (val < ((m_tableData->maxZAxis()/4)*3))
				{
					r=(255*((val-((m_tableData->maxZAxis()/4.0)*2))/(m_tableData->maxZAxis()/4.0)));
					g=255;
					b=0;
				}
				else
				{
					r=255;
					g=255-(255*((val-((m_tableData->maxZAxis()/4.0)*3))/(m_tableData->maxZAxis()/4.0)));
					b=0;
				}
				if (i == 0 || i == 2)
				{
					r = 0;
					g = 0;
					b = 0;
				}
				else if (i == 1)
				{
					r = r/255.0;
					g = g/255.0;
					b = b/255.0;
				}

				//X and Y are reversed here, to allow for the graph to look the proper way.

				float y0 = ((float)x * maxy)/((float)m_tableData->xAxis().size()-1.0);
				float x0 = ((float)y)/((float)m_tableData->yAxis().size()-1.0);
				float z0 = (float)m_tableData->values()[y][x] / m_tableData->maxZAxis();
				glColor4f(r,g,b,1);
				//glVertex3f(x0+((i==1) ? MAP3DCELLSPACING : 0),(maxy-y0)-((i==1) ? MAP3DCELLSPACING : 0),z0);
				glVertex3f(x0,(maxy-y0),z0+((i==0) ? 0.001 : ((i==2) ? -0.001 : 0)));

				float y1 = ((float)x * maxy)/((float)m_tableData->xAxis().size()-1.0);
				float x1 = ((float)y+1)/((float)m_tableData->yAxis().size()-1.0);
				float z1 = (float)m_tableData->values()[y+1][x] / m_tableData->maxZAxis();
				glColor4f(r,g,b,1);
				//glVertex3f(x1-((i==1) ? MAP3DCELLSPACING : 0),(maxy-y1)-((i==1) ? MAP3DCELLSPACING : 0),z1);
				glVertex3f(x1,(maxy-y1),z1+((i==0) ? 0.001 : ((i==2) ? -0.001 : 0)));

				float y2 = ((float)((x+1.0) * maxy))/((float)m_tableData->xAxis().size()-1.0);
				float x2 = ((float)y+1.0)/((float)m_tableData->yAxis().size()-1.0);
				float z2 = (float)m_tableData->values()[y+1][x+1] / m_tableData->maxZAxis();
				glColor4f(r,g,b,1);
				//glVertex3f(x2-((i==1) ? MAP3DCELLSPACING : 0),(maxy-y2)+((i==1) ? MAP3DCELLSPACING : 0),z2);
				glVertex3f(x2,(maxy-y2),z2+((i==0) ? 0.001 : ((i==2) ? -0.001 : 0)));

				float y3 = ((float)(x+1) * maxy)/((float)m_tableData->xAxis().size()-1.0);
				float x3 = ((float)y)/((float)m_tableData->yAxis().size()-1.0);
				float z3 = (float)m_tableData->values()[y][x+1]/m_tableData->maxZAxis();
				glColor4f(r,g,b,1);
				//glVertex3f(x3+((i==1) ? MAP3DCELLSPACING : 0),(maxy-y3)+((i==1) ? MAP3DCELLSPACING : 0),z3);
				glVertex3f(x3,(maxy-y3),z3+((i==0) ? 0.001 : ((i==2) ? -0.001 : 0)));
			}
			glEnd();
		}
	}
}
Exemplo n.º 25
0
void	MD5Node::DebugDrawJointTransforms(float size, bool worldSpace) {
	//Temporary VAO and VBO
	unsigned int skeletonArray;
	unsigned int skeletonBuffer;
	unsigned int skeletonColourBuffer;

	glGenVertexArrays(1, &skeletonArray);
	glGenBuffers(1, &skeletonBuffer);
	glGenBuffers(1, &skeletonColourBuffer);
	//Temporary chunk of memory to keep our joint positions in

	int numVerts = currentSkeleton.numJoints * 6;

	Vector3*	 skeletonVertices = new Vector3[numVerts];
	Vector4*	 skeletonColours = new Vector4[numVerts];


	for (int i = 0; i < currentSkeleton.numJoints; ++i) {
		Matrix4 transform = (worldSpace ? currentSkeleton.joints[i].transform : currentSkeleton.joints[i].localTransform);

		Vector3 start = transform.GetPositionVector();
		transform.SetPositionVector(Vector3(0, 0, 0));

		Vector4 endX = transform * Vector4(1, 0, 0, 1);
		Vector4 endY = transform * Vector4(0, 1, 0, 1);
		Vector4 endZ = transform * Vector4(0, 0, 1, 1);

		skeletonVertices[(i * 6) + 0] = currentSkeleton.joints[i].transform.GetPositionVector();
		skeletonVertices[(i * 6) + 1] = currentSkeleton.joints[i].transform.GetPositionVector() + (endX.ToVector3() * size);

		skeletonVertices[(i * 6) + 2] = currentSkeleton.joints[i].transform.GetPositionVector();
		skeletonVertices[(i * 6) + 3] = currentSkeleton.joints[i].transform.GetPositionVector() + (endY.ToVector3() * size);

		skeletonVertices[(i * 6) + 4] = currentSkeleton.joints[i].transform.GetPositionVector();
		skeletonVertices[(i * 6) + 5] = currentSkeleton.joints[i].transform.GetPositionVector() + (endZ.ToVector3() * size);


		skeletonColours[(i * 6) + 0] = Vector4(1, 0, 0, 1);
		skeletonColours[(i * 6) + 1] = Vector4(1, 0, 0, 1);

		skeletonColours[(i * 6) + 2] = Vector4(0, 1, 0, 1);
		skeletonColours[(i * 6) + 3] = Vector4(0, 1, 0, 1);

		skeletonColours[(i * 6) + 4] = Vector4(0, 0, 1, 1);
		skeletonColours[(i * 6) + 5] = Vector4(0, 0, 1, 1);
	}

	//You should know what this all does by now, except we combine it with the draw operations in a single function
	glBindVertexArray(skeletonArray);
	glBindBuffer(GL_ARRAY_BUFFER, skeletonBuffer);
	glBufferData(GL_ARRAY_BUFFER, currentSkeleton.numJoints*sizeof(Vector3) * 6, skeletonVertices, GL_STREAM_DRAW);
	glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
	glEnableVertexAttribArray(0);

	glBindBuffer(GL_ARRAY_BUFFER, skeletonColourBuffer);
	glBufferData(GL_ARRAY_BUFFER, currentSkeleton.numJoints*sizeof(Vector4) * 6, skeletonColours, GL_STREAM_DRAW);
	glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 0, 0);
	glEnableVertexAttribArray(1);

	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, 0);

	glLineWidth(2.0f);
	glDrawArrays(GL_LINES, 0, currentSkeleton.numJoints * 6);	// draw Bones
	glLineWidth(1.0f);

	glBindVertexArray(0);

	//Delete the VBO and VAO, and the heap memory we allocated earlier
	glDeleteVertexArrays(1, &skeletonArray);
	glDeleteBuffers(1, &skeletonBuffer);
	glDeleteBuffers(1, &skeletonColourBuffer);

	delete[]skeletonVertices;
	delete[]skeletonColours;
}
Exemplo n.º 26
0
void SpaceShip::draw() {
	Point abc[4];

	// Right & Left Carriers
	glLineWidth(2);
	glColor3f(0.799, 0.1098, 0.0588);

	glBegin(GL_TRIANGLE_STRIP);
	glVertex2i(startX + 10, (startY + 0));
	glVertex2i(startX + 20, (startY + 10));
	glVertex2i(startX + 7, (startY + 23));
	glVertex2i(startX + 17, (startY + 30));
	glEnd();

	glBegin(GL_TRIANGLE_STRIP);
	glVertex2i(startX + 68, (startY + 0));
	glVertex2i(startX + 58, (startY + 10));
	glVertex2i(startX + 72, (startY + 23));
	glVertex2i(startX + 62, (startY + 30));
	glEnd();

	// Main Body
	glLineWidth(4);
	glColor3f(0.925, 0.925, 0.925);

	abc[0].setxy(startX + 22, (startY + 9));
	abc[1].setxy(startX + 14, (startY + 28));
	abc[2].setxy(startX + 16, (startY + 86));
	abc[3].setxy(startX + 39, (startY + 97));
	basicShapes.drawCurve(abc[0], abc[1], abc[2], abc[3]);

	abc[0].setxy(startX + 56, (startY + 9));
	abc[1].setxy(startX + 66, (startY + 28));
	abc[2].setxy(startX + 62, (startY + 86));
	abc[3].setxy(startX + 39, (startY + 97));
	basicShapes.drawCurve(abc[0], abc[1], abc[2], abc[3]);

	abc[0].setxy(startX + 22, (startY + 9));
	abc[1].setxy(startX + 34, (startY + 16));
	abc[2].setxy(startX + 44, (startY + 16));
	abc[3].setxy(startX + 56, (startY + 9));
	basicShapes.drawCurve(abc[0], abc[1], abc[2], abc[3]);

	basicShapes.solidCircle(startX + 39, (startY + 82), 13);
	basicShapes.solidCircle(startX + 39, (startY + 65), 20);
	basicShapes.solidCircle(startX + 39, (startY + 53), 22);
	basicShapes.solidCircle(startX + 39, (startY + 35), 23);
	basicShapes.solidCircle(startX + 27, (startY + 20), 9);
	basicShapes.solidCircle(startX + 52, (startY + 20), 9);

	// Glass Window
	glColor3f(0.827, 0.96, 1);
	basicShapes.solidCircle(startX + 39, (startY + 60), 10);

	// Middle Carrier
	glLineWidth(2.8);
	glColor3f(0.799, 0.1098, 0.0588);

	glBegin(GL_LINES);
	glVertex2i(startX + 39, (startY + 0));
	glVertex2i(startX + 39, (startY + 30));
	glEnd();

	// Glass Frame
	glLineWidth(2);
	basicShapes.hallowCircle(startX + 39, (startY + 60), 10);

}
Exemplo n.º 27
0
void FenceSegment::render() const
{
   // HAUKAP - need spike::render to reduce code
   glPushMatrix();
   {
      glTranslatef( m_point.x, m_point.y, m_point.z);
      glRotatef( m_fenceAngle, 0.0f, 0.0f, 1.0f);
      glLineWidth(1);
      //glColor3f(0.0f, 0.0f, 0.0f);
      glScalef( m_scale, m_scale, m_scale );

      // first spike 
      glPushMatrix();
      {
         glRotatef( m_spikeAngles[0], 0.0f, 0.0f, 1.0f);         
         glBegin( GL_LINES );
            glVertex3f( 0, 0, 0.0f );
            glVertex3f( 0, 1.0, 0.0f);
         glEnd();  
      }
      glPopMatrix();

      // second spike 
      glPushMatrix();
      {
         glRotatef( m_spikeAngles[1], 0.0f, 0.0f, 1.0f);
         glBegin( GL_LINES );
            glVertex3f( 0, 0, 0.0f );
            glVertex3f( 0, 1.0, 0.0f);
         glEnd();  
      }
      glPopMatrix();
      
      // third spike 
      glPushMatrix();
      {
         glRotatef( m_spikeAngles[2], 0.0f, 0.0f, 1.0f);
         glBegin( GL_LINES );
            glVertex3f( 0, 0, 0.0f );
            glVertex3f( 0, 1.0, 0.0f);
         glEnd();  
      }
      glPopMatrix();

      // fourth spike 
      glPushMatrix();
      {
         glRotatef( m_spikeAngles[3], 0.0f, 0.0f, 1.0f);
         glBegin( GL_LINES );
            glVertex3f( 0, 0, 0.0f );
            glVertex3f( 0, 1.0, 0.0f);
         glEnd();  
      }
      glPopMatrix();

      // fifth spike 
      glPushMatrix();
      {
         glRotatef( m_spikeAngles[4], 0.0f, 0.0f, 1.0f);
         glBegin( GL_LINES );
            glVertex3f( 0, 0, 0.0f );
            glVertex3f( 0, 1.0, 0.0f);
         glEnd();  
      }
      glPopMatrix();
   }
   glPopMatrix();

}
Exemplo n.º 28
0
void GLGSRender::ExecCMD()
{
	//return;
	if(!LoadProgram())
	{
		ConLog.Error("LoadProgram failed.");
		Emu.Pause();
		return;
	}

	if(!m_fbo.IsCreated() || RSXThread::m_width != last_width || RSXThread::m_height != last_height || last_depth_format != m_surface_depth_format)
	{
		ConLog.Warning("New FBO (%dx%d)", RSXThread::m_width, RSXThread::m_height);
		last_width = RSXThread::m_width;
		last_height = RSXThread::m_height;
		last_depth_format = m_surface_depth_format;

		m_fbo.Create();
		checkForGlError("m_fbo.Create");
		m_fbo.Bind();

		m_rbo.Create(4 + 1);
		checkForGlError("m_rbo.Create");

		for(int i=0; i<4; ++i)
		{
			m_rbo.Bind(i);
			m_rbo.Storage(GL_RGBA, RSXThread::m_width, RSXThread::m_height);
			checkForGlError("m_rbo.Storage(GL_RGBA)");
		}

		m_rbo.Bind(4);

		switch(m_surface_depth_format)
		{
		case 1:
			m_rbo.Storage(GL_DEPTH_COMPONENT16, RSXThread::m_width, RSXThread::m_height);
			checkForGlError("m_rbo.Storage(GL_DEPTH_COMPONENT16)");
		break;

		case 2:
			m_rbo.Storage(GL_DEPTH24_STENCIL8, RSXThread::m_width, RSXThread::m_height);
			checkForGlError("m_rbo.Storage(GL_DEPTH24_STENCIL8)");
		break;

		default:
			ConLog.Error("Bad depth format! (%d)", m_surface_depth_format);
			assert(0);
		break;
		}

		for(int i=0; i<4; ++i)
		{
			m_fbo.Renderbuffer(GL_COLOR_ATTACHMENT0 + i, m_rbo.GetId(i));
			checkForGlError(wxString::Format("m_fbo.Renderbuffer(GL_COLOR_ATTACHMENT%d)", i));
		}

		m_fbo.Renderbuffer(GL_DEPTH_ATTACHMENT, m_rbo.GetId(4));
		checkForGlError("m_fbo.Renderbuffer(GL_DEPTH_ATTACHMENT)");

		if(m_surface_depth_format == 2)
		{
			m_fbo.Renderbuffer(GL_STENCIL_ATTACHMENT, m_rbo.GetId(4));
			checkForGlError("m_fbo.Renderbuffer(GL_STENCIL_ATTACHMENT)");
		}
	}

	if(!m_set_surface_clip_horizontal)
	{
		m_surface_clip_x = 0;
		m_surface_clip_w = RSXThread::m_width;
	}

	if(!m_set_surface_clip_vertical)
	{
		m_surface_clip_y = 0;
		m_surface_clip_h = RSXThread::m_height;
	}
		
	m_fbo.Bind();
	if(Ini.GSDumpDepthBuffer.GetValue())
		WriteDepthBuffer();
	static const GLenum draw_buffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3 };

	switch(m_surface_colour_target)
	{
	case 0x0:
		break;

	case 0x1:
		glDrawBuffer(draw_buffers[0]);
	break;

	case 0x2:
		glDrawBuffer(draw_buffers[1]);
	break;

	case 0x13:
		glDrawBuffers(2, draw_buffers);
	break;

	case 0x17:
		glDrawBuffers(3, draw_buffers);
	break;

	case 0x1f:
		glDrawBuffers(4, draw_buffers);
	break;

	default:
		ConLog.Error("Bad surface colour target: %d", m_surface_colour_target);
	break;
	}

	if(m_set_color_mask)
	{
		glColorMask(m_color_mask_r, m_color_mask_g, m_color_mask_b, m_color_mask_a);
		checkForGlError("glColorMask");
	}

	if(m_set_viewport_horizontal && m_set_viewport_vertical)
	{
		glViewport(m_viewport_x, RSXThread::m_height-m_viewport_y-m_viewport_h, m_viewport_w, m_viewport_h);
		checkForGlError("glViewport");
	}

	if(m_set_scissor_horizontal && m_set_scissor_vertical)
	{
		glScissor(m_scissor_x, RSXThread::m_height-m_scissor_y-m_scissor_h, m_scissor_w, m_scissor_h);
		checkForGlError("glScissor");
	}

	if(m_clear_surface_mask)
	{
		GLbitfield f = 0;

		if (m_clear_surface_mask & 0x1)
		{
			glClearDepth(m_clear_surface_z / (float)0xffffff);

			f |= GL_DEPTH_BUFFER_BIT;
		}

		if (m_clear_surface_mask & 0x2)
		{
			glClearStencil(m_clear_surface_s);

			f |= GL_STENCIL_BUFFER_BIT;
		}

		if (m_clear_surface_mask & 0xF0)
		{
			glClearColor(
				m_clear_surface_color_r / 255.0f,
				m_clear_surface_color_g / 255.0f,
				m_clear_surface_color_b / 255.0f,
				m_clear_surface_color_a / 255.0f);

			f |= GL_COLOR_BUFFER_BIT;
		}

		glClear(f);
	}

	if(m_set_front_polygon_mode)
	{
		glPolygonMode(GL_FRONT, m_front_polygon_mode);
		checkForGlError("glPolygonMode");
	}

	Enable(m_depth_test_enable, GL_DEPTH_TEST);
	Enable(m_set_alpha_test, GL_ALPHA_TEST);
	Enable(m_set_depth_bounds_test, GL_DEPTH_BOUNDS_TEST_EXT);
	Enable(m_set_blend, GL_BLEND);
	Enable(m_set_logic_op, GL_LOGIC_OP);
	Enable(m_set_cull_face_enable, GL_CULL_FACE);
	Enable(m_set_dither, GL_DITHER);
	Enable(m_set_stencil_test, GL_STENCIL_TEST);
	Enable(m_set_line_smooth, GL_LINE_SMOOTH);
	Enable(m_set_poly_smooth, GL_POLYGON_SMOOTH);
	Enable(m_set_poly_offset_fill, GL_POLYGON_OFFSET_FILL);
	Enable(m_set_poly_offset_line, GL_POLYGON_OFFSET_LINE);
	Enable(m_set_poly_offset_point, GL_POLYGON_OFFSET_POINT);
	//Enable(m_set_restart_index, GL_PRIMITIVE_RESTART); //Requires OpenGL 3.1+

	if(m_set_clip_plane)
	{
		Enable(m_clip_plane_0, GL_CLIP_PLANE0);
		Enable(m_clip_plane_1, GL_CLIP_PLANE1);
		Enable(m_clip_plane_2, GL_CLIP_PLANE2);
		Enable(m_clip_plane_3, GL_CLIP_PLANE3);
		Enable(m_clip_plane_4, GL_CLIP_PLANE4);
		Enable(m_clip_plane_5, GL_CLIP_PLANE5);

		checkForGlError("m_set_clip_plane");
	}

	checkForGlError("glEnable");

	if(m_set_two_sided_stencil_test_enable)
	{
		if(m_set_stencil_fail && m_set_stencil_zfail && m_set_stencil_zpass)
		{
			glStencilOpSeparate(GL_FRONT, m_stencil_fail, m_stencil_zfail, m_stencil_zpass);
			checkForGlError("glStencilOpSeparate");
		}

		if(m_set_stencil_mask)
		{
			glStencilMaskSeparate(GL_FRONT, m_stencil_mask);
			checkForGlError("glStencilMaskSeparate");
		}

		if(m_set_stencil_func && m_set_stencil_func_ref && m_set_stencil_func_mask)
		{
			glStencilFuncSeparate(GL_FRONT, m_stencil_func, m_stencil_func_ref, m_stencil_func_mask);
			checkForGlError("glStencilFuncSeparate");
		}

		if(m_set_back_stencil_fail && m_set_back_stencil_zfail && m_set_back_stencil_zpass)
		{
			glStencilOpSeparate(GL_BACK, m_back_stencil_fail, m_back_stencil_zfail, m_back_stencil_zpass);
			checkForGlError("glStencilOpSeparate(GL_BACK)");
		}

		if(m_set_back_stencil_mask)
		{
			glStencilMaskSeparate(GL_BACK, m_back_stencil_mask);
			checkForGlError("glStencilMaskSeparate(GL_BACK)");
		}

		if(m_set_back_stencil_func && m_set_back_stencil_func_ref && m_set_back_stencil_func_mask)
		{
			glStencilFuncSeparate(GL_BACK, m_back_stencil_func, m_back_stencil_func_ref, m_back_stencil_func_mask);
			checkForGlError("glStencilFuncSeparate(GL_BACK)");
		}
	}
	else
	{
		if(m_set_stencil_fail && m_set_stencil_zfail && m_set_stencil_zpass)
		{
			glStencilOp(m_stencil_fail, m_stencil_zfail, m_stencil_zpass);
			checkForGlError("glStencilOp");
		}

		if(m_set_stencil_mask)
		{
			glStencilMask(m_stencil_mask);
			checkForGlError("glStencilMask");
		}

		if(m_set_stencil_func && m_set_stencil_func_ref && m_set_stencil_func_mask)
		{
			glStencilFunc(m_stencil_func, m_stencil_func_ref, m_stencil_func_mask);
			checkForGlError("glStencilFunc");
		}
	}

	if(m_set_shade_mode)
	{
		glShadeModel(m_shade_mode);
		checkForGlError("glShadeModel");
	}

	if(m_set_depth_mask)
	{
		glDepthMask(m_depth_mask);
		checkForGlError("glDepthMask");
	}

	if(m_set_depth_func)
	{
		glDepthFunc(m_depth_func);
		//ConLog.Warning("glDepthFunc(0x%x)", m_depth_func);
		checkForGlError("glDepthFunc");
	}

	if(m_set_depth_bounds)
	{
		//ConLog.Warning("glDepthBounds(%f, %f)", m_depth_bounds_min, m_depth_bounds_max);
		glDepthBounds(m_depth_bounds_min, m_depth_bounds_max);
		checkForGlError("glDepthBounds");
	}

	if(m_set_clip)
	{
		//ConLog.Warning("glDepthRangef(%f, %f)", m_clip_min, m_clip_max);
		glDepthRangef(m_clip_min, m_clip_max);
		checkForGlError("glDepthRangef");
	}

	if(m_set_line_width)
	{
		glLineWidth(m_line_width / 255.f);
		checkForGlError("glLineWidth");
	}

	if(m_set_blend_equation)
	{
		glBlendEquationSeparate(m_blend_equation_rgb, m_blend_equation_alpha);
		checkForGlError("glBlendEquationSeparate");
	}

	if(m_set_blend_sfactor && m_set_blend_dfactor)
	{
		glBlendFuncSeparate(m_blend_sfactor_rgb, m_blend_dfactor_rgb, m_blend_sfactor_alpha, m_blend_dfactor_alpha);
		checkForGlError("glBlendFuncSeparate");
	}

	if(m_set_blend_color)
	{
		glBlendColor(m_blend_color_r, m_blend_color_g, m_blend_color_b, m_blend_color_a);
		checkForGlError("glBlendColor");
	}

	if(m_set_cull_face)
	{
		glCullFace(m_cull_face);
		checkForGlError("glCullFace");
	}

	if(m_set_alpha_func && m_set_alpha_ref)
	{
		glAlphaFunc(m_alpha_func, m_alpha_ref);
		checkForGlError("glAlphaFunc");
	}

	if(m_set_fog_mode)
	{
		glFogi(GL_FOG_MODE, m_fog_mode);
		checkForGlError("glFogi(GL_FOG_MODE)");
	}

	if(m_set_fog_params)
	{
		glFogf(GL_FOG_START, m_fog_param0);
		checkForGlError("glFogf(GL_FOG_START)");
		glFogf(GL_FOG_END, m_fog_param1);
		checkForGlError("glFogf(GL_FOG_END)");
	}

	if(m_set_restart_index)
	{
		ConLog.Warning("m_set_restart_index requires glPrimitiveRestartIndex()");
		//glPrimitiveRestartIndex(m_restart_index); //Requires OpenGL 3.1+
		//checkForGlError("glPrimitiveRestartIndex");
	}

	if(m_indexed_array.m_count && m_draw_array_count)
	{
		ConLog.Warning("m_indexed_array.m_count && draw_array_count");
	}

	for(u32 i=0; i<m_textures_count; ++i)
	{
		if(!m_textures[i].IsEnabled()) continue;

		glActiveTexture(GL_TEXTURE0 + i);
		checkForGlError("glActiveTexture");
		m_gl_textures[i].Create();
		m_gl_textures[i].Bind();
		checkForGlError(wxString::Format("m_gl_textures[%d].Bind", i));
		m_program.SetTex(i);
		m_gl_textures[i].Init(m_textures[i]);
		checkForGlError(wxString::Format("m_gl_textures[%d].Init", i));
	}

	m_vao.Bind();
	if(m_indexed_array.m_count)
	{
		LoadVertexData(m_indexed_array.index_min, m_indexed_array.index_max - m_indexed_array.index_min + 1);
	}

	EnableVertexData(m_indexed_array.m_count ? true : false);

	InitVertexData();
	InitFragmentData();

	if(m_indexed_array.m_count)
	{
		switch(m_indexed_array.m_type)
		{
		case 0:
			glDrawElements(m_draw_mode - 1, m_indexed_array.m_count, GL_UNSIGNED_INT, nullptr);
			checkForGlError("glDrawElements #4");
		break;

		case 1:
			glDrawElements(m_draw_mode - 1, m_indexed_array.m_count, GL_UNSIGNED_SHORT, nullptr);
			checkForGlError("glDrawElements #2");
		break;

		default:
			ConLog.Error("Bad indexed array type (%d)", m_indexed_array.m_type);
		break;
		}

		DisableVertexData();
		m_indexed_array.Reset();
	}

	if(m_draw_array_count)
	{
		//ConLog.Warning("glDrawArrays(%d,%d,%d)", m_draw_mode - 1, m_draw_array_first, m_draw_array_count);
		glDrawArrays(m_draw_mode - 1, 0, m_draw_array_count);
		checkForGlError("glDrawArrays");
		DisableVertexData();
	}

	if(Ini.GSDumpColorBuffers.GetValue())
		WriteBuffers();
}
Exemplo n.º 29
0
void GLWidget::drawCoordinateCross(void)
{
    GLint   viewport[4];

    glMatrixMode (GL_PROJECTION);
    glPushMatrix();
    glLoadIdentity();

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

    glGetIntegerv (GL_VIEWPORT, viewport);

    glTranslatef (-1, -1, 0.0);
    glScalef (40.0 / viewport[2], 40.0 / viewport[3], 1);
    glTranslatef (1.25, 1.25, 0.0);

    glRotatef(xRot / 16.0, 1.0, 0.0, 0.0);
    glRotatef(yRot / 16.0, 0.0, 1.0, 0.0);
    glRotatef(zRot / 16.0, 0.0, 0.0, 1.0);

    glEnable (GL_COLOR_MATERIAL);
    glDisable (GL_LIGHTING);

    glLineWidth (1.0f);

    glBegin(GL_LINES);
    glColor3f(1,0,0);
    glVertex3f (0.0f, 0.0f, 0.0f);
    glVertex3f (0.9, 0.0f, 0.0f);
    glColor3f(0,1,0);
    glVertex3f (0.0f, 0.0f, 0.0f);
    glVertex3f (0.0f, 0.9, 0.0f);
    glColor3f(0,0,1);
    glVertex3f (0.0f, 0.0f, 0.0f);
    glVertex3f (0.0f, 0.0f, 0.9);
    glEnd ();

    glColor3f(1,0,0);
    glPushMatrix();
    glTranslatef(0.5,0,0);
    glRotatef(90,0,1,0);
    gluCylinder(row,0.1,0,0.4,10,10);
    glPopMatrix();

    glColor3f(0,1,0);
    glPushMatrix();
    glTranslatef(0,0.5,0);
    glRotatef(-90,1,0,0);
    gluCylinder(row,0.1,0,0.4,10,10);
    glPopMatrix();

    glColor3f(0,0,1);
    glPushMatrix();
    glTranslatef(0,0,0.5);
    gluCylinder(row,0.1,0,0.4,10,10);
    glPopMatrix();

    glColor3f(1,0,0);
    draw2DText(1.1, 0.0, 0.0, (char*)"X");

    glColor3f(0,1,0);
    draw2DText(0.1, 1.0, 0.0, (char*)"Y");

    glColor3f(0,0,1);
    draw2DText(0.1, 0.0, 1.0, (char*)"Z");

    glEnable(GL_LIGHTING);
    glDisable (GL_COLOR_MATERIAL);

    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
}
Exemplo n.º 30
0
void Circle3DOverlay::render(RenderArgs* args) {
    if (!_visible) {
        return; // do nothing if we're not visible
    }

    float alpha = getAlpha();

    if (alpha == 0.0) {
        return; // do nothing if our alpha is 0, we're not visible
    }
    
    // Create the circle in the coordinates origin
    float outerRadius = getOuterRadius();
    float innerRadius = getInnerRadius(); // only used in solid case
    float startAt = getStartAt();
    float endAt = getEndAt();
    
    bool geometryChanged = (startAt != _lastStartAt || endAt != _lastEndAt ||
                                innerRadius != _lastInnerRadius || outerRadius != _lastOuterRadius);

    
    const float FULL_CIRCLE = 360.0f;
    const float SLICES = 180.0f;  // The amount of segment to create the circle
    const float SLICE_ANGLE = FULL_CIRCLE / SLICES;

    //const int slices = 15;
    xColor colorX = getColor();
    const float MAX_COLOR = 255.0f;
    glm::vec4 color(colorX.red / MAX_COLOR, colorX.green / MAX_COLOR, colorX.blue / MAX_COLOR, alpha);

    bool colorChanged = colorX.red != _lastColor.red || colorX.green != _lastColor.green || colorX.blue != _lastColor.blue;
    _lastColor = colorX;

    glDisable(GL_LIGHTING);
    
    glm::vec3 position = getPosition();
    glm::vec3 center = getCenter();
    glm::vec2 dimensions = getDimensions();
    glm::quat rotation = getRotation();

    float glowLevel = getGlowLevel();
    Glower* glower = NULL;
    if (glowLevel > 0.0f) {
        glower = new Glower(glowLevel);
    }

    glPushMatrix();
        glTranslatef(position.x, position.y, position.z);
        glm::vec3 axis = glm::axis(rotation);
        glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z);
        glPushMatrix();
            glm::vec3 positionToCenter = center - position;
            glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z);
            glScalef(dimensions.x / 2.0f, dimensions.y / 2.0f, 1.0f);

            glLineWidth(_lineWidth);

            auto geometryCache = DependencyManager::get<GeometryCache>();
            
            // for our overlay, is solid means we draw a ring between the inner and outer radius of the circle, otherwise
            // we just draw a line...
            if (getIsSolid()) {
                if (_quadVerticesID == GeometryCache::UNKNOWN_ID) {
                    _quadVerticesID = geometryCache->allocateID();
                }
                
                if (geometryChanged || colorChanged) {
                    
                    QVector<glm::vec2> points;

                    float angle = startAt;
                    float angleInRadians = glm::radians(angle);
                    glm::vec2 firstInnerPoint(cos(angleInRadians) * innerRadius, sin(angleInRadians) * innerRadius);
                    glm::vec2 firstOuterPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);

                    points << firstInnerPoint << firstOuterPoint;

                    while (angle < endAt) {
                        angleInRadians = glm::radians(angle);
                        glm::vec2 thisInnerPoint(cos(angleInRadians) * innerRadius, sin(angleInRadians) * innerRadius);
                        glm::vec2 thisOuterPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);

                        points << thisOuterPoint << thisInnerPoint;
                
                        angle += SLICE_ANGLE;
                    }
            
                    // get the last slice portion....
                    angle = endAt;
                    angleInRadians = glm::radians(angle);
                    glm::vec2 lastInnerPoint(cos(angleInRadians) * innerRadius, sin(angleInRadians) * innerRadius);
                    glm::vec2 lastOuterPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
            
                    points << lastOuterPoint << lastInnerPoint;

                    geometryCache->updateVertices(_quadVerticesID, points, color);
                }
                
                geometryCache->renderVertices(gpu::QUAD_STRIP, _quadVerticesID);

            } else {
                if (_lineVerticesID == GeometryCache::UNKNOWN_ID) {
                    _lineVerticesID = geometryCache->allocateID();
                }

                if (geometryChanged || colorChanged) {
                    QVector<glm::vec2> points;
                    
                    float angle = startAt;
                    float angleInRadians = glm::radians(angle);
                    glm::vec2 firstPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
                    points << firstPoint;

                    while (angle < endAt) {
                        angle += SLICE_ANGLE;
                        angleInRadians = glm::radians(angle);
                        glm::vec2 thisPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
                        points << thisPoint;

                        if (getIsDashedLine()) {
                            angle += SLICE_ANGLE / 2.0f; // short gap
                            angleInRadians = glm::radians(angle);
                            glm::vec2 dashStartPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
                            points << dashStartPoint;
                        }
                    }
            
                    // get the last slice portion....
                    angle = endAt;
                    angleInRadians = glm::radians(angle);
                    glm::vec2 lastPoint(cos(angleInRadians) * outerRadius, sin(angleInRadians) * outerRadius);
                    points << lastPoint;

                    geometryCache->updateVertices(_lineVerticesID, points, color);
                }

                if (getIsDashedLine()) {
                    geometryCache->renderVertices(gpu::LINES, _lineVerticesID);
                } else {
                    geometryCache->renderVertices(gpu::LINE_STRIP, _lineVerticesID);
                }
            }
            
            // draw our tick marks
            // for our overlay, is solid means we draw a ring between the inner and outer radius of the circle, otherwise
            // we just draw a line...
            if (getHasTickMarks()) {

                if (_majorTicksVerticesID == GeometryCache::UNKNOWN_ID) {
                    _majorTicksVerticesID = geometryCache->allocateID();
                }
                if (_minorTicksVerticesID == GeometryCache::UNKNOWN_ID) {
                    _minorTicksVerticesID = geometryCache->allocateID();
                }

                if (geometryChanged) {
                    QVector<glm::vec2> majorPoints;
                    QVector<glm::vec2> minorPoints;

                    // draw our major tick marks
                    if (getMajorTickMarksAngle() > 0.0f && getMajorTickMarksLength() != 0.0f) {
                
                        float tickMarkAngle = getMajorTickMarksAngle();
                        float angle = startAt - fmod(startAt, tickMarkAngle) + tickMarkAngle; 
                        float angleInRadians = glm::radians(angle);
                        float tickMarkLength = getMajorTickMarksLength();
                        float startRadius = (tickMarkLength > 0.0f) ? innerRadius : outerRadius;
                        float endRadius = startRadius + tickMarkLength;

                        while (angle <= endAt) {
                            angleInRadians = glm::radians(angle);

                            glm::vec2 thisPointA(cos(angleInRadians) * startRadius, sin(angleInRadians) * startRadius);
                            glm::vec2 thisPointB(cos(angleInRadians) * endRadius, sin(angleInRadians) * endRadius);

                            majorPoints << thisPointA << thisPointB;
                
                            angle += tickMarkAngle;
                        }
                    }

                    // draw our minor tick marks
                    if (getMinorTickMarksAngle() > 0.0f && getMinorTickMarksLength() != 0.0f) {
                
                        float tickMarkAngle = getMinorTickMarksAngle();
                        float angle = startAt - fmod(startAt, tickMarkAngle) + tickMarkAngle; 
                        float angleInRadians = glm::radians(angle);
                        float tickMarkLength = getMinorTickMarksLength();
                        float startRadius = (tickMarkLength > 0.0f) ? innerRadius : outerRadius;
                        float endRadius = startRadius + tickMarkLength;

                        while (angle <= endAt) {
                            angleInRadians = glm::radians(angle);

                            glm::vec2 thisPointA(cos(angleInRadians) * startRadius, sin(angleInRadians) * startRadius);
                            glm::vec2 thisPointB(cos(angleInRadians) * endRadius, sin(angleInRadians) * endRadius);

                            minorPoints << thisPointA << thisPointB;
                
                            angle += tickMarkAngle;
                        }
                    }

                    xColor majorColorX = getMajorTickMarksColor();
                    glm::vec4 majorColor(majorColorX.red / MAX_COLOR, majorColorX.green / MAX_COLOR, majorColorX.blue / MAX_COLOR, alpha);

                    geometryCache->updateVertices(_majorTicksVerticesID, majorPoints, majorColor);

                    xColor minorColorX = getMinorTickMarksColor();
                    glm::vec4 minorColor(minorColorX.red / MAX_COLOR, minorColorX.green / MAX_COLOR, minorColorX.blue / MAX_COLOR, alpha);

                    geometryCache->updateVertices(_minorTicksVerticesID, minorPoints, minorColor);
                }

                geometryCache->renderVertices(gpu::LINES, _majorTicksVerticesID);

                geometryCache->renderVertices(gpu::LINES, _minorTicksVerticesID);
            }
            
 
        glPopMatrix();
    glPopMatrix();
    
    if (geometryChanged) {
        _lastStartAt = startAt;
        _lastEndAt = endAt;
        _lastInnerRadius = innerRadius;
        _lastOuterRadius = outerRadius;
    }
    
    if (glower) {
        delete glower;
    }
}