import * as THREE from "three";


let convertTool = {
  getPos2d: function (point, camera, dom) {//获取一个三维坐标对应屏幕中的二维坐标
    if (!camera) return
    var pos = point.clone().project(camera)	//比之前hotspot的计算方式写得简单  project用于3转2(求法同shader)； unproject用于2转3 :new r.Vector3(e.x, e.y, -1).unproject(this.camera);

    var x, y;
    x = (pos.x + 1) / 2 * dom.clientWidth;
    y = (1 - (pos.y + 1) / 2) * dom.clientHeight;

    var inSight = x <= dom.clientWidth && x >= 0    //是否在屏幕中   
      && y <= dom.clientHeight && y >= 0


    return {
      pos: new THREE.Vector2(x, y),  // 屏幕像素坐标
      vector: pos,   //（范围 -1 ~ 1）
      trueSide: pos.z < 1, //trueSide为false时，即使在屏幕范围内可见，也是反方向的另一个不可以被渲染的点   参见Tag.update
      inSight: inSight	//在屏幕范围内可见
    };
  },

  ifShelter: function (pos3d, pos2d, camera, colliders,domElement) {
    //检测某点在视线中是否被mesh遮挡
    if (!pos2d) pos2d = convertTool.getPos2d(pos3d,camera,domElement)
    var ori = new THREE.Vector3(pos2d.x, pos2d.y, -1).unproject(camera) //找到视线原点
    var dir = pos3d.clone().sub(ori).normalize()
    var ray = new THREE.Raycaster(ori, dir); //由外向里 因为模型从内侧是可见的所以从外侧
    // var o = ray.intersectObjects(colliders);
    // console.log(ray.intersectObjects);

    // console.log(o);

    // var len = pos3d.distanceTo(ori);
    
    // if (o && o.length) {
    //   for (var i = 0; i < o.length; i++) {
    //     if (o[i].distance < len) {
    //       console.log('有遮挡');
    //        return true; }//有遮挡
    //   }
    // }
  },



  getMouseIntersect: function (camera, meshes, mouse) {//获取鼠标和meshes交点
    var raycaster = new THREE.Raycaster;
    camera.updateMatrixWorld();
    var origin = new THREE.Vector3(mouse.x, mouse.y, -1).unproject(camera)
      , end = new THREE.Vector3(mouse.x, mouse.y, 1).unproject(camera);
    var dir = end.sub(origin).normalize()
    raycaster.set(origin, dir);
    var n = raycaster.intersectObjects(meshes);
    if (0 === n.length)
      return null;
    return n[0];

  },

}


export default convertTool
