Пример #1
0
void			RadarRenderer::render(SceneRenderer& renderer,
							bool blank)
{
  const int ox = renderer.getWindow().getOriginX();
  const int oy = renderer.getWindow().getOriginY();
  float opacity = renderer.getPanelOpacity();

  if ((opacity < 1.0f) && (opacity > 0.0f)) {
    glScissor(ox + x - 2, oy + y - 2, w + 4, h + 4);
    glColor4f(0.0f, 0.0f, 0.0f, opacity);
    glRectf((float) x, (float) y, (float)(x + w), (float)(y + h));
  }

  glScissor(ox + x, oy + y, w, h);

  LocalPlayer *myTank = LocalPlayer::getMyTank();

  if (opacity == 1.0f)
	{
  // glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
  // glClear(GL_COLOR_BUFFER_BIT);
  }

  if (blank)
    return;

  // prepare transforms
  float worldSize = BZDB.eval(StateDatabase::BZDB_WORLDSIZE);
  float range = BZDB.eval("displayRadarRange") * worldSize;
  // when burrowed, limit radar range
  if (myTank && (myTank->getFlag() == Flags::Burrow) &&
      (myTank->getPosition()[2] < 0.0f)) {
#ifdef _MSC_VER
    range = min(range, worldSize / 4.0f);
#else
    range = std::min(range, worldSize / 4.0f);
#endif
  }
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  const int xSize = renderer.getWindow().getWidth();
  const int ySize = renderer.getWindow().getHeight();
  const double xCenter = double(x) + 0.5 * double(w);
  const double yCenter = double(y) + 0.5 * double(h);
  const double xUnit = 2.0 * range / double(w);
  const double yUnit = 2.0 * range / double(h);
  glOrtho(-xCenter * xUnit, (xSize - xCenter) * xUnit, -yCenter * yUnit, (ySize - yCenter) * yUnit, -1.0, 1.0);
  glMatrixMode(GL_MODELVIEW);
  glPushMatrix();
  glLoadIdentity();
  OpenGLGState::resetState();

  TextureManager &tm = TextureManager::instance();
  int noiseTexture = tm.getTextureID( "noise" );

  // if jammed then draw white noise.  occasionally draw a good frame.
  if (jammed && bzfrand() > decay)
	{

    glColor3f(1.0,1.0,1.0);

    if (noiseTexture >= 0 && renderer.useQuality() > 0)
		{
      const int sequences = 10;

      static float np[] = { 0, 0, 1, 1,
														1, 1, 0, 0,
														0.5f, 0.5f, 1.5f, 1.5f,
														1.5f, 1.5f, 0.5f, 0.5f,
														0.25f, 0.25f, 1.25f, 1.25f,
														1.25f, 1.25f, 0.25f, 0.25f,
														0, 0.5f, 1, 1.5f,
														1, 1.5f, 0, 0.5f,
														0.5f, 0, 1.5f, 1,
														1.4f, 1, 0.5f, 0,
														0.75f, 0.75f, 1.75f, 1.75f,
														1.75f, 1.75f, 0.75f, 0.75f,
													};
      int noisePattern = 4 * int(floor(sequences * bzfrand()));

      glEnable(GL_TEXTURE_2D);
      tm.bind(noiseTexture);

      glBegin(GL_QUADS);
				glTexCoord2f(np[noisePattern+0],np[noisePattern+1]);
				glVertex2f(-range,-range);
				glTexCoord2f(np[noisePattern+2],np[noisePattern+1]);
				glVertex2f( range,-range);
				glTexCoord2f(np[noisePattern+2],np[noisePattern+3]);
				glVertex2f( range, range);
				glTexCoord2f(np[noisePattern+0],np[noisePattern+3]);
				glVertex2f(-range, range);
      glEnd();
      glDisable(GL_TEXTURE_2D);
    }
    else if (noiseTexture >= 0 && BZDBCache::texture && renderer.useQuality() == 0)
		{
      glEnable(GL_TEXTURE_2D);
      tm.bind(noiseTexture);

      glBegin(GL_QUADS);
				glTexCoord2f(0,0);
				glVertex2f(-range,-range);
				glTexCoord2f(1,0);
				glVertex2f( range,-range);
				glTexCoord2f(1,1);
				glVertex2f( range, range);
				glTexCoord2f(0,1);
				glVertex2f(-range, range);
      glEnd();

      glDisable(GL_TEXTURE_2D);
    }
    if (decay > 0.015f)
			decay *= 0.5f;
  }
	else if (myTank)  // only draw if there's a local player
	{
    // if decay is sufficiently small then boost it so it's more
    // likely a jammed radar will get a few good frames closely
    // spaced in time.  value of 1 guarantees at least two good
    // frames in a row.
    if (decay <= 0.015f)
			decay = 1.0f;
    else
			decay *= 0.5f;

    // get size of pixel in model space (assumes radar is square)
    ps = 2.0f * range / GLfloat(w);

    // relative to my tank
    const LocalPlayer* myTank = LocalPlayer::getMyTank();
    const float* pos = myTank->getPosition();
    float angle = myTank->getAngle();

    // draw the view angle blewow stuff
    // view frustum edges
    glColor3f(1.0f, 0.625f, 0.125f);
    const float fovx = renderer.getViewFrustum().getFOVx();
    const float viewWidth = range * tanf(0.5f * fovx);
    glBegin(GL_LINE_STRIP);
			glVertex2f(-viewWidth, range);
			glVertex2f(0.0f, 0.0f);
			glVertex2f(viewWidth, range);
    glEnd();

    glPushMatrix();
    glRotatef(90.0f - angle * 180.0f / M_PI, 0.0f, 0.0f, 1.0f);
    glPushMatrix();
    glTranslatef(-pos[0], -pos[1], 0.0f);

    // Redraw buildings
    makeList( renderer);

    // draw my shots
    int maxShots = world.getMaxShots();
    int i;
    float muzzleHeight = BZDB.eval(StateDatabase::BZDB_MUZZLEHEIGHT);
    for (i = 0; i < maxShots; i++)
		{
      const ShotPath* shot = myTank->getShot(i);
      if (shot)
			{
				const float cs = colorScale(shot->getPosition()[2], muzzleHeight, BZDBCache::enhancedRadar);
				glColor3f(1.0f * cs, 1.0f * cs, 1.0f * cs);
				shot->radarRender();
			}
    }

    //draw world weapon shots
    WorldPlayer *worldWeapons = World::getWorld()->getWorldWeapons();
    maxShots = worldWeapons->getMaxShots();
    for (i = 0; i < maxShots; i++)
		{
      const ShotPath* shot = worldWeapons->getShot(i);
      if (shot)
			{
				const float cs = colorScale(shot->getPosition()[2],	muzzleHeight, BZDBCache::enhancedRadar);
				glColor3f(1.0f * cs, 1.0f * cs, 1.0f * cs);
				shot->radarRender();
      }
    }


    // draw other tanks (and any flags on them)
    // note about flag drawing.  each line segment is drawn twice
    // (once in each direction);  this degrades the antialiasing
    // but on systems that don't do correct filtering of endpoints
    // not doing it makes (half) the endpoints jump wildly.
    const int curMaxPlayers = world.getCurMaxPlayers();
    for (i = 0; i < curMaxPlayers; i++) {
      RemotePlayer* player = world.getPlayer(i);
      if (!player || !player->isAlive() || ((player->getFlag() == Flags::Stealth) &&
					    (myTank->getFlag() != Flags::Seer)))
	continue;

      GLfloat x = player->getPosition()[0];
      GLfloat y = player->getPosition()[1];
      GLfloat z = player->getPosition()[2];
      if (player->getFlag() != Flags::Null) {
	glColor3fv(player->getFlag()->getColor());
	drawFlagOnTank(x, y, z);
      }

      if (player->isPaused() || player->isNotResponding()) {
	const float dimfactor = 0.4f;
	const float *color = Team::getRadarColor(myTank->getFlag() ==
			     Flags::Colorblindness ? RogueTeam : player->getTeam());
	float dimmedcolor[3];
	dimmedcolor[0] = color[0] * dimfactor;
	dimmedcolor[1] = color[1] * dimfactor;
	dimmedcolor[2] = color[2] * dimfactor;
	glColor3fv(dimmedcolor);
      } else {
	glColor3fv(Team::getRadarColor(myTank->getFlag() ==
			     Flags::Colorblindness ? RogueTeam : player->getTeam()));
      }
      // If this tank is hunted flash it on the radar
      if (player->isHunted() && myTank->getFlag() != Flags::Colorblindness) {
	if (flashTank.isOn()) {
	  if (!toggleTank) {
	    float flashcolor[3];
	    flashcolor[0] = 0.0f;
	    flashcolor[1] = 0.8f;
	    flashcolor[2] = 0.9f;
	    glColor3fv(flashcolor);
	  }
	} else {
	  toggleTank = !toggleTank;
	  flashTank.setClock(0.2f);
	}
      }
      drawTank(x, y, z);
    }

    bool coloredShot = BZDB.isTrue("coloredradarshots");
    // draw other tanks' shells
    maxShots = World::getWorld()->getMaxShots();
    for (i = 0; i < curMaxPlayers; i++) {
      RemotePlayer* player = world.getPlayer(i);
      if (!player) continue;
      for (int j = 0; j < maxShots; j++) {
	const ShotPath* shot = player->getShot(j);
	if (shot && shot->getFlag() != Flags::InvisibleBullet) {
	  const float *shotcolor;
	  if (coloredShot) {
	    if (myTank->getFlag() == Flags::Colorblindness)
	      shotcolor = Team::getRadarColor(RogueTeam);
	    else
	      shotcolor = Team::getRadarColor(player->getTeam());
	    const float cs = colorScale(shot->getPosition()[2],
		    muzzleHeight, BZDBCache::enhancedRadar);
	    glColor3f(shotcolor[0] * cs, shotcolor[1] * cs, shotcolor[2] * cs);
	  } else {
	    glColor3f(1.0f, 1.0f, 1.0f);
	  }
	  shot->radarRender();
	}
      }
    }

    // draw flags not on tanks.
    const int maxFlags = world.getMaxFlags();
    const bool drawNormalFlags = BZDB.isTrue("displayRadarFlags");
    for (i = 0; i < maxFlags; i++) {
      const Flag& flag = world.getFlag(i);
      // don't draw flags that don't exist or are on a tank
      if (flag.status == FlagNoExist || flag.status == FlagOnTank)
	continue;
      // don't draw normal flags if we aren't supposed to
      if (flag.type->flagTeam == NoTeam && !drawNormalFlags)
	continue;
      // Flags change color by height
      const float cs = colorScale(flag.position[2], muzzleHeight, BZDBCache::enhancedRadar);
      const float *flagcolor = flag.type->getColor();
      glColor3f(flagcolor[0] * cs, flagcolor[1] * cs, flagcolor[2] * cs);
      drawFlag(flag.position[0], flag.position[1], flag.position[2]);
    }
    // draw antidote flag
    const float* antidotePos =
		LocalPlayer::getMyTank()->getAntidoteLocation();
    if (antidotePos) {
      glColor3f(1.0f, 1.0f, 0.0f);
      drawFlag(antidotePos[0], antidotePos[1], antidotePos[2]);
    }

    // draw these markers above all others always centered
    glPopMatrix();

    // north marker
    GLfloat ns = 0.05f * range, ny = 0.9f * range;
    glColor3f(1.0f, 1.0f, 1.0f);
    glBegin(GL_LINE_STRIP);
    glVertex2f(-ns, ny - ns);
    glVertex2f(-ns, ny + ns);
    glVertex2f(ns, ny - ns);
    glVertex2f(ns, ny + ns);
    glEnd();

    // always up
    glPopMatrix();

    // get size of pixel in model space (assumes radar is square)
    GLfloat ps = 2.0f * range / GLfloat(w);

    // forward tick
    glBegin(GL_LINES);
    glVertex2f(0.0f, range - ps);
    glVertex2f(0.0f, range - 4.0f * ps);
    glEnd();

    // my tank
    glColor3f(1.0f, 1.0f, 1.0f);
    drawTank(0.0f, 0.0f, myTank->getPosition()[2]);

    // my flag
    if (myTank->getFlag() != Flags::Null) {
      glColor3fv(myTank->getFlag()->getColor());
      drawFlagOnTank(0.0f, 0.0f, myTank->getPosition()[2]);
    }
  }

  // restore GL state
  glPopMatrix();
}
Пример #2
0
void
Canvas::DrawCircle(int x, int y, unsigned radius)
{
#ifdef USE_GLSL
  OpenGL::solid_shader->Use();
#endif

  if (IsPenOverBrush() && pen.GetWidth() > 2) {
    ScopeVertexPointer vp;
    GLDonutVertices vertices(x, y,
                             radius - pen.GetWidth() / 2,
                             radius + pen.GetWidth() / 2);
    if (!brush.IsHollow()) {
      vertices.BindInnerCircle(vp);
      brush.Set();
      glDrawArrays(GL_TRIANGLE_FAN, 0, vertices.CIRCLE_SIZE);
    }
    vertices.Bind(vp);
    pen.Bind();
    glDrawArrays(GL_TRIANGLE_STRIP, 0, vertices.SIZE);
    pen.Unbind();
  } else {
    GLFallbackArrayBuffer &buffer = radius < 16
      ? *OpenGL::small_circle_buffer
      : *OpenGL::circle_buffer;
    const unsigned n = radius < 16
      ? OpenGL::SMALL_CIRCLE_SIZE
      : OpenGL::CIRCLE_SIZE;

    const FloatPoint *const points = (const FloatPoint *)buffer.BeginRead();
    const ScopeVertexPointer vp(points);

#ifdef USE_GLSL
    glm::mat4 matrix2 = glm::scale(glm::translate(glm::mat4(),
                                                  glm::vec3(x, y, 0)),
                                   glm::vec3(GLfloat(radius), GLfloat(radius),
                                             1.));
    glUniformMatrix4fv(OpenGL::solid_modelview, 1, GL_FALSE,
                       glm::value_ptr(matrix2));
#else
    glPushMatrix();

#ifdef HAVE_GLES
    glTranslatex((GLfixed)x << 16, (GLfixed)y << 16, 0);
    glScalex((GLfixed)radius << 16, (GLfixed)radius << 16, (GLfixed)1 << 16);
#else
    glTranslatef(x, y, 0.);
    glScalef(radius, radius, 1.);
#endif
#endif

    if (!brush.IsHollow()) {
      brush.Set();
      glDrawArrays(GL_TRIANGLE_FAN, 0, n);
    }

    if (IsPenOverBrush()) {
      pen.Bind();
      glDrawArrays(GL_LINE_LOOP, 0, n);
      pen.Unbind();
    }

#ifdef USE_GLSL
    glUniformMatrix4fv(OpenGL::solid_modelview, 1, GL_FALSE,
                       glm::value_ptr(glm::mat4()));
#else
    glPopMatrix();
#endif

    buffer.EndRead();
  }
}
void
DecomposeIntoNoRepeatTriangles(const gfx::IntRect& aTexCoordRect,
                               const gfx::IntSize& aTexSize,
                               RectTriangles& aRects,
                               bool aFlipY /* = false */)
{
    // normalize this
    gfx::IntRect tcr(aTexCoordRect);
    while (tcr.x >= aTexSize.width)
        tcr.x -= aTexSize.width;
    while (tcr.y >= aTexSize.height)
        tcr.y -= aTexSize.height;

    // Compute top left and bottom right tex coordinates
    GLfloat tl[2] =
        { GLfloat(tcr.x) / GLfloat(aTexSize.width),
          GLfloat(tcr.y) / GLfloat(aTexSize.height) };
    GLfloat br[2] =
        { GLfloat(tcr.XMost()) / GLfloat(aTexSize.width),
          GLfloat(tcr.YMost()) / GLfloat(aTexSize.height) };

    // then check if we wrap in either the x or y axis; if we do,
    // then also use fmod to figure out the "true" non-wrapping
    // texture coordinates.

    bool xwrap = false, ywrap = false;
    if (tcr.x < 0 || tcr.x > aTexSize.width ||
        tcr.XMost() < 0 || tcr.XMost() > aTexSize.width)
    {
        xwrap = true;
        tl[0] = WrapTexCoord(tl[0]);
        br[0] = WrapTexCoord(br[0]);
    }

    if (tcr.y < 0 || tcr.y > aTexSize.height ||
        tcr.YMost() < 0 || tcr.YMost() > aTexSize.height)
    {
        ywrap = true;
        tl[1] = WrapTexCoord(tl[1]);
        br[1] = WrapTexCoord(br[1]);
    }

    NS_ASSERTION(tl[0] >= 0.0f && tl[0] <= 1.0f &&
                 tl[1] >= 0.0f && tl[1] <= 1.0f &&
                 br[0] >= 0.0f && br[0] <= 1.0f &&
                 br[1] >= 0.0f && br[1] <= 1.0f,
                 "Somehow generated invalid texture coordinates");

    // If xwrap is false, the texture will be sampled from tl[0]
    // .. br[0].  If xwrap is true, then it will be split into tl[0]
    // .. 1.0, and 0.0 .. br[0].  Same for the Y axis.  The
    // destination rectangle is also split appropriately, according
    // to the calculated xmid/ymid values.

    // There isn't a 1:1 mapping between tex coords and destination coords;
    // when computing midpoints, we have to take that into account.  We
    // need to map the texture coords, which are (in the wrap case):
    // |tl->1| and |0->br| to the |0->1| range of the vertex coords.  So
    // we have the length (1-tl)+(br) that needs to map into 0->1.
    // These are only valid if there is wrap involved, they won't be used
    // otherwise.
    GLfloat xlen = (1.0f - tl[0]) + br[0];
    GLfloat ylen = (1.0f - tl[1]) + br[1];

    NS_ASSERTION(!xwrap || xlen > 0.0f, "xlen isn't > 0, what's going on?");
    NS_ASSERTION(!ywrap || ylen > 0.0f, "ylen isn't > 0, what's going on?");
    NS_ASSERTION(aTexCoordRect.width <= aTexSize.width &&
                 aTexCoordRect.height <= aTexSize.height, "tex coord rect would cause tiling!");

    if (!xwrap && !ywrap) {
        aRects.addRect(0.0f, 0.0f,
                       1.0f, 1.0f,
                       tl[0], tl[1],
                       br[0], br[1],
                       aFlipY);
    } else if (!xwrap && ywrap) {
        GLfloat ymid = (1.0f - tl[1]) / ylen;
        aRects.addRect(0.0f, 0.0f,
                       1.0f, ymid,
                       tl[0], tl[1],
                       br[0], 1.0f,
                       aFlipY);
        aRects.addRect(0.0f, ymid,
                       1.0f, 1.0f,
                       tl[0], 0.0f,
                       br[0], br[1],
                       aFlipY);
    } else if (xwrap && !ywrap) {
        GLfloat xmid = (1.0f - tl[0]) / xlen;
        aRects.addRect(0.0f, 0.0f,
                       xmid, 1.0f,
                       tl[0], tl[1],
                       1.0f, br[1],
                       aFlipY);
        aRects.addRect(xmid, 0.0f,
                       1.0f, 1.0f,
                       0.0f, tl[1],
                       br[0], br[1],
                       aFlipY);
    } else {
        GLfloat xmid = (1.0f - tl[0]) / xlen;
        GLfloat ymid = (1.0f - tl[1]) / ylen;
        aRects.addRect(0.0f, 0.0f,
                       xmid, ymid,
                       tl[0], tl[1],
                       1.0f, 1.0f,
                       aFlipY);
        aRects.addRect(xmid, 0.0f,
                       1.0f, ymid,
                       0.0f, tl[1],
                       br[0], 1.0f,
                       aFlipY);
        aRects.addRect(0.0f, ymid,
                       xmid, 1.0f,
                       tl[0], 0.0f,
                       1.0f, br[1],
                       aFlipY);
        aRects.addRect(xmid, ymid,
                       1.0f, 1.0f,
                       0.0f, 0.0f,
                       br[0], br[1],
                       aFlipY);
    }
}
Пример #4
0
/**
 * if (load)
 *    Accum = ColorBuf * value
 * else
 *    Accum += ColorBuf * value
 */
static void
accum_or_load(struct gl_context *ctx, GLfloat value,
              GLint xpos, GLint ypos, GLint width, GLint height,
              GLboolean load)
{
   struct gl_renderbuffer *accRb =
      ctx->DrawBuffer->Attachment[BUFFER_ACCUM].Renderbuffer;
   struct gl_renderbuffer *colorRb = ctx->ReadBuffer->_ColorReadBuffer;
   GLubyte *accMap, *colorMap;
   GLint accRowStride, colorRowStride;
   GLbitfield mappingFlags;

   if (!colorRb) {
      /* no read buffer - OK */
      return;
   }

   assert(accRb);

   mappingFlags = GL_MAP_WRITE_BIT;
   if (!load) /* if we're accumulating */
      mappingFlags |= GL_MAP_READ_BIT;

   /* Map accum buffer */
   ctx->Driver.MapRenderbuffer(ctx, accRb, xpos, ypos, width, height,
                               mappingFlags, &accMap, &accRowStride);
   if (!accMap) {
      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glAccum");
      return;
   }

   /* Map color buffer */
   ctx->Driver.MapRenderbuffer(ctx, colorRb, xpos, ypos, width, height,
                               GL_MAP_READ_BIT,
                               &colorMap, &colorRowStride);
   if (!colorMap) {
      ctx->Driver.UnmapRenderbuffer(ctx, accRb);
      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glAccum");
      return;
   }

   if (accRb->Format == MESA_FORMAT_SIGNED_RGBA_16) {
      const GLfloat scale = value * 32767.0f;
      GLuint i, j;
      GLfloat (*rgba)[4];

      rgba = malloc(width * 4 * sizeof(GLfloat));
      if (rgba) {
         for (j = 0; j < height; j++) {
            GLshort *acc = (GLshort *) accMap;

            /* read colors from source color buffer */
            _mesa_unpack_rgba_row(colorRb->Format, width, colorMap, rgba);

            if (load) {
               for (i = 0; i < width; i++) {
                  acc[i * 4 + 0] = (GLshort) (rgba[i][RCOMP] * scale);
                  acc[i * 4 + 1] = (GLshort) (rgba[i][GCOMP] * scale);
                  acc[i * 4 + 2] = (GLshort) (rgba[i][BCOMP] * scale);
                  acc[i * 4 + 3] = (GLshort) (rgba[i][ACOMP] * scale);
               }
            }
            else {
               /* accumulate */
               for (i = 0; i < width; i++) {
                  acc[i * 4 + 0] += (GLshort) (rgba[i][RCOMP] * scale);
                  acc[i * 4 + 1] += (GLshort) (rgba[i][GCOMP] * scale);
                  acc[i * 4 + 2] += (GLshort) (rgba[i][BCOMP] * scale);
                  acc[i * 4 + 3] += (GLshort) (rgba[i][ACOMP] * scale);
               }
            }

            colorMap += colorRowStride;
            accMap += accRowStride;
         }

         free(rgba);
      }
      else {
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glAccum");
      }
   }
   else {
      /* other types someday? */
   }

   ctx->Driver.UnmapRenderbuffer(ctx, accRb);
   ctx->Driver.UnmapRenderbuffer(ctx, colorRb);
}
Пример #5
0
void Surface3d::generateMesh(const Surface& S)
{
	int n = S.getHeight();
	int m = S.getWidth();

	//set up vertices and normals
	vector<Vector> smoothNormals;
	getSmoothNormals(smoothNormals);

	GLfloat* vertices = new GLfloat[n*m*3];
	GLfloat* normals = new GLfloat[n*m*3];

	unsigned int verticesStride = 0;
	for (int i = 0; i < n; ++i) {
		for (int j = 0; j < m; ++j) {
			vertices[verticesStride + 0] = GLfloat(j);
			vertices[verticesStride + 1] = GLfloat(S.getZ(j, i));
			vertices[verticesStride + 2] = GLfloat(i);

			normals[verticesStride + 0] = smoothNormals[i*m + j].x; 
			normals[verticesStride + 1] = smoothNormals[i*m + j].y;
			normals[verticesStride + 2] = smoothNormals[i*m + j].z;

			verticesStride += 3;
		}
	}

	glGenBuffers(1, &verticesId);
    glBindBuffer(GL_ARRAY_BUFFER, verticesId);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*verticesStride, vertices, GL_STATIC_DRAW);

	glGenBuffers(1, &normalsId);
    glBindBuffer(GL_ARRAY_BUFFER, normalsId);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*verticesStride, normals, GL_STATIC_DRAW);

	delete vertices;
	delete normals;
	
	//set up indices

	//a triangle strip generated by stitching
	GLuint* indices = new GLuint[2*m + (n-2)*m*2];

	unsigned int indicesStride = 0;

	for (int i = 0; i < n-1; ++i) {
		for (int j = 0; j < m; ++j) {
			indices[indicesStride++] = i*m + j;
			indices[indicesStride++] = (i+1)*m + j;
		}

		++i;
		if (i < n-1) {
			for (int j = m-1; j >= 0; --j) {
				indices[indicesStride++] = i*m + j;
				indices[indicesStride++] = (i+1)*m + j;
			}
		}
	}

	glGenBuffers(1, &indicesId);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesId);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*indicesStride, indices, GL_STATIC_DRAW);

	delete indices;

	indicesCount = indicesStride;
}
Пример #6
0
void TesseractWidget::SetColor(Coordinate color) {
    GLfloat c[4]= {GLfloat(color.x),GLfloat(color.y),GLfloat(color.z),1};
    glMaterialfv(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE,c);
    glColor4fv(c);
}
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
// ------------------------------------------------------------------------------------------------
Texture2D::Texture2D(Texture2DContainer* container, GLsizei sliceNum)
: mContainer(container)
, mSliceNum(GLfloat(sliceNum))
{
    assert(mContainer);
}
Пример #8
0
void GLLineIlluminator::updateMaterial(GLLineIlluminator::DataItem* dataItem) const
	{
	/* Update the material version: */
	dataItem->materialVersion=materialVersion;
	
	/* Upload the material texture: */
	dataItem->materialType=materialType;
	if(materialType==INTENSITY)
		{
		/* Create a 2D texture map encoding Phong's lighting model: */
		static GLfloat texture[32][32];
		for(int x=0;x<32;++x)
			{
			GLfloat s=2.0f*(GLfloat(x)+0.5f)/32.0f-1.0f;
			GLfloat oneMinusS2=1.0f-s*s;
			GLfloat ambientDiffuse=material.diffuse[0];
			ambientDiffuse*=Math::pow(Math::sqrt(oneMinusS2),2.0f);
			ambientDiffuse+=material.ambient[0];
			for(int y=0;y<32;++y)
				{
				GLfloat t=2.0f*(GLfloat(y)+0.5f)/32.0f-1.0f;
				GLfloat oneMinusT2=1.0f-t*t;
				GLfloat color=material.specular[0];
				color*=Math::pow(Math::abs(Math::sqrt(oneMinusS2*oneMinusT2)-s*t),material.shininess);
				color+=ambientDiffuse;
				texture[y][x]=color;
				}
			}
		
		/* Upload the created texture: */
		glBindTexture(GL_TEXTURE_2D,dataItem->materialTextureId);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_BASE_LEVEL,0);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAX_LEVEL,0);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glPixelStorei(GL_UNPACK_ROW_LENGTH,0);
		glPixelStorei(GL_UNPACK_SKIP_ROWS,0);
		glPixelStorei(GL_UNPACK_SKIP_PIXELS,0);
		glPixelStorei(GL_UNPACK_ALIGNMENT,1);
		glTexImage2D(GL_TEXTURE_2D,0,GL_INTENSITY,32,32,0,GL_LUMINANCE,GL_FLOAT,texture);
		glBindTexture(GL_TEXTURE_2D,0);
		}
	else if(materialType==RGBA)
		{
		/* Create a 2D texture map encoding Phong's lighting model: */
		static Color texture[32][32];
		for(int x=0;x<32;++x)
			{
			GLfloat s=2.0f*(GLfloat(x)+0.5f)/32.0f-1.0f;
			GLfloat oneMinusS2=1.0f-s*s;
			Color ambientDiffuse=material.diffuse;
			ambientDiffuse*=Math::pow(Math::sqrt(oneMinusS2),2.0f);
			ambientDiffuse+=material.ambient;
			for(int y=0;y<32;++y)
				{
				GLfloat t=2.0f*(GLfloat(y)+0.5f)/32.0f-1.0f;
				GLfloat oneMinusT2=1.0f-t*t;
				Color color=material.specular;
				color*=Math::pow(Math::abs(Math::sqrt(oneMinusS2*oneMinusT2)-s*t),material.shininess);
				color+=ambientDiffuse;
				texture[y][x]=color;
				}
			}
		
		/* Upload the created texture: */
		glBindTexture(GL_TEXTURE_2D,dataItem->materialTextureId);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_BASE_LEVEL,0);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAX_LEVEL,0);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
		glPixelStorei(GL_UNPACK_ROW_LENGTH,0);
		glPixelStorei(GL_UNPACK_SKIP_ROWS,0);
		glPixelStorei(GL_UNPACK_SKIP_PIXELS,0);
		glPixelStorei(GL_UNPACK_ALIGNMENT,1);
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,32,32,0,GL_RGBA,GL_FLOAT,texture);
		glBindTexture(GL_TEXTURE_2D,0);
		}
	}
Пример #9
0
  void VisualSceneSpecPoints :: DrawScene ()
  {
    if (!mesh) 
      {
	VisualScene::DrawScene();
	return;
      }

    if (changeval != specpoints.Size())
      BuildScene();
    changeval = specpoints.Size();



    glClearColor(backcolor, backcolor, backcolor, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glEnable (GL_COLOR_MATERIAL);
    glColor3f (1.0f, 1.0f, 1.0f);
    glLineWidth (1.0f);

    glPushMatrix();
    glMultMatrixd (transformationmat);

    //  glEnable (GL_COLOR);
    //  glDisable (GL_COLOR_MATERIAL);
    if (vispar.drawedtangents)
      {
	glColor3d (1, 0, 0);
	glBegin (GL_LINES);
	for (int i = 1; i <= specpoints.Size(); i++)
	  {
	    const Point3d p1 = specpoints.Get(i).p;
	    const Point3d p2 = specpoints.Get(i).p + len * specpoints.Get(i).v;
	    glVertex3d (p1.X(), p1.Y(), p1.Z());
	    glVertex3d (p2.X(), p2.Y(), p2.Z());
	  }
	glEnd();
      }

    if (vispar.drawededges)
      {
	glColor3d (1, 0, 0);
	glBegin (GL_LINES);
	for (int i = 1; i <= mesh->GetNSeg(); i++)
	  {
	    const Segment & seg = mesh -> LineSegment (i);
	    glVertex3dv ( (*mesh)[seg[0]] );
            glVertex3dv ( (*mesh)[seg[1]] );
	    // glVertex3dv ( &(*mesh)[seg[0]].X() );
	    // glVertex3dv ( &(*mesh)[seg[1]].X() );
	  }
	glEnd();
      }

    glColor3d (1, 0, 0);
    glBegin (GL_LINES);
    int edges[12][2] = 
      { { 0, 1 },
	{ 2, 3 },
	{ 4, 5 },
	{ 6, 7 },
	{ 0, 2 },
	{ 1, 3 },
	{ 4, 6 },
	{ 5, 7 },
	{ 0, 4 },
	{ 1, 5 },
	{ 2, 6 },
	{ 3, 7 } };
    for (int i = 0; i < boxes.Size(); i++)
      {
	for (int j = 0; j < 12; j++)
	  {
	    glVertex3dv ( boxes[i].GetPointNr(edges[j][0]) );
	    glVertex3dv ( boxes[i].GetPointNr(edges[j][1]) );
	  }
	/*
	glVertex3dv ( boxes[i].PMin() );
	glVertex3dv ( boxes[i].PMax() );
	*/
      }
    glEnd();



    if (vispar.drawededgenrs)
      {
	glEnable (GL_COLOR_MATERIAL);
	GLfloat textcol[3] = { GLfloat(1 - backcolor),
			       GLfloat(1 - backcolor), 
			       GLfloat(1 - backcolor) };
	glColor3fv (textcol);
	glNormal3d (0, 0, 1);
	glPushAttrib (GL_LIST_BIT);
	// glListBase (fontbase);

	char buf[20];
	for (int i = 1; i <= mesh->GetNSeg(); i++)
	  {
	    const Segment & seg = mesh -> LineSegment (i);
	    const Point3d p1 = mesh -> Point (seg[0]);
	    const Point3d p2 = mesh -> Point (seg[1]);

	    const Point3d p = Center (p1, p2);
	    glRasterPos3d (p.X(), p.Y(), p.Z());
	  
	    sprintf (buf, "%d", seg.edgenr);
	    // glCallLists (GLsizei(strlen (buf)), GL_UNSIGNED_BYTE, buf);
	    MyOpenGLText (buf);
	  }
      
	glPopAttrib ();
	glDisable (GL_COLOR_MATERIAL);
      }


    if (vispar.drawedpoints)
      {

	glColor3d (0, 0, 1);
	/*
	  glPointSize( 3.0 );

	float range[2];
	glGetFloatv(GL_POINT_SIZE_RANGE, &range[0]);
	cout << "max ptsize = " << range[0] << "-" << range[1] << endl;
      

	glBegin( GL_POINTS );
	for (int i = 1; i <= mesh -> GetNP(); i++)
	  {
	    const Point3d & p = mesh -> Point(i);
	    if (i % 2)
	      glVertex3f( p.X(), p.Y(), p.Z());
	  }
	glEnd();
	*/

	static GLubyte knoedel[] = 
	  {
	    0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe,
	  };
	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

	glDisable (GL_COLOR_MATERIAL);
	glDisable (GL_LIGHTING);
	glDisable (GL_CLIP_PLANE0);
      
	for (int i = 1; i <= mesh -> GetNP(); i++)
	  {
	    const Point3d & p = mesh -> Point(i);
	    glRasterPos3d (p.X(), p.Y(), p.Z());
	    glBitmap (7, 7, 3, 3, 0, 0, &knoedel[0]);
	  }
      }

    if (vispar.drawedpointnrs)
      {
	glEnable (GL_COLOR_MATERIAL);
	GLfloat textcol[3] = { GLfloat(1 - backcolor),
			       GLfloat(1 - backcolor),
			       GLfloat(1 - backcolor) };
	glColor3fv (textcol);
	glNormal3d (0, 0, 1);
	glPushAttrib (GL_LIST_BIT);
	// glListBase (fontbase);
      
	char buf[20];
	for (int i = 1; i <= mesh->GetNP(); i++)
	  {
	    const Point3d & p = mesh->Point(i);
	    glRasterPos3d (p.X(), p.Y(), p.Z());
	  
	    sprintf (buf, "%d", i);
	    // glCallLists (GLsizei(strlen (buf)), GL_UNSIGNED_BYTE, buf);
	    MyOpenGLText (buf);
	  }
      
	glPopAttrib ();
	glDisable (GL_COLOR_MATERIAL);
      }


    
    
    

    glPopMatrix();

    if (vispar.drawcoordinatecross)
      DrawCoordinateCross ();
    DrawNetgenLogo ();

    glFinish();  
  }
Пример #10
0
/**
 * Apply fog to a span of RGBA pixels.
 * The fog value are either in the span->array->fog array or interpolated from
 * the fog/fogStep values.
 * They fog values are either fog coordinates (Z) or fog blend factors.
 * _PreferPixelFog should be in sync with that state!
 */
void
_swrast_fog_rgba_span( const struct gl_context *ctx, SWspan *span )
{
   const SWcontext *swrast = CONST_SWRAST_CONTEXT(ctx);
   GLfloat rFog, gFog, bFog;

   ASSERT(swrast->_FogEnabled);
   ASSERT(span->arrayMask & SPAN_RGBA);

   /* compute (scaled) fog color */
   if (span->array->ChanType == GL_UNSIGNED_BYTE) {
      rFog = ctx->Fog.Color[RCOMP] * 255.0F;
      gFog = ctx->Fog.Color[GCOMP] * 255.0F;
      bFog = ctx->Fog.Color[BCOMP] * 255.0F;
   }
   else if (span->array->ChanType == GL_UNSIGNED_SHORT) {
      rFog = ctx->Fog.Color[RCOMP] * 65535.0F;
      gFog = ctx->Fog.Color[GCOMP] * 65535.0F;
      bFog = ctx->Fog.Color[BCOMP] * 65535.0F;
   }
   else {
      rFog = ctx->Fog.Color[RCOMP];
      gFog = ctx->Fog.Color[GCOMP];
      bFog = ctx->Fog.Color[BCOMP];
   }

   if (swrast->_PreferPixelFog) {
      /* The span's fog values are fog coordinates, now compute blend factors
       * and blend the fragment colors with the fog color.
       */
      switch (ctx->Fog.Mode) {
      case GL_LINEAR:
         {
            const GLfloat fogEnd = ctx->Fog.End;
            const GLfloat fogScale = (ctx->Fog.Start == ctx->Fog.End)
               ? 1.0F : 1.0F / (ctx->Fog.End - ctx->Fog.Start);
            if (span->array->ChanType == GL_UNSIGNED_BYTE) {
               GLubyte (*rgba)[4] = span->array->rgba8;
               FOG_LOOP(GLubyte, LINEAR_FOG);
            }
            else if (span->array->ChanType == GL_UNSIGNED_SHORT) {
               GLushort (*rgba)[4] = span->array->rgba16;
               FOG_LOOP(GLushort, LINEAR_FOG);
            }
            else {
               GLfloat (*rgba)[4] = span->array->attribs[FRAG_ATTRIB_COL];
               ASSERT(span->array->ChanType == GL_FLOAT);
               FOG_LOOP(GLfloat, LINEAR_FOG);
            }
         }
         break;

      case GL_EXP:
         {
            const GLfloat density = -ctx->Fog.Density;
            if (span->array->ChanType == GL_UNSIGNED_BYTE) {
               GLubyte (*rgba)[4] = span->array->rgba8;
               FOG_LOOP(GLubyte, EXP_FOG);
            }
            else if (span->array->ChanType == GL_UNSIGNED_SHORT) {
               GLushort (*rgba)[4] = span->array->rgba16;
               FOG_LOOP(GLushort, EXP_FOG);
            }
            else {
               GLfloat (*rgba)[4] = span->array->attribs[FRAG_ATTRIB_COL];
               ASSERT(span->array->ChanType == GL_FLOAT);
               FOG_LOOP(GLfloat, EXP_FOG);
            }
         }
         break;

      case GL_EXP2:
         {
            const GLfloat negDensitySquared = -ctx->Fog.Density * ctx->Fog.Density;
            if (span->array->ChanType == GL_UNSIGNED_BYTE) {
               GLubyte (*rgba)[4] = span->array->rgba8;
               FOG_LOOP(GLubyte, EXP2_FOG);
            }
            else if (span->array->ChanType == GL_UNSIGNED_SHORT) {
               GLushort (*rgba)[4] = span->array->rgba16;
               FOG_LOOP(GLushort, EXP2_FOG);
            }
            else {
               GLfloat (*rgba)[4] = span->array->attribs[FRAG_ATTRIB_COL];
               ASSERT(span->array->ChanType == GL_FLOAT);
               FOG_LOOP(GLfloat, EXP2_FOG);
            }
         }
         break;

      default:
         _mesa_problem(ctx, "Bad fog mode in _swrast_fog_rgba_span");
         return;
      }
   }
   else {
      /* The span's fog start/step/array values are blend factors in [0,1].
       * They were previously computed per-vertex.
       */
      if (span->array->ChanType == GL_UNSIGNED_BYTE) {
         GLubyte (*rgba)[4] = span->array->rgba8;
         FOG_LOOP(GLubyte, BLEND_FOG);
      }
      else if (span->array->ChanType == GL_UNSIGNED_SHORT) {
         GLushort (*rgba)[4] = span->array->rgba16;
         FOG_LOOP(GLushort, BLEND_FOG);
      }
      else {
         GLfloat (*rgba)[4] = span->array->attribs[FRAG_ATTRIB_COL];
         ASSERT(span->array->ChanType == GL_FLOAT);
         FOG_LOOP(GLfloat, BLEND_FOG);
      }
   }
}
Пример #11
0
void GLLineIlluminator::enableLighting(GLContextData& contextData) const
	{
	/* Get a pointer to the context data item: */
	DataItem* dataItem=contextData.retrieveDataItem<DataItem>(this);
	
	/* Update the material texture if it is outdated: */
	if(dataItem->materialVersion!=materialVersion)
		updateMaterial(dataItem);
	
	GLenum previousMatrixMode=glGet<GLint>(GL_MATRIX_MODE);
	
	Geometry::Matrix<GLfloat,4,4> modelView;
	if(autoViewDirection||autoLightDirection)
		{
		/* Get the modelview matrix from OpenGL: */
		GLfloat matrixArray[16];
		glGetFloatv(GL_MODELVIEW_MATRIX,matrixArray);
		modelView=Geometry::Matrix<GLfloat,4,4>::fromColumnMajor(matrixArray);
		}
	
	/* Determine the view direction: */
	Geometry::ComponentArray<GLfloat,3> viewDir(viewDirection.getXyzw());
	if(autoViewDirection)
		{
		/* Get the projection matrix from OpenGL: */
		GLfloat matrixArray[16];
		glGetFloatv(GL_PROJECTION_MATRIX,matrixArray);
		Geometry::Matrix<GLfloat,4,4> projection=Geometry::Matrix<GLfloat,4,4>::fromColumnMajor(matrixArray);
		
		/* Calculate the view direction from the OpenGL projection and modelview matrices: */
		Geometry::ComponentArray<GLfloat,4> viewPos(0.0f,0.0f,1.0f,0.0f);
		viewPos=viewPos/projection;
		viewPos=viewPos/modelView;
		
		/* Check if it's an orthogonal or perspective projection: */
		if(Math::abs(viewPos[3])<1.0e-8f)
			{
			/* Just copy the view direction: */
			viewDir=viewPos;
			}
		else
			{
			/* Calculate the direction from the view point to the scene center: */
			for(int i=0;i<3;++i)
				viewDir[i]=viewPos[i]/viewPos[3]-sceneCenter[i];
			}
		GLfloat viewDirLen=GLfloat(Geometry::mag(viewDir));
		for(int i=0;i<3;++i)
			viewDir[i]/=viewDirLen;
		}
	
	/* Determine the light direction: */
	Geometry::ComponentArray<GLfloat,3> lightDir(lightDirection.getXyzw());
	if(autoLightDirection)
		{
		/* Query the light direction from OpenGL and transform it to model coordinates: */
		Geometry::ComponentArray<GLfloat,4> lightPos;
		glGetLightPosition(autoLightIndex,lightPos.getComponents());
		lightPos=lightPos/modelView;
		
		/* Check if it's a directional or point light: */
		if(Math::abs(lightPos[3])<1.0e-8f)
			{
			/* Just copy the light direction: */
			lightDir=lightPos;
			}
		else
			{
			/* Calculate the direction from the light source to the scene center: */
			for(int i=0;i<3;++i)
				lightDir[i]=lightPos[i]/lightPos[3]-sceneCenter[i];
			}
		GLfloat lightDirLen=GLfloat(Geometry::mag(lightDir));
		for(int i=0;i<3;++i)
			lightDir[i]/=lightDirLen;
		}
	
	/* Set up the OpenGL texture matrix: */
	glMatrixMode(GL_TEXTURE);
	glPushMatrix();
	GLfloat matrix[4][4];
	for(int j=0;j<3;++j)
		{
		matrix[j][0]=lightDir[j];
		matrix[j][1]=viewDir[j];
		matrix[j][2]=0.0f;
		matrix[j][3]=0.0f;
		}
	matrix[3][0]=1.0f;
	matrix[3][1]=1.0f;
	matrix[3][2]=0.0f;
	matrix[3][3]=2.0f;
	glLoadMatrixf((const GLfloat*)matrix);
	
	/* Set the OpenGL rendering mode: */
	glPushAttrib(GL_TEXTURE_BIT);
	glBindTexture(GL_TEXTURE_2D,dataItem->materialTextureId);
	glEnable(GL_TEXTURE_2D);
	if(dataItem->materialType==INTENSITY)
		glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
	else
		glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE);
	
	/* Clean up: */
	glMatrixMode(previousMatrixMode);
	}
Пример #12
0
/*
 * RGBA copypixels with convolution.
 */
static void
copy_conv_rgba_pixels(GLcontext *ctx, GLint srcx, GLint srcy,
                      GLint width, GLint height, GLint destx, GLint desty)
{
   SWcontext *swrast = SWRAST_CONTEXT(ctx);
   struct gl_renderbuffer *drawRb = NULL;
   GLboolean quick_draw;
   GLint row;
   const GLboolean zoom = ctx->Pixel.ZoomX != 1.0F || ctx->Pixel.ZoomY != 1.0F;
   const GLuint transferOps = ctx->_ImageTransferState;
   GLfloat *dest, *tmpImage, *convImage;
   struct sw_span span;

   INIT_SPAN(span, GL_BITMAP, 0, 0, SPAN_RGBA);

   if (ctx->Depth.Test)
      _swrast_span_default_z(ctx, &span);
   if (swrast->_FogEnabled)
      _swrast_span_default_fog(ctx, &span);


   if (SWRAST_CONTEXT(ctx)->_RasterMask == 0
       && !zoom
       && destx >= 0
       && destx + width <= (GLint) ctx->DrawBuffer->Width) {
      quick_draw = GL_TRUE;
      drawRb = ctx->DrawBuffer->_ColorDrawBuffers[0][0];
   }
   else {
      quick_draw = GL_FALSE;
   }

   /* allocate space for GLfloat image */
   tmpImage = (GLfloat *) _mesa_malloc(width * height * 4 * sizeof(GLfloat));
   if (!tmpImage) {
      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCopyPixels");
      return;
   }
   convImage = (GLfloat *) _mesa_malloc(width * height * 4 * sizeof(GLfloat));
   if (!convImage) {
      _mesa_free(tmpImage);
      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glCopyPixels");
      return;
   }

   /* read source image */
   dest = tmpImage;
   for (row = 0; row < height; row++) {
      GLchan rgba[MAX_WIDTH][4];
      /* Read GLchan and convert to GLfloat */
      _swrast_read_rgba_span(ctx, ctx->ReadBuffer->_ColorReadBuffer,
                             width, srcx, srcy + row, rgba);
      chan_span_to_float(width, (CONST GLchan (*)[4]) rgba,
                         (GLfloat (*)[4]) dest);
      dest += 4 * width;
   }

   /* do the image transfer ops which preceed convolution */
   for (row = 0; row < height; row++) {
      GLfloat (*rgba)[4] = (GLfloat (*)[4]) (tmpImage + row * width * 4);
      _mesa_apply_rgba_transfer_ops(ctx,
                                    transferOps & IMAGE_PRE_CONVOLUTION_BITS,
                                    width, rgba);
   }

   /* do convolution */
   if (ctx->Pixel.Convolution2DEnabled) {
      _mesa_convolve_2d_image(ctx, &width, &height, tmpImage, convImage);
   }
   else {
      ASSERT(ctx->Pixel.Separable2DEnabled);
      _mesa_convolve_sep_image(ctx, &width, &height, tmpImage, convImage);
   }
   _mesa_free(tmpImage);

   /* do remaining post-convolution image transfer ops */
   for (row = 0; row < height; row++) {
      GLfloat (*rgba)[4] = (GLfloat (*)[4]) (convImage + row * width * 4);
      _mesa_apply_rgba_transfer_ops(ctx,
                                    transferOps & IMAGE_POST_CONVOLUTION_BITS,
                                    width, rgba);
   }

   /* write the new image */
   for (row = 0; row < height; row++) {
      const GLfloat *src = convImage + row * width * 4;
      GLint dy;

      /* convert floats back to chan */
      float_span_to_chan(width, (const GLfloat (*)[4]) src, span.array->rgba);

      /* write row to framebuffer */
      dy = desty + row;
      if (quick_draw && dy >= 0 && dy < (GLint) ctx->DrawBuffer->Height) {
         drawRb->PutRow(ctx, drawRb, width, destx, dy, span.array->rgba, NULL);
      }
      else {
         span.x = destx;
         span.y = dy;
         span.end = width;
         if (zoom) {
            _swrast_write_zoomed_rgba_span(ctx, destx, desty, &span, 
                                        (CONST GLchan (*)[4])span.array->rgba);
         }
         else {
            _swrast_write_rgba_span(ctx, &span);
         }
      }
   }

   _mesa_free(convImage);
}
Пример #13
0
// Handles the reshape event by setting the viewport so that it takes up the
// whole visible region, then sets the projection matrix to something reason-
// able that maintains proper aspect ratio.
void reshape(GLint w, GLint h) {
  glViewport(0, 0, w, h);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(65.0, GLfloat(w)/GLfloat(h), 1.0, 20.0);
}
Пример #14
0
void WaterRenderer::render(const PTransform& projection,const OGTransform& modelview,GLContextData& contextData) const
	{
	/* Get the data item: */
	DataItem* dataItem=contextData.retrieveDataItem<DataItem>(this);
	
	/* Calculate the required matrices: */
	PTransform projectionModelview=projection;
	projectionModelview*=modelview;
	
	/* Bind the water rendering shader: */
	glUseProgramObjectARB(dataItem->waterShader);
	const GLint* ulPtr=dataItem->waterShaderUniforms;
	
	/* Bind the water quantity texture: */
	glActiveTextureARB(GL_TEXTURE0_ARB);
	waterTable->bindQuantityTexture(contextData);
	glUniform1iARB(*(ulPtr++),0);
	
	/* Bind the bathymetry texture: */
	glActiveTextureARB(GL_TEXTURE1_ARB);
	waterTable->bindBathymetryTexture(contextData);
	glUniform1iARB(*(ulPtr++),1);
	
	/* Calculate and upload the vertex transformation from grid space to eye space: */
	PTransform modelviewGridTransform=gridTransform;
	modelviewGridTransform.leftMultiply(modelview);
	glUniformARB(*(ulPtr++),modelviewGridTransform);
	
	/* Calculate the transposed tangent plane transformation from grid space to eye space: */
	PTransform tangentModelviewGridTransform=tangentGridTransform;
	tangentModelviewGridTransform*=Geometry::invert(modelview);
	
	/* Transpose and upload the transposed tangent plane transformation: */
	const Scalar* tmvgtPtr=tangentModelviewGridTransform.getMatrix().getEntries();
	GLfloat tangentModelviewGridTransformMatrix[16];
	GLfloat* tmvgtmPtr=tangentModelviewGridTransformMatrix;
	for(int i=0;i<16;++i,++tmvgtPtr,++tmvgtmPtr)
		*tmvgtmPtr=GLfloat(*tmvgtPtr);
	glUniformMatrix4fvARB(*(ulPtr++),1,GL_FALSE,tangentModelviewGridTransformMatrix);
	
	/* Calculate and upload the vertex transformation from grid space to clip space: */
	PTransform projectionModelviewGridTransform=gridTransform;
	projectionModelviewGridTransform.leftMultiply(modelview);
	projectionModelviewGridTransform.leftMultiply(projection);
	glUniformARB(*(ulPtr++),projectionModelviewGridTransform);
	
	/* Bind the vertex and index buffers: */
	glBindBufferARB(GL_ARRAY_BUFFER_ARB,dataItem->vertexBuffer);
	glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB,dataItem->indexBuffer);
	
	/* Draw the surface: */
	GLVertexArrayParts::enable(Vertex::getPartsMask());
	glVertexPointer(static_cast<const Vertex*>(0));
	GLuint* indexPtr=0;
	for(unsigned int y=1;y<waterGridSize[1];++y,indexPtr+=waterGridSize[0]*2)
		glDrawElements(GL_QUAD_STRIP,waterGridSize[0]*2,GL_UNSIGNED_INT,indexPtr);
	GLVertexArrayParts::disable(Vertex::getPartsMask());
	
	/* Unbind all textures and buffers: */
	glBindBufferARB(GL_ARRAY_BUFFER_ARB,0);
	glBindBufferARB(GL_ELEMENT_ARRAY_BUFFER_ARB,0);
	glBindTexture(GL_TEXTURE_RECTANGLE_ARB,0);
	glActiveTextureARB(GL_TEXTURE0_ARB);
	glBindTexture(GL_TEXTURE_RECTANGLE_ARB,0);
	
	/* Unbind the water rendering shader: */
	glUseProgramObjectARB(0);
	}
void TextureBlitter::drawTexture(int textureId, const QRectF &targetRect, const QSize &targetSize, int depth, bool targethasInvertedY, bool sourceHasInvertedY)
{

    glViewport(0,0,targetSize.width(),targetSize.height());
    GLfloat zValue = depth / 1000.0f;
    //Set Texture and Vertex coordinates
    const GLfloat textureCoordinates[] = {
        0, 0,
        1, 0,
        1, 1,
        0, 1
    };

    GLfloat x1 = targetRect.left();
    GLfloat x2 = targetRect.right();
    GLfloat y1, y2;
    if (targethasInvertedY) {
        if (sourceHasInvertedY) {
            y1 = targetRect.top();
            y2 = targetRect.bottom();
        } else {
            y1 = targetRect.bottom();
            y2 = targetRect.top();
        }
    } else {
        if (sourceHasInvertedY) {
            y1 = targetSize.height() - targetRect.top();
            y2 = targetSize.height() - targetRect.bottom();
        } else {
            y1 = targetSize.height() - targetRect.bottom();
            y2 = targetSize.height() - targetRect.top();
        }
    }

    const GLfloat vertexCoordinates[] = {
        GLfloat(x1), GLfloat(y1), zValue,
        GLfloat(x2), GLfloat(y1), zValue,
        GLfloat(x2), GLfloat(y2), zValue,
        GLfloat(x1), GLfloat(y2), zValue
    };



    //Set matrix to transfrom geometry values into gl coordinate space.
    m_transformMatrix.setToIdentity();
    m_transformMatrix.scale( 2.0f / targetSize.width(), 2.0f / targetSize.height() );
    m_transformMatrix.translate(-targetSize.width() / 2.0f, -targetSize.height() / 2.0f);

    //attach the data!
    QOpenGLContext *currentContext = QOpenGLContext::currentContext();
    currentContext->functions()->glEnableVertexAttribArray(m_vertexCoordEntry);
    currentContext->functions()->glEnableVertexAttribArray(m_textureCoordEntry);

    currentContext->functions()->glVertexAttribPointer(m_vertexCoordEntry, 3, GL_FLOAT, GL_FALSE, 0, vertexCoordinates);
    currentContext->functions()->glVertexAttribPointer(m_textureCoordEntry, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinates);
    m_shaderProgram->setUniformValue(m_matrixLocation, m_transformMatrix);

    glBindTexture(GL_TEXTURE_2D, textureId);

    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

    glBindTexture(GL_TEXTURE_2D, 0);

    currentContext->functions()->glDisableVertexAttribArray(m_vertexCoordEntry);
    currentContext->functions()->glDisableVertexAttribArray(m_textureCoordEntry);
}
Пример #16
0
Vector Vector::operator/(const GLfloat & r)
{
	Vector tmp(*this);
	tmp = tmp * (GLfloat(1) / r);
	return tmp;
}
void Globe::load_mapdata(string mapname, int lat, int lng) {
    if (DEBUG) cout << "Loading map " << mapname << endl;
    ifstream file(mapname.c_str(), std::ios::in | std::ios::binary);
    short heights[map_size][map_size];

    if(!file) {
        cout << "Error opening file: " << mapname << endl;
    } else {
        unsigned char buffer[2];
        for (int i = map_size-1; i >= 0; i--) {
            for (int j = 0; j < map_size; j++) {
                if(!file.read( reinterpret_cast<char*>(buffer), sizeof(buffer) )) {
                    cout << "Error reading file: " << mapname << endl;
                }
                heights[j][i] = (buffer[0] << 8) | buffer[1]; // zamieniamy bajty
            }
        }
    }

    // ponizsze ladowanie mozna przeniesc wyzej
    GLfloat tmpa, tmpb;
    GLfloat tmph;
    GLfloat tlat, tlng;
    vsize = engine->vertices.size();

    for (int j = 0; j < map_size; j++) {
        for (int i = 0; i < map_size; i++) {
            if (engine->current_mode == 3) {
                tmpa = lat + j * DEGREES;
                tmpb = lng + i * DEGREES;
                tmph = GLfloat (heights[i][j]);
            } else {
                tmpa = lng * 1200 + i;
                tmpb = lat * 1200 + j;
//                tmpa = lng * ANGLES;
//                tmpb = log(tan((lat * ANGLES) / 2));

                tmph = GLfloat (heights[i][j]);
                if (i % 1201 == 0 && j % 1201 == 0) cout << "V(" << tmpa << ", " << tmpb << ", " << tmph << ") [" << lng << ", " << lat << "]\n";
            }

            engine->vertices.push_back({
                tmpa, tmpb, tmph
            });
        }
    }

    // tworzenie trójkątów
    for (int l = 0; l < LODS; l++) {
        int inc;
        if (STRICTER_LOD) {
            inc = pow(2.0,float(l));
        } else {
            int inc = l+1;
        }

        int last = ((map_size - inc) / inc) * inc;

        for (int i = 0; i < map_size-inc; i += inc) {
            for (int j = 0; j < map_size-inc; j += inc) {
//                engine->indices_points[l].push_back(engine->vertices.size() - 1);
                engine->indices_triangles[l].push_back(vsize + i * map_size + j);
                engine->indices_triangles[l].push_back(vsize + i * map_size + j + inc);
                engine->indices_triangles[l].push_back(vsize + (i+inc) * map_size + j);

                engine->indices_triangles[l].push_back(vsize + i * map_size + j + inc);
                engine->indices_triangles[l].push_back(vsize + (i+inc) * map_size + j);
                engine->indices_triangles[l].push_back(vsize + (i+inc) * map_size + j + inc);
            }

            // jesli to nie jest ostatnie i
            if (i + inc < map_size - inc) {
                engine->indices_triangles[l].push_back(vsize + i * map_size + last);
                engine->indices_triangles[l].push_back(vsize + i * map_size + 1200);
                engine->indices_triangles[l].push_back(vsize + (i+inc) * map_size + last);

                engine->indices_triangles[l].push_back(vsize + i * map_size + 1200);
                engine->indices_triangles[l].push_back(vsize + (i+inc) * map_size + last);
                engine->indices_triangles[l].push_back(vsize + (i+inc) * map_size + 1200);
            }
        }

        for (int j = 0; j < map_size-inc; j += inc) {
            engine->indices_triangles[l].push_back(vsize + last * map_size + j);
            engine->indices_triangles[l].push_back(vsize + last * map_size + j + inc);
            engine->indices_triangles[l].push_back(vsize + 1200 * map_size + j);

            engine->indices_triangles[l].push_back(vsize + last * map_size + j + inc);
            engine->indices_triangles[l].push_back(vsize + 1200 * map_size + j);
            engine->indices_triangles[l].push_back(vsize + 1200 * map_size + j + inc);
        }

        engine->indices_triangles[l].push_back(vsize + last * map_size + last);
        engine->indices_triangles[l].push_back(vsize + last * map_size + 1200);
        engine->indices_triangles[l].push_back(vsize + 1200 * map_size + last);

        engine->indices_triangles[l].push_back(vsize + last * map_size + 1200);
        engine->indices_triangles[l].push_back(vsize + 1200 * map_size + last);
        engine->indices_triangles[l].push_back(vsize + 1200 * map_size + 1200);
    }
}
Пример #18
0
void Ship::Render(const vector3d &viewCoords, const matrix4x4d &viewTransform)
{
	if ((!IsEnabled()) && !m_flightState) return;
	LmrObjParams &params = GetLmrObjParams();
	
	if ( (this != reinterpret_cast<Ship*>(Pi::player)) ||
	     (Pi::worldView->GetCamType() == WorldView::CAM_EXTERNAL) ) {
		m_shipFlavour.ApplyTo(&params);
		SetLmrTimeParams();
		params.angthrust[0] = float(-m_angThrusters.x);
		params.angthrust[1] = float(-m_angThrusters.y);
		params.angthrust[2] = float(-m_angThrusters.z);
		params.linthrust[0] = float(m_thrusters.x);
		params.linthrust[1] = float(m_thrusters.y);
		params.linthrust[2] = float(m_thrusters.z);
		params.argDoubles[0] = m_wheelState;
		params.argDoubles[5] = double(m_equipment.Get(Equip::SLOT_FUELSCOOP));
		params.argDoubles[6] = double(m_equipment.Get(Equip::SLOT_ENGINE));
		params.argDoubles[7] = double(m_equipment.Get(Equip::SLOT_ECM));
		params.argDoubles[8] = double(m_equipment.Get(Equip::SLOT_SCANNER));
		params.argDoubles[9] = double(m_equipment.Get(Equip::SLOT_ATMOSHIELD));
		params.argDoubles[10] = double(m_equipment.Get(Equip::SLOT_LASER, 0));
		params.argDoubles[11] = double(m_equipment.Get(Equip::SLOT_LASER, 1));
		for (int i=0; i<8; i++) {
			params.argDoubles[12+i] = double(m_equipment.Get(Equip::SLOT_MISSILE, i));
		}
		params.argDoubles[20] = m_flightState;

		//strncpy(params.pText[0], GetLabel().c_str(), sizeof(params.pText));
		RenderLmrModel(viewCoords, viewTransform);

		// draw shield recharge bubble
		if (m_stats.shield_mass_left < m_stats.shield_mass) {
			float shield = 0.01f*GetPercentShields();
			glDisable(GL_LIGHTING);
			glEnable(GL_BLEND);
			glColor4f((1.0f-shield),shield,0.0,0.33f*(1.0f-shield));
			glPushMatrix();
			glTranslatef(GLfloat(viewCoords.x), GLfloat(viewCoords.y), GLfloat(viewCoords.z));
			Render::State::UseProgram(Render::simpleShader);
			gluSphere(Pi::gluQuadric, GetLmrCollMesh()->GetBoundingRadius(), 20, 20);
			Render::State::UseProgram(0);
			glPopMatrix();
			glEnable(GL_LIGHTING);
			glDisable(GL_BLEND);
		}
	}
	if (m_ecmRecharge > 0.0f) {
		// pish effect
		vector3f v[100];
		for (int i=0; i<100; i++) {
			const double r1 = Pi::rng.Double()-0.5;
			const double r2 = Pi::rng.Double()-0.5;
			const double r3 = Pi::rng.Double()-0.5;
			v[i] = viewTransform * (
				GetPosition() +
				GetLmrCollMesh()->GetBoundingRadius() *
				vector3d(r1, r2, r3).Normalized()
			);
		}
		Color c(0.5,0.5,1.0,1.0);
		float totalRechargeTime = GetECMRechargeTime();
		if (totalRechargeTime >= 0.0f) {
			c.a = m_ecmRecharge / totalRechargeTime;
		}
		GLuint tex = util_load_tex_rgba(PIONEER_DATA_DIR"/textures/ecm.png");

		glBindTexture(GL_TEXTURE_2D, tex);
		Render::PutPointSprites(100, v, 50.0f, c);
	}

#if 0
	if (IsFiringLasers()) {
		glPushMatrix();
		TransformToModelCoords(camFrame);
		RenderLaserfire();
		glPopMatrix();
	}
#endif /* 0 */
}
Пример #19
0
//--------------------------------------------------------------
void ofApp::update(){

	pointLight.setOrientation(ofVec3f(0,0,180));
	pointLight2.setOrientation(ofVec3f(0,0,180));
	pointLight3.setOrientation(ofVec3f(0,0,180));

	pointLight.setPosition(
		cos(ofGetElapsedTimef()*.5)*floorLimits*0.7, 
		floorLimits/4, 
		sin(ofGetElapsedTimef()*.5)*floorLimits*0.7);
    pointLight2.setPosition(
		sin(ofGetElapsedTimef()*.5)*floorLimits*0.5, 
		floorLimits/3, 
		cos(ofGetElapsedTimef()*.5)*floorLimits*0.5);
    pointLight3.setPosition(
		floorLimits/2, 
		floorLimits/2, 
		-floorLimits/2);

	
		
	//Cam test
	//camObjective.setPosition(ofVec3f(0,(floorLimits/2)-ofGetElapsedTimef()*10,0));

	//Test random controlPoints
	/*circ++;

	if(circ%cicl == 0){
		for(int i=0; i<kBezierPoints; i++) {
			bzNodes[i].setPosition(ofVec3f(ofRandom(-floorLimits,floorLimits),20,ofRandom(-floorLimits,floorLimits)));
			ctrlpoints[i][0]=bzNodes[i].getX();
			ctrlpoints[i][1]=bzNodes[i].getY();
			ctrlpoints[i][2]=bzNodes[i].getZ();
		}
		glMap1f(GL_MAP1_VERTEX_3, 0.0, 1.0, 3, 4, &ctrlpoints[0][0]);
		glEnable(GL_MAP1_VERTEX_3);
	}
	if(circ > cicl){
		circ = 0;
	}*/

	//Update control points
	for(int i=0; i<kBezierPoints; i++) {
		ctrlpoints[i][0]=bzNodes[i].getX();
		ctrlpoints[i][1]=bzNodes[i].getY();
		ctrlpoints[i][2]=bzNodes[i].getZ();
	}

	actorNode.setPosition(bzNodes[0].getGlobalPosition());
	
	GLfloat b2 = (sin(ofGetElapsedTimef()*.5) + 1) / 2;
	GLfloat a1 = GLfloat(1.0-b2);
		
	//Draw actor node
	ofVec3f lastPosition = actorNode.getPosition();

	ofVec3f nextPosition = ofVec3f(
		bzNodes[0].getX()*a1*a1*a1 + bzNodes[1].getX()*3*a1*a1*b2 + bzNodes[2].getX()*3*a1*b2*b2 + bzNodes[3].getX()*b2*b2*b2,
		bzNodes[0].getY()*a1*a1*a1 + bzNodes[1].getY()*3*a1*a1*b2 + bzNodes[2].getY()*3*a1*b2*b2 + bzNodes[3].getY()*b2*b2*b2,
		bzNodes[0].getZ()*a1*a1*a1 + bzNodes[1].getZ()*3*a1*a1*b2 + bzNodes[2].getZ()*3*a1*b2*b2 + bzNodes[3].getZ()*b2*b2*b2);

	nextPosition.y = nextPosition.y + humanScale*2.25;
	actorNode.setPosition(nextPosition);
	myHuman.lookAt(nextPosition);
	myHuman.setPosition(nextPosition);
	myHuman.update();

	/*Update current steo and actor direction
	if(int(ofGetElapsedTimef())% 3 == 0 ){
		currentStep += actorDirection;
		
		if(0>currentStep || currentStep>bezierMovSubDiv){
			actorDirection*=-1;
		}
	}*/
	
	//Calculate and edit current bezir point
	ofVec2f mouse(mouseX, mouseY);
	for(int i = 0; i < kBezierPoints; i++) {
		ofVec3f cur = cam.worldToScreen(bzNodes[i].getGlobalPosition());
		bzPoints[i].setGlobalPosition(bzNodes[i].getGlobalPosition());
		float distance = cur.distance(mouse);
		if(i == 0 || distance < nearestDistance) {
			nearestDistance = distance;
			nearestVertex = cur;
			nearestIndex = i;
		}
	}
	

	
}
Пример #20
0
	void RenderImage(
		double time,
		const Mat4f& torus_matrix,
		const Mat4f& light_proj_matrix
	)
	{
		// this is going into the on-screen framebuffer
		DefaultFramebuffer().Bind(Framebuffer::Target::Draw);

		gl.ClearColor(1.0f, 0.9f, 0.8f, 0.0f);
		gl.Viewport(width, height);
		gl.Clear().ColorBuffer().DepthBuffer();
		gl.CullFace(Face::Back);
		//
		transf_prog.light_proj_matrix.Set(light_proj_matrix);

		Mat4f perspective = CamMatrixf::PerspectiveX(
			Degrees(60),
			float(width)/height,
			1, 60
		);

		// setup the camera
		Vec3f camera_target(0.0f, 0.8f, 0.0f);
		auto camera = CamMatrixf::Orbiting(
			camera_target,
			GLfloat(7.0 - SineWave(time / 14.0)*3.0),
			FullCircles(time / 26.0),
			Degrees(45 + SineWave(time / 17.0) * 40)
		);
		Vec3f camera_position = camera.Position();
		transf_prog.camera_matrix.Set(perspective*camera);
		transf_prog.camera_position.Set(camera_position);

		// render into the depth buffer
		shadow_pp.Bind();

		gl.Enable(Capability::PolygonOffsetFill);
		gl.ColorMask(false, false, false, false);

		transf_prog.model_matrix = ModelMatrixf();
		plane.Draw();

		transf_prog.model_matrix.Set(torus_matrix);
		torus.Draw();

		gl.ColorMask(true, true, true, true);
		gl.Disable(Capability::PolygonOffsetFill);

		gl.Enable(Capability::Blend);
		gl.Disable(Capability::Blend);

		// render into the color buffer
		sketch_pp.Bind();

		gl.Enable(Capability::Blend);

		transf_prog.model_matrix = ModelMatrixf();
		transf_prog.texture_matrix.Set(Mat2f(Vec2f(3.0, 0.0), Vec2f(0.0, 3.0)));
		plane.Draw();

		transf_prog.model_matrix.Set(torus_matrix);
		transf_prog.texture_matrix.Set(Mat2f(Vec2f(8.0, 0.0), Vec2f(0.0, 2.0)));
		torus.Draw([](GLuint phase) -> bool { return phase <  4; });
		transf_prog.texture_matrix.Set(Mat2f(Vec2f(0.0, 2.0), Vec2f(8.0, 0.0)));
		torus.Draw([](GLuint phase) -> bool { return phase >= 4; });

		// render the edges
		line_pp.Bind();

		transf_prog.model_matrix = ModelMatrixf();
		plane.DrawEdges();

		transf_prog.model_matrix.Set(torus_matrix);
		torus.DrawEdges();

		gl.Disable(Capability::Blend);
	}
Пример #21
0
void CanvasWidget::paintGL(void)
{
    int i = 0;
    int j = 0;

    glClearColor(1, 1, 1, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   // glLoadIdentity();
    //glColor3f(0.0, 0.0, 0.0);
    //glClearColor(1, 1, 1, 1);
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix ();
    glScalef(curScale, curScale, curScale);
    glRotatef(glm::degrees(xCurAngle), 0.0, 1.0, 0.0);
    glRotatef(glm::degrees(yCurAngle), 1.0, 0.0, 0.0);
    int color;

    for (i = 0; i <= PATCHES_NUM * bezierPatch.getN() * bezierPatch.getStride(); i += SURFACE_STRIDE) {
        glBegin(GL_LINE_STRIP);
        for (j = 0; j<= PATCHES_NUM * bezierPatch.getN() * bezierPatch.getStride(); j += SURFACE_STRIDE) {
            color = GLfloat(surfaceImage[i][j].z) / 255.0f * colors.size();
            glColor3f(colors[color].red, colors[color].green, colors[color].blue);
            glVertex3f(surfaceImage[i][j].x + xCenter - MAP_SIZE/2, surfaceImage[i][j].y + yCenter - MAP_SIZE/2, surfaceImage[i][j].z);
        }
        glEnd();
    }
    for (j = 0; j <= PATCHES_NUM * bezierPatch.getN() * bezierPatch.getStride(); j += SURFACE_STRIDE) {
        glBegin(GL_LINE_STRIP);
        for (i = 0; i<= PATCHES_NUM * bezierPatch.getN() * bezierPatch.getStride(); i += SURFACE_STRIDE) {
            color = GLfloat(surfaceImage[i][j].z) / 255.0f * colors.size();
            glColor3f(colors[color].red, colors[color].green, colors[color].blue);
            glVertex3f(surfaceImage[i][j].x + xCenter - MAP_SIZE/2, surfaceImage[i][j].y + yCenter - MAP_SIZE/2, surfaceImage[i][j].z);
        }
        glEnd();
    }
    //glTranslatef(0, 0, 0);

//    for (i = 0; i <= PATCHES_NUM * bezierPatch.getN() * bezierPatch.getStride(); i += SURFACE_STRIDE) {
//        glBegin(GL_LINE_STRIP);
//        for (j = 0; j<= PATCHES_NUM * bezierPatch.getN() * bezierPatch.getStride(); j += SURFACE_STRIDE) {
//            glVertex3f(surfaceImage[i][j].x, surfaceImage[i][j].y, surfaceImage[i][j].z);
//        }
//        glEnd();
//    }
//    for (j = 0; j <= PATCHES_NUM * bezierPatch.getN() * bezierPatch.getStride(); j += SURFACE_STRIDE) {
//        glBegin(GL_LINE_STRIP);
//        for (i = 0; i<= PATCHES_NUM * bezierPatch.getN() * bezierPatch.getStride(); i += SURFACE_STRIDE) {
//            glVertex3f(surfaceImage[i][j].x, surfaceImage[i][j].y, surfaceImage[i][j].z);
//        }
//        glEnd();
//    }



    //glTranslatef(3*width/4, 3*height/4, 0);
    //glTranslatef(-width/4, -height/4, 0);
   // glTranslatef(-width, -height, 0);

//    glColor3f(1.0, 0.0, 0.0);

//    for(int i = 0; i < selectedPatches.size(); ++i) {
//        int x = selectedPatches[i].x();
//        int y = selectedPatches[i].y();
//        if (x >= 0 && x < surfaceImage.size() && y >= 0 && y < surfaceImage[0].size()) {

//            glBegin(GL_QUADS);
//            glVertex3f(surfaceImage[x][y].x, surfaceImage[x][y].y, surfaceImage[x][y].z);
//            glVertex3f(surfaceImage[x + SURFACE_STRIDE][y].x,
//                    surfaceImage[x+SURFACE_STRIDE][y].y, surfaceImage[x+SURFACE_STRIDE][y].z);
//            glVertex3f(surfaceImage[x+SURFACE_STRIDE][y+SURFACE_STRIDE].x,
//                    surfaceImage[x+SURFACE_STRIDE][y+SURFACE_STRIDE].y,
//                    surfaceImage[x+SURFACE_STRIDE][y+SURFACE_STRIDE].z);
//            glVertex3f(surfaceImage[x][y+SURFACE_STRIDE].x,
//                    surfaceImage[x][y+SURFACE_STRIDE].y, surfaceImage[x][y+SURFACE_STRIDE].z);
//            glEnd();
//        }
//    }

    glPopMatrix ();
    glFlush();
}
Пример #22
0
void SimpleGreedy::computeLayer( Uint8*** p_mask, bool*** voxminguid, Vector3< Uint16 > dimensions )
{
	Color _color;
	Sint32 i, j, k;
	Sint32 _w, _h, _face;
	bool done;
	char ext;
	GLfloat _ext2;
	i = dimensions.x;
	k = dimensions.y;
	j = dimensions.z;

	Uint8*** mask = new Uint8**[dimensions.x];
	for ( Uint16 i = 0; i < dimensions.x; i++ )
	{
		mask[i] = new Uint8*[dimensions.y];
		for ( Uint16 j = 0; j < dimensions.y; j++ )
		{
			mask[i][j] = new Uint8[dimensions.z];
			for ( Uint16 k = 0; k < dimensions.z; k++ )
			{
				mask[i][j][k] = p_mask[i][j][k];
			}
		}
	}
	int lx, ly, lz;

	for ( _face = 0; _face < 6; _face++ )
	{
		for ( Sint32 x = 0; x < i; x++ )
		{
			for ( Sint32 y = 0; y < k; y++ )
			{
				for ( Sint32 z = 0; z < j; z++ )
				{
					lx = x + 1;
					ly = y + 1;
					lz = z + 1;
					if ( !voxminguid[lx][ly][lz] || ( ( mask[x][y][z] ) & ( 2 << _face ) ) != ( 2 << _face ) )
						continue;
					ext = ( _face % 2 == 0 ? 1 : -1 );
					_ext2 = ( _face % 2 == 0 ? 1.f : 0.f );
					done = false;
					if ( ( _face == 0 || _face == 1 ) ) // EAST/WEST
					{
						for ( _w = 1; z + _w < j 
							&& voxminguid[lx][ly][lz + _w] 
							&& ( ( mask[x][y][z + _w] & ( 2 << _face ) ) == ( 2 << _face ) )
							&& voxminguid[lx][ly][lz + _w] == voxminguid[lx][ly][lz]
							; )
							_w++;

						for ( _h = 1; y + _h < k; _h++ )
						{
							for ( Sint32 m = 0; m < _w; m++ )
							{
								if ( !voxminguid[lx][ly + _h][lz + m]
									|| ( mask[x][y + _h][z + m] & ( 2 << _face ) ) != ( 2 << _face )
									|| voxminguid[lx][ly + _h][lz + m] != voxminguid[lx][ly][lz]
									)
								{
									done = true;
									break;
								}
							}
							if ( done )
								break;
						}

						_color = Color( 255, 255, 255, 255 );
						_color = _color / 1.125f;

						if ( _ext2 )
						{
							m_vertices.push_back( { GLfloat( x + _ext2 ), GLfloat( y + _h ), GLfloat( z + 0 ) } );
							m_vertices.push_back( { GLfloat( x + _ext2 ), GLfloat( y + _h ), GLfloat( z + _w ) } );
							m_vertices.push_back( { GLfloat( x + _ext2 ), GLfloat( y + 0 ), GLfloat( z + _w ) } );
							m_vertices.push_back( { GLfloat( x + _ext2 ), GLfloat( y + 0 ), GLfloat( z + 0 ) } );

							m_colors.push_back( _color );
							m_colors.push_back( _color );
							m_colors.push_back( _color );
							m_colors.push_back( _color );
						}
						else
						{
							m_vertices.push_back( { GLfloat( x + _ext2 ), GLfloat( y + _h ), GLfloat( z + 0 ) } );
							m_vertices.push_back( { GLfloat( x + _ext2 ), GLfloat( y + 0 ), GLfloat( z + 0 ) } );
							m_vertices.push_back( { GLfloat( x + _ext2 ), GLfloat( y + 0 ), GLfloat( z + _w ) } );
							m_vertices.push_back( { GLfloat( x + _ext2 ), GLfloat( y + _h ), GLfloat( z + _w ) } );

							m_colors.push_back( _color );
							m_colors.push_back( _color );
							m_colors.push_back( _color );
							m_colors.push_back( _color );
						}

						for ( Sint32 l = 0; l < _h; l++ )
						{
							for ( Sint32 m = 0; m < _w; m++ )
							{
								mask[x][y + l][z + m] -= ( 2 << _face );
							}
						}
					}
					else if ( ( _face == 2 || _face == 3 ) ) // TOP/BOTTOM
					{
						for ( _w = 0; x + _w < i
							&& voxminguid[lx + _w][ly][lz]
							&& ( ( mask[x + _w][y][z] & ( 2 << _face ) ) == ( 2 << _face ) )
							&& voxminguid[lx + _w][ly][lz] == voxminguid[lx][ly][lz]
							; )
							_w++;


						for ( _h = 1; z + _h < j; _h++ )
						{
							for ( Sint32 m = 0; m < _w; m++ )
							{
								if ( ( !voxminguid[lx + m][ly][lz + _h]
									|| ( mask[x + m][y][z + _h] & ( 2 << _face ) ) != ( 2 << _face ) )
									|| voxminguid[lx + m][ly][lz + _h] != voxminguid[lx][ly][lz]
									)
								{
									done = true;
									break;
								}
							}
							if ( done )
								break;
						}

						_color = Color( 255, 255, 255, 255 );
						//_color = _color * ( 1 - ( - GLfloat( y ) ) / 512 );

						if ( _face == 3 )
							_color = _color / 1.2f;

						if ( _ext2 )
						{
							m_vertices.push_back( { GLfloat( x + 0 ), GLfloat( y + _ext2 ), GLfloat( z + _h ) } );
							m_vertices.push_back( { GLfloat( x + _w ), GLfloat( y + _ext2 ), GLfloat( z + _h ) } );
							m_vertices.push_back( { GLfloat( x + _w ), GLfloat( y + _ext2 ), GLfloat( z + 0 ) } );
							m_vertices.push_back( { GLfloat( x + 0 ), GLfloat( y + _ext2 ), GLfloat( z + 0 ) } );

							m_colors.push_back( _color );
							m_colors.push_back( _color );
							m_colors.push_back( _color );
							m_colors.push_back( _color );
						}
						else
						{
							m_vertices.push_back( { GLfloat( x + 0 ), GLfloat( y + _ext2 ), GLfloat( z + _h ) } );
							m_vertices.push_back( { GLfloat( x + 0 ), GLfloat( y + _ext2 ), GLfloat( z + 0 ) } );
							m_vertices.push_back( { GLfloat( x + _w ), GLfloat( y + _ext2 ), GLfloat( z + 0 ) } );
							m_vertices.push_back( { GLfloat( x + _w ), GLfloat( y + _ext2 ), GLfloat( z + _h ) } );

							m_colors.push_back( _color );
							m_colors.push_back( _color );
							m_colors.push_back( _color );
							m_colors.push_back( _color );
						}

						for ( Sint32 l = 0; l < _h; l++ )
						{
							for ( Sint32 m = 0; m < _w; m++ )
							{
								mask[x + m][y][z + l] -= ( 2 << _face );
							}
						}
					}
					else if ( ( _face == 4 || _face == 5 ) ) // NORTH/SOUTH
					{
						for ( _w = 1; x + _w < i
							&& voxminguid[lx + _w][ly][lz]
							&& ( ( mask[x + _w][y][z] & ( 2 << _face ) ) == ( 2 << _face ) )
							&& voxminguid[lx + _w][ly][lz] == voxminguid[lx][ly][lz]
							; )
							_w++;

						for ( _h = 1; y + _h < k; _h++ )
						{
							for ( Sint32 m = 0; m < _w; m++ )
							{
								if ( ( !voxminguid[lx + m][ly + _h][lz]
									|| ( mask[x + m][y + _h][z] & ( 2 << _face ) ) != ( 2 << _face ) )
									|| voxminguid[lx + m][ly + _h][lz] != voxminguid[lx][ly][lz]
									)
								{
									done = true;
									break;
								}
							}
							if ( done )
								break;
						}

						_color = Color( 255, 255, 255, 255 );
						_color = _color / 1.2f;

						if ( _ext2 )
						{
							m_vertices.push_back( { GLfloat( x + _w ), GLfloat( y + _h ), GLfloat( z + _ext2 ) } );
							m_vertices.push_back( { GLfloat( x + 0 ), GLfloat( y + _h ), GLfloat( z + _ext2 ) } );
							m_vertices.push_back( { GLfloat( x + 0 ), GLfloat( y + 0 ), GLfloat( z + _ext2 ) } );
							m_vertices.push_back( { GLfloat( x + _w ), GLfloat( y + 0 ), GLfloat( z + _ext2 ) } );

							m_colors.push_back( _color );
							m_colors.push_back( _color );
							m_colors.push_back( _color );
							m_colors.push_back( _color );
						}
						else
						{
							m_vertices.push_back( { GLfloat( x + _w ), GLfloat( y + _h ), GLfloat( z + _ext2 ) } );
							m_vertices.push_back( { GLfloat( x + _w ), GLfloat( y + 0 ), GLfloat( z + _ext2 ) } );
							m_vertices.push_back( { GLfloat( x + 0 ), GLfloat( y + 0 ), GLfloat( z + _ext2 ) } );
							m_vertices.push_back( { GLfloat( x + 0 ), GLfloat( y + _h ), GLfloat( z + _ext2 ) } );

							m_colors.push_back( _color );
							m_colors.push_back( _color );
							m_colors.push_back( _color );
							m_colors.push_back( _color );
						}

						for ( Sint32 l = 0; l < _h; l++ )
						{
							for ( Sint32 m = 0; m < _w; m++ )
							{
								mask[x + m][y + l][z] -= ( 2 << _face );
							}
						}
					}
				}
			}
		}
	}

	for ( Uint16 i = 0; i < dimensions.x; i++ )
	{
		for ( Uint16 j = 0; j < dimensions.y; j++ )
		{
			delete[] mask[i][j];
		}
		delete[] mask[i];
	}
	delete[] mask;
	mask = 0;
}
Пример #23
0
/**
 * ColorBuffer = Accum * value
 */
static void
accum_return(struct gl_context *ctx, GLfloat value,
             GLint xpos, GLint ypos, GLint width, GLint height)
{
   struct gl_framebuffer *fb = ctx->DrawBuffer;
   struct gl_renderbuffer *accRb = fb->Attachment[BUFFER_ACCUM].Renderbuffer;
   GLubyte *accMap, *colorMap;
   GLint accRowStride, colorRowStride;
   GLuint buffer;

   /* Map accum buffer */
   ctx->Driver.MapRenderbuffer(ctx, accRb, xpos, ypos, width, height,
                               GL_MAP_READ_BIT,
                               &accMap, &accRowStride);
   if (!accMap) {
      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glAccum");
      return;
   }

   /* Loop over destination buffers */
   for (buffer = 0; buffer < fb->_NumColorDrawBuffers; buffer++) {
      struct gl_renderbuffer *colorRb = fb->_ColorDrawBuffers[buffer];
      const GLboolean masking = (!ctx->Color.ColorMask[buffer][RCOMP] ||
                                 !ctx->Color.ColorMask[buffer][GCOMP] ||
                                 !ctx->Color.ColorMask[buffer][BCOMP] ||
                                 !ctx->Color.ColorMask[buffer][ACOMP]);
      GLbitfield mappingFlags = GL_MAP_WRITE_BIT;

      if (masking)
         mappingFlags |= GL_MAP_READ_BIT;

      /* Map color buffer */
      ctx->Driver.MapRenderbuffer(ctx, colorRb, xpos, ypos, width, height,
                                  mappingFlags, &colorMap, &colorRowStride);
      if (!colorMap) {
         _mesa_error(ctx, GL_OUT_OF_MEMORY, "glAccum");
         continue;
      }

      if (accRb->Format == MESA_FORMAT_SIGNED_RGBA_16) {
         const GLfloat scale = value / 32767.0f;
         GLint i, j;
         GLfloat (*rgba)[4], (*dest)[4];

         rgba = malloc(width * 4 * sizeof(GLfloat));
         dest = malloc(width * 4 * sizeof(GLfloat));

         if (rgba && dest) {
            for (j = 0; j < height; j++) {
               GLshort *acc = (GLshort *) accMap;

               for (i = 0; i < width; i++) {
                  rgba[i][0] = acc[i * 4 + 0] * scale;
                  rgba[i][1] = acc[i * 4 + 1] * scale;
                  rgba[i][2] = acc[i * 4 + 2] * scale;
                  rgba[i][3] = acc[i * 4 + 3] * scale;
               }

               if (masking) {

                  /* get existing colors from dest buffer */
                  _mesa_unpack_rgba_row(colorRb->Format, width, colorMap, dest);

                  /* use the dest colors where mask[channel] = 0 */
                  if (ctx->Color.ColorMask[buffer][RCOMP] == 0) {
                     for (i = 0; i < width; i++)
                        rgba[i][RCOMP] = dest[i][RCOMP];
                  }
                  if (ctx->Color.ColorMask[buffer][GCOMP] == 0) {
                     for (i = 0; i < width; i++)
                        rgba[i][GCOMP] = dest[i][GCOMP];
                  }
                  if (ctx->Color.ColorMask[buffer][BCOMP] == 0) {
                     for (i = 0; i < width; i++)
                        rgba[i][BCOMP] = dest[i][BCOMP];
                  }
                  if (ctx->Color.ColorMask[buffer][ACOMP] == 0) {
                     for (i = 0; i < width; i++)
                        rgba[i][ACOMP] = dest[i][ACOMP];
                  }
               }

               _mesa_pack_float_rgba_row(colorRb->Format, width,
                                         (const GLfloat (*)[4]) rgba, colorMap);

               accMap += accRowStride;
               colorMap += colorRowStride;
            }
         }
         else {
            _mesa_error(ctx, GL_OUT_OF_MEMORY, "glAccum");
         }
         free(rgba);
         free(dest);
      }
      else {
         /* other types someday? */
      }

      ctx->Driver.UnmapRenderbuffer(ctx, colorRb);
   }

   ctx->Driver.UnmapRenderbuffer(ctx, accRb);
}
Пример #24
0
void ogl::mesh::calc_tangent()
{
    // Assume all tangent vectors were zeroed during loading.  Enumerate faces.

    for (ogl::face_i fi = faces.begin(); fi != faces.end(); ++fi)
    {
        // Compute the vertex position differences.

        const GLfloat *vi = vv[fi->i].v;
        const GLfloat *vj = vv[fi->j].v;
        const GLfloat *vk = vv[fi->k].v;

        GLfloat dv0[3], dv1[3];

        dv0[0] = vj[0] - vi[0];
        dv0[1] = vj[1] - vi[1];
        dv0[2] = vj[2] - vi[2];

        dv1[0] = vk[0] - vi[0];
        dv1[1] = vk[1] - vi[1];
        dv1[2] = vk[2] - vi[2];

        // Compute the vertex texture coordinate differences.

        const GLfloat *si = uv[fi->i].v;
        const GLfloat *sj = uv[fi->j].v;
        const GLfloat *sk = uv[fi->k].v;

        GLfloat ds0[2], ds1[2];

        ds0[0] = sj[0] - si[0];
        ds0[1] = sj[1] - si[1];

        ds1[0] = sk[0] - si[0];
        ds1[1] = sk[1] - si[1];

        // Compute the tangent vector.

        GLfloat t[3];

        t[0] = ds1[1] * dv0[0] - ds0[1] * dv1[0];
        t[1] = ds1[1] * dv0[1] - ds0[1] * dv1[1];
        t[2] = ds1[1] * dv0[2] - ds0[1] * dv1[2];

        // Accumulate the vertex tangent vectors.

        GLfloat d = t[0] * t[0] + t[1] * t[1] + t[2] * t[2];

        if (d > 0.0f)
        {
            const GLfloat k = sqrtf(d);

            GLfloat *ti = tv[fi->i].v;
            GLfloat *tj = tv[fi->j].v;
            GLfloat *tk = tv[fi->k].v;

            ti[0] += t[0] / k;
            ti[1] += t[1] / k;
            ti[2] += t[2] / k;

            tj[0] += t[0] / k;
            tj[1] += t[1] / k;
            tj[2] += t[2] / k;

            tk[0] += t[0] / k;
            tk[1] += t[1] / k;
            tk[2] += t[2] / k;
        }
    }

    // Orthonormalize all tangent vectors.

    assert(tv.size() == nv.size());

    for (unsigned int i = 0; i < tv.size(); ++i)
    {
        vec3 n = vec3(double(nv[i].v[0]), double(nv[i].v[1]), double(nv[i].v[2]));
        vec3 t = vec3(double(tv[i].v[0]), double(tv[i].v[1]), double(tv[i].v[2]));

        t = normal(cross(cross(n, t), n));

        tv[i].v[0] = GLfloat(t[0]);
        tv[i].v[1] = GLfloat(t[1]);
        tv[i].v[2] = GLfloat(t[2]);
    }
}
Пример #25
0
void DisplayHandler () // display callback function
{
	if (bRotate) 
	{
		fCameraAngle[0] += 1.0 ;
		fCameraAngle[2] += 1.0 ;
	}
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) ;
	glLoadIdentity() ;

	SetCamera() ;

	if (!bPause)
	{
		GLfloat fTempX = GLfloat(iLastMouseX) / GLfloat(iWinWidth) ;
		GLfloat fTempY = GLfloat(iLastMouseY) / GLfloat(iWinHeight) ;
		GLfloat fFixedX = (Player.ptLocation.dX - 8.65) / -17.3 ;
		GLfloat fFixedZ = (Player.ptLocation.dZ - 8.65) / -17.3 ;
		if (bRightMouseDown)
		{
			if (!(fFixedX + 0.02 > fTempX && fFixedX - 0.02 < fTempX))
			{
				if (fFixedX > fTempX)
				{
					Player.ptLocation.dX += 0.1 ;
					if (Player.ptAngle.dZ > -20) 
						Player.ptAngle.dZ -= 5.0 ;
				} else
				{
					Player.ptLocation.dX -= 0.1 ;
					if (Player.ptAngle.dZ < 20) 
						Player.ptAngle.dZ += 5.0 ;
				}
			} else
			{
				if (Player.ptAngle.dZ < 0) Player.ptAngle.dZ += 5.0 ;
				else if (Player.ptAngle.dZ > 0)	Player.ptAngle.dZ -= 5.0 ;
			}
			if (!(fFixedZ + 0.1 > fTempY && fFixedZ - 0.02 < fTempY))
			{
				if (fFixedZ > fTempY)
				{
					Player.ptLocation.dZ += 0.1 ;
				} else 
				{
					Player.ptLocation.dZ -= 0.1 ;
				}
			}
		} else Player.ptAngle.dZ = 0 ;

		if (randp() > 0.98) AddPlanet() ;
		AddStar() ;
		AddStar() ;
		AddStar() ;
		AddStar() ;
		AddStar() ;
		AddStar() ;

		if (/*!bExplode && */iCount % 15 == 0) SpawnEnemy() ;

		if (!bExplode && bAutofire && iCount % 4 == 0) FireShot(&Player, pPlayerShots) ;

		iCount ++ ;

	}
	
	DisplayStars() ;
	DisplayPlanets() ;
	DisplayEnemies() ;

	DisplayShots(pPlayerShots) ;
	DisplayShots(pEnemyShots) ;

	if (bExplode && !bPause)
	{
		if (iCount == 0) 
		{
			printf("Game over\n") ;
			MakeExplosion(Player.ptLocation, 1000) ;
		}
	} else 
	{
		if (iCount % 4)
		{
			Particle *pNew = new Particle ;
			pNew->ptLocation.dX = Player.ptLocation.dX + randp() * 0.5 - 0.25;
			pNew->ptLocation.dY = Player.ptLocation.dY + 0.3 * randp() ;
			pNew->ptLocation.dZ = Player.ptLocation.dZ - 1.5 + 0.2 * randp() ;
			pNew->ptVelocity.dX = 0 ;
			pNew->ptVelocity.dY = 0 ;
			pNew->ptVelocity.dZ = -0.2 ;
			pNew->ptColor.dX = 0.98 ;
			pNew->ptColor.dY = 0.59 + 0.3 * randp() - 0.15 ;
			pNew->ptColor.dZ = 0.01 ;
			pNew->dAlpha = 0.7 ;
			pNew->dMass = 1 ;
			pNew->dLife = 7 * randp() + 3 ;
			pNew->ptAcceleration = 0 ;
			Particles.AddBack(pNew) ;
		}

		Player.Display() ;
	}

	LinkedListNode<Particle> *pTravParticles = Particles.pHead ;
	LinkedListNode<Particle> *pTempParticle ;
	
	while (pTravParticles != 0)
	{
		pTravParticles->pValue->dLife -- ;
		if (pTravParticles->pValue->dLife <= 0)
		{
			pTempParticle = pTravParticles ;
			pTravParticles = pTravParticles->pNext ;
			Particles.Remove(pTempParticle, true) ;
		} else
		{
			pTravParticles->pValue->Apply(0.9) ;
			
			DisplayParticle(pTravParticles->pValue) ;
			
			pTravParticles = pTravParticles->pNext ;
		}
	}
	
		
	glFinish() ;
	glutSwapBuffers() ;
	glutPostRedisplay() ;
}
Пример #26
0
// Here we have to support all pnames with both int and float params.
// See this discussion:
//   https://www.khronos.org/webgl/public-mailing-list/archives/1008/msg00014.html
void
WebGLTexture::TexParameter(TexTarget texTarget, GLenum pname, GLint* maybeIntParam,
                           GLfloat* maybeFloatParam)
{
    MOZ_ASSERT(maybeIntParam || maybeFloatParam);

    GLint   intParam   = maybeIntParam   ? *maybeIntParam   : GLint(*maybeFloatParam);
    GLfloat floatParam = maybeFloatParam ? *maybeFloatParam : GLfloat(*maybeIntParam);

    bool isPNameValid = false;
    switch (pname) {
    // GLES 2.0.25 p76:
    case LOCAL_GL_TEXTURE_WRAP_S:
    case LOCAL_GL_TEXTURE_WRAP_T:
    case LOCAL_GL_TEXTURE_MIN_FILTER:
    case LOCAL_GL_TEXTURE_MAG_FILTER:
        isPNameValid = true;
        break;

    // GLES 3.0.4 p149-150:
    case LOCAL_GL_TEXTURE_BASE_LEVEL:
    case LOCAL_GL_TEXTURE_COMPARE_MODE:
    case LOCAL_GL_TEXTURE_COMPARE_FUNC:
    case LOCAL_GL_TEXTURE_MAX_LEVEL:
    case LOCAL_GL_TEXTURE_MAX_LOD:
    case LOCAL_GL_TEXTURE_MIN_LOD:
    case LOCAL_GL_TEXTURE_WRAP_R:
        if (mContext->IsWebGL2())
            isPNameValid = true;
        break;

    case LOCAL_GL_TEXTURE_MAX_ANISOTROPY_EXT:
        if (mContext->IsExtensionEnabled(WebGLExtensionID::EXT_texture_filter_anisotropic))
            isPNameValid = true;
        break;
    }

    if (!isPNameValid) {
        mContext->ErrorInvalidEnumInfo("texParameter: pname", pname);
        return;
    }

    ////////////////
    // Validate params and invalidate if needed.

    bool paramBadEnum = false;
    bool paramBadValue = false;

    switch (pname) {
    case LOCAL_GL_TEXTURE_BASE_LEVEL:
    case LOCAL_GL_TEXTURE_MAX_LEVEL:
        paramBadValue = (intParam < 0);
        break;

    case LOCAL_GL_TEXTURE_COMPARE_MODE:
        paramBadValue = (intParam != LOCAL_GL_NONE &&
                         intParam != LOCAL_GL_COMPARE_REF_TO_TEXTURE);
        break;

    case LOCAL_GL_TEXTURE_COMPARE_FUNC:
        switch (intParam) {
        case LOCAL_GL_LEQUAL:
        case LOCAL_GL_GEQUAL:
        case LOCAL_GL_LESS:
        case LOCAL_GL_GREATER:
        case LOCAL_GL_EQUAL:
        case LOCAL_GL_NOTEQUAL:
        case LOCAL_GL_ALWAYS:
        case LOCAL_GL_NEVER:
            break;

        default:
            paramBadValue = true;
            break;
        }
        break;

    case LOCAL_GL_TEXTURE_MIN_FILTER:
        switch (intParam) {
        case LOCAL_GL_NEAREST:
        case LOCAL_GL_LINEAR:
        case LOCAL_GL_NEAREST_MIPMAP_NEAREST:
        case LOCAL_GL_LINEAR_MIPMAP_NEAREST:
        case LOCAL_GL_NEAREST_MIPMAP_LINEAR:
        case LOCAL_GL_LINEAR_MIPMAP_LINEAR:
            break;

        default:
            paramBadEnum = true;
            break;
        }
        break;

    case LOCAL_GL_TEXTURE_MAG_FILTER:
        switch (intParam) {
        case LOCAL_GL_NEAREST:
        case LOCAL_GL_LINEAR:
            break;

        default:
            paramBadEnum = true;
            break;
        }
        break;

    case LOCAL_GL_TEXTURE_WRAP_S:
    case LOCAL_GL_TEXTURE_WRAP_T:
    case LOCAL_GL_TEXTURE_WRAP_R:
        switch (intParam) {
        case LOCAL_GL_CLAMP_TO_EDGE:
        case LOCAL_GL_MIRRORED_REPEAT:
        case LOCAL_GL_REPEAT:
            break;

        default:
            paramBadEnum = true;
            break;
        }
        break;

    case LOCAL_GL_TEXTURE_MAX_ANISOTROPY_EXT:
        if (maybeFloatParam && floatParam < 1.0f)
            paramBadValue = true;
        else if (maybeIntParam && intParam < 1)
            paramBadValue = true;

        break;
    }

    if (paramBadEnum) {
        if (maybeIntParam) {
            mContext->ErrorInvalidEnum("texParameteri: pname 0x%04x: Invalid param"
                                       " 0x%04x.",
                                       pname, intParam);
        } else {
            mContext->ErrorInvalidEnum("texParameterf: pname 0x%04x: Invalid param %g.",
                                       pname, floatParam);
        }
        return;
    }

    if (paramBadValue) {
        if (maybeIntParam) {
            mContext->ErrorInvalidValue("texParameteri: pname 0x%04x: Invalid param %i"
                                        " (0x%x).",
                                        pname, intParam, intParam);
        } else {
            mContext->ErrorInvalidValue("texParameterf: pname 0x%04x: Invalid param %g.",
                                        pname, floatParam);
        }
        return;
    }

    ////////////////
    // Store any needed values

    switch (pname) {
    case LOCAL_GL_TEXTURE_BASE_LEVEL:
        mBaseMipmapLevel = intParam;
        ClampLevelBaseAndMax();
        intParam = mBaseMipmapLevel;
        break;

    case LOCAL_GL_TEXTURE_MAX_LEVEL:
        mMaxMipmapLevel = intParam;
        ClampLevelBaseAndMax();
        intParam = mMaxMipmapLevel;
        break;

    case LOCAL_GL_TEXTURE_MIN_FILTER:
        mMinFilter = intParam;
        break;

    case LOCAL_GL_TEXTURE_MAG_FILTER:
        mMagFilter = intParam;
        break;

    case LOCAL_GL_TEXTURE_WRAP_S:
        mWrapS = intParam;
        break;

    case LOCAL_GL_TEXTURE_WRAP_T:
        mWrapT = intParam;
        break;

    case LOCAL_GL_TEXTURE_COMPARE_MODE:
        mTexCompareMode = intParam;
        break;

    // We don't actually need to store the WRAP_R, since it doesn't change texture
    // completeness rules.
    }

    // Only a couple of pnames don't need to invalidate our resolve status cache.
    switch (pname) {
    case LOCAL_GL_TEXTURE_MAX_ANISOTROPY_EXT:
    case LOCAL_GL_TEXTURE_WRAP_R:
        break;

    default:
        InvalidateResolveCache();
        break;
    }

    ////////////////

    mContext->MakeContextCurrent();
    if (maybeIntParam)
        mContext->gl->fTexParameteri(texTarget.get(), pname, intParam);
    else
        mContext->gl->fTexParameterf(texTarget.get(), pname, floatParam);
}
Пример #27
0
void Image::draw(GLContextData& contextData) const
	{
	/* Draw parent class decorations: */
	Widget::draw(contextData);
	
	/* Draw the image frame, in case there is one: */
	glBegin(GL_QUAD_STRIP);
	glColor(getBackgroundColor());
	glNormal3f(0.0f,0.0f,1.0f);
	glVertex(imageBox.getCorner(0));
	glVertex(getInterior().getCorner(0));
	glVertex(imageBox.getCorner(1));
	glVertex(getInterior().getCorner(1));
	glVertex(imageBox.getCorner(3));
	glVertex(getInterior().getCorner(3));
	glVertex(imageBox.getCorner(2));
	glVertex(getInterior().getCorner(2));
	glVertex(imageBox.getCorner(0));
	glVertex(getInterior().getCorner(0));
	glEnd();
	
	/* Get the context data item: */
	DataItem* dataItem=contextData.retrieveDataItem<DataItem>(this);
	
	/* Set up OpenGL state: */
	glPushAttrib(GL_ENABLE_BIT);
	glEnable(GL_TEXTURE_2D);
	glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE);
	
	/* Bind the texture object: */
	glBindTexture(GL_TEXTURE_2D,dataItem->textureObjectId);
	
	/* Check if the texture object is outdated: */
	if(dataItem->version!=version)
		{
		/* Upload the new texture image: */
		image.glTexImage2D(GL_TEXTURE_2D,0,GL_RGB8,!dataItem->npotdtSupported);
		
		/* Update the texture image's size: */
		if(dataItem->npotdtSupported)
			{
			/* Copy the image's size: */
			for(int i=0;i<2;++i)
				dataItem->textureSize[i]=image.getSize(i);
			}
		else
			{
			/* Power-of-two pad the image's size: */
			for(int i=0;i<2;++i)
				for(dataItem->textureSize[i]=1;dataItem->textureSize[i]<image.getSize(i);dataItem->textureSize[i]<<=1)
					;
			}
		
		/* Mark the texture object as up-to-date: */
		dataItem->version=version;
		}
	
	/* Check if the texture coordinate cache is outdated: */
	if(dataItem->regionVersion!=regionVersion)
		{
		/* Calculate the new image region's texture coordinates: */
		dataItem->regionTex[0]=GLfloat(region[0])/GLfloat(dataItem->textureSize[0]);
		if(dataItem->regionTex[0]<0.0f)
			dataItem->regionTex[0]=0.0f;
		dataItem->regionTex[1]=GLfloat(region[1])/GLfloat(dataItem->textureSize[1]);
		if(dataItem->regionTex[1]<0.0f)
			dataItem->regionTex[1]=0.0f;
		dataItem->regionTex[2]=GLfloat(region[2])/GLfloat(dataItem->textureSize[0]);
		if(dataItem->regionTex[2]>GLfloat(image.getWidth())/dataItem->textureSize[0])
			dataItem->regionTex[2]=GLfloat(image.getWidth())/dataItem->textureSize[0];
		dataItem->regionTex[3]=GLfloat(region[3])/GLfloat(dataItem->textureSize[1]);
		if(dataItem->regionTex[3]>GLfloat(image.getHeight())/dataItem->textureSize[1])
			dataItem->regionTex[3]=GLfloat(image.getHeight())/dataItem->textureSize[1];
		
		/* Mark the texture coordinate cache as up-to-date: */
		dataItem->regionVersion=regionVersion;
		}
	
	/* Draw the image: */
	glBegin(GL_QUADS);
	glTexCoord2f(dataItem->regionTex[0],dataItem->regionTex[1]);
	glVertex(imageBox.getCorner(0));
	glTexCoord2f(dataItem->regionTex[2],dataItem->regionTex[1]);
	glVertex(imageBox.getCorner(1));
	glTexCoord2f(dataItem->regionTex[2],dataItem->regionTex[3]);
	glVertex(imageBox.getCorner(3));
	glTexCoord2f(dataItem->regionTex[0],dataItem->regionTex[3]);
	glVertex(imageBox.getCorner(2));
	glEnd();
	
	/* Protect the texture object: */
	glBindTexture(GL_TEXTURE_2D,0);
	
	/* Restore OpenGL state: */
	glPopAttrib();
	}
Пример #28
0
	void bar_widget::handle_draw() const
	{
		int x_offset = x();
		{
			color_save_context color_saver;

			// draw color under end caps.			
			graphics::draw_rect(rect(x()+scale_, y()+scale_, left_cap_width_-2*scale_, height()-2*scale_), graphics::color(bar_color_));
			graphics::draw_rect(rect(x()+left_cap_width_+total_bar_length_, y()+scale_, right_cap_width_-scale_, height()-2*scale_), graphics::color(drained_segments_ ? drained_bar_color_ : bar_color_));

			// background for active segments.
			int anim_offset = animation_current_position_*scale_;
			graphics::draw_rect(rect(x()+left_cap_width_, y(), active_bar_length_+anim_offset, height()), graphics::color(bar_color_));

			// background for drained segments.
			if(drained_segments_ || animating_) {
				graphics::draw_rect(rect(x()+active_bar_length_+left_cap_width_+anim_offset, y(), drained_bar_length_-anim_offset, height()), graphics::color(drained_bar_color_));
			}
			
			draw_ticks(x()+left_cap_width_, segments_-drained_segments_+(drained_segments_?1:0), tick_mark_color_);
			draw_ticks(x()+left_cap_width_+active_bar_length_, drained_segments_, drained_tick_mark_color_);
		}

		// left cap
		if(left_cap_.area.w() == 0) {
			graphics::blit_texture(left_cap_.texture, x_offset, y(), left_cap_width_, height(), rotate_);
		} else {
			graphics::blit_texture(left_cap_.texture, x_offset, y(), left_cap_width_, height(), rotate_,
				GLfloat(left_cap_.area.x())/left_cap_.texture.width(),
				GLfloat(left_cap_.area.y())/left_cap_.texture.height(),
				GLfloat(left_cap_.area.x2())/left_cap_.texture.width(),
				GLfloat(left_cap_.area.y2())/left_cap_.texture.height());
		}
		x_offset += left_cap_width_;
		// bar
		if(bar_.area.w() == 0) {
			graphics::blit_texture(bar_.texture, x_offset, y(), total_bar_length_, height(), rotate_);
		} else {
			graphics::blit_texture(bar_.texture, x_offset, y(), total_bar_length_, height(), rotate_,
				GLfloat(bar_.area.x())/bar_.texture.width(),
				GLfloat(bar_.area.y())/bar_.texture.height(),
				GLfloat(bar_.area.x2())/bar_.texture.width(),
				GLfloat(bar_.area.y2())/bar_.texture.height());
		}
		x_offset += total_bar_length_;

		// right cap
		if(right_cap_.area.w() == 0) {
			graphics::blit_texture(left_cap_.texture, x_offset, y(), right_cap_width_, height(), rotate_);
		} else {
			graphics::blit_texture(right_cap_.texture, x_offset, y(), right_cap_width_, height(), rotate_,
				GLfloat(right_cap_.area.x())/right_cap_.texture.width(),
				GLfloat(right_cap_.area.y())/right_cap_.texture.height(),
				GLfloat(right_cap_.area.x2())/right_cap_.texture.width(),
				GLfloat(right_cap_.area.y2())/right_cap_.texture.height());
		}
	}
Пример #29
0
void CompasWidget::resizeGL(int w, int h){
	m_proj.setToIdentity();
	m_proj.perspective(45.0f, GLfloat(w) / h, 0.01f, 100.0f);
}
Пример #30
0
/**
* Load an MD2 model from file.
*
* Note: MD2 format stores model's data in little-endian ordering.  On
* big-endian machines, you'll have to perform proper conversions.
*/
GLuint md2model::ReadMD2Model (const char *filename)
{
	FILE *fp;
	int i;

	fp = fopen (filename, "rb");
	if (!fp)
	{
		fprintf (stderr, "Error: couldn't open \"%s\"!\n", filename);
		return 0;
	}

	/* Read header */
	fread (&mdl.header, 1, sizeof (struct md2_header_t), fp);

	if ((mdl.header.ident != 844121161) ||
		(mdl.header.version != 8))
	{
		/* Error! */
		fprintf (stderr, "Error: bad version or identifier\n");
		fclose (fp);
		return 0;
	}

	/* Memory allocations */
	mdl.skins = (struct md2_skin_t *)
		malloc (sizeof (struct md2_skin_t) * mdl.header.num_skins);
	mdl.texcoords = (struct md2_texCoord_t *)
		malloc (sizeof (struct md2_texCoord_t) * mdl.header.num_st);
	mdl.triangles = (struct md2_triangle_t *)
		malloc (sizeof (struct md2_triangle_t) * mdl.header.num_tris);
	mdl.frames = (struct md2_frame_t *)
		malloc (sizeof (struct md2_frame_t) * mdl.header.num_frames);
	mdl.glcmds = (int *)malloc (sizeof (int) * mdl.header.num_glcmds);

	/* Read model data */
	fseek (fp, mdl.header.offset_skins, SEEK_SET);
	fread (mdl.skins, sizeof (struct md2_skin_t),
		mdl.header.num_skins, fp);

	fseek (fp, mdl.header.offset_st, SEEK_SET);
	fread (mdl.texcoords, sizeof (struct md2_texCoord_t),
		mdl.header.num_st, fp);

	fseek (fp, mdl.header.offset_tris, SEEK_SET);
	fread (mdl.triangles, sizeof (struct md2_triangle_t),
		mdl.header.num_tris, fp);

	fseek (fp, mdl.header.offset_glcmds, SEEK_SET);
	fread (mdl.glcmds, sizeof (int), mdl.header.num_glcmds, fp);

	/* Read frames */
	fseek (fp, mdl.header.offset_frames, SEEK_SET);
	for (i = 0; i < mdl.header.num_frames; ++i)
	{
		/* Memory allocation for vertices of this frame */
		mdl.frames[i].verts = (struct md2_vertex_t *)
			malloc (sizeof (struct md2_vertex_t) * mdl.header.num_vertices);

		/* Read frame data */
		fread (mdl.frames[i].scale, sizeof (md2vec3), 1, fp);
		fread (mdl.frames[i].translate, sizeof (md2vec3), 1, fp);
		fread (mdl.frames[i].name, sizeof (char), 16, fp);
		fread (mdl.frames[i].verts, sizeof (struct md2_vertex_t),
			mdl.header.num_vertices, fp);
	}

	fclose (fp);

	// now generate VBO data and create mesh
	// then save the data we actually need and free all the stuff we no longer need
	// this is required to allow the correct generation of normals etc

	int j;
	GLfloat s, t;
	md2vec3 v, *norm;
	struct md2_frame_t *pframe;
	struct md2_vertex_t *pvert;

	//std::vector<GLfloat> verts;
	// these automatic variables will be created on stack and automatically deleted when this
	// function ends - no need to delete
	std::vector<GLfloat> tex_coords;
	std::vector<GLfloat> norms;
	std::vector<GLuint> indices;

	pframe = &mdl.frames[0]; // first frame
	// For each triangle 
	// The bad news for MD2 is that we need to expand the triangles to get the data
	// The number of tex coords need not match the number of vertices, and the number of normals
	// is different again. So we need to calculate each vertex
	// Is it possible to use indexing and remove duplicates though...
	// But I'll not bother doing that for this aged format that I'm definately dumping next year
	// (about 8 years overdue...! :-D )
	for (i = 0; i < mdl.header.num_tris; ++i)
	{
		// For each vertex 
		for (j = 0; j < 3; ++j)
		{
			// Get texture coordinates 
			tex_coords.push_back( (GLfloat)mdl.texcoords[mdl.triangles[i].st[j]].s / mdl.header.skinwidth );
			tex_coords.push_back( (GLfloat)mdl.texcoords[mdl.triangles[i].st[j]].t / mdl.header.skinheight );

			// get current vertex
			pvert = &pframe->verts[mdl.triangles[i].vertex[j]];

			// Get normals 
			//norm = anorms_table[pvert->normalIndex][0];
			norms.push_back(anorms_table[pvert->normalIndex][0]);
			norms.push_back(anorms_table[pvert->normalIndex][1]);
			norms.push_back(anorms_table[pvert->normalIndex][2]);

			// Vertices 
			// Doing these scaling operations *every* refresh is *very* wasteful
			// Should do all the scaling calculations once only, when loading the file
			//verts.push_back( pframe->scale[0] * pvert->v[0] + pframe->translate[0] );
			//verts.push_back( pframe->scale[1] * pvert->v[1] + pframe->translate[1] );
			//verts.push_back( pframe->scale[2] * pvert->v[2] + pframe->translate[2] );
			
		}
	}
	// now repeat for each frame...
	int k = 0;
	GLfloat *verts;
	vertDataSize = mdl.header.num_tris * 9;
	for (k=0;k<mdl.header.num_frames;++k) {
		verts = new GLfloat[vertDataSize];
		pframe = &mdl.frames[k]; // first frame
		for (i = 0; i < mdl.header.num_tris; ++i)
		{
			// For each vertex 
			for (j = 0; j < 3; ++j)
			{
				// get current vertex
				pvert = &pframe->verts[mdl.triangles[i].vertex[j]];
				verts[(i*3 + j)*3] = GLfloat(pframe->scale[0] * pvert->v[0] + pframe->translate[0]);
				verts[(i*3 + j)*3+1] = GLfloat(pframe->scale[1] * pvert->v[1] + pframe->translate[1]);
				verts[(i*3 + j)*3+2] = GLfloat(pframe->scale[2] * pvert->v[2] + pframe->translate[2]);
			}
		}
		vertData.push_back(verts);
	}

	// initialise animVerts with frame 0 data
	animVerts = new GLfloat[vertDataSize];
	memcpy(animVerts,vertData[0],vertDataSize*sizeof(float));


	GLuint VAO;
	VAO = rt3d::createMesh(mdl.header.num_tris * 3,vertData[0],nullptr,norms.data(),tex_coords.data());
	
	// actually have all the data we need, so call FreeModel
	this->FreeModel();

	return VAO;
}