More accurate clockwise vertices sorting
<p>I've used few algorithms for clockwise vertices sorting and still can't sort as it should be sorted. </p>

<p>The poly is always square with cutted off smaller squares of same size (let's name them chunks). So say I have square 6x6 and chunks are 1x1. More specifically: square has vertices: [0,0], [5,0], [5,5], [0,5].
If I'll cut the chunk off at position [0,0] (like intersection done with smaller square on vertices from [0,0] to [1,1]), square looks like this:</p>

<p><a href="https://i.stack.imgur.com/h1q0y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/h1q0y.png" alt="Beautiful chunk intersection"></a></p>

<p>His vertices are now: [0,1], [1,1], [1,0], [5,0], [5,5], [0,5]</p>

<p>It's fine. But let's do some more intersections. I won't show second intersection of chunk at position [1,0] because there is all fine. Now if I'll do third intersection, say at position [0,1] it looks like this:</p>

<p><a href="https://i.stack.imgur.com/0K31o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0K31o.png" alt="Ugly intersection"></a></p>

<p>Of course, it should look like this:</p>

<p><a href="https://i.stack.imgur.com/5yzHg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5yzHg.png" alt="enter image description here"></a></p>

<p>So as You can see, it's just sorting fail which sorts vertex [1,2] before [0,2]</p>

<p>I'm wonder if it will sort good when I'll add something like checking the distance from centroid. Well.. Here is a code of this sorting:</p>

<pre><code>function (a, b) {

    var distance1 = Math.sqrt(Math.pow(a.x - centroid.x, 2) + Math.pow(a.y - centroid.y, 2));
    var distance2 = Math.sqrt(Math.pow(b.x - centroid.x, 2) + Math.pow(b.y - centroid.y, 2));
    var a1 = Math.acos((a.x - centroid.x) / distance1);
    var a2 = Math.acos((b.x - centroid.x) / distance2);

    if (a.y &gt; centroid.y)
        a1 = Math.PI + Math.PI - a1;

    if (b.y &gt; centroid.y)
        a2 = Math.PI + Math.PI - a2;

    return a1 - a2;

}
</code></pre>

<p>and centroid:</p>

<pre><code>function (vertices) {
    var 
        x = 0,
        y = 0,
        pointCount = vertices.length;

    for (var i = 0; i &lt; pointCount; i++){
        x += vertices[i].x;
        y += vertices[i].y;
    }

    x = x/pointCount;
    y = y/pointCount;

    return new vec2(x, y);
}
</code></pre>