#include "edview.h"
#include <QtGui>


QEDGLDemoView::QEDGLDemoView(QWidget *parent) :
    QGLWidget(QGLFormat(QGL::SampleBuffers|QGL::AlphaChannel), parent)
{
    makeCurrent();

    if (QGLFramebufferObject::hasOpenGLFramebufferBlit())
    {
        QGLFramebufferObjectFormat format;
        format.setSamples(4);
        format.setAttachment(QGLFramebufferObject::CombinedDepthStencil);

//        render_fbo = new QGLFramebufferObject(512, 512, format);
//        texture_fbo = new QGLFramebufferObject(512, 512);
    }
    else
    {
//        render_fbo = new QGLFramebufferObject(1024, 1024);
//        texture_fbo = render_fbo;
    }

    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
}


QEDGLDemoView::~QEDGLDemoView()
{
}


QSize QEDGLDemoView::minimumSizeHint() const
{
    return QSize(320, 240);
}


QSize QEDGLDemoView::sizeHint() const
{
    return QSize(640, 480);
}


void QEDGLDemoView::setEngineData(DMEngineData *mengine)
{
    engine = mengine;
}


void QEDGLDemoView::render(int frameTime)
{
    if (engine != NULL)
    {
        engine->frameTime = frameTime;

        if (engine->demoRender != NULL)
        {
            engine->demoRender(engine);
        }
        else
        {
            dmExecuteTimeline(engine->ptl, engine->screen, engineGetTick(engine));
        }
        
        engine->frameCount++;
    }
}


void QEDGLDemoView::paintEvent(QPaintEvent *)
{
    // save the GL state set for QPainter
    saveGLState();

    // restore the GL state that QPainter expects
    restoreGLState();
}


void QEDGLDemoView::saveGLState()
{
    glPushAttrib(GL_ALL_ATTRIB_BITS);
    glMatrixMode(GL_PROJECTION);
    glPushMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPushMatrix();
}


void QEDGLDemoView::restoreGLState()
{
    glMatrixMode(GL_PROJECTION);
    glPopMatrix();
    glMatrixMode(GL_MODELVIEW);
    glPopMatrix();
    glPopAttrib();
}


QEDSWDemoView::QEDSWDemoView(QWidget *parent) : QEDGLDemoView(parent)
{
    img = NULL;
}


QEDSWDemoView::~QEDSWDemoView()
{
    delete img;
}


void QEDSWDemoView::setEngineData(DMEngineData *mengine)
{
    engine = mengine;
    delete img;

    img = new QImage((const uchar *)mengine->screen->pixels,
        mengine->screen->w, mengine->screen->h,
        mengine->screen->pitch, QImage::Format_RGB32);
}


void QEDSWDemoView::paintEvent(QPaintEvent *)
{
    if (img != NULL)
    {
        QPainter painter(this);
        painter.drawImage(QPoint(0, 0), *img);
    }
}


void QEDSWDemoView::render(int frameTime)
{
    if (SDL_MUSTLOCK(engine->screen) != 0 && SDL_LockSurface(engine->screen) != 0)
        return;

    QEDGLDemoView::render(frameTime);

    if (SDL_MUSTLOCK(engine->screen) != 0)
        SDL_UnlockSurface(engine->screen);

    update();
}


