Cleanup: use staticmethod where appropriate
[blender.git] / release / scripts / templates_py / operator_modal_draw.py
1 import bpy
2 import bgl
3 import blf
4
5
6 def draw_callback_px(self, context):
7     print("mouse points", len(self.mouse_path))
8
9     font_id = 0  # XXX, need to find out how best to get this.
10
11     # draw some text
12     blf.position(font_id, 15, 30, 0)
13     blf.size(font_id, 20, 72)
14     blf.draw(font_id, "Hello Word " + str(len(self.mouse_path)))
15
16     # 50% alpha, 2 pixel width line
17     bgl.glEnable(bgl.GL_BLEND)
18     bgl.glColor4f(0.0, 0.0, 0.0, 0.5)
19     bgl.glLineWidth(2)
20
21     bgl.glBegin(bgl.GL_LINE_STRIP)
22     for x, y in self.mouse_path:
23         bgl.glVertex2i(x, y)
24
25     bgl.glEnd()
26
27     # restore opengl defaults
28     bgl.glLineWidth(1)
29     bgl.glDisable(bgl.GL_BLEND)
30     bgl.glColor4f(0.0, 0.0, 0.0, 1.0)
31
32
33 class ModalDrawOperator(bpy.types.Operator):
34     """Draw a line with the mouse"""
35     bl_idname = "view3d.modal_operator"
36     bl_label = "Simple Modal View3D Operator"
37
38     def modal(self, context, event):
39         context.area.tag_redraw()
40
41         if event.type == 'MOUSEMOVE':
42             self.mouse_path.append((event.mouse_region_x, event.mouse_region_y))
43
44         elif event.type == 'LEFTMOUSE':
45             bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
46             return {'FINISHED'}
47
48         elif event.type in {'RIGHTMOUSE', 'ESC'}:
49             bpy.types.SpaceView3D.draw_handler_remove(self._handle, 'WINDOW')
50             return {'CANCELLED'}
51
52         return {'RUNNING_MODAL'}
53
54     def invoke(self, context, event):
55         if context.area.type == 'VIEW_3D':
56             # the arguments we pass the the callback
57             args = (self, context)
58             # Add the region OpenGL drawing callback
59             # draw in view space with 'POST_VIEW' and 'PRE_VIEW'
60             self._handle = bpy.types.SpaceView3D.draw_handler_add(draw_callback_px, args, 'WINDOW', 'POST_PIXEL')
61
62             self.mouse_path = []
63
64             context.window_manager.modal_handler_add(self)
65             return {'RUNNING_MODAL'}
66         else:
67             self.report({'WARNING'}, "View3D not found, cannot run operator")
68             return {'CANCELLED'}
69
70
71 def register():
72     bpy.utils.register_class(ModalDrawOperator)
73
74
75 def unregister():
76     bpy.utils.unregister_class(ModalDrawOperator)
77
78
79 if __name__ == "__main__":
80     register()