簡體   English   中英

用 OpenGL 畫一條任意線(即軸范圍沒有限制)

[英]draw an arbitrary line with OpenGL(i.e. no limit on axis range)

我想用用戶定義的參數繪制一條二維線。 但是 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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM