OpenGL GLUT solor system code example
标签:
OpenGL
C++
发布于:2020-04-09 22:55:07
编辑于:2022-11-15 12:18:53
浏览量:1397
/*
title: OpenGL GLUT solor system code example
tags:
- OpenGL
- C++
*/
#include <GL/glut.h>
#include <Math.h>
const float PI = 3.14159265f;
GLfloat sunRadius = 0.15f;
GLfloat earthRadius = 0.07f;
GLfloat moonRadius = 0.01f;
GLfloat sunTrackRadius = 0.5f;
GLfloat earthTrackRadius = 0.15f; // 0.1
GLfloat sunX = 0.0f;
GLfloat sunY = 0.0f;
GLfloat earthX, earthY, moonX, moonY;
GLfloat earthSpeed = 0.03;
GLfloat moonSpeed = 0.05;
GLfloat currentEarthAngle = 0;
GLfloat currentMoonAngle = 0;
bool isPaused = false;
int refreshMillis = 16;
GLdouble clipAreaXLeft, clipAreaXRight, clipAreaYBottom, clipAreaYTop;
void init()
{
glClearColor(0.0, 0.0, 0.0, 1.0);
}
void drawCirle(float circleX, float circleY, float radius, float r, float g, float b, int segmantNumber = 100)
{
glLoadIdentity(); // very important
glTranslatef(circleX, circleY, 0.0f);
glBegin(GL_TRIANGLE_FAN);
glColor3f(r, g, b);
GLfloat angle;
for (int i = 0; i <= segmantNumber; i++)
{
angle = i * 2.0f * PI / segmantNumber;
glVertex2f(cos(angle) * radius, sin(angle) * radius);
}
glEnd();
}
void circularMove(float centerX, float centerY, float& targetX, float& targetY, float& currentAngle, float speed, float radius)
{
currentAngle += speed;
targetX = centerX + cos(currentAngle) * radius;
targetY = centerY + sin(currentAngle) * radius;
}
void display()
{
if (isPaused) return;
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
circularMove(sunX, sunY, earthX, earthY, currentEarthAngle, earthSpeed, sunTrackRadius);
circularMove(earthX, earthY, moonX, moonY, currentMoonAngle, moonSpeed, earthTrackRadius);
drawCirle(sunX, sunY, sunRadius, 1, 0, 0);
drawCirle(earthX, earthY, earthRadius, 0, 0, 1);
drawCirle(moonX, moonY, moonRadius, 0.7925, 0.7925, 0.7925);
glutSwapBuffers();
}
void reshape(GLsizei width, GLsizei height)
{
if (height == 0) height = 1;
GLfloat aspect = (GLfloat)width / (GLfloat)height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (width >= height)
{
clipAreaXLeft = -1.0 * aspect;
clipAreaXRight = 1.0 * aspect;
clipAreaYBottom = -1.0;
clipAreaYTop = 1.0;
}
else
{
clipAreaXLeft = -1.0;
clipAreaXRight = 1.0;
clipAreaYBottom = -1.0 / aspect;
clipAreaYTop = 1.0 / aspect;
}
gluOrtho2D(clipAreaXLeft, clipAreaXRight, clipAreaYBottom, clipAreaYTop);
}
void timer(int value)
{
glutPostRedisplay();
glutTimerFunc(refreshMillis, timer, 0);
}
void keyboard(unsigned char key, int x, int y) {
switch (key)
{
case 32:
isPaused = !isPaused; break;
default: break;
}
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE);
glutInitWindowSize(1000, 1000);
glutCreateWindow("solar-system");
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutKeyboardFunc(keyboard);
glutTimerFunc(0, timer, 0);
init();
glutMainLoop();
return 0;
}
未经允许,禁止转载,本文源站链接:https://iamazing.cn/