import { Vector3 as ThreeVector3 } from "three";


const farTL = new ThreeVector3();
const farTR = new ThreeVector3();
const farBL = new ThreeVector3();
const farBR = new ThreeVector3();


const nearTL = new ThreeVector3();
const nearTR = new ThreeVector3();
const nearBL = new ThreeVector3();
const nearBR = new ThreeVector3();

/**
 *
 * @param {Frustum} output
 * @param {AABB2} box screen-space 2d box in NDC (-1,+1)
 * @param {THREE.Camera} camera
 */
export function makeScreenScissorFrustum(output, box, camera) {

    camera.updateProjectionMatrix();
    camera.updateMatrixWorld();


    //convert box from view space into world space
    farTL.set(box.x0, box.y0, 1);
    farTR.set(box.x1, box.y0, 1);
    farBL.set(box.x0, box.y1, 1);
    farBR.set(box.x1, box.y1, 1);

    nearTL.set(box.x0, box.y0, -1);
    nearTR.set(box.x1, box.y0, -1);
    nearBL.set(box.x0, box.y1, -1);
    nearBR.set(box.x1, box.y1, -1);

    farTL.unproject(camera);
    farTR.unproject(camera);
    farBL.unproject(camera);
    farBR.unproject(camera);

    nearTL.unproject(camera);
    nearTR.unproject(camera);
    nearBL.unproject(camera);
    nearBR.unproject(camera);

    //create frustum planes
    const planes = output.planes;

    //set planes
    planes[0].setFromCoplanarPoints(nearTL, farTL, farTR);
    planes[1].setFromCoplanarPoints(nearTR, farTR, farBR);
    planes[2].setFromCoplanarPoints(farBR, farBL, nearBL);
    planes[3].setFromCoplanarPoints(farBL, farTL, nearTL);
    planes[4].setFromCoplanarPoints(nearTR, nearBR, nearBL);

    planes[5].setFromCoplanarPoints(farBR, farTR, farTL);
    planes[5].normal.multiplyScalar(-1);
}
