Drawing in Blender viewport

The Blender 2.80 API provides the 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 2 votes
Article Rating
Subscribe
Notify of
guest

9 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Sal
Sal
2 years ago

If we draw something on a viewport, it will show in a render?

Join
2 years ago

how to erase the draw in blender view port?

lynchon
lynchon
2 years ago

Hi, removing the draw_handle wont clear the viewport drawing, in order to do so I need to restart blender. How can it be done? I’m trying to draw some text in the viewport and remove it afterwards.

lynchon
lynchon
2 years ago
Reply to  Nikita

Well, I tried, but clearly there is something wrong with how I’m doing it. First I run your script which creates the lines as expected, then I run the code below to clear the lines, but nothing happens, I don’t even get any message in console:

lynchon
lynchon
2 years ago
Reply to  lynchon

I keep trying but with no success, here I’m just using a boolean property to switch on and of the draw function… it just keeps drawing it.