Beispiel #1
0
Matrix rot(double w, double axis[], double point[])
{
	////
	double theta = w * 180 / M_PI; //needed as glRotate* takes degrees
	double matrix[16];

	glPushMatrix();
	glLoadIdentity();

	glTranslated(point[0], point[1], point[2]);
	glRotated(theta, axis[0], axis[1], axis[2]);
	glTranslated(-point[0], -point[1], -point[2]);

	glGetDoublev(GL_MODELVIEW_MATRIX, matrix);

	glPopMatrix();

	Matrix C(4, 4, matrix);

	return C.traspose();

	
}
void FGLRenderBuffers::ClearFrameBuffer(bool stencil, bool depth)
{
	GLboolean scissorEnabled;
	GLint stencilValue;
	GLdouble depthValue;
	glGetBooleanv(GL_SCISSOR_TEST, &scissorEnabled);
	glGetIntegerv(GL_STENCIL_CLEAR_VALUE, &stencilValue);
	glGetDoublev(GL_DEPTH_CLEAR_VALUE, &depthValue);
	glDisable(GL_SCISSOR_TEST);
	glClearColor(0.0, 0.0, 0.0, 0.0);
	glClearDepth(0.0);
	glClearStencil(0);
	GLenum flags = GL_COLOR_BUFFER_BIT;
	if (stencil)
		flags |= GL_STENCIL_BUFFER_BIT;
	if (depth)
		flags |= GL_DEPTH_BUFFER_BIT;
	glClear(flags);
	glClearStencil(stencilValue);
	glClearDepth(depthValue);
	if (scissorEnabled)
		glEnable(GL_SCISSOR_TEST);
}
Beispiel #3
0
void C3dCamera::SetNearClipPlane(GLdouble fNear)
{
	m_fNear = fNear;

	// Reset the projection matrix (coordinate system)
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	
	if(m_bPerspective)
		// Perspective transformations.
		gluPerspective(m_fFovY, m_fAspect, m_fNear, m_fFar);

	else
		// Orthographic transformations.
		glOrtho(m_fLeft, m_fRight, m_fBottom, m_fTop, m_fNear, m_fFar);	

	// Save the Projection matrix.  This is used later for
	// conversion of mouse coordinates to world coordinates.
	glGetDoublev(GL_PROJECTION_MATRIX, m_dProjectionMatrix);

	// Reset the ModelView matrix
	glMatrixMode(GL_MODELVIEW);
}
Beispiel #4
0
void output(int x, int y, float r, float g, float b, int font, std::string string)
{
    glMatrixMode(GL_PROJECTION); // change the current matrix to PROJECTION
    double matrix[16]; // 16 doubles in stack memory
    glGetDoublev(GL_PROJECTION_MATRIX, matrix); // get the values from PROJECTION matrix to local variable
    glLoadIdentity(); // reset PROJECTION matrix to identity matrix
    glOrtho(0, 800, 0, 600, -5, 5); // orthographic perspective
    glMatrixMode(GL_MODELVIEW); // change current matrix to MODELVIEW matrix again
    glLoadIdentity(); // reset it to identity matrix
    glPushMatrix(); // push current state of MODELVIEW matrix to stack
    //glLoadIdentity();
    glRasterPos2d(10, 10); // raster position in 2D
    int len, i;
    len = (int)string.size();
    for (i = 0; i < len; i++) {
        glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, string[i]);
    }
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glLoadMatrixd(matrix);
    glMatrixMode(GL_MODELVIEW);
    
}
Beispiel #5
0
void CBall::Init()
{
	static float dif_orange[4] = {0.75,0.4,0.2,1.0};
	static float amb_orange[4] = {0.5,0.2,0.1,1.0};
	static float spec[4] = {1.0,1.0,1.0,1.0};

	glPushMatrix();
	glLoadIdentity();
	glTranslatef(0.000,  0.000,  1.100);
	glGetDoublev(GL_MODELVIEW_MATRIX, position);
	glPopMatrix();

	material.SetDiffuse(dif_orange);
	material.SetAmbient(amb_orange);
	material.SetSpecular(spec);
	material.SetShininess(300);

	radius = 0.040;

	//body設定
	bBall = dBodyCreate(world);
	dBodySetAutoDisableFlag(bBall,0);
	dBodySetPosition(bBall, position[12+0], position[12+1], position[12+2]);

	dMass mass;
	dMassSetSphereTotal(&(mass),0.010,0.040);
	dBodySetMass (bBall ,&(mass));

	//geom設定
	transBall = dCreateGeomTransform(space);
	gBall = dCreateSphere (0,0.040);
	dGeomSetPosition(gBall, 0 ,0, 0.002);//重心が3mmずれてる
	dGeomTransformSetGeom(transBall, gBall);

	dGeomSetBody(transBall, bBall);

}
Beispiel #6
0
void MapPreview::onMouseMotion(GtkWidget* widget, GdkEventMotion* ev, MapPreview* self) {
	if (ev->state & GDK_BUTTON1_MASK) { // dragging with mouse button
		static gdouble _lastX = ev->x;
		static gdouble _lastY = ev->y;

		// Calculate the mouse delta as a vector in the XY plane, and store the
		// current position for the next event.
		Vector3 deltaPos(ev->x - _lastX,
						 _lastY - ev->y,
						 0);
		_lastX = ev->x;
		_lastY = ev->y;
		
		// Calculate the axis of rotation. This is the mouse vector crossed with the Z axis,
		// to give a rotation axis in the XY plane at right-angles to the mouse delta.
		static Vector3 _zAxis(0, 0, 1);
		Vector3 axisRot = deltaPos.crossProduct(_zAxis);
		
		// Grab the GL widget, and update the modelview matrix with the 
		// additional rotation
		if (gtkutil::GLWidget::makeCurrent(widget)) {

			// Premultiply the current modelview matrix with the rotation,
			// in order to achieve rotations in eye space rather than object
			// space. At this stage we are only calculating and storing the
			// matrix for the GLDraw callback to use.
			glLoadIdentity();
			glRotated(-2, axisRot.x(), axisRot.y(), axisRot.z());
			glMultMatrixd(self->_rotation);

			// Save the new GL matrix for GL draw
			glGetDoublev(GL_MODELVIEW_MATRIX, self->_rotation);

			gtk_widget_queue_draw(widget); // trigger the GLDraw method to draw the actual model
		}
	}
}
void LightPosition::prepare()
{
	if (!_lightIsInWorldCoords)
	{
		glGetLightfv(GL_LIGHT0, GL_POSITION, _lightPositionf);
		gmVector4 eyeLP;
		for(size_t i = 0; i < 4; i++) 
			eyeLP[i] = _lightPositionf[i];
		
		GLdouble modelview[16];
		glGetDoublev(GL_MODELVIEW_MATRIX,modelview);
		gmMatrix4 _m(modelview[0], modelview[4], modelview[8], modelview[12],
					modelview[1], modelview[5], modelview[9], modelview[13],
					modelview[2], modelview[6], modelview[10], modelview[14],
					modelview[3], modelview[7], modelview[11], modelview[15]);
		gmMatrix4 _m_inv = _m.inverse();
			
		_lightPosition = _m_inv * eyeLP;
	}
	else
	{
		_lightPosition = _lightPositionInput;
	}
}
Beispiel #8
0
void drawText(const char *text, int length, int x, int y)
{
    double *matrix = new double[16];
    
    glMatrixMode(GL_PROJECTION);
    glGetDoublev(GL_PROJECTION_MATRIX, matrix);
    glLoadIdentity();
    glOrtho(0, 800, 0, 600, -5, 5);
    
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    
    glPushMatrix();
    glLoadIdentity();
    glRasterPos2i(x, y);
    
    for (int i = 0; i < length; i++) {
        glutBitmapCharacter(GLUT_BITMAP_9_BY_15, (int) text[i]);
    }
    glPopMatrix();
    glMatrixMode(GL_PROJECTION);
    glLoadMatrixd(matrix);
    glMatrixMode(GL_MODELVIEW);
}
void CScanLineZBufferView::OnMouseMove(UINT nFlags, CPoint point)
{
	// std::cout << logTime() << " 当前屏幕坐标点:" << point.x << " " << point.y << std::endl;
	// 没有导入模型
	if ( GetDocument()->m_mesh.n_vertices() <= 0)	return;
	
	// 处理模型旋转事件
	// 保存上一次点击位置
	
	static CPoint prevPointPos(-1, -1);
	if (nFlags & MK_LBUTTON)
	{
		// std::cout << logTime() << " " << "Model Move" << std::endl;
		// std::cout << "(" << prevPointPos.x << ", " << prevPointPos.y << ")" << " " << "(" << point.x << ", " << point.y << ")" << std::endl;
		if (prevPointPos.x < 0 || prevPointPos.y < 0) prevPointPos = point; // 处理一次点击
		// 旋转模型
		double x = prevPointPos.x - point.x;
		double y = prevPointPos.y - point.y;
		double modelview_matrix[16];
		glGetDoublev(GL_MODELVIEW_MATRIX, modelview_matrix);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glTranslated(0., 0., m_z_delta); // 移动到原点
		glRotated(sqrt((double)(x*x + y*y)), y, x, 0.0); // 旋转
		glTranslated(0., 0., -m_z_delta); // 移回原处
		glMultMatrixd(modelview_matrix);
		prevPointPos = point;
		RedrawWindow();
	}
	else
	{
		prevPointPos.x = prevPointPos.y = -1;
	}
	
	// CView::OnMouseMove(nFlags, point);
}
//------------------------------------------------------------------------------
// drawFunc() --
//------------------------------------------------------------------------------
void DspRwr::drawFunc()
{
    // Need a RWR to draw; if not, just draw a big X
    if (rwr == 0) {
        glBegin(GL_LINES);
        glVertex3d(-1.0, -1.0, 0.0);
        glVertex3d( 1.0,  1.0, 0.0);
        glVertex3d(-1.0,  1.0, 0.0);
        glVertex3d( 1.0, -1.0, 0.0);
        glEnd();
        return;
    }

    // ---
    // Draw the RWR signal rays
    // ---

    GLdouble  ocolor[4];
    glGetDoublev(GL_CURRENT_COLOR,ocolor);

    glColor3d(0.0, 1.0, 0.0);

    unsigned int n = rwr->getNumberOfRays();
    for (unsigned int i = 0; i < n; i++) {
        GLdouble azr = (Basic::Angle::D2RCC *  rwr->getRayAzimuth(i) );
        GLdouble pwr = rwr->getRay(i);
        GLdouble up = cos(azr) * pwr;
        GLdouble right = sin(azr) * pwr;
        glBegin(GL_LINES);
        glVertex3d( 0.0,  0.0, 0.0);
        glVertex3d( right, up, 0.0);
        glEnd();
    }

    glColor4dv(ocolor);
}
Beispiel #11
0
void zprReset() {
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(_left,_right,_bottom,_top,_zNear,_zFar);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glGetDoublev(GL_MODELVIEW_MATRIX,_matrix);
    double initscale = 1.5/display_r->boxsize_max;
    glScalef(initscale,initscale,initscale);
    switch(resetOrientation){
	    case 1:
	    	glRotatef(90,1.,0.,0.);
		break;
	    case 2:
	    	glRotatef(90,1.,0.,0.);
	    	glRotatef(90,0.,0.,1.);
		break;
    }
    glscale = 1.0;
    resetOrientation++;
    if (resetOrientation>2){
	    resetOrientation=0;
    }
}
// makes sure that the axis aligned box is visible in the camera (and y is up)
void Camera::makeVisible(float xMin, float xMax,
					float yMin, float yMax, float zMin, float zMax) {
//	float yPos = (yMax + yMin) / 2; // just the average
	float yPos = (1.0/5.0) * yMin + (4.0/5.0) * yMax; // lift it up a bit

	float xPos, zPos;
	// find position (x, z) st when camera is facing along one of these axes
	// the box is fully in the view but and as big as possible
	float distX = xMax - xMin, distZ = zMax - zMin;
	float xAvr = ( xMax + xMin ) / 2;
	float zAvr = ( zMax + zMin ) / 2;
	if (distX > distZ) {
		xPos = xAvr;
		zPos = zMin - distX/2;
		// TODO check if y fits? --not--> move z more negative
		while (distX/2 + distZ > far) { far += 10; } // make sure it's in the picture
		// add a little extra so we can see the man from an angle
		xPos += 20;
		zPos -= 20;
	} else {
		zPos = zAvr;
		xPos = xMin - distZ/2;
		// TODO check if y fits? --not--> move x more negative
		while (distZ/2 + distX > far) { far += 10; } // make sure it's in the picture
		// add a little extra so we can see the man from an angle
		zPos += 20;
		xPos -= 20;
	}

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();
	gluLookAt(xPos, yPos, zPos, xAvr, yPos, zAvr, 0, 1.0, 0);
	glGetDoublev(GL_MODELVIEW_MATRIX, cameraTrans); // initialize it to identity --> move to resetScene()
	glPopMatrix();
}
	vector3 RawDataVisualization::Unprojection(vector2 _2Dpos){
		float Depth;
		int viewport[4];
		//double ModelViewMatrix[16];				//Model_view matrix
		double ProjectionMatrix[16];			//Projection matrix

		glPushMatrix();

		glGetIntegerv(GL_VIEWPORT, viewport);
		//glGetDoublev(GL_MODELVIEW_MATRIX, ModelViewMatrix);
		glGetDoublev(GL_PROJECTION_MATRIX, ProjectionMatrix);

		glPopMatrix();

		glReadPixels((int)_2Dpos.x , viewport[3] - (int)_2Dpos.y , 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &Depth);

		double X = _2Dpos.x;
		double Y = _2Dpos.y;
		double wpos[3] = {0.0 , 0.0 , 0.0};

		gluUnProject(X , ((double)viewport[3] - Y) , (double)Depth , ModelViewMatrix2 , ProjectionMatrix , viewport, &wpos[0] , &wpos[1] , &wpos[2]);

		return vector3(wpos[0] , wpos[1] , wpos[2]);
	}
Beispiel #14
0
vec3 Project(const vec3 &p)
{
	GLdouble modelMat[16], projMat[16];
	GLint viewport[4];
	GLdouble winx = 0, winy = 0, winz = 0;
	GLdouble objx = p.x, objy = p.y, objz = p.z;

	glPushAttrib(GL_ALL_ATTRIB_BITS);

		viewport[0] = 0;
		viewport[1] = 0;
		viewport[2] = 1024;
		viewport[3] = 800;

		// Use the game camera's modelview matrix
		const mat4 &modl = g_Camera.getTransformation();
		for(int i=0; i<16; ++i)
		{
			modelMat[i] = modl[i];
		}

		// Use the perspective transformation for the projection matrix
		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
			glLoadIdentity();
			gluPerspective(45, 1024.0f / 768.0f, 0.01f, 5000.0f);
			glGetDoublev(GL_PROJECTION_MATRIX, projMat);
		glPopMatrix();

		// Now project the point to window coords
		gluProject(objx, objy, objz, modelMat, projMat, viewport, &winx, &winy, &winz);

	glPopAttrib();

	return vec3((float)winx, (float)winy, (float)winz);
}
Beispiel #15
0
   void VisualSceneOCCGeometry :: MouseDblClick (int px, int py)
   {
      int hits;

      // select surface triangle by mouse click

      GLuint selbuf[10000];
      glSelectBuffer (10000, selbuf);

      glRenderMode (GL_SELECT);

      GLint viewport[4];
      glGetIntegerv (GL_VIEWPORT, viewport);

      glMatrixMode (GL_PROJECTION);
      glPushMatrix();

      GLdouble projmat[16];
      glGetDoublev (GL_PROJECTION_MATRIX, projmat);

      glLoadIdentity();
      gluPickMatrix (px, viewport[3] - py, 1, 1, viewport);
      glMultMatrixd (projmat);

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

      glMatrixMode (GL_MODELVIEW);

      glPushMatrix();
      glMultMatrixf (transformationmat);

      glInitNames();
      glPushName (1);

      glPolygonOffset (1, 1);
      glEnable (GL_POLYGON_OFFSET_FILL);

      glDisable(GL_CLIP_PLANE0);

      // Philippose - 30/01/2009
      // Enable clipping planes for Selection mode in OCC Geometry
      if (vispar.clipenable)
      {
         Vec<3> n(clipplane[0], clipplane[1], clipplane[2]);
         double len = Abs(n);
         double mu = -clipplane[3] / (len*len);
         Point<3> p (mu * n);
         n /= len;
         Vec<3> t1 = n.GetNormal ();
         Vec<3> t2 = Cross (n, t1);

         double xi1mid = (center - p) * t1;
         double xi2mid = (center - p) * t2;

         glLoadName (0);
         glBegin (GL_QUADS);
         glVertex3dv (p + (xi1mid-rad) * t1 + (xi2mid-rad) * t2);
         glVertex3dv (p + (xi1mid+rad) * t1 + (xi2mid-rad) * t2);
         glVertex3dv (p + (xi1mid+rad) * t1 + (xi2mid+rad) * t2);
         glVertex3dv (p + (xi1mid-rad) * t1 + (xi2mid+rad) * t2);
         glEnd ();
      }

      glCallList (trilists.Get(1));

      glDisable (GL_POLYGON_OFFSET_FILL);

      glPopName();

      glMatrixMode (GL_PROJECTION);
      glPopMatrix();

      glMatrixMode (GL_MODELVIEW);
      glPopMatrix();

      glFlush();

      hits = glRenderMode (GL_RENDER);

      int minname = 0;
      GLuint mindepth = 0;

      // find clippingplane
      GLuint clipdepth = 0; // GLuint(-1);

      for (int i = 0; i < hits; i++)
      {
         int curname = selbuf[4*i+3];
         if (!curname) clipdepth = selbuf[4*i+1];
      }

      for (int i = 0; i < hits; i++)
      {
         int curname = selbuf[4*i+3];
         GLuint curdepth = selbuf[4*i+1];
         if (curname && (curdepth> clipdepth) &&
               (curdepth < mindepth || !minname))
         {
            mindepth = curdepth;
            minname = curname;
         }
      }

      occgeometry->LowLightAll();

      if (minname)
      {
         occgeometry->fvispar[minname-1].Highlight();

         if (vispar.occzoomtohighlightedentity)
         occgeometry->changed = OCCGEOMETRYVISUALIZATIONFULLCHANGE;
         else
         occgeometry->changed = OCCGEOMETRYVISUALIZATIONHALFCHANGE;
         cout << "Selected face: " << minname << endl;
      }
      else
      {
         occgeometry->changed = OCCGEOMETRYVISUALIZATIONHALFCHANGE;
      }

      glDisable(GL_CLIP_PLANE0);

      SelectFaceInOCCDialogTree (minname);

      // Philippose - 30/01/2009
      // Set the currently selected face in the array
      // for local face mesh size definition
      occgeometry->SetSelectedFace(minname);

      //  selecttimestamp = NextTimeStamp();
   }
Beispiel #16
0
void Scarry::drawtra(wardraw_t *wd){
	st::drawtra(wd);
	Scarry *p = this;
	Scarry *pt = this;
	Mat4d mat;
	Vec3d pa, pb, pa0(.01, 0, 0), pb0(-.01, 0, 0);
	double scale;

/*	if(scarry_cull(pt, wd))
		return;*/

	if(wd->vw->gc->cullFrustum(pos, getHitRadius()))
		return;

	scale = fabs(wd->vw->gc->scale(this->pos));

	transform(mat);

	const double blastscale = .04;
	drawCapitalBlast(wd, Vec3d(0, 0, .55), blastscale);
	drawCapitalBlast(wd, Vec3d(.08, .08, .55), blastscale);
	drawCapitalBlast(wd, Vec3d(-.08, .08, .55), blastscale);
	drawCapitalBlast(wd, Vec3d(-.08, -.08, .55), blastscale);
	drawCapitalBlast(wd, Vec3d(.08, -.08, .55), blastscale);

	pa = pt->rot.trans(pa0);
	pa += pt->pos;
	pb = pt->rot.trans(pb0);
	pb += pt->pos;
	glColor4ub(255,255,9,255);
	glBegin(GL_LINES);
	glVertex3dv(pa);
	glVertex3dv(pb);
	glEnd();

	{
		int i;
		static const avec3_t lights[] = {
			{0, 520 * SCARRY_SCALE, 220 * SCARRY_SCALE},
			{0, -520 * SCARRY_SCALE, 220 * SCARRY_SCALE},
			{140 * SCARRY_SCALE, 370 * SCARRY_SCALE, 220 * SCARRY_SCALE},
			{-140 * SCARRY_SCALE, 370 * SCARRY_SCALE, 220 * SCARRY_SCALE},
			{140 * SCARRY_SCALE, -370 * SCARRY_SCALE, 220 * SCARRY_SCALE},
			{-140 * SCARRY_SCALE, -370 * SCARRY_SCALE, 220 * SCARRY_SCALE},
			{100 * SCARRY_SCALE, -360 * SCARRY_SCALE, -600 * SCARRY_SCALE},
			{100 * SCARRY_SCALE,  360 * SCARRY_SCALE, -600 * SCARRY_SCALE},
			{ 280 * SCARRY_SCALE,   20 * SCARRY_SCALE, 520 * SCARRY_SCALE},
			{ 280 * SCARRY_SCALE,  -20 * SCARRY_SCALE, 520 * SCARRY_SCALE},
			{-280 * SCARRY_SCALE,   20 * SCARRY_SCALE, 520 * SCARRY_SCALE},
			{-280 * SCARRY_SCALE,  -20 * SCARRY_SCALE, 520 * SCARRY_SCALE},
			{-280 * SCARRY_SCALE,   20 * SCARRY_SCALE, -300 * SCARRY_SCALE},
			{-280 * SCARRY_SCALE,  -20 * SCARRY_SCALE, -300 * SCARRY_SCALE},
			{ 280 * SCARRY_SCALE,   20 * SCARRY_SCALE, -480 * SCARRY_SCALE},
			{ 280 * SCARRY_SCALE,  -20 * SCARRY_SCALE, -480 * SCARRY_SCALE},
		};
		avec3_t pos;
		double rad = .01;
		double t;
		GLubyte col[4] = {255, 31, 31, 255};
		random_sequence rs;
		init_rseq(&rs, (unsigned long)this);

		/* color calculation of static navlights */
		t = fmod(wd->vw->viewtime + drseq(&rs) * 2., 2.);
		if(t < 1.){
			rad *= (t + 1.) / 2.;
			col[3] *= t;
		}
		else{
			rad *= (2. - t + 1.) / 2.;
			col[3] *= 2. - t;
		}
		for(i = 0 ; i < numof(lights); i++){
			mat4vp3(pos, mat, lights[i]);
			gldSpriteGlow(pos, rad, col, wd->vw->irot);
		}

		/* runway lights */
		if(1 < scale * .01){
			col[0] = 0;
			col[1] = 191;
			col[2] = 255;
			for(i = 0 ; i <= 10; i++){
				avec3_t pos0;
				pos0[0] = -160 * SCARRY_SCALE;
				pos0[1] = 20 * SCARRY_SCALE + .0025;
				pos0[2] = (i * -460 + (10 - i) * -960) * SCARRY_SCALE / 10;
				rad = .005 * (1. - fmod(i / 10. + t / 2., 1.));
				col[3] = 255/*rad * 255 / .01*/;
				mat4vp3(pos, mat, pos0);
				gldSpriteGlow(pos, rad, col, wd->vw->irot);
				pos0[0] = -40 * SCARRY_SCALE;
				mat4vp3(pos, mat, pos0);
				gldSpriteGlow(pos, rad, col, wd->vw->irot);
				pos0[1] = -20 * SCARRY_SCALE - .0025;
				mat4vp3(pos, mat, pos0);
				gldSpriteGlow(pos, rad, col, wd->vw->irot);
				pos0[0] = -160 * SCARRY_SCALE;
				mat4vp3(pos, mat, pos0);
				gldSpriteGlow(pos, rad, col, wd->vw->irot);
			}
		}

/*		for(i = 0; i < numof(p->turrets); i++)
			mturret_drawtra(&p->turrets[i], pt, wd);*/
	}

	static int init = 0;
	static suftex_t *pst;
	static suf_t *sufbase = NULL;
	if(init == 0) do{
		init = 1;
		sufbase = CallLoadSUF("models/spacecarrier.bin");
	} while(0);
	if(sufbase){
		static const double normal[3] = {0., 1., 0.};
		double scale = SCARRY_SCALE;
		static const GLdouble rotaxis[16] = {
			-1,0,0,0,
			0,1,0,0,
			0,0,-1,0,
			0,0,0,1,
		};
		Mat4d mat;

		glPushAttrib(GL_TEXTURE_BIT | GL_LIGHTING_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT);
		glEnable(GL_CULL_FACE);
		glPushMatrix();
		transform(mat);
		glMultMatrixd(mat);

		extern GLuint screentex;
		glBindTexture(GL_TEXTURE_2D, screentex);
		glTexEnvi(GL_TEXTURE_2D, GL_TEXTURE_ENV_MODE, GL_REPLACE);
		glColor4f(1.,1.,1.,1.);
		glDisable(GL_LIGHTING);
		glEnable(GL_TEXTURE_2D);

		Mat4d modelview, proj;
		glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
		glGetDoublev(GL_PROJECTION_MATRIX, proj);
		Mat4d trans = proj * modelview;
		texture((glPushMatrix(),
			glScaled(1./2., 1./2., 1.),
			glTranslated(1, 1, 0),
			glMultMatrixd(trans)
		));
		glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
		glTexGendv(GL_S, GL_EYE_PLANE, Vec4d(.9,0,0,0));
		glEnable(GL_TEXTURE_GEN_S);
		glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
		glTexGendv(GL_T, GL_EYE_PLANE, Vec4d(0,.9,0,0));
		glEnable(GL_TEXTURE_GEN_T);
		glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
		glTexGendv(GL_R, GL_EYE_PLANE, Vec4d(0,0,.9,0));
		glEnable(GL_TEXTURE_GEN_R);
		glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
		glTexGeniv(GL_Q, GL_EYE_PLANE, Vec4<int>(0,0,0,1));
		glEnable(GL_TEXTURE_GEN_Q);

		glPushMatrix();
		glScaled(-scale, scale, -scale);
		DrawSUF(sufbase, 0, NULL);
		glPopMatrix();

		texture((glPopMatrix()));
		glPopMatrix();
		glPopAttrib();
	}
}
Beispiel #17
0
void Scarry::draw(wardraw_t *wd){
	Scarry *const p = this;
	static int init = 0;
	static suftex_t *pst;
	static suf_t *sufbase = NULL;
	if(!w)
		return;

	/* cull object */
/*	if(beamer_cull(this, wd))
		return;*/
//	wd->lightdraws++;

	draw_healthbar(this, wd, health / getMaxHealth(), getHitRadius(), -1., capacitor / maxenergy());

	if(wd->vw->gc->cullFrustum(pos, getHitRadius()))
		return;
#if 0
	if(init == 0) do{
		init = 1;
		sufbase = CallLoadSUF("models/spacecarrier.bin");
		if(!sufbase) break;
		CallCacheBitmap("bridge.bmp", "bridge.bmp", NULL, NULL);
		CallCacheBitmap("beamer_panel.bmp", "beamer_panel.bmp", NULL, NULL);
		CallCacheBitmap("bricks.bmp", "bricks.bmp", NULL, NULL);
		CallCacheBitmap("runway.bmp", "runway.bmp", NULL, NULL);
		suftexparam_t stp;
		stp.flags = STP_MAGFIL | STP_MINFIL | STP_ENV;
		stp.magfil = GL_LINEAR;
		stp.minfil = GL_LINEAR;
		stp.env = GL_ADD;
		stp.mipmap = 0;
		CallCacheBitmap5("engine2.bmp", "engine2br.bmp", &stp, "engine2.bmp", NULL);
		pst = AllocSUFTex(sufbase);
		extern GLuint screentex;
		glNewList(pst->a[0].list, GL_COMPILE);
		glBindTexture(GL_TEXTURE_2D, screentex);
		glTexEnvi(GL_TEXTURE_2D, GL_TEXTURE_ENV_MODE, GL_REPLACE);
		glDisable(GL_LIGHTING);
		glEndList();
	} while(0);
	if(sufbase){
		static const double normal[3] = {0., 1., 0.};
		double scale = SCARRY_SCALE;
		static const GLdouble rotaxis[16] = {
			-1,0,0,0,
			0,1,0,0,
			0,0,-1,0,
			0,0,0,1,
		};
		Mat4d mat;

		glPushAttrib(GL_TEXTURE_BIT | GL_LIGHTING_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT);
		glPushMatrix();
		transform(mat);
		glMultMatrixd(mat);

#if 1
		for(int i = 0; i < nhitboxes; i++){
			Mat4d rot;
			glPushMatrix();
			gldTranslate3dv(hitboxes[i].org);
			rot = hitboxes[i].rot.tomat4();
			glMultMatrixd(rot);
			hitbox_draw(this, hitboxes[i].sc);
			glPopMatrix();
		}
#endif

		Mat4d modelview, proj;
		glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
		glGetDoublev(GL_PROJECTION_MATRIX, proj);
		Mat4d trans = proj * modelview;
		texture((glPushMatrix(),
			glScaled(1./2., 1./2., 1.),
			glTranslated(1, 1, 0),
			glMultMatrixd(trans)
		));
		glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
		glTexGendv(GL_S, GL_EYE_PLANE, Vec4d(1,0,0,0));
		glEnable(GL_TEXTURE_GEN_S);
		glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
		glTexGendv(GL_T, GL_EYE_PLANE, Vec4d(0,1,0,0));
		glEnable(GL_TEXTURE_GEN_T);
		glTexGeni(GL_R, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
		glTexGeniv(GL_R, GL_EYE_PLANE, Vec4<int>(0,0,1,0));
		glEnable(GL_TEXTURE_GEN_R);
		glTexGeni(GL_Q, GL_TEXTURE_GEN_MODE, GL_EYE_LINEAR);
		glTexGeniv(GL_Q, GL_EYE_PLANE, Vec4<int>(0,0,0,1));
		glEnable(GL_TEXTURE_GEN_Q);

		glPushMatrix();
		glScaled(scale, scale, scale);
		glMultMatrixd(rotaxis);
		DecalDrawSUF(sufbase, SUF_ATR, NULL, pst, NULL, NULL);
		glPopMatrix();

		texture((glPopMatrix()));
		glPopMatrix();
		glPopAttrib();
	}
#endif
}
Beispiel #18
0
int main(int /*argc*/, char** /*argv*/)
{
	// Init SDL
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
	{
		printf("Could not initialise SDL\n");
		return -1;
	}
	
	// Center window
	char env[] = "SDL_VIDEO_CENTERED=1";
	putenv(env);

	// Init OpenGL
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
//#ifndef WIN32
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
//#endif

	const SDL_VideoInfo* vi = SDL_GetVideoInfo();

	bool presentationMode = false;

	int width, height;
	SDL_Surface* screen = 0;
	
	if (presentationMode)
	{
        width = 1700;
        height = 1000;
		screen = SDL_SetVideoMode(width, height, 0, SDL_OPENGL|SDL_FULLSCREEN);
	}
	else
	{	
        width = 1700;
        height = 1000;
		screen = SDL_SetVideoMode(width, height, 0, SDL_OPENGL);
	}
	
	if (!screen)
	{
		printf("Could not initialise SDL opengl\n");
		return -1;
	}

	glEnable(GL_MULTISAMPLE);

	SDL_WM_SetCaption("Recast Demo", 0);
	
	if (!imguiRenderGLInit("DroidSans.ttf"))
	{
		printf("Could not init GUI renderer.\n");
		SDL_Quit();
		return -1;
	}
	
	float t = 0.0f;
	float timeAcc = 0.0f;
	Uint32 lastTime = SDL_GetTicks();
	int mx = 0, my = 0;
	float rx = 45;
	float ry = -45;
	float moveW = 0, moveS = 0, moveA = 0, moveD = 0;
	float camx = 0, camy = 0, camz = 0, camr = 1000;
	float origrx = 0, origry = 0;
	int origx = 0, origy = 0;
	float scrollZoom = 0;
	bool rotate = false;
	bool movedDuringRotate = false;
	float rays[3], raye[3]; 
	bool mouseOverMenu = false;
	bool showMenu = !presentationMode;
	bool showLog = false;
	bool showTools = true;
	bool showLevels = false;
	bool showSample = false;
	bool showTestCases = false;

	int propScroll = 0;
	int logScroll = 0;
	int toolsScroll = 0;
	
	char sampleName[64] = "Choose Sample..."; 
	
	FileList files;
	char meshName[128] = "Choose Mesh...";
	
	float mpos[3] = {0,0,0};
	bool mposSet = false;
	
	SlideShow slideShow;
	slideShow.init("slides/");
	
	InputGeom* geom = 0;
	Sample* sample = 0;
	TestCase* test = 0;

	BuildContext ctx;
	
	glEnable(GL_CULL_FACE);
	
	float fogCol[4] = { 0.32f, 0.31f, 0.30f, 1.0f };
	glEnable(GL_FOG);
	glFogi(GL_FOG_MODE, GL_LINEAR);
	glFogf(GL_FOG_START, camr*0.1f);
	glFogf(GL_FOG_END, camr*1.25f);
	glFogfv(GL_FOG_COLOR, fogCol);
	
	glDepthFunc(GL_LEQUAL);
	
	bool done = false;
	while(!done)
	{
		// Handle input events.
		int mscroll = 0;
		bool processHitTest = false;
		bool processHitTestShift = false;
		SDL_Event event;
		
		while (SDL_PollEvent(&event))
		{
			switch (event.type)
			{
				case SDL_KEYDOWN:
					// Handle any key presses here.
					if (event.key.keysym.sym == SDLK_ESCAPE)
					{
						done = true;
					}
					else if (event.key.keysym.sym == SDLK_t)
					{
						showLevels = false;
						showSample = false;
						showTestCases = true;
						scanDirectory("Tests", ".txt", files);
					}
					else if (event.key.keysym.sym == SDLK_TAB)
					{
						showMenu = !showMenu;
					}
					else if (event.key.keysym.sym == SDLK_SPACE)
					{
						if (sample)
							sample->handleToggle();
					}
					else if (event.key.keysym.sym == SDLK_1)
					{
						if (sample)
							sample->handleStep();
					}
					else if (event.key.keysym.sym == SDLK_9)
					{
						if (geom)
							geom->save("geomset.txt");
					}
					else if (event.key.keysym.sym == SDLK_0)
					{
						delete geom;
						geom = new InputGeom;
						if (!geom || !geom->load(&ctx, "geomset.txt"))
						{
							delete geom;
							geom = 0;
							
							showLog = true;
							logScroll = 0;
							ctx.dumpLog("Geom load log %s:", meshName);
						}
						if (sample && geom)
						{
							sample->handleMeshChanged(geom);
						}
							
						if (geom || sample)
						{
							const float* bmin = 0;
							const float* bmax = 0;
							if (sample)
							{
								bmin = sample->getBoundsMin();
								bmax = sample->getBoundsMax();
							}
							else if (geom)
							{
								bmin = geom->getMeshBoundsMin();
								bmax = geom->getMeshBoundsMax();
							}
							// Reset camera and fog to match the mesh bounds.
							if (bmin && bmax)
							{
								camr = sqrtf(rcSqr(bmax[0]-bmin[0]) +
											 rcSqr(bmax[1]-bmin[1]) +
											 rcSqr(bmax[2]-bmin[2])) / 2;
								camx = (bmax[0] + bmin[0]) / 2 + camr;
								camy = (bmax[1] + bmin[1]) / 2 + camr;
								camz = (bmax[2] + bmin[2]) / 2 + camr;
								camr *= 3;
							}
							rx = 45;
							ry = -45;
							glFogf(GL_FOG_START, camr*0.2f);
							glFogf(GL_FOG_END, camr*1.25f);
						}
					}
					else if (event.key.keysym.sym == SDLK_RIGHT)
					{
						slideShow.nextSlide();
					}
					else if (event.key.keysym.sym == SDLK_LEFT)
					{
						slideShow.prevSlide();
					}
					break;
					
				case SDL_MOUSEBUTTONDOWN:
					if (event.button.button == SDL_BUTTON_RIGHT)
					{
						if (!mouseOverMenu)
						{
							// Rotate view
							rotate = true;
							movedDuringRotate = false;
							origx = mx;
							origy = my;
							origrx = rx;
							origry = ry;
						}
					}	
					else if (event.button.button == SDL_BUTTON_WHEELUP)
					{
						if (mouseOverMenu)
							mscroll--;
						else
							scrollZoom -= 1.0f;
					}
					else if (event.button.button == SDL_BUTTON_WHEELDOWN)
					{
						if (mouseOverMenu)
							mscroll++;
						else
							scrollZoom += 1.0f;
					}
					break;
					
				case SDL_MOUSEBUTTONUP:
					// Handle mouse clicks here.
					if (event.button.button == SDL_BUTTON_RIGHT)
					{
						rotate = false;
						if (!mouseOverMenu)
						{
							if (!movedDuringRotate)
							{
								processHitTest = true;
								processHitTestShift = true;
							}
						}
					}
					else if (event.button.button == SDL_BUTTON_LEFT)
					{
						if (!mouseOverMenu)
						{
							processHitTest = true;
							processHitTestShift = (SDL_GetModState() & KMOD_SHIFT) ? true : false;
						}
					}
					
					break;
					
				case SDL_MOUSEMOTION:
					mx = event.motion.x;
					my = height-1 - event.motion.y;
					if (rotate)
					{
						int dx = mx - origx;
						int dy = my - origy;
						rx = origrx - dy*0.25f;
						ry = origry + dx*0.25f;
						if (dx*dx+dy*dy > 3*3)
							movedDuringRotate = true;
					}
					break;
					
				case SDL_QUIT:
					done = true;
					break;
					
				default:
					break;
			}
		}

		unsigned char mbut = 0;
		if (SDL_GetMouseState(0,0) & SDL_BUTTON_LMASK)
			mbut |= IMGUI_MBUT_LEFT;
		if (SDL_GetMouseState(0,0) & SDL_BUTTON_RMASK)
			mbut |= IMGUI_MBUT_RIGHT;
		
		Uint32	time = SDL_GetTicks();
		float	dt = (time - lastTime) / 1000.0f;
		lastTime = time;
		
		t += dt;


		// Hit test mesh.
		if (processHitTest && geom && sample)
		{
			float hitt;
			bool hit = geom->raycastMesh(rays, raye, hitt);
			
			if (hit)
			{
				if (SDL_GetModState() & KMOD_CTRL)
				{
					// Marker
					mposSet = true;
					mpos[0] = rays[0] + (raye[0] - rays[0])*hitt;
					mpos[1] = rays[1] + (raye[1] - rays[1])*hitt;
					mpos[2] = rays[2] + (raye[2] - rays[2])*hitt;
				}
				else
				{
					float pos[3];
					pos[0] = rays[0] + (raye[0] - rays[0])*hitt;
					pos[1] = rays[1] + (raye[1] - rays[1])*hitt;
					pos[2] = rays[2] + (raye[2] - rays[2])*hitt;
					sample->handleClick(rays, pos, processHitTestShift);
				}
			}
			else
			{
				if (SDL_GetModState() & KMOD_CTRL)
				{
					// Marker
					mposSet = false;
				}
			}
		}
		
		// Update sample simulation.
		const float SIM_RATE = 20;
		const float DELTA_TIME = 1.0f/SIM_RATE;
		timeAcc = rcClamp(timeAcc+dt, -1.0f, 1.0f);
		int simIter = 0;
		while (timeAcc > DELTA_TIME)
		{
			timeAcc -= DELTA_TIME;
			if (simIter < 5)
			{
				if (sample)
					sample->handleUpdate(DELTA_TIME);
			}
			simIter++;
		}

		// Clamp the framerate so that we do not hog all the CPU.
		const float MIN_FRAME_TIME = 1.0f/40.0f;
		if (dt < MIN_FRAME_TIME)
		{
			int ms = (int)((MIN_FRAME_TIME - dt)*1000.0f);
			if (ms > 10) ms = 10;
			if (ms >= 0)
				SDL_Delay(ms);
		}
		
		
		// Update and render
		glViewport(0, 0, width, height);
		glClearColor(0.3f, 0.3f, 0.32f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glDisable(GL_TEXTURE_2D);
		
		// Render 3d
		glEnable(GL_DEPTH_TEST);
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		gluPerspective(50.0f, (float)width/(float)height, 1.0f, camr);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		glRotatef(rx,1,0,0);
		glRotatef(ry,0,1,0);
		glTranslatef(-camx, -camy, -camz);
		
		// Get hit ray position and direction.
		GLdouble proj[16];
		GLdouble model[16];
		GLint view[4];
		glGetDoublev(GL_PROJECTION_MATRIX, proj);
		glGetDoublev(GL_MODELVIEW_MATRIX, model);
		glGetIntegerv(GL_VIEWPORT, view);
		GLdouble x, y, z;
		gluUnProject(mx, my, 0.0f, model, proj, view, &x, &y, &z);
		rays[0] = (float)x; rays[1] = (float)y; rays[2] = (float)z;
		gluUnProject(mx, my, 1.0f, model, proj, view, &x, &y, &z);
		raye[0] = (float)x; raye[1] = (float)y; raye[2] = (float)z;
		
		// Handle keyboard movement.
		Uint8* keystate = SDL_GetKeyState(NULL);
		moveW = rcClamp(moveW + dt * 4 * (keystate[SDLK_w] ? 1 : -1), 0.0f, 1.0f);
		moveS = rcClamp(moveS + dt * 4 * (keystate[SDLK_s] ? 1 : -1), 0.0f, 1.0f);
		moveA = rcClamp(moveA + dt * 4 * (keystate[SDLK_a] ? 1 : -1), 0.0f, 1.0f);
		moveD = rcClamp(moveD + dt * 4 * (keystate[SDLK_d] ? 1 : -1), 0.0f, 1.0f);
		
		float keybSpeed = 22.0f;
		if (SDL_GetModState() & KMOD_SHIFT)
			keybSpeed *= 4.0f;
		
		float movex = (moveD - moveA) * keybSpeed * dt;
		float movey = (moveS - moveW) * keybSpeed * dt;
		
		movey += scrollZoom * 2.0f;
		scrollZoom = 0;
		
		camx += movex * (float)model[0];
		camy += movex * (float)model[4];
		camz += movex * (float)model[8];
		
		camx += movey * (float)model[2];
		camy += movey * (float)model[6];
		camz += movey * (float)model[10];

		glEnable(GL_FOG);

		if (sample)
			sample->handleRender();
		if (test)
			test->handleRender();
		
		glDisable(GL_FOG);
		
		// Render GUI
		glDisable(GL_DEPTH_TEST);
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		gluOrtho2D(0, width, 0, height);
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		
		mouseOverMenu = false;
		
		imguiBeginFrame(mx,my,mbut,mscroll);
		
		if (sample)
		{
			sample->handleRenderOverlay((double*)proj, (double*)model, (int*)view);
		}
		if (test)
		{
			if (test->handleRenderOverlay((double*)proj, (double*)model, (int*)view))
				mouseOverMenu = true;
		}

		// Help text.
		if (showMenu)
		{
			const char msg[] = "W/S/A/D: Move  RMB: Rotate";
			imguiDrawText(280, height-20, IMGUI_ALIGN_LEFT, msg, imguiRGBA(255,255,255,128));
		}
		
		if (showMenu)
		{
			if (imguiBeginScrollArea("Properties", width-250-10, 10, 250, height-20, &propScroll))
				mouseOverMenu = true;

			if (imguiCheck("Show Log", showLog))
				showLog = !showLog;
			if (imguiCheck("Show Tools", showTools))
				showTools = !showTools;

			imguiSeparator();
			imguiLabel("Sample");
			if (imguiButton(sampleName))
			{
				if (showSample)
				{
					showSample = false;
				}
				else
				{
					showSample = true;
					showLevels = false;
					showTestCases = false;
				}
			}
			
			imguiSeparator();
			imguiLabel("Input Mesh");
			if (imguiButton(meshName))
			{
				if (showLevels)
				{
					showLevels = false;
				}
				else
				{
					showSample = false;
					showTestCases = false;
					showLevels = true;
					scanDirectory("Meshes", ".obj", files);
				}
			}
			if (geom)
			{
				char text[64];
				snprintf(text, 64, "Verts: %.1fk  Tris: %.1fk",
						 geom->getMesh()->getVertCount()/1000.0f,
						 geom->getMesh()->getTriCount()/1000.0f);
				imguiValue(text);
			}
			imguiSeparator();

			if (geom && sample)
			{
				imguiSeparatorLine();
				
				sample->handleSettings();

				if (imguiButton("Build"))
				{
					ctx.resetLog();
					if (!sample->handleBuild())
					{
						showLog = true;
						logScroll = 0;
					}
					ctx.dumpLog("Build log %s:", meshName);
					
					// Clear test.
					delete test;
					test = 0;
				}

				imguiSeparator();
			}
			
			if (sample)
			{
				imguiSeparatorLine();
				sample->handleDebugMode();
			}

			imguiEndScrollArea();
		}
		
		// Sample selection dialog.
		if (showSample)
		{
			static int levelScroll = 0;
			if (imguiBeginScrollArea("Choose Sample", width-10-250-10-200, height-10-250, 200, 250, &levelScroll))
				mouseOverMenu = true;

			Sample* newSample = 0;
			for (int i = 0; i < g_nsamples; ++i)
			{
				if (imguiItem(g_samples[i].name))
				{
					newSample = g_samples[i].create();
					if (newSample)
						strcpy(sampleName, g_samples[i].name);
				}
			}
			if (newSample)
			{
				delete sample;
				sample = newSample;
				sample->setContext(&ctx);
				if (geom && sample)
				{
					sample->handleMeshChanged(geom);
				}
				showSample = false;
			}

			if (geom || sample)
			{
				const float* bmin = 0;
				const float* bmax = 0;
				if (sample)
				{
					bmin = sample->getBoundsMin();
					bmax = sample->getBoundsMax();
				}
				else if (geom)
				{
					bmin = geom->getMeshBoundsMin();
					bmax = geom->getMeshBoundsMax();
				}
				// Reset camera and fog to match the mesh bounds.
				if (bmin && bmax)
				{
					camr = sqrtf(rcSqr(bmax[0]-bmin[0]) +
								 rcSqr(bmax[1]-bmin[1]) +
								 rcSqr(bmax[2]-bmin[2])) / 2;
					camx = (bmax[0] + bmin[0]) / 2 + camr;
					camy = (bmax[1] + bmin[1]) / 2 + camr;
					camz = (bmax[2] + bmin[2]) / 2 + camr;
					camr *= 3;
				}
				rx = 45;
				ry = -45;
				glFogf(GL_FOG_START, camr*0.1f);
				glFogf(GL_FOG_END, camr*1.25f);
			}
			
			imguiEndScrollArea();
		}
		
		// Level selection dialog.
		if (showLevels)
		{
			static int levelScroll = 0;
			if (imguiBeginScrollArea("Choose Level", width-10-250-10-200, height-10-450, 200, 450, &levelScroll))
				mouseOverMenu = true;
			
			int levelToLoad = -1;
			for (int i = 0; i < files.size; ++i)
			{
				if (imguiItem(files.files[i]))
					levelToLoad = i;
			}
			
			if (levelToLoad != -1)
			{
				strncpy(meshName, files.files[levelToLoad], sizeof(meshName));
				meshName[sizeof(meshName)-1] = '\0';
				showLevels = false;
				
				delete geom;
				geom = 0;
				
				char path[256];
				strcpy(path, "Meshes/");
				strcat(path, meshName);
				
				geom = new InputGeom;
				if (!geom || !geom->loadMesh(&ctx, path))
				{
					delete geom;
					geom = 0;
					
					showLog = true;
					logScroll = 0;
					ctx.dumpLog("Geom load log %s:", meshName);
				}
				if (sample && geom)
				{
					sample->handleMeshChanged(geom);
				}

				if (geom || sample)
				{
					const float* bmin = 0;
					const float* bmax = 0;
					if (sample)
					{
						bmin = sample->getBoundsMin();
						bmax = sample->getBoundsMax();
					}
					else if (geom)
					{
						bmin = geom->getMeshBoundsMin();
						bmax = geom->getMeshBoundsMax();
					}
					// Reset camera and fog to match the mesh bounds.
					if (bmin && bmax)
					{
						camr = sqrtf(rcSqr(bmax[0]-bmin[0]) +
									 rcSqr(bmax[1]-bmin[1]) +
									 rcSqr(bmax[2]-bmin[2])) / 2;
						camx = (bmax[0] + bmin[0]) / 2 + camr;
						camy = (bmax[1] + bmin[1]) / 2 + camr;
						camz = (bmax[2] + bmin[2]) / 2 + camr;
						camr *= 3;
					}
					rx = 45;
					ry = -45;
					glFogf(GL_FOG_START, camr*0.1f);
					glFogf(GL_FOG_END, camr*1.25f);
				}
			}
			
			imguiEndScrollArea();
			
		}
		
		// Test cases
		if (showTestCases)
		{
			static int testScroll = 0;
			if (imguiBeginScrollArea("Choose Test To Run", width-10-250-10-200, height-10-450, 200, 450, &testScroll))
				mouseOverMenu = true;

			int testToLoad = -1;
			for (int i = 0; i < files.size; ++i)
			{
				if (imguiItem(files.files[i]))
					testToLoad = i;
			}
			
			if (testToLoad != -1)
			{
				char path[256];
				strcpy(path, "Tests/");
				strcat(path, files.files[testToLoad]);
				test = new TestCase;
				if (test)
				{
					// Load the test.
					if (!test->load(path))
					{
						delete test;
						test = 0;
					}

					// Create sample
					Sample* newSample = 0;
					for (int i = 0; i < g_nsamples; ++i)
					{
						if (strcmp(g_samples[i].name, test->getSampleName()) == 0)
						{
							newSample = g_samples[i].create();
							if (newSample) strcpy(sampleName, g_samples[i].name);
						}
					}
					if (newSample)
					{
						delete sample;
						sample = newSample;
						sample->setContext(&ctx);
						showSample = false;
					}

					// Load geom.
					strcpy(meshName, test->getGeomFileName());
					meshName[sizeof(meshName)-1] = '\0';
					
					delete geom;
					geom = 0;
					
					strcpy(path, "Meshes/");
					strcat(path, meshName);
					
					geom = new InputGeom;
					if (!geom || !geom->loadMesh(&ctx, path))
					{
						delete geom;
						geom = 0;
						showLog = true;
						logScroll = 0;
						ctx.dumpLog("Geom load log %s:", meshName);
					}
					if (sample && geom)
					{
						sample->handleMeshChanged(geom);
					}

					// This will ensure that tile & poly bits are updated in tiled sample.
					if (sample)
						sample->handleSettings();

					ctx.resetLog();
					if (sample && !sample->handleBuild())
					{
						ctx.dumpLog("Build log %s:", meshName);
					}
					
					if (geom || sample)
					{
						const float* bmin = 0;
						const float* bmax = 0;
						if (sample)
						{
							bmin = sample->getBoundsMin();
							bmax = sample->getBoundsMax();
						}
						else if (geom)
						{
							bmin = geom->getMeshBoundsMin();
							bmax = geom->getMeshBoundsMax();
						}
						// Reset camera and fog to match the mesh bounds.
						if (bmin && bmax)
						{
							camr = sqrtf(rcSqr(bmax[0]-bmin[0]) +
										 rcSqr(bmax[1]-bmin[1]) +
										 rcSqr(bmax[2]-bmin[2])) / 2;
							camx = (bmax[0] + bmin[0]) / 2 + camr;
							camy = (bmax[1] + bmin[1]) / 2 + camr;
							camz = (bmax[2] + bmin[2]) / 2 + camr;
							camr *= 3;
						}
						rx = 45;
						ry = -45;
						glFogf(GL_FOG_START, camr*0.2f);
						glFogf(GL_FOG_END, camr*1.25f);
					}
					
					// Do the tests.
					if (sample)
						test->doTests(sample->getNavMesh(), sample->getNavMeshQuery());
				}
			}				
				
			imguiEndScrollArea();
		}

		
		// Log
		if (showLog && showMenu)
		{
			if (imguiBeginScrollArea("Log", 250+20, 10, width - 300 - 250, 200, &logScroll))
				mouseOverMenu = true;
			for (int i = 0; i < ctx.getLogCount(); ++i)
				imguiLabel(ctx.getLogText(i));
			imguiEndScrollArea();
		}
		
		// Tools
		if (!showTestCases && showTools && showMenu) // && geom && sample)
		{
			if (imguiBeginScrollArea("Tools", 10, 10, 250, height-20, &toolsScroll))
				mouseOverMenu = true;

			if (sample)
				sample->handleTools();
			
			imguiEndScrollArea();
		}
		
		slideShow.updateAndDraw(dt, (float)width, (float)height);
		
		// Marker
		if (mposSet && gluProject((GLdouble)mpos[0], (GLdouble)mpos[1], (GLdouble)mpos[2],
								  model, proj, view, &x, &y, &z))
		{
			// Draw marker circle
			glLineWidth(5.0f);
			glColor4ub(240,220,0,196);
			glBegin(GL_LINE_LOOP);
			const float r = 25.0f;
			for (int i = 0; i < 20; ++i)
			{
				const float a = (float)i / 20.0f * RC_PI*2;
				const float fx = (float)x + cosf(a)*r;
				const float fy = (float)y + sinf(a)*r;
				glVertex2f(fx,fy);
			}
			glEnd();
			glLineWidth(1.0f);
		}
		
		imguiEndFrame();
		imguiRenderGLDraw();		
		
		glEnable(GL_DEPTH_TEST);
		SDL_GL_SwapBuffers();
	}
	
	imguiRenderGLDestroy();
	
	SDL_Quit();
	
	delete sample;
	delete geom;
	
	return 0;
}
Beispiel #19
0
inline void updateProjectionState() {
	glGetDoublev(GL_MODELVIEW_MATRIX, modelviewMatrix);
	glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix);
	glGetIntegerv(GL_VIEWPORT, viewport);
}
void draw_arrow(
	float ax, float ay, float az,
	float bx, float by, float bz,
	float ah, float bh,
	char const * const annotation,
	float annot_size )
{
	int i;

	GLdouble mv[16];
	glGetDoublev(GL_MODELVIEW_MATRIX, mv);
	
	/* We're assuming the modelview RS part is (isotropically scaled)
	 * orthonormal, so the inverse is the transpose.
	 * The local view direction vector is the 3rd column of the matrix;
	 * assuming the view direction to be the normal on the arrows tangent
	 * space  taking the cross product of this with the arrow direction
	 * yields the binormal to be used as the orthonormal base to the 
	 * arrow direction to be used for drawing the arrowheads */

	double d[3] = {
	      bx - ax,
	      by - ay,
	      bz - az
	};
	normalize_v(d);

	double r[3] = { mv[0], mv[4], mv[8] };
	int rev = scalarproduct_v(d, r) < 0.;

	double n[3] = { mv[2], mv[6], mv[10] };
	{
		double const s = scalarproduct_v(d,n);
		for(int i = 0; i < 3; i++)
			n[i] -= d[i]*s;
	}
	normalize_v(n);

	double b[3];
	crossproduct_v(n, d, b);

	GLfloat const pos[][3] = {
		{ax, ay, az},
		{bx, by, bz},
		{ ax + (0.866*d[0] + 0.5*b[0])*ah,
		  ay + (0.866*d[1] + 0.5*b[1])*ah,
		  az + (0.866*d[2] + 0.5*b[2])*ah },
		{ ax + (0.866*d[0] - 0.5*b[0])*ah,
		  ay + (0.866*d[1] - 0.5*b[1])*ah,
		  az + (0.866*d[2] - 0.5*b[2])*ah },
		{ bx + (-0.866*d[0] + 0.5*b[0])*bh,
		  by + (-0.866*d[1] + 0.5*b[1])*bh,
		  bz + (-0.866*d[2] + 0.5*b[2])*bh },
		{ bx + (-0.866*d[0] - 0.5*b[0])*bh,
		  by + (-0.866*d[1] - 0.5*b[1])*bh,
		  bz + (-0.866*d[2] - 0.5*b[2])*bh }
	};
	GLushort const idx_line[][2] = {
		{0, 1},
	};
	GLushort const idx_heads[][3] = {
		{0, 2, 3},
		{1, 4, 5}
	};
	glDisableClientState(GL_COLOR_ARRAY);
	glDisableClientState(GL_NORMAL_ARRAY);
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);

	glEnableClientState(GL_VERTEX_ARRAY);
	glVertexPointer(3, GL_FLOAT, 0, pos);

	glDrawElements(GL_LINES, 2, GL_UNSIGNED_SHORT, idx_line);
	glDrawElements(GL_TRIANGLES, 2*3, GL_UNSIGNED_SHORT, idx_heads);
	glDisableClientState(GL_VERTEX_ARRAY);

	if(annotation) {
		float w = 0;
		for(char const *c = annotation; *c; c++)
			w += glutStrokeWidth(GLUT_STROKE_ROMAN, *c);
		w *= annot_size / 100.;

		float tx = (ax + bx)/2.;
		float ty = (ay + by)/2.;
		float tz = (az + bz)/2.;

		GLdouble r[16] = {
			d[0], d[1], d[2], 0,
			b[0], b[1], b[2], 0,
			n[0], n[1], n[2], 0,
			   0,    0,    0, 1
		};
		glPushMatrix();
		glTranslatef(tx, ty, tz);
		glMultMatrixd(r);
		if(rev)
			glScalef(-1, -1, 1);
		glTranslatef(-w/2., annot_size*0.1, 0);
		draw_strokestring(GLUT_STROKE_ROMAN, annot_size, annotation);
		glPopMatrix();
	}
}
void LineBuilderState::mousePressEvent(QMouseEvent *pe)
{
    if (log)
    Logger::getLogger()->infoLog() << "LineBuilderState::mousePressEvent(QMouseEvent *pe)\n";
    ptrMousePosition = pe->pos();
    switch (pe->button())
    {
    case Qt::LeftButton:
    {
        leftButtonIsPressed = true;

        if (lineBroken == NULL)
        {
            GLint viewport[4];
            GLdouble modelview[16];
            GLdouble projection[16];
            GLfloat winX, winY, winZ;
            GLdouble posX = 0.0, posY = 0.0, posZ = 0.0;

            glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
            glGetDoublev( GL_PROJECTION_MATRIX, projection );
            glGetIntegerv( GL_VIEWPORT, viewport );

            winX = (float)pe->pos().x();
            winY = (float)viewport[3] - (float)pe->pos().y();
            glReadPixels( int(winX), int(winY), 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &winZ );

            gluUnProject( winX, winY, winZ, modelview, projection, viewport, &posX, &posY, &posZ);

            float x = posX / scene->nSca + scene->xDelta;
            float y = posY / scene->nSca + scene->yDelta;



            float axis[6];
            axis[0] = x - 2.5f;
            axis[1] = y;
            axis[2] = 0.02f;
            axis[3] = x + 2.5f;
            axis[4] = y;
            axis[5] = 0.02f;
            lineBroken = new LineBroken(0.1f, axis, 6, QString("LineBroken"), 1);
            model->getGroup(1).push_back(lineBroken);
            groupIndex = 1;
            elementIndex = model->getGroup(1).size() - 1;
            lineBroken->setSelectedStatus(true);
            lineBroken->getProperties(properties, scene);
            lineBroken->setFixed(false);
            model->setModified(true);
        }

        else
        {
            if (this->tryToSelectControlsInSelectedFigure(ptrMousePosition) == true)
            {
                controlIsSelected = true;
                switch (key)
                {
                case Qt::Key_Control:
                {
                    if (controlIndex == lineBroken->getNumberOfControls() - 1)
                    {
                        //lineBroken->addBreak(false);
                        RoadElement::undoStack->push(new AddLineBrokenBreakCommand(lineBroken, false, scene));
                        controlIndex = lineBroken->getNumberOfControls() - 1;
                    }
                    else
                        if (controlIndex == 0)
                        {
                            //lineBroken->addBreak(true);
                            RoadElement::undoStack->push(new AddLineBrokenBreakCommand(lineBroken, true, scene));
                            controlIndex = 0;
                        }
                }
                    break;
                default:
                    break;
                }
                if (resizeByControlCommand == NULL)
                    resizeByControlCommand = new ResizeByControlCommand(lineBroken,controlIndex, scene);
                scene->setCursor(lineBroken->getCursorForControlElement(controlIndex));
                scene->updateGL();
            }
            else
            {
                if (this->tryToSelectFigures(ptrMousePosition) == true)
                {
//                    oldX = (GLdouble)ptrMousePosition.x()/
//                            scene->width()/(scene->nSca * scene->ratio) * 2.0;
//                    oldY = (GLdouble)(scene->height() -  ptrMousePosition.y())/
//                            scene->width()/(scene->nSca * scene->ratio) * 2.0;

                    scene->getWorldCoord(ptrMousePosition, oldX, oldY);
                    scene->setCursor(Qt::SizeAllCursor);
                    scene->updateGL();
                }
                else
                {
                    // Переключить в состояние по умолчанию
                    clear();
                    scene->setMouseTracking(false);
                    scene->setCursor(Qt::ArrowCursor);
                    scene->updateGL();
                    stateManager->setState(stateManager->defaultState);
                }

            }
        }
        scene->updateGL();
    }
        break;

    case Qt::RightButton:
        rightButtonIsPressed = true;
        break;
    default:
        break;
    }
    scene->updateGL();
}
Beispiel #22
0
//*********************************
// OnButtonRun 
//*********************************
void CDialogWmf::OnButtonRun() 
{
	
	BeginWaitCursor();

	UpdateData(TRUE);

	// Get DC
	CDC *pDC = m_pDoc->GetView()->GetDC();
	ASSERT(pDC);

	// Get view rect
	CRect rect;
	m_pDoc->GetView()->GetClientRect(&rect);
	rect.InflateRect(5,5);

	// Create metafile device context
	HDC hMetaDC = CreateEnhMetaFile(pDC->m_hDC,"metafile.emf",NULL,NULL);
	if(!hMetaDC)
	{
		AfxMessageBox("Unable to create MetaFile");
		ReleaseDC(pDC);
		return;
	}

	// Get DC from handle
	CDC *pMetaDC = CDC::FromHandle(hMetaDC);
	ASSERT(pMetaDC);
	pMetaDC->SetMapMode(MM_TEXT); 

	// Position / translation / scale
	glPushMatrix();
	CMeshView *pView = (CMeshView *)m_pDoc->GetView();
	glTranslated(pView->m_xTranslation,pView->m_yTranslation,pView->m_zTranslation);
	glRotatef(pView->m_xRotation, 1.0, 0.0, 0.0);
	glRotatef(pView->m_yRotation, 0.0, 1.0, 0.0);
	glRotatef(pView->m_zRotation, 0.0, 0.0, 1.0);
	glScalef(pView->m_xScaling,pView->m_yScaling,pView->m_zScaling);

	// Get OpenGL parameters
	GLdouble modelMatrix[16];
	GLdouble projMatrix[16];
	GLint viewport[4];
	glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
	glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
	glGetIntegerv(GL_VIEWPORT,viewport);

	// Start rendering via std GDI 2D drawing functions
	CSceneGraph3d *pScene = &m_pDoc->m_SceneGraph;
	for(int i=0;i<pScene->NbObject();i++)
	{
		CObject3d *pObject = pScene->GetAt(i);
		if(pObject->GetType() == TYPE_MESH3D) // meshes only
			// The line mode (no sort)
			if(m_Mode == MODE_LINE) 
				((CMesh3d *)pObject)->glDrawProjectLine(pMetaDC,
				                                        modelMatrix,
																								projMatrix,
																								viewport,
																								m_ColorLine,
																								m_Ratio,
																								rect.Height());
			else 
				// The face mode (faces are z-sorted 
				// according to their barycenter)
				((CMesh3d *)pObject)->glDrawProjectFace(pMetaDC,
				                                        modelMatrix,
																								projMatrix,
																								viewport,
																								m_ColorLine,
																								m_ColorFace,
																								m_Ratio,
																								rect.Height(),
																								m_RatioNbFaces);
	}

	glPopMatrix();

	// Close metafile
	HENHMETAFILE hMetaFile = CloseEnhMetaFile(hMetaDC);

	// Fill the clipboard (direct sent to wmf2eps or 
	// any windows app such as Powerpoint)
	OpenClipboard();
	EmptyClipboard();
	SetClipboardData(CF_ENHMETAFILE,CopyEnhMetaFile(hMetaFile,NULL));
	CloseClipboard();

	// Cleanup
	DeleteEnhMetaFile(hMetaFile);
	ReleaseDC(pDC);

	EndWaitCursor();
}
Beispiel #23
0
void
screen_display(void)
{
    GLfloat pos[4], lKa[4], lKd[4], lKs[4];
    GLfloat dir[3], mKa[4], mKd[4], mKs[4], mKe[4];
    GLfloat lmKa[4];

    cell_vector(pos, light_pos, 4);
    cell_vector(lKa, light_Ka, 4);
    cell_vector(lKd, light_Kd, 4);
    cell_vector(lKs, light_Ks, 4);
    cell_vector(dir, spot_direction, 3);
    cell_vector(mKa, material_Ka, 4);
    cell_vector(mKd, material_Kd, 4);
    cell_vector(mKs, material_Ks, 4);
    cell_vector(mKe, material_Ke, 4);
    cell_vector(lmKa, lmodel_Ka, 4);

    glLightModelf(GL_LIGHT_MODEL_LOCAL_VIEWER, local_viewer.value);
    glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, two_side.value);
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmKa);

    glLightfv(GL_LIGHT0, GL_POSITION, pos);
    glLightfv(GL_LIGHT0, GL_AMBIENT, lKa);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, lKd);
    glLightfv(GL_LIGHT0, GL_SPECULAR, lKs);
    glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, dir);
    glLighti(GL_LIGHT0, GL_SPOT_EXPONENT, (int)spot_exponent.value);
    if (spot_cutoff.value > 90)
        glLighti(GL_LIGHT0, GL_SPOT_CUTOFF, 180);
    else
        glLighti(GL_LIGHT0, GL_SPOT_CUTOFF, (int)spot_cutoff.value);
    glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, Kc.value);
    glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, Kl.value);
    glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, Kq.value);

    glMaterialfv(GL_FRONT, GL_AMBIENT, mKa);
    glMaterialfv(GL_FRONT, GL_DIFFUSE, mKd);
    glMaterialfv(GL_FRONT, GL_SPECULAR, mKs);
    glMaterialfv(GL_FRONT, GL_EMISSION, mKe);
    glMaterialf(GL_FRONT, GL_SHININESS, material_Se.value);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glPushMatrix();
    glRotatef(spin_y, 1.0, 0.0, 0.0);
    glRotatef(spin_x, 0.0, 1.0, 0.0);
    glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
    if (pmodel)
        drawmodel();
    else
        glutSolidTorus(0.25, 0.75, 28, 28);
    glPopMatrix();

#if 0
#define TESS 20
    glNormal3f(0.0, 1.0, 0.0);
    for (i = 0; i < TESS; i++) {
        glBegin(GL_TRIANGLE_STRIP);
        for (j = 0; j <= TESS; j++) {
            glVertex3f(-1+(float)i/TESS*2, -1.0, -1+(float)j/TESS*2);
            glVertex3f(-1+(float)(i+1)/TESS*2, -1.0, -1+(float)j/TESS*2);
        }
        glEnd();
    }
#endif

    glutSwapBuffers();
}
void Frame::select(int mouse_x, int mouse_y)
{
	
	GLuint	buffer[512];
	GLint	hits;
	GLint   viewport[4];
	glGetIntegerv(GL_VIEWPORT, viewport);
	glSelectBuffer(512, buffer);

	mouse_y = (viewport[3]-mouse_y);
	glRenderMode(GL_SELECT);
	glInitNames();
	glPushName(0); 
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	gluPickMatrix((GLdouble) mouse_x, (GLdouble) mouse_y, 1.0f, 1.0f, viewport);

	gluPerspective(m_fov, (GLfloat) (viewport[2]-viewport[0])/(GLfloat) (viewport[3]-viewport[1]), 0.1f, 100.0f);
	glMatrixMode(GL_MODELVIEW);
	DrawGLScene();
	glMatrixMode(GL_PROJECTION);   
	glPopMatrix(); 
	glMatrixMode(GL_MODELVIEW);
	hits=glRenderMode(GL_RENDER);

	if (hits > 0) 
	{
		int choose = buffer[3];
		int depth = buffer[1];
		for (int loop = 1; loop < hits; loop++)         
		{			
			if (buffer[loop*4+1] < GLuint(depth))
			{
				choose = buffer[loop*4+3];        
				depth = buffer[loop*4+1];         
			}       
		}

		// ray 구해서 가장 가까운점 찾음.
		GLdouble modelViewMatrix[16];
		GLdouble projectionMatrix[16];
		int viewport[4];

		glGetDoublev(GL_MODELVIEW_MATRIX, modelViewMatrix);
		glGetDoublev(GL_PROJECTION_MATRIX, projectionMatrix);
		glGetIntegerv(GL_VIEWPORT, viewport);

		GLdouble nearPlaneLocation[3];
		gluUnProject(mouse_x, mouse_y, 0.0, modelViewMatrix, projectionMatrix,
			viewport, &nearPlaneLocation[0], &nearPlaneLocation[1], 
			&nearPlaneLocation[2]);

		GLdouble farPlaneLocation[3];
		gluUnProject(mouse_x, mouse_y, 1.0, modelViewMatrix, projectionMatrix,
			viewport, &farPlaneLocation[0], &farPlaneLocation[1],
			&farPlaneLocation[2]);

		Vector3F ray;
		Vector3F pos;
		for(int i = 0; i < 3; i++)
		{
			ray[i] = farPlaneLocation[i] - nearPlaneLocation[i];
			pos[i] = nearPlaneLocation[i];
		}		
		m_mesh.select_vertex(choose,pos,ray);
	}
}
void SeedGLWidget::selectRegion()
{
	/*if (_seedRegions.empty())
	{
		return;
	}*/

	glViewport (0, 0, 1024, 1024);

	glBindTexture(GL_TEXTURE_2D, 0);
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, _fboId);
	glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);

	glClearColor (0.0f, 0.0f, 0.0f, 0.0f);
	glClear (GL_COLOR_BUFFER_BIT);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluOrtho2D(0, _widgetWidth-_planeWidth, _widgetHeight, 0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();

	glColor3f(1, 1, 1);

	gluTessBeginPolygon(tessObj, NULL);
	gluTessBeginContour(tessObj);
	for (int i=0; i<_penTrack.size(); ++i)
	{
		gluTessVertex(tessObj, _penTrack[i], _penTrack[i]);
	}
	gluTessEndContour(tessObj);
	gluTessEndPolygon(tessObj);
	
	glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
	GLubyte * tempBuffer = new GLubyte [1024*1024];
	glBindTexture(GL_TEXTURE_2D, _texId);
	glGetTexImage(GL_TEXTURE_2D, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, tempBuffer);

	GLdouble modelMatrix[16];
	GLdouble projMatrix[16];
	int viewport[4];

	int viewportWidth = _viewportHeight*(_widgetWidth-_planeWidth)*1.0/_widgetHeight;
	glViewport (0, 0, 1024, 1024);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	glOrtho(0, viewportWidth, 0, _viewportHeight, -2000, 2000);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glTranslatef(_translateX, _translateY, 0);
	glTranslatef(viewportWidth/2.0, _viewportHeight/2.0, 0);
	setRotationMatrix();
	_volumeData->setTransformMatrix();

	glGetIntegerv(GL_VIEWPORT, viewport);
	glGetDoublev(GL_MODELVIEW_MATRIX, modelMatrix);
	glGetDoublev(GL_PROJECTION_MATRIX, projMatrix);

	int minX = floor(_minDrawX*1023.0/(_widgetWidth-_planeWidth-1));
	int maxX = ceil(_maxDrawX*1023.0/(_widgetWidth-_planeWidth-1));
	int minY = floor((_widgetHeight-_maxDrawY)*1023.0/(_widgetHeight-1));
	int maxY = ceil((_widgetHeight-_minDrawY)*1023.0/(_widgetHeight-1));

	for (int i=minX; i<=maxX; ++i)
	{
		for (int j=minY; j<maxY; ++j)
		{
			if (tempBuffer[j*1024+i]>0)
			{
				double x, y, z;
				gluUnProject(i, j, 0, modelMatrix, projMatrix, viewport, &x, &y, &z);
				//add to seed region list

				switch (_viewpoint)
				{
				case 1: //AXIAL
					z = _seedData->_aSliceIdx;
					break;
				case 2: //CORONAL
					y = _seedData->_cSliceIdx;
					break;
				case 3: //SAGITTAL
					x = _seedData->_pSliceIdx;
					break;
				}
				if (_bAddRegion)
				{
					_seedData->addSeedPoint(x,y,z, _currentSeedIndex);
				} else
				{
					_seedData->removeSeedPoint(x,y,z,_currentSeedIndex);
				}
			}
		}
	}

	delete tempBuffer;

	_seedData->setASlice(_aSlicePos);
	_seedData->setPSlice(_pSlicePos);
	_seedData->setCSlice(_cSlicePos);

}
Beispiel #26
0
//---------------------------------------------------------------------------
// Draw the major and minor tick marks
//----------------------------------------------------------------------------
void VisusBorderAxis::renderTickMarks(const float borderWidth, const float borderLength,
                                      const BBAxis axis, const BBTickLine tickLineType)
{ 
  // If drawing ticks is disabled, return
  if(!mDrawTicks)
    return;
  
  float low,high,minor_low,minor_high;
  float dimensions[2] = { borderLength, borderWidth };
  int other = (axis+1) % 2;
  float width = dimensions[other];
  float length = dimensions[axis];

  // Get the current viewport
  GLdouble model[16];
  GLdouble projection[16];
  GLint viewport[4];  // x, y, width, height
  glGetDoublev(GL_PROJECTION_MATRIX, projection);
  glGetDoublev(GL_MODELVIEW_MATRIX, model);
  glGetIntegerv(GL_VIEWPORT,viewport); 

  // Determine number of pixels per tick mark based on thickness (smallest 1)
  float minval = numPixels(model, projection, viewport, length, axis);
  const int numPixelPerMajorTick = std::max(1, (int)floor(minval*mMajorTickThickness));
  const int numPixelPerMinorTick = std::max(1, (int)floor(minval*mMinorTickThickness));
    
  float majorDelta = length / (mMajorTicks-1);
  float minorDelta = majorDelta / mMinorTicks;

  // Determine Tick Up/Down Positions
  low = minor_low = 0;
  high = minor_high = width;
  
  // If we need to draw tick on the normal side (below or right)
  if ((mTickPosition == AXIS_LOW) || (mTickPosition == AXIS_BOTH)) 
    {
      low -= mMajorTickLength * width; // it needs to start this much below 0
      minor_low -= mMinorTickLength * mMajorTickLength * width;
    }

  // If we need to draw tick on the opposite side (above or left)
  if ((mTickPosition == AXIS_HIGH) || (mTickPosition == AXIS_BOTH)) 
    {
      high += mMajorTickLength * width; // it needs to end this much above the bar
      minor_high += mMinorTickLength * mMajorTickLength * width;
    }

  // Set the bounding box
  if (axis == BB_X_AXIS) {
    mDrawBox[0] = 0; 
    mDrawBox[1] = low;
    mDrawBox[3] = length; 
    mDrawBox[4] = high;
  }
  else {
    mDrawBox[0] = low; 
    mDrawBox[1] = 0;
    mDrawBox[3] = high; 
    mDrawBox[4] = length;	  
  }

  mWidth = width;
  mLength= length;
  mDrawAxis = axis;
  mDrawOther = other;
  
  if (! mDrawTicks)
    return;

  mTickColor.glColor();
      
  // We can't change the thickness between a glBegin() and
  // glEnd(). Therefore, we first draw the major ticks then the minor
  // ones
  glLineWidth(numPixelPerMajorTick);
  glBegin(GL_LINES);
  float axisPosition = 0;
  for (int i=0;i<mMajorTicks; ++i, axisPosition+=majorDelta) {
    if (i==0 || i==(mMajorTicks-1))
    	drawTick(low, 0, axisPosition, BB_SOLID);   
    else
    	drawTick(low, high, axisPosition, tickLineType);    
  }
  glEnd();

  
  // Now draw the minor ticks
  glLineWidth(numPixelPerMinorTick);
  glBegin(GL_LINES);
  axisPosition = 0;
  for (int i=0;i<mMajorTicks-1; ++i, axisPosition+=majorDelta) 
    {	  
      for (int j=0;j<mMinorTicks; ++j) 
	{
	  float position = axisPosition + (minorDelta*j);
	  drawTick(minor_low, minor_high, position, tickLineType);
	}
    }
  glEnd();
}
Beispiel #27
0
void GLLUTWidget::paintGL()
{
  m.lock();
  if (gl_ready && needs_init && _lut!=0) {
    init();
  }
  m.unlock();

  glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_ACCUM_BUFFER_BIT);

  setupProjection();

  //setup lens:
  
  //switch to modelview mode
  glMatrixMode( GL_MODELVIEW );
  
  glLoadIdentity();

  glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
  //cam.apply();

  if (view_mode==VIEW_SINGLE || view_mode==VIEW_GRID) {
    gluLookAt(0.0,0.0,100.0, 0.0, 0.0, 0.0,0.0,1.0,0.0);
  } else {
    cam.apply();
  }

  if (_lut==0) return;
  //store matrices for reverse mouse-lookup
  for (int i=0;i<(int)slices.size();i++) {
    Slice * s=slices[i];
    if (s->bg_update_pending) {
      if (s->bg->update()==false) printf("draw-slice texture update failed\n");
      s->bg_update_pending=false;
    }
    if (s->selection_update_pending) {
      if (s->selection->update(GL_CLAMP,GL_CLAMP,GL_NEAREST,GL_NEAREST)==false) printf("draw-slice texture update failed\n");
      s->selection_update_pending=false;
    }
    if (s->sampler_update_pending) {
      if (s->sampler->update(GL_CLAMP,GL_CLAMP,GL_LINEAR,GL_NEAREST)==false) printf("draw-slice texture update failed\n");
      s->sampler_update_pending=false;
    }
  }

  
  //let's draw a slice
  //glColor3f(0.0,0.0,0.0);
  if (view_mode==VIEW_SINGLE) {
    glGetIntegerv(GL_VIEWPORT,viewport);
    glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
    glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
    glDrawSlice(slices[state.slice_idx]);
  } else if (view_mode==VIEW_GRID) {
    int cols=(int)(sqrt(slices.size()));
    int rows=slices.size()/cols;
    int c=0;
    int r=0;
    for (int i=0;i<(int)slices.size();i++) {
      glPushMatrix();
      glTranslatef((1.0/(float)cols)*(float)c,(1.0/(float)rows)*(float)r,0.0);
      c++;
      if (c >= cols) { c=0; r++; }

      glScalef((1.0/(float)cols)*0.98,(1.0/(float)rows)*0.98,1.0);
      glTranslatef(0.01,0.01,0.0);
      if (i==state.slice_idx) {
        glGetIntegerv(GL_VIEWPORT,viewport);
        glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
        glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
      }
      glDrawSlice(slices[i]);
      glBindTexture(GL_TEXTURE_2D,0);
      glColor3f(1.0,1.0,1.0);
      if (i==state.slice_idx) {
        glPushMatrix();
        glLineWidth(2.0);
        glBegin(GL_LINES);

        glVertex3f(0.0,0.0,0.01);
        glVertex3f(1.0,0.0,0.01);

        glVertex3f(1.0,0.0,0.01);
        glVertex3f(1.0,1.0,0.01);

        glVertex3f(1.0,1.0,0.01);
        glVertex3f(0.0,1.0,0.01);

        glVertex3f(0.0,1.0,0.01);
        glVertex3f(0.0,0.0,0.01);

        glEnd();
        glPopMatrix();
      }
      glPopMatrix();
    }
  } else if (view_mode==VIEW_CUBE) {

      

      glTranslatef(-0.5,-0.5,-0.5);
      glColor3f(0.7,0.7,0.7);
      glPushMatrix();
        glLineWidth(1.0);
        glBegin(GL_LINES);

        glVertex3f(0.0,0.0,0.0);
        glVertex3f(1.0,0.0,0.0);

        glVertex3f(0.0,1.0,0.0);
        glVertex3f(1.0,1.0,0.0);

        glVertex3f(0.0,0.0,1.0);
        glVertex3f(1.0,0.0,1.0);

        glVertex3f(0.0,1.0,1.0);
        glVertex3f(1.0,1.0,1.0);

        glVertex3f(0.0,0.0,0.0);
        glVertex3f(0.0,1.0,0.0);

        glVertex3f(1.0,0.0,0.0);
        glVertex3f(1.0,1.0,0.0);

        glVertex3f(0.0,0.0,1.0);
        glVertex3f(0.0,1.0,1.0);

        glVertex3f(1.0,0.0,1.0);
        glVertex3f(1.0,1.0,1.0);

        glVertex3f(0.0,0.0,0.0);
        glVertex3f(0.0,0.0,1.0);

        glVertex3f(0.0,1.0,0.0);
        glVertex3f(0.0,1.0,1.0);

        glVertex3f(1.0,0.0,0.0);
        glVertex3f(1.0,0.0,1.0);

        glVertex3f(1.0,1.0,0.0);
        glVertex3f(1.0,1.0,1.0);

        glEnd();
      glPopMatrix();
    for (int i=0;i<(int)slices.size();i++) {
      glPushMatrix();
      glTranslatef(0.0,0.0,(1.0 / (float)slices.size()) * (float)i);
      //glScalef((1.0/(float)cols)*0.98,(1.0/(float)rows)*0.98,1.0);
      //glTranslatef(0.01,0.01,0.0);
      /*if (i==state.slice_idx) {
        glGetIntegerv(GL_VIEWPORT,viewport);
        glGetDoublev(GL_PROJECTION_MATRIX,projMatrix);
        glGetDoublev(GL_MODELVIEW_MATRIX,modelMatrix);
      }*/
      glDrawSlice(slices[i]);
      glBindTexture(GL_TEXTURE_2D,0);
      


      glColor3f(1.0,1.0,1.0);
      if (i==state.slice_idx) {
        glPushMatrix();
        glLineWidth(2.0);
        glBegin(GL_LINES);

        glVertex3f(0.0,0.0,0.01);
        glVertex3f(1.0,0.0,0.01);

        glVertex3f(1.0,0.0,0.01);
        glVertex3f(1.0,1.0,0.01);

        glVertex3f(1.0,1.0,0.01);
        glVertex3f(0.0,1.0,0.01);

        glVertex3f(0.0,1.0,0.01);
        glVertex3f(0.0,0.0,0.01);

        glEnd();
        glPopMatrix();
      }
      glPopMatrix();
    }
  }

  c_draw.count();
  //updateVideoStats(stats);
}
Beispiel #28
0
void GlStateSnapshot::log(std::string id, unsigned key, int type) {
	GLint ival[4];
	GLboolean bval[4];
	GLdouble dval[4];
	GLfloat fval[16];
	ival[0] = ival[1] = ival[2] = ival[3] = 0;
	fval[0] = fval[1] = fval[2] = fval[3] = 0;
	dval[0] = dval[1] = dval[2] = dval[3] = 0;
	bval[0] = bval[1] = bval[2] = bval[3] = false;
	std::ostringstream os;
	switch (type) {
		case INTv:
			glGetIntegerv(key, ival);
			os << "GL state: " << id << " " << ival[0];
			break;
		case BOOLv:
			glGetBooleanv(key, bval);
			os << "GL state: " << id << " " << (bval[0] ? "yes" : "no");
			break;
		case FLOATv:
			glGetFloatv(key, fval);
			os << "GL state: " << id << " " << fval[0];
			break;
		case DOUBLEv:
			glGetDoublev(key, dval);
			os << "GL state: " << id << " " << dval[0];
			break;
		case INTv2:
			glGetIntegerv(key, ival);
			os << "GL state: " << id << " " << ival[0] << " " << ival[1];
			break;
		case INTv4:
			glGetIntegerv(key, ival);
			os << "GL state: " << id << " " << ival[0] << " " << ival[1] << " " << ival[2] << " " << ival[3];
			break;
		case BOOLv4:
			glGetBooleanv(key, bval);
			os << "GL state: " << id << " " << (bval[0] ? 'y':'n') << " " << (bval[1] ? 'y':'n') << " " << (bval[2] ? 'y':'n') << " " << (bval[3] ? 'y':'n');
			break;
		case FLOATv4:
			glGetFloatv(key, fval);
			os << "GL state: " << id << " " << fval[0] << " " << fval[1] << " " << fval[2] << " " << fval[3];
			break;
		case FLOATv16:
			glGetFloatv(key, fval);
			os << "GL state: " << id << "0 " << fval[0] << " " << fval[1] << " " << fval[2] << " " << fval[3] << "\n";
			os << "GL state: " << id << "1 " << fval[4] << " " << fval[5] << " " << fval[6] << " " << fval[7] << "\n";
			os << "GL state: " << id << "2 " << fval[8] << " " << fval[9] << " " << fval[10] << " " << fval[11] << "\n";
			os << "GL state: " << id << "3 " << fval[12] << " " << fval[13] << " " << fval[14] << " " << fval[15];
			break;
		case TEXENViv:
			glGetTexEnviv(GL_TEXTURE_ENV, key, ival);
			os << "GL state: " << id << " " << ival[0];
			break;
		case TEXENVfv4:
			glGetTexEnvfv(GL_TEXTURE_ENV, key, fval);
			os << "GL state: " << id << " " << fval[0] << " " << fval[1] << " " << fval[2] << " " << fval[3];
			break;
		case TEXGENiv:
			glGetTexGeniv(GL_Q, key, ival); ival[3] = ival[0];
			glGetTexGeniv(GL_R, key, ival); ival[2] = ival[0];
			glGetTexGeniv(GL_T, key, ival); ival[1] = ival[0];
			glGetTexGeniv(GL_S, key, ival);
			os << "GL state: " << id << " " << ival[0] << " " << ival[1] << " " << ival[2] << " " << ival[3];
			break;
	}
	m_StateLog.push_back(os.str());
}
void CGraphicsReaction::Draw( CDC* pDC, const CWindowFilter& filter, double scale, CGLText* text, double length )
{
	ASSERT( m_pN && m_pRC );

	if( !m_pN || !m_pRC || m_pN->isFree() )
		return;

	float w = (float)ini.size().reactionWidth;
	float l = length;
	
	const CResult* cR = m_pRC->result( *m_pN );
	double xi = m_pN->x();
	double yi = m_pN->y();
	double zi = m_pN->z();
	if( cR )
	{
		xi += scale*cR->displacement( DX );
		yi += scale*cR->displacement( DY );
		zi += scale*cR->displacement( DZ );
		
	}
	COLORREF c = ini.color().nodes;
	ApplyAmbientGLMaterialiv( c );
	glPushMatrix();
	glTranslatef( float( xi ), float( yi ), float( zi ) );
	double mv[16];
	glGetDoublev( GL_MODELVIEW_MATRIX, mv );
	for( int i=0; i<3; i++ ){ 
		for( int j=0; j<3; j++ ) {
			if ( i==j )
				mv[i*4+j] = 1.0;
			else
				mv[i*4+j] = 0.0;
		}
	}
	CPoint p2D;
	CVector3D mvz( mv[8], mv[9], mv[10] );
	CPoint3D p3D( 0., -l, 0. );
	if( m_pN->isFixed( DX ) && !zero(cR->force( DX )) && filter.node.fx )
	{
		CString label = "FX = ";
		label += Units::show( FORCE_UNIT, cR->force( DX ));
		text->ClearText();
		text->AddLine( label );
		glPushMatrix();
			if( cR->force( DX ) < 0. )
				glRotatef( 180.f, 0.f, 0.f, 1.f );
			DrawLineArrow( l, w, pDC, text,
						ini.font().graphWindow.name, 
						ini.font().graphWindow.size, 
						ini.color().nodalLoads); 
		glPopMatrix();
	}
	if( m_pN->isFixed( DY ) && !zero(cR->force( DY )) && filter.node.fy )
	{
		CString label = "FY = ";
		label += Units::show( FORCE_UNIT, cR->force( DY ));
		text->ClearText();
		text->AddLine( label );
		glPushMatrix();
		glRotatef( 90.f, 0.f, 0.f, 1.f );
			if( cR->force( DY ) < 0. )
				glRotatef( 180.f, 0.f, 0.f, 1.f );
			DrawLineArrow( l, w, pDC, text,
						ini.font().graphWindow.name, 
						ini.font().graphWindow.size, 
						ini.color().nodalLoads); 
		glPopMatrix();
	}
	if( m_pN->isFixed( DZ ) && !zero(cR->force( DZ )) && filter.node.fz )
	{
		CString label = "FZ = ";
		label += Units::show( FORCE_UNIT, cR->force( DZ ));
		text->ClearText();
		text->AddLine( label );
		glPushMatrix();
			glRotatef( 90.f, 0.f, 1.f, 0.f );
			if( cR->force( DZ ) < 0. )
				glRotatef( 180.f, 0.f, 0.f, 1.f );
			DrawLineArrow( l, w, pDC, text,
						ini.font().graphWindow.name, 
						ini.font().graphWindow.size, 
						ini.color().nodalLoads); 
		glPopMatrix();
	}
	if( m_pN->isFixed( RX ) && !zero(cR->force( RX )) && filter.node.mx )
	{
		CString label = "MX = ";
		label += Units::show( MOMENT_UNIT, cR->force( RX ));
		text->ClearText();
		text->AddLine( label );
		glPushMatrix();
			glRotatef( 90.f, 0.f, 1.f, 0.f );
			if( cR->force( RX ) < 0. )
				glRotatef( 180.f, 0.f, 0.f, 1.f );
			DrawSolidMomentArrow( l, w, pDC, text,
						ini.font().graphWindow.name, 
						ini.font().graphWindow.size, 
						ini.color().nodalLoads); 
		glPopMatrix();	
		text->AddLine( label );
	}
	if( m_pN->isFixed( RY ) && !zero(cR->force( RY )) && filter.node.my )
	{
		CString label = "MY = ";
		label += Units::show( MOMENT_UNIT, cR->force( RY ));
		text->ClearText();
		text->AddLine( label );
		glPushMatrix();
			glRotatef( 90.f, 1.f, 0.f, 0.f );
			if( cR->force( RY ) > 0. )
				glRotatef( 180.f, 0.f, 0.f, 1.f );
			DrawSolidMomentArrow( l, w, pDC, text,
						ini.font().graphWindow.name, 
						ini.font().graphWindow.size, 
						ini.color().nodalLoads); 
		glPopMatrix();	
	}
	if( m_pN->isFixed( RZ ) && !zero(cR->force( RZ )) && filter.node.mz )
	{
		CString label = "MZ = ";
		label += Units::show( MOMENT_UNIT, cR->force( RZ ));
		text->ClearText();
		text->AddLine( label );
		glPushMatrix();
			if( cR->force( RZ ) < 0. )
				glRotatef( 180.f, 0.f, 1.f, 0.f );
			DrawSolidMomentArrow( l, w, pDC, text,
						ini.font().graphWindow.name, 
						ini.font().graphWindow.size, 
						ini.color().nodalLoads); 
		glPopMatrix();
	}
	glPopMatrix();
}
Beispiel #30
0
void render(void)
{
static GLint iFrames = 0;
static GLfloat fps = 0.0f, DeltaT;
static char cBuffer[64];
struct timeval tv;
GLuint model_id;

	// Update timer
	gettimeofday(&tv, NULL);
	etime = (double)tv.tv_sec + tv.tv_usec / 1000000.0f;

	dt = etime - t0;
	t0 = etime;

	/*
	 * Make the shadow pass
	 *
	 */

	glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, FBO );

	glPushMatrix();

		//Compute light position
		sinE = sinf(eLit);
		cosE = cosf(eLit);
		sinA = sinf(aLit);
		cosA = cosf(aLit);

		lightPos[0] = lightRadius * cosE * sinA;
		lightPos[1] = lightRadius * sinE;
		lightPos[2] = lightRadius * cosE * cosA;
		lightPos[3] = 1.0f;

		//Set light position
		glLightfv(GL_LIGHT0, GL_POSITION, lightPos);

		//Set up camera to light location
		glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		gluPerspective( 70.0f, 1.0f, 75.0f, 350.0f );
		glGetDoublev(GL_PROJECTION_MATRIX, lightProjection );
		glMatrixMode(GL_MODELVIEW);
		glLoadIdentity();
		gluLookAt( lightPos[0], lightPos[1], lightPos[2],
			0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f );
		glGetDoublev(GL_MODELVIEW_MATRIX, lightModelview );
		glViewport( 0, 0, shadow_sz, shadow_sz );

		glClear(GL_DEPTH_BUFFER_BIT);

		glEnable(GL_POLYGON_OFFSET_FILL);
		glShadeModel(GL_FLAT);

		//Rotate scene, if required
		glRotatef(xRot, 1.0f, 0.0f, 0.0f);
		glRotatef(yRot, 0.0f, 1.0f, 0.0f);

		//Disable shaders
		glUseProgramObjectARB(0);
		glDisable(GL_VERTEX_PROGRAM_ARB);
		glDisable(GL_FRAGMENT_PROGRAM_ARB);

		// Draw dynamic objects
		for (model_id = 0; model_id < NUM_MODELS; model_id++ )
		{
			//Update the kinematic's state
			UpdateMD2(md2_model[model_id], dt);
	
			//Animate the MD2 models
			AnimateMD2(md2_model[model_id], dt);
			
			//Draw the geometry
			glPushMatrix();
				glTranslatef(	md2_model[model_id]->position.x,
						md2_model[model_id]->position.y,
						md2_model[model_id]->position.z );
				glRotatef( md2_model[model_id]->rotation, 0.0f, 1.0f, 0.0f );
				DrawMD2(md2_model[model_id]);
			glPopMatrix();
		}

	glPopMatrix();

	glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 );

	/*
	 * And now the normal pass
	 *
	 */

	//Back to normal settings
	glDisable(GL_POLYGON_OFFSET_FILL);
	glShadeModel(GL_SMOOTH);
	change_size( width, height );

	// Clear the window with current clearing color
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glPushMatrix();

		//Set up camera location and parameters
		setup_camera((float)dt);

		//Retrieve modelview matrix and invert it
		glGetDoublev(GL_MODELVIEW_MATRIX, cameraModelview );
		FastInvert4( cameraModelview, cameraModelviewInverse );

		//Set up depth texture
		glActiveTexture(GL_TEXTURE2);
		glBindTexture(GL_TEXTURE_2D, shadow_tx);

		//Set up texture matrix for shadow map projection
		glMatrixMode(GL_TEXTURE);
		glLoadIdentity();
		glTranslatef(0.5f, 0.5f, 0.5f);
		glScalef(0.5f, 0.5f, 0.5f);
		glMultMatrixd(lightProjection);
		glMultMatrixd(lightModelview);
		glMultMatrixd(cameraModelviewInverse);
		glMatrixMode(GL_MODELVIEW);

		//Rotate scene
		glRotatef(xRot, 1.0f, 0.0f, 0.0f);
		glRotatef(yRot, 0.0f, 1.0f, 0.0f);

		//Re-enable shaders
		glEnable(GL_VERTEX_PROGRAM_ARB);
		glEnable(GL_FRAGMENT_PROGRAM_ARB);

		if (GLSLshader)
			glUseProgramObjectARB(progObj);
		else
			glUseProgramObjectARB(0);

		//Floor

		//Color
		glColor3f(0.64f, 0.63f, 0.65f);

		//Set textures
		glActiveTexture(GL_TEXTURE0);	//Diffuse map
		glBindTexture(GL_TEXTURE_2D, texture_id[NUM_TEXTURES-2]);

		glActiveTexture(GL_TEXTURE1);	//Normal map
		glBindTexture(GL_TEXTURE_2D, texture_id[NUM_TEXTURES-1]);

		//Set Tangent vector
		glVertexAttrib3fv( tangent, floorT );

		//Set Binormal vector
		glVertexAttrib3fv( binormal, floorB );

		//Set Normal vector
		glNormal3fv( floorN );

		//Call Display List to draw
		glCallList(FList);

		// Draw dynamic objects
		for (model_id = 0; model_id < NUM_MODELS; model_id++ )
		{
			//Set color
			glColor3f(	md2_model[model_id]->color.x,
					md2_model[model_id]->color.y,
					md2_model[model_id]->color.z );
	
			//Set texture
			glActiveTexture(GL_TEXTURE0);
			glBindTexture(GL_TEXTURE_2D, texture_id[2*model_id]);
			glActiveTexture(GL_TEXTURE1);
			glBindTexture(GL_TEXTURE_2D, texture_id[2*model_id+1]);
	
			//Draw the geometry
			glPushMatrix();
				glTranslatef(	md2_model[model_id]->position.x,
						md2_model[model_id]->position.y,
						md2_model[model_id]->position.z );
				glRotatef( md2_model[model_id]->rotation, 0.0f, 1.0f, 0.0f );
				DrawMD2(md2_model[model_id]);
			glPopMatrix();
		}

	glPopMatrix();

	iFrames++;
	DeltaT = (GLfloat)(etime-t1);
	if( DeltaT >= Timed )
	{
		fps = (GLfloat)(iFrames)/DeltaT;
		fps_count++;
		fps_mean = ((fps_count - 1.0f) * fps_mean + fps ) / fps_count;

		iFrames = 0;
		t1 = etime;

		sprintf(cBuffer,"FPS: %.1f Mean FPS: %.1f Poly Scale: %.1f Bias: %.1f", fps, fps_mean, scalePoly, biasPoly);
	}
	if (print_fps)
	{
		if (windowpos)
		{
			glColor3f(1.0f, 1.0f, 1.0f);
			glPushAttrib(GL_LIST_BIT);
				glListBase(fps_font - ' ');
				glWindowPos2i(0,2);
				glCallLists(strlen(cBuffer), GL_UNSIGNED_BYTE, cBuffer);
			glPopAttrib();
		}
		if( iFrames == 0 )
			printf("FPS: %.1f Mean FPS: %.1f\n", fps, fps_mean);
	}
	lCam = 0.0f;
	vCam = 0.0f;
	dCam = 0.0f;
}