Skip to content

Instantly share code, notes, and snippets.

@mosser
Created June 24, 2014 12:09
Show Gist options
  • Save mosser/3ae589f1ed21c474367e to your computer and use it in GitHub Desktop.
Save mosser/3ae589f1ed21c474367e to your computer and use it in GitHub Desktop.
Voronoi and delaunay triangulation in Scala using JTS
/**
* Island universe
*/
import eu.ace_design.island.{PointGenerator, RandomGrid, SquaredGrid}
val MAP_SIZE = 800
val generators: Map[String,PointGenerator] = Map(
"RANDOM" -> new RandomGrid(MAP_SIZE),
"SQUARE" -> new SquaredGrid(MAP_SIZE)
)
val generator = generators("RANDOM")
//val generator = generators("SQUARE")
val points = generator(81)
// Allows scala collections to be transparently transformed into plain Java ones.
import scala.collection.JavaConversions._
/**
* JTS universe : Voronoi diagram building
*/
import com.vividsolutions.jts.triangulate._
import com.vividsolutions.jts.geom._
val coordinates = points map { p => new Coordinate(p.x, p.y) }
// Voronoi diagram building
val voronoi = new VoronoiDiagramBuilder()
voronoi.setSites(coordinates)
val envelope = new Envelope(new Coordinate(0.0,0.0), new Coordinate(MAP_SIZE, MAP_SIZE))
voronoi.setClipEnvelope(envelope)
val geometry = voronoi.getDiagram(new GeometryFactory()).asInstanceOf[GeometryCollection]
val polygons = for(i <- 0 until geometry.getNumGeometries)
yield geometry.getGeometryN(i).asInstanceOf[Polygon]
// Delaunay triagulation building
val delaunay = new DelaunayTriangulationBuilder()
delaunay.setSites(coordinates)
val triangles = delaunay.getTriangles(new GeometryFactory()).asInstanceOf[GeometryCollection]
val neighborhood = for(i <- 0 until triangles.getNumGeometries)
yield triangles.getGeometryN(i).asInstanceOf[Polygon]
/**
* Image builder
*/
import java.awt.image.BufferedImage
import scala.math.round
val img = new BufferedImage(MAP_SIZE, MAP_SIZE, BufferedImage.TYPE_INT_ARGB)
val g = img.createGraphics()
g.clearRect(0, 0, MAP_SIZE, MAP_SIZE)
polygons foreach { poly => // draw the voronoi diagram
val xs = poly.getBoundary.getCoordinates map { c => round(c.x).toInt }
val ys = poly.getBoundary.getCoordinates map { c => round(c.y).toInt }
g.setColor(java.awt.Color.WHITE)
g.fillPolygon(xs, ys, xs.size)
g.setColor(java.awt.Color.ORANGE)
g.drawPolygon(xs, ys, xs.size)
}
neighborhood foreach { triangle => // draw the delaunay triangulation
val xs = triangle.getBoundary.getCoordinates map { c => round(c.x).toInt }
val ys = triangle.getBoundary.getCoordinates map { c => round(c.y).toInt }
g.setColor(java.awt.Color.RED)
g.drawPolygon(xs, ys, xs.size)
}
/**
* File system interaction
*/
import java.io.File
import javax.imageio.ImageIO
val outputFile = new File("/Users/mosser/Desktop/image-voronoi.png")
outputFile.getAbsolutePath()
ImageIO.write(img, "png", outputFile)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment