Artifact [a1adddf1a8]
Not logged in

Artifact a1adddf1a80e23c31cde7cc17e85cd0d7857d383:


<html>
<script src='matrix_vector_lib.js' ></script>

<script>

//  TODO rotate selected points
//  TODO control with zoom rotate or pan means that action is only applied to the camera not the selected points.
//  TODO clicking and dragging on a line allows you to place a point somewhere on that line.  Perhaps with the modifier key it would break up the existing line into line segments.
//  TODO when lines are deleted, readd the solo points to the solo_points list
//  TODO z for undo shift + z for redo.
//  TODO 
//  TODO drop down minimalist menu in top right of canvas.



//
//
//  Global variables
//
//  use longer more descriptive names, especially for obscure variables, to avoid conflict in the global space,
//  even if certain properties are factored into objects, if it is a large object, they work similar to globals in that exist in a large namespace accessible from many functions.
//
//  All caps indicates a constant
//  Some lower case variables may also be constants
//  Capitalized constants indicate that we expect that variable to remain a constant
//  even in future code changes, ie statically configured with an initial.
//
//



var canvas;
var origin = [0, 0, 0];
var frame_rate = 20;
var saveTimeout = 10*1000;



// to prevent camera from rotating beyond straight vertical
var vertical_camera_rotation = 0;

var zoom_scale = 2.667;  // scalar zoom property.
var zoom_dist = 1;
var last_zoom_dist = 1;
var zoom_factor = 0.83;



// camera animation
var max_move_delta = 0.01;
var max_angle_delta = Math.PI;

var delta_horizontal_angle = 0;
var delta_vertical_angle = 0;
var delta_position = [0,0,0];


//  Use to rotate selected points about a vector line
var selection_rotation_axis = null;
var rotation_center = origin.slice(0);
var zoom_center = origin.slice(0);

var selected_points_start_loc = [];





var points = []; //global
var solo_points = {};
var lines = [];

var point_projections = [];
var line_midpoint_projections = [];

var highlight_object = null;
var mouse_dragging = false;
var last_mouse_down = null;
var mouse_loc = null;



var selected_points = [];
var selected_lines = [];

var helpmsg = //"3D drawing tool\n\n" +
              "Select     Left Click\n" +
		      "Rotate     Right Click\n" +
		      "Move       wasd, qe\n" +
		      "Copy       Space\n" +
		      "Delete     x\n" +
		      "\n" +
		      "Click the red dot to create a point\n" +
			  "Spam a motion key to increase speed\n" +
			  "Drag between points to connect them\n";
	          
			  
var msg = helpmsg;


var view_transform =
    [[1, 0, 0],
     [0, 1, 0],
     [0, 0, 1]];


var key_state = {};
var key_state_augmentation_timeout = 150; // the permissible time in milliseconds since the last key event to still allow the key state to augment instead of clearing.




// constants
var MIN_DRAG_DIST = 10;
var POINT_HIGHLIGHT_DIST = 10;
var LINE_HIGHLIGHT_DIST = 15;

var MOTION_SPEED_BASE =  2.8;

var CENTER_POINT_COLOR = "rgba(250, 0, 0, 1.0)";
var AXIS_POINT_COLOR = "rgba(0, 0, 250, 1.0)";

var CENTER_POINT_RADIUS = 2.5;
var MIN_AXIS_POINT_RADIUS = 1;
var MAX_AXIS_POINT_RADIUS = 4;
var AXIS_LINE_WIDTH = 1.333;

var FORWARD_AXIS_LEN = 0.15;
var VERTICAL_AXIS_LEN = 0.075;


//  The point, line, and fill colors are the same for a reason.
//  Because all the colors are the same we don't have to worry about occlusion and z-order,
//  because no matter which order colors are painted onto a pixel, the final result will be the same.
//  Observe that this assertion holds even with a color with an alpha channel.
//  This helps us use our 2d canvas happily and not have to worry about draw order or non-sensical visual effects from wrong order.
//  With transparency we can still see each individual object and it almost mimics occlusion.
//  This is meant to be a lightweight drawing tool, not a full featured one, so this decision is limiting but fits our goals perfectly.

var POINT_COLOR = "rgba(0, 0, 0, 0.9)";
var LINE_COLOR = "rgba(0, 0, 0, 0.9)";
var FILL_COLOR = "rgba(0, 0, 0, 0.9)";

var LINE_WIDTH = 1;


function getKeyState(code){
	if(!key_state[code]) return 0;
	return key_state[code].state; }



function addKeyListener(keycode, func){
    if(!key_state[keycode]) key_state[keycode] = {};
    
    var key_obj = key_state[keycode];
    if(!key_obj.listeners) key_obj.listeners = [];
    
    var listeners = key_obj.listeners;
    listeners.push(func);
}


function keyDown(event, code){
    var time = (new Date()).getTime();
    var code = event.keyCode;
    // alert("you pressed: " + code);
        
    var key_obj = key_state[code];
    if(!key_obj) key_obj = key_state[code] = {}; // create object

    
    //  update state etc.
    
    var state = key_obj.state;
    if(state) return; //key is already pressed.
    
    state = 0;
    
    var latest = key_obj.latest;

    if(latest && time - latest < key_state_augmentation_timeout)
        state = key_obj.state = key_obj.lastState + 1;
    else
        state = key_obj.state = 1;
        
    key_obj.latest = time;
    
    key_obj.lastState = state;


    //  call listener functions 
    var listeners = key_obj.listeners
    if(!listeners) return;  //nothing to do.
      
    for(var i = 0; i < listeners.length; ++i)
        listeners[i](event, state, state); }

    
function keyUp(event){
    var time = (new Date()).getTime();
    var code = event.keyCode;
    
    var key_obj = key_state[code];
    if(!key_obj) return;  //nothing to do.
      
    key_obj.latest = time;
    key_obj.lastState = key_obj.state;
    var state = key_obj.state = 0;
    var lastState = key_obj.lastState;
    
    var listeners = key_obj.listeners;
    if(!listeners) return;  //nothing to do.
    
    for(var i = 0; i < listeners.length; ++i)
        listeners[i](event, state, lastState); }

        
        
        
function setUiEvents(){
    document.body.onkeydown = keyDown;
    document.body.onkeyup = keyUp;
    
    document.body.onmousedown = function(event){
        var x = event.pageX;
        var y = event.pageY;
        x -= canvas.offsetLeft;
        y -= canvas.offsetTop;
        last_mouse_down = [x, y];
        
        var button = event.button;
        var keycode = button + 1000;  //treat clicks like a button press but with higher keycode.
        keyDown({keyCode: keycode}); }  // it seems the keyCode of the original event cant be overwritten.
        
    document.body.onmousewheel = function(event){
        var delta = event.wheelDelta;
        
		if(delta < 0)
			zoom_dist /= zoom_factor;
		else if(delta > 0)
			zoom_dist *= zoom_factor; }
        
        
    document.body.onmouseup = function(event){
        var button = event.button;
        var keycode = button + 1000;  //treat clicks like a button press but with higher keycode.
        keyUp({keyCode: keycode});
        last_mouse_down = null;
        mouse_dragging = false; }}
        


    
function changeVelocity(direction, positive, state, lastState){
    if(state == 0){
        state = lastState;
        positive = !positive; }  // reverse the velocity
    
    var delta = Math.pow(MOTION_SPEED_BASE, state - 1) * max_move_delta / frame_rate;
    if(!positive) delta = -delta;
    
    var velocityChange = [0, 0, 0];
    velocityChange[direction] = delta;
    vector_add(delta_position, velocityChange, delta_position); }
    

	

    
function leftPress(e, s, lasts){
    changeVelocity(0, false, s, lasts); }
    
function rightPress(e, s, lasts){
     changeVelocity(0, true, s, lasts); }
     
function downPress(e, s, lasts){
    changeVelocity(1, false, s, lasts); }
    
function upPress(e, s, lasts){
    changeVelocity(1, true, s, lasts); }

function backwardPress(e, s, lasts){
    changeVelocity(2, false, s, lasts); }
    
function forwardPress(e, s, lasts){
    changeVelocity(2, true, s, lasts); }
        
        
function zoomInPress(e, s, lasts){
    zoom_dist *= zoom_factor; }
        
        
function zoomOutPress(e, s, lasts){
    zoom_dist *= zoom_factor; }


function copySelectedPoints(e, s, lasts){
    if(s){
        var new_selection = [];
        var selection_map = {};
        
        for(var i = 0; i < selected_points.length; ++i){
            selection_map[selected_points[i]] = i;
            var pt = points[selected_points[i]];
            
            var newpt = addPoint(pt);
            new_selection[i] = newpt; }
        
        //if(getKeyState(16)){  //shift + space copies lines as well.
        
        // copy lines as well
        for(var i = 0; i < lines.length; ++i){
           var line = lines[i];
           if(!line) continue;
           
           var pt1 = lines[i][0];
           var pt2 = lines[i][1];
           var i1 = selection_map[pt1];
           var i2 = selection_map[pt2];
           
           if(i1 !== undefined && i2 !== undefined){  // both points are selected
               addLine(new_selection[i1], new_selection[i2]); }}
       
        selected_points = new_selection; }}
            
            
addKeyListener(32, copySelectedPoints);        
    
addKeyListener(37, leftPress);  // arrow keys
addKeyListener(38, forwardPress);
addKeyListener(39, rightPress);
addKeyListener(40, backwardPress);


addKeyListener(65, leftPress);  // wasd
addKeyListener(87, forwardPress);
addKeyListener(68, rightPress);
addKeyListener(83, backwardPress);
addKeyListener(69, upPress);
addKeyListener(81, downPress);


addKeyListener(88, function(e, s, lasts){  // x

    if(s){
        if(highlight_object !== null && highlight_object > 0){  // delete highlighted object
            
            if(highlight_object < point_projections.length){  // point
                points[highlight_object] = null; }
                
            else if(highlight_object < point_projections.length + line_midpoint_projections.length){  // line
                lines[highlight_object - point_projections.length] = null; }
            else throw "highlight object index to large"; }
        
        else if(selected_points.length){  // delete selected points
            for(var i = 0; i < selected_points.length; ++i){
                points[selected_points[i]] = null; }
            selected_points.length = 0; }
        
        cleanupDeletedPoints();
        highlight_object = null;
        selected_points.length = 0; }});

		
//  select point
addKeyListener(1000, function(e, s, lasts){

	if(s){
		if(highlight_object !== null){
			if(highlight_object == -1)
				highlight_object = addPoint(origin);  // create a new point at the origin
				
			
			var alreadySelected = false;  // only set for shift clicks
			
			if(getKeyState(16)){  // shift key is pressed.
			
				for(var i = 0; i < selected_points.length; ++i){
					if(selected_points[i] == highlight_object){
					   selected_points.splice(i, 1); // deselect point
					   alreadySelected = true; 
					   break; }}}
			else{
				selected_points.length = 0;}
				
			if(!alreadySelected && highlight_object < points.length) selected_points.push(highlight_object); }

		else if(!getKeyState(16))
			selected_points.length = 0; }
		
		
	else if(lasts && mouse_dragging ){  // drag actions
		
		//  connect selected points to highlight point with lines
		if(selected_points.length && (!getKeyState(16))){  //  TODO right now this really only works for drawing a single line, 
		
			if(highlight_object !== null && highlight_object < point_projections.length){
				if(highlight_object == -1) highlight_object = addPoint(origin);
				
				for(var i = 0; i < selected_points.length; ++i){
					var pt = selected_points[i];
					if(pt == highlight_object) continue;
					addLine(pt, highlight_object); }
				selected_points.length = 0; }}
			
		// select points inside selection rectangle
		else if(mouse_loc && last_mouse_down){ 
		
			var minx = Math.min(mouse_loc[0], last_mouse_down[0]);
			var maxx = Math.max(mouse_loc[0], last_mouse_down[0]);
			var miny = Math.min(mouse_loc[1], last_mouse_down[1]);
			var maxy = Math.max(mouse_loc[1], last_mouse_down[1]);
			
			
			var selected_point_map = {};             
			
			if(!getKeyState(16)){
				selected_points.length = 0;
				selected_lines.length = 0; }
			else{
				for(var i = 0; i < selected_points.length; ++i){
					selected_point_map[selected_points[i]] = i; }}
			
			for(var i = 0; i < point_projections.length; ++i){
				if(selected_point_map[i]) continue; // already selected.
				
				var pt = point_projections[i];
				if(!pt) continue;
				var _x = pt[0];
				var _y = pt[1];
				
				if(minx < _x && _x < maxx
				 && miny < _y && _y < maxy){
				   selected_points.push(i); }}}                
        }});


// right click
addKeyListener(1002, function(e, s, lasts){
	if(s == 0){
		delta_horizontal_angle = 0;
		delta_vertical_angle = 0; }
		
	else if(getKeyState(16)){  // use default as rotation center
		rotation_center = origin.slice(0); }
		
	else if(highlight_object > 0){  // use highlighted points for rotation center.
		if(highlight_object < points.length){
			rotation_center = points[highlight_object].slice(0); }
			
		else{
			var line = lines[highlight_object];
			var pointa = points[line[0]];
			var pointb = points[line[1]];
			rotation_center = vector_midpoint(pointa, pointb);
			selection_rotation_axis = vector_minus(pointa, pointb);
			if(vector_dot(selection_rotation_axis, view_transform[2]) < 0){
				vector_scale(-1, selection_rotation_axis, selection_rotation_axis); }}}  // axis should be pointing vertical, horizontal motions along the screen will dictate motion angle.
	
	else if(selected_points.length){  //find average of selected points for rotation center
		var rotation_center = [0,0,0];
	    for(var i = 0; i < selected_points.length; ++i){
			vector_add(rotation_center, selected_points[i], rotation_center); }
		var l = selected_points.length;
		rotation_center = [rotation_center[0]/l, rotation_center[1]/l, rotation_center[2]/l];
		}});


function writeMsg(canvas, msg){
	var lines = msg.split("\n");
	var ctx = canvas.getContext("2d");
	ctx.font = "9pt sans-serif"
	for(var i = 0; i < lines.length; ++i){
		ctx.fillText(lines[i], 5, 10 + 16 *  i); }}

    
//  camera functions

function rotateView(norm, theta, cameracentric){

    // camera centric uses the camera axes to perform the rotation instead of the space axes.   
    if(cameracentric) norm = matrix_mult(view_transform, [norm])[0];
    var rotation = vector_rotation(norm, theta);
    
    view_transform = matrix_mult(rotation, view_transform); }
	
	
function rotatePoint(point, axis, angle, center){
}
    
    
    
function rotateHorizontal(theta){
    rotateView([0, 1, 0], theta, false); }
    
function rotateVertical(theta){
    if(vertical_camera_rotation + theta > Math.PI/2)
        theta = Math.PI/2 - vertical_camera_rotation;
        
    if(vertical_camera_rotation + theta < -Math.PI/2)
        theta = -Math.PI/2 - vertical_camera_rotation;
        
    vertical_camera_rotation += theta;
    
    rotateView([1, 0, 0], theta, true); }
    
    
function moveCamera(offset, cameracentric){
    if(cameracentric) offset = matrix_mult(view_transform, [offset])[0];
    //alert("offset: " + offset);
    vector_add(origin, offset, origin); }
    

// converts a point from three space to the canvas plane.
// Note: because of depth perspective, this conversion is not
// easy to define if the point lies behind the camera.
// There are two options:
// When drawing a line, another colinear point in front of the camera may be provided
// to help find an alertnate point.
// if both points lie behind the camera or the colinear_point is not provided,
// this function will return null.
 
function project(canvas, xyz, view_transform, origin, colinear_point){
    if(!xyz) return null;  // point has been deleted or does not exist
    
    var w = canvas.width;
    var h = canvas.height;
    
    var scale = Math.min(w, h);
    
    var v = xyz.slice(0);
    if(origin) v = vector_minus(v, origin, v);
    
    var z = vector_dot(view_transform[2], v);
    
    if(z <= -zoom_dist){
        if(!colinear_point) return null;
        
        var v2 = colinear_point.slice(0);
        if(origin) vector_minus(v2, origin, v2);
        
        var z2 = vector_dot(view_transform[2], v2);
        
        if(z2 < 0) return null;
        
        // get the coefficients for a complex combination.
        // t*z + (1-t)*z2 = 0.0002  -- z of new point is just barely infront of the camera.
        
        var t = (0.0002 - z2)/(z - z2);  // no division by zero, z is negative, z2 is positive
        
        vector_add(vector_scale(v, t, v),
                   vector_scale(v2, 1-t, v2),
                   v);
                   
        z = vector_dot(view_transform[2], v); }

        
    var scale2 = zoom_scale * scale / (zoom_dist + z);
    
    return [ scale2 * vector_dot(view_transform[0], v) + 0.5 * w,
             scale2 * vector_dot(view_transform[1], v) + 0.5 * h ]; }
   

   
//  removes deleted points and lines
//  works with global objects.

function cleanupDeletedPoints(){
    var newpoints = [];
    var newlines = [];
    var pointmap = {};
    
    var j = 0;
    
    for(var i = 0; i < points.length; ++i){
       
       if(points[i]){
           newpoints.push(points[i]);
           pointmap[i] = j;
           ++j; }
           
       else{
           pointmap[i] = -1; }}
    
    
    for(var i = 0; i < lines.length; ++i){
        if(!lines[i]) continue;
        var a = lines[i][0];
        var b = lines[i][1];
        
        if(pointmap[a] != -1 && pointmap[b] != -1){
            newlines.push([ pointmap[a], pointmap[b] ]); }}
    
    points = newpoints;
    lines = newlines; }
        

function addPoint(pt){
    points.push(pt.slice(0));
    var index = points.length - 1;
    solo_points[index] = true;
    return index; }
    
    
function addLine(pt0, pt1){
    delete solo_points[pt0];
    delete solo_points[pt1];
    lines.push([pt0, pt1]);
    return lines.length - 1; }    
    
    
    
function draw(canvas){
    var ctx = canvas.getContext('2d');
    var w = canvas.width;
    var h = canvas.height;
    
    // ctx.fillStyle = "rgba(100, 100, 100, .05)";
    
    
    ctx.beginPath();
    
    for(var i = 0; i < lines.length; ++i){
        var line = lines[i];
        if(!line) continue;
        //draw line
        
        var pt0 = points[line[0]];
        var pt1 = points[line[1]];
            
        var _pt0 = point_projections[line[0]];
        var _pt1 = point_projections[line[1]];
        
        //  finish the line even if one point is on wrong side of viewer.
        if(!_pt0 && _pt1){
            _pt0 = project(canvas, pt0, view_transform, origin, pt1); }
        else if(_pt0 && !_pt1){
            _pt1 = project(canvas, pt1, view_transform, origin, pt0); }
            
        if(!_pt0 || !_pt1) continue;
        
        var x0 = _pt0[0];
        var y0 = _pt0[1];

        var x1 = _pt1[0];
        var y1 = _pt1[1];
        
        ctx.moveTo(x0, y0);
        ctx.lineTo(x1, y1); }
    
    ctx.clearRect(0, 0, w, h);
	
    
	ctx.strokeStyle = "rgba(0, 0, 0, 0.9)";
    ctx.stroke();
    
	ctx.fillStyle = "rgba(0, 0, 0, 0.9)";
	
    for(var k in solo_points){
       var pt = point_projections[k];
       if(pt) ctx.fillRect(pt[0] - 2, pt[1] - 2, 4, 4); }
        
	//
	//  The following drawing of axes is to help provide an perspective
	//  The nuances of this draw behavior are created to provide visual cues for interpreting perspective and depth.
	//  
	//  Because we use a 2d canvas library for the drawing the rest of the points/shapes after projection, these visual information nuances are important.
	//

	// axis lines and dots
	
    var faxis_pt = project(canvas, vector_add(origin, [0, 0, FORWARD_AXIS_LEN]), view_transform, origin);
	var vaxis_pt = project(canvas, vector_add(origin, [0, -VERTICAL_AXIS_LEN, 0]), view_transform, origin);
	
	ctx.fillStyle = AXIS_POINT_COLOR;
	
	var fdot = vector_dot(view_transform[2], [0, 0, 1]);
	
	var a = MIN_AXIS_POINT_RADIUS;  //random letters for intermediate computations
	var b = MAX_AXIS_POINT_RADIUS;
	var c = (a+b)/2;
	var d = (b-a)/2;
	
	var fr = c - d * fdot;
	var vdot = vector_dot(view_transform[2], [0, -1, 0]);
	var vr = c - d * vdot;
	
	ctx.lineWidth = AXIS_LINE_WIDTH;
	ctx.beginPath();
	
	if(fdot >=0 && faxis_pt){ // occlude this axis, draw first
		ctx.moveTo(w/2, h/2);
		ctx.lineTo(faxis_pt[0], faxis_pt[1]);	
		ctx.fillRect(faxis_pt[0] - fr, faxis_pt[1] - fr, 2*fr, 2*fr); }
		
	if(vdot >=0 && vaxis_pt){ // occlude this axis, draw first
		ctx.moveTo(w/2, h/2);
		ctx.lineTo(vaxis_pt[0], vaxis_pt[1]);	
		ctx.fillRect(vaxis_pt[0] - vr, vaxis_pt[1] - vr, 2*vr, 2*vr); }
	
	ctx.stroke();
	
		
	// draw center red square
	ctx.fillStyle = CENTER_POINT_COLOR;
	var cr = CENTER_POINT_RADIUS;
	ctx.fillRect(w/2 - cr, h/2 - cr, 2*cr, 2*cr);
		
	ctx.fillStyle = AXIS_POINT_COLOR;
	
	
	if(fdot < 0 && faxis_pt){
		ctx.beginPath();
		ctx.moveTo(w/2, h/2);
		ctx.lineTo(faxis_pt[0], faxis_pt[1]);
		ctx.stroke();
		ctx.fillRect(faxis_pt[0] - fr, faxis_pt[1] - fr, 2*fr, 2*fr); }
		
	if(vdot < 0 && vaxis_pt){
		ctx.beginPath();
		ctx.moveTo(w/2, h/2);
		ctx.lineTo(vaxis_pt[0], vaxis_pt[1]);
		ctx.stroke();
		ctx.fillRect(vaxis_pt[0] - vr, vaxis_pt[1] - vr, 2*vr, 2*vr); }
	

	// reset line width
	ctx.lineWidth = LINE_WIDTH;
	
	

    
		
	
	for(var i = 0; i < selected_points.length; ++i){
		var pt;
		
		if(selected_points[i] == -1)
			pt = [w/2, h/2];
		else pt = point_projections[selected_points[i]];
		
		ctx.fillStyle = POINT_COLOR;
		if(pt) ctx.fillRect(pt[0] - 4, pt[1] - 4, 8, 8); }
	
	
	if(highlight_object !== null){
		
		
		if(highlight_object < point_projections.length){
			var pt;
			if(highlight_object == -1)
				pt = [w/2, h/2];
			else pt = point_projections[highlight_object];
			
			ctx.fillStyle = "rgba(50, 50, 50, .6)";    
			ctx.fillRect(pt[0] - 4, pt[1] - 4, 8, 8);  // TODO getting a error here that pt is null 
			document.body.style.cursor = "hand"; }
			
		else if(highlight_object < point_projections.length + line_midpoint_projections.length){
			// alert("drawing highlighted line");
			
			var line = lines[highlight_object - point_projections.length];
			if(line){
				var pt1 = point_projections[line[0]];
				var pt2 = point_projections[line[1]];
				
				if(pt1 && pt2){
				
					ctx.beginPath();
					
					ctx.moveTo(pt1[0], pt1[1]);
					ctx.lineTo(pt2[0], pt2[1]);
					ctx.lineWidth = 3;
					ctx.stroke();
					ctx.lineWidth = 1; }}}
			
		else{
			throw "highlight object index to large"; }}
		
	else{
		document.body.style.cursor = "crosshair"; }
	
	if(mouse_dragging){
	
		if(selected_points.length && !getKeyState(16)){  // if shift is held, we are selecting more points.
			if(mouse_loc && getKeyState(1000)){
				ctx.beginPath();
				var pt = point_projections[selected_points[0]];
				if(pt){
					ctx.moveTo(mouse_loc[0], mouse_loc[1]);
					ctx.lineTo(pt[0], pt[1]); }
				ctx.stroke(); }}
				
		else if(mouse_loc && last_mouse_down){  
		
		
		    if(getKeyState(1000)){     // select points inside square
				var minx = Math.min(mouse_loc[0], last_mouse_down[0]);
				var maxx = Math.max(mouse_loc[0], last_mouse_down[0]);
				var miny = Math.min(mouse_loc[1], last_mouse_down[1]);
				var maxy = Math.max(mouse_loc[1], last_mouse_down[1]);
				ctx.beginPath();
				ctx.rect(minx, miny, maxx - minx, maxy - miny);
				ctx.stroke(); }}
	}
    
    ctx.fillStyle = "rgb(0,0,0)";
	writeMsg(canvas, msg); }

    
    
window.onload = function(){

    // load localStorage saved state.
    if(localStorage.points && localStorage.lines){
        points = JSON.parse(localStorage.points);
        lines = JSON.parse(localStorage.lines); }
    
    canvas = document.createElement('canvas');
    document.body.appendChild(canvas);
    
    canvas.width = window.innerWidth - 20;
    canvas.height = window.innerHeight - 20;
    
    
    window.onresize = function(){
        canvas.width = window.innerWidth - 20;
        canvas.height = window.innerHeight - 20; }

    
    
    function getRotationAngle(x, size, max, center_size){

        if(!center_size) center_size = 0.05;  // the proportional size of the area in which no rotation is effected by the mouse movement
        if(!max) max = Math.PI/128;
        
        //  center does nothing
        if(Math.abs(x) < size * center_size/2) x = 0;
        else if(x < 0) x += size * center_size/2;
        else           x -= size * center_size/2;
        
        return max * x / ((1 - center_size) * size/2); }
        
    
    document.body.onmousemove = function(event){
    //var test = function(event){

        var x = event.pageX;
        var y = event.pageY;
        x -= canvas.offsetLeft;
        y -= canvas.offsetTop;
        mouse_loc = [x, y]

        var w = canvas.width;
        var h = canvas.height;
        
        if(!mouse_dragging && last_mouse_down){
            var _x = x - last_mouse_down[0];
            var _y = y - last_mouse_down[1];
            
            var dist2 = _x*_x + _y*_y;
            
            if(dist2 > MIN_DRAG_DIST * MIN_DRAG_DIST){
                mouse_dragging = true; }}
                

				
	    if(getKeyState(1002) && last_mouse_down){
			delta_horizontal_angle = getRotationAngle(x - last_mouse_down[0], w, max_angle_delta/frame_rate, 0);
			delta_vertical_angle = -getRotationAngle(y - last_mouse_down[1], h, max_angle_delta/frame_rate, 0); }
			
			
		var min_point_dist2 = LINE_HIGHLIGHT_DIST * LINE_HIGHLIGHT_DIST;
		highlight_object = null;
		
		var _x = canvas.width/2 - x;
		var _y = canvas.height/2 - y;
		var point_dist = _x*_x + _y*_y;
		
		if(point_dist < POINT_HIGHLIGHT_DIST * POINT_HIGHLIGHT_DIST){
			highlight_object = -1;
			min_point_dist = point_dist; }
			
			
		for(var i = 0; i < line_midpoint_projections.length; ++i){
			var pt = line_midpoint_projections[i];
			if(!pt) continue;
			
			var _x = pt[0] - x;
			var _y = pt[1] - y;
			point_dist = _x*_x + _y*_y;
			
			if(point_dist < min_point_dist2){  // alert('highlighting line');
				highlight_object = i + point_projections.length;
				min_point_dist = point_dist; }}
				
		min_point_dist2 = Math.min( min_point_dist2, POINT_HIGHLIGHT_DIST * POINT_HIGHLIGHT_DIST);
			
		for(var i = 0; i < point_projections.length; ++i){
			var pt = point_projections[i];
			if(!pt) continue;
			
			var _x = pt[0] - x;
			var _y = pt[1] - y;
			point_dist = _x*_x + _y*_y;
			
			if(point_dist < min_point_dist2){
				highlight_object = i;
				min_point_dist = point_dist; }}
    }
 
    setUiEvents();     
        
    document.body.oncontextmenu = function(){
        return false; };
   
    
    // draw(canvas);
    // var ctx = canvas.getContext('2d');
    // ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 
    
    
    function animateLoop(){
        
		if(selected_points.length && !getKeyState(1002)){  // move selection if exists
			for(var i = 0; i < selected_points.length; ++i){
				var pt = points[selected_points[i]];
				vector_add(pt, delta_position, pt); }}
		
		else{
			moveCamera(delta_position, false); }
      
        if(delta_horizontal_angle) rotateHorizontal(delta_horizontal_angle);
        if(delta_vertical_angle) rotateVertical(delta_vertical_angle);
        
       
        //  overwrite point projections
        //  TODO this may not be perfect if points are deleted etc.        
        point_projections.length = 0;
        for(var i = 0; i < points.length; ++i){
            point_projections[i] = project(canvas, points[i], view_transform, origin); }
            
        line_midpoint_projections.length = 0;
        
        for(var i = 0; i < lines.length; ++i){
            var line = lines[i];
            if(!line){
                line_midpoint_projections[i] = null;
                continue; }
                
            var pt1 = point_projections[line[0]];
            var pt2 = point_projections[line[1]];
            if(pt1 && pt2){
                line_midpoint_projections[i] = [(pt1[0] + pt2[0])/2, (pt1[1] + pt2[1])/2]; }
            else{
                line_midpoint_projections[i] = null; }}
            

        draw(canvas);
    }
    setInterval(animateLoop, 1000/frame_rate);
    
    var saveAction = function(){
        localStorage.points = JSON.stringify(points);
        localStorage.lines = JSON.stringify(lines);
    }
        
    setInterval(saveAction, saveTimeout);
}


</script>


<body></body>
</html>