CodePlea icon
CodePlea
Random thoughts on programming
04 Mar 2015

OpenGL with C and Tcl/Tk


Tcl/Tk has been my language of choice lately for doing GUIs. I often combine this with a C back-end for some of the heavy lifting. A few times I've needed a 3D visualization in C and OpenGL, but was stuck without a good GUI. So the obvious solution was to combine C and Tcl/Tk with OpenGL.

There are a few existing solutions for combining Tcl/Tk with OpenGL (see the Tcl wiki). However, everything I've found has had some shortcoming. Almost all of these projects are old and not maintained. This can make even compiling them a huge pain. Also, I didn't really want to actually do 3D from Tcl. Tcl is great for text processing and glue logic, but it's not my favorite language for math.

It turns out there is a very easy way to combine Tcl/Tk with OpenGL and C on Windows. It involves making a frame widget in Tcl, and then passing its HWND to C to initialize the OpenGL rendering context.

#We'll use a frame control to draw our OpenGL.
set display [frame .opengl -width 800 -height 500 -background white -takefocus 1]
pack $display -fill both -expand 1

#Tell C where to put the OpenGL
SetRenderWindow [winfo id $display]

#Tell C when the window resizes
bind $display  {Resize %w %h}

Both SetRenderWindow and Resize are commands added in C. SetRenderWindow takes the HWND and creates an OpenGL rendering context. Resize uses the new size info from TCL to change the OpenGL viewport.

All of the OpenGL math and rendering is done from C. We use the Tcl_CreateTimerHandler function to create a regular callback for rendering.

This way it's easy to use OpenGL from C with a nice Tcl/Tk GUI.

Tcl/TK app showing 3d cube in OpenGL.

Update July 2017: Todd Nordland gave me code to make this work on Linux with X11. I've posted the updated code on Github here.


Like this post? Consider following me on Twitter or following me on Github. Don't forget to subscribe to my feed.