OpenGL核心配置文件中的Catmull-Rom Spline

时间:2016-03-10 07:45:17

标签: opengl

寻找帮助在核心配置文件中生成Catmull-Rom Spline的帮助。我有以前的兼容性配置文件代码:

void display(void) 
{
    float xcr, ycr;   //Points on the Catmull-Rom spline
    float dx, dy;     //tangent components
    glClear(GL_COLOR_BUFFER_BIT);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glPointSize(6.0); 
    glColor3f(1.0, 0.0, 1.0);
    glBegin(GL_POINTS);
    for(int i = 0; i < numPts; i++)
           glVertex2f(x[i], y[i]);
    glEnd();

    if(numPts > 3)
    {
       glColor3f(1.,0.,0.);
       glBegin(GL_LINES); //draw tangents
       for(int i = 1; i < numPts-1; i++){
           dx = 0.2*(x[i+1]-x[i-1]);
           dy = 0.2*(y[i+1]-y[i-1]);
           glVertex2f(x[i]-dx, y[i]-dy);
           glVertex2f(x[i]+dx,y[i]+dy);
        }
        glEnd();

        glColor3f(0., 0., 1.);
        glBegin(GL_LINE_STRIP);
        for(int i = 1; i < numPts-2; i++)
        {
            for(int k = 0;  k < 50; k++){    //50 points
               float t = k*0.02;  //Interpolation parameter
                   xcr = x[i] + 0.5*t*(-x[i-1]+x[i+1]) 
                       + t*t*(x[i-1] - 2.5*x[i] + 2*x[i+1] - 0.5*x[i+2])
                       + t*t*t*(-0.5*x[i-1] + 1.5*x[i] - 1.5*x[i+1] + 0.5*x[i+2]);
                   ycr = y[i] + 0.5*t*(-y[i-1]+y[i+1]) 
                       + t*t*(y[i-1] - 2.5*y[i] + 2*y[i+1] - 0.5*y[i+2])
                       + t*t*t*(-0.5*y[i-1] + 1.5*y[i] - 1.5*y[i+1] + 0.5*y[i+2]);
               glVertex2f(xcr, ycr);
           }
        }
        glEnd();
    }
        glFlush(); 
}

但我很难掌握如何将其翻译成核心档案。

1 个答案:

答案 0 :(得分:2)

由于您想要使用顶点数组,这很简单:

struct vec2 {
    vec2(float x_, y_) : x(x_), y(y_) {}
    float x, y;
};

std::vector<vec2> vertices;

glVertex2f(xcr,ycr)替换为vertices.push_back(vec(xcr,ycr))

创建一个顶点缓冲区对象,如众多VBO教程中所述。将vertices的内容上传到VBO。

GLuint vbo_id;
glGenBuffers(1, &vbo_id);
glBindBuffer(GL_ARRAY_BUFFER, vbo_id);
glBufferData(GL_ARRAY_BUFFER,
    vertices.size()*sizeof(vertices[0]),
    vertices.data(),
    GL_STATIC_DRAW );

GLuint vao_id;
glGenVertexArrays(1, &vao_id);
glBindVertexArray(vao_id);
glEnableVertexAttribArray(vertex_location);
glVertexAttribPointer(
    vertex_location, 2, GL_FLOAT, GL_FALSE,
    sizeof(vertices[0]), 0);

glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);

绘制它

glBindVertexArray(vao_id);
glDrawArrays(GL_LINE_STRIP, 0, sizeof(vertices));

您还必须实现着色器程序,加载它并确定顶点输入的属性位置;我建议使用布局位置说明符。