As described in API the following script will create a mesh from active object using bgl module:

import bpy
import gpu
import bgl
import numpy as np
from random import random
from gpu_extras.batch import batch_for_shader

mesh = bpy.context.active_object.data

vertices = np.empty((len(mesh.vertices), 3), 'f')
indices = np.empty((len(mesh.loop_triangles), 3), 'i')

    "co", np.reshape(vertices, len(mesh.vertices) * 3))
    "vertices", np.reshape(indices, len(mesh.loop_triangles) * 3))

vertex_colors = [(random(), random(), random(), 1) for _ in range(len(mesh.vertices))]

shader = gpu.shader.from_builtin('3D_SMOOTH_COLOR')
batch = batch_for_shader(
    shader, 'TRIS',
    {"pos": vertices, "color": vertex_colors},

def draw():

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

But the created mesh flips when nothing is selected:

enter image description here

Please help!

  • $\begingroup$ Script draws a randomly vertex coloured bgl representation of mesh. based on the context active object when run. It keeps drawing this same object. Running with no object selected will cause an error. To draw dynamically based on context object will need to adjust shader data based on this, and pass (for example) context as an argument to the draw call back method. (See other examples) $\endgroup$ – batFINGER Jan 6 at 12:35
  • $\begingroup$ @batFinger I already know what the script does. my question is about when the mesh is created (so no errors would happen). after the mesh(es) is(are) created if we deselect everything, any bgl mesh would be flipped. I'm searching for a GL option or something like that to solve the problem $\endgroup$ – MohammadHossein Jamshidi Jan 11 at 7:46
  • $\begingroup$ @batFinger I've tested adding flipping indices. It doesn't work either! $\endgroup$ – MohammadHossein Jamshidi Jan 11 at 7:46
  • $\begingroup$ To clarify this. For me if run on default cube, no issue when selecting another object. Is this the case for you. If so it leads towards the concavities in mesh above, and if this effects the bgl display on screen when active. $\endgroup$ – batFINGER Jan 11 at 9:53
  • 1
    $\begingroup$ would also suggest if you are using code similar, but not the same as above, post that code. As mentioned I do not see this behaviour. $\endgroup$ – batFINGER Jan 11 at 14:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.