A very basic issue with draw line

Hi All,
Sorry if my question is very basic, I am struggling to draw a line using glfw3 on Ubuntu. Here is my code … It does nothing I only see a black screen.

#include <GLFW/glfw3.h>
#include <iostream>
void render_loop()
{
    glClearColor ( 1.0f, 1.0f, 1.0f, 1.0f );
    glClear (GL_COLOR_BUFFER_BIT);
    glPointSize(10);
	glLineWidth(2.5); 
	glColor3f(1.0, 0.0, 0.0);
    glBegin(GL_LINES);
    glVertex3f(10.0,10.0,0.0);
	glVertex3f(20.0,20.0,0.0);
    glEnd();

   std::cout<<"leaving loop \n";

}
int main ( int argc, char* argv[] )
{

 // Init GLFW
    glfwInit();
    // Set all the required options for GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);


	GLFWwindow* window = glfwCreateWindow(400, 400, "LearnOpenGL", nullptr, nullptr);  
   

    do {
         render_loop();
		 glfwSwapBuffers(window);
    } while (true);

    glfwTerminate();
}

You are asking for core context opengl 3.3, but then use legacy opengl functions, and the line you are drawing is off screen because the projection matrix has not been set up for your coordinates.

I have a simple example for you (this is a C program, but you should be able to understand what you need to change):

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <GLFW/glfw3.h>
#include <gl/GL.h>


void render_loop()
{
	glClearColor ( 1.0f, 1.0f, 1.0f, 1.0f );
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glPointSize(10);
	glLineWidth(2.5); 
	glColor3f(1.0, 0.0, 0.0);
	glBegin(GL_LINES);
	glVertex3f(10.0,10.0,0.0);
	glVertex3f(200.0,200.0,0.0);
	glEnd();
}

/* program entry */
int main(int argc, char *argv[])
{
	GLFWwindow* window;

	if( !glfwInit() )
	{
		fprintf( stderr, "Failed to initialize GLFW\n" );
		exit( EXIT_FAILURE );
	}

	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
	window = glfwCreateWindow( 400, 400, "LearnOpenGL", NULL, NULL );
	if (!window)
	{
		fprintf( stderr, "Failed to open GLFW window\n" );
		glfwTerminate();
		exit( EXIT_FAILURE );
	}


	glfwMakeContextCurrent(window);
	glfwSwapInterval( 1 );

	// set up view
	glViewport( 0, 0, 400, 400 );
	glMatrixMode( GL_PROJECTION );
	glLoadIdentity();

	// see https://www.opengl.org/sdk/docs/man2/xhtml/glOrtho.xml
	glOrtho(0.0,400.0,0.0,400.0,0.0,1.0); // this creates a canvas you can do 2D drawing on


	// Main loop
	while( !glfwWindowShouldClose(window) )
	{
		// Draw gears
		render_loop();

		// Swap buffers
		glfwSwapBuffers(window);
		glfwPollEvents();
	}

	// Terminate GLFW
	glfwTerminate();

	// Exit program
	exit( EXIT_SUCCESS );
}
3 Likes

Thank you very much for helping me, you made my day :slight_smile: Thanks again…

1 Like

awesome~!!!! I am looking for this whole night… Thanks