• Stars
    star
    223
  • Rank 178,458 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

2D constrained Delaunay triangulation

cdt2d

A robust 2D constrained Delaunay triangulation library written in JavaScript.

WORK IN PROGRESS

Demo

To test out this module, you can open up a demo in your browser with the following link:

cdt2d demo

  • Click to add points
  • Click on a point to remove it
  • Drag one point onto another to add an edge constraint
  • Click on a green edge to remove a constraint
  • Toggle options by clicking on the checkboxes on the left
  • Click reset to clear all points

Examples

Simple example

Here is a simple example showing how to invoke cdt2d:

//First we need to reqire the module
var cdt2d = require('cdt2d')

//Then we define a list of points, represented as pairs of x,y coordinates
var points = [
  [-2,-2],
  [-2, 2],
  [ 2, 2],
  [ 2,-2],
  [ 1, 0],
  [ 0, 1],
  [-1, 0],
  [ 0,-1]
]

//Next we can optionally define some edge constraints
// This set of edges determines a pair of loops
var edges = [
 //Outer loop
 [0, 1],
 [1, 2],
 [2, 3],
 [3, 0],

 //Inner loop
 [4, 5],
 [5, 6],
 [6, 7],
 [7, 4]
]

//Finally we call cdt2d with the points and edges
// The flag {exterior: false} tells  it to remove exterior faces
console.log(cdt2d(points, edges, {exterior: false}))

Output

The above program will output the following triangles:

[ [ 0, 3, 7 ],
  [ 0, 6, 1 ],
  [ 0, 7, 6 ],
  [ 1, 5, 2 ],
  [ 1, 6, 5 ],
  [ 2, 4, 3 ],
  [ 2, 5, 4 ],
  [ 3, 4, 7 ] ]

Each triangle is represented as an array of 3 indices of points. We can visualize this data in the following figure:

Messy graphs

If your input doesn't satisfy the validity invariants (ie no self intersections, duplicate vertices or t-junctions), then you will need to preprocess it to clean it up. One way to do this is with the clean-pslg module. Here is an example showing how to do this:

var cleanPSLG = require('clean-pslg')
var cdt2d = require('cdt2d')

var points = [
  [-1, 0],
  [ 1, 0],
  [ 0,-1],
  [ 0, 1]
]

var edges = [
  [0, 1],
  [1, 2]
]

//This updates points/edges so that they now form a valid PSLG
cleanPSLG(points, edges)

//Generate the triangulation
console.log({
  points: points,
  edges: edges,
  triangles: cdt2d(points, edges)
})

Output

TODO

Polygon example

It is also pretty easy to use this module with polygons, as one would get from a GeoJSON file. To do this, it is first necessary to convert them into a planar straight line graph. This can be done using the poly-to-pslg module:

var toPSLG = require('poly-to-pslg')
var cdt2d = require('cdt2d')

TODO

Polygon with holes example

The above procedure even works if the polygons have holes:

var toPSLG = require('poly-to-pslg')
var cdt2d = require('cdt2d')

TODO

Delaunay triangulation

You can also use cdt2d to generate Delaunay triangulations of arbitrary point sets in the plane:

TODO

Install

This module works in any modern CommonJS environment. You can install it using npm with the following command:

npm i cdt2d

You should be able to then use it in node or on the web with browserify.

API

var cells = require('cdt2d')(points[, edges, options])

Constructs a constrained Delaunay triangulation of a planar straight-line graph.

  • points are the vertices of the triangulation, represented by pairs of numbers.
  • edges is an optional list of edge constraints which must occur within the triangulation. These constraints are given by pairs of indices of points. If not specified, then no constraints are used.
  • options is an object which takes some optional parameters.
    • delaunay if this flag is set to true, then the resulting triangulation is converted to a Delaunay triangulation by edge flipping. Otherwise if it is false, then an arbitrary triangulation is returned. (Default true)
    • interior if set, only return interior faces. See note. (Default true)
    • exterior if set, only return exterior faces. See note. (Default true)
    • infinity if set, then the triangulation is augmented with a point at infinity represented by the index -1. (Default false)

Returns A list of all triangles represented as triples of indices of vertices

Note on interior/exterior classification Interior/exterior faces are classified by treating the constraint edges as the boundary and traversing the triangulation. The point at infinity is in the exterior of the set, and other faces are classified by the parity of the path with fewest crossings from the face to the point at infinity.

Assumptions This module makes the following assumptions about the points and edge constraints:

  • No point in the input is duplicated
  • No pair of edge constraints cross in their relative interior
  • No point is contained in the relative interior of an edge (ie no T-junctions)

If your input does not satisfy these conditions, you will need to preprocess it first (using clean-pslg for example) otherwise cdt2d may return incorrect results.

Limitations Currently there is no way to specify that only some edge constraints are to be included in the boundary. It is also not possible to add a constraint from a vertex to the point at infinity. If there is enough demand I may add these features or perhaps create a separate module.

Benchmarks and comparisons

Assertion: cdt2d is the only non-broken triangulation library in JavaScript.

  • TODO Catalogue failing cases for other libraries
  • TODO Need to measure performance and finetune

Libraries to compare against:

  • earcut
  • poly2tri
  • pnltri
  • libtess.js

License

(c) 2015 Mikola Lysenko. MIT License

More Repositories

1

l1-path-finder

πŸ—Ί Fast path planning for 2D grids
JavaScript
471
star
2

functional-red-black-tree

A purely functional red-black tree data structure
JavaScript
358
star
3

vectorize-text

Turns a text string into a 2D poly line
JavaScript
303
star
4

static-kdtree

A static kdtree data structure
JavaScript
302
star
5

orthogami

Orthogonal polyhedra origami
JavaScript
279
star
6

box-intersect

πŸ“¦ Any dimensional box intersection
JavaScript
271
star
7

robust-point-in-polygon

Exactly test if a point is inside, outside or on the boundary of a polygon
JavaScript
229
star
8

mikolalysenko.github.com

JavaScript
210
star
9

laplacian-deformation

Laplacian mesh deformation
C++
209
star
10

robust-arithmetic-notes

Tutorial on robust arithmetic in JavaScript
JavaScript
198
star
11

mudb

Low latency state replication for the web
TypeScript
168
star
12

isosurface

Isosurface polygonizer algorithms
JavaScript
166
star
13

delaunay-triangulate

Easy to use robust Delaunay triangulation
JavaScript
153
star
14

game-shell

Ready to go JavaScript shell for games or other interactive demos
JavaScript
118
star
15

patcher.js

JSON diffing and patching library
JavaScript
112
star
16

electron-recorder

Record animations using Electron
JavaScript
108
star
17

surface-nets

Arbitrary dimensional level sets
JavaScript
96
star
18

binary-search-bounds

Better binary searching
JavaScript
88
star
19

dynamic-forest

Maintain a dynamic spanning forest of a graph under edge insertions and deletions
JavaScript
84
star
20

uniq

Removes duplicate items from an array in place
JavaScript
81
star
21

NodeMinecraftThing

Javascript MMO framework
JavaScript
78
star
22

pitch-shift

Variable speed pitch shifter written in JavaScript
JavaScript
78
star
23

refine-mesh

Iterative mesh refinement
JavaScript
77
star
24

box-intersect-benchmark

Box intersection benchmark
JavaScript
74
star
25

typedarray-pool

Reuse typed arrays
JavaScript
74
star
26

rectangle-decomposition

Computes a minimal rectangular decomposition of a rectilinear polygon
JavaScript
71
star
27

conway-hart

A port of George Hart's implementation/extension of Conway's polyhedral notation to CommonJS
JavaScript
69
star
28

femgl

WebGL finite element viewer
JavaScript
68
star
29

interval-tree-1d

1D interval tree
JavaScript
67
star
30

voxel-mipmap-demo

Demo of mipmapping for voxel terrain
JavaScript
66
star
31

alpha-shape

Any dimensional alpha shapes
JavaScript
66
star
32

simplicial-complex

Tools for manipulating simplicial complexes in JavaScript
JavaScript
63
star
33

mespeak

NPM entry for mespeak for easier installation and usage in browserify
JavaScript
62
star
34

detect-pitch

Detects the pitch of an audio snippet
JavaScript
61
star
35

drag-and-drop-files

Handle file drag-and-drop events without all the Yak shaving
JavaScript
55
star
36

vertex-ao

Vertex based ambient occlusion calculation for meshes
JavaScript
53
star
37

bit-twiddle

Bit twidling hacks for node.js
JavaScript
53
star
38

mouse-wheel

Speed controlled mouse scrolling
JavaScript
50
star
39

to-px

Convert any CSS unit to logical pixels (aka "px")
JavaScript
48
star
40

voronoi-diagram

n-dimensional voronoi diagram constructor
JavaScript
46
star
41

local-perception-filter-demo

Demonstration of local perception filters in a browser
JavaScript
46
star
42

monotone-convex-hull-2d

Robust and fast 2D convex hull
JavaScript
44
star
43

clean-pslg

Clean up messy planar straight line graphs
JavaScript
44
star
44

greedy-mesher

Greedy mesh compiler
JavaScript
43
star
45

ndarray-experiments

Multidimensional typed arrays in JS
JavaScript
42
star
46

glsl-read-float

Read floating point values back from WebGL
JavaScript
41
star
47

a-big-triangle

Draws a big triangle onto the screen
JavaScript
41
star
48

ao-mesher

Voxel mesher with ambient occlusion
JavaScript
40
star
49

convex-hull

Any dimensional convex hull
JavaScript
36
star
50

taubin-smooth

Taubin's mesh smoothing algorithm implemented in JavaScript
HTML
34
star
51

stft

Short time Fourier transform
JavaScript
34
star
52

plastimesh

πŸ‘Ύ A free form mesh sculpting tool
JavaScript
34
star
53

3d-view-controls

A camera with input hooks for basic 3D projects
JavaScript
34
star
54

orbit-camera

Orbit camera for 3D scenes
JavaScript
33
star
55

LudumDare23MMO

LudumDare23 MMO source code (rebuilt to remove database stuff)
JavaScript
33
star
56

ndarray-project-list

List of stuff todo with ndarrays
33
star
57

voxelize

Voxelizes a triangulated mesh into an ndarray
JavaScript
32
star
58

gif-3d

3D gif visualizer
JavaScript
29
star
59

haar-tree-3d

3D Wavelet Rasterization
JavaScript
29
star
60

mouse-event

Cross browser mouse event property access
JavaScript
28
star
61

strongly-connected-components

Computes the strongly connected components of a directed graph
JavaScript
27
star
62

union-find

A basic union-find data structure for node.js
JavaScript
26
star
63

0fpsBlog

Code and examples for 0fps blog
JavaScript
25
star
64

point-in-region

Fast and exact point in region location
JavaScript
25
star
65

node-latex

node.js wrapper for LaTeX
JavaScript
25
star
66

MineHack

WebGL based AJAX videogame -- with MMO, Minecraft and Roguelike elements.
C
24
star
67

incremental-delaunay

Constructs a Delaunay triangulation for a collection of points
JavaScript
24
star
68

angle

Almost Native Graphics Layer Engine (local fork)
C++
24
star
69

bibtex-parser

A CommonJS port of BibTeX-js
JavaScript
24
star
70

count-min-sketch

Count-Min Sketch Data Structure
JavaScript
24
star
71

bound-points

Find a bounding box for a set of points
JavaScript
23
star
72

robust-orientation

Robustly computes the orientation of a tuple of points
JavaScript
23
star
73

lpf-ctf

Multiplayer capture the flag demo
JavaScript
23
star
74

parse-obj

Parses a .OBJ file
JavaScript
23
star
75

cubic-hermite

Cubic hermite interpolation
JavaScript
22
star
76

angle-normals

Compute mesh normals using angle weights
JavaScript
22
star
77

ao-shader

Ambient occlusion shader for ao-mesher
JavaScript
22
star
78

svg-3d-simplicial-complex

Renders a simplicial complex to a list of polygons in SVG
JavaScript
22
star
79

ndarray-tutorial

Guide to ndarrays
21
star
80

mesh-fixer

Fixes holes in 3D meshes
HTML
20
star
81

functional-priority-queue

A functional priority queue in JavaScript
JavaScript
20
star
82

3p

Progressive triangle streams
JavaScript
20
star
83

bunny

The Stanford bunny
19
star
84

ndpack-image

Package an image into a requireable module
JavaScript
19
star
85

gl-modules

A modular approach to WebGL programming
19
star
86

csr-matrix

Compressed sparse row matrix for node.js
JavaScript
19
star
87

contour2d

Extracts a rectilinear polygon contour from a binary image
JavaScript
18
star
88

triangulate-polyline

Triangulates a complex polygon
JavaScript
18
star
89

mathmode

Turns LaTeX math mode expressions into images
JavaScript
18
star
90

poly-bool

Exact polygon boolean operations
JavaScript
18
star
91

filtered-vector

Path smoothing for vector valued input curves
JavaScript
18
star
92

gl-render-text

Renders text to a WebGL texture
JavaScript
17
star
93

differential-growth

Differential growth, inspired by @inconvergent
JavaScript
17
star
94

point-in-big-polygon

Industrial strength point in polygon test
JavaScript
17
star
95

vishull2d

Visible regions for 2D poly-lines
JavaScript
17
star
96

normals

Computes normals for triangulated meshes
JavaScript
17
star
97

commutative-rendering

Ideas about modular graphical rendering
16
star
98

vj-stuff

Stream of consciousness programmed WebGL visualizations
JavaScript
16
star
99

split-polygon

Splits a convex polygon by a plane
JavaScript
16
star
100

control-flow

Control flow graph and 3AC form for JavaScript programs
JavaScript
16
star