3

I am trying to use Haskell to procedurally generate a triangulated square terrain of a given width to be given to OpenGL.

The only thing that is actually procedurally generated is the heights, which is not hard at all, I just use a random function to create a [[GLfloat]], representing rows of heights.

Then I also have a function, heightsToCoords that takes the [[GLfloat]] and returns a [GLfloat] containing the x, y, and z coords of each vertex.

So if I call heightsToCoords [[0, 1], [1, 0]], it will return

[0, 0, 0,  
 1, 1, 0,
 0, 1, 1,
 1, 0, 1]

The problem I'm having is getting the data to OpenGL. OpenGL needs each face triangulated (at least with my setup) and all I have is the points, I am not sure how to create the faces.

How could I transform this data from a list of points to a list of faces? Disregard normals and order of vertices.

functorial
  • 687
  • 5
  • 13
  • Unrelated suggestion: I'd use an [array](https://hackage.haskell.org/package/array) rather than a list of lists for the heights, as you can then guarantee that each row will have the same width. (And it's probably more efficient.) – icktoofay Jan 12 '14 at 22:48
  • 1
    Or maybe even a [vector](https://hackage.haskell.org/package/vector), which is supposedly even more efficient. – icktoofay Jan 12 '14 at 22:55
  • I wrote something that made 2D procedurally generated graphics in haskell. It used display lists and haskell lists. Code is [here](https://github.com/DiegoNolan/Generated). – DiegoNolan Jan 13 '14 at 01:41

1 Answers1

3

On the GL side, I'd use drawElements, which needs a list of points and a list of indices as inputs. So the question becomes how to generate a list of indices into your list of points.

Keeping in mind the original XZ grid, the idea is to draw two triangles for each cell of the grid. So we need 6 indices per grid cell. In Haskell, we can write something like:

concat [[x + width * (y+1), 1 + x + width*y, x + width * y, 
         x + width* (y+1), 1 + x + width * (y+1), 1 + x + width*y] 
         | y <- [0..height-1], x <- [0..width-1]]
bergey
  • 3,041
  • 11
  • 17