//-----------------------------------------------------------------------------------------
void CTerrainGroupEditor::importFullTerrainFromHeightMap()
{
    UTFStringVector extlist;
    extlist.push_back(OTR("PNG Grayscale"));
    extlist.push_back("*.png");
    extlist.push_back(OTR("Raw 32bit Float File"));
    extlist.push_back("*.raw;*.ohm;*.f32;*.r32");

    Ogre::UTFString defaultPath = mSystem->GetSetting("system", "ExportTerrainPath", "");

    Ogre::String filename = mSystem->DisplayOpenDialog(OTR("Import Heightmap"), extlist, defaultPath);
    if(filename == "") 
        return;

    mSystem->SetSetting("system", "ExportTerrainPath", OgitorsUtils::ExtractFilePath(filename));

    Ogre::NameValuePairList params;
    if(!mSystem->DisplayImportHeightMapDialog(params))
        return;
    
    Ogre::Real fScale = Ogre::StringConverter::parseReal(params["scale"]);
    Ogre::Real fBias = Ogre::StringConverter::parseReal(params["bias"]);
    Ogre::String normal = params["normal"];
    Ogre::String diffuse = params["diffuse"];
    bool flipV = Ogre::StringConverter::parseBool(params["inverted"]);

    float *data = 0;
    float *flipBV = 0;

    Ogre::String namePart = OgitorsUtils::ExtractFileName(filename);
    namePart.erase(0, namePart.find("."));

    int imgW = 0;
    int imgH = 0;

    if(namePart == ".png")
    {
        std::fstream fstr(filename.c_str(), std::ios::in|std::ios::binary);
        Ogre::DataStreamPtr stream = Ogre::DataStreamPtr(OGRE_NEW Ogre::FileStreamDataStream(&fstr, false));

        Ogre::Image img;
        img.load(stream);

        data = OGRE_ALLOC_T(float, img.getWidth() * img.getHeight(), Ogre::MEMCATEGORY_GEOMETRY);
        Ogre::PixelBox pb(img.getWidth(), img.getHeight(), 1, Ogre::PF_FLOAT32_R, data);
        Ogre::PixelUtil::bulkPixelConversion(img.getPixelBox(), pb);

        imgW = img.getWidth();
        imgH = img.getHeight();
        
        img.freeMemory();
        stream.setNull();
    }
/****************************************************************************
**
** Copyright (C) 2016 - 2017
**
** This file is part of the Magus toolkit
**
** 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."
**
****************************************************************************/

#include "constants.h"
#include "texturelayer.h"
#include "OgreHlmsPbs.h"
#include "OgreHlmsManager.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include <fstream>
#include <ctime>

//****************************************************************************/
TextureLayer::TextureLayer(void) :
    mTextureOnWhichIsPaintedWidth(0),
    mTextureOnWhichIsPaintedHeight(0),
    mTextureOnWhichIsPaintedHasAlpha(false),
    mNumMipMaps(0),
    mTextureTypeDefined(false),
    mMaxSequence(0)
{
    mTextureType = Ogre::PBSM_DIFFUSE;
    mDatablockId = "";
    mTextureFileName = "";
}

//****************************************************************************/
TextureLayer::~TextureLayer(void)
{
}

//****************************************************************************/
void TextureLayer::setDatablockIdAndTexture (const Ogre::IdString& datablockId,
                                             Ogre::PbsTextureTypes textureType,
                                             const Ogre::String& textureFileName)
{
    mDatablockId = datablockId;
    mTextureType = textureType;
    mTextureFileName = textureFileName;
    mTextureTypeDefined = true;

    // Load the texture as image; assume it can be loaded, because it was already loaded as part of the material
    setFirstTextureGeneration();

    // Create the pixelbox of the original texture; this MUST be a separate image
    mOriginalTexture.load(textureFileName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
    mPixelboxOriginalTexture = mOriginalTexture.getPixelBox(0, 0);

    // Debug texture
    //Ogre::LogManager::getSingleton().logMessage("Debug texture: " + textureFileName);
    //Ogre::LogManager::getSingleton().logMessage("Depth: " + Ogre::StringConverter::toString(mOriginalTexture.getDepth()));
    //Ogre::LogManager::getSingleton().logMessage("Pixel format: " + Ogre::StringConverter::toString(mOriginalTexture.getFormat()));
    //Ogre::LogManager::getSingleton().logMessage("Alpha: " + Ogre::StringConverter::toString(mOriginalTexture.getHasAlpha()));
    //Ogre::LogManager::getSingleton().logMessage("Height: " + Ogre::StringConverter::toString(mOriginalTexture.getHeight()));
    //Ogre::LogManager::getSingleton().logMessage("Number of faces: " + Ogre::StringConverter::toString(mOriginalTexture.getNumFaces()));
    //Ogre::LogManager::getSingleton().logMessage("Number of mipmaps: " + Ogre::StringConverter::toString(mOriginalTexture.getNumMipmaps()));
    //Ogre::LogManager::getSingleton().logMessage("Width: " + Ogre::StringConverter::toString(mOriginalTexture.getWidth()));
}

//****************************************************************************/
void TextureLayer::blitTexture (void)
{
    /* Always get the actual pointers, because they may change. That is the reason why the datablock pointer cannot be cached.
     * The same seems to apply to the texture pointer.
     */
    Ogre::HlmsDatablock* datablock;
    Ogre::HlmsPbsDatablock* datablockPbs;
    Ogre::TexturePtr texture;
    Ogre::HlmsManager* hlmsManager = Ogre::Root::getSingletonPtr()->getHlmsManager();
    Ogre::HlmsPbs* hlmsPbs = static_cast<Ogre::HlmsPbs*>(hlmsManager->getHlms(Ogre::HLMS_PBS));
    datablock = hlmsPbs->getDatablock(mDatablockId);
    if (!datablock)
        return;

    datablockPbs = static_cast<Ogre::HlmsPbsDatablock*>(datablock);
    try
    {
        // Get texture on GPU
        if (!datablockPbs->getTexture(mTextureType).isNull())
        {
            texture = datablockPbs->getTexture(mTextureType); // TextureType MUST exist, otherwise the application crashes
            mNumMipMaps = texture->getNumMipmaps();
        }
    }
    catch (Ogre::Exception e){}

    if (texture.isNull())
        return;

    Ogre::uint8 maxMipMaps = mNumMipMaps + 1; // Increase with one, because there is always one image to blit
    maxMipMaps = maxMipMaps > PAINT_MAX_MIP_MAPS ? PAINT_MAX_MIP_MAPS : maxMipMaps; // Just paint a few mipmaps (not all)
    Ogre::Image textureOnWhichIsPaintedScaled = mTextureOnWhichIsPainted; // Temporary image must be used, otherwise painting doesn't work
    size_t w = mTextureOnWhichIsPaintedWidth;
    size_t h = mTextureOnWhichIsPaintedHeight;
    Ogre::v1::HardwarePixelBuffer* buffer;
    for (Ogre::uint8 i = 0; i < maxMipMaps; ++i)
    {
        buffer = texture->getBuffer(0, i).getPointer();
        buffer->blitFromMemory(textureOnWhichIsPaintedScaled.getPixelBox(0, 0), Ogre::Box(0, 0, 0, w, h, 1));
        w*=0.5f; // Mipmaps always are half of the previous one
        h*=0.5f;
        if (w < 1.0f || h < 1.0f)
            break; // Stop when the mipmaps are too small

        textureOnWhichIsPaintedScaled.resize(w, h);

    }
    textureOnWhichIsPaintedScaled.freeMemory();
}