ToolDistanceMin.py 14 KB

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