/* Copyright (c) 2011 Artjom Popov */


#import "UTGeometry.h"

CGPoint UTGeometryClampPoint(CGPoint v, CGFloat min, CGFloat max)
{
	CGFloat x = ((v.x > max) ? max : ((v.x < min) ? min : v.x));
	CGFloat y = ((v.y > max) ? max : ((v.y < min) ? min : v.y));
	return CGPointMake(x, y);
}

CGFloat UTGeometryClampFloat(CGFloat v, CGFloat min, CGFloat max)
{
	return ((v > max) ? max : ((v < min) ? min : v));
}

CGRect UTGeometryAlignedRectangle(CGSize viewport, CGSize viewbox, CGPoint focus, float scale, CGSize minbox)
{
	CGRect rect = CGRectZero;
	
	float a = viewport.width / viewport.height;
	float b = viewbox.width / viewbox.height;
	
	focus = UTGeometryClampPoint(focus, -1.0F, 1.0F);
	scale = UTGeometryClampFloat(scale, 0.0F, 1.0F);
	
	// Harmonize the aspect ratio & scale & ensure minimum size
	if(a >= b) {
		rect.size.width = viewbox.width * scale;
		if(rect.size.width < minbox.width) rect.size.width = (viewbox.width < minbox.width) ? viewbox.width : minbox.width;
		rect.size.height = rect.size.width / a;
	} else {
		rect.size.height = viewbox.height * scale;
		if(rect.size.height < minbox.height) rect.size.height = (viewbox.height < minbox.height) ? viewbox.height : minbox.height;
		rect.size.width = rect.size.height * a;
	}
	
	// Center
	rect.origin.x = (viewbox.width - rect.size.width) * 0.5F;
	rect.origin.y = (viewbox.height - rect.size.height) * 0.5F;
	
	// Focus
	if(!CGPointEqualToPoint(focus, CGPointZero)) {
		rect.origin.x += focus.x * 0.5F * viewbox.width;
		rect.origin.y += focus.y * 0.5F * viewbox.height;
	}
	
	if(rect.origin.x < 0.0F) {
		rect.origin.x = 0.0F;
	} else if(rect.origin.x + rect.size.width > viewbox.width) {
		rect.origin.x = viewbox.width - rect.size.width;
	}
	if(rect.origin.y < 0.0F) {
		rect.origin.y = 0.0F;
	} else if(rect.origin.y + rect.size.height > viewbox.height) {
		rect.origin.y = viewbox.height - rect.size.height;
	}
	
	
	return rect;
}

CGAffineTransform UTGeometryTransform(CGRect a, CGRect b) 
{
	return 	CGAffineTransformMake(b.size.width / a.size.width, 0.0F, 0.0F, b.size.height / a.size.height, -a.origin.x * b.size.width / a.size.width + b.origin.x, -a.origin.y * b.size.height / a.size.height + b.origin.y);
}

CGSize UTGeometryAspectFitSize(CGSize originalSize, CGSize sizeToFit)
{
	CGSize size = CGSizeZero;
	float a = originalSize.width / originalSize.height;
	float b = sizeToFit.width / sizeToFit.height;
	
	if(a >= b) {
		size.width = sizeToFit.width;
		size.height = size.width / a;
	} else {
		size.height = sizeToFit.height;
		size.width = size.height * a;
	}
	
	return size;
	
}






