Drawing in Blender viewport

The Blender 2.80 API provides an ability to draw in a viewport (3D Viewport) using the “gpu” module.

As an example let’s draw a simple coordinate system widget in the center of the scene, consisting of three lines with different colors.

Custom viewport drawing is performed with the same principles as common meshes are displayed in it. To draw some object in the viewport we need to specify the location of its vertices and assign them a shader.

Let’s set the coordinates for six vertices, each pair of which forms an edge from the center of coordinates – the origin (0.0, 0.0, 0.0) to a point spaced 1 by the desired axis (X, Y, and Z):

For each vertex, let’s set the color in RGBA format. For the first pair of vertices – red (1.0, 0.0, 0.0), for the second – blue (0.0, 1.0, 0.0) and for the third pair – green (0.0, 0.0, 1.0).

and make a shader:

Compile all to the batch for drawing it in the viewport:

The second parameter value “LINES” sets the display mode, in our case – drawing lines by the specified points.

Define a function that will render the given batch in the viewport:

and add it to the viewport drawing handler.

Now the “draw” function will be called every time the viewport is updated.

For initial drawing we can force the viewport update:

Full code:

After executing this code we can see our widget in the center of the scene:

Not all features have been transferred to the “gpu” AIP module yet. For example, to set the line thickness, you need to use the “bgl” module:

The final code:

To remove the widget rendering, we need to remove our “draw” function from the window update handler.

5 1 vote
Article Rating
Notify of
0 Comment
Inline Feedbacks
View all comments