Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Accept an option to return indexed vertices #11

Merged
merged 4 commits into from
Feb 24, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ The fastest and smallest JavaScript polygon triangulation library. 2.5KB gzipped
[![Build Status](https://travis-ci.org/mapbox/earcut.svg?branch=master)](https://travis-ci.org/mapbox/earcut)
[![Coverage Status](https://coveralls.io/repos/mapbox/earcut/badge.svg?branch=master)](https://coveralls.io/r/mapbox/earcut?branch=master)

#### The algorithm

The library implements a modified ear slicing algorithm,
optimized by [z-order curve](http://en.wikipedia.org/wiki/Z-order_curve) hashing
and extended to handle holes, twisted polygons, degeneracies and self-intersections
in a way that doesn't _guarantee_ correctness of triangulation,
but attempts to always produce acceptable results for practical data like geographical shapes.
but attempts to always produce acceptable results for practical data.

It's based on ideas from
[FIST: Fast Industrial-Strength Triangulation of Polygons](http://www.cosy.sbg.ac.at/~held/projects/triang/triang.html) by Martin Held
Expand Down Expand Up @@ -44,10 +46,19 @@ var triangles = earcut([[[10,0],[0,50],[60,60],[70,10]]]);
```

Input should be an array of rings, where the first is outer ring and others are holes;
each ring is an array of points, where each point is of the `[x, y]` form.
each ring is an array of points, where each point is of the `[x, y]` or `[x, y, z]` form.

Each group of three points in the resulting array forms a triangle.

Alternatively, you can get triangulation results in the form of flat indices and vertices arrays
by passing `true` as a second argument to `earcut`
(convenient for uploading resulting data directly to WebGL as buffers):

```js
var triangles = earcut([[[10,0],[0,50],[60,60],[70,10]]], true);
// {vertices: [0,50, 10,0, 70,10, 60,60], indices: [1,0,2, 3,2,1]}
```

#### Install

NPM and Browserify:
Expand Down
53 changes: 45 additions & 8 deletions src/earcut.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@

module.exports = earcut;

function earcut(points) {
function earcut(points, returnIndices) {

var outerNode = filterPoints(linkedList(points[0], true)),
triangles = [];
triangles = returnIndices ? {vertices: [], indices: []} : [];

if (!outerNode) return triangles;

Expand Down Expand Up @@ -98,6 +98,8 @@ function filterPoints(start, end) {
function earcutLinked(ear, triangles, minX, minY, size, pass) {
if (!ear) return;

var indexed = !!triangles.vertices;

// interlink polygon nodes in z-order
if (!pass && minX !== undefined) indexCurve(ear, minX, minY, size);

Expand All @@ -111,9 +113,15 @@ function earcutLinked(ear, triangles, minX, minY, size, pass) {

if (isEar(ear, minX, minY, size)) {
// cut off the triangle
triangles.push(prev.p);
triangles.push(ear.p);
triangles.push(next.p);
if (indexed) {
addIndexedVertex(triangles, prev);
addIndexedVertex(triangles, ear);
addIndexedVertex(triangles, next);
} else {
triangles.push(prev.p);
triangles.push(ear.p);
triangles.push(next.p);
}

// remove ear node
next.prev = prev;
Expand Down Expand Up @@ -152,6 +160,20 @@ function earcutLinked(ear, triangles, minX, minY, size, pass) {
}
}

function addIndexedVertex(triangles, node) {
if (node.source) node = node.source;

var i = node.index;
if (i === null) {
var vertices = triangles.vertices;
node.index = i = vertices.length;
vertices.push(node.p[0]);
vertices.push(node.p[1]);
if (node.p.length > 2) vertices.push(node.p[2]);
}
triangles.indices.push(i);
}

// check whether a polygon node forms a valid ear with adjacent nodes
function isEar(ear, minX, minY, size) {

Expand Down Expand Up @@ -260,6 +282,8 @@ function isEar(ear, minX, minY, size) {

// go through all polygon nodes and cure small local self-intersections
function cureLocalIntersections(start, triangles) {
var indexed = !!triangles.vertices;

var node = start;
do {
var a = node.prev,
Expand All @@ -268,9 +292,15 @@ function cureLocalIntersections(start, triangles) {
// a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2])
if (intersects(a.p, node.p, node.next.p, b.p) && locallyInside(a, b) && locallyInside(b, a)) {

triangles.push(a.p);
triangles.push(node.p);
triangles.push(b.p);
if (indexed) {
addIndexedVertex(triangles, a);
addIndexedVertex(triangles, node);
addIndexedVertex(triangles, b);
} else {
triangles.push(a.p);
triangles.push(node.p);
triangles.push(b.p);
}

// remove two nodes involved
a.next = b;
Expand Down Expand Up @@ -606,6 +636,9 @@ function splitPolygon(a, b) {
an = a.next,
bp = b.prev;

a2.source = a;
b2.source = b;

a.next = b;
b.prev = a;

Expand Down Expand Up @@ -652,4 +685,8 @@ function Node(p) {
// previous and next nodes in z-order
this.prevZ = null;
this.nextZ = null;

// used for indexed output
this.source = null;
this.index = null;
}
23 changes: 18 additions & 5 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ var test = require('tape'),
areaTest('building');
areaTest('dude');
areaTest('water', 0.0019);
areaTest('water', 0.0019, true);
areaTest('water2');
areaTest('water3');
areaTest('water3b');
Expand All @@ -18,18 +19,30 @@ areaTest('degenerate');
areaTest('bad-hole', 0.0420);
areaTest('empty-square');

function areaTest(filename, expectedDeviation) {
function areaTest(filename, expectedDeviation, indexed) {
expectedDeviation = expectedDeviation || 0.000001;

test(filename, function (t) {

var data = JSON.parse(fs.readFileSync(path.join(__dirname, '/fixtures/' + filename + '.json'))),
triangles = earcut(data),
triangles = earcut(data, indexed),
vertices = triangles.vertices,
indices = triangles.indices,
expectedArea = polygonArea(data),
area = 0;
area = 0,
i;

for (var i = 0; i < triangles.length; i += 3) {
area += triangleArea(triangles[i], triangles[i + 1], triangles[i + 2]);
if (vertices) {
for (i = 0; i < indices.length; i += 3) {
area += triangleArea(
[vertices[indices[i]], vertices[indices[i] + 1]],
[vertices[indices[i + 1]], vertices[indices[i + 1] + 1]],
[vertices[indices[i + 2]], vertices[indices[i + 2] + 1]]);
}
} else {
for (i = 0; i < triangles.length; i += 3) {
area += triangleArea(triangles[i], triangles[i + 1], triangles[i + 2]);
}
}

var deviation = expectedArea === 0 && area === 0 ? 0 : Math.abs(area - expectedArea) / expectedArea;
Expand Down
Loading