Also Like

📁 last Posts

glBegin(GL_LINES)


glBegin(GL_LINES) in OpenGL

Definition:

glBegin(GL_LINES) is a function in OpenGL Legacy API that begins defining lines in immediate mode rendering.

Syntax:

void glBegin(GLenum mode);
  • mode: Type of primitives to draw
  • GL_LINES: Draws disconnected lines

How it Works:

1. Start Definition:

glBegin(GL_LINES);

2. Specify Vertices:

glVertex3f(x1, y1, z1);  // Start point of first line
glVertex3f(x2, y2, z2);  // End point of first line

glVertex3f(x3, y3, z3);  // Start point of second line
glVertex3f(x4, y4, z4);  // End point of second line

3. End Definition:

glEnd();

Complete Example:

#include <GL/glut.h>

void display() {
    glClear(GL_COLOR_BUFFER_BIT);

    glColor3f(1.0, 0.0, 0.0);  // Red color

    glBegin(GL_LINES);
        // Horizontal line
        glVertex2f(-0.8, 0.0);
        glVertex2f(0.8, 0.0);

        // Vertical line
        glVertex2f(0.0, -0.8);
        glVertex2f(0.0, 0.8);

        // Diagonal line
        glVertex2f(-0.5, -0.5);
        glVertex2f(0.5, 0.5);
    glEnd();

    glFlush();
}

GL_LINES Patterns:

GL_LINES (Disconnected Lines):

  • Every pair of glVertex calls forms one line
  • 2 vertices = 1 lines

GL_LINE_STRIP (Connected Lines):

glBegin(GL_LINE_STRIP);
    glVertex2f(0, 0);    // ───
    glVertex2f(1, 1);    //   │
    glVertex2f(2, 0);    //   └──
glEnd();
  • Each vertex connects to the previous one

GL_LINE_LOOP (Closed Line Loop):

glBegin(GL_LINE_LOOP);
    glVertex2f(0, 0);    // Square
    glVertex2f(1, 0);
    glVertex2f(1, 1);
    glVertex2f(0, 1);
    // Last connects back to first
glEnd();

Line Properties:

Line Width:

glLineWidth(3.0);  // Line width = 3 pixels
glBegin(GL_LINES);
// vertices...
glEnd();

Color:

glColor3f(1.0, 0.0, 0.0);  // RGB: Red

Vertex Types:

  • glVertex2f(x, y): 2D coordinates
  • glVertex3f(x, y, z): 3D coordinates
  • glVertex3d(x, y, z): Double precision
Comments