import * as THREE from 'three'
import {clearFids} from '../core/dyWoker'
import {threeLayer, vector} from './initScene3D'

const frustum = new THREE.Frustum();
const cameraViewProjectionMatrix = new THREE.Matrix4();


function meshStatus() {
  let camera = threeLayer.getCamera();
  if (!camera) return
  camera.updateMatrixWorld();
  camera.matrixWorldInverse.getInverse(camera.matrixWorld);
  cameraViewProjectionMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
  frustum.setFromMatrix(cameraViewProjectionMatrix);
  let scene = threeLayer.getScene()
  let children = scene.children
  for (let i = 0; i < children.length; i++) {
    let m = children[i]
    if (m.type === 'Mesh') {
      let viewMesh = frustum.intersectsObject(m)
      if (!viewMesh) {
        scene.remove(m)
        m.isRemove = true
        vector.removeGeometry(m.texts)
        clearFids(m.fids)
        i--
      }
    }
  }
}


function unMeshAll () {
  let scene = threeLayer.getScene()
  let children = scene.children
  for (let i = 0; i < children.length; i++) {
    let m = children[i]
    if (m.type === 'Mesh') {
      scene.remove(m)
      m.isRemove = true
      vector.removeGeometry(m.texts)
      clearFids(m.fids)
      i--
    }
  }
}
export {
  unMeshAll,
  meshStatus
}