我正在用C ++编写一个使用freeglut的简单图形库。我有多个源文件,一个处理颜色,一个处理形状,一个处理OpenGL函数。我有一个基本的Shape Class,以及从它衍生的形状(Triangle,Quad等)。我从.cpp初始化GL,并且glutDisplayFunc调用一个方法,该方法遍历一个形状列表,这些形状反过来调用三角形,四边形等的虚拟刷新函数。
问题是,当我使用init和display函数在同一个.cpp中编写测试刷新函数时,会呈现三角形。但是当我从单独的Shape.cpp文件中调用每个形状的flush函数时,它不起作用。当glVertex2f在不同的源文件中使用时,它是否有可能超出范围?
//Glut_Functions.cpp
#include "Glut_Functions.h"
using namespace Cors;
static int shapeCount = 0;
static Shape** shapeList = nullptr;
void Cors::display()
{
glClear(GL_COLOR_BUFFER_BIT);
for (int i = 0; i < Cors::shapeCount; i++)
{
Cors::shapeList[i]->flush();
}
glutSwapBuffers();
}
void Cors::init(int *argc, char **argv)
{
glutInit(argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition(700, 100);
glutInitWindowSize(800, 600);
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glutCreateWindow("whatevs");
glutDisplayFunc(Cors::display);
glutIdleFunc(Cors::display);
}
//Glut_Functions.h
#ifndef GLUT_FUNCTIONS_H_INCLUDED
#define GLUT_FUNCTIONS_H_INCLUDED
#include <freeglut.h>
#include "Shape.h"
namespace Cors
{
static Shape **shapeList; //not used in this example for simplification of code.
static int shapeCount; //ditto...
void init(int*, char**);
void display(void);
}
#endif
//Shape.h
#ifndef SHAPE_H_INCLUDED
#define SHAPE_H_INCLUDED
#include <cmath>
#include <freeglut.h>
#include "Vector.h"
#include "Color.h"
namespace Cors
{
class Shape
{
protected:
Vector position;
Vector *localVertexList;
int localVertexCount;
Color color;
public:
Shape();
Shape(Vector argPosition);
virtual void flush() = 0;
//some other functions...
};
class Triangle : public Shape
{
private:
void flush();
public:
Triangle();
Triangle(Vector argVertex0, Vector argVertex1, Vector argVertex2);
};
}
#endif
//Shape.cpp
#include "Shape.h"
using namespace Cors;
using namespace std;
//Shape Base Class
Shape::Shape() : position(0.0f, 0.0f) {}
Shape::Shape(Vector argPosition) : position(argPosition) {}
//Triangle Class
Triangle::Triangle()
{
//some stuff
}
Triangle::Triangle(Vector argVertex0, Vector argVertex1, Vector argVertex2)
{
//some other stuff
}
void Triangle::flush()
{
//The triangle flush method has been simplified for test purposes.
glColor3f(1.0f, 0.0f, 0.0f);
glBegin(GL_TRIANGLES);
glVertex2f(-0.5f, -0.5f);
glVertex2f(0.5f, -0.5f);
glVertex2f(0.0f, 0.2f);
glEnd();
}
请注意,为了简单起见,我发布了一个简化代码,不包括构造函数和其他一些派生类。
我确信正在调用Triangle :: flush(),我已经在其中放置了一个std :: cout并且它会被调用。
另请注意,我也欢迎任何与我的编码风格相关的建议:)
PS:为了彻底解决问题,当我在Glut_Functions.cpp中创建一个flush函数时,会渲染三角形。当我在Shape.cpp中执行它时,它没有。