Blob Blame Raw

#include "perspectivesandboxview.h"


View::PointPtr
	persp_p0,
	persp_px,
	persp_py,
	persp_p1,
	bounds_p0,
	bounds_p1;

PerspectiveSandBoxView::PerspectiveSandBoxView():
	persp_p0  (new View::Point( Vector2(-1, -1) )),
	persp_px  (new View::Point( Vector2( 1, -1) )),
	persp_py  (new View::Point( Vector2(-1,  1) )),
	persp_p1  (new View::Point( Vector2( 1,  1) )),
	bounds_p0 (new View::Point( Vector2(-2, -2) )),
	bounds_p1 (new View::Point( Vector2( 2,  2) ))
{
	transform.scale(50, 50);
	points.push_back(persp_p0);
	points.push_back(persp_px);
	points.push_back(persp_py);
	points.push_back(persp_p1);
	points.push_back(bounds_p0);
	points.push_back(bounds_p1);
}

void
PerspectiveSandBoxView::draw_grid(
	const Cairo::RefPtr<Cairo::Context> &context,
	const Matrix &matrix,
	const Color &color )
{
	const int count = 100;
	const int subcount = 10;

	const Real ps = get_pixel_size();

	for(int i = -count; i < count; ++i) {
		for(int j = -count; j < count; ++j) {
			Vector4 src(i/(Real)subcount, j/(Real)subcount, 0, 1);
			Vector4 dst = matrix*src;
			Real w = dst.w;
			if (w > real_precision) {
				Vector2 pos(dst.x/w, dst.y/w);
				
				Real ka = clamp(1/w, 0, 1);
				
				Real a = color.a*ka;
				Real r = 4*ps;
				if (i) r *= 0.5;
				if (j) r *= 0.5;
				if (i % 10) r *= 0.75;
				if (j % 10) r *= 0.75;
				context->set_source_rgba(color.r, color.g, color.b, a);
				context->arc(pos.x, pos.y, r, 0, 2.0*M_PI);
				context->fill();
			}
		}
	}
}

void
PerspectiveSandBoxView::draw_line(
	const Cairo::RefPtr<Cairo::Context> &context,
	const Pair2 &bounds,
	Real a,
	Real b,
	Real c,
	const Color &color )
{
	
}

void
PerspectiveSandBoxView::on_draw_view(const Cairo::RefPtr<Cairo::Context> &context) {
	context->save();

	const Real ps = get_pixel_size();
	context->set_line_width(ps);

	Vector2 p0 = persp_p0->position;
	Vector2 px = persp_px->position;
	Vector2 py = persp_py->position;
	Vector2 p1 = persp_p1->position;
	
	Pair2 bounds(bounds_p0->position, bounds_p1->position);
	
	
	// perspective matrix
	Matrix matrix;
	{
		Vector2 A = px - p1;
		Vector2 B = py - p1;
		Vector2 C = p0 + p1 - px - py;
		
		Real cw = A.y*B.x - A.x*B.y;
		Real aw = B.x*C.y - B.y*C.x;
		Real bw = A.y*C.x - A.x*C.y;
		
		Vector2 c = p0*cw;
		Vector2 a = px*(cw + aw) - c;
		Vector2 b = py*(cw + bw) - c;

		matrix.row_x() = Vector4(a, 0, aw);
		matrix.row_y() = Vector4(b, 0, bw);
		matrix.row_w() = Vector4(c, 0, cw);
	}

	draw_grid(context, matrix, Color(0, 1, 0, 1));

	// draw frames
	context->set_source_rgba(0, 0, 1, 0.75);
	context->move_to(p0.x, p0.y);
	context->line_to(px.x, px.y);
	context->line_to(p1.x, p1.y);
	context->line_to(py.x, py.y);
	context->close_path();
	context->stroke();

	context->move_to(bounds.p0.x, bounds.p0.y);
	context->line_to(bounds.p1.x, bounds.p0.y);
	context->line_to(bounds.p1.x, bounds.p1.y);
	context->line_to(bounds.p0.x, bounds.p1.y);
	context->close_path();
	context->stroke();
	
	context->restore();
}