import { Vector3 } from "three"
import { round, round2 } from "./utils"

export const zero = new Vector3(0, 0, 0)
export const up = new Vector3(0, 0, 1)

export function vec(v) {
  return new Vector3(v.x, v.y, v.z)
}

const upCrossVec = new Vector3()
export function upCross(v) {
  return upCrossVec.copy(up).cross(v)
}
const normVec = new Vector3()
export function norm(v) {
  return normVec.copy(v).normalize()
}

const vc = new Vector3()
export function passesThroughZero(v, dv) {
  return vc.copy(v).add(dv).dot(v) <= 0
}

export function unitAtAngle(theta, target = new Vector3()) {
  return target.set(1, 0, 0).applyAxisAngle(up, theta)
}

export function roundVec(v) {
  v.x = round(v.x)
  v.y = round(v.y)
  v.z = round(v.z)
  return v
}

export function roundVec2(v) {
  v.x = round2(v.x)
  v.y = round2(v.y)
  v.z = round2(v.z)
  return v
}

export function anglesAlign(a, b, toleranceRad) {
  const dot = Math.cos(a - b)
  const diff = Math.acos(Math.max(-1, Math.min(1, dot)))
  return diff <= toleranceRad
}
