Рисование букв с использованием треугольников в OpenGL? - PullRequest
0 голосов
/ 06 сентября 2018

Я должен нарисовать свое имя, используя треугольники. Я понимаю, как обращаться с шейдерами. Я просто запутался в том, как на самом деле нарисовать объекты и соединить их, чтобы сделать письмо.

Мне дали код для работы:

#include "Angel.h"

const int NumPoints = 50000;


/*This function initializes an array of 3d vectors 
   and sends it to the graphics card along with shaders
   properly connected to them.*/

void
init( void )
{
    vec3 points[NumPoints];

    // Specifiy the vertices for a triangle
    vec3 vertices[] = {
        vec3( -1.0, -1.0, 0.0 ),
        vec3(  0.0,  1.0, 0.0 ),
        vec3(  1.0, -1.0, 0.0 )
    };

    // Select an arbitrary initial point inside of the triangle
    points[0] = vec3( 0.0, 1.0, 0.0 );

    // compute and store NumPoints - 1 new points
    for ( int i = 1; i < NumPoints; ++i ) {
        int j = rand() % 3;   // pick a vertex from the triangle at random

        // Compute the point halfway between the selected vertex
        //   and the previous point
        points[i] = ( points[i - 1] + vertices[j] ) / 2.0;
    }

    // Create a vertex array object
    GLuint vao;  //just an integer recognized by graphics card
    glGenVertexArrays( 1, &vao ); //generate 1 buffer
    glBindVertexArray( vao ); //become array buffer

    // Create and initialize a buffer object //sends it to graphics card
    GLuint buffer;
    glGenBuffers( 1, &buffer );
    glBindBuffer( GL_ARRAY_BUFFER, buffer );
    glBufferData( GL_ARRAY_BUFFER, sizeof(points), points, GL_STATIC_DRAW ); //size of array glstatic draw means this point isnt gonna change its static

   // Load shaders and use the resulting shader program

    GLuint program = InitShader("simpleShader - Copy.vert", "simpleShader - Copy.frag");
    // make these shaders the current shaders
    glUseProgram( program );

    // Initialize the vertex position attribute from the vertex shader
    GLuint loc = glGetAttribLocation( program, "vPosition" ); //find the location in the code
    glEnableVertexAttribArray( loc );
    glVertexAttribPointer( loc, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) );

    glClearColor( 0.5, 0.5, 0.5, 1.0 ); // gray background
}

//----------------------------------------------------------------------------
/* This function handles the display and it is automatically called by GLUT
   once it is declared as the display function. The application should not
   call it directly.
*/

void
display( void )
{
    glClear( GL_COLOR_BUFFER_BIT );             // clear the window
    glDrawArrays( GL_POINTS, 0, NumPoints );    // draw the points
    glFlush();                                  // flush the buffer
}

//----------------------------------------------------------------------------
/* This function handles the keyboard and it is called by GLUT once it is 
   declared as the keyboard function. The application should not call it
   directly.
*/

void
keyboard( unsigned char key, int x, int y )
{
    switch ( key ) {
    case 033:                   // escape key
        exit( EXIT_SUCCESS );   // terminates the program
        break;
    }
}

//----------------------------------------------------------------------------
/* This is the main function that calls all the functions to initialize
   and setup the OpenGL environment through GLUT and GLEW.
*/

int
main( int argc, char **argv )
{
    // Initialize GLUT
    glutInit( &argc, argv );
    // Initialize the display mode to a buffer with Red, Green, Blue and Alpha channels
    glutInitDisplayMode( GLUT_RGBA );
    // Set the window size
    glutInitWindowSize( 512, 512 );
    // Here you set the OpenGL version
    glutInitContextVersion( 3, 2 );
    //Use only one of the next two lines
    //glutInitContextProfile( GLUT_CORE_PROFILE );
    glutInitContextProfile( GLUT_COMPATIBILITY_PROFILE );
    glutCreateWindow( "Simple GLSL example" );

    // Uncomment if you are using GLEW
    glewInit(); 

    // initialize the array and send it to the graphics card
    init();

    // provide the function that handles the display
    glutDisplayFunc( display );
    // provide the functions that handles the keyboard
    glutKeyboardFunc( keyboard );
    glutMainLoop();
    return 0;
}

1 Ответ

0 голосов
/ 06 сентября 2018

Похоже, ваша задача предназначена для того, чтобы познакомить вас с настройкой и использованием буфера вершин. Если так, то не имеет значения, как вы придумали треугольники - дело в том, чтобы понять, как работает установка.

Итак, первое, что вам нужно сделать, это прочитать ваш учебник по этой теме. Если у вас нет текста, вам нужно будет просмотреть графические вызовы в справочнике OpenGL.

Если вы запустите программу как есть, она должна нарисовать группу случайно выбранных, несвязанных точек (в форме фрактала, но все же ...). Это связано с тем, что фактический вызов отрисовки glDrawArrays() вызывается с перечисленным значением GL_POINTS, которое говорит ему о необходимости рисовать точки в качестве первого аргумента.

Если вы читаете документацию для glDrawArrays(), в нем должны быть перечислены другие значения для этого аргумента, некоторые из которых рисуют треугольники различными способами. Самым простым из них является GL_TRIANGLES, но я рекомендую вам просмотреть все из них, чтобы дать вам представление о том, какие у вас есть варианты.

Генерация треугольников зависит от вас. Если ваше имя короткое, генерировать их вручную должно быть довольно легко. Обратите внимание, что вы должны полностью заменить код, генерирующий случайные точки; варианты включают в себя:

  • со встроенными данными
  • с некоторым кодом для загрузки координат из файла
  • с чем-то более умным, чтобы вам не пришлось создавать их вручную
...