/*****************************************************************************

	File: HeightmapLoader.h
	Desc: Simple patch loader that loads data from a heightmap
	Date: 2003/03/02

	Author: Martin Persson

*****************************************************************************/

#ifndef __HEIGHTMAPLOADER_H
#define __HEIGHTMAPLOADER_H

#include <OgreString.h>
#include <OgreImage.h>

//#include "TriangleLoader.h"
#include "QuadIndex.h"
#include "Quad.h"

namespace Ogre
{

//----------------------------------------------------------------------------

class HeightmapLoader //: public BDAMPatchLoader
{
public:
    HeightmapLoader(SceneNode *sceneMgr);

    ~HeightmapLoader();

    bool initialise(const String& filename);

    /// loads patch data from the heightmap and returns it, 0 on error
    Quad *requestData(int x, int y,	Vector3 *worldPos, Vector3 *zonePos, Vector3 *scale);

    /// returns the size of the map (in unscaled units)
    int getMapSize();

    Vector3 mScale,mWorld;
    Real mScaleHeight, mOffset;

	float clipRegion;
	int clipSize;
	
	QuadIndex* quadIndex[6];
	String material;

private:

	Real getHeight(int x, int y, int level);
	void getNormal(int x, int y, int level, Vector3 *normal, unsigned char* heightMap, QuadIndex* quadIndex);
	
	int levelHeaderSize, saveSize;
	unsigned char* heightMap[6];

	bool saveClipmap;
	FILE* savefile[6];
	bool swapmap;

    bool generateClipmapTree(const String& filename, bool rawdata=false);
	bool loadClipmapTree();
	bool checkValidMap();
    /// loads data from a raw heightmap file
    unsigned char* loadRAWHeightmap(const char *filename,
			   	    unsigned int realSize,
				    unsigned int requestSize,
				    unsigned int xoff,
				    unsigned int yoff);

    /// holds number of patches in x direction
    int mMapSizeX;
    /// holds number of patches in y direction
    int mMapSizeY;


    /// holds filename of the heightmap
    Image *mHeightMap[6];

    /// common material for the terrain
    Material *mMaterial;

    bool mInited;
    
	void getNormal(int x, int z, Vector3 *normal, unsigned char* heightMap, QuadIndex* quadIndex);

	void collapseLevels(QuadIndex* quadIndex);
	
	void collapseLevel(QuadIndex* quadIndex,int level);
		
	bool writeVertex(Real* vertex, Real height, FILE *file);
	void setVertexSaveSize(QuadIndex* quadIndex);
	bool writeLevelHeader(int level, int width, int height, FILE *file);
	
//	void setQuadSize(QuadIndex* quadIndex);
	void setLevelHeaderSize(QuadIndex* quadIndex);
	int readMapsize(FILE* file);

	int getVertexPosition(int x, int y, int level, QuadIndex *quadIndex);

	void getTextureCoordinates(int x, int y, Real &tx, Real &ty);
	Vector3 getVertex(int x, int y, int direction, int level, QuadIndex* quadIndex);
protected:
    SceneNode *mSceneRoot;

};


//----------------------------------------------------------------------------

} // namespace Ogre

#endif
