PolyPointsTool = {
    //https://stackoverflow.com/questions/18305712/how-to-compute-the-center-of-a-polygon-in-2d-and-3d-space
    getPolyCenter: function (points) {
        let sumX = 0, sumY = 0, sumZ = 0, sumL = 0;
        for (let cursor = 0; cursor < points.length - 1; cursor++) {
            let distance = points[cursor + 1].distanceTo(points[cursor]);
            sumX += distance * ((points[cursor + 1].x + points[cursor].x) / 2);
            sumY += distance * ((points[cursor + 1].y + points[cursor].y) / 2);
            sumZ += distance * ((points[cursor + 1].z + points[cursor].z) / 2);
            sumL += distance;
        }

        //补上最后一条边
        let distance = points[points.length - 1].distanceTo(points[0]);
        sumX += distance * ((points[points.length - 1].x + points[0].x) / 2);
        sumY += distance * ((points[points.length - 1].y + points[0].y) / 2);
        sumZ += distance * ((points[points.length - 1].z + points[0].z) / 2);
        sumL += distance;

        return new THREE.Vector3(sumX / sumL, sumY / sumL, sumZ / sumL);
    },

    clockwiseSortPoints: function(points, normal) {
    let center = getCenter(points);

    points.sort((a, b) => {
        if (a.y > b.y) {
            return 1;
        }
        else if (a.y == b.y) {
            if (a.z < b.z) {
                return 1;
            } else if (a.z == b.z) {
                if (a.x > b.x) {
                    return 1;
                }
            }
        }

        return -1;
    });

    let baseLine = points[0].clone().sub(center);
    let tPoints = points.slice(1);
    tPoints.sort((a, b) => {
        let oa = a.clone().sub(center);
        let ob = b.clone().sub(center);
        let temp1 = normal.dot(oa.clone().cross(baseLine));
        let temp2 = normal.dot(ob.clone().cross(baseLine));

        if (temp1 * temp2 <= 0) {
            if (temp2 < temp1) {
                return 1;
            }
            else {
                return -1;
            }
        }

        if (temp1 < 0 && temp2 < 0) {
            let angleA = oa.angleTo(baseLine);
            let angleB = ob.angleTo(baseLine);
            if (angleA > angleB) {
                return 1;
            }

            return -1;
        }

        if (temp1 > 0 && temp2 > 0) {
            let angleA = oa.angleTo(baseLine);
            let angleB = ob.angleTo(baseLine);
            if (angleA > angleB) {
                return -1;
            }

            return 1;
        }
    });

    tPoints.splice(0, 0, points[0]);
    return tPoints;

    function getCenter(points) {
        let sumX = 0, sumY = 0,sumZ = 0;
        points.forEach(m =>{
            sumX += m.x;
            sumY += m.y;
            sumZ += m.z;
        });

        return new THREE.Vector3(sumX/points.length, sumY/points.length, sumZ/points.length);
    }
}
}