Skip to content

Instantly share code, notes, and snippets.

@joncol
Last active December 30, 2024 19:57
Show Gist options
  • Save joncol/3d56046addb8bfc683afe5800bae5fb3 to your computer and use it in GitHub Desktop.
Save joncol/3d56046addb8bfc683afe5800bae5fb3 to your computer and use it in GitHub Desktop.
ImGui + SDL z-order
module Main (main) where
import Control.Exception (bracket, bracket_)
import Control.Monad (unless, when)
import Control.Monad.IO.Class ()
import Control.Monad.Managed
import DearImGui
import DearImGui.OpenGL3
import DearImGui.SDL
import DearImGui.SDL.Renderer
import Graphics.GL
import SDL
main :: IO ()
main = do
-- Initialize SDL
initializeAll
runManaged $ do
-- Create a window using SDL; as we're using OpenGL, we enable OpenGL too
window <- do
let title = "Hello, Dear ImGui!"
let config =
defaultWindow
{ windowGraphicsContext = OpenGLContext defaultOpenGL
, windowInitialSize = V2 1024 768
}
managed $ bracket (createWindow title config) destroyWindow
-- Create an OpenGL context
_glContext <- managed $ bracket (glCreateContext window) glDeleteContext
-- Create an ImGui context
_ <- managed $ bracket createContext destroyContext
-- Initialize ImGui's SDL2 backend
-- managed_ $ bracket_ (sdl2InitForOpenGL window glContext) sdl2Shutdown
-- Initialize ImGui's OpenGL backend
managed_ $ bracket_ openGL3Init openGL3Shutdown
renderer <-
managed $
bracket (createRenderer window -1 defaultRenderer) destroyRenderer
-- Initialize ImGui's SDL2 backend
managed_ $ bracket_ (sdl2InitForSDLRenderer window renderer) sdl2Shutdown
liftIO $ mainLoop window renderer
mainLoop :: Window -> Renderer -> IO ()
mainLoop window renderer = unlessQuit $ do
-- Tell ImGui we're starting a new frame
openGL3NewFrame
sdl2NewFrame
newFrame
-- Draw some shapes using SDL. This will draw on the back buffer.
rendererDrawColor renderer $= V4 64 0 0 255
-- clear renderer
rendererDrawColor renderer $= V4 255 0 0 255
drawLine renderer (P $ V2 100 50) (P $ V2 400 200)
rendererDrawColor renderer $= V4 0 127 0 127
fillRect renderer (Just $ Rectangle (P $ V2 500 250) $ V2 100 50)
-- Build the GUI
setNextWindowFocus
withWindowOpen "Hello, ImGui!" $ do
text "what can we do here!?"
button "Click me" >>= \clicked ->
when clicked $ putStrLn "You clicked the button"
-- Render ImGui stuff to back buffer.
render
glClearColor 0 0 0.25 0
glClear GL_COLOR_BUFFER_BIT
openGL3RenderDrawData =<< getDrawData
-- Moving this to above the `openGL3RenderDrawData =<< getDrawData` only
-- results in the ImGui stuff not being shown at all.
present renderer
mainLoop window renderer
where
-- Process the event loop
unlessQuit action = do
shouldQuit <- gotQuitEvent
unless shouldQuit action
gotQuitEvent = do
ev <- pollEventWithImGui
case ev of
Nothing ->
return False
Just event ->
(isQuit event ||) <$> gotQuitEvent
isQuit event =
eventPayload event == QuitEvent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment