
/*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans  http://bulletphysics.org

This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, 
including commercial applications, and to alter it and redistribute it freely, 
subject to the following restrictions:

1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/

// zlib open source license
//
// Copyright (c) 2010 to 2013 David Forsgren Piuva
// 
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
// 
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
// 
//    1. The origin of this software must not be misrepresented; you must not
//    claim that you wrote the original software. If you use this software
//    in a product, an acknowledgment in the product documentation would be
//    appreciated but is not required.
// 
//    2. Altered source versions must be plainly marked as such, and must not be
//    misrepresented as being the original software.
// 
//    3. This notice may not be removed or altered from any source
//    distribution.

#pragma once

#include "Physics_FourChannelHeightField.h"
#include "MathMethods.h"

FourChannelHeightField::~FourChannelHeightField()
{
}

void FourChannelHeightField::getAabb(const btTransform& t,btVector3& aabbMin,btVector3& aabbMax) const
{
	btVector3 halfExtents = (m_localAabbMax-m_localAabbMin)* m_localScaling * btScalar(0.5);

	btVector3 localOrigin(0, 0, 0);
	localOrigin[m_upAxis] = (m_minHeight + m_maxHeight) * btScalar(0.5);
	localOrigin *= m_localScaling;

	btMatrix3x3 abs_b = t.getBasis().absolute();  
	btVector3 center = t.getOrigin();
	btVector3 extent = btVector3(abs_b[0].dot(halfExtents),
		   abs_b[1].dot(halfExtents),
		  abs_b[2].dot(halfExtents));
	extent += btVector3(getMargin(),getMargin(),getMargin());

	aabbMin = center - extent;
	aabbMax = center + extent;
}

// this returns the vertex in bullet-local coordinates
void	FourChannelHeightField::getVertex(int x,int y,btVector3& vertex) const
{
	btAssert(x>=0);
	btAssert(y>=0);
	btAssert(x<m_heightStickWidth);
	btAssert(y<m_heightStickLength);

	btScalar	height = getRawHeightFieldValue(x,y);

	switch (m_upAxis)
	{
	case 0:
		{
		vertex.setValue(
			height - m_localOrigin.getX(),
			(-m_width/btScalar(2.0)) + x,
			(-m_length/btScalar(2.0) ) + y
			);
			break;
		}
	case 1:
		{
			vertex.setValue(
			(-m_width/btScalar(2.0)) + x,
			height - m_localOrigin.getY(),
			(-m_length/btScalar(2.0)) + y
			);
			break;
		};
	case 2:
		{
			vertex.setValue(
			(-m_width/btScalar(2.0)) + x,
			(-m_length/btScalar(2.0)) + y,
			height - m_localOrigin.getZ()
			);
			break;
		}
	default:
		{
			//need to get valid m_upAxis
			btAssert(0);
		}
	}

	vertex*=m_localScaling;
}

static inline int getQuantized (btScalar x) {
	if (x < 0.0) {
		return (int) (x - 0.5);
	}
	return (int) (x + 0.5);
}

/// given input vector, return quantized version
/**
  This routine is basically determining the gridpoint indices for a given
  input vector, answering the question: "which gridpoint is closest to the
  provided point?".

  "with clamp" means that we restrict the point to be in the heightfield's
  axis-aligned bounding box.
 */
void FourChannelHeightField::quantizeWithClamp(int* out, const btVector3& point,int /*isMax*/) const
{
	btVector3 clampedPoint(point);
	clampedPoint.setMax(m_localAabbMin);
	clampedPoint.setMin(m_localAabbMax);

	// Round to closest integer using the inlined function getQuantized
	out[0] = getQuantized(clampedPoint.getX());
	out[1] = getQuantized(clampedPoint.getY());
	out[2] = getQuantized(clampedPoint.getZ());
	
}

void	FourChannelHeightField::calculateLocalInertia(btScalar ,btVector3& inertia) const
{
	//moving concave objects not supported
	
	inertia.setValue(btScalar(0.),btScalar(0.),btScalar(0.));
}

void	FourChannelHeightField::setLocalScaling(const btVector3& scaling)
{
	m_localScaling = scaling;
}
const btVector3& FourChannelHeightField::getLocalScaling() const
{
	return m_localScaling;
}

// Below is modified

void FourChannelHeightField::initialize(
	int heightStickWidth, int heightStickLength, const void* heightfieldData,
	btScalar minHeight, btScalar maxHeight, int upAxis,
	int channelIndex, bool flipQuadEdges, bool diamondPattern
	)
{
	// validation
	btAssert(heightStickWidth > 1);
	btAssert(heightStickLength > 1);
	btAssert(heightfieldData != NULL);
	btAssert(minHeight <= maxHeight);
	btAssert(upAxis >= 0 && upAxis <= 2);

	// initialize member variables
	m_shapeType = TERRAIN_SHAPE_PROXYTYPE;
	m_heightStickWidth = heightStickWidth;
	m_heightStickLength = heightStickLength;
	m_minHeight = minHeight;
	m_maxHeight = maxHeight;
	m_width = (btScalar) (heightStickWidth - 1);
	m_length = (btScalar) (heightStickLength - 1);
	m_heightfieldDataUnknown = heightfieldData;
	m_channelIndex = channelIndex;
	m_flipQuadEdges = flipQuadEdges;
	m_useDiamondSubdivision = diamondPattern;
	m_upAxis = upAxis;
	m_localScaling.setValue(btScalar(1.), btScalar(1.), btScalar(1.));

	// determine min/max axis-aligned bounding box (aabb) values
	switch (m_upAxis)
	{
	case 0:
		{
			m_localAabbMin.setValue(m_minHeight, 0, 0);
			m_localAabbMax.setValue(m_maxHeight, m_width, m_length);
			break;
		}
	case 1:
		{
			m_localAabbMin.setValue(0, m_minHeight, 0);
			m_localAabbMax.setValue(m_width, m_maxHeight, m_length);
			break;
		};
	case 2:
		{
			m_localAabbMin.setValue(0, 0, m_minHeight);
			m_localAabbMax.setValue(m_width, m_length, m_maxHeight);
			break;
		}
	default:
		{
			//need to get valid m_upAxis
			btAssert(0 && "Bad m_upAxis");
		}
	}

	// remember origin (defined as exact middle of aabb)
	m_localOrigin = btScalar(0.5) * (m_localAabbMin + m_localAabbMax);
}

FourChannelHeightField::FourChannelHeightField(int heightStickWidth, int heightStickLength, void* heightfieldData, btScalar minHeight, btScalar maxHeight,int upAxis,int channelIndex, bool flipQuadEdges, bool diamondPattern) {
	initialize(heightStickWidth, heightStickLength, heightfieldData, minHeight, maxHeight, upAxis, channelIndex, flipQuadEdges, diamondPattern);
}

btScalar FourChannelHeightField::getRawHeightFieldValue(int x,int y) const {
	return m_heightfieldDataFloat[(((y * m_heightStickWidth) + x) * 4) + m_channelIndex];
}

void FourChannelHeightField::processQuad(btTriangleCallback* callback,int x,int j) const {
	btVector3 vertices[3];
	bool Checker;
	Checker = m_useDiamondSubdivision && !((j+x) & 1);
	if ((m_flipQuadEdges && !Checker) || (!m_flipQuadEdges && Checker)) {
		//first triangle
		getVertex(x,j,vertices[0]);
		getVertex(x+1,j,vertices[1]);
		getVertex(x+1,j+1,vertices[2]);
		callback->processTriangle(vertices,x,j);
		//second triangle
		getVertex(x,j,vertices[0]);
		getVertex(x+1,j+1,vertices[1]);
		getVertex(x,j+1,vertices[2]);
		callback->processTriangle(vertices,x,j);
	} else {
		//first triangle
		getVertex(x,j,vertices[0]);
		getVertex(x,j+1,vertices[1]);
		getVertex(x+1,j,vertices[2]);
		callback->processTriangle(vertices,x,j);
		//second triangle
		getVertex(x+1,j,vertices[0]);
		getVertex(x,j+1,vertices[1]);
		getVertex(x+1,j+1,vertices[2]);
		callback->processTriangle(vertices,x,j);
	}
}

void FourChannelHeightField::processAllTriangles(btTriangleCallback* callback,const btVector3& aabbMin,const btVector3& aabbMax) const {
	// scale down the input aabb's so they are in local (non-scaled) coordinates
	btVector3	localAabbMin = aabbMin*btVector3(1.f/m_localScaling[0],1.f/m_localScaling[1],1.f/m_localScaling[2]);
	btVector3	localAabbMax = aabbMax*btVector3(1.f/m_localScaling[0],1.f/m_localScaling[1],1.f/m_localScaling[2]);
	
	// account for local origin
	localAabbMin += m_localOrigin;
	localAabbMax += m_localOrigin;
	
	//quantize the aabbMin and aabbMax, and adjust the start/end ranges
	int	quantizedAabbMin[3];
	int	quantizedAabbMax[3];
	quantizeWithClamp(quantizedAabbMin, localAabbMin,0);
	quantizeWithClamp(quantizedAabbMax, localAabbMax,1);
	
	// expand the min/max quantized values
	// this is to catch the case where the input aabb falls between grid points!
	for (int i = 0; i < 3; ++i) {
		quantizedAabbMin[i]--;
		quantizedAabbMax[i]++;
	}
	
	int startX=0;
	int endX=m_heightStickWidth-1;
	int startJ=0;
	int endJ=m_heightStickLength-1;
	
	switch (m_upAxis)
	{
	case 0:
		{
			if (quantizedAabbMin[1]>startX)
				startX = quantizedAabbMin[1];
			if (quantizedAabbMax[1]<endX)
				endX = quantizedAabbMax[1];
			if (quantizedAabbMin[2]>startJ)
				startJ = quantizedAabbMin[2];
			if (quantizedAabbMax[2]<endJ)
				endJ = quantizedAabbMax[2];
			break;
		}
	case 1:
		{
			if (quantizedAabbMin[0]>startX)
				startX = quantizedAabbMin[0];
			if (quantizedAabbMax[0]<endX)
				endX = quantizedAabbMax[0];
			if (quantizedAabbMin[2]>startJ)
				startJ = quantizedAabbMin[2];
			if (quantizedAabbMax[2]<endJ)
				endJ = quantizedAabbMax[2];
			break;
		};
	default:
		{
			if (quantizedAabbMin[0]>startX)
				startX = quantizedAabbMin[0];
			if (quantizedAabbMax[0]<endX)
				endX = quantizedAabbMax[0];
			if (quantizedAabbMin[1]>startJ)
				startJ = quantizedAabbMin[1];
			if (quantizedAabbMax[1]<endJ)
				endJ = quantizedAabbMax[1];
			break;
		}
	}
	
	for(int j=startJ; j<endJ; j++) {
		for(int x=startX; x<endX; x++) {
			processQuad(callback,x,j);
		}
	}
}

void FourChannelHeightField::processTrianglesAlongLine(btTriangleCallback* callback,const btVector3& lineStart,const btVector3& lineEnd) const {
	// Divide by local scaling
	btVector3	localLineStart = lineStart * btVector3(1.0f / m_localScaling[0], 1.0f / m_localScaling[1], 1.0f / m_localScaling[2]);
	btVector3	localLineEnd = lineEnd * btVector3(1.0f / m_localScaling[0], 1.0f / m_localScaling[1], 1.0f / m_localScaling[2]);
	
	// Add the center because the array don't have any negative index
	localLineStart += m_localOrigin;
	localLineEnd += m_localOrigin;
	
	float realStartX;
	float realStartJ;
	float realEndX;
	float realEndJ;
	switch (m_upAxis) {
	case 0:
		realStartX = localLineStart.getY();
		realEndX = localLineEnd.getY();
		realStartJ = localLineStart.getZ();
		realEndJ = localLineEnd.getZ();
		break;
	case 1:
		realStartX = localLineStart.getX();
		realEndX = localLineEnd.getX();
		realStartJ = localLineStart.getZ();
		realEndJ = localLineEnd.getZ();
		break;
	default:
		realStartX = localLineStart.getX();
		realEndX = localLineEnd.getX();
		realStartJ = localLineStart.getY();
		realEndJ = localLineEnd.getY();
		break;
	}
	float DX = realEndX - realStartX;
	float DJ = realEndJ - realStartJ;
	int startX = ClampInt(0,getQuantized(MinFloat(realStartX,realEndX)) - 1,m_heightStickWidth - 1);
	int endX = ClampInt(0,getQuantized(MaxFloat(realStartX,realEndX)) + 1,m_heightStickWidth - 1);
	int startJ = ClampInt(0,getQuantized(MinFloat(realStartJ,realEndJ)) - 1,m_heightStickLength - 1);
	int endJ = ClampInt(0,getQuantized(MaxFloat(realStartJ,realEndJ)) + 1,m_heightStickLength - 1);

	if (AbsFloat(DX) < 3 && AbsFloat(DJ) < 3) {
		// Sample within AABB
		for(int j=startJ; j<endJ; j++) {
			for(int x=startX; x<endX; x++) {
				processQuad(callback,x,j);
			}
		}
	} else if (AbsFloat(DX) > AbsFloat(DJ)) {
		// Sample along X using startX and endX in the outmost loop
		for(int x = startX; x < endX; x++) { // From start to less than end so that n to n + m gives m iterations
			float VA = Lerp(realStartJ,realEndJ,InverseLerp(realStartX,realEndX,(float)x));
			float VB = Lerp(realStartJ,realEndJ,InverseLerp(realStartX,realEndX,(float)(x + 1)));
			startJ = ClampInt(0,getQuantized(MinFloat(VA,VB)) - 1,m_heightStickLength - 1);
			endJ = ClampInt(0,getQuantized(MaxFloat(VA,VB)) + 1,m_heightStickLength - 1);
			for(int j=startJ; j<endJ; j++) {
				processQuad(callback,x,j);
			}
		}
	} else {
		// Sample along J using startJ and endJ in the outmost loop
		for(int j = startJ; j < endJ; j++) { // From start to less than end so that n to n + m gives m iterations
			float VA = Lerp(realStartX,realEndX,InverseLerp(realStartJ,realEndJ,(float)j));
			float VB = Lerp(realStartX,realEndX,InverseLerp(realStartJ,realEndJ,(float)(j + 1)));
			startX = ClampInt(0,getQuantized(MinFloat(VA,VB)) - 1,m_heightStickWidth - 1);
			endX = ClampInt(0,getQuantized(MaxFloat(VA,VB)) + 1,m_heightStickWidth - 1);
			for(int x = startX; x < endX; x++) {
				processQuad(callback,x,j);
			}
		}
	}
}
