operator_modal_view3d.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import bpy
  2. from mathutils import Vector
  3. from bpy.props import FloatVectorProperty
  4. class ViewOperator(bpy.types.Operator):
  5. """Translate the view using mouse events"""
  6. bl_idname = "view3d.modal_operator"
  7. bl_label = "Simple View Operator"
  8. offset: FloatVectorProperty(
  9. name="Offset",
  10. size=3,
  11. )
  12. def execute(self, context):
  13. v3d = context.space_data
  14. rv3d = v3d.region_3d
  15. rv3d.view_location = self._initial_location + Vector(self.offset)
  16. def modal(self, context, event):
  17. v3d = context.space_data
  18. rv3d = v3d.region_3d
  19. if event.type == 'MOUSEMOVE':
  20. self.offset = (self._initial_mouse - Vector((event.mouse_x, event.mouse_y, 0.0))) * 0.02
  21. self.execute(context)
  22. context.area.header_text_set("Offset %.4f %.4f %.4f" % tuple(self.offset))
  23. elif event.type == 'LEFTMOUSE':
  24. context.area.header_text_set(None)
  25. return {'FINISHED'}
  26. elif event.type in {'RIGHTMOUSE', 'ESC'}:
  27. rv3d.view_location = self._initial_location
  28. context.area.header_text_set(None)
  29. return {'CANCELLED'}
  30. return {'RUNNING_MODAL'}
  31. def invoke(self, context, event):
  32. if context.space_data.type == 'VIEW_3D':
  33. v3d = context.space_data
  34. rv3d = v3d.region_3d
  35. if rv3d.view_perspective == 'CAMERA':
  36. rv3d.view_perspective = 'PERSP'
  37. self._initial_mouse = Vector((event.mouse_x, event.mouse_y, 0.0))
  38. self._initial_location = rv3d.view_location.copy()
  39. context.window_manager.modal_handler_add(self)
  40. return {'RUNNING_MODAL'}
  41. else:
  42. self.report({'WARNING'}, "Active space must be a View3d")
  43. return {'CANCELLED'}
  44. def register():
  45. bpy.utils.register_class(ViewOperator)
  46. def unregister():
  47. bpy.utils.unregister_class(ViewOperator)
  48. if __name__ == "__main__":
  49. register()