在中心而不是在一个顶点处合并颜色顶点?

时间:2019-05-09 20:07:59

标签: c++ opengl glfw opengl-compat

我正在尝试制作一个颜色色板工具,在其中给它提供n种颜色,并用这些颜色在中间合并一个n边形。

到目前为止,它只制作了一个n-gon(不指定颜色,它会随机生成它们)。

但是颜色不是在中心融合而是一个顶点。

对此有任何解决办法吗?

#include <GLFW/glfw3.h>
#include <iostream>
#include <cmath>
float randfloat(){
  float r = ((float)(rand() % 10))/10;
  return r;
}
int main() {
  int side_count;
  std::cout<<"Type the no. of sides: "<<std::endl;
  std::cin>>side_count;
  srand(time(NULL));
  std::cout<<randfloat()<<std::endl;
  std::cout<<randfloat()<<std::endl;
  float rs[side_count];
  float gs[side_count];
  float bs[side_count];
  for (int i=0;i<side_count;i++)
  {
    rs[i] = randfloat();
    gs[i] = randfloat();
    bs[i] = randfloat();
  }
  GLFWwindow* window;
  if (!glfwInit())
    return 1;
  window = glfwCreateWindow(800, 800, "Window", NULL, NULL);
  if (!window) {
    glfwTerminate();
    return 1;
  }
  glfwMakeContextCurrent(window);
  if(glewInit()!=GLEW_OK)
    std::cout<<"Error"<<std::endl;

  while(!glfwWindowShouldClose(window)) {
    glClear(GL_COLOR_BUFFER_BIT);
    glClearColor(0.11f,0.15f,0.17f,1.0f);
    glBegin(GL_POLYGON);
      //glColor3f(1.0f,0.0f,0.0f);glVertex3f(-0.5f,0.0f,0.0f);
      for(int i=0; i<side_count;i++)
      {
        float r = rs[i];
        float g = gs[i];
        float b = bs[i];
        float x = 0.5f * sin(2.0*M_PI*i/side_count);
        float y = 0.5f * cos(2.0*M_PI*i/side_count);
        glColor3f(r,g,b);glVertex2f(x,y);
      }
    glEnd();
    glfwSwapBuffers(window);
    glfwPollEvents();
  }
  glfwTerminate();
  return 0;
}

1 个答案:

答案 0 :(得分:2)

您要做的就是在圆形的中心向GL_POLYGON原语添加一个新点:

glBegin(GL_TRIANGLE_FAN);

glColor3f(0.5f, 0.5f, 0.5f);
glVertex2f(0, 0);

for(int i=0; i <= side_count; i++)
{
    float r = rs[i % side_count];
    float g = gs[i % side_count];
    float b = bs[i % side_count];
    float x = 0.5f * sin(2.0*M_PI*i/side_count);
    float y = 0.5f * cos(2.0*M_PI*i/side_count);
    glColor3f(r, g, b);
    glVertex2f(x, y);
}

glEnd();

请注意,您必须定义中心点的颜色。在代码段中,我选择了(0.5,0.5,0.5)。
也可以使用GL_TRIANGLE_FAN代替GL_POLYGON

相关问题