我想绘制一条2D线,其中包含用户定义的参数。但x轴和y轴的范围是[-1,1]。
如何绘制可以在窗口中完全显示的线?我使用gluOrtho2D(-10.0, 10.0, -10.0, 10.0)
但它似乎不是一个好选择,因为根据参数范围是动态的。
例如,该行是y=ax^3+bx^2+cx+d
。 x的范围是[1,100]。
我的代码是:
#include "pch.h"
#include<windows.h>
#include <gl/glut.h>
#include <iostream>
using namespace std;
double a, b, c, d;
void init(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(-10.0, 10.0, -10.0, 10.0);
}
double power(double x, int p) {
double y = 1.0;
for (int i = 0; i < p; ++i) {
y *= x;
}
return y;
}
void linesegment(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1, 0, 0);
glPointSize(1);
glBegin(GL_POINTS);
for (int i = 1; i <= 10; ++i) {
double y = a * power(i, 3) + b * power(i, 2) + c * i + d;
glVertex2f(i, y);
}
glEnd();
glFlush();
}
int main(int argc, char**argv)
{
if (argc < 4) {
cout << "should input 4 numbers" << endl;
return 0;
}
a = atof(argv[1]);
b = atof(argv[2]);
c = atof(argv[3]);
d = atof(argv[4]);
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(50, 100);
glutInitWindowSize(400, 300);
glutCreateWindow("AnExample");
init();
glutDisplayFunc(linesegment);
glutMainLoop();
return 0;
}
设置投影矩阵不是一次性操作。您可以随时更改它。事实上,强烈劝阻你做init
的方式。只需在绘图功能中设置投影参数即可。还使用标准库函数,不要自己滚动。无需自己实施power
。只需使用pow
标准库函数。最后但并非最不重要的是,使用双缓冲;因为它提供了更好的性能,并具有更好的兼容性。
#include "pch.h"
#include <windows.h>
#include <gl/glut.h>
#include <iostream>
#include <cmath>
using namespace std;
double a, b, c, d;
double x_min, x_max, y_min, y_max; // <<<<---- fill these per your needs
void linesegment(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(x_min, x_max, y_min, y_max, -1, 1);
glColor3f(1, 0, 0);
glPointSize(1);
glBegin(GL_POINTS);
for (int i = 1; i <= 10; ++i) {
double y = a * pow(i, 3) + b * pow(i, 2) + c * i + d;
glVertex2f(i, y);
}
glEnd();
glFlush();
}