在Haskell中使用opengl绘制线条

lew*_*mbs 5 opengl haskell

我正在尝试使用opengl创建一个go board.为此,我试图绘制一堆线来创建网格.但是,每个教程站点(包括opengl)都有C++中的示例,而Haskell wiki并没有很好地解释它.我是opengl的新手,想要一个教程.

dfl*_*str 12

我假设你想要使用OpenGL 2.1或更早版本.对于OpenGL 3.0,您需要不同的代码.

所以,在C中你会写这个:

glBegin(GL_LINES);
glVertex3f(1, 2, 3);
glVertex3f(5, 6, 7);
glEnd();
Run Code Online (Sandbox Code Playgroud)

你在Haskell中编写等效的代码如下:

renderPrimitive Lines $ do
  vertex $ Vertex3 1 2 3
  vertex $ Vertex3 5 6 7
Run Code Online (Sandbox Code Playgroud)

有了这个代码,因为我用如1来代替一些变量,你可能会得到不明的错误类型(所以你应该更换1使用(1 :: GLfloat)),但如果您使用的是已有的实际类型的变量GLfloat,你不应该这样做.

这是一个在窗口中绘制白色对角线的完整程序:

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
Run Code Online (Sandbox Code Playgroud)

默认的OpenGL固定功能投影使用左下角的(-1,-1)和窗口右上角的(1,1).您需要更改投影矩阵以获得不同的坐标空间.

有关此类更完整的示例,请参阅NEHE教程的Haskell端口.他们使用RAW OpenGL绑定,更像是C绑定.

  • @lewdsterthumbs你可能会喜欢[40种方法来获得一个空白的黑屏](http://dmalcolm.livejournal.com/2433.html). (2认同)