/*libC++RWD Library for C++ Rendering of White_dune Data (in Development)*/

/* Copyright (c) Stefan Wolf, 2010. */

/*
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "libC++RWD.h"
#include "C++Export.cc"

#define Z_NEAR 0.05f
#define Z_FAR 7000.0f

static bool viewpointRendered = false;
static bool lightRendered = false;

static bool pointLightexists = false;
static bool viewPointexists = false;

static GLfloat viewpoint1Position[] = { 0, 0, 10 };

static bool preRender = false;
static bool initRender = false;

static X3dSceneGraph scenegraph;

void CPPRWD::error(const char *errormsg)
{
    #ifdef WIN32
    MessageBox(NULL, errormsg, NULL, MB_OK);
    #else
    fprintf(stderr, "%s\n", errormsg);
    #endif
}

void CPPRWD::IndexedFaceSetRender(X3dNode *data, void* extraData)
{
    if(preRender)
    {
    }
    else if(initRender)
    {
    }
    else
    {
        X3dIndexedFaceSet *Xindexedfaceset = (X3dIndexedFaceSet*)data;
        X3dCoordinate *Xcoordinate = (X3dCoordinate*)Xindexedfaceset->coord;
        X3dNormal *Xnormal = (X3dNormal*)Xindexedfaceset->normal;
        X3dColor *Xcolor = (X3dColor*)Xindexedfaceset->color;
        X3dTextureCoordinate *Xtexturecoordinate = (X3dTextureCoordinate*)Xindexedfaceset->texCoord;
        GLint *faces = NULL;
        GLfloat *vertex = NULL;
        GLint *normalindex = NULL;
        GLfloat *normal = NULL;
        GLfloat *colors = NULL;
        GLint *colorindex = NULL;
        GLint *texturecoordinateindex = NULL;
        int faces_len, vertex_len, normalindex_len, normal_len, color_len, colorindex_len, texturecoordinateindex_len;
        bool normalpervertex, colorpervertex;
        if(Xcolor != NULL)
        {
            glEnable(GL_COLOR_MATERIAL); //Maybe needfull
            glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
            colors = Xcolor->color;
            color_len = Xcolor->color_length;
            colorpervertex = Xindexedfaceset->colorPerVertex;
        }
        if(Xindexedfaceset->colorIndex != NULL)
        {
            colorindex = Xindexedfaceset->colorIndex;
            colorindex_len = Xindexedfaceset->colorIndex_length;
        }
        if(Xindexedfaceset->texCoordIndex != NULL)
        {
            texturecoordinateindex = Xindexedfaceset->texCoordIndex;
            texturecoordinateindex_len = Xindexedfaceset->texCoordIndex_length;
        }
        vertex = Xcoordinate->point;
        faces = Xindexedfaceset->coordIndex;
        normalindex = Xindexedfaceset->normalIndex;
        if(Xnormal!=NULL)normal = Xnormal->vector;
        vertex_len = Xcoordinate->point_length;
        faces_len = Xindexedfaceset->coordIndex_length;
        if(Xnormal != NULL)normal_len = Xnormal->vector_length;
        normalindex_len = Xindexedfaceset->normalIndex_length;
        normalpervertex = Xindexedfaceset->normalPerVertex;
        int buffer, normalbuffer, texturebuffer;
        int facecounter = 0;
        if (Xindexedfaceset->ccw != 0)
        {
           glFrontFace(GL_CCW);
        }
        else
        {
           glFrontFace(GL_CW);
        }
        if (Xindexedfaceset->solid == 0) 
        {
           glDisable(GL_CULL_FACE);
           glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);
        } 
        else 
        {
           glEnable(GL_CULL_FACE);
           glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
        }

        glBegin(GL_POLYGON);
        if(colors && !colorpervertex)
            glColor3f(colors[facecounter], colors[facecounter + 1], colors[facecounter + 2]);

        for(int i = 0; i != faces_len; i++)
        {
            buffer = faces[i];
            if(normalindex != NULL)normalbuffer = normalindex[i];
            if(texturecoordinateindex != NULL)texturebuffer = texturecoordinateindex[i];
            if(buffer == -1 && (normalbuffer == -1 || normalindex != NULL))
            {
                facecounter++;
                glEnd();
                glBegin(GL_POLYGON);
                if(colors && !colorpervertex)
                        glColor3f(colors[3 * facecounter], colors[3 * facecounter + 1], colors[3 * facecounter + 2]);
            }
            else if(((buffer == -1 && normalbuffer != -1) || (buffer != -1 && normalbuffer == -1)) && normalindex != NULL)
                error("Error in normalIndex");
            else
            {
                if(normalpervertex && normal != NULL)glNormal3f(normal[normalbuffer*3], normal[normalbuffer*3+1], normal[normalbuffer*3+2]);
                if(colors && colorpervertex)glColor3f(colors[buffer*3], colors[buffer*3+1], colors[buffer*3+2]);
                if(texturecoordinateindex)glTexCoord2f(Xtexturecoordinate->point[texturebuffer*2], Xtexturecoordinate->point[texturebuffer*2+1]);
                glVertex3f(vertex[buffer*3], vertex[buffer*3+1], vertex[buffer*3+2]);
            }
        }
        glEnd();
    }
}

static bool not2PowN(int number)
{
    bool ret = true;
    for (int i = 0; i < 32; i++)
        if (number == (1 << i))
        {
            ret = false;
            break;
        }
    return ret;
}

static void renderTexture(int height, int width, int format, GLuint *data,
                          bool repeatS, bool repeatT)
{
    glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, 
                 GL_UNSIGNED_BYTE, data);
    if(repeatS)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    if(repeatT)
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glEnable(GL_TEXTURE_2D);
}

void CPPRWD::PixelTextureRender(X3dNode *data, void*)
{
    X3dPixelTexture *pixeltexture = (X3dPixelTexture*) data;
    if(preRender)
    {
    }
    else if(initRender)
    {
        int bigEndian = 1;
        bigEndian = (*(unsigned char *)&bigEndian) == 0;

        if (not2PowN(pixeltexture->image[0]))
            error("warning: texture width is not 2 pow N");            
        if (not2PowN(pixeltexture->image[1]))
            error("warning: texture height is not 2 pow N");            
        if (pixeltexture->image[0] != pixeltexture->image[1])
            error("warning: texture width and height is not equal\n");
        // store modified colors back to PixelTexture.image
        for (int i = 3; i < pixeltexture->image_length; i++) {
            int a = 0xff;
            int r,g,b;
            switch (pixeltexture->image[2])
            {
              case 4:
                r = (pixeltexture->image[i]&0xFF000000) >> 24;
                g = (pixeltexture->image[i]&0x00FF0000) >> 16;
                b = (pixeltexture->image[i]&0x0000FF00) >> 8;
                a = (pixeltexture->image[i]&0x000000FF);
                break;
              case 3:
                r = (pixeltexture->image[i]&0x00FF0000) >> 16;
                g = (pixeltexture->image[i]&0x0000FF00) >> 8;
                b = (pixeltexture->image[i]&0x000000FF);
                break;
              case 2:
                r = g = b = (pixeltexture->image[i]&0x0000FF00) >> 8;
                a = (pixeltexture->image[i]&0x000000FF);
                break;
              case 1:
                r = g = b = (pixeltexture->image[i]&0xFF);
                break;
            }
            if (bigEndian)
            {
                pixeltexture->image[i] = a | 
                                         (b << 8) | (g << 16) | (r << 24);
            }
            else
            {
                pixeltexture->image[i] = r | (g << 8) | (b << 16) | 
                                         (a << 24);
            }
        }
    }
    else
        renderTexture(pixeltexture->image[0], pixeltexture->image[1], GL_RGBA, 
                      (GLuint *)&pixeltexture->image[3], 
                      pixeltexture->repeatS, pixeltexture->repeatT); 
}

void CPPRWD::PointLightRender(X3dNode *data, void*)
{
    if(preRender)
    {
        glEnable(GL_LIGHT0);
        X3dPointLight *light = (X3dPointLight*)data;
        GLfloat light_color[4] = {light->color[0]*light->intensity, light->color[1]*light->intensity, light->color[2]*light->intensity, 1};
        GLfloat light_ambient_color[4] = {light->color[0]*light->ambientIntensity, light->color[1]*light->ambientIntensity, light->color[2]*light->ambientIntensity, 1};
        GLfloat light_position[4] = {light->location[0], light->location[1], light->location[2], 1};
        GLfloat light_attenuation[3] = {light->attenuation[0], light->attenuation[1], light->attenuation[2]};
        glLightfv(GL_LIGHT0, GL_DIFFUSE, light_color);
        glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient_color);
        glLightfv(GL_LIGHT0, GL_POSITION, light_position);
        glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, light_attenuation[0]);
        glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, light_attenuation[1]);
        glLightf(GL_LIGHT0, GL_QUADRATIC_ATTENUATION, light_attenuation[2]);
        glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 180.0f);
        glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 0.0f);
        lightRendered = true;
    }
    else if(initRender)
    {
        pointLightexists = true;
    }
    else
    {
    }
}

void CPPRWD::MaterialRender(X3dNode *data, void*)
{
    if(preRender)
    {
    }
    else if(initRender)
    {
    }
    else
    {
        X3dMaterial *material = (X3dMaterial*)data;
        GLfloat diffuse_color[4] = {material->diffuseColor[0], material->diffuseColor[1], material->diffuseColor[2], 1.0f};
        GLfloat ambient = material->ambientIntensity;
        GLfloat ambient_color[4] = {ambient * material->diffuseColor[0], ambient * material->diffuseColor[1], ambient * material->diffuseColor[2], 1};
        GLfloat emissive_color[4] = {material->emissiveColor[0], material->emissiveColor[1], material->emissiveColor[2], 1.0f};
        GLfloat specuar_color[4] = {material->specularColor[0], material->specularColor[1], material->specularColor[2], 1.0f};
        GLfloat shininess = material->shininess*128.0f;
        glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse_color);
        glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient_color);
        glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emissive_color);
        glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specuar_color);
        glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess);
    }
}

void CPPRWD::GroupTreeRender(X3dNode *data, void *dataptr)
{
    X3dGroup *group = (X3dGroup*)data;
    glPushMatrix();
    if (group->children)
        for (int i = 0; i < group->children_length; i++)
            if (group->children[i]) 
            {
                if(!(preRender || initRender))
                    glDisable(GL_TEXTURE_2D);
                group->children[i]->treeRender(dataptr);
            }
    glPopMatrix();
}

void CPPRWD::TransformTreeRender(X3dNode *data, void *dataptr)
{
    X3dTransform *transform = (X3dTransform*)data;
    if(preRender || initRender)
    {
        if (transform->children)
            for (int i = 0; i < transform->children_length; i++)
                if (transform->children[i])
                    transform->children[i]->treeRender(dataptr);
    }
    else
    {
        glPushMatrix();
        glTranslatef(transform->translation[0], transform->translation[1], transform->translation[2]);
        glTranslatef(transform->center[0], transform->center[1], transform->center[2]);
        glRotatef( ( (transform->rotation[3] / (2*M_PI) ) * 360), transform->rotation[0], transform->rotation[1], transform->rotation[2]);
        glRotatef( ( (transform->scaleOrientation[3] / (2*M_PI) ) * 360), transform->scaleOrientation[0], transform->scaleOrientation[1], transform->scaleOrientation[2]);
        glScalef(transform->scale[0], transform->scale[1], transform->scale[2]);
        glRotatef( ( (transform->scaleOrientation[3] / (2*M_PI) ) * 360) * -1, transform->scaleOrientation[0], transform->scaleOrientation[1], transform->scaleOrientation[2]);
        glTranslatef(transform->center[0] * -1, transform->center[1] * -1, transform->center[2] * -1);
        if (transform->children)
            for (int i = 0; i < transform->children_length; i++)
                if (transform->children[i]) 
                {
                    glDisable(GL_TEXTURE_2D);
                    transform->children[i]->treeRender(dataptr);
                }
        glPopMatrix();
    }
}

void CPPRWD::ViewpointRender(X3dNode *data, void*)
{
    X3dViewpoint *viewpoint = (X3dViewpoint*)data;
    if(preRender)
    {
        if(!viewpointRendered)
        {
            glMatrixMode(GL_MODELVIEW);
            glRotatef( ( -(viewpoint->orientation[3] / (2*M_PI) ) * 360), viewpoint->orientation[0], viewpoint->orientation[1], viewpoint->orientation[2]);
            glTranslatef(-viewpoint->position[0], -viewpoint->position[1], -viewpoint->position[2]);
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
            viewpointRendered = true;
        }
    }
    else if(initRender)
    {
        float fieldOfViewdegree = ( (viewpoint->fieldOfView / (2*M_PI) ) * 360);

        glMatrixMode(GL_PROJECTION);
        gluPerspective(fieldOfViewdegree, 1.0, Z_NEAR, Z_FAR);  /* fieldOfView in degree, aspect radio, Z nearest, Z farest */

        viewPointexists = true;
        for (int i = 0; i < 3; i++)
            viewpoint1Position[i] = viewpoint->position[i];
    }
    else
    {
    }
}

X3dNode *rootNode = &scenegraph.root;
//X3dNode *rootNode = &scenegraph.DEFNAME;

void CPPRWD::draw()
{
    glClearColor(0, 0, 0, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    viewpointRendered = 0;
    
    preRender = true;
    rootNode->treeRender(NULL);

    if(!viewPointexists)
    {
        X3dViewpoint viewpoint;
        viewpoint.fieldOfView = 0.79;
        viewpoint.position = new float[3];
        viewpoint.position[0] = 0;
        viewpoint.position[1] = 0;
        viewpoint.position[2] = 10;
        viewpoint.orientation = new float[4];
        viewpoint.orientation[0] = 0;
        viewpoint.orientation[1] = 0;
        viewpoint.orientation[2] = 1;
        viewpoint.orientation[3] = 0;
        ViewpointRender(&viewpoint, NULL);
        delete [] viewpoint.position;
        viewpoint.position = NULL;
        delete [] viewpoint.orientation;
        viewpoint.orientation = NULL;
    }

    if(!pointLightexists)
    {
        X3dPointLight pointlight;
        GLfloat attentuation[] = {1, 0, 0};
        pointlight.attenuation = attentuation;
        GLfloat color[] = {1, 1, 1};
        pointlight.color = color;
        GLfloat intensity = 1;
        pointlight.intensity = intensity;
        GLfloat *position = viewpoint1Position;
        pointlight.location = position;
        pointlight.ambientIntensity = 0;
        pointlight.on = true;
        PointLightRender(&pointlight, NULL);
    }

    preRender = false;
    rootNode->treeRender(NULL);
}

void CPPRWD::init()
{
    X3dTransform::treeRenderCallback = TransformTreeRender;
    X3dGroup::treeRenderCallback = GroupTreeRender;
    X3dIndexedFaceSet::renderCallback = IndexedFaceSetRender;
    X3dPointLight::renderCallback = PointLightRender;
    X3dMaterial::renderCallback = MaterialRender;
    X3dViewpoint::renderCallback = ViewpointRender;
    X3dPixelTexture::renderCallback = PixelTextureRender;

    glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT);
    glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE);
    glColorMaterial(GL_FRONT_AND_BACK, GL_EMISSION);
    glColorMaterial(GL_FRONT_AND_BACK, GL_SPECULAR);
    glColorMaterial(GL_FRONT_AND_BACK, GL_SHININESS);

    /*Enable light*/
    glEnable(GL_LIGHTING);

    GLint zero[4] = {0, 0, 0, 0};
    glLightModeliv(GL_LIGHT_MODEL_AMBIENT, zero);

    /* Use depth buffering for hidden surface elimination. */
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_NORMALIZE);

    glDepthMask(GL_TRUE);
    glDepthFunc(GL_LEQUAL);

    glEnable(GL_ALPHA_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glAlphaFunc(GL_NOTEQUAL, 0);

    glShadeModel(GL_SMOOTH);

    preRender = false;
    initRender = true;
    rootNode->treeRender(NULL);
    if (!viewPointexists)
    {
        float fieldOfViewdegree = ( (0.79 / (2*M_PI) ) * 360);

        glMatrixMode(GL_PROJECTION);
        gluPerspective(fieldOfViewdegree, 1.0, Z_NEAR, Z_FAR);
    }
    initRender = false;
}

void CPPRWD::finalize()
{
}
