x^2 + (y-(x^2)(1/3))^2 = 1 心形方程 5.20無聊之作


2017.05.20 一個無聊的周六,只能看別人秀恩愛.偶然間在網上看到一個有意思的方程 x^2 + (y-(x^2)(1/3))^2 = 1,據說這個方程可以繪制出一個愛心的形狀.既然很無聊,就隨便動手實現了.

附:opengl開發庫 http://pan.baidu.com/s/1mip2pja

 

#include <stdio.h>
#include "glut.h"
#include "math.h"

// x^2 + (y-(x^2)(1/3))^2 = 1
// y = (+/-)sqrt(1-x^2) + (x^2)(1/3)
void love_fun(float x, float &y1, float &y2)
{
    if (x > 1.0)
    {
        return;
    }
    float a = pow(x, 2.0f);
    float b = sqrt(1 - a);
    float c1 = b;
    float c2 = -b;
    float d = pow(a, 0.333333f);
    y1 = c1 + d;
    y2 = c2 + d;
}

void coordinate()
{
    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINES);
    glVertex3f(-2.0, 0.0f, 0.0);
    glVertex3f(2.0, 0.0f, 0.0);
    glVertex3f(0.0, -2.0f, 0.0);
    glVertex3f(0.0, 2.0f, 0.0);
    glEnd();
}

void love()
{
    float step = 0.0005f;
    glColor3f(1.0, 0.0, 0.0);
    glBegin(GL_POLYGON);
    for (float x = -1.0; x <= 1.0; x += step)
    {
        float y1 = 0, y2 = 0;
        love_fun(x, y1, y2);
        // printf("(%f %f) (%f %f)\n", x, y1, x, y2);
        glVertex3f(x, y1, 0.0);
        glVertex3f(x, y2, 0.0);
    }
    glEnd();
}

void display_love()
{
    glClear(GL_COLOR_BUFFER_BIT);
    love();
    coordinate();
    glutSwapBuffers();
}

void init(void)
{

    glClearColor(0.4, 0.4, 0.8, 0.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-2.0f, 2.0f, -2.0f, 2.0f, -1.0f, 1.0f);
}


int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowPosition(500, 100);
    glutInitWindowSize(600, 500);
    glutCreateWindow("love : x^2 + (y-(x^2)(1/3))^2 = 1");
    init();
    glutDisplayFunc(display_love);
    glutMainLoop();
    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM