ToolDistanceMin.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 09/29/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore
  8. from AppTool import AppTool
  9. from AppGUI.VisPyVisuals import *
  10. from AppGUI.GUIElements import FCEntry
  11. from shapely.ops import nearest_points
  12. from shapely.geometry import Point, MultiPolygon
  13. from shapely.ops import cascaded_union
  14. import math
  15. import logging
  16. import gettext
  17. import AppTranslation as fcTranslate
  18. import builtins
  19. fcTranslate.apply_language('strings')
  20. if '_' not in builtins.__dict__:
  21. _ = gettext.gettext
  22. log = logging.getLogger('base')
  23. class DistanceMin(AppTool):
  24. toolName = _("Minimum Distance Tool")
  25. def __init__(self, app):
  26. AppTool.__init__(self, app)
  27. self.app = app
  28. self.canvas = self.app.plotcanvas
  29. self.units = self.app.defaults['units'].lower()
  30. self.decimals = self.app.decimals
  31. # ## Title
  32. title_label = QtWidgets.QLabel("<font size=4><b>%s</b></font><br>" % self.toolName)
  33. self.layout.addWidget(title_label)
  34. # ## Form Layout
  35. form_layout = QtWidgets.QFormLayout()
  36. self.layout.addLayout(form_layout)
  37. self.units_label = QtWidgets.QLabel('%s:' % _("Units"))
  38. self.units_label.setToolTip(_("Those are the units in which the distance is measured."))
  39. self.units_value = QtWidgets.QLabel("%s" % str({'mm': _("METRIC (mm)"), 'in': _("INCH (in)")}[self.units]))
  40. self.units_value.setDisabled(True)
  41. self.start_label = QtWidgets.QLabel("%s:" % _('First object point'))
  42. self.start_label.setToolTip(_("This is first object point coordinates.\n"
  43. "This is the start point for measuring distance."))
  44. self.stop_label = QtWidgets.QLabel("%s:" % _('Second object point'))
  45. self.stop_label.setToolTip(_("This is second object point coordinates.\n"
  46. "This is the end point for measuring distance."))
  47. self.distance_x_label = QtWidgets.QLabel('%s:' % _("Dx"))
  48. self.distance_x_label.setToolTip(_("This is the distance measured over the X axis."))
  49. self.distance_y_label = QtWidgets.QLabel('%s:' % _("Dy"))
  50. self.distance_y_label.setToolTip(_("This is the distance measured over the Y axis."))
  51. self.angle_label = QtWidgets.QLabel('%s:' % _("Angle"))
  52. self.angle_label.setToolTip(_("This is orientation angle of the measuring line."))
  53. self.total_distance_label = QtWidgets.QLabel("<b>%s:</b>" % _('DISTANCE'))
  54. self.total_distance_label.setToolTip(_("This is the point to point Euclidean distance."))
  55. self.half_point_label = QtWidgets.QLabel("<b>%s:</b>" % _('Half Point'))
  56. self.half_point_label.setToolTip(_("This is the middle point of the point to point Euclidean distance."))
  57. self.start_entry = FCEntry()
  58. self.start_entry.setReadOnly(True)
  59. self.start_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  60. self.start_entry.setToolTip(_("This is first object point coordinates.\n"
  61. "This is the start point for measuring distance."))
  62. self.stop_entry = FCEntry()
  63. self.stop_entry.setReadOnly(True)
  64. self.stop_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  65. self.stop_entry.setToolTip(_("This is second object point coordinates.\n"
  66. "This is the end point for measuring distance."))
  67. self.distance_x_entry = FCEntry()
  68. self.distance_x_entry.setReadOnly(True)
  69. self.distance_x_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  70. self.distance_x_entry.setToolTip(_("This is the distance measured over the X axis."))
  71. self.distance_y_entry = FCEntry()
  72. self.distance_y_entry.setReadOnly(True)
  73. self.distance_y_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  74. self.distance_y_entry.setToolTip(_("This is the distance measured over the Y axis."))
  75. self.angle_entry = FCEntry()
  76. self.angle_entry.setReadOnly(True)
  77. self.angle_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  78. self.angle_entry.setToolTip(_("This is orientation angle of the measuring line."))
  79. self.total_distance_entry = FCEntry()
  80. self.total_distance_entry.setReadOnly(True)
  81. self.total_distance_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  82. self.total_distance_entry.setToolTip(_("This is the point to point Euclidean distance."))
  83. self.half_point_entry = FCEntry()
  84. self.half_point_entry.setReadOnly(True)
  85. self.half_point_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  86. self.half_point_entry.setToolTip(_("This is the middle point of the point to point Euclidean distance."))
  87. self.measure_btn = QtWidgets.QPushButton(_("Measure"))
  88. self.layout.addWidget(self.measure_btn)
  89. self.jump_hp_btn = QtWidgets.QPushButton(_("Jump to Half Point"))
  90. self.layout.addWidget(self.jump_hp_btn)
  91. self.jump_hp_btn.setDisabled(True)
  92. form_layout.addRow(self.units_label, self.units_value)
  93. form_layout.addRow(self.start_label, self.start_entry)
  94. form_layout.addRow(self.stop_label, self.stop_entry)
  95. form_layout.addRow(self.distance_x_label, self.distance_x_entry)
  96. form_layout.addRow(self.distance_y_label, self.distance_y_entry)
  97. form_layout.addRow(self.angle_label, self.angle_entry)
  98. form_layout.addRow(self.total_distance_label, self.total_distance_entry)
  99. form_layout.addRow(self.half_point_label, self.half_point_entry)
  100. self.layout.addStretch()
  101. self.h_point = (0, 0)
  102. self.measure_btn.clicked.connect(self.activate_measure_tool)
  103. self.jump_hp_btn.clicked.connect(self.on_jump_to_half_point)
  104. def run(self, toggle=False):
  105. self.app.defaults.report_usage("ToolDistanceMin()")
  106. if self.app.tool_tab_locked is True:
  107. return
  108. self.app.ui.notebook.setTabText(2, _("Minimum Distance Tool"))
  109. # if the splitter is hidden, display it
  110. if self.app.ui.splitter.sizes()[0] == 0:
  111. self.app.ui.splitter.setSizes([1, 1])
  112. if toggle:
  113. pass
  114. self.set_tool_ui()
  115. self.app.inform.emit('MEASURING: %s' %
  116. _("Select two objects and no more, to measure the distance between them ..."))
  117. def install(self, icon=None, separator=None, **kwargs):
  118. AppTool.install(self, icon, separator, shortcut='Shift+M', **kwargs)
  119. def set_tool_ui(self):
  120. # Remove anything else in the AppGUI
  121. self.app.ui.tool_scroll_area.takeWidget()
  122. # Put oneself in the AppGUI
  123. self.app.ui.tool_scroll_area.setWidget(self)
  124. # Switch notebook to tool page
  125. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  126. self.units = self.app.defaults['units'].lower()
  127. # initial view of the layout
  128. self.start_entry.set_value('(0, 0)')
  129. self.stop_entry.set_value('(0, 0)')
  130. self.distance_x_entry.set_value('0.0')
  131. self.distance_y_entry.set_value('0.0')
  132. self.angle_entry.set_value('0.0')
  133. self.total_distance_entry.set_value('0.0')
  134. self.half_point_entry.set_value('(0, 0)')
  135. self.jump_hp_btn.setDisabled(True)
  136. log.debug("Minimum Distance Tool --> tool initialized")
  137. def activate_measure_tool(self):
  138. # ENABLE the Measuring TOOL
  139. self.jump_hp_btn.setDisabled(False)
  140. self.units = self.app.defaults['units'].lower()
  141. if self.app.call_source == 'app':
  142. selected_objs = self.app.collection.get_selected()
  143. if len(selected_objs) != 2:
  144. self.app.inform.emit('[WARNING_NOTCL] %s %s' %
  145. (_("Select two objects and no more. Currently the selection has objects: "),
  146. str(len(selected_objs))))
  147. return
  148. else:
  149. if isinstance(selected_objs[0].solid_geometry, list):
  150. try:
  151. selected_objs[0].solid_geometry = MultiPolygon(selected_objs[0].solid_geometry)
  152. except Exception:
  153. selected_objs[0].solid_geometry = cascaded_union(selected_objs[0].solid_geometry)
  154. try:
  155. selected_objs[1].solid_geometry = MultiPolygon(selected_objs[1].solid_geometry)
  156. except Exception:
  157. selected_objs[1].solid_geometry = cascaded_union(selected_objs[1].solid_geometry)
  158. first_pos, last_pos = nearest_points(selected_objs[0].solid_geometry, selected_objs[1].solid_geometry)
  159. elif self.app.call_source == 'geo_editor':
  160. selected_objs = self.app.geo_editor.selected
  161. if len(selected_objs) != 2:
  162. self.app.inform.emit('[WARNING_NOTCL] %s %s' %
  163. (_("Select two objects and no more. Currently the selection has objects: "),
  164. str(len(selected_objs))))
  165. return
  166. else:
  167. first_pos, last_pos = nearest_points(selected_objs[0].geo, selected_objs[1].geo)
  168. elif self.app.call_source == 'exc_editor':
  169. selected_objs = self.app.exc_editor.selected
  170. if len(selected_objs) != 2:
  171. self.app.inform.emit('[WARNING_NOTCL] %s %s' %
  172. (_("Select two objects and no more. Currently the selection has objects: "),
  173. str(len(selected_objs))))
  174. return
  175. else:
  176. # the objects are really MultiLinesStrings made out of 2 lines in cross shape
  177. xmin, ymin, xmax, ymax = selected_objs[0].geo.bounds
  178. first_geo_radius = (xmax - xmin) / 2
  179. first_geo_center = Point(xmin + first_geo_radius, ymin + first_geo_radius)
  180. first_geo = first_geo_center.buffer(first_geo_radius)
  181. # the objects are really MultiLinesStrings made out of 2 lines in cross shape
  182. xmin, ymin, xmax, ymax = selected_objs[1].geo.bounds
  183. last_geo_radius = (xmax - xmin) / 2
  184. last_geo_center = Point(xmin + last_geo_radius, ymin + last_geo_radius)
  185. last_geo = last_geo_center.buffer(last_geo_radius)
  186. first_pos, last_pos = nearest_points(first_geo, last_geo)
  187. elif self.app.call_source == 'grb_editor':
  188. selected_objs = self.app.grb_editor.selected
  189. if len(selected_objs) != 2:
  190. self.app.inform.emit('[WARNING_NOTCL] %s %s' %
  191. (_("Select two objects and no more. Currently the selection has objects: "),
  192. str(len(selected_objs))))
  193. return
  194. else:
  195. first_pos, last_pos = nearest_points(selected_objs[0].geo['solid'], selected_objs[1].geo['solid'])
  196. else:
  197. first_pos, last_pos = 0, 0
  198. self.start_entry.set_value("(%.*f, %.*f)" % (self.decimals, first_pos.x, self.decimals, first_pos.y))
  199. self.stop_entry.set_value("(%.*f, %.*f)" % (self.decimals, last_pos.x, self.decimals, last_pos.y))
  200. dx = first_pos.x - last_pos.x
  201. dy = first_pos.y - last_pos.y
  202. self.distance_x_entry.set_value('%.*f' % (self.decimals, abs(dx)))
  203. self.distance_y_entry.set_value('%.*f' % (self.decimals, abs(dy)))
  204. try:
  205. angle = math.degrees(math.atan(dy / dx))
  206. self.angle_entry.set_value('%.*f' % (self.decimals, angle))
  207. except Exception as e:
  208. pass
  209. d = math.sqrt(dx ** 2 + dy ** 2)
  210. self.total_distance_entry.set_value('%.*f' % (self.decimals, abs(d)))
  211. self.h_point = (min(first_pos.x, last_pos.x) + (abs(dx) / 2), min(first_pos.y, last_pos.y) + (abs(dy) / 2))
  212. if d != 0:
  213. self.half_point_entry.set_value(
  214. "(%.*f, %.*f)" % (self.decimals, self.h_point[0], self.decimals, self.h_point[1])
  215. )
  216. else:
  217. self.half_point_entry.set_value(
  218. "(%.*f, %.*f)" % (self.decimals, 0.0, self.decimals, 0.0)
  219. )
  220. if d != 0:
  221. self.app.inform.emit("{tx1}: {tx2} D(x) = {d_x} | D(y) = {d_y} | {tx3} = {d_z}".format(
  222. tx1=_("MEASURING"),
  223. tx2=_("Result"),
  224. tx3=_("Distance"),
  225. d_x='%*f' % (self.decimals, abs(dx)),
  226. d_y='%*f' % (self.decimals, abs(dy)),
  227. d_z='%*f' % (self.decimals, abs(d)))
  228. )
  229. else:
  230. self.app.inform.emit('[WARNING_NOTCL] %s: %s' %
  231. (_("AppObjects intersects or touch at"),
  232. "(%.*f, %.*f)" % (self.decimals, self.h_point[0], self.decimals, self.h_point[1])))
  233. def on_jump_to_half_point(self):
  234. self.app.on_jump_to(custom_location=self.h_point)
  235. self.app.inform.emit('[success] %s: %s' %
  236. (_("Jumped to the half point between the two selected objects"),
  237. "(%.*f, %.*f)" % (self.decimals, self.h_point[0], self.decimals, self.h_point[1])))
  238. def set_meas_units(self, units):
  239. self.meas.units_label.setText("[" + self.app.options["units"].lower() + "]")
  240. # end of file