コード例 #1
0
ファイル: glwidget.cpp プロジェクト: EikaNN/FIB-G
void GLWidget::drawPoint(const Vector& pos, float r, float g, float b) 
{
    static bool created = false;
    static QGLShaderProgram program;
    static GLuint VAO;

    if (!created)
    {
        created = true;
        // 1. Create shaders
        QGLShader vs(QGLShader::Vertex);
        vs.compileSourceCode("#version 330 core \n in vec3 vertex; in vec3 color; uniform mat4 modelViewProjectionMatrix; out vec4 frontColor;    void main() { frontColor = vec4(color,1); gl_Position = modelViewProjectionMatrix * vec4(vertex, 1.0); }");
        QGLShader fs(QGLShader::Fragment);
        fs.compileSourceCode("#version 330 core \n in vec4 frontColor; out vec4 FragColor; void main() {FragColor = frontColor;}");	
        program.addShader(&vs);
        program.addShader(&fs);
        program.link();

        // Get location of VS attributes
        GLuint vertexLoc = program.attributeLocation("vertex");
        GLuint colorLoc  = program.attributeLocation("color");

        // 2. Create VBO Buffers

        // Create & bind empty VAO
        glGenVertexArrays(1, &VAO);
        glBindVertexArray(VAO);
        // Create VBO with (x,y,z) coordinates
        float coords[] = { 0, 0, 0}; 
        GLuint VBO_coords;
        glGenBuffers(1, &VBO_coords);
        glBindBuffer(GL_ARRAY_BUFFER, VBO_coords);
        glBufferData(GL_ARRAY_BUFFER, sizeof(coords), coords, GL_STATIC_DRAW);
        glVertexAttribPointer(vertexLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
        glEnableVertexAttribArray(vertexLoc);
        // Create VBO with (r,g,b) color
        float colors[] = {r, g, b};
        GLuint VBO_colors;
        glGenBuffers(1, &VBO_colors);
        glBindBuffer(GL_ARRAY_BUFFER, VBO_colors);
        glBufferData(GL_ARRAY_BUFFER, sizeof(colors), colors, GL_STATIC_DRAW);
        glVertexAttribPointer(colorLoc, 3, GL_FLOAT, GL_FALSE, 0, 0);
        glEnableVertexAttribArray(colorLoc);

        glBindVertexArray(0);
    }

    program.bind();

    // 1. Define uniforms
    QMatrix4x4 T;
    T.translate(pos); 
    QMatrix4x4 MVP = camera()->projectionMatrix() * camera()->modelviewMatrix()*T;
    program.setUniformValue("modelViewProjectionMatrix", MVP);    

    // 2. Draw
    glPointSize(8);
    glBindVertexArray (VAO);
    glDrawArrays(GL_POINTS, 0, 1);
    glBindVertexArray(0);
    program.release();
}
コード例 #2
0
ファイル: main.cpp プロジェクト: PFCM/COMP308FinalProject
void display() {
    // test the perlin noise
    glClear(GL_COLOR_BUFFER_BIT);
    
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
    {
        float mat[16];
        cameraRotation.toMatrix(mat);
        glMultMatrixf(mat);
        
        if (display_vortons) {
            /*glEnable(GL_LIGHT0);
             glEnable(GL_LIGHTING);*/
            for (vorton &v : vortons) {
                //glBegin(GL_POINTS);
                //glVertex3f(v.mPos[0], v.mPos[1], v.mPos[2]);
                glColor3f(0.0,0.5,0.5);
                glPushMatrix();
                glTranslatef(v.mPos[0], v.mPos[1], v.mPos[2]);
                glutSolidSphere(.03, 8,8);
                glPopMatrix();
                glBegin(GL_LINES);
                {
                    glColor3f(1.0, 0.0, 0.0);
                    glVertex3f(v.mPos[0], v.mPos[1], v.mPos[2]);
                    glVertex3f(v.mPos[0]+v.mVel[0]*0.1,
                               v.mPos[1]+v.mVel[1]*0.1,
                               v.mPos[2]+v.mVel[2]*0.1);
                    glColor3f(0.0, 1.0, 0.0);
                    glVertex3f(v.mPos[0], v.mPos[1], v.mPos[2]);
                    glVertex3f(v.mPos[0]+v.mVorticity[0]*0.1,
                               v.mPos[1]+v.mVorticity[1]*0.1,
                               v.mPos[2]+v.mVorticity[2]*0.1);
                }
                glEnd();
            }
        }
        
        glDisable(GL_LIGHTING);
        glEnable(GL_POINT_SMOOTH);
        glEnable (GL_BLEND);
        glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glPointSize(3);
        for (particle &p : tracers) {
            float col = (200-p.mLife)/200.0;
            glColor4f(col, col, col, (1-col)*0.05);
            if (particle_lines) {
                glBegin(GL_LINES);
                glVertex3f(p.mPos[0], p.mPos[1], p.mPos[2]);
                glVertex3f(p.mPos[0]-p.mVel[0]*gTimeStep,
                           p.mPos[1]-p.mVel[1]*gTimeStep,
                           p.mPos[2]-p.mVel[2]*gTimeStep);
                glEnd();
            } else {
                glBegin(GL_POINTS);
                glVertex3f(p.mPos[0], p.mPos[1], p.mPos[2]);
                glEnd();
            }
        }
    }
    glPopMatrix();
    
    if (show_info)
        print_info();
    
    glutSwapBuffers();
}
コード例 #3
0
ファイル: glwidget.cpp プロジェクト: jiayuanxu90/3D_DEAL
void GLWidget::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    GLfloat range = 0.0f;

    glLoadIdentity();
    if (halfEdge==NULL || halfEdge->is_empty()) {
        range = 0.0f;
    } else {
        range = halfEdge->range;
    }
    if (range == 0.0f) {
        glTranslatef(0.0f, 0.0f, -1.0f);
    } else {
        glTranslatef(-halfEdge->x_trans/range, -halfEdge->y_trans/range, -halfEdge->z_trans/range-1.0);
    }


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

    glScalef(m_fScale, m_fScale, m_fScale);


    if (!halfEdge->is_empty()) {
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        glBegin(GL_TRIANGLES);
        Face * face_current = halfEdge->get_face_first();
        //int i = 0;
        glColor3f(1.0f, 1.0f, 1.0f);
        while (face_current != halfEdge->get_face_front()) {
            glVertex3f(face_current->e1->vertex1->coordinate_normalized.x(),
                       face_current->e1->vertex1->coordinate_normalized.y(),
                       face_current->e1->vertex1->coordinate_normalized.z());
            glVertex3f(face_current->e2->vertex1->coordinate_normalized.x(),
                       face_current->e2->vertex1->coordinate_normalized.y(),
                       face_current->e2->vertex1->coordinate_normalized.z());
            glVertex3f(face_current->e3->vertex1->coordinate_normalized.x(),
                       face_current->e3->vertex1->coordinate_normalized.y(),
                       face_current->e3->vertex1->coordinate_normalized.z());
            face_current = face_current->next;
            //i++;
            //qDebug() << i;
        }
//        for (int i=0; i<model->node_size(); ++i) {
//            if (!model->normal_indices.empty() && model->normal_indices.size()!=0) {
//                glNormal3f(model->vn_array.at(model->normal_indices.at(i)).x(),
//                           model->vn_array.at(model->normal_indices.at(i)).y(),
//                           model->vn_array.at(model->normal_indices.at(i)).z());
//            }
//            glVertex3f(model->v_array.at(model->vertex_indices.at(i)).x(),
//                       model->v_array.at(model->vertex_indices.at(i)).y(),
//                       model->v_array.at(model->vertex_indices.at(i)).z());
//        }
        glEnd();

        glPointSize(5.0f);
        glBegin(GL_POINTS);
        Vertex * vtx_current = halfEdge->get_vertex_first();
        while (vtx_current != halfEdge->get_vertex_front()) {
            if (vtx_current->isOod()) {
                glColor3f(1.0f, 0.0f, 0.0f);
                glVertex3f(vtx_current->coordinate_normalized.x(),
                           vtx_current->coordinate_normalized.y(),
                           vtx_current->coordinate_normalized.z());
            }
            else if (vtx_current->isEven()) {
                glColor3f(0.0f, 1.0f, 0.0f);
                glVertex3f(vtx_current->coordinate_normalized.x(),
                           vtx_current->coordinate_normalized.y(),
                           vtx_current->coordinate_normalized.z());
            }
            vtx_current = vtx_current->next;
        }
        glEnd();

    }
}
コード例 #4
0
// Inicializacio, a program futasanak kezdeten, az OpenGL kontextus letrehozasa utan hivodik meg (ld. main() fv.)
void onInitialization()
{
	glPointSize(3.0);
	
	Planes.resize(NUM_TRIANGLES_2);
	unsigned int I = 0;
	for(lmVector3D *vertices : triangles2)
	{
		Planes[I] = Q3Plane(vertices[0],vertices[1],vertices[2]);
		I++;
	}
	
	ConstructBrushMesh(Planes,Lines,Vertices,Result);
	
	TeglaPlanes.resize(NUM_TRIANGLES);
	I = 0;
	for(lmVector3D *vertices : triangles)
	{
		TeglaPlanes[I] = Q3Plane(vertices[0],vertices[1],vertices[2]);
		I++;
	}
	
	ConstructBrushMesh(TeglaPlanes,TeglaLines,TeglaVertices,Tegla);
	
	HulyePlanes.resize(NUM_TRIANGLES_3);
	I = 0;
	for(lmVector3D *vertices : triangles3)
	{
		HulyePlanes[I] = Q3Plane(vertices[0],vertices[1],vertices[2]);
		I++;
	}
	
	ConstructBrushMesh(HulyePlanes,HulyeLines,HulyeVertices,Hulye);
	
	PyramidPlanes.resize(NUM_TRIANGLES_4);
	I = 0;
	for(lmVector3D *vertices : triangles4)
	{
		PyramidPlanes[I] = Q3Plane(vertices[0],vertices[1],vertices[2]);
		I++;
	}
	
	ConstructBrushMesh(PyramidPlanes,PyramidLines,PyramidVertices,Pyramid);
	
	GyokerPyramidPlanes.resize(NUM_TRIANGLES_5);
	I = 0;
	for(lmVector3D *vertices : triangles5)
	{
		GyokerPyramidPlanes[I] = Q3Plane(vertices[0],vertices[1],vertices[2]);
		I++;
	}
	
	ConstructBrushMesh(GyokerPyramidPlanes,GyokerPyramidLines,GyokerPyramidVertices,GyokerPyramid);
	
	GyokerHulyePlanes.resize(NUM_TRIANGLES_6);
	I = 0;
	for(lmVector3D *vertices : triangles6)
	{
		GyokerHulyePlanes[I] = Q3Plane(vertices[0],vertices[1],vertices[2]);
		I++;
	}
	
	//ConstructBrushMesh(GyokerHulyePlanes,GyokerHulyeLines,GyokerHulyeVertices,GyokerHulye);
	
	std::cout << "Init finished" << std::endl;
}
コード例 #5
0
ファイル: Nonbreakable.cpp プロジェクト: hydrosolar/CS330
void Nonbreakable::draw(bool update)
{

	if (type_ != REGULAR){
        glColor3ub(255,204,0);
        glBegin(GL_POLYGON);
        glVertex2d(left(),bottom());
        glVertex2d(right(),bottom());
        glVertex2d(right(),top());
        glVertex2d(left(),top());
        glEnd();
	
        if (type_ == QUESTION) {
        
            glColor3ub(255, 0, 0);
            
            glBegin(GL_POLYGON);
            glVertex2d(left()+6, bottom()+6);
            glVertex2d(left()+10, bottom()+6);
            glVertex2d(left()+10, bottom()+14);
            glVertex2d(left()+6, bottom()+14);
            glEnd();
        
            glBegin(GL_POLYGON);
            glVertex2d(left()+6, bottom()+2);
            glVertex2d(left()+10, bottom()+2);
            glVertex2d(left()+10, bottom()+4);
            glVertex2d(left()+6, bottom()+4);
            glEnd();
        
        }
    
    
        glColor3ub(0, 0, 0);
        glPointSize(2.0);
    
        glBegin(GL_POINTS);
        glVertex2d(left()+2, bottom()+2);
        glVertex2d(left()+2, top()-2);
        glVertex2d(right()-2, bottom()+2);
        glVertex2d(right()-2, top()-2);
        glEnd();
    
        glColor3ub(0, 0, 0);
        glBegin(GL_LINE_LOOP);
        glVertex2d(left(), bottom());
        glVertex2d(left(), top());
        glVertex2d(right(), top());
        glVertex2d(right(), bottom());
        glEnd();
    }
    else{
        
        glColor3ub(0, 0, 0);
        glBegin(GL_POLYGON);
        glVertex2d(left(), bottom());
        glVertex2d(right(), bottom());
        glVertex2d(right(), top());
        glEnd();
        
        glColor3ub(199, 133, 120);    
        glBegin(GL_POLYGON);
        glVertex2d(right(), top());
        glVertex2d(left(), top());
        glVertex2d(left(), bottom());
        glEnd();

        glColor3b(0, 0, 0);
        glBegin(GL_LINES);
        glVertex2d(left(), bottom());
        glVertex2d(right(), top());
        glEnd();
        
        glColor3ub(199, 133, 64);
        glBegin(GL_LINES);
        glVertex2d(left(), bottom());
        glVertex2d(right(), top());
        glEnd();
        
        glBegin(GL_POLYGON);
        glVertex2d(left()+4, bottom()+4);
        glVertex2d(left()+4, top()-4);
        glVertex2d(right()-4, top()-4);
        glVertex2d(right()-4, bottom()+4);
        glEnd();
        
        
    }
         
    
  
}
コード例 #6
0
ファイル: lab4.cpp プロジェクト: botanegg/openGlLabs
void lab4::draw() {
    glPushMatrix();
    {
        glBegin(GL_LINES);
        {
            glVertex2f(10, -10);
            glVertex2f(10, 10);
            glVertex2f(-10, 10);
            glVertex2f(-10, -10);
        }
        glEnd();

        float l_x = -10;
        float l_y = func(l_x);

        float t = 0.05f;

        float next_x = l_x + t;
        float next_y = func(next_x);

        bool prev_hi = false;

        while(l_x <= 10) {
            bool is_hi = false;

            if(next_y - l_y > 0) is_hi = true;

            if(is_hi) glColor3f(1.0, 0, 0);

            else glColor3f(0, 1.0, 0);

            glBegin(GL_LINES);
            {
                glVertex2f(l_x, l_y);
                glVertex2f(next_x, next_y);
            }
            glEnd();

            if(prev_hi != is_hi) {
                glPointSize(5);
                glBegin(GL_POINT);
                {
                    glColor3f(0, 1.0, 1.0);
                    drawface(next_x, next_y);
                }
                glEnd();
                glPointSize(1);
            }

            prev_hi = is_hi;

            l_x = next_x;
            l_y = next_y;

            next_x = l_x + t;
            next_y = func(next_x);
        }


    }
    glPopMatrix();
}
コード例 #7
0
//--------------------------------------------------------------
void ofApp::setup(){
    ofSetVerticalSync(true);
    ofEnableAntiAliasing();
    glEnable(GL_POINT_SMOOTH); // use circular points instead of square points
    glPointSize(3);
    
//    // --- Loading files
    ofFileDialogResult openFileResult = ofSystemLoadDialog("Get the txt data", true);
    ofLogNotice()  << "Folder: " << openFileResult.getPath();
    ofDirectory     dirFiles;
    dirFiles.listDir( openFileResult.getPath() );
    ofDrawBitmapString("Loading files", ofGetWidth()/2 - 20, ofGetHeight() / 2 );
    
    for ( int indexOfFile = 0; indexOfFile < dirFiles.size(); ++indexOfFile )
    {
//        ofLogNotice() << "file: " << dirFiles.getPath( indexOfFile );
        ofBuffer buffer = ofBufferFromFile( dirFiles.getPath( indexOfFile ) );
        std::vector< weatherData >     currentWeatherData;
        
        if(buffer.size()) {
            buffer.getNextLine();
            while(buffer.isLastLine() == false) {
                string              line = buffer.getNextLine();
                std::stringstream   lineStream( line );
                string              cell;
                std::getline( lineStream, cell, ';' );
                weatherData data;
                
                std::getline( lineStream, cell, ';' );
                data.lon = ofToDouble( cell );
                std::getline( lineStream, cell, ';' );
                data.lat = ofToDouble( cell );
                std::getline( lineStream, cell, ';' );
                data.temp = ofToDouble( cell );
                std::getline( lineStream, cell, ';' );
                data.velWind = ofToDouble( cell );
                
                currentWeatherData.push_back( data );
//                std::cout << data.lon << "\t" << data.lat << "\t" << data.temp << "\n";
            }
        }
        weatherTimed.weatherDataVector.push_back( currentWeatherData );
        
        // --- transform into pixel vec
        ofMesh  currentMeshTemp, currentMeshWind;
        currentMeshTemp.setMode(OF_PRIMITIVE_POINTS);
        currentMeshWind.setMode(OF_PRIMITIVE_POINTS);
        
        for ( auto &data : weatherTimed.weatherDataVector[ indexOfFile ] )
        {
            data.point = ofVec3f( ofMap( data.lon, 0, 357, 0, 300 ),
                                  ofMap( data.lat, 32, 77, 0, 100),
                                  ofMap( data.temp, 273, 320, 0, 100 ) );
            currentMeshTemp.addColor( ofColor(ofMap( data.temp, 273, 320, 0, 255, true ), 0, 0 ) );
            currentMeshTemp.addVertex( data.point );
            
            currentMeshWind.addColor( ofColor( 0, 0, ofMap( std::abs( data.velWind ), 0, 45, 0, 255, true ) ) );
            currentMeshWind.addVertex( ofVec3f( ofMap( data.lon, 0, 357, 0, 300 ),
                                               ofMap( data.lat, 32, 77, 0, 100),
                                               ofMap( data.velWind, -55, 55, -100, 100 ) ) );
        }
        weatherTimed.meshVecTemp.push_back( currentMeshTemp );
        weatherTimed.meshVecWind.push_back( currentMeshWind );
    }
    
    ofLogNotice() << "Loaded file amount: " << weatherTimed.meshVecTemp.size();

    tempButton.addListener( this, &ofApp::tempPlotActivation );
    windButton.addListener( this, &ofApp::windPlotActivation );
    
    gui.setup();
    gui.add( tempButton.setup( "Temperature Plot", true ) );
    gui.add( windButton.setup("Wind Velocity Plot", false ) );
	gui.add( timeSlider.setup("time", 0, 0, weatherTimed.meshVecTemp.size() - 1 ) );
    gui.add( playButton.setup("play time", false ) );
    gui.add( rotation.setup( "rotation", 0, 0, 360 ) );
    gui.add( autoRotate.setup("Auto Rotate", true ) );
    
    cam.disableMouseInput();
    rotation = 0.0;
    tempPlotActivation();
    
    picturePlot.loadImage("Plot1.png");
}
コード例 #8
0
ファイル: simulator.c プロジェクト: OldNo7/openlase
void draw_gl(void)
{
	int i, ridx;

	static int fno=0;
	fno++;
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();
	glLineWidth(psize);
	glPointSize(psize);

	// horrid workaround for recordmydesktop/libtheora brokenness
#if 0
	glBegin(GL_POINTS);
	glColor4f((fno&1) * (64/256.0), (fno&2) * (32/256.0), (fno&4)  * (16/256.0), 1);
	//glColor4f(1,1,1,1);
	glVertex3f(-0.99, -0.74, 0);
	glVertex3f(0.99, 0.74, 0);
	glVertex3f(-0.99, 0.74, 0);
	glVertex3f(0.99, -0.74, 0);
	glEnd();
#endif

	ridx = (buf_widx - HIST_SAMPLES + BUF_SAMPLES) % BUF_SAMPLES;

	float lx, ly, lg;
	lx = ly = lg = 0;

	float gdelay[2] = {0,0};

	for (i = 0; i<HIST_SAMPLES; i++)
	{
		float g;

		bufsample_t s = buffer[ridx];
		// lowpass
		s.x = lx * 0.65 + s.x * 0.35;
		s.y = ly * 0.65 + s.y * 0.35;
		// delay brightness
		gdelay[i%2] = s.g;
		s.g = gdelay[(i+1)%2];

		float d = sqrtf((s.x-lx)*(s.x-lx) + (s.y-ly)*(s.y-ly));
		if (d == 0)
			d = 0.0001;
		float dfactor = 0.01/d;
		if (dfactor > 1.5)
			dfactor = 1.5;

		int age = HIST_SAMPLES-i;
		float factor;

		factor = (HIST_SAMPLES-age)/(float)HIST_SAMPLES;

		factor = factor*factor;

		if (fabsf(s.x-lx) < 0.001 && fabsf(s.y-ly) < 0.001) {
			g = (s.g-0.2) * factor * 1.4;
			glBegin(GL_POINTS);
			laser_color(g, 0.08);
			glVertex3f(s.x, s.y, 0);
			glEnd();
		} else {
			g = (s.g-0.2) * factor * dfactor * 1.8;
			glBegin(GL_LINES);
			laser_color(lg, 0.8);
			glVertex3f(lx, ly, 0);
			laser_color(g, 0.8);
			glVertex3f(s.x, s.y, 0);
			glEnd();
		}

		lx = s.x;
		ly = s.y;
		lg = g;

		ridx++;
		if (ridx >= BUF_SAMPLES)
			ridx = 0;
	}
	glEnd();
	glutSwapBuffers();
}
コード例 #9
0
ファイル: dphyspush.cpp プロジェクト: melax/dsamples
int main(int argc, char *argv[]) try
{

	physics_driftmax = 0.0025f;

	GLWin glwin("point cloud push interaction");
	RSCam dcam;
	dcam.Init((argc == 2) ? argv[1] : NULL);
	Image<unsigned short> dimage(dcam.dcamera());

	glwin.ViewAngle = dcam.fov().y;
	float viewdist = 2.0f;
	float yaw = 120;
	int mousexold = 0;
	Mesh   mesh;

	bool   pause = false;
	bool   debuglines=false;
	int    center = 0;
	bool   chains = true;
	bool   usehull = false;
	std::vector<RigidBody*> rigidbodies;
	std::vector < std::pair<RigidBody*, RigidBody*>> links;
	for (float x = -0.2f; x < 0.2f; x+= 0.07f)  
		for(float z: {0.350f})
			for (float y = -0.2f; y <= 0.2f; y += 0.07f)
	{
				rigidbodies.push_back(new RigidBody({ AsShape(WingMeshDual(WingMeshCube(0.025f),0.028f)) }, { x,y,z }));
				//rigidbodies.push_back(new RigidBody({ AsShape(WingMeshCube(0.025f)                       ) }, { x,y,z }));
				links.push_back({(y > -0.2f)?rigidbodies[rigidbodies.size() - 2]:NULL , rigidbodies.back()});
	}

	//rigidbodies.push_back(new RigidBody({ AsShape(WingMeshCube(0.05f)) }, { 0,0,0.50f }));

	auto seesaw = new RigidBody({ AsShape(WingMeshBox({ 0.20f, 0.015f,  0.05f })) }, { 0,0,0.45f });
	rigidbodies.push_back(seesaw);

	glwin.keyboardfunc = [&](unsigned char key, int x, int y)->void
	{
		switch (std::tolower(key))
		{
		case 'q': case 27:  exit(0); break;   // 27 is ESC
		case ' ': pause = !pause; break;
		case 'c': chains = !chains; break;
		case 'd': debuglines = !debuglines; break;
		case 'h': usehull = !usehull; break;
		case 'r': for (auto &rb : rigidbodies) { rb->angular_momentum = rb->linear_momentum = float3(0.0f);rb->pose() = { rb->position_start,rb->orientation_start }; }  break;
		default:  std::cout << "unassigned key (" << (int)key << "): '" << key << "'\n";   break;
		}
	};

	if (dcam.dev->supports_option(rs::option::r200_lr_auto_exposure_enabled))
		dcam.dev->set_option(rs::option::r200_lr_auto_exposure_enabled, 1);

	while (glwin.WindowUp())
	{
		if (glwin.MouseState)
		{
			yaw += glwin.mousepos.x - mousexold;
		}
		mousexold = glwin.mousepos.x;
		viewdist *= powf(1.1f, (float)glwin.mousewheel);

		if (!pause)
			dimage = dcam.GetDepth();

		glPushAttrib(GL_ALL_ATTRIB_BITS);
		glViewport(0, 0, glwin.res.x, glwin.res.y);
		glClearColor(0.1f, 0.1f, 0.15f, 1);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadIdentity();
		gluPerspective(glwin.ViewAngle, (double)glwin.aspect_ratio(), 0.01f, 50.0f);

		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		gluLookAt(0, 0, viewdist, 0, 0, 0, 0, -1, 0);
		glEnable(GL_DEPTH_TEST);

		glTranslatef(0, 0, 0.35f);
		glRotatef(yaw, 0, 1, 0);
		glTranslatef(0, 0, -0.35f);

		std::vector<float3> pts;
		std::vector<float3> outliers;
		std::vector<float3> vpts;
		glDisable(GL_BLEND);

		float2 wrange = { 0.20f,0.60f };


		auto dp_image_c = Transform(dimage, [](unsigned short s) {return byte3((unsigned char)clamp(255 - s / 4, 0, 255)); });
		drawimage(dp_image_c, { 0.78f,0.22f }, { 0.2f,-0.2f }, 3);

		float depth_scale = (dcam.dev) ? dcam.dev->get_depth_scale() : 0.001f;  // to put into meters    // if file assume file is mm


		for (auto p : rect_iteration(dimage.dim())) // p is int2 from 0,0 to w,h of dcam
		{
			float d = dimage.pixel(p) * depth_scale;  // d is in meters, whereas depth[i] is in camera units  mm for R200, .125mm for SR300 ivycam
			if (p.x<5 || p.x> dimage.dim().x - 5 || p.y<5 || p.y>dimage.dim().y - 5) continue;  // crop, seems to be lots of noise at the edges
			if (d > 1.0f)  // just too far
				continue;  
			float3 v = dimage.cam.deprojectz(asfloat2(p), d);
			if (d>wrange.x && d < wrange.y) 
				pts.push_back(v);
			else
				outliers.push_back(v);
		}

		vpts = ObtainVoxelPointCloud(pts, 0.0082f, 8);


		std::vector<std::pair<float3, float3>> lines;
		std::vector<std::pair<float3, float3>> glines;

		if (1)// && pts.size())
		{
			std::vector<LimitLinear>  linears;
			std::vector<LimitAngular> angulars;
			physics_gravity = { 0,  (float) chains,0 };  // ugg y is down

			if(!usehull) for(auto rb:rigidbodies) 
			{
				if (!rb->shapes[0].planes.size())
					rb->shapes[0].planes = Planes(rb->shapes[0].verts, rb->shapes[0].tris);
				auto planes = Transform(rb->shapes[0].planes, [&](float4 p) { return rb->pose().TransformPlane(p);});
				rb->gravscale = (float)chains;
				float separation = FLT_MAX;
				float3 pushpoint = float3(0, 0, 0);  //
				float4 pushplane;
				for (auto p : vpts)
				{
						auto plane = mostabove(planes, p);
						float sep;
						if ((sep = dot(plane, float4(p, 1))) < separation)
						{
							pushpoint = p;
							pushplane = plane;
							separation = sep;
						}
				}
				if (separation > 0.1f)
					continue;
				float3 closestpoint = ProjectOntoPlane(pushplane, pushpoint);
				pushplane = float4({ -pushplane.xyz(), -dot(-pushplane.xyz(),pushpoint) });
				linears.push_back(ConstrainAlongDirection(NULL, pushpoint, rb, rb->pose().inverse()*closestpoint, pushplane.xyz(), 0, 100.0f)); //  FLT_MAX));
				lines.push_back({ closestpoint,pushpoint });
				auto cp=Separated(rb->shapes[0].verts, rb->position, rb->orientation, { pushpoint }, { 0,0,0 }, { 0,0,0,1 }, 1);
				glines.push_back({ cp.p0w, cp.p1w });
			}
			Append(linears, ConstrainPositionNailed(NULL, seesaw->position_start, seesaw, { 0, 0, 0 }));
			Append(angulars, ConstrainAngularRange(NULL, seesaw, { 0, 0, 0, 1 }, { 0, 0,-20 }, { 0, 0,20 }));

			if (chains) for (auto link : links)
				Append(linears, ConstrainPositionNailed(link.first,link.first? float3(0, 0.035f, 0) : link.second->position_start-float3(0, -0.035f, 0) , link.second, { 0,-0.035f,0 }));
			if(!pause)
				
				if(usehull && vpts.size()>5) 
					PhysicsUpdate(rigidbodies, linears, angulars, { &vpts });
				else 
					PhysicsUpdate(rigidbodies, linears, angulars, std::vector<std::vector<float3>*>());
		}


		glColor3f(1, 1, 1);
		glwirefrustumz(dcam.deprojectextents(), { 0.1f,1.0f });  // draw the camera frustum volume

		glPushAttrib(GL_ALL_ATTRIB_BITS);
		glPointSize(1);
		glBegin(GL_POINTS);
		glColor3f(0, 1, 0.5f);
		for (auto p : pts)
			glVertex3fv(p);
		glColor3f(1, 0.15f, 0.15f);
		for (auto p : outliers)
			glVertex3fv(p);
		glEnd();

		glPointSize(3);
		glBegin(GL_POINTS);
		glColor3f(1, 1, 1);
		for (auto p : vpts)  // was: spts
			glVertex3fv(p);
		glEnd();

		glPopAttrib();

		if (debuglines)
		{
			glBegin(GL_LINES);
			glColor3f(0, 1, 1);
			if (0)for (auto line : lines)
				glVertex3fv(line.first), glVertex3fv(line.second);
			glColor3f(1, 1, 0);
			for (auto line : glines)
				glVertex3fv(line.first), glVertex3fv(line.second);
			glEnd();
		}
		if (usehull && vpts.size() > 5)
		{
			auto tris = calchull(vpts, 0);
			glBegin(GL_LINES);
			glColor3f(1, 1, 1);
			for (auto t : tris) for( int i : {0,1,1,2,2,0})
				glVertex3fv(vpts[t[i]]);
			glEnd();

		}
		if (chains)
		{
			glBegin(GL_LINES);
			glColor3f(1, 0, 1);
			for (auto link : links)
			{
				if(link.first) 
					glVertex3fv(link.first->pose()* float3(0, 0, 0)), glVertex3fv(link.first->pose()* float3(0, 0.035f, 0));
				glVertex3fv(link.second->pose()* float3(0, 0, 0)) , glVertex3fv(link.second->pose()* float3(0, -0.035f, 0));
			}
			glEnd();
		}
		glPushAttrib(GL_ALL_ATTRIB_BITS);
		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
		glEnable(GL_TEXTURE_2D);
		glColor3f(0.5f, 0.5f, 0.5f);
		for (auto &rb : rigidbodies)
			rbdraw(rb);
		glPopAttrib();   // Restore state

		// Restore state
		glPopMatrix();  //should be currently in modelview mode
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glPopAttrib();
		glMatrixMode(GL_MODELVIEW);

		glwin.PrintString({ 0,0 }, "esc to quit.");
		glwin.PrintString({ 0,1 }, "[h] collision %s  ",(usehull)?"hull":"points");
		glwin.SwapBuffers();

	}
	return 0;
}
catch (const char *c)
{
	MessageBox(GetActiveWindow(), c, "FAIL", 0);
}
catch (std::exception e)
{
	MessageBox(GetActiveWindow(), e.what(), "FAIL", 0);
}
コード例 #10
0
ファイル: tr_shade.cpp プロジェクト: TheDushan/OpenWolf
/*
================
DrawNormals

Draws vertex normals for debugging
================
*/
static void DrawNormals(shaderCommands_t * input)
{
	int             i;
	vec3_t          temp;

	GL_Bind(tr.whiteImage);
	glColor3f(1, 1, 1);
	glDepthRange(0, 0);		// never occluded
	GL_State(GLS_POLYMODE_LINE | GLS_DEPTHMASK_TRUE);

	// ydnar: light direction
	if(r_shownormals->integer == 2)
	{
		trRefEntity_t  *ent = backEnd.currentEntity;
		vec3_t          temp2;

		if(ent->e.renderfx & RF_LIGHTING_ORIGIN)
		{
			VectorSubtract(ent->e.lightingOrigin, backEnd.orientation.origin, temp2);
		}
		else
		{
			VectorClear(temp2);
		}
		temp[0] = DotProduct(temp2, backEnd.orientation.axis[0]);
		temp[1] = DotProduct(temp2, backEnd.orientation.axis[1]);
		temp[2] = DotProduct(temp2, backEnd.orientation.axis[2]);

		glColor3f(ent->ambientLight[0] / 255, ent->ambientLight[1] / 255, ent->ambientLight[2] / 255);
		glPointSize(5);
		glBegin(GL_POINTS);
		glVertex3fv(temp);
		glEnd();
		glPointSize(1);

		if(fabs(VectorLengthSquared(ent->lightDir) - 1.0f) > 0.2f)
		{
			glColor3f(1, 0, 0);
		}
		else
		{
			glColor3f(ent->directedLight[0] / 255, ent->directedLight[1] / 255, ent->directedLight[2] / 255);
		}
		glLineWidth(3);
		glBegin(GL_LINES);
		glVertex3fv(temp);
		VectorMA(temp, 32, ent->lightDir, temp);
		glVertex3fv(temp);
		glEnd();
		glLineWidth(1);
	}
	// ydnar: normals drawing
	else
	{
		glBegin(GL_LINES);
		for(i = 0; i < input->numVertexes; i++)
		{
			glVertex3fv(input->xyz[i].v);
			VectorMA(input->xyz[i].v, r_normallength->value, input->normal[i].v, temp);
			glVertex3fv(temp);
		}
		glEnd();
	}

	glDepthRange(0, 1);
}
コード例 #11
0
//----------------------------------------------------------------------
void appRender()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //this updates the particle system by calling the kernel
    for(int i=0;i<NUM_PARTICLES;++i)
	{	
		

		//we've stored the life in the fourth component of our velocity array
		float life = vel[i].w;
		//decrease the life by the time step (this value could be adjusted to lengthen or shorten particle life
		life -= dt;
		//if the life is 0 or less we reset the particle's values back to the original values and set life to 1
		if(life <= 0)
		{
			pos[i] = pos_gen[i];
			vel[i] = vel_gen[i];
			life = 1.0;    
		}

		//we use a first order euler method to integrate the velocity and position (i'll expand on this in another tutorial)
		//update the velocity to be affected by "gravity" in the z direction
		vel[i].z -= 9.8*dt;
		//update the position with the new velocity
		pos[i].z += vel[i].z*dt;
		//store the updated life in the velocity array
		vel[i].w = life;

		//update the arrays with our newly computed values
		

		//you can manipulate the color based on properties of the system
		//here we adjust the alpha
		color[i].w = life;
		color[i].x=life;
		color[i].y=1-life;
		color[i].z=0.5;
		glBindBuffer(GL_ARRAY_BUFFER, p_vbo);
		glBufferData(GL_ARRAY_BUFFER, array_size,&pos[0], GL_DYNAMIC_DRAW);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		glBindBuffer(GL_ARRAY_BUFFER, c_vbo);
		glBufferData(GL_ARRAY_BUFFER, array_size,&color[0], GL_DYNAMIC_DRAW);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
	}

    //render the particles from VBOs
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_POINT_SMOOTH);
    glPointSize(5.);
    
    //printf("color buffer\n");
    glBindBuffer(GL_ARRAY_BUFFER,c_vbo);
    glColorPointer(4, GL_FLOAT, 0, 0);

    //printf("vertex buffer\n");
    glBindBuffer(GL_ARRAY_BUFFER,p_vbo);
    glVertexPointer(4, GL_FLOAT, 0, 0);

    //printf("enable client state\n");
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);

    //Need to disable these for blender
    glDisableClientState(GL_NORMAL_ARRAY);

    //printf("draw arrays\n");
    glDrawArrays(GL_POINTS, 0,NUM_PARTICLES);

    //printf("disable stuff\n");
    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);
    
    glutSwapBuffers();
}
コード例 #12
0
ファイル: mglStrokeText.c プロジェクト: Field-Lab/Photons
/////////////
//   main   //
//////////////
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) {

  // mglStrokeText( string, x, y, scalex, scaley, linewidth, color, rotation )
  if ( nrhs<3 )
    return;


  // Set character string variable
  // Set scale
  // Set starting position
  int buflen=mxGetN( prhs[0] )*mxGetM( prhs[0] )+1;
  char * inputString=(char*) malloc(buflen);
  mxGetString( prhs[0], inputString, buflen);
  float x,y,scaleX,scaleY;
  float linewidth,rot;
  float color[3];
  
  x=(float) *mxGetPr( prhs[1] );
  y=(float) *mxGetPr( prhs[2] );
  if (nrhs>3) 
    scaleX=(float) *mxGetPr( prhs[3] );
  else
    scaleX=1.0;
  if (nrhs>4) 
    scaleY=(float) *mxGetPr( prhs[4] );
  else
    scaleY=scaleX;
  if (nrhs>5) 
    linewidth=(float) *mxGetPr( prhs[5] );
  else
    linewidth=1;
  if (nrhs>6) {
    color[0]=(float)*mxGetPr( prhs[6] );
    color[1]=(float)*(mxGetPr( prhs[6] )+1);
    color[2]=(float)*(mxGetPr( prhs[6] )+2);
  } else {
    color[0]=1.0;
    color[1]=1.0;
    color[2]=1.0;
  }
  if (nrhs>7) 
    rot=(float) *mxGetPr( prhs[7] );
  else
    rot=0.0;

  glLineWidth(linewidth);

  int rectWidth=0;
  GLint range[2];
  glGetIntegerv(GL_POINT_SIZE_RANGE,range);
  if (range[1]<linewidth) {
    rectWidth=linewidth+1;
  } else {
    glPointSize(linewidth+1);
  }

  char space[]=" ";
  int iS,iC,numstrokes;
  float * strokesX;
  float * strokesY;
  glColor3f(color[0],color[1],color[2]);
  glEnable(GL_LINE_SMOOTH);
  bool charFound;
  
  // Select each character in string
  for (iS=0; iS<buflen-1; iS++) {
    // note that buflen includes null \0 character which we ignore
    iC=0;
    charFound=false;
    if (inputString[iS]==(*space)) {
      // advance x
      x+=(scaleX*1.1);
      continue;
    } else {
      // Find index of corresponding character      
      for (iC=0; iC<MGLNUMCHARS; iC++) {
	if (inputString[iS]==MGLChars[iC]) {
	  //	  mexPrintf("%c %c\n",inputString[iS],MGLChars[iC]);
	  numstrokes=MGLCharNumStrokes[iC];
	  strokesX=MGLCharStrokesX[iC];
	  strokesY=MGLCharStrokesY[iC];
	  // Draw character
	  //	  mexPrintf("%i %i\n",iC, iS);
	  drawStrokeCharacter( x, y, strokesX, strokesY, scaleX, scaleY, numstrokes, MGLCharsWithDots[iC], rot, rectWidth );	
	  // Update x,y
	  x+=(scaleX*1.1); // letter spacing
	  charFound=true;
	  break;
	}	
      }
      if (!charFound) {
	// draw hash
	iC=33;
	numstrokes=MGLCharNumStrokes[iC];
	strokesX=MGLCharStrokesX[iC];
	strokesY=MGLCharStrokesY[iC];
	// Draw character
	//	mexPrintf("%i %i\n",iC, iS);
	drawStrokeCharacter( x, y, strokesX, strokesY, scaleX, scaleY, numstrokes, MGLCharsWithDots[iC], rot, rectWidth );	
	// Update x,y
	x+=(scaleX*1.1); // letter spacing
      }
    }
  }

  if (nlhs==2) {
    plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
    plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL);
    *mxGetPr(plhs[0]) = x;
    *mxGetPr(plhs[1]) = y;
  }
}
コード例 #13
0
ファイル: DotSpreaderTool.cpp プロジェクト: KeckCAVES/flow
void DotSpreaderTool::render(DTS::DataItem* dataItem) const
{
   // if dragging locator render release sphere
   if (active and !data.running)
   {
      // save current attribute state
      #ifdef MESA
      // GL_POINT_BIT causes GL enum error
      glPushAttrib(GL_LIGHTING_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
      #else
      glPushAttrib(GL_LIGHTING_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_POINT_BIT);
      #endif

      glDisable(GL_LIGHTING);

      // save current location
      glPushMatrix();

      // move to center of sphere
      glTranslatef(org[0], org[1], org[2]);

      // compute radius of sphere
      float radius=Math::sqrt((pos[0] - org[0]) * (pos[0] - org[0]) + (pos[1]
            - org[1]) * (pos[1] - org[1]) + (pos[2] - org[2]) * (pos[2]
            - org[2]));

      GLUquadricObj *quadric=gluNewQuadric();

      // draw transparent sphere
      gluQuadricDrawStyle(quadric, GLU_FILL);
      glDepthMask(GL_FALSE);
      glEnable(GL_BLEND);
      glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

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

      gluSphere(quadric, radius, 10, 15);
      glDisable(GL_BLEND);

      // draw surrounding wireframe (solid)
      gluQuadricDrawStyle(quadric, GLU_LINE);
      glDepthMask(GL_TRUE);
      glColor4f(0.0f, 0.8f, 1.0f, 1.0f);

      gluSphere(quadric, radius, 10, 15);
      glDepthMask(GL_FALSE);

      gluDeleteQuadric(quadric);

      // restore previous position
      glPopMatrix();
      // restore previous attribute state
      glPopAttrib();
   }
   // if simulation is running draw particles
   else if (data.running)
   {
      // save current attribute state
      #ifdef MESA
      // GL_POINT_BIT causes GL enum error
      glPushAttrib(GL_LIGHTING_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
      #else
      glPushAttrib(GL_LIGHTING_BIT | GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_POINT_BIT);
      #endif

      glDisable(GL_LIGHTING);
      glDepthMask(GL_FALSE);

      glEnable(GL_POINT_SMOOTH);
      glEnable(GL_BLEND);
      glBlendFunc(GL_SRC_ALPHA, GL_ONE);

      glEnable(GL_TEXTURE_2D);
      glBindTexture(GL_TEXTURE_2D, dataItem->spriteTextureObjectId);
      glTexEnvf(GL_POINT_SPRITE_ARB, GL_COORD_REPLACE_ARB, GL_TRUE);
      glEnable(GL_POINT_SPRITE_ARB);

      float particleRadius=data.point_radius;

      // Query the OpenGL viewing frustum
      GLFrustum<float> frustum;
      frustum.setFromGL();

      #ifdef GHETTO
      if (0)
      #else
      if (dataItem->hasShaders)
      #endif
      {
         /* Calculate the scaled point size for this frustum: */
         GLfloat scaledParticleRadius=frustum.getPixelSize() * particleRadius
               / frustum.getEyeScreenDistance();

         /* Enable the vertex/fragment shader: */
         glEnable(GL_VERTEX_PROGRAM_POINT_SIZE_ARB);
         glUseProgramObjectARB(dataItem->programObject);
         glUniform1fARB(dataItem->scaledParticleRadiusLocation, scaledParticleRadius);
         glUniform1iARB(dataItem->tex0Location, 0);
      }
      else
      {
         glPointSize(particleRadius
               * Vrui::getNavigationTransformation().getScaling());

         GLfloat linear[3]= { 0.0, 1 / 5.0, 0.0 };
         glPointParameterfvARB(GL_POINT_DISTANCE_ATTENUATION_ARB, linear);

         //
         // NOTE::the following scaling calculation does not work properly
         // in the CAVE. This is due to changes in the OpenGL library and
         // cannot be fixed. On a 2D screen the scaling should look correct.
         //

         // Query the OpenGL viewing frustum
         GLFrustum<float> frustum;
         frustum.setFromGL();

         // Calculate the nominal pixel size for particles
         float pointSizeCounter=frustum.getPixelSize() * 2.0f * particleRadius;

         float pointSizeDenominator=frustum.getEyeScreenDistance();

         // Query the maximum point size accepted by glPointSize(...)
         GLfloat pointSizeRange[2];
         glGetFloatv(GL_SMOOTH_POINT_SIZE_RANGE, pointSizeRange);

         // Enable point parameters
         glPointSize(pointSizeRange[1]); // select the maximum point size
         pointSizeCounter/=pointSizeRange[1]; // adjust the point size numerator
         GLfloat attenuation[3]= { 0.0f, 0.0f, 0.0f };
         attenuation[2]=Math::sqr(pointSizeDenominator / pointSizeCounter);
         glPointParameterfvARB(GL_POINT_DISTANCE_ATTENUATION_ARB, attenuation);
      }

      glBindBufferARB(GL_ARRAY_BUFFER_ARB, dataItem->vertexBufferId);
      glEnableClientState(GL_VERTEX_ARRAY);
      glEnableClientState(GL_COLOR_ARRAY);

      // If data has been modified, send to graphics card
      if (dataItem->versionDS != data.currentVersion)
      {
         dataItem->numParticlesDS = data.numPoints;
         glBufferDataARB(GL_ARRAY_BUFFER_ARB, dataItem->numParticlesDS
               * sizeof(ColorPoint), &data.particles[0], GL_DYNAMIC_DRAW_ARB);

         dataItem->versionDS = data.currentVersion;
      }

      glInterleavedArrays(GL_C4UB_V3F, sizeof(ColorPoint), 0);

      glDrawArrays(GL_POINTS, 0, dataItem->numParticlesDS);

      glDisableClientState(GL_COLOR_ARRAY);
      glDisableClientState(GL_VERTEX_ARRAY);

      #ifndef GHETTO
      if (dataItem->hasShaders)
      #endif
      {
         glUseProgramObjectARB(0);
         glDisable(GL_VERTEX_PROGRAM_POINT_SIZE_ARB);
      }

      glBindTexture(GL_TEXTURE_2D, 0);
      glDisable(GL_TEXTURE_2D);
      glDisable(GL_POINT_SPRITE_ARB);
      glDisable(GL_BLEND);

      // restore previous attribute state
      glPopAttrib();
   }
}
コード例 #14
0
ファイル: Goti.cpp プロジェクト: cravindra/OpenGL
void shortestpath(int src)
{

    //START OF BELLMAN FORD
    int j,p,q,x1,y1,x2,y2,x,y;
    int d[MAX],parent[MAX];
    
   int it,flag=0,child[MAX];
   
   //INITIALIZE DATA OBJECTS
   for (it = 1; it <= n; ++it) 
   {
       d[it] = INFINITY;
       parent[it]=src;
       
   }
   d[src] = 0;

   //RELAXATION METHOD
   for(int m=0;m<n;m++)//REPEAT N TIMES
   {
           //RELAX ALL EDGES
           for (it = 1; it <=n; ++it) {
               for (j = 1; j <=n; ++j) {
               
                                           if(d[it]+cost[it][j]<d[j])
                                           {
                                                                     
                                                                     d[j]=d[it]+cost[it][j];
                                                                     parent[j]=it;
                                           }
               }
           }
   }

   //CHECK FOR NEGATIVE LOOPS
for (it = 1; it <=n; ++it) {
       for (j = 1; j <=n; ++j) {
           if(cost[it][j]==INFINITY) continue;
           if(d[it]+cost[it][j]<d[j])
           {
                                    printf("\n\nGraph contains a negative-weight cycle\n");
                                    
                                    
       return;
           }
       }
   }
   
   //INITIALIZE SPANNING TREE EDGES
   int l=0;
   for (int it = 1; it <= n; ++it) {
   if(parent[it]==it) continue;    
tree[l][1]=parent[it];
tree[l++][2]=it;
   }

   //DRAW THE SPANNING TREE
   for(int r=1;r<=n;r++)
   {
     
             x=a[r];
             y=b[r];

             glPointSize(25);
             if(r==src)
                       glColor3f(0.7f, 0.4f, 0.0f);
             else
                       glColor3f(0.5f, 0.5f, 0.8f);

             glBegin(GL_POINTS);
                                glVertex2f(x,y+250);
             glEnd();
             
             glColor3f(0.0,1.0,0.0);
             
             s1=itoa(r,s,10);
             drawstring(x,y+250,s1);
             
             glFlush();

             }
             printf("\nL=%d",l);
             for(int x=0;x<l;x++)
             {
                     p=tree[x][1];
                     q=tree[x][2];
                     if(p==0||q==0) continue;
                     printf("\np=%d\tq=%d",p,q);
                     x1=a[p];
                     y1=b[p];
                     x2=a[q];
                     y2=b[q];
                     
                     if(p<q)
                     {
                            glColor3f(0.0,0.5,0.0);
                            glBegin(GL_LINES);
                                              glVertex2i(x1,y1+250);
                                              glVertex2i(x2,y2+250);
                            glEnd();

                            s1=itoa(cost[p][q],s,10);
                            drawstring((x1+x2)/2,(y1+y2+500)/2,s1);
                     }

                     else
                     {
                            glColor3f(1.0,0.5,0.0);
                            glBegin(GL_LINES);
                                              glVertex2i(x1,y1+250);
                                              glVertex2i(x2,y2+250);
                            glEnd();

                            s1=itoa(cost[p][q],s,10);
                            drawstring((x1+x2)/2,(y1+y2+500)/2,s1);
                     }
                     }
             glFlush();
     
}
コード例 #15
0
PsychError SCREENDrawDots(void)  
{
	PsychWindowRecordType                   *windowRecord;
	int                                     whiteValue, m,n,p,mc,nc,pc,idot_type;
	int                                     i, nrpoints, nrsize;
	boolean                                 isArgThere, usecolorvector, isdoublecolors, isuint8colors;
	double									*xy, *size, *center, *dot_type, *colors;
	unsigned char                           *bytecolors;
	GLfloat									pointsizerange[2];
	double									convfactor;
    
	// All sub functions should have these two lines
	PsychPushHelp(useString, synopsisString,seeAlsoString);
	if(PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);};
	
	// Check for superfluous arguments
	PsychErrorExit(PsychCapNumInputArgs(6));   //The maximum number of inputs
	PsychErrorExit(PsychCapNumOutputArgs(0));  //The maximum number of outputs
	
	// Get the window record from the window record argument and get info from the window record
	PsychAllocInWindowRecordArg(1, kPsychArgRequired, &windowRecord);
	
	// Query, allocate and copy in all vectors...
	nrpoints = 2;
	nrsize = 0;
	colors = NULL;
	bytecolors = NULL;

	PsychPrepareRenderBatch(windowRecord, 2, &nrpoints, &xy, 4, &nc, &mc, &colors, &bytecolors, 3, &nrsize, &size);
	isdoublecolors = (colors) ? TRUE:FALSE;
	isuint8colors  = (bytecolors) ? TRUE:FALSE;
	usecolorvector = (nc>1) ? TRUE:FALSE;
	
	// Get center argument
	isArgThere = PsychIsArgPresent(PsychArgIn, 5);
	if(!isArgThere){
		center = (double *) PsychMallocTemp(2 * sizeof(double));
		center[0] = 0;
		center[1] = 0;
	} else {
		PsychAllocInDoubleMatArg(5, TRUE, &m, &n, &p, &center);
		if(p!=1 || n!=2 || m!=1) PsychErrorExitMsg(PsychError_user, "center must be a 1-by-2 vector");
	}
	
	// Get dot_type argument
	isArgThere = PsychIsArgPresent(PsychArgIn, 6);
	if(!isArgThere){
		idot_type = 0;
	} else {
		PsychAllocInDoubleMatArg(6, TRUE, &m, &n, &p, &dot_type);
		if(p!=1 || n!=1 || m!=1 || (dot_type[0]<0 || dot_type[0]>2))
			PsychErrorExitMsg(PsychError_user, "dot_type must be 0, 1 or 2");
		idot_type = (int) dot_type[0];
	}
	
	// Child-protection: Alpha blending needs to be enabled for smoothing to work:
	// Ok, not such a good idea :-( The flag also enables drawing of round dots and
	// there are applications were we want to set the flag without using alpha blending...
	// Therefore disabled -> May want to turn this into some kind of warning or hint in the future...
	if (idot_type>0 && windowRecord->actualEnableBlending!=TRUE) {
		//PsychErrorExitMsg(PsychError_user, "Point smoothing doesn't work with alpha-blending disabled! See Screen('BlendFunction') on how to enable it.");
	}
	
	// Turn on antialiasing to draw circles	
	if(idot_type) {
		glEnable(GL_POINT_SMOOTH);
		glGetFloatv(GL_POINT_SIZE_RANGE, (GLfloat*) &pointsizerange);
		// A dot type of 2 requests for highest quality point smoothing:
		glHint(GL_POINT_SMOOTH_HINT, (idot_type>1) ? GL_NICEST : GL_DONT_CARE);
	}
	else {
		#ifndef GL_ALIASED_POINT_SIZE_RANGE
		#define GL_ALIASED_POINT_SIZE_RANGE 0x846D
		#endif
		
		glGetFloatv(GL_ALIASED_POINT_SIZE_RANGE, (GLfloat*) &pointsizerange);
	}
	
	// Set size of a single dot:
	if (size[0] > pointsizerange[1] || size[0] < pointsizerange[0]) {
		printf("PTB-ERROR: You requested a point size of %f units, which is not in the range (%f to %f) supported by your graphics hardware.\n",
			   size[0], pointsizerange[0], pointsizerange[1]);
		PsychErrorExitMsg(PsychError_user, "Unsupported point size requested in Screen('DrawDots').");
	}
	
	// Setup initial common point size for all points:
	glPointSize(size[0]);
	
	// Setup modelview matrix to perform translation by 'center':
	glMatrixMode(GL_MODELVIEW);
	
	// Make a backup copy of the matrix:
	glPushMatrix();
	
	// Apply a global translation of (center(x,y)) pixels to all following points:
	glTranslated(center[0], center[1], 0);
	
	// Render the array of 2D-Points - Efficient version:
	// This command sequence allows fast processing of whole arrays
	// of vertices (or points, in this case). It saves the call overhead
	// associated with the original implementation below and is potentially
	// optimized in specific OpenGL implementations.
	
	// Pass a pointer to the start of the point-coordinate array:
	glVertexPointer(2, GL_DOUBLE, 0, &xy[0]);
	
	// Enable fast rendering of arrays:
	glEnableClientState(GL_VERTEX_ARRAY);
	
	if (usecolorvector) {
		PsychSetupVertexColorArrays(windowRecord, TRUE, mc, colors, bytecolors);
	}
	
	// Render all n points, starting at point 0, render them as POINTS:
	if (nrsize==1) {
		// One common point size for all dots provided. Good! This is very efficiently
		// done with one single render-call:
		glDrawArrays(GL_POINTS, 0, nrpoints);
	}
	else {
		// Different size for each dot provided: We have to do One GL - call per dot.
		// This is *pretty inefficient* and should be reimplemented in the future via
		// Point-Sprite extensions, cleverly used display lists or via vertex-shaders...
		// For now we do it the stupid way:
		for (i=0; i<nrpoints; i++) {
			if (size[i] > pointsizerange[1] || size[i] < pointsizerange[0]) {
				printf("PTB-ERROR: You requested a point size of %f units, which is not in the range (%f to %f) supported by your graphics hardware.\n",
					   size[i], pointsizerange[0], pointsizerange[1]);
				PsychErrorExitMsg(PsychError_user, "Unsupported point size requested in Screen('DrawDots').");
			}
			
			// Setup point size for this point:
			glPointSize(size[i]);
			
			// Render point:
			glDrawArrays(GL_POINTS, i, 1);
		}
	}
	
	// Disable fast rendering of arrays:
	glDisableClientState(GL_VERTEX_ARRAY);
	glVertexPointer(2, GL_DOUBLE, 0, NULL);
	
	if (usecolorvector) PsychSetupVertexColorArrays(windowRecord, FALSE, 0, NULL, NULL);
	
	// Restore old matrix from backup copy, undoing the global translation:
	glPopMatrix();
	
	// turn off antialiasing again
	if(idot_type) glDisable(GL_POINT_SMOOTH);
	
	// Reset pointsize to 1.0
	glPointSize(1);
	
	// Mark end of drawing op. This is needed for single buffered drawing:
	PsychFlushGL(windowRecord);
	
 	//All psychfunctions require this.
	return(PsychError_none);
}
コード例 #16
0
ファイル: Level.cpp プロジェクト: cimpresovec/JAHP
void StateLevel::render()
{
	glClear(GL_COLOR_BUFFER_BIT);

	glPushMatrix();

		glOrtho(0,800,600,0,-1,1);

		glColor4ub(70,90,255,255);

			glBegin(GL_QUADS);
				glVertex2f(0,0);
				glColor4ub(180,90,100,255);glVertex2f(800,0);
				glVertex2f(800,600);
				glColor4ub(70,180,50,255);glVertex2f(0,600);
			glEnd();


	glPopMatrix();

	glPushMatrix();

		glTranslated ( -(float)roomX/400, (float)roomY/300, 0);




		o_player.render();

		for ( int n = 0; n < (signed)o_gameObjects.size(); n++ )
		{

			o_gameObjects[n]->render();

		}

		glPushMatrix();

			glOrtho(0,800,600,0,-1,1);

			glColor4ub(255,255,255,255);

			glPointSize(3);
			glBegin(GL_POINTS);
			for ( int n = 0; n < (signed)Gparticles.size(); n++ )
			{
				glVertex2f(Gparticles[n]->f_x, Gparticles[n]->f_y);
			}

			glEnd();

		glPopMatrix();

	glPopMatrix();

	glPushMatrix();

		glOrtho(0,800,600,0,-1,1);

		font.render((int)o_player.f_levelTimer,10,570);

		glColor4ub(255,255,255,255);

			if ( o_player.b_win == true )
			{
				glEnable(GL_TEXTURE_2D);

				if ( o_player.f_levelTimer <= o_scores[i_levelNumber-1]->i_G )
				{
					glBindTexture(GL_TEXTURE_2D, tex_gold);
				}

				else if ( o_player.f_levelTimer <= o_scores[i_levelNumber-1]->i_S)
				{
					glBindTexture(GL_TEXTURE_2D, tex_silver);
				}

				else if (o_player.f_levelTimer <= o_scores[i_levelNumber-1]->i_B)
				{
					glBindTexture(GL_TEXTURE_2D, tex_bronze);
				}

				else
				{
					glBindTexture(GL_TEXTURE_2D, tex_done);
				}

				glBegin(GL_QUADS);
					glTexCoord2i(0,0); glVertex2i(200,150);
					glTexCoord2i(1,0); glVertex2i(600,150);
					glTexCoord2i(1,1); glVertex2i(600,450);
					glTexCoord2i(0,1); glVertex2i(200,450);
				glEnd();

				font.render(o_scores[i_levelNumber-1]->i_S, 250,370);
				font.render(o_scores[i_levelNumber-1]->i_G, 360,370);
				font.render(o_scores[i_levelNumber-1]->i_B, 460,370);

				glDisable(GL_TEXTURE_2D);
			}



	glPopMatrix();

	SDL_GL_SwapBuffers();

}
コード例 #17
0
void TGLForm2D::pintarSinBaldosas()
{
    //Dibujamos el centro del área visible de la escena
        glPointSize(grosorCentro);
        glBegin(GL_POINTS);
            glColor3f(colorCentro1,colorCentro2,colorCentro3);
            glVertex2f((xLeft+xRight)/2.0,(yBot+yTop)/2.0);
        glEnd();

        //Dibujamos el triángulo
        glLineWidth(grosorLinea);
        //Primer vértice del triángulo
        x1=-180;
        y1=-160;
        //Segundo vértice del triángulo
        x2=180;
        y2=-160;
        //Tercer vértice del triángulo
        x3=0;
        y3=160;
        glBegin(GL_LINE_LOOP);
            glColor3f(colorLinea1,colorLinea2,colorLinea3);
            glVertex2f(x1,y1);
            glVertex2f(x2,y2);
            glVertex2f(x3,y3);
        glEnd();

        //Dibujamos el centro de gravedad del triángulo
        glPointSize(grosorGravedad);
        glBegin(GL_POINTS);
            glColor3f(colorGravedad1,colorGravedad2,colorGravedad3);
            glVertex2f((x1+x2+x3)/3.0,(y1+y2+y3)/3.0);
        glEnd();

        //Parte de anidar nTriangulos
        if (anidamientoTotal){
			//calculaMedios();
                                int n =  pow (2,(nTriangulos-1));
                                float i = float(180 / float(n)) ;
                                 float j= float(320 / float(n));
                                 float k= float(360 / float(n));

                                 listaV1 = new listaVertices[2*n];
                                 listaV2 = new listaVertices[2*n];
                                 listaV3 = new listaVertices[2*n];

                                 listaV1[1].x=-180;
                                listaV1[1].y=-160;

                                listaV2[1].x=0;
                                listaV2[1].y=160;

                                 listaV3[1].x=180;
                                 listaV3[1].y=-160;

                                  for (int a = 2;a<=n;a++){
	                                listaV1[a].x=(listaV1[a-1].x)+i;
                                        listaV1[a].y=(listaV1[a-1].y)+j;

                                        listaV2[a].x=(listaV2[a-1].x)+i;
                                        listaV2[a].y=(listaV2[a-1].y)-j;

                                        listaV3[a].x=(listaV3[a-1].x)-k;
                                        listaV3[a].y=-160;
                                }

			//int n =  pow (2,(nTriangulos-1));

			for (int a = 2;a<=n;a++){
				glBegin(GL_LINE_LOOP);
					glColor3f(colorLinea1,colorLinea2,colorLinea3);
					glVertex2f(listaV1[a].x,listaV1[a].y);
					glVertex2f(listaV2[n-a+2].x,listaV2[n-a+2].y);
				glEnd();

				glBegin(GL_LINE_LOOP);
					glColor3f(colorLinea1,colorLinea2,colorLinea3);
					glVertex2f(listaV1[a].x,listaV1[a].y);
					glVertex2f(listaV3[n-a+2].x,listaV3[n-a+2].y);
				glEnd();

                                glBegin(GL_LINE_LOOP);
		                        glColor3f(colorLinea1,colorLinea2,colorLinea3);
		                        glVertex2f(listaV3[a].x,listaV3[a].y);
		                        glVertex2f(listaV2[n-a+2].x,listaV2[n-a+2].y);
		                glEnd();

			}
            if (listaV1!=NULL){
                delete [] listaV1;
                listaV1=NULL;
            }
            if (listaV2!=NULL){
                delete [] listaV2;
                listaV2=NULL;
            }
            if (listaV3!=NULL){
                delete [] listaV3;
                listaV3=NULL;
            }                         
        }
        else{
			for(int i=1;i<nTriangulos;i++){
				calculaMedias();
				dibujaTriangulo(i);
			}
		}
}
コード例 #18
0
ファイル: init.cpp プロジェクト: dagothar/apollo
//inicjalizuj GL
void init_gl(int &argc, char *argv[])
{
    glutInit(&argc, argv);
    
    // tryb rgba + przezroczystosc + bufor z + podwojne buforowanie
    glutInitDisplayMode(GLUT_RGB | GL_DOUBLE | GLUT_DEPTH);
    
    // ustaw okno
    glutInitWindowSize(screenw, screenh);
    glutInitWindowPosition(0, 0);
    window = glutCreateWindow("Apollo");
    
    glClearColor(0.0, 0.0, 10.0*b_atm, 0.0);
    glClearDepth(1.0);
    
    // tryb cieniowania
    glShadeModel(GL_SMOOTH);
    
    // korekcja perspektywiczna
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
    
    // wlacz testowanie z
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    
    //obcinaj tylne sciany poligonow
    glCullFace(GL_BACK);
    
    // ustaw widok
    // projekcja
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(fov, (double)screenw / (double)screenh, 0.1, 100000.0);
    
    // widok
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    
    // ustaw parametry swiatla
    glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
    glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
    glLightfv(GL_LIGHT0, GL_POSITION, light_position);
    glEnable(GL_LIGHT0);
    
    // tryb tekstury
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); // zastap kolor tekstura a nie zmiksuj
    
    // wczytaj tekstury
    //texture_moon = load_texture("moon.bmp");
    
    //wczytaj modele
    if(!SetCurrentDirectory("data")) {
                                     MessageBox(NULL, "Nie znaleziono katalogu!", "B³¹d", MB_OK);
                                     exit(-1);
    }
    
    stack_model.load("lander.obj");
    aps_model.load("lander2.obj");
    
    
    SetCurrentDirectory("..");
     
    
    // wyczysc stany klawiszy
    for(int i = 0; i < 256; ++i) keys[i] = false;
    
    // ignoruj automatyczne powtarzanie klawiszy
    glutIgnoreKeyRepeat(1);
    
    // wlacz przenikanie
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    
    //okragle punkty
    glEnable(GL_POINT_SMOOTH);
    glPointSize(10.0);
}
コード例 #19
0
ファイル: testApp.cpp プロジェクト: badgeek/membajakTV
//--------------------------------------------------------------
void testApp::draw(){
	

			windowCamera.begin();
		
			glPushMatrix();
			//unflip the camera
			//glScalef(1.0, -1.0, 1.0);
			glScalef(4.0, -3.0, 1);
	
			fuxShader.begin();
			
			fuxShader.setUniform1f("eyeMultiply", shaderMultiply);
			fuxShader.setUniformTexture("eyeTexDepth", eyeCam.getTextureReference(), 0);
	
			if	(enableEffects1)
			{
				glPushMatrix();
					glTranslatef(0, 0, effectsTranslate1);
					gridCam.draw(GL_LINES);
				glPopMatrix();
			}

			if	(enableEffects2)
			{
				glPushMatrix();
					glTranslatef(0, 0, effectsTranslate2);
						glPushAttrib(GL_POLYGON_BIT);
							glFrontFace(GL_CW);
							glPointSize(2.5f);
							gridCam.drawDisplayList(GL_POINTS);
						glPopAttrib();
				glPopMatrix();
			}
	
			
			if	(enableEffects3)
			{
				glPushMatrix();
					glTranslatef(0, 0, effectsTranslate3);
						glPushAttrib(GL_POLYGON_BIT);
							 glFrontFace(GL_CW);
							 glPolygonMode(GL_FRONT, GL_LINE);
							 glPolygonMode(GL_BACK, GL_LINE);
							 gridCam.drawDisplayList(GL_TRIANGLE_STRIP);
						glPopAttrib();
				glPopMatrix();
			}
			
			if	(enableEffects4)
			{
				glPushMatrix();
					glTranslatef(0, 0, effectsTranslate4);
						glPushAttrib(GL_POLYGON_BIT);
								glPointSize(5.f);
								gridCam.drawDisplayList(GL_POINTS);
						glPopAttrib();	
				glPopMatrix();
			}


			glPopMatrix();
		
			fuxShader.end();


		windowCamera.end();
	
	
		if (enableGui == true) {
			ofDisableBlendMode();
		hGui * gui = hGui::getInstance();
		gui->draw();
			ofEnableBlendMode(OF_BLENDMODE_ADD);
		}	
	

	
	
}
コード例 #20
0
ファイル: GPU.cpp プロジェクト: tambry/GBS
// Draws the screen using software renderer to a buffer.
void GBGPU::start_draw()
{
	u8 LCDCtrl = memory->read(LCDC); // Read the LCDC register

	if (get_bit8(LCDCtrl, 7)) // Check whether the display is on or not
	{
		// End the drawing before displaying
		glEnd();

		// Switch the last drawn frame to be shown
		window->swap_buffers();

		// Clear the screen
		glClear(GL_COLOR_BUFFER_BIT);

		// Begin drawing
		glPointSize(scaling);
		glBegin(GL_POINTS);

		bool tile_data_location = get_bit8(LCDCtrl, 6); // Get the location of background and window tile data
		u16 tile_data = 0x8000;

		if (tile_data_location)
		{
			tile_data = 0x8800;
		}

		// Indicate, that VRAM can't be accessed
		u8 status = memory->read(STAT);
		set_bit8(status, 0);
		set_bit8(status, 1);
		memory->write(STAT, status);

		// Unset the pixels
		memset(gfx, 0, sizeof(gfx[0][0]) * 256 * 256);

		if (get_bit8(LCDCtrl, 0)) // Check whether to display the background or not
		{
			bool background_tm_location = get_bit8(LCDCtrl, 3); // Get the location of background tile map
			u16 bg_tm = 0x9800;

			if (background_tm_location)
			{
				bg_tm = 0x9C00;
			}

			// Draw the background
			for (u8 y = 0; y < 32; y++)
			{
				for (u8 x = 0; x < 32; x++)
				{
					u8 bg_map = memory->read(bg_tm + y + x);

					for (u8 y1 = 0; y1 < 8; y1++)
					{
						u8 bgData1 = memory->read(tile_data + (bg_map * 16) + (y1 * 2));
						u8 bgData2 = memory->read(tile_data + (bg_map * 16) + (y1 * 2) + 1);

						for (u8 x1 = 8; x1 > 0; x1--)
						{
							if ((get_bit8(bgData1, x1) != 0) || (get_bit8(bgData2, x1) != 0))
							{
								gfx[(x * 8) + x1][(y * 8) + y1] = true;
							}
						}
					}
				}
			}
		}

		if (get_bit8(LCDCtrl, 1)) // Check whether to display sprites or not
		{
			bool sprite_size = get_bit8(LCDCtrl, 2); // TODO: Support 8x16 sprites

			if (sprite_size)
			{
				log(ERROR, "Unsupported sprite size");
			}

			bool object_tm_location = get_bit8(LCDCtrl, 6); // Get the location of window tile map
			u16 object_tm = 0x9800;

			if (object_tm_location)
			{
				object_tm = 0x9C00;
			}

			// Draw the sprites
			for (u8 s = 0; s < 40; s++)
			{
				//u1 objMap = memory->read(objTileMap + (s * 4));
				u8 x = memory->read(object_tm + (s * 32));
				u8 y = memory->read(object_tm + (s * 32) + 1);
				u8 palette = memory->read(tile_data + (s * 32) + 2);
				u8 flags = memory->read(tile_data + (s * 32) + 3);

				for (u8 y1 = 0; y1 < 8; y1++)
				{
					u8 spriteData1 = memory->read(tile_data + (palette * 16) + (y1 * 2));
					u8 spriteData2 = memory->read(tile_data + (palette * 16) + (y1 * 2) + 1);

					for (u8 x1 = 0; x1 < 8; x1++)
					{
						if ((get_bit8(spriteData1, x1) != 0) || (get_bit8(spriteData2, x1) != 0))
						{
							//gfx[x + x1][y + y1] = true;
						}
					}
				}
			}
		}

		// Indicate the line 0 to be drawn
		memory->write(LY, 0);
	}
}
コード例 #21
0
ファイル: main.cpp プロジェクト: svagionitis/qu3e
	void SetScale( f32 sx, f32 sy, f32 sz ) override
	{
		glPointSize( (float)sx );
		sx_ = sx, sy_ = sy, sz_ = sz;
	}
コード例 #22
0
ファイル: mainc.cpp プロジェクト: kapukiran/kapukiran
static void DrawBox(){
	int i;




	glPushMatrix();
	  glTranslatef(0,-1,-3);
	glPushMatrix();
	
	glRotatef(angle, 0, 1, 0);
	//glColor3f(1, 1, 0);

	Image* img = loadBMP("günes.bmp");
	_textureId = loadTexture(img);
	delete img;

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	
	sphere = gluNewQuadric();
	gluQuadricDrawStyle(sphere, GLU_FILL);
	gluQuadricTexture(sphere, GL_TRUE);
	gluQuadricNormals(sphere, GLU_SMOOTH);
	glBindTexture(GL_TEXTURE_2D, _textureId);

	gluSphere(sphere, 0.5, 20, 20);


	glPopMatrix();
	glPushMatrix();

	glColor3f(0.5,0.5,0.5);
glPointSize(1.0);
glBegin(GL_POINTS); 
for(i = 1; i < 360; i++) {
 float   x = distance * sin(((float)i) * 3.14 / 180);
  float  z = distance * cos(((float)i) * 3.14 / 180);
 glVertex3f(x,0,z); 
}
glEnd();

		glPopMatrix();
	glPushMatrix();

	glTranslatef(distance*(cos(-angle1*PI/180)),0.0,distance*(sin(-angle1*PI/180)));
	glPushMatrix();
	glRotatef(10*angle1, 0, 1, 0);


		Image* img1 = loadBMP("earth.bmp");
	_textureId = loadTexture(img1);
	delete img1;

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	
	sphere = gluNewQuadric();
	gluQuadricDrawStyle(sphere, GLU_FILL);
	gluQuadricTexture(sphere, GL_TRUE);
	gluQuadricNormals(sphere, GLU_SMOOTH);
	glBindTexture(GL_TEXTURE_2D, _textureId);

	gluSphere(sphere, 0.2, 20, 20);




	glPopMatrix();
	glPushMatrix();

		glColor3f(0.5,0.5,0.5);
glPointSize(1.0);
glBegin(GL_POINTS); 
for(i = 1; i < 360; i++) {
 float   x = 0.3 * sin(((float)i) * 3.14 / 180);
  float  z = 0.3 * cos(((float)i) * 3.14 / 180);
 glVertex3f(x,0,z); 
}
glEnd();

		glPopMatrix();


	
	glTranslatef(0.3*(cos(-angle*PI/180)),0.0,0.3*(sin(-angle*PI/180)));
	//glColor3f(0, 1, 0);

	Image* img2 = loadBMP("moon.bmp");
	_textureId = loadTexture(img2);
	delete img2;

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	
	sphere = gluNewQuadric();
	gluQuadricDrawStyle(sphere, GLU_FILL);
	gluQuadricTexture(sphere, GL_TRUE);
	gluQuadricNormals(sphere, GLU_SMOOTH);
	glBindTexture(GL_TEXTURE_2D, _textureId);
	
	glRotatef(30*angle1, 0, 1, 0);
	gluSphere(sphere, 0.05, 20, 20);


   //glutSolidSphere(0.05,20,20);

	glPopMatrix();
	glPushMatrix();

			glColor3f(0.5,0.5,0.5);
glPointSize(1.0);
glBegin(GL_POINTS); 
for(i = 1; i < 360; i++) {
 float   x = 2 * sin(((float)i) * 3.14 / 180);
  float  z = 2 * cos(((float)i) * 3.14 / 180);
 glVertex3f(x,0,z); 
}
glEnd();

   glPopMatrix();

	glTranslatef(2*(cos(angle1*PI/180)),0.0,2*(sin(angle1*PI/180)));
	glPushMatrix();
	glRotatef(angle, 0, 1, 0);
	// glColor3f(1, 0, 0);
	
	 Image* img3 = loadBMP("venus.bmp");
	_textureId = loadTexture(img3);
	delete img3;

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	
	sphere = gluNewQuadric();
	gluQuadricDrawStyle(sphere, GLU_FILL);
	gluQuadricTexture(sphere, GL_TRUE);
	gluQuadricNormals(sphere, GLU_SMOOTH);
	glBindTexture(GL_TEXTURE_2D, _textureId);
	
	glRotatef(30*angle1, 0, 1, 0);
	gluSphere(sphere, 0.05, 20, 20);
	 
	// glutSolidSphere(0.05,20,20);
    

	glPopMatrix();
	glPushMatrix();


	glColor3f(0.5,0.5,0.5);
glPointSize(1.0);
glBegin(GL_POINTS); 
for(i = 1; i < 360; i++) {
 float   x = 0.3 * sin(((float)i) * 3.14 / 180);
  float  z = 0.3 * cos(((float)i) * 3.14 / 180);
 glVertex3f(x,0,z); 
}
glEnd();

   glPopMatrix();
   glPushMatrix();



	glTranslatef(0.3*(cos(-angle*PI/180)),0.0,0.3*(sin(-angle*PI/180)));
	glRotatef(10*angle1, 0, 1, 0);
	// glColor3f(1, 1, 0);
	 Image* img4 = loadBMP("mars.bmp");
	_textureId = loadTexture(img4);
	delete img4;

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	
	sphere = gluNewQuadric();
	gluQuadricDrawStyle(sphere, GLU_FILL);
	gluQuadricTexture(sphere, GL_TRUE);
	gluQuadricNormals(sphere, GLU_SMOOTH);
	glBindTexture(GL_TEXTURE_2D, _textureId);
	
	glRotatef(30*angle1, 0, 1, 0);
	gluSphere(sphere, 0.05, 20, 20);




	
	glPopMatrix();
	glPushMatrix();


	glColor3f(0.5,0.5,0.5);
glPointSize(1.0);
glBegin(GL_POINTS); 
for(i = 1; i < 360; i++) {
 float   x = 0.5 * sin(((float)i) * 3.14 / 180);
  float  z = 0.5 * cos(((float)i) * 3.14 / 180);
 glVertex3f(x,0,z); 
}
glEnd();

   glPopMatrix();

	glTranslatef(0.5*(cos(angle*PI/180)),0.0,0.5*(sin(angle*PI/180)));
	glRotatef(10*angle1, 0, 1, 0);
	 glColor3f(1, 0.9, 0);


	glutSolidSphere(0.03,20,20);
	
	glPopMatrix();


glPopMatrix();

}
コード例 #23
0
void LoadingObject::Draw()
{
    // Enable depth testing if flag is set
    if(_depth)
    {
        glEnable(GL_DEPTH_TEST);
        glAlphaFunc (GL_GREATER, 0.1f);
        glEnable (GL_ALPHA_TEST);
    }
    else
        glDisable(GL_DEPTH_TEST);

    float zoom = _sx/2;
    float width = _sy;
    glLoadIdentity();
    glTranslatef(0.0f, 0.0f, 0.0f);
    glRotatef(_rotX, 1, 0, 0);
    glRotatef(_rotY, 0, 1, 0);
    glRotatef(_rotZ, 0, 0, 1);

    float z = -4;

    glPushMatrix(); //push the matrix so that our translations only affect
    {
        glTranslatef(_x, _y, z); //translate the tile to where it should belong
        glColor4f(_color->r,_color->g,_color->b,_color->a);
        glPointSize(1);
        //glColor3f(0.0,1.0,1.0);

        glBegin(GL_LINES);
        {
            int num_segments = 200;
            for(int r = 10; r < 20; r++)
                for(int ii = 0; ii < num_segments; ii++)
                {
                    bool found = false;
                    if (_counter > 490)
                    {
                        _counter = 0;
                        rot++;
                        if (_open)
                            _smax++;
                        else
                            _smax--;

                        if (_smax == 51)
                            _open = false;
                        else if (_smax == 0)
                            _open = true;
                    }
                    else
                    {
                        _counter++;
                    }
                    for (uint8 splint = 0; splint < _smax; splint++)
                    {
                        if (ii == 00+splint ||
                                ii == 50+splint ||
                                ii == 100+splint ||
                                ii == 150+splint)
                        {
                            found = true;
                            break;
                        }
                    }
                    if (found)
                        continue;


                    float theta = rot *2.0f * 3.1415926f * float(ii) / float(num_segments);  //get the current angle
                    float x = ((float)r/100) * cosf(theta);                             //calculate the x component
                    float y = ((float)r/100) * sinf(theta);                             //calculate the y component
                    glVertex2f(x + _x, y + _y);                                         //output vertex
                }
        }
        glEnd();
    }
    glGetFloatv (GL_MODELVIEW_MATRIX, _matrix);
    glPopMatrix(); //pop the matrix


    /*    glEnable(GL_TEXTURE_2D);
        {
            glEnable(GL_BLEND);
            {
                glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
                glBindTexture(GL_TEXTURE_2D, _texture); //get the texture for the actual quad
                glPushMatrix(); //push the matrix so that our translations only affect
                {
                    glTranslatef(_x, _y, z); //translate the tile to where it should belong
                    glColor4f(_Colr,_Colg,_Colb,_Cola);
                    glBegin(GL_QUADS); //begin drawing our quads
                    {
                        glTexCoord2d(0.0, 1.0);
                        glVertex2d((-1.0) * width, 1.0);

                        glTexCoord2d(1.0, 1.0);
                        glVertex2d((1.0) * width, 1.0);

                        glTexCoord2d(1.0, 0.0);
                        glVertex2d((1.0) * width, 0.9);

                        glTexCoord2d(0.0, 0.0);
                        glVertex2d((-1.0) * width, 0.9);
                    }
                    glEnd();
                }
                glGetFloatv (GL_MODELVIEW_MATRIX, _matrix);
                glPopMatrix(); //pop the matrix

                glPushMatrix(); //push the matrix so that our translations only affect
                {
                    glTranslatef(_x, _y, z);
                    glColor4f(1,1,1,1);
                    glBegin(GL_QUADS); //begin drawing our quads
                    {
                        float width = 3;
                        //TOP
                        glTexCoord2d(0.0, 1.0); glVertex2d(-1.0*width, 1.0);
                        glTexCoord2d(1.0, 1.0); glVertex2d(1.0*width, 1.0);
                        glTexCoord2d(1.0, 0.0); glVertex2d(1.0*width, 0.99);
                        glTexCoord2d(0.0, 0.0); glVertex2d(-1.0*width, 0.99);

                        //Bottom
                        glTexCoord2d(0.0, 1.0); glVertex2d(-1.0*width, 0.89);
                        glTexCoord2d(1.0, 1.0); glVertex2d(1.0*width, 0.89);
                        glTexCoord2d(1.0, 0.0); glVertex2d(1.0*width, 0.88);
                        glTexCoord2d(0.0, 0.0); glVertex2d(-1.0*width, 0.88);

                        //Left
                        glTexCoord2d(0.0, 1.0); glVertex2d(-1.0*width, 0.99);
                        glTexCoord2d(1.0, 1.0); glVertex2d(-0.99*width, 0.99);
                        glTexCoord2d(1.0, 0.0); glVertex2d(-0.99*width, 0.88);
                        glTexCoord2d(0.0, 0.0); glVertex2d(-1.0*width, 0.88);

                        //Right
                        glTexCoord2d(0.0, 1.0); glVertex2d(1.0*width, 0.99);
                        glTexCoord2d(1.0, 1.0); glVertex2d(0.99*width, 0.99);
                        glTexCoord2d(1.0, 0.0); glVertex2d(0.99*width, 0.88);
                        glTexCoord2d(0.0, 0.0); glVertex2d(1.0*width, 0.88);
                    }
                    glEnd();
                }
                glPopMatrix(); //pop the matrix
            }
            glDisable(GL_BLEND);
        }
        glDisable(GL_TEXTURE_2D);*/

    if(_depth)
    {
        glDisable (GL_ALPHA_TEST) ;
        glDisable(GL_DEPTH_TEST);
    }
}
コード例 #24
0
void RamachandranPlot::draw(void)
{
    ProteinState *state = curProtein();
    if ( !state ) return;
	 
	 GLText text;
    if(!valid())
    {
        /* Set the viewport: */
        glViewport(0,0,w(),h());
        
        /* Set the projection and modelview matrices: */
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        float factor=1.0/Math::Constants<double>::pi;
        glScale(factor,factor,factor);
        glDisable(GL_DEPTH_TEST);
    }
    
    /* Clear window: */
    glClearColor(backgroundColor);
    glClear(GL_COLOR_BUFFER_BIT);
    
    /* Draw ramachandran texture background: */
    glEnable(GL_TEXTURE_2D);
    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);
    glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE);
    glPixelStorei(GL_UNPACK_ALIGNMENT,1);
    glPixelStorei(GL_UNPACK_SKIP_PIXELS,0);
    glPixelStorei(GL_UNPACK_ROW_LENGTH,0);
    glPixelStorei(GL_UNPACK_SKIP_ROWS,0);
    glPixelStorei(GL_UNPACK_IMAGE_HEIGHT,0);
    glPixelStorei(GL_UNPACK_SKIP_IMAGES,0);
    glTexImage2D(GL_TEXTURE_2D,0,GL_RGB8,ramachandranTextureHeight,ramachandranTextureWidth,0,GL_RGB,GL_UNSIGNED_BYTE,ramachandranTexture);
    glColor3f(1.0f,0.0f,1.0f);
    glBegin(GL_QUADS);
    glTexCoord2f(0.0f,0.0f);
    glVertex2f(-Math::Constants<float>::pi,-Math::Constants<float>::pi);
    glTexCoord2f(1.0f,0.0f);
    glVertex2f(Math::Constants<float>::pi,-Math::Constants<float>::pi);
    glTexCoord2f(1.0f,1.0f);
    glVertex2f(Math::Constants<float>::pi,Math::Constants<float>::pi);
    glTexCoord2f(0.0f,1.0f);
    glVertex2f(-Math::Constants<float>::pi,Math::Constants<float>::pi);
    glEnd();
    glDisable(GL_TEXTURE_2D);
    
    /* Draw coordinate axes: */
    glColor3f(1.0f-backgroundColor[0],1.0f-backgroundColor[1],1.0f-backgroundColor[2]);
    glBegin(GL_LINES);
    glVertex2f(0.0f,-4.0f);
    glVertex2f(0.0f,4.0f);
    glVertex2f(-4.0f,0.0f);
    glVertex2f(4.0f,0.0f);
    glEnd();

	/* Draw axes data range */
	text.setFontColor(0.0, 0.0, 0.0);
	/* h, v */
	/*	+  */
	/*-   +*/
	/*	-  */	
	text.drawFreeString("pi",2.3f,-2.7f);
	text.drawFreeString("-pi",-2.8f,-2.7f);
	text.drawFreeString("pi",-3.0f,2.6f);
	text.drawFreeString("0",-3.0f,-0.3f);
	text.drawFreeString("0",-0.3f,-2.7f);
	text.drawFreeString("Phi",0.15f,2.5f);
	text.drawFreeString("Psi",2.5f,0.15f);

	/* Draw axes label */
	text.setFontScale(0.003, 0.003);
	text.setFontColor(0.0, 0.0, 1.0);
    
    if(structureValid)
    {
        /* Visualize dihedral angles inside a selected structure: */
        glPointSize(3.0f);
        glBegin(GL_POINTS);
        glColor(selectedStructureColor);
        for(int i=0;i<numStructureResidues;++i)
            glVertex(structurePhis[i],structurePsis[i]);
        glEnd();
    }
    
    /* Visualize dihedral angles inside all active coil regions: */
    if(activeCoilsValid)
    {
        /* Visualize dihedral angles inside all active coil regions: */
        glPointSize(3.0f);
        glBegin(GL_POINTS);
        glColor(activeCoilRegionColor);
        for(int i=0;i<numActiveCoilsResidues;++i)
            glVertex(activeCoilsPhis[i],activeCoilsPsis[i]);
        glEnd();
    }

	if ( state->selectedResidue != 0 )
	{
    	/* Highlight dihedral angles of selected residue: */
		glEnable(GL_BLEND);
		glEnable(GL_POINT_SMOOTH);
        glPointSize(6.0f);
		glBegin(GL_POINTS);
        
		if(boundary)
			glColor3f(0.0f, 0.0f, 5.0f);
		else
			glColor3f(1.0f, 1.0f, 1.0f);
			//printf("draw phi %f psi %f\n", oldPhiAngle,oldPsiAngle);
			glVertex2f(oldPhiAngle,oldPsiAngle);
        
		glEnd();
		}
}
コード例 #25
0
ファイル: ar-notes.cpp プロジェクト: NightFury13/BriteCam
// main function to draw 3D overlays
void drawResults()
{
		tracker->getTrackingData(&data);
		
		glMatrixMode(GL_MODELVIEW);
		glPushMatrix();
		glMatrixMode(GL_PROJECTION);
		glPushMatrix();

		//set image specs
		glViewport(0,0,data.frame->width,data.frame->height);
		//enable stuff
		glShadeModel(GL_FLAT);
		//set camera
		setGlView(data.frame->width,data.frame->height,data.cameraFocus);
		//rotate and translate into the current coordinate system of the head
		glMatrixMode(GL_MODELVIEW);
		float *r = data.faceRotation;
		float *t = data.faceTranslation;
		glTranslatef(-t[0],t[1],-t[2]); //because x and z axes in OpenGL are opposite from the ones used by visage|SDK - see FaceData::faceTranslation
		glRotatef(r[1]*180.0f/3.1415926f, 0.0f, 1.0f, 0.0f);
		glRotatef(r[0]*180.0/3.1415926f, 1.0f, 0.0f, 0.0f);
		glRotatef(r[2]*180.0/3.1415926f, 0.0f, 0.0f, 1.0f);

		//NOW WE ARE IN THE 3D COORDINATE SYSTEM OF THE HEAD AND WE CAN DRAW WHAT WE WANT

		glPointSize(3);

		//draw nose
		glColor3ub(255,255,32);
		glBegin(GL_POINTS);
		for(int j = 0; j < 15; j++)
		{
			drawPoint3D(9,j+1);
		}
		glEnd();
		glBegin(GL_LINE_LOOP);
		drawPoint3D(9,15);
		drawPoint3D(9,4);
		drawPoint3D(9,2);
		drawPoint3D(9,3);
		drawPoint3D(9,1);
		drawPoint3D(9,5);
		glEnd();
		glBegin(GL_LINE_LOOP);
		drawPoint3D(9,6);
		drawPoint3D(9,7);
		drawPoint3D(9,13);
		drawPoint3D(9,12);
		drawPoint3D(9,14);
		glEnd();
		glBegin(GL_LINES);
		drawPoint3D(9,14);
		drawPoint3D(9,2);
		drawPoint3D(9,13);
		drawPoint3D(9,1);
		glEnd();

		//draw eyes
		glBegin(GL_POINTS);
		for(int j = 6; j < 14; j++)
		{
			drawPoint3D(3,j+1);
		}
		glEnd();
		glBegin(GL_LINE_LOOP);
		drawPoint3D(3,12);
		drawPoint3D(3,14);
		drawPoint3D(3,8);
		drawPoint3D(3,10);
		glEnd();
		glBegin(GL_LINE_LOOP);
		drawPoint3D(3,11);
		drawPoint3D(3,13);
		drawPoint3D(3,7);
		drawPoint3D(3,9);
		glEnd();

		//draw cheeks
		glBegin(GL_POINTS);
		for(int j = 0; j < 4; j++)
		{
			drawPoint3D(5,j+1);
		}
		glEnd();
		glBegin(GL_LINES);
		drawPoint3D(5,2);
		drawPoint3D(5,4);
		drawPoint3D(5,1);
		drawPoint3D(5,3);
		glEnd();

		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glMatrixMode(GL_MODELVIEW);
		glPopMatrix();
}
コード例 #26
0
void Ship::renderBrick(Brick* brick, Brick* base, GLuint colorLocation, int tick)
{
	brick->tick = tick;

	for (int j = 0; j < brick->numConnections; ++j)
	{

		Connection* connection = brick->connections + j;
		//for (int axis = Z; false; ++axis)
		{
			int axis = m_minAxis;


			for (int i = 0; i < 2; ++i)
			{
				Joint* joint = connection->joints[axis] + i;

				if (joint->flow != 0)
				{
					glLineWidth(10.0f * joint->flow);
					glBegin(GL_LINES);
					glVertex3f(brick->pos[0], brick->pos[1], brick->pos[2]);
					glVertex3f(connection->other->pos[0], connection->other->pos[1], connection->other->pos[2]);
					glEnd();
					glLineWidth(1);
				}


				//glLineWidth(connection->joint->capacity * 10.0f);
				//glBegin(GL_LINES);
				//glVertex3f(0.5f * (brick->pos[0] + connection->other->pos[0]), 0.5f*(brick->pos[1] + connection->other->pos[1]), 0.5f * (brick->pos[2] + connection->other->pos[2]));
				//glVertex3f(0.5f * (brick->pos[0] + connection->other->pos[0]), brick->pos[1] , 0.5f * (brick->pos[2] + connection->other->pos[2]));
				//glEnd();
				//glLineWidth(1);

				for (int i = 0; i < brick->numBlocking; ++i)
				{
					glBegin(GL_LINES);
					glVertex3f(brick->pos[0], brick->pos[1], brick->pos[2]);
					glVertex3f((*brick->blocking[i])->connection->brick->pos[0], (*brick->blocking[i])->connection->brick->pos[1], (*brick->blocking[i])->connection->brick->pos[2]);
					glEnd();
				}

				if (joint->capacity > 0)
				{
					glLineWidth(joint->capacity * 5.0f);
					glBegin(GL_LINES);
					if (axis == X)
					{
						int min = ong_MIN(brick->pos[2], joint->connection->other->pos[2]) - 1 + abs(brick->pos[2] - joint->connection->other->pos[2]);
						int max = ong_MAX(brick->pos[2], joint->connection->other->pos[2]) + 1 - abs(brick->pos[2] - joint->connection->other->pos[2]);

						glVertex3f(joint->data->fulcrum, joint->data->y, min);
						glVertex3f(joint->data->fulcrum, joint->data->y, max);
					}
					else if (axis == Z)
					{
						int min = ong_MIN(brick->pos[0], joint->connection->other->pos[0]) - 2 + abs(brick->pos[0] - joint->connection->other->pos[0]);
						int max = ong_MAX(brick->pos[0], joint->connection->other->pos[0]) + 2 - abs(brick->pos[0] - joint->connection->other->pos[0]);

						glVertex3f(min, joint->data->y, joint->data->fulcrum);
						glVertex3f(max, joint->data->y, joint->data->fulcrum);
					}
					glEnd();
					glLineWidth(1);
				}

			}
		}
		if (connection->other->tick != tick)
			renderBrick(connection->other, base, colorLocation, tick);
	}

	if (brick == base)
	{
		glUniform3f(colorLocation, 1, 0, 1);
		glPointSize(10.0f);
		glBegin(GL_POINTS);
		glVertex3f(brick->pos[0], brick->pos[1], brick->pos[2]);
		glEnd();
		glPointSize(1.0f);
		glUniform3f(colorLocation, 0, 1, 1);
	}

}
コード例 #27
0
ファイル: cal.c プロジェクト: alberich/Eternal-Lands
void cal_render_bones(actor *act)
{
	float lines[1024][2][3];
	float points[1024][3];
	int nrLines;
	int nrPoints;
	int currLine;
	int currPoint;
	struct CalSkeleton *skel;

	skel=CalModel_GetSkeleton(act->calmodel);
	nrLines = CalSkeleton_GetBoneLines(skel,&lines[0][0][0]);

	glLineWidth(2.0f);
	glColor3f(1.0f, 1.0f, 1.0f);

	glLineStipple(1, 0x3030);
	glEnable(GL_LINE_STIPPLE);
	glBegin(GL_LINES);

	for(currLine = 0; currLine < nrLines; currLine++) {
    		glVertex3f(lines[currLine][0][0], lines[currLine][0][1], lines[currLine][0][2]);
    		glVertex3f(lines[currLine][1][0], lines[currLine][1][1], lines[currLine][1][2]);
	}

	glEnd();
	glDisable(GL_LINE_STIPPLE);

  	// draw the bone points
  	nrPoints = CalSkeleton_GetBonePoints(skel,&points[0][0]);

	glPointSize(4.0f);
	glColor3f(0.0f, 1.0f, 1.0f);
	glBegin(GL_POINTS);
	for(currPoint = 0; currPoint < nrPoints; currPoint++) {
		glVertex3f(points[currPoint][0], points[currPoint][1], points[currPoint][2]);
	}
	glEnd();

#ifdef DEBUG
	// draw the bones orientation
	if (render_bones_orientation) {
		float shift[3], pos[3];
		
		glLineWidth(3.0f);
		glBegin(GL_LINES);
		for (currPoint = nrPoints; currPoint--;) {
			shift[0] = 0.1; shift[1] = 0.0; shift[2] = 0.0;
			cal_get_actor_bone_local_position(act, currPoint, shift, pos);
			glColor3f(1.0, 0.0, 0.0);
			glVertex3f(points[currPoint][0], points[currPoint][1], points[currPoint][2]);
			glVertex3fv(pos);
			
			shift[0] = 0.0; shift[1] = 0.1; shift[2] = 0.0;
			cal_get_actor_bone_local_position(act, currPoint, shift, pos);
			glColor3f(0.0, 1.0, 0.0);
			glVertex3f(points[currPoint][0], points[currPoint][1], points[currPoint][2]);
			glVertex3fv(pos);
			
			shift[0] = 0.0; shift[1] = 0.0; shift[2] = 0.1;
			cal_get_actor_bone_local_position(act, currPoint, shift, pos);
			glColor3f(0.0, 0.0, 1.0);
			glVertex3f(points[currPoint][0], points[currPoint][1], points[currPoint][2]);
			glVertex3fv(pos);
		}
		glEnd();
	}

	// draw bones id
	if (render_bones_id) {
		GLdouble model[16], proj[16];
		GLint view[4];
		GLdouble px,py,pz;
		unsigned char buf[16];
		float font_size_x = SMALL_INGAME_FONT_X_LEN/ALT_INGAME_FONT_X_LEN;
		float font_size_y = SMALL_INGAME_FONT_Y_LEN/ALT_INGAME_FONT_X_LEN;

		glGetDoublev(GL_MODELVIEW_MATRIX, model);
		glGetDoublev(GL_PROJECTION_MATRIX, proj);
		glGetIntegerv(GL_VIEWPORT, view);
		
		glPushMatrix();
		glLoadIdentity();
		glMatrixMode(GL_PROJECTION);
		glPushMatrix();
		glLoadIdentity();
		
		glOrtho(view[0],view[2]+view[0],view[1],view[3]+view[1],0.0f,-1.0f);
		
		glPushAttrib(GL_ENABLE_BIT);
		
		glEnable(GL_TEXTURE_2D);
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
		
		glColor4f(1.0, 0.0, 1.0, 1.0);
		
		for (currPoint = nrPoints; currPoint--;) {
			struct CalBone *bone;
			bone = CalSkeleton_GetBone(skel, currPoint);
			
			sprintf((char*)buf, "%d", currPoint);
			gluProject(points[currPoint][0], points[currPoint][1], points[currPoint][2], model, proj, view, &px, &py, &pz);
			draw_ortho_ingame_string(px, py, pz, buf, 1, font_size_x, font_size_y);
		}
		
		glPopAttrib();
		
		glMatrixMode(GL_PROJECTION);
		glPopMatrix();
		glMatrixMode(GL_MODELVIEW);
		glPopMatrix();
	}
#endif // DEBUG

	glLineWidth(1.0f);

#ifdef OPENGL_TRACE
CHECK_GL_ERRORS();
#endif //OPENGL_TRACE

}
コード例 #28
0
ファイル: MeshPainter.cpp プロジェクト: Britefury/gsculpt
void MeshPainter::drawVertices(MMesh *mesh, bool overlay, bool reflection)
{
	const Array<MVertex*> &vertices = mesh->getVertices();

	if ( vertices.size() > 0 )
	{
		int first = 0;
		int last = vertices.size() - 1;


		if ( reflection )
		{
			glPointSize( getReflectedVertexPointSize() );

			Colour3f vertexColour = getReflectedVertexColour();
			if ( overlay )
			{
				computeOverlayColour( vertexColour );
			}
			glColor3( vertexColour );


			glBegin( GL_POINTS );
			for (int i = first; i <= last; i++)
			{
				glVertex3( vertices[i]->getPosition() );
			}
			glEnd();
		}
		else
		{
			double unmarkedPointSize = getUnmarkedVertexPointSize();
			double markedPointSize = getMarkedVertexPointSize();
			Colour3f unmarkedColour = getUnmarkedVertexColour();
			Colour3f markedColour = getMarkedVertexColour();


			if ( overlay )
			{
				computeOverlayColour( unmarkedColour );
				computeOverlayColour( markedColour );
			}


			if ( unmarkedPointSize == markedPointSize )
			{
				// Marked and unmarked vertex point sizes are the same; render each vertex, changing colour as necessary
				bool marked = graphicsOverrideMarkState( vertices[first]->isVertexMarked() );

				glPointSize( unmarkedPointSize );
				if ( marked )
				{
					glColor3( markedColour );
				}
				else
				{
					glColor3( unmarkedColour );
				}

				glBegin( GL_POINTS );
				for (int i = first; i <= last; i++)
				{
					bool thisMarked = graphicsOverrideMarkState( vertices[i]->isVertexMarked() );
					if ( thisMarked != marked )
					{
						if ( thisMarked )
						{
							glColor3( markedColour );
						}
						else
						{
							glColor3( unmarkedColour );
						}
						marked = thisMarked;
					}

					glVertex3( vertices[i]->getPosition() );
				}
				glEnd();
			}
			else
			{
				// Marked and unmarked vertex point sizes are different; render unmarked, then marked
				glColor3( unmarkedColour );
				glPointSize( unmarkedPointSize );
				glBegin( GL_POINTS );
				for (int i = first; i <= last; i++)
				{
					if ( !graphicsOverrideMarkState( vertices[i]->isVertexMarked() ) )
					{
						glVertex3( vertices[i]->getPosition() );
					}
				}
				glEnd();

				glColor3( markedColour );
				glPointSize( markedPointSize );
				glBegin( GL_POINTS );
				for (int i = first; i <= last; i++)
				{
					if ( graphicsOverrideMarkState( vertices[i]->isVertexMarked() ) )
					{
						glVertex3( vertices[i]->getPosition() );
					}
				}
				glEnd();
			}
		}

#ifdef DEBUG_PRINT_MESH_POINTERS
		if ( !reflection  &&  !overlay )
		{
			const Colour3f &unmarkedColour = getUnmarkedVertexColour();
			glColor3( unmarkedColour );
			for (int i = first; i <= last; i++)
			{
				Point3 pos = vertices[i]->getPosition();
				std::ostringstream stream;
				stream << vertices[i] << (char)0x00;
				glDrawString3( pos, stream.str().c_str() );
			}
		}
#endif
	}

	glPointSize( 1.0 );
}
コード例 #29
0
ファイル: stategl.c プロジェクト: hsanjuan/sar2
/*
 *	Resets all states (supported in the state_gl_struct)
 *	for the current OpenGL context to be disabled.
 *
 *	If s is NULL then no operation will be performed.
 */
void StateGLResetAll(state_gl_struct *s)
{
#if 0
	if(s == NULL)
	    return;
#endif

	/* Reset states */
	s->alpha_test = False;
	glDisable(GL_ALPHA_TEST);

	s->blend = False;
	glDisable(GL_BLEND);

	s->color_material = False;
	glDisable(GL_COLOR_MATERIAL);

	s->cull_face = False;
	glDisable(GL_CULL_FACE);

	s->depth_test = False;
	glDisable(GL_DEPTH_TEST);

	s->dither = False;
	glDisable(GL_DITHER);

	s->fog = False;
	glDisable(GL_FOG);

	s->lighting = False;
	glDisable(GL_LIGHTING);

	s->light0 = False;
	glDisable(GL_LIGHT0);

	s->light1 = False;
	glDisable(GL_LIGHT1);

	s->light2 = False;
	glDisable(GL_LIGHT2);

	s->light3 = False;
	glDisable(GL_LIGHT3);

	s->light4 = False;
	glDisable(GL_LIGHT4);

	s->light5 = False;
	glDisable(GL_LIGHT5);

	s->light6 = False;
	glDisable(GL_LIGHT6);

	s->light7 = False;
	glDisable(GL_LIGHT7);

	s->line_smooth = False;
	glDisable(GL_LINE_SMOOTH);

	s->point_smooth = False;
	glDisable(GL_POINT_SMOOTH);

	s->polygon_offset_fill = False;
	glDisable(GL_POLYGON_OFFSET_FILL);

	s->polygon_offset_line = False;
	glDisable(GL_POLYGON_OFFSET_LINE);

	s->polygon_offset_point = False;
	glDisable(GL_POLYGON_OFFSET_POINT);

	s->scissor_test = False;
	glDisable(GL_SCISSOR_TEST);

	s->stencil_test = False;
	glDisable(GL_STENCIL_TEST);

	s->texture_1d = False;
	glDisable(GL_TEXTURE_1D);

	s->texture_2d = False;
	glDisable(GL_TEXTURE_2D);

	s->texture_3d = False;
	glDisable(GL_TEXTURE_2D);


	/* Functions and paramters. */
	s->alpha_func_func = GL_ALWAYS;
	s->alpha_func_ref = 0.0f;
	glAlphaFunc(GL_ALWAYS, 0.0f);

	s->blend_func_sfactor = GL_ONE;
	s->blend_func_dfactor = GL_ZERO;
	glBlendFunc(GL_ONE, GL_ZERO);

	s->color_material_face = GL_FRONT_AND_BACK;
	s->color_material_mode = GL_AMBIENT_AND_DIFFUSE;
	glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);

	s->depth_func_func = GL_LESS;
	glDepthFunc(GL_LESS);

	s->front_face_mode = GL_CCW;
	glFrontFace(GL_CCW);

	s->depth_mask_flag = GL_TRUE;
	glDepthMask(GL_TRUE);

	s->line_width = 1.0f;
	glLineWidth(1.0f);

	s->point_size = 1.0f;
	glPointSize(1.0f);

	s->polygon_offset_factor = 0.0f;
	s->polygon_offset_units = 0.0f;
	glPolygonOffset(0.0f, 0.0f);

	s->scissor_test_x = 0;
	s->scissor_test_y = 0;
	s->scissor_test_width = 0;
	s->scissor_test_height = 0;
	glScissor(0, 0, 0, 0);

	s->shade_model_mode = GL_SMOOTH;
	glShadeModel(GL_SMOOTH);

	s->stencil_func_func = GL_ALWAYS;
	s->stencil_func_ref = 0;
	s->stencil_func_mask = 0xffffffff;
	glStencilFunc(GL_ALWAYS, 0, 0xffffffff);

	s->stencil_op_fail = GL_KEEP;
	s->stencil_op_zfail = GL_KEEP;
	s->stencil_op_zpass = GL_KEEP;
	glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

	s->tex_env_target = GL_TEXTURE_ENV;
	s->tex_env_pname = GL_TEXTURE_ENV_MODE;
	s->tex_env_param = GL_MODULATE;
	glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

}
コード例 #30
0
ファイル: main.cpp プロジェクト: saumiko/GraphicsLabCodes
void mydisplay()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glPointSize(5.0f);
    double xf,yf,xf2,yf2;
    
    //rounding
    xf = rint(x);
    xf2 = rint(x2);
    yf = rint(y);
    yf2 = rint(y2);
    
    //swapping if necessary
    if (xf2 < xf)
    {
        double temp = xf2;
        xf2 = xf;
        xf = temp;
        temp = yf2;
        yf2 = yf;
        yf = temp;
    }
    
    //if horizontal line
    if (yf2 - yf == 0)
    {
        double i;
        glBegin(GL_POINTS);
        for(i = xf; i <= xf2; ++i)
        {
            glVertex2f(i/100, yf/100);
        }
        glEnd();
        glFlush();
    }
    
    //if vertical line
    else if (xf2 - xf == 0)
    {
        double i;
        glBegin(GL_POINTS);
        for(i = yf; i <= yf2; ++i)
        {
            glVertex2f(xf/100, i/100);
        }
        glEnd();
        glFlush();
    }
    
    //if others
    else
    {
        //calculating m of y = mx + b
        double m;
        m = (yf2-yf)/(xf2-xf);
        
        //if diagonal line
        if (fabs(m) == 1.0)
        {
            double i,j;
            glBegin(GL_POINTS);
            
            //if yf < yf2
            if (yf < yf2)
            {
                for(i = xf,j = yf; i <= xf2; ++i,++j)
                {
                    glVertex2f(i/100, j/100);
                }
                glEnd();
                glFlush();
            }
            else
            {
                for(i = xf,j = yf; i <= xf2; ++i,--j)
                {
                    glVertex2f(i/100, j/100);
                }
                glEnd();
                glFlush();
            }
            
        }
        
        //if others
        else
        {
            //if slope is small
            if (fabs(m) < 1)
            {
                glBegin(GL_POINTS);
                glVertex2f(xf/100, yf/100);
                double yi,i;
                for (i = xf+1; i <= xf2 ; ++i){
                    yi = yf + m;
                    yf = yi;
                    yi = rint(yi);
                    glVertex2f(i/100, yi/100);
                }
                glEnd();
                glFlush();
            }
            
            // if slop is large
            else
            {
                double i,xi;
                glBegin(GL_POINTS);
                
                //if yf < yf2
                if (yf < yf2)
                {
                    glBegin(GL_POINTS);
                    glVertex2f(xf/100, yf/100);
                    double xi,i;
                    m = 1/m;
                    for (i = yf+1; i <= yf2 ; ++i){
                        xi = xf + m;
                        xf = xi;
                        xi = rint(xi);
                        glVertex2f(xi/100, i/100);
                    }
                    glEnd();
                    glFlush();
                }
                else
                {
                    glBegin(GL_POINTS);
                    glVertex2f(xf2/100, yf2/100);
                    double xi,i;
                    m = 1/m;
                    for (i = yf2+1; i <= yf ; ++i){
                        xi = xf2 + m;
                        xf2 = xi;
                        xi = rint(xi);
                        glVertex2f(xi/100, i/100);
                    }
                    glEnd();
                    glFlush();
                }
                
            }
        }
    }
    
}