1
$\begingroup$

I have problems with the GPU Module and rendering custom geometry in Blender. When I run the example code from the Blender docs, it works as expected. Running the first line drawing example produces the image below, drawing a thin red line ten units up in Z:

import bpy
import gpu
from gpu_extras.batch import batch_for_shader

coords = [(0, 0, 0), (0, 0, 10)]
shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR')
batch = batch_for_shader(shader, 'LINES', {"pos": coords})


def draw():
    shader.bind()
    shader.uniform_float("color", (1, 0, 0, 1))
    batch.draw(shader)


bpy.types.SpaceView3D.draw_handler_add(draw, (), 'WINDOW', 'POST_VIEW')

enter image description here

But, when I try to encapsulate the code in a simple class, things get weird. The same coordinates in the code produces a line in a weird position, downwards at an angle instead of straight up. And I have to execute the code twice to make it even show up.

import bpy
import gpu
from gpu_extras.batch import batch_for_shader


class drawManager:
    
    coords = []
    shader = None
    batch = None
    handle = None

    def __init__(self):
        self.coords = [(0, 0, 0), (0, 0, 10)]
        self.shader = gpu.shader.from_builtin('3D_UNIFORM_COLOR')
        self.batch = batch_for_shader(self.shader, 'LINES', {"pos": self.coords})
        

    def draw(self):
        self.shader.bind()
        self.shader.uniform_float("color", (1, 0, 0, 1))
        self.batch.draw(self.shader)

    def doDraw(self):
        handle = bpy.types.SpaceView3D.draw_handler_add(self.draw, (), 'WINDOW', 'POST_VIEW')
        
    def stopDraw(self):
        bpy.types.SpaceView3D.draw_handler_remove(self.handle, 'WINDOW')
        

dm = drawManager()
dm.draw()
dm.doDraw()

enter image description here

Am I missing something essential here or is this a weird bug?

$\endgroup$
2
  • 2
    $\begingroup$ Please do not add "solved" as part of the title. Write an answer so that other users will learn from what you learned. Please take the tour to understand how the site works. Also read:Can I answer my own question? $\endgroup$
    – Timaroberts
    Commented Dec 31, 2020 at 6:30
  • $\begingroup$ Can not emulate the issue shown above. Both examples give same result. $\endgroup$
    – batFINGER
    Commented Dec 31, 2020 at 17:40

1 Answer 1

1
$\begingroup$

The problem seems to arise only when using uniform_float(). Instead I put the position/color information inside the batch_for_shader()-function and update it whenever necessary. It now works like a charm.

$\endgroup$
1
  • 2
    $\begingroup$ Please post amended code. $\endgroup$
    – batFINGER
    Commented Dec 31, 2020 at 17:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .