// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//
ofVec3f MousePosOnPlane::getMousePosOnPlane( float _mouseX, float _mouseY, ofVec3f _planeNormal, ofVec3f _pointOnPlane,
						   ofMatrix4x4* _modelViewMatrix, ofMatrix4x4* _projectionMatrix, ofRectangle* _viewPort )
{
	ofMatrix4x4 modelViewMat;
	ofMatrix4x4 projectionMat;
	GLint viewport[4];
	
	if( _modelViewMatrix == NULL ) { glGetFloatv(GL_MODELVIEW_MATRIX, modelViewMat.getPtr() ); }
	else { modelViewMat.set( *_modelViewMatrix ); }
	
	if( _projectionMatrix == NULL ) { glGetFloatv(GL_PROJECTION_MATRIX, projectionMat.getPtr() );	 }
	else { projectionMat.set( *_projectionMatrix ); }
	
	
	if( _viewPort == NULL )
	{
		glGetIntegerv(GL_VIEWPORT, viewport);
	}
	else
	{
		viewport[0] = _viewPort->x;
		viewport[1] = _viewPort->y;
		viewport[2] = _viewPort->width;
		viewport[3] = _viewPort->height;
	}
	
	float dx, dy, dz = 0.0;
	ofVec3f mouseRayPosition;
	ofVec3f mouseRayVector;
	
	int ry = viewport[3] - _mouseY - 1;
	
	gluES::gluUnProject( _mouseX, ry, 0.0,
						modelViewMat.getPtr(), projectionMat.getPtr(), viewport,
						&mouseRayPosition.x, &mouseRayPosition.y, &mouseRayPosition.z);
	
	gluES::gluUnProject( _mouseX, ry, 1.0,
						modelViewMat.getPtr(), projectionMat.getPtr(), viewport,
						&mouseRayVector.x, &mouseRayVector.y, &mouseRayVector.z);
	
	mouseRayVector -= mouseRayPosition;
	mouseRayVector.normalize();
	
	float planeDistance = getPlaneDistance( &_planeNormal, &_pointOnPlane );
	float tmpDist = rayIntersectPlane( &_planeNormal, planeDistance, &mouseRayPosition, &mouseRayVector );
	
	return mouseRayPosition + (mouseRayVector * tmpDist);

	
}
OSMAND_CORE_API bool OSMAND_CORE_CALL OsmAnd::Utilities_OpenGL_Common::lineSegmentIntersectPlane( const glm::vec3& planeN, const glm::vec3& planeO, const glm::vec3& line0, const glm::vec3& line1, glm::vec3& lineX )
{
    const auto line = line1 - line0;
    const auto lineD = glm::normalize(line);
    float d;
    if(!rayIntersectPlane(planeN, planeO, lineD, line0, d))
        return false;

    // If point is not in [line0 .. line1]
    if(d < 0.0f || d > glm::length(line))
        return false;

    lineX = line0 + d*lineD;
    return true;
}