Example of using "Canvas" form "Graphics" library to display 3D graphics.

Dependencies:   BSP_DISCO_F746NG Graphics mbed

Models/Sphere.cpp

Committer:
karpent
Date:
2016-11-11
Revision:
2:ef3093a7a43e
Parent:
1:4a5e329e617b

File content as of revision 2:ef3093a7a43e:

//
// Sphere.cpp - example of usage graphics commands to create 3D graphics.
//
// This example is based on code written by
// Fabio de Albuquerque Dela Antonio (fabio914 at gmail.com)
// See : https://github.com/fabio914/arduinogl/blob/master/examples
//

#include "Sphere.h"

// Constructor
Sphere::Sphere(Display * display) : Model()
{
    glUseCanvas(display);
    
    _perspectiveAspect = display->DisplayWidth() / display->DisplayHeight();
}


void Sphere::Setup()
{
    // Make the model a little bigger
    SetFixedScaleMode(3.1f);
    
    glClear(GL_COLOR_BUFFER_BIT);
    glPointSize(4);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    gluPerspective(30.0, _perspectiveAspect, 0.1f, 9999.f);

    glMatrixMode(GL_MODELVIEW);
}


void Sphere::Render()
{
    float scale = GetScaleValue();

    glLoadIdentity();
    gluLookAt(10, 8, -10, 0, 0, 0, 0, 1, 0);

    glScalef(scale, scale, scale);
    glRotatef(GetAngleValue(), 0.f, 1.f, 0.f);

    DrawModel(1.0, 10);
}


void Sphere::DrawModel(float radius, float p)
{

    float theta1 = 0.f, theta2 = 0.f, theta3 = 0.f;
    float ex, ey, ez;

    for(int i = 0; i < p/2; i++) {

        theta1 = i * (M_PI * 2.0)/p - M_PI_2;
        theta2 = (i + 1) * (M_PI * 2.0)/p - M_PI_2;

        glBegin(GL_TRIANGLE_STRIP);
        for(int j = 0; j <= p; j++) {

            theta3 = j * (M_PI * 2.0)/p;
            ex = cosf(theta2) * cosf(theta3);
            ey = sinf(theta2);
            ez = cosf(theta2) * sinf(theta3);

            glVertex3f(radius * ex, radius * ey, radius * ez);

            ex = cosf(theta1) * cosf(theta3);
            ey = sinf(theta1);
            ez = cosf(theta1) * sinf(theta3);

            glVertex3f(radius * ex, radius * ey, radius * ez);
        }
        glEnd();
    }
}