Search code examples
c++xcodemacosopenglglut

Only black window drawing Triangle, using openGL and GLUT with Xcode on MacOS


Nothing shows up on my window only black solid color, the build proceeded, but nothing else happening..

Also I tried the same code on Windows, still nothing.

Here is my code:

#define _USE_MATH_DEFINES
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <vector>

#if defined(__APPLE__)
#include <GLUT/GLUT.h>
#include <OpenGL/gl3.h>
#include <OpenGL/glu.h>
#else
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__)
#include <windows.h>
#endif
#include <GL/glew.h>        // must be downloaded
#include <GL/freeglut.h>    // must be downloaded unless you have an Apple
#endif

using namespace std;

void changeViewPort(int w, int h)
{
    glViewport(0, 0, w, h);
}

void render()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glBegin(GL_TRIANGLES);
    glVertex2f(0.5, 0.5);
    glVertex2f(-0.5, -0.5);
    glVertex2f(1.5, 1.5);
    glEnd();
    glutSwapBuffers();
}

int main(int argc, char* argv[]) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
    glutInitWindowSize(800, 600);
    glutCreateWindow("Hello, GL");
    glutReshapeFunc(changeViewPort);
    glutDisplayFunc(render);
    glMatrixMode(GL_PROJECTION);
    gluOrtho2D(0,400,0,500);
    glutMainLoop();
    return 0;
}

Solution

  • That's a zero-area triangle, all the vertices are in a line. You can double-check by using GL_LINE_LOOP instead of GL_TRIANGLES or using glPolygonMode(GL_FRONT_AND_BACK, GL_LINE).

    Zero-area triangles generally don't generate any fragments during rasterization. No fragments, nothing drawn.

    Fixes:

    All together:

    #include <GL/glut.h>
    
    void render()
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glBegin(GL_TRIANGLES);
        glVertex2f( -0.5, -0.5 );
        glVertex2f(  0.5, -0.5 );
        glVertex2f(  0.0,  0.5 );
        glEnd();
        glutSwapBuffers();
    }
    
    int main(int argc, char* argv[])
    {
        glutInit(&argc, argv);
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
        glutInitWindowSize(800, 600);
        glutCreateWindow("Hello, GL");
        glutDisplayFunc(render);
        glutMainLoop();
        return 0;
    }