Hw4 helper

by j91157j91157

HTML

<div id="info">Homework 4 Helper<br>Right click add a point
  <br><button id="reset" style="width:20%">RESET</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/84/three.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<!-- the following disable the regular right-button click -->
<script type="text/javascript">
  document.oncontextmenu = function() {
    return false;
  }

</script>

CSS

#info {
  position: absolute;
  top: 0px;
  width: 100%;
  padding: 10px;
  text-align: center;
  color: #ffff00
}

body {
  overflow: hidden;
}

JavaScript

var camera, scene, renderer;
var mouse = new THREE.Vector2();
var point;
var points = [];
var halfSize = 50;
var xct = 0, yct = 0, avecounter = 0;
var covxx = 0, covxy = 0, covyy = 0;

init();
animate();

$('#reset').click (function() {
	scene.remove (scene.getObjectByName ('aabb'));  
  points.forEach (function(point) {
  	scene.remove(point)
  })
  points=[];
  avecounter = 0;
  xct = 0;
  yct = 0;
  covxx = 0;
  covxy = 0;
  covyy = 0;
})

function make_OBB() {
 scene.remove (scene.getObjectByName ('aabb'));  
  let minX = 1e3, maxX = -1e3;
  let minY = 1e3, maxY = -1e3;
  var avex = xct / avecounter;
  var avey = yct / avecounter;
  
  for (let i = 0; i < points.length; i++) {
  	covxx += ((points[i].position.x - avex) * (points[i].position.x - avex));
  	covxy += ((points[i].position.x - avex) * (points[i].position.y - avey));
  	covyy += ((points[i].position.y - avey) * (points[i].position.y - avey));
  }
  covxx /= (avecounter - 1);
  covxy /= (avecounter - 1);
  covyy /= (avecounter - 1);
  
  
  //////////轉成單位向量//////////
  let x = covxx;
  //if(x > covxy) x = covxy;
  //if(x > covyy) x = covyy;
  if(x < 1){
  	x = 1 / x;
    if(x < 0) x = -x;
    covxx *= x;
    covxy *= x;
    covyy *= x;
  }
  var covxx2 = covxx * covxx;
  var covxy2 = covxy * covxy;
  var covyy2 = covyy * covyy;
  
  
  var PC1x, PC1y, PC2x, PC2y;
  var newx, newy;
  var lambda1 = -(Math.sqrt(covyy2-2*covxx*covyy+4*covxy2+covxx2)-covyy-covxx)/2 ;
  var lambda2 = (Math.sqrt(covyy2-2*covxx*covyy+4*covxy2+covxx2)+covyy+covxx)/2;
  
  PC1x = 1;
  if(lambda1 > lambda2) PC1y = -(Math.sqrt(covyy2-2*covxx*covyy+4*covxy2+covxx2)-covyy+covxx)/(2*covxy);
  else PC1y = (Math.sqrt(covyy2-2*covxx*covyy+4*covxy2+covxx2)+covyy-covxx)/(2*covxy);
  //////////將PC1轉成單位向量//////////
  let t = PC1x * PC1x + PC1y * PC1y;
  if(t > 0){
  	t = Math.sqrt(1/t);
    PC1x *= t;
    PC1y *= t;
  }
  
  //////////根據右手定則求出(0,0,1)與(PC1x, PC1y, 0)的外積,也就是PC2//////////
  PC2x = -1 * PC1y;
  PC2y = PC1x;
  
 ...