如何使用 OpenGL 在圆内绘制随机点

How do I plot random points inside a circle using OpenGL?

本文关键字:绘制 随机 何使用 OpenGL      更新时间:2023-10-16

如何在圆内绘制随机点?我有以下代码可以绘制随机点,但我似乎无法弄清楚如何在圆圈内绘制它们!我一直在使用距离公式生成随机点,但没有运气。我希望在一个圆圈内生成点,但我只是得到了一个空白屏幕。不知道我做错了什么。

这是我的代码:

#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#include <vector>
#include <cstdlib>
#define __gl_h_
#include <cmath>
#include <iostream>
struct Point
{
    float x, y;
    unsigned char r, g, b, a;
};
std::vector< Point > points;
void display(void)
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-50, 50, -50, 50, -1, 1);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // draw
    glColor3ub( 255, 255, 255 );
    glEnableClientState( GL_VERTEX_ARRAY );
    glEnableClientState( GL_COLOR_ARRAY );
    glVertexPointer( 2, GL_FLOAT, sizeof(Point), &points[0].x );
    glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof(Point), &points[0].r );
    glPointSize( 3.0 );
    glDrawArrays( GL_POINTS, 0, points.size() );
    glDisableClientState( GL_VERTEX_ARRAY );
    glDisableClientState( GL_COLOR_ARRAY );
    glFlush();
    glutSwapBuffers();
}
void reshape(int w, int h)
{
    glViewport(0, 0, w, h);
}
int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
    glutInitWindowSize(640,480);
    glutCreateWindow("Random Points");
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    // populate points
    for( size_t i = 0; i < 1000; ++i )
    {
        Point pt;
        //pt.x = -50 + (rand() % 100);
        //pt.y = -50 + (rand() % 100);

        int angle = (rand() % 100 + 1) * 3.1416 * 2;
        int radius = (rand() % 100 + 1) * 50;
        pt.x = ((radius * cos(angle))-50);
        pt.y = ((radius * sin(angle))-50);

        pt.r = 125;
        pt.g = 125;
        pt.b = 125;
        pt.a = 255;
        points.push_back(pt);
    }
    glutMainLoop();
    return 0;
}
  1. 您的角度以弧度为单位int

    所以它只被截断到角度{0,1,2,3,4,5,6} [rad]所以你不能只覆盖那些7线的圆的内部。

  2. 您在计算时混合intdouble

    如果没有适当的转换,它可能会被截断(取决于编译器)。如果您意识到截断后sin,cos <-1,+1>范围内,那么您只会得到{-1,0,+1}这将产生9可能的角度。(与#1的组合甚至更少,所以你只渲染几个点,很可能没有在视野中识别它们)。

  3. 我不使用你的rand()所以我不确定它会返回什么。

    我敢打赌,它返回的整数范围高达某个RAND_MAX值。

    我习惯了VCL风格的Random(),它有两个选择:

    double Random();     // return pseudo-random floating number in range <0.0,1.0)
    int Random(int max); // return pseudo-random integer number in range <0,max)
    

    因此,如果您的rand()相似,那么您正在截断结果以{0}使其无用。请参阅rand()的文档以查看它是整数还是浮动,并根据需要进行相应更改。

  4. 您很可能正在将中心移到外部视图

    您正在从范围<-50,+50>的值中减去50,然后将其转换为我敢打赌在您的屏幕之外的<-100,0>。我懒得分析你的代码,但我认为你的屏幕<-50,+50>所以尽量不要移动

当全部放在一起时,请尝试以下操作:

double angle = double(rand() % 1000) * 6.283185307179586476925286766559;
int   radius = rand() % 51;
pt.x = double(double(radius)*cos(angle));
pt.y = double(double(radius)*sin(angle));