#include "3dutils.h"
#include <d3d9.h>
#include <D3dx9.h>
#include <windows.h>

//returns true if there was an intersection, false if there wasn't
bool FindClickedFace(LPDIRECT3DDEVICE9 pd3dDevice, int WindowWidth, int WindowHeight, LPD3DXMESH CheckMesh, POINT ptCursor, DWORD& FaceHit /*out*/)
{
	D3DXVECTOR3 vPickRayDir;
	D3DXVECTOR3 vPickRayOrig;

	// Get the pick	ray	from the mouse position

	D3DXMATRIX matProj;
	pd3dDevice->GetTransform(D3DTS_PROJECTION, &matProj );

	// Compute the vector of the pick ray in screen	space
	D3DXVECTOR3	v;
	v.x	=  ( ( ( 2.0f *	ptCursor.x ) / WindowWidth	) -	1 )	/ matProj._11;
	v.y	= -( ( ( 2.0f *	ptCursor.y ) / WindowHeight	) -	1 )	/ matProj._22;
	v.z	=  1.0f;

	// Get the inverse view	matrix
	D3DXMATRIX matView,	m;
	pd3dDevice->GetTransform(D3DTS_VIEW,&matView );
	D3DXMatrixInverse( &m, NULL, &matView );

	// Transform the screen	space pick ray into	3D space
	vPickRayDir.x  = v.x*m._11 + v.y*m._21 + v.z*m._31;
	vPickRayDir.y  = v.x*m._12 + v.y*m._22 + v.z*m._32;
	vPickRayDir.z  = v.x*m._13 + v.y*m._23 + v.z*m._33;
	vPickRayOrig.x = m._41;
	vPickRayOrig.y = m._42;
	vPickRayOrig.z = m._43;


	// Get the picked triangle
	LPD3DXBASEMESH			pMesh =	CheckMesh;
	LPDIRECT3DVERTEXBUFFER9	pVB;
	LPDIRECT3DINDEXBUFFER9	pIB;

	pMesh->GetVertexBuffer(	&pVB );
	pMesh->GetIndexBuffer( &pIB	);

	WORD*	   pIndices;
	StandardVertex*  pVertices;

	pIB->Lock( 0,0,(void**)&pIndices, 0	);
	pVB->Lock( 0,0,(void**)&pVertices, 0 );


	// When	calling	D3DXIntersect, one can get just	the	closest	intersection and not
	// need	to work	with a D3DXBUFFER.	Or,	to get all intersections between the ray and 
	// the mesh, one can use a D3DXBUFFER to receive all intersections.	 We	show both
	// methods.

	// Collect only	the	closest	intersection
	BOOL bHit;
	DWORD dwFace;
	//FLOAT fBary1, fBary2, fDist;
	D3DXIntersect(pMesh, &vPickRayOrig,	&vPickRayDir, &bHit, &dwFace, NULL, NULL, NULL,	
		NULL, NULL);
	if(	bHit )
	{
		FaceHit = dwFace;
	}

	pVB->Unlock();
	pIB->Unlock();

	pVB->Release();
	pIB->Release();

	return (bHit!=0);
}