summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCsaba Hruska <csaba.hruska@gmail.com>2018-09-22 11:26:50 +0200
committerGitHub <noreply@github.com>2018-09-22 11:26:50 +0200
commit9f6e1725b52ea6f48101a37181f0aa9f7d1494d3 (patch)
tree7c10ffae525116bbdcf5a681f755e658078aa5fb
parent42bc23db138991343708d14e2b5032d2dabd3d0d (diff)
parenta5880684868824b34689df4589106730ad1c7fc0 (diff)
Merge pull request #13 from deepfire/master
Keep track of GLRenderer outputs and fix integer render textures
-rw-r--r--.gitignore2
-rw-r--r--examples/pickInt.hs192
-rw-r--r--examples/pickInt.json1
-rw-r--r--examples/pickInt.lc21
-rw-r--r--examples/pickIntDraw.json1
-rw-r--r--examples/pickIntDraw.lc21
-rw-r--r--lambdacube-gl.cabal35
-rw-r--r--src/LambdaCube/GL/Backend.hs83
-rw-r--r--src/LambdaCube/GL/Type.hs11
-rw-r--r--src/LambdaCube/GL/Util.hs18
10 files changed, 352 insertions, 33 deletions
diff --git a/.gitignore b/.gitignore
index 561a774..cf6ea4b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,7 @@
1*~ 1*~
2dist 2dist
3dist-newstyle
3*.hi 4*.hi
4*.o 5*.o
5.stack-work 6.stack-work
7.ghc.environment.*
diff --git a/examples/pickInt.hs b/examples/pickInt.hs
new file mode 100644
index 0000000..2703e91
--- /dev/null
+++ b/examples/pickInt.hs
@@ -0,0 +1,192 @@
1{-# LANGUAGE PackageImports, LambdaCase, OverloadedStrings, StandaloneDeriving, ViewPatterns #-}
2import Control.Monad
3import Data.Aeson
4import Data.Vect (Mat4(..), Vec3(..), Vec4(..))
5import Graphics.GL.Core33 as GL
6import LambdaCube.GL as LambdaCubeGL
7import LambdaCube.GL.Mesh as LambdaCubeGL
8import Text.Printf
9import "GLFW-b" Graphics.UI.GLFW as GLFW
10import qualified Data.ByteString as SB
11import qualified Data.Map as Map
12import qualified Data.Vect as Vc
13import qualified Data.Vector as V
14import qualified Foreign as F
15import qualified Foreign.C.Types as F
16import qualified LambdaCube.GL.Type as LC
17import qualified LambdaCube.Linear as LCLin
18
19----------------------------------------------------
20-- See: http://lambdacube3d.com/getting-started
21----------------------------------------------------
22
23screenDim :: (Int, Int)
24screenDim = (800, 600)
25(screenW, screenH) = screenDim
26
27main :: IO ()
28main = do
29 Just pipePickDesc <- decodeStrict <$> SB.readFile "pickInt.json"
30 Just pipeDrawDesc <- decodeStrict <$> SB.readFile "pickIntDraw.json"
31
32 win <- initWindow "LambdaCube 3D integer picking" 800 600
33
34 -- setup render data
35 let inputSchema = makeSchema $ do
36 defObjectArray "objects" Triangles $ do
37 "position" @: Attribute_V2F
38 "id" @: Attribute_Int
39 "color" @: Attribute_V4F
40 defUniforms $ do
41 "viewProj" @: M44F
42
43 storage <- LambdaCubeGL.allocStorage inputSchema
44
45 -- upload geometry to GPU and add to pipeline input
46 LambdaCubeGL.uploadMeshToGPU triangleA >>= LambdaCubeGL.addMeshToObjectArray storage "objects" []
47 LambdaCubeGL.uploadMeshToGPU triangleB >>= LambdaCubeGL.addMeshToObjectArray storage "objects" []
48
49 -- allocate GL pipeline
50 pipePick <- LambdaCubeGL.allocRenderer pipePickDesc
51 pipeDraw <- LambdaCubeGL.allocRenderer pipeDrawDesc
52 errPick <- LambdaCubeGL.setStorage pipePick storage
53 errDraw <- LambdaCubeGL.setStorage pipeDraw storage
54 case (errPick, errDraw) of -- check schema compatibility
55 (Just err, _) -> putStrLn err
56 (_, Just err) -> putStrLn err
57 (Nothing, Nothing) -> loop
58 where loop = do
59 -- update graphics input
60 GLFW.getWindowSize win >>= \(w,h) -> LambdaCubeGL.setScreenSize storage (fromIntegral w) (fromIntegral h)
61 LambdaCubeGL.updateUniforms storage $ do
62 let (x, y) = (,) 0 0
63 cvpos = Vec3 x (-y) 0
64 toScreen = screenM screenW screenH
65 "viewProj" @= pure (mat4ToM44F $! (Vc.fromProjective $! Vc.translation cvpos) Vc..*. toScreen)
66
67 (curX, curY) <- GLFW.getCursorPos win
68 let pickPoints = -- should be fb 0 fb 1 (pick)
69 [ (clamp curX 800, clamp curY 600)
70 , (0, 0) -- black 0
71 , (200, 200) -- ..blue, ffff0000 2
72 , (600, 400) -- ..red, ff0000ff 1
73 ] :: [(Int, Int)]
74 clamp v m = min (pred m) $ max 0 (floor v)
75
76 -- render to render texture
77 LambdaCubeGL.renderFrame pipePick
78 case LC.glOutputs pipePick of
79 [LC.GLOutputRenderTexture (fromIntegral -> fbo) _rendTex] -> do
80 rtexPicks <- collectPicks fbo pickPoints
81 printPicks pickPoints rtexPicks
82 x -> error $ "Unexpected outputs: " <> show x
83
84 -- render to framebuffer & pick
85 LambdaCubeGL.renderFrame pipeDraw
86 colorPicks <- collectPicks 0 pickPoints
87 printPicks pickPoints colorPicks
88
89 GLFW.swapBuffers win
90 GLFW.pollEvents
91
92 let keyIsPressed k = fmap (==KeyState'Pressed) $ GLFW.getKey win k
93 escape <- keyIsPressed Key'Escape
94 if escape then return () else loop
95 collectPicks :: Int -> [(Int, Int)] -> IO [Int]
96 collectPicks fb picks =
97 forM picks $ (fromIntegral <$>) . pickFrameBuffer fb screenDim
98 printPicks pickPoints colorPicks = do
99 forM_ (zip pickPoints colorPicks) $ \((x,y), col)-> do
100 printf "%d:%d: %x " x y col
101 putStrLn ""
102
103 LambdaCubeGL.disposeRenderer pipePick
104 LambdaCubeGL.disposeRenderer pipeDraw
105 LambdaCubeGL.disposeStorage storage
106 GLFW.destroyWindow win
107 GLFW.terminate
108
109deriving instance Show (LC.GLOutput)
110deriving instance Show (LC.GLTexture)
111
112-- geometry data: triangles
113scale = 250.0
114s = scale
115
116triangleA :: LambdaCubeGL.Mesh
117triangleA = Mesh
118 { mAttributes = Map.fromList
119 [ ("position", A_V2F $ V.fromList [V2 s s, V2 s (-s), V2 (-s) (-s)])
120 , ("color", A_V4F $ V.fromList $ take 4 $ repeat $ V4 1 0 0 1)
121 , ("id", A_Int $ V.fromList [1, 1, 1])
122 ]
123 , mPrimitive = P_Triangles
124 }
125
126triangleB :: LambdaCubeGL.Mesh
127triangleB = Mesh
128 { mAttributes = Map.fromList
129 [ ("position", A_V2F $ V.fromList [V2 s s, V2 (-s) (-s), V2 (-s) s])
130 , ("color", A_V4F $ V.fromList $ take 4 $ repeat $ V4 0 0 1 1)
131 , ("id", A_Int $ V.fromList [2, 2, 2])
132 ]
133 , mPrimitive = P_Triangles
134 }
135
136vec4ToV4F :: Vec4 -> LCLin.V4F
137vec4ToV4F (Vc.Vec4 x y z w) = LCLin.V4 x y z w
138
139mat4ToM44F :: Mat4 -> LCLin.M44F
140mat4ToM44F (Mat4 a b c d) = LCLin.V4 (vec4ToV4F a) (vec4ToV4F b) (vec4ToV4F c) (vec4ToV4F d)
141
142screenM :: Int -> Int -> Mat4
143screenM w h = scaleM
144 where (fw, fh) = (fromIntegral w, fromIntegral h)
145 scaleM = Vc.Mat4 (Vc.Vec4 (1/fw) 0 0 0)
146 (Vc.Vec4 0 (1/fh) 0 0)
147 (Vc.Vec4 0 0 1 0)
148 (Vc.Vec4 0 0 0 0.5)
149
150pickFrameBuffer
151 :: Int -- ^ framebuffer
152 -> (Int, Int) -- ^ FB dimensions
153 -> (Int, Int) -- ^ pick coordinates
154 -> IO F.Word32 -- ^ resultant pixel value
155pickFrameBuffer fb (w, h) (x, y) = do
156 glFinish
157 glBindFramebuffer GL_READ_FRAMEBUFFER $ fromIntegral fb
158 let (fbmode, format) =
159 if fb == 0
160 then (GL_BACK_LEFT, GL_RGBA)
161 else (GL_COLOR_ATTACHMENT0, GL_RGBA_INTEGER)
162 glReadBuffer fbmode
163 withFrameBuffer w format x (h - y - 1) 1 1 $ \p -> fromIntegral <$> F.peek (F.castPtr p :: F.Ptr F.Word32)
164
165withFrameBuffer :: Int -> GLenum -> Int -> Int -> Int -> Int -> (F.Ptr F.Word8 -> IO a) -> IO a
166withFrameBuffer rowLen format x y w h fn = F.allocaBytes (w*h*4) $ \p -> do
167 glPixelStorei GL_UNPACK_LSB_FIRST 0
168 glPixelStorei GL_UNPACK_SWAP_BYTES 0
169 glPixelStorei GL_UNPACK_ROW_LENGTH $ fromIntegral rowLen
170 glPixelStorei GL_UNPACK_IMAGE_HEIGHT 0
171 glPixelStorei GL_UNPACK_SKIP_ROWS 0
172 glPixelStorei GL_UNPACK_SKIP_PIXELS 0
173 glPixelStorei GL_UNPACK_SKIP_IMAGES 0
174 glPixelStorei GL_UNPACK_ALIGNMENT 1
175 glReadPixels (fromIntegral x) (fromIntegral y) (fromIntegral w) (fromIntegral h) format GL_UNSIGNED_BYTE $ F.castPtr p
176 glPixelStorei GL_UNPACK_ROW_LENGTH 0
177 fn p
178
179initWindow :: String -> Int -> Int -> IO Window
180initWindow title width height = do
181 GLFW.init
182 GLFW.defaultWindowHints
183 mapM_ GLFW.windowHint
184 [ WindowHint'ContextVersionMajor 3
185 , WindowHint'ContextVersionMinor 3
186 , WindowHint'OpenGLProfile OpenGLProfile'Core
187 , WindowHint'OpenGLForwardCompat True
188 ]
189 Just win <- GLFW.createWindow width height title Nothing Nothing
190 GLFW.makeContextCurrent $ Just win
191 return win
192
diff --git a/examples/pickInt.json b/examples/pickInt.json
new file mode 100644
index 0000000..233cd61
--- /dev/null
+++ b/examples/pickInt.json
@@ -0,0 +1 @@
{"textures":[{"textureBaseLevel":0,"textureSize":{"tag":"VV2U","arg0":{"x":800,"y":600}},"tag":"TextureDescriptor","textureMaxLevel":0,"textureSampler":{"samplerMaxLod":null,"samplerLodBias":0,"tag":"SamplerDescriptor","samplerBorderColor":{"tag":"VV4F","arg0":{"w":1,"z":0,"x":0,"y":0}},"samplerMinFilter":{"tag":"Nearest"},"samplerWrapT":{"tag":"Repeat"},"samplerMagFilter":{"tag":"Nearest"},"samplerWrapR":null,"samplerCompareFunc":null,"samplerWrapS":{"tag":"Repeat"},"samplerMinLod":null},"textureType":{"tag":"Texture2D","arg0":{"tag":"IntT","arg0":{"tag":"RGBA"}},"arg1":1},"textureSemantic":{"tag":"Color"}}],"commands":[{"tag":"SetRenderTarget","arg0":0},{"tag":"ClearRenderTarget","arg0":[{"tag":"ClearImage","clearValue":{"tag":"VV4I","arg0":{"w":0,"z":0,"x":0,"y":0}},"imageSemantic":{"tag":"Color"}}]},{"tag":"SetProgram","arg0":0},{"tag":"SetRasterContext","arg0":{"arg3":{"tag":"LastVertex"},"tag":"TriangleCtx","arg0":{"tag":"CullFront","arg0":{"tag":"CCW"}},"arg1":{"tag":"PolygonFill"},"arg2":{"tag":"NoOffset"}}},{"tag":"SetAccumulationContext","arg0":{"accViewportName":null,"tag":"AccumulationContext","accOperations":[{"tag":"ColorOp","arg0":{"tag":"NoBlending"},"arg1":{"tag":"VV4B","arg0":{"w":true,"z":true,"x":true,"y":true}}}]}},{"tag":"RenderSlot","arg0":0}],"slots":[{"tag":"Slot","slotPrimitive":{"tag":"Triangles"},"slotStreams":{"color":{"tag":"V4F"},"id":{"tag":"Int"},"position":{"tag":"V3F"}},"slotName":"objects","slotUniforms":{"viewProj":{"tag":"M44F"}},"slotPrograms":[0]}],"programs":[{"programInTextures":{},"tag":"Program","programOutput":[{"tag":"Parameter","ty":{"tag":"V4I"},"name":"f0"}],"programStreams":{"vi3":{"tag":"Parameter","ty":{"tag":"Int"},"name":"id"},"vi2":{"tag":"Parameter","ty":{"tag":"V4F"},"name":"color"},"vi1":{"tag":"Parameter","ty":{"tag":"V3F"},"name":"position"}},"fragmentShader":"#version 330 core\nvec4 texture2D(sampler2D s,vec2 uv) {\n return texture(s,uv);\n}\nflat in vec2 vo1;\nflat in ivec4 vo2;\nout ivec4 f0;\nvoid main() {\n f0 = vo2;\n}","vertexShader":"#version 330 core\nvec4 texture2D(sampler2D s,vec2 uv) {\n return texture(s,uv);\n}\nuniform mat4 viewProj;\nin vec3 vi1;\nin vec4 vi2;\nin int vi3;\nflat out vec2 vo1;\nflat out ivec4 vo2;\nvoid main() {\n gl_Position = (viewProj) * (vec4 ((vi1).x,(vi1).y,0.0,1.0));\n vo1 = vec2 (0.0,0.0);\n vo2 = ivec4 (0,0,0,vi3);\n}","geometryShader":null,"programUniforms":{"viewProj":{"tag":"M44F"}}}],"samplers":[],"tag":"Pipeline","backend":{"tag":"OpenGL33"},"streams":[],"targets":[{"tag":"RenderTarget","renderTargets":[{"tag":"TargetItem","targetSemantic":{"tag":"Color"},"targetRef":{"tag":"TextureImage","arg0":0,"arg1":0,"arg2":null}}]}],"info":"generated by lambdacube-compiler 0.6.1.0"} \ No newline at end of file
diff --git a/examples/pickInt.lc b/examples/pickInt.lc
new file mode 100644
index 0000000..a75bc19
--- /dev/null
+++ b/examples/pickInt.lc
@@ -0,0 +1,21 @@
1type FB = FrameBuffer 1 '[ 'Color (Vec 4 Int)]
2
3scene :: String -> FB -> FB
4scene name prevFB =
5 Accumulate ((ColorOp NoBlending (one :: Vec 4 Bool)))
6 (mapFragments (\(uv, rgba) -> ((rgba)))
7 $ rasterizePrimitives (TriangleCtx CullFront PolygonFill NoOffset LastVertex) (Flat, Flat)
8 $ mapPrimitives
9 (\(pos, color, id)->
10 ( (Uniform "viewProj" :: Mat 4 4 Float) *. (V4 pos%x pos%y 0 1)
11 , V2 0.0 0.0
12 , V4 0 0 0 id))
13 $ fetch name ( Attribute "position" :: Vec 3 Float
14 , Attribute "color" :: Vec 4 Float
15 , Attribute "id" :: Int))
16 prevFB
17
18main :: Output
19main = TextureOut (V2 800 600) $
20 scene "objects" $
21 FrameBuffer ((colorImage1 (V4 0 0 0 0)))
diff --git a/examples/pickIntDraw.json b/examples/pickIntDraw.json
new file mode 100644
index 0000000..610caf3
--- /dev/null
+++ b/examples/pickIntDraw.json
@@ -0,0 +1 @@
{"textures":[],"commands":[{"tag":"SetRenderTarget","arg0":0},{"tag":"ClearRenderTarget","arg0":[{"tag":"ClearImage","clearValue":{"tag":"VV4F","arg0":{"w":0,"z":0,"x":0,"y":0}},"imageSemantic":{"tag":"Color"}}]},{"tag":"SetProgram","arg0":0},{"tag":"SetRasterContext","arg0":{"arg3":{"tag":"LastVertex"},"tag":"TriangleCtx","arg0":{"tag":"CullFront","arg0":{"tag":"CCW"}},"arg1":{"tag":"PolygonFill"},"arg2":{"tag":"NoOffset"}}},{"tag":"SetAccumulationContext","arg0":{"accViewportName":null,"tag":"AccumulationContext","accOperations":[{"tag":"ColorOp","arg0":{"tag":"NoBlending"},"arg1":{"tag":"VV4B","arg0":{"w":true,"z":true,"x":true,"y":true}}}]}},{"tag":"RenderSlot","arg0":0}],"slots":[{"tag":"Slot","slotPrimitive":{"tag":"Triangles"},"slotStreams":{"color":{"tag":"V4F"},"id":{"tag":"Int"},"position":{"tag":"V3F"}},"slotName":"objects","slotUniforms":{"viewProj":{"tag":"M44F"}},"slotPrograms":[0]}],"programs":[{"programInTextures":{},"tag":"Program","programOutput":[{"tag":"Parameter","ty":{"tag":"V4F"},"name":"f0"}],"programStreams":{"vi3":{"tag":"Parameter","ty":{"tag":"Int"},"name":"id"},"vi2":{"tag":"Parameter","ty":{"tag":"V4F"},"name":"color"},"vi1":{"tag":"Parameter","ty":{"tag":"V3F"},"name":"position"}},"fragmentShader":"#version 330 core\nvec4 texture2D(sampler2D s,vec2 uv) {\n return texture(s,uv);\n}\nflat in vec2 vo1;\nflat in vec4 vo2;\nout vec4 f0;\nvoid main() {\n f0 = vo2;\n}","vertexShader":"#version 330 core\nvec4 texture2D(sampler2D s,vec2 uv) {\n return texture(s,uv);\n}\nuniform mat4 viewProj;\nin vec3 vi1;\nin vec4 vi2;\nin int vi3;\nflat out vec2 vo1;\nflat out vec4 vo2;\nvoid main() {\n gl_Position = (viewProj) * (vec4 ((vi1).x,(vi1).y,0.0,1.0));\n vo1 = vec2 (0.0,0.0);\n vo2 = vi2;\n}","geometryShader":null,"programUniforms":{"viewProj":{"tag":"M44F"}}}],"samplers":[],"tag":"Pipeline","backend":{"tag":"OpenGL33"},"streams":[],"targets":[{"tag":"RenderTarget","renderTargets":[{"tag":"TargetItem","targetSemantic":{"tag":"Color"},"targetRef":{"tag":"Framebuffer","arg0":{"tag":"Color"}}}]}],"info":"generated by lambdacube-compiler 0.6.1.0"} \ No newline at end of file
diff --git a/examples/pickIntDraw.lc b/examples/pickIntDraw.lc
new file mode 100644
index 0000000..fd1a587
--- /dev/null
+++ b/examples/pickIntDraw.lc
@@ -0,0 +1,21 @@
1type FB = FrameBuffer 1 '[ 'Color (Vec 4 Float)]
2
3scene :: String -> FB -> FB
4scene name prevFB =
5 Accumulate ((ColorOp NoBlending (one :: Vec 4 Bool)))
6 (mapFragments (\(uv, rgba) -> ((rgba)))
7 $ rasterizePrimitives (TriangleCtx CullFront PolygonFill NoOffset LastVertex) (Flat, Flat)
8 $ mapPrimitives
9 (\(pos, color, id)->
10 ( (Uniform "viewProj" :: Mat 4 4 Float) *. (V4 pos%x pos%y 0 1)
11 , V2 0.0 0.0
12 , color))
13 $ fetch name ( Attribute "position" :: Vec 3 Float
14 , Attribute "color" :: Vec 4 Float
15 , Attribute "id" :: Int))
16 prevFB
17
18main :: Output
19main = ScreenOut $
20 scene "objects" $
21 FrameBuffer ((colorImage1 (V4 0 0 0 0)))
diff --git a/lambdacube-gl.cabal b/lambdacube-gl.cabal
index d473889..1859262 100644
--- a/lambdacube-gl.cabal
+++ b/lambdacube-gl.cabal
@@ -79,11 +79,34 @@ executable lambdacube-gl-hello
79 bytestring >=0.10 && <0.11, 79 bytestring >=0.10 && <0.11,
80 vector >=0.12 && <0.13, 80 vector >=0.12 && <0.13,
81 JuicyPixels >=3.2 && <3.3, 81 JuicyPixels >=3.2 && <3.3,
82 aeson >= 1.1.2 && <1.3, 82 aeson >= 1.1.2,
83 GLFW-b >= 1.4 && <1.5, 83 GLFW-b >= 1.4,
84 lambdacube-gl, 84 lambdacube-gl,
85 lambdacube-ir == 0.3.* 85 lambdacube-ir == 0.3.*
86 86
87executable lambdacube-gl-pickint
88 if flag(example)
89 Buildable: True
90 else
91 Buildable: False
92
93 hs-source-dirs: examples
94 main-is: pickInt.hs
95 default-language: Haskell2010
96
97 build-depends:
98 GLFW-b >= 1.4,
99 JuicyPixels >=3.2,
100 OpenGLRaw,
101 aeson >= 1.1.2,
102 base,
103 bytestring >=0.10,
104 containers >=0.5,
105 lambdacube-gl,
106 lambdacube-ir,
107 vect,
108 vector >=0.12
109
87executable lambdacube-gl-hello-obj 110executable lambdacube-gl-hello-obj
88 if flag(example) 111 if flag(example)
89 Buildable: True 112 Buildable: True
@@ -103,8 +126,8 @@ executable lambdacube-gl-hello-obj
103 bytestring >=0.10 && <0.11, 126 bytestring >=0.10 && <0.11,
104 vector >=0.12 && <0.13, 127 vector >=0.12 && <0.13,
105 JuicyPixels >=3.2 && <3.3, 128 JuicyPixels >=3.2 && <3.3,
106 aeson >= 1.1.2 && <1.3, 129 aeson >= 1.1.2,
107 GLFW-b >= 1.4 && <1.5, 130 GLFW-b >= 1.4,
108 wavefront >= 0.7 && <1, 131 wavefront >= 0.7 && <1,
109 lambdacube-gl, 132 lambdacube-gl,
110 lambdacube-ir == 0.3.* 133 lambdacube-ir == 0.3.*
@@ -132,10 +155,10 @@ executable lambdacube-gl-test-client
132 base64-bytestring >=1 && <1.1, 155 base64-bytestring >=1 && <1.1,
133 vector >=0.12 && <0.13, 156 vector >=0.12 && <0.13,
134 JuicyPixels >=3.2 && <3.3, 157 JuicyPixels >=3.2 && <3.3,
135 aeson >= 1.1 && <1.3, 158 aeson >= 1.1.2,
136 websockets >= 0.10 && <1, 159 websockets >= 0.10 && <1,
137 network >= 2.6 && <2.7, 160 network >= 2.6 && <2.7,
138 OpenGLRaw >=3.2 && <4, 161 OpenGLRaw >=3.2 && <4,
139 GLFW-b >= 1.4 && <1.5, 162 GLFW-b >= 1.4,
140 lambdacube-gl, 163 lambdacube-gl,
141 lambdacube-ir == 0.3.* 164 lambdacube-ir == 0.3.*
diff --git a/src/LambdaCube/GL/Backend.hs b/src/LambdaCube/GL/Backend.hs
index 324b3e6..0584a34 100644
--- a/src/LambdaCube/GL/Backend.hs
+++ b/src/LambdaCube/GL/Backend.hs
@@ -126,7 +126,7 @@ setupAccumulationContext (AccumulationContext n ops) = cvt ops
126 glDepthFunc $! comparisonFunctionToGLType df 126 glDepthFunc $! comparisonFunctionToGLType df
127 glDepthMask (cvtBool dm) 127 glDepthMask (cvtBool dm)
128 cvtC 0 xs 128 cvtC 0 xs
129 cvt xs = do 129 cvt xs = do
130 glDisable GL_DEPTH_TEST 130 glDisable GL_DEPTH_TEST
131 glDisable GL_STENCIL_TEST 131 glDisable GL_STENCIL_TEST
132 cvtC 0 xs 132 cvtC 0 xs
@@ -169,8 +169,8 @@ setupAccumulationContext (AccumulationContext n ops) = cvt ops
169 cvtBool True = 1 169 cvtBool True = 1
170 cvtBool False = 0 170 cvtBool False = 0
171 171
172clearRenderTarget :: [ClearImage] -> IO () 172clearRenderTarget :: GLRenderTarget -> [ClearImage] -> IO ()
173clearRenderTarget values = do 173clearRenderTarget GLRenderTarget{..} values = do
174 let setClearValue (m,i) value = case value of 174 let setClearValue (m,i) value = case value of
175 ClearImage Depth (VFloat v) -> do 175 ClearImage Depth (VFloat v) -> do
176 glDepthMask 1 176 glDepthMask 1
@@ -180,20 +180,46 @@ clearRenderTarget values = do
180 glClearStencil $ fromIntegral v 180 glClearStencil $ fromIntegral v
181 return (m .|. GL_STENCIL_BUFFER_BIT, i) 181 return (m .|. GL_STENCIL_BUFFER_BIT, i)
182 ClearImage Color c -> do 182 ClearImage Color c -> do
183 let (r,g,b,a) = case c of
184 VFloat r -> (realToFrac r, 0, 0, 1)
185 VV2F (V2 r g) -> (realToFrac r, realToFrac g, 0, 1)
186 VV3F (V3 r g b) -> (realToFrac r, realToFrac g, realToFrac b, 1)
187 VV4F (V4 r g b a) -> (realToFrac r, realToFrac g, realToFrac b, realToFrac a)
188 _ -> (0,0,0,1)
189 glColorMask 1 1 1 1 183 glColorMask 1 1 1 1
190 glClearColor r g b a 184 if framebufferObject == 0
191 return (m .|. GL_COLOR_BUFFER_BIT, i+1) 185 then
186 clearDefaultFB >>
187 pure (m .|. GL_COLOR_BUFFER_BIT, i+1)
188 else
189 clearFBColorAttachment >>
190 pure (m, i+1)
191 where
192 clearDefaultFB = do
193 let (r,g,b,a) = case c of
194 VFloat r -> (realToFrac r, 0, 0, 1)
195 VV2F (V2 r g) -> (realToFrac r, realToFrac g, 0, 1)
196 VV3F (V3 r g b) -> (realToFrac r, realToFrac g, realToFrac b, 1)
197 VV4F (V4 r g b a) -> (realToFrac r, realToFrac g, realToFrac b, realToFrac a)
198 _ -> (0,0,0,1)
199 glClearColor r g b a
200 clearFBColorAttachment = do
201 let buf = GL_COLOR
202 case c of -- there must be some clever way to extract the generality here, I'm sure..
203 VFloat r -> with (V4 r 0 0 1) $ glClearBufferfv buf i . castPtr
204 VV2F (V2 r g) -> with (V4 r g 0 1) $ glClearBufferfv buf i . castPtr
205 VV3F (V3 r g b) -> with (V4 r g b 1) $ glClearBufferfv buf i . castPtr
206 VV4F (V4 r g b a) -> with (V4 r g b a) $ glClearBufferfv buf i . castPtr
207
208 VInt r -> with (V4 r 0 0 1) $ glClearBufferiv buf i . castPtr
209 VV2I (V2 r g) -> with (V4 r g 0 1) $ glClearBufferiv buf i . castPtr
210 VV3I (V3 r g b) -> with (V4 r g b 1) $ glClearBufferiv buf i . castPtr
211 VV4I (V4 r g b a) -> with (V4 r g b a) $ glClearBufferiv buf i . castPtr
212
213 VWord r -> with (V4 r 0 0 1) $ glClearBufferiv buf i . castPtr
214 VV2U (V2 r g) -> with (V4 r g 0 1) $ glClearBufferiv buf i . castPtr
215 VV3U (V3 r g b) -> with (V4 r g b 1) $ glClearBufferiv buf i . castPtr
216 VV4U (V4 r g b a) -> with (V4 r g b a) $ glClearBufferiv buf i . castPtr
217 _ -> error $ "internal error: unsupported color attachment format: " <> show c
218
192 _ -> error "internal error (clearRenderTarget)" 219 _ -> error "internal error (clearRenderTarget)"
193 (mask,_) <- foldM setClearValue (0,0) values 220 (mask,_) <- foldM setClearValue (0,0) values
194 glClear $ fromIntegral mask 221 glClear $ fromIntegral mask
195 222
196
197printGLStatus = checkGL >>= print 223printGLStatus = checkGL >>= print
198printFBOStatus = checkFBO >>= print 224printFBOStatus = checkFBO >>= print
199 225
@@ -283,6 +309,15 @@ compileProgram p = do
283 , inputStreams = Map.fromList [(n,(idx, attrName)) | (n,idx) <- Map.toList $ attributes, let attrName = fromMaybe (error $ "missing attribute: " ++ n) $ Map.lookup n lcStreamName] 309 , inputStreams = Map.fromList [(n,(idx, attrName)) | (n,idx) <- Map.toList $ attributes, let attrName = fromMaybe (error $ "missing attribute: " ++ n) $ Map.lookup n lcStreamName]
284 } 310 }
285 311
312renderTargetOutputs :: Vector GLTexture -> RenderTarget -> GLRenderTarget -> [GLOutput]
313renderTargetOutputs glTexs (RenderTarget targetItems) (GLRenderTarget fbo bufs) =
314 let isFB (Framebuffer _) = True
315 isFB _ = False
316 images = [img | TargetItem _ (Just img) <- V.toList targetItems]
317 in case all isFB images of
318 True -> fromMaybe [] $ (GLOutputDrawBuffer fbo <$>) <$> bufs
319 False -> (\(TextureImage texIdx _ _)-> GLOutputRenderTexture fbo $ glTexs ! texIdx) <$> images
320
286compileRenderTarget :: Vector TextureDescriptor -> Vector GLTexture -> RenderTarget -> IO GLRenderTarget 321compileRenderTarget :: Vector TextureDescriptor -> Vector GLTexture -> RenderTarget -> IO GLRenderTarget
287compileRenderTarget texs glTexs (RenderTarget targets) = do 322compileRenderTarget texs glTexs (RenderTarget targets) = do
288 let isFB (Framebuffer _) = True 323 let isFB (Framebuffer _) = True
@@ -344,7 +379,7 @@ compileRenderTarget texs glTexs (RenderTarget targets) = do
344 | n > 1 -> attachArray 379 | n > 1 -> attachArray
345 | otherwise -> attach2D 380 | otherwise -> attach2D
346 TextureBuffer _ -> fail "internalError (compileRenderTarget/TextureBuffer)!" 381 TextureBuffer _ -> fail "internalError (compileRenderTarget/TextureBuffer)!"
347 382
348 go a (TargetItem Stencil (Just img)) = do 383 go a (TargetItem Stencil (Just img)) = do
349 fail "Stencil support is not implemented yet!" 384 fail "Stencil support is not implemented yet!"
350 return a 385 return a
@@ -453,7 +488,7 @@ createStreamCommands texUnitMap topUnis attrs primitive prg = streamUniCmds ++ s
453 488
454 -- object attribute stream commands 489 -- object attribute stream commands
455 streamCmds = [attrCmd i s | (i,name) <- Map.elems attrMap, let s = fromMaybe (error $ "missing attribute: " ++ name) $ Map.lookup name attrs] 490 streamCmds = [attrCmd i s | (i,name) <- Map.elems attrMap, let s = fromMaybe (error $ "missing attribute: " ++ name) $ Map.lookup name attrs]
456 where 491 where
457 attrMap = inputStreams prg 492 attrMap = inputStreams prg
458 attrCmd i s = case s of 493 attrCmd i s = case s of
459 Stream ty (Buffer arrs bo) arrIdx start len -> case ty of 494 Stream ty (Buffer arrs bo) arrIdx start len -> case ty of
@@ -488,16 +523,25 @@ createStreamCommands texUnitMap topUnis attrs primitive prg = streamUniCmds ++ s
488 -- constant generic attribute 523 -- constant generic attribute
489 constAttr -> GLSetVertexAttrib i constAttr 524 constAttr -> GLSetVertexAttrib i constAttr
490 525
526outputIsRenderTexture :: GLOutput -> Bool
527outputIsRenderTexture GLOutputRenderTexture{..} = True
528outputIsRenderTexture _ = False
529
491allocRenderer :: Pipeline -> IO GLRenderer 530allocRenderer :: Pipeline -> IO GLRenderer
492allocRenderer p = do 531allocRenderer p = do
493 smps <- V.mapM compileSampler $ samplers p 532 smps <- V.mapM compileSampler $ samplers p
494 texs <- V.mapM compileTexture $ textures p 533 texs <- V.mapM compileTexture $ textures p
495 trgs <- V.mapM (compileRenderTarget (textures p) texs) $ targets p 534 let cmds = V.toList $ commands p
535 finalRenderTargetIdx = head [i | SetRenderTarget i <- reverse $ cmds]
536 trgs <- traverse (compileRenderTarget (textures p) texs) $ targets p
537 let finalRenderTarget = targets p ! finalRenderTargetIdx
538 finalGLRenderTarget = trgs ! finalRenderTargetIdx
539 outs = renderTargetOutputs texs finalRenderTarget finalGLRenderTarget
496 prgs <- V.mapM compileProgram $ programs p 540 prgs <- V.mapM compileProgram $ programs p
497 -- texture unit mapping ioref trie 541 -- texture unit mapping ioref trie
498 -- texUnitMapRefs :: Map UniformName (IORef TextureUnit) 542 -- texUnitMapRefs :: Map UniformName (IORef TextureUnit)
499 texUnitMapRefs <- Map.fromList <$> mapM (\k -> (k,) <$> newIORef 0) (Set.toList $ Set.fromList $ concat $ V.toList $ V.map (Map.keys . programInTextures) $ programs p) 543 texUnitMapRefs <- Map.fromList <$> mapM (\k -> (k,) <$> newIORef 0) (Set.toList $ Set.fromList $ concat $ V.toList $ V.map (Map.keys . programInTextures) $ programs p)
500 let st = execState (mapM_ (compileCommand texUnitMapRefs smps texs trgs prgs) (V.toList $ commands p)) initCGState 544 let st = execState (mapM_ (compileCommand texUnitMapRefs smps texs trgs prgs) cmds) initCGState
501 input <- newIORef Nothing 545 input <- newIORef Nothing
502 -- default Vertex Array Object 546 -- default Vertex Array Object
503 vao <- alloca $! \pvao -> glGenVertexArrays 1 pvao >> peek pvao 547 vao <- alloca $! \pvao -> glGenVertexArrays 1 pvao >> peek pvao
@@ -515,6 +559,7 @@ allocRenderer p = do
515 , glCommands = reverse $ drawCommands st 559 , glCommands = reverse $ drawCommands st
516 , glSlotPrograms = V.map (V.toList . slotPrograms) $ IR.slots p 560 , glSlotPrograms = V.map (V.toList . slotPrograms) $ IR.slots p
517 , glInput = input 561 , glInput = input
562 , glOutputs = outs
518 , glSlotNames = V.map slotName $ IR.slots p 563 , glSlotNames = V.map slotName $ IR.slots p
519 , glVAO = vao 564 , glVAO = vao
520 , glTexUnitMapping = texUnitMapRefs 565 , glTexUnitMapping = texUnitMapRefs
@@ -573,7 +618,7 @@ isSubTrie eqFun universe subset = and [isMember a (Map.lookup n universe) | (n,a
573 when (sPrim /= (primitiveToFetchPrimitive prim)) $ throw $ userError $ 618 when (sPrim /= (primitiveToFetchPrimitive prim)) $ throw $ userError $
574 "Primitive mismatch for slot (" ++ show slotName ++ ") expected " ++ show sPrim ++ " but got " ++ show prim 619 "Primitive mismatch for slot (" ++ show slotName ++ ") expected " ++ show sPrim ++ " but got " ++ show prim
575 let sType = fmap streamToStreamType attribs 620 let sType = fmap streamToStreamType attribs
576 when (sType /= sAttrs) $ throw $ userError $ unlines $ 621 when (sType /= sAttrs) $ throw $ userError $ unlines $
577 [ "Attribute stream mismatch for slot (" ++ show slotName ++ ") expected " 622 [ "Attribute stream mismatch for slot (" ++ show slotName ++ ") expected "
578 , show sAttrs 623 , show sAttrs
579 , " but got " 624 , " but got "
@@ -790,7 +835,7 @@ renderFrame GLRenderer{..} = do
790 case cmd of 835 case cmd of
791 GLClearRenderTarget rt vals -> do 836 GLClearRenderTarget rt vals -> do
792 setupRenderTarget glInput rt 837 setupRenderTarget glInput rt
793 clearRenderTarget vals 838 clearRenderTarget rt vals
794 modifyIORef glDrawContextRef $ \ctx -> ctx {glRenderTarget = rt} 839 modifyIORef glDrawContextRef $ \ctx -> ctx {glRenderTarget = rt}
795 840
796 GLRenderStream ctx streamIdx progIdx -> do 841 GLRenderStream ctx streamIdx progIdx -> do
@@ -895,4 +940,4 @@ compileCommand texUnitMap samplers textures targets programs cmd = case cmd of
895 case IM.lookup tu tb of 940 case IM.lookup tu tb of
896 Nothing -> fail "internal error (GenerateMipMap)!" 941 Nothing -> fail "internal error (GenerateMipMap)!"
897 Just tex -> return $ GLGenerateMipMap (GL_TEXTURE0 + fromIntegral tu) (glTextureTarget tex) 942 Just tex -> return $ GLGenerateMipMap (GL_TEXTURE0 + fromIntegral tu) (glTextureTarget tex)
898-} \ No newline at end of file 943-}
diff --git a/src/LambdaCube/GL/Type.hs b/src/LambdaCube/GL/Type.hs
index 49491ed..bd3f827 100644
--- a/src/LambdaCube/GL/Type.hs
+++ b/src/LambdaCube/GL/Type.hs
@@ -152,6 +152,7 @@ data GLRenderer
152 , glTextures :: Vector GLTexture 152 , glTextures :: Vector GLTexture
153 , glSamplers :: Vector GLSampler 153 , glSamplers :: Vector GLSampler
154 , glTargets :: Vector GLRenderTarget 154 , glTargets :: Vector GLRenderTarget
155 , glOutputs :: [GLOutput]
155 , glCommands :: [GLCommand] 156 , glCommands :: [GLCommand]
156 , glSlotPrograms :: Vector [ProgramName] -- programs depend on a slot 157 , glSlotPrograms :: Vector [ProgramName] -- programs depend on a slot
157 , glInput :: IORef (Maybe InputConnection) 158 , glInput :: IORef (Maybe InputConnection)
@@ -177,6 +178,16 @@ data GLRenderTarget
177 , framebufferDrawbuffers :: Maybe [GLenum] 178 , framebufferDrawbuffers :: Maybe [GLenum]
178 } deriving Eq 179 } deriving Eq
179 180
181data GLOutput
182 = GLOutputDrawBuffer
183 { glOutputFBO :: GLuint
184 , glOutputDrawBuffer :: GLenum
185 }
186 | GLOutputRenderTexture
187 { glOutputFBO :: GLuint
188 , glOutputRenderTexture :: GLTexture
189 }
190
180type GLTextureUnit = Int 191type GLTextureUnit = Int
181type GLUniformBinding = GLint 192type GLUniformBinding = GLint
182 193
diff --git a/src/LambdaCube/GL/Util.hs b/src/LambdaCube/GL/Util.hs
index bba322b..b267c7f 100644
--- a/src/LambdaCube/GL/Util.hs
+++ b/src/LambdaCube/GL/Util.hs
@@ -403,6 +403,8 @@ blendingFactorToGLType a = case a of
403 SrcColor -> GL_SRC_COLOR 403 SrcColor -> GL_SRC_COLOR
404 Zero -> GL_ZERO 404 Zero -> GL_ZERO
405 405
406-- XXX: we need to extend IR.TextureDescriptor to carry component bit depth
407-- if we want to avoid making arbitrary decisions here
406textureDataTypeToGLType :: ImageSemantic -> TextureDataType -> GLenum 408textureDataTypeToGLType :: ImageSemantic -> TextureDataType -> GLenum
407textureDataTypeToGLType Color a = case a of 409textureDataTypeToGLType Color a = case a of
408 FloatT Red -> GL_R32F 410 FloatT Red -> GL_R32F
@@ -412,8 +414,8 @@ textureDataTypeToGLType Color a = case a of
412 IntT RG -> GL_RG32I 414 IntT RG -> GL_RG32I
413 WordT RG -> GL_RG32UI 415 WordT RG -> GL_RG32UI
414 FloatT RGBA -> GL_RGBA32F 416 FloatT RGBA -> GL_RGBA32F
415 IntT RGBA -> GL_RGBA32I 417 IntT RGBA -> GL_RGBA8I
416 WordT RGBA -> GL_RGBA32UI 418 WordT RGBA -> GL_RGBA8UI
417 a -> error $ "FIXME: This texture format is not yet supported" ++ show a 419 a -> error $ "FIXME: This texture format is not yet supported" ++ show a
418textureDataTypeToGLType Depth a = case a of 420textureDataTypeToGLType Depth a = case a of
419 FloatT Red -> GL_DEPTH_COMPONENT32F 421 FloatT Red -> GL_DEPTH_COMPONENT32F
@@ -425,14 +427,14 @@ textureDataTypeToGLType Stencil a = case a of
425textureDataTypeToGLArityType :: ImageSemantic -> TextureDataType -> GLenum 427textureDataTypeToGLArityType :: ImageSemantic -> TextureDataType -> GLenum
426textureDataTypeToGLArityType Color a = case a of 428textureDataTypeToGLArityType Color a = case a of
427 FloatT Red -> GL_RED 429 FloatT Red -> GL_RED
428 IntT Red -> GL_RED 430 IntT Red -> GL_RED_INTEGER
429 WordT Red -> GL_RED 431 WordT Red -> GL_RED_INTEGER
430 FloatT RG -> GL_RG 432 FloatT RG -> GL_RG
431 IntT RG -> GL_RG 433 IntT RG -> GL_RG_INTEGER
432 WordT RG -> GL_RG 434 WordT RG -> GL_RG_INTEGER
433 FloatT RGBA -> GL_RGBA 435 FloatT RGBA -> GL_RGBA
434 IntT RGBA -> GL_RGBA 436 IntT RGBA -> GL_RGBA_INTEGER
435 WordT RGBA -> GL_RGBA 437 WordT RGBA -> GL_RGBA_INTEGER
436 a -> error $ "FIXME: This texture format is not yet supported" ++ show a 438 a -> error $ "FIXME: This texture format is not yet supported" ++ show a
437textureDataTypeToGLArityType Depth a = case a of 439textureDataTypeToGLArityType Depth a = case a of
438 FloatT Red -> GL_DEPTH_COMPONENT 440 FloatT Red -> GL_DEPTH_COMPONENT