/**

 Copyright (c) 2010-2013  hkrn

 All rights reserved.

 Redistribution and use in source and binary forms, with or
 without modification, are permitted provided that the following
 conditions are met:

 - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 - 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.
 - Neither the name of the MMDAI project team nor the names of
   its contributors may be used to endorse or promote products
   derived from this software without specific prior written
   permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS
 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.

*/

#pragma once
#ifndef VPVL2_EXTENSIONS_GL_VERTEXBUNDLE_H_
#define VPVL2_EXTENSIONS_GL_VERTEXBUNDLE_H_

#include <vpvl2/extensions/gl/Global.h>

namespace vpvl2
{
namespace extensions
{
namespace gl
{

class VertexBundle VPVL2_DECL_FINAL {
public:
    static const GLenum kGL_STATIC_DRAW = 0x88E4;
    static const GLenum kGL_DYNAMIC_DRAW = 0x88E8;
    static const GLenum kGL_ARRAY_BUFFER = 0x8892;
    static const GLenum kGL_ELEMENT_ARRAY_BUFFER = 0x8893;
    static const GLenum kGL_WRITE_ONLY = 0x88B9;
    static const GLenum kGL_MAP_WRITE_BIT = 0x0002;


    enum Type {
        kVertexBuffer,
        kIndexBuffer,
        kMaxVertexBufferType
    };

    VertexBundle(const IApplicationContext::FunctionResolver *resolver)
        : genBuffers(reinterpret_cast<PFNGLGENBUFFERSPROC>(resolver->resolveSymbol("glGenBuffers"))),
          bindBuffer(reinterpret_cast<PFNGLBINDBUFFERPROC>(resolver->resolveSymbol("glBindBuffer"))),
          bufferData(reinterpret_cast<PFNGLBUFFERDATAPROC>(resolver->resolveSymbol("glBufferData"))),
          bufferSubData(reinterpret_cast<PFNGLBUFFERSUBDATAPROC>(resolver->resolveSymbol("glBufferSubData"))),
          deleteBuffers(reinterpret_cast<PFNGLDELETEBUFFERSPROC>(resolver->resolveSymbol("glDeleteBuffers"))),
          mapBuffer(reinterpret_cast<PFNGLMAPBUFFERPROC>(resolver->resolveSymbol("glMapBuffer"))),
          unmapBuffer(reinterpret_cast<PFNGLUNMAPBUFFERPROC>(resolver->resolveSymbol("glUnmapBuffer"))),
          mapBufferRange(reinterpret_cast<PFNGLMAPBUFFERRANGEPROC>(resolver->resolveSymbol("glMapBufferRange"))),
          m_hasMapBufferRange(resolver->hasExtension("ARB_map_buffer_range")),
          m_indexBuffer(0)
    {
    }
    ~VertexBundle() {
        const int nbuffers = m_vertexBuffers.count();
        for (int i = 0; i < nbuffers; i++) {
            const GLuint *value = m_vertexBuffers.value(i);
            deleteBuffers(1, value);
        }
        release(kIndexBuffer, 0);
    }

    void create(Type value, GLuint key, GLenum usage, const void *ptr, vsize size) {
        release(value, key);
        GLuint name = 0, target = type2target(value);
        genBuffers(1, &name);
        bindBuffer(target, name);
        bufferData(target, size, ptr, usage);
        bindBuffer(target, 0);
        switch (value) {
        case kVertexBuffer:
            m_vertexBuffers.insert(key, name);
            break;
        case kIndexBuffer:
            m_indexBuffer = name;
            break;
        case kMaxVertexBufferType:
        default:
            break;
        }
    }
    void release(Type value, GLuint key) {
        switch (value) {
        case kVertexBuffer:
            if (const GLuint *buffer = m_vertexBuffers.find(key)) {
                deleteBuffers(1, buffer);
                m_vertexBuffers.remove(key);
            }
            break;
        case kIndexBuffer:
            if (m_indexBuffer) {
                deleteBuffers(1, &m_indexBuffer);
                m_indexBuffer = 0;
            }
            break;
        case kMaxVertexBufferType:
        default:
            break;
        }
    }
    void bind(Type value, GLuint key) {
        switch (value) {
        case kVertexBuffer:
            if (const GLuint *bufferPtr = m_vertexBuffers.find(key)) {
                GLuint buffer = *bufferPtr;
                bindBuffer(kGL_ARRAY_BUFFER, buffer);
            }
            break;
        case kIndexBuffer:
            bindBuffer(kGL_ELEMENT_ARRAY_BUFFER, m_indexBuffer);
            break;
        case kMaxVertexBufferType:
        default:
            break;
        }
    }
    void unbind(Type type) {
        GLuint target = type2target(type);
        bindBuffer(target, 0);
    }
    void allocate(Type type, GLuint usage, vsize size, const void *data) {
        GLuint target = type2target(type);
        bufferData(target, size, data, usage);
    }
    void write(Type type, vsize offset, vsize size, const void *data) {
        GLuint target = type2target(type);
        bufferSubData(target, offset, size, data);
    }
    void *map(Type type, vsize offset, vsize size) {
        GLuint target = type2target(type);
#if defined(GL_CHROMIUM_map_sub)
        return glMapBufferSubDataCHROMIUM(target, offset, size, GL_WRITE_ONLY);
#elif defined(VPVL2_ENABLE_GLES2)
        (void) offset;
        (void) size;
        m_bytes.resize(size);
        return &m_bytes[0];
#else /* GL_CHROMIUM_map_sub */
        if (m_hasMapBufferRange) {
            return mapBufferRange(target, offset, size, kGL_MAP_WRITE_BIT);
        }
        else {
            return mapBuffer(target, kGL_WRITE_ONLY);
        }
#endif /* GL_CHROMIUM_map_sub */
    }
    void unmap(Type type, void *address) {
#ifdef GL_CHROMIUM_map_sub
        (void) type;
        glUnmapBufferSubDataCHROMIUM(address);
#elif defined(VPVL2_ENABLE_GLES2)
        GLuint target = type2target(type);
        bufferSubData(target, 0, m_bytes.count(), &m_bytes[0]);
#else /* GL_CHROMIUM_map_sub */
        (void) address;
        GLuint target = type2target(type);
        unmapBuffer(target);
#endif /* GL_CHROMIUM_map_sub */
    }
    GLuint findName(GLuint key) const {
        if (const GLuint *value = m_vertexBuffers.find(key)) {
            return *value;
        }
        return 0;
    }

private:
    static GLuint type2target(Type value) {
        switch (value) {
        case kVertexBuffer:
            return kGL_ARRAY_BUFFER;
        case kIndexBuffer:
            return kGL_ELEMENT_ARRAY_BUFFER;
        case kMaxVertexBufferType:
        default:
            return 0;
        }
    }

    typedef void (GLAPIENTRY * PFNGLGENBUFFERSPROC) (GLsizei n, GLuint* buffers);
    typedef void (GLAPIENTRY * PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
    typedef void (GLAPIENTRY * PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage);
    typedef void (GLAPIENTRY * PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data);
    typedef void (GLAPIENTRY * PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint* buffers);
    typedef GLvoid* (GLAPIENTRY * PFNGLMAPBUFFERPROC) (GLenum target, GLenum access);
    typedef GLboolean (GLAPIENTRY * PFNGLUNMAPBUFFERPROC) (GLenum target);
    typedef GLvoid * (GLAPIENTRY * PFNGLMAPBUFFERRANGEPROC) (GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access);
    PFNGLGENBUFFERSPROC genBuffers;
    PFNGLBINDBUFFERPROC bindBuffer;
    PFNGLBUFFERDATAPROC bufferData;
    PFNGLBUFFERSUBDATAPROC bufferSubData;
    PFNGLDELETEBUFFERSPROC deleteBuffers;
    PFNGLMAPBUFFERPROC mapBuffer;
    PFNGLUNMAPBUFFERPROC unmapBuffer;
    PFNGLMAPBUFFERRANGEPROC mapBufferRange;

    Hash<HashInt, GLuint> m_vertexBuffers;
    const bool m_hasMapBufferRange;
    GLuint m_indexBuffer;
#ifdef VPVL2_ENABLE_GLES2
    Array<uint8_t> m_bytes;
#endif

    VPVL2_DISABLE_COPY_AND_ASSIGN(VertexBundle)
};

} /* namespace gl */
} /* namespace extensions */
} /* namespace vpvl2 */

#endif
