operator_modal_draw.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import bpy
  2. import bgl
  3. import blf
  4. import gpu
  5. from gpu_extras.batch import batch_for_shader
  6. def draw_callback_px(self, context):
  7. print("mouse points", len(self.mouse_path))
  8. font_id = 0 # XXX, need to find out how best to get this.
  9. # draw some text
  10. blf.position(font_id, 15, 30, 0)
  11. blf.size(font_id, 20, 72)
  12. blf.draw(font_id, "Hello Word " + str(len(self.mouse_path)))
  13. # 50% alpha, 2 pixel width line
  14. shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR')
  15. bgl.glEnable(bgl.GL_BLEND)
  16. bgl.glLineWidth(2)
  17. batch = batch_for_shader(shader, 'LINE_STRIP', {"pos": self.mouse_path})
  18. shader.bind()
  19. shader.uniform_float("color", (0.0, 0.0, 0.0, 0.5))
  20. batch.draw(shader)
  21. # restore opengl defaults
  22. bgl.glLineWidth(1)
  23. bgl.glDisable(bgl.GL_BLEND)
  24. class ModalDrawOperator(bpy.types.Operator):
  25. """Draw a line with the mouse"""
  26. bl_idname = "view3d.modal_operator"
  27. bl_label = "Simple Modal View3D Operator"
  28. def modal(self, context, event):
  29. context.area.tag_redraw()
  30. if event.type == 'MOUSEMOVE':
  31. self.mouse_path.append((event.mouse_region_x, event.mouse_region_y))
  32. elif event.type == 'LEFTMOUSE':
  33. bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
  34. return {'FINISHED'}
  35. elif event.type in {'RIGHTMOUSE', 'ESC'}:
  36. bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
  37. return {'CANCELLED'}
  38. return {'RUNNING_MODAL'}
  39. def invoke(self, context, event):
  40. if context.area.type == 'VIEW_3D':
  41. # the arguments we pass the the callback
  42. args = (self, context)
  43. # Add the region OpenGL drawing callback
  44. # draw in view space with 'POST_VIEW' and 'PRE_VIEW'
  45. self._handle = bpy.types.SpaceView3D.draw_handler_add(draw_callback_px, args, 'WINDOW', 'POST_PIXEL')
  46. self.mouse_path = []
  47. context.window_manager.modal_handler_add(self)
  48. return {'RUNNING_MODAL'}
  49. else:
  50. self.report({'WARNING'}, "View3D not found, cannot run operator")
  51. return {'CANCELLED'}
  52. def register():
  53. bpy.utils.register_class(ModalDrawOperator)
  54. def unregister():
  55. bpy.utils.unregister_class(ModalDrawOperator)
  56. if __name__ == "__main__":
  57. register()