Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawing lines with opengl in Haskell

Tags:

haskell

opengl

I'm trying to create a go board using opengl. To do this, I'm trying to draw a bunch of lines to create the grid. However, every tutorial site (including opengl's) has the examples in C++ and the Haskell wiki doesn't do a good job of explaining it. I'm new to opengl and would like a tutorial.

like image 234
lewdsterthumbs Avatar asked Feb 15 '12 20:02

lewdsterthumbs


2 Answers

I'll assume that you want to use OpenGL 2.1 or earlier. For OpenGL 3.0, you need different code.

So, in C you would write this:

glBegin(GL_LINES);
glVertex3f(1, 2, 3);
glVertex3f(5, 6, 7);
glEnd();

You write the equivalent in Haskell like this:

renderPrimitive Lines $ do
  vertex $ Vertex3 1 2 3
  vertex $ Vertex3 5 6 7

With this code, since I used e.g. 1 instead of some variable, you might get errors about ambiguous types (So you should replace 1 with (1 :: GLfloat)), but if you use actual variables that already have the type GLfloat, you shouldn't have to do this.

Here's a complete program that draws a white diagonal in the window:

import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT

main :: IO ()
main = do
  -- Initialize OpenGL via GLUT
  (progname, _) <- getArgsAndInitialize

  -- Create the output window
  createWindow progname

  -- Every time the window needs to be updated, call the display function
  displayCallback $= display

  -- Let GLUT handle the window events, calling the displayCallback as fast as it can
  mainLoop

display :: IO ()
display = do
  -- Clear the screen with the default clear color (black)
  clear [ ColorBuffer ]

  -- Render a line from the bottom left to the top right
  renderPrimitive Lines $ do
    vertex $ (Vertex3 (-1) (-1)  0 :: Vertex3 GLfloat)
    vertex $ (Vertex3   1    1   0 :: Vertex3 GLfloat)

  -- Send all of the drawing commands to the OpenGL server
  flush

The default OpenGL fixed-function projection uses (-1, -1) for the bottom left and (1, 1) for the top right of the window. You need to alter the projection matrix to get different coordinate spaces.

For more complete examples like this, see the Haskell port of the NEHE tutorials. They use the RAW OpenGL bindings, which are more like the C bindings.

like image 113
dflemstr Avatar answered Nov 02 '22 22:11

dflemstr


A quick google turned up this:

http://www.haskell.org/haskellwiki/OpenGLTutorial1

In any case, since OpenGL is originally a C library, you may want to get your feet wet in C (or C++) first, since you'll be able to use the original OpenGL documentation as-is; after that, you may want to dig into the Haskell bindings and see how you use the same OpenGL calls in Haskell.

like image 40
tdammers Avatar answered Nov 02 '22 22:11

tdammers