ToolCutOut.py 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 3/10/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtGui, QtCore
  8. from FlatCAMTool import FlatCAMTool
  9. from flatcamGUI.GUIElements import FCDoubleSpinner, FCCheckBox, RadioSet, FCComboBox, OptionalInputSection, FCButton
  10. from shapely.geometry import box, MultiPolygon, Polygon, LineString, LinearRing
  11. from shapely.ops import cascaded_union, unary_union
  12. import shapely.affinity as affinity
  13. from matplotlib.backend_bases import KeyEvent as mpl_key_event
  14. from numpy import Inf
  15. from copy import deepcopy
  16. import math
  17. import logging
  18. import gettext
  19. import FlatCAMTranslation as fcTranslate
  20. import builtins
  21. fcTranslate.apply_language('strings')
  22. if '_' not in builtins.__dict__:
  23. _ = gettext.gettext
  24. log = logging.getLogger('base')
  25. settings = QtCore.QSettings("Open Source", "FlatCAM")
  26. if settings.contains("machinist"):
  27. machinist_setting = settings.value('machinist', type=int)
  28. else:
  29. machinist_setting = 0
  30. class CutOut(FlatCAMTool):
  31. toolName = _("Cutout PCB")
  32. def __init__(self, app):
  33. FlatCAMTool.__init__(self, app)
  34. self.app = app
  35. self.canvas = app.plotcanvas
  36. self.decimals = self.app.decimals
  37. # Title
  38. title_label = QtWidgets.QLabel("%s" % self.toolName)
  39. title_label.setStyleSheet("""
  40. QLabel
  41. {
  42. font-size: 16px;
  43. font-weight: bold;
  44. }
  45. """)
  46. self.layout.addWidget(title_label)
  47. self.layout.addWidget(QtWidgets.QLabel(''))
  48. # Form Layout
  49. grid0 = QtWidgets.QGridLayout()
  50. grid0.setColumnStretch(0, 0)
  51. grid0.setColumnStretch(1, 1)
  52. self.layout.addLayout(grid0)
  53. self.object_label = QtWidgets.QLabel('<b>%s:</b>' % _("Source Object"))
  54. self.object_label.setToolTip('%s.' % _("Object to be cutout"))
  55. grid0.addWidget(self.object_label, 0, 0, 1, 2)
  56. # Object kind
  57. self.kindlabel = QtWidgets.QLabel('%s:' % _('Kind'))
  58. self.kindlabel.setToolTip(
  59. _("Choice of what kind the object we want to cutout is.<BR>"
  60. "- <B>Single</B>: contain a single PCB Gerber outline object.<BR>"
  61. "- <B>Panel</B>: a panel PCB Gerber object, which is made\n"
  62. "out of many individual PCB outlines.")
  63. )
  64. self.obj_kind_combo = RadioSet([
  65. {"label": _("Single"), "value": "single"},
  66. {"label": _("Panel"), "value": "panel"},
  67. ])
  68. grid0.addWidget(self.kindlabel, 1, 0)
  69. grid0.addWidget(self.obj_kind_combo, 1, 1)
  70. # Type of object to be cutout
  71. self.type_obj_radio = RadioSet([
  72. {"label": _("Gerber"), "value": "grb"},
  73. {"label": _("Geometry"), "value": "geo"},
  74. ])
  75. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Type"))
  76. self.type_obj_combo_label.setToolTip(
  77. _("Specify the type of object to be cutout.\n"
  78. "It can be of type: Gerber or Geometry.\n"
  79. "What is selected here will dictate the kind\n"
  80. "of objects that will populate the 'Object' combobox.")
  81. )
  82. grid0.addWidget(self.type_obj_combo_label, 2, 0)
  83. grid0.addWidget(self.type_obj_radio, 2, 1)
  84. # Object to be cutout
  85. self.obj_combo = FCComboBox()
  86. self.obj_combo.setModel(self.app.collection)
  87. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  88. self.obj_combo.is_last = True
  89. grid0.addWidget(self.obj_combo, 3, 0, 1, 2)
  90. separator_line = QtWidgets.QFrame()
  91. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  92. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  93. grid0.addWidget(separator_line, 4, 0, 1, 2)
  94. grid0.addWidget(QtWidgets.QLabel(''), 5, 0, 1, 2)
  95. self.param_label = QtWidgets.QLabel('<b>%s:</b>' % _("Tool Parameters"))
  96. grid0.addWidget(self.param_label, 6, 0, 1, 2)
  97. # Tool Diameter
  98. self.dia = FCDoubleSpinner(callback=self.confirmation_message)
  99. self.dia.set_precision(self.decimals)
  100. self.dia.set_range(0.0000, 9999.9999)
  101. self.dia_label = QtWidgets.QLabel('%s:' % _("Tool Diameter"))
  102. self.dia_label.setToolTip(
  103. _("Diameter of the tool used to cutout\n"
  104. "the PCB shape out of the surrounding material.")
  105. )
  106. grid0.addWidget(self.dia_label, 8, 0)
  107. grid0.addWidget(self.dia, 8, 1)
  108. # Cut Z
  109. cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  110. cutzlabel.setToolTip(
  111. _(
  112. "Cutting depth (negative)\n"
  113. "below the copper surface."
  114. )
  115. )
  116. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  117. self.cutz_entry.set_precision(self.decimals)
  118. if machinist_setting == 0:
  119. self.cutz_entry.setRange(-9999.9999, -0.00001)
  120. else:
  121. self.cutz_entry.setRange(-9999.9999, 9999.9999)
  122. self.cutz_entry.setSingleStep(0.1)
  123. grid0.addWidget(cutzlabel, 9, 0)
  124. grid0.addWidget(self.cutz_entry, 9, 1)
  125. # Multi-pass
  126. self.mpass_cb = FCCheckBox('%s:' % _("Multi-Depth"))
  127. self.mpass_cb.setToolTip(
  128. _(
  129. "Use multiple passes to limit\n"
  130. "the cut depth in each pass. Will\n"
  131. "cut multiple times until Cut Z is\n"
  132. "reached."
  133. )
  134. )
  135. self.maxdepth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  136. self.maxdepth_entry.set_precision(self.decimals)
  137. self.maxdepth_entry.setRange(0, 9999.9999)
  138. self.maxdepth_entry.setSingleStep(0.1)
  139. self.maxdepth_entry.setToolTip(
  140. _(
  141. "Depth of each pass (positive)."
  142. )
  143. )
  144. self.ois_mpass_geo = OptionalInputSection(self.mpass_cb, [self.maxdepth_entry])
  145. grid0.addWidget(self.mpass_cb, 10, 0)
  146. grid0.addWidget(self.maxdepth_entry, 10, 1)
  147. # Margin
  148. self.margin = FCDoubleSpinner(callback=self.confirmation_message)
  149. self.margin.set_range(-9999.9999, 9999.9999)
  150. self.margin.setSingleStep(0.1)
  151. self.margin.set_precision(self.decimals)
  152. self.margin_label = QtWidgets.QLabel('%s:' % _("Margin"))
  153. self.margin_label.setToolTip(
  154. _("Margin over bounds. A positive value here\n"
  155. "will make the cutout of the PCB further from\n"
  156. "the actual PCB border")
  157. )
  158. grid0.addWidget(self.margin_label, 11, 0)
  159. grid0.addWidget(self.margin, 11, 1)
  160. # Gapsize
  161. self.gapsize = FCDoubleSpinner(callback=self.confirmation_message)
  162. self.gapsize.set_precision(self.decimals)
  163. self.gapsize_label = QtWidgets.QLabel('%s:' % _("Gap size"))
  164. self.gapsize_label.setToolTip(
  165. _("The size of the bridge gaps in the cutout\n"
  166. "used to keep the board connected to\n"
  167. "the surrounding material (the one \n"
  168. "from which the PCB is cutout).")
  169. )
  170. grid0.addWidget(self.gapsize_label, 13, 0)
  171. grid0.addWidget(self.gapsize, 13, 1)
  172. # How gaps wil be rendered:
  173. # lr - left + right
  174. # tb - top + bottom
  175. # 4 - left + right +top + bottom
  176. # 2lr - 2*left + 2*right
  177. # 2tb - 2*top + 2*bottom
  178. # 8 - 2*left + 2*right +2*top + 2*bottom
  179. # Surrounding convex box shape
  180. self.convex_box = FCCheckBox('%s' % _("Convex Shape"))
  181. # self.convex_box_label = QtWidgets.QLabel('%s' % _("Convex Sh."))
  182. self.convex_box.setToolTip(
  183. _("Create a convex shape surrounding the entire PCB.\n"
  184. "Used only if the source object type is Gerber.")
  185. )
  186. grid0.addWidget(self.convex_box, 15, 0, 1, 2)
  187. separator_line = QtWidgets.QFrame()
  188. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  189. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  190. grid0.addWidget(separator_line, 16, 0, 1, 2)
  191. grid0.addWidget(QtWidgets.QLabel(''), 17, 0, 1, 2)
  192. # Title2
  193. title_param_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('A. Automatic Bridge Gaps'))
  194. title_param_label.setToolTip(
  195. _("This section handle creation of automatic bridge gaps.")
  196. )
  197. grid0.addWidget(title_param_label, 18, 0, 1, 2)
  198. # Gaps
  199. gaps_label = QtWidgets.QLabel('%s:' % _('Gaps'))
  200. gaps_label.setToolTip(
  201. _("Number of gaps used for the Automatic cutout.\n"
  202. "There can be maximum 8 bridges/gaps.\n"
  203. "The choices are:\n"
  204. "- None - no gaps\n"
  205. "- lr - left + right\n"
  206. "- tb - top + bottom\n"
  207. "- 4 - left + right +top + bottom\n"
  208. "- 2lr - 2*left + 2*right\n"
  209. "- 2tb - 2*top + 2*bottom\n"
  210. "- 8 - 2*left + 2*right +2*top + 2*bottom")
  211. )
  212. # gaps_label.setMinimumWidth(60)
  213. self.gaps = FCComboBox()
  214. gaps_items = ['None', 'LR', 'TB', '4', '2LR', '2TB', '8']
  215. for it in gaps_items:
  216. self.gaps.addItem(it)
  217. self.gaps.setStyleSheet('background-color: rgb(255,255,255)')
  218. grid0.addWidget(gaps_label, 19, 0)
  219. grid0.addWidget(self.gaps, 19, 1)
  220. # Buttons
  221. self.ff_cutout_object_btn = FCButton(_("Generate Freeform Geometry"))
  222. self.ff_cutout_object_btn.setToolTip(
  223. _("Cutout the selected object.\n"
  224. "The cutout shape can be of any shape.\n"
  225. "Useful when the PCB has a non-rectangular shape.")
  226. )
  227. self.ff_cutout_object_btn.setStyleSheet("""
  228. QPushButton
  229. {
  230. font-weight: bold;
  231. }
  232. """)
  233. grid0.addWidget(self.ff_cutout_object_btn, 20, 0, 1, 2)
  234. self.rect_cutout_object_btn = FCButton(_("Generate Rectangular Geometry"))
  235. self.rect_cutout_object_btn.setToolTip(
  236. _("Cutout the selected object.\n"
  237. "The resulting cutout shape is\n"
  238. "always a rectangle shape and it will be\n"
  239. "the bounding box of the Object.")
  240. )
  241. self.rect_cutout_object_btn.setStyleSheet("""
  242. QPushButton
  243. {
  244. font-weight: bold;
  245. }
  246. """)
  247. grid0.addWidget(self.rect_cutout_object_btn, 21, 0, 1, 2)
  248. separator_line = QtWidgets.QFrame()
  249. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  250. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  251. grid0.addWidget(separator_line, 22, 0, 1, 2)
  252. # Title5
  253. title_manual_label = QtWidgets.QLabel("<font size=4><b>%s</b></font>" % _('B. Manual Bridge Gaps'))
  254. title_manual_label.setToolTip(
  255. _("This section handle creation of manual bridge gaps.\n"
  256. "This is done by mouse clicking on the perimeter of the\n"
  257. "Geometry object that is used as a cutout object. ")
  258. )
  259. grid0.addWidget(title_manual_label, 23, 0, 1, 2)
  260. # Manual Geo Object
  261. self.man_object_combo = FCComboBox()
  262. self.man_object_combo.setModel(self.app.collection)
  263. self.man_object_combo.setRootModelIndex(self.app.collection.index(2, 0, QtCore.QModelIndex()))
  264. self.man_object_combo.is_last = True
  265. self.man_object_combo.obj_type = "Geometry"
  266. self.man_object_label = QtWidgets.QLabel('%s:' % _("Geometry Object"))
  267. self.man_object_label.setToolTip(
  268. _("Geometry object used to create the manual cutout.")
  269. )
  270. # self.man_object_label.setMinimumWidth(60)
  271. grid0.addWidget(self.man_object_label, 25, 0, 1, 2)
  272. grid0.addWidget(self.man_object_combo, 26, 0, 1, 2)
  273. self.man_geo_creation_btn = FCButton(_("Generate Manual Geometry"))
  274. self.man_geo_creation_btn.setToolTip(
  275. _("If the object to be cutout is a Gerber\n"
  276. "first create a Geometry that surrounds it,\n"
  277. "to be used as the cutout, if one doesn't exist yet.\n"
  278. "Select the source Gerber file in the top object combobox.")
  279. )
  280. self.man_geo_creation_btn.setStyleSheet("""
  281. QPushButton
  282. {
  283. font-weight: bold;
  284. }
  285. """)
  286. grid0.addWidget(self.man_geo_creation_btn, 28, 0, 1, 2)
  287. self.man_gaps_creation_btn = FCButton(_("Manual Add Bridge Gaps"))
  288. self.man_gaps_creation_btn.setToolTip(
  289. _("Use the left mouse button (LMB) click\n"
  290. "to create a bridge gap to separate the PCB from\n"
  291. "the surrounding material.\n"
  292. "The LMB click has to be done on the perimeter of\n"
  293. "the Geometry object used as a cutout geometry.")
  294. )
  295. self.man_gaps_creation_btn.setStyleSheet("""
  296. QPushButton
  297. {
  298. font-weight: bold;
  299. }
  300. """)
  301. grid0.addWidget(self.man_gaps_creation_btn, 30, 0, 1, 2)
  302. self.layout.addStretch()
  303. # ## Reset Tool
  304. self.reset_button = FCButton(_("Reset Tool"))
  305. self.reset_button.setToolTip(
  306. _("Will reset the tool parameters.")
  307. )
  308. self.reset_button.setStyleSheet("""
  309. QPushButton
  310. {
  311. font-weight: bold;
  312. }
  313. """)
  314. self.layout.addWidget(self.reset_button)
  315. self.cutting_gapsize = 0.0
  316. self.cutting_dia = 0.0
  317. # true if we want to repeat the gap without clicking again on the button
  318. self.repeat_gap = False
  319. self.flat_geometry = []
  320. # this is the Geometry object generated in this class to be used for adding manual gaps
  321. self.man_cutout_obj = None
  322. # if mouse is dragging set the object True
  323. self.mouse_is_dragging = False
  324. # event handlers references
  325. self.kp = None
  326. self.mm = None
  327. self.mr = None
  328. # hold the mouse position here
  329. self.x_pos = None
  330. self.y_pos = None
  331. # store the default data for the resulting Geometry Object
  332. self.default_data = {}
  333. # Signals
  334. self.ff_cutout_object_btn.clicked.connect(self.on_freeform_cutout)
  335. self.rect_cutout_object_btn.clicked.connect(self.on_rectangular_cutout)
  336. self.type_obj_radio.activated_custom.connect(self.on_type_obj_changed)
  337. self.man_geo_creation_btn.clicked.connect(self.on_manual_geo)
  338. self.man_gaps_creation_btn.clicked.connect(self.on_manual_gap_click)
  339. self.reset_button.clicked.connect(self.set_tool_ui)
  340. def on_type_obj_changed(self, val):
  341. obj_type = {'grb': 0, 'geo': 2}[val]
  342. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  343. self.obj_combo.setCurrentIndex(0)
  344. self.obj_combo.obj_type = {"grb": "Gerber", "geo": "Geometry"}[val]
  345. def run(self, toggle=True):
  346. self.app.defaults.report_usage("ToolCutOut()")
  347. if toggle:
  348. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  349. if self.app.ui.splitter.sizes()[0] == 0:
  350. self.app.ui.splitter.setSizes([1, 1])
  351. else:
  352. try:
  353. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  354. # if tab is populated with the tool but it does not have the focus, focus on it
  355. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  356. # focus on Tool Tab
  357. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  358. else:
  359. self.app.ui.splitter.setSizes([0, 1])
  360. except AttributeError:
  361. pass
  362. else:
  363. if self.app.ui.splitter.sizes()[0] == 0:
  364. self.app.ui.splitter.setSizes([1, 1])
  365. FlatCAMTool.run(self)
  366. self.set_tool_ui()
  367. self.app.ui.notebook.setTabText(2, _("Cutout Tool"))
  368. def install(self, icon=None, separator=None, **kwargs):
  369. FlatCAMTool.install(self, icon, separator, shortcut='Alt+X', **kwargs)
  370. def set_tool_ui(self):
  371. self.reset_fields()
  372. self.dia.set_value(float(self.app.defaults["tools_cutouttooldia"]))
  373. self.obj_kind_combo.set_value(self.app.defaults["tools_cutoutkind"])
  374. self.margin.set_value(float(self.app.defaults["tools_cutoutmargin"]))
  375. self.cutz_entry.set_value(float(self.app.defaults["tools_cutout_z"]))
  376. self.mpass_cb.set_value(float(self.app.defaults["tools_cutout_mdepth"]))
  377. self.maxdepth_entry.set_value(float(self.app.defaults["tools_cutout_depthperpass"]))
  378. self.gapsize.set_value(float(self.app.defaults["tools_cutoutgapsize"]))
  379. self.gaps.set_value(self.app.defaults["tools_gaps_ff"])
  380. self.convex_box.set_value(self.app.defaults['tools_cutout_convexshape'])
  381. self.type_obj_radio.set_value('grb')
  382. self.default_data.update({
  383. "plot": True,
  384. "cutz": float(self.app.defaults["geometry_cutz"]),
  385. "multidepth": self.app.defaults["geometry_multidepth"],
  386. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  387. "vtipdia": float(self.app.defaults["geometry_vtipdia"]),
  388. "vtipangle": float(self.app.defaults["geometry_vtipangle"]),
  389. "travelz": float(self.app.defaults["geometry_travelz"]),
  390. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  391. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  392. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  393. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  394. "dwell": self.app.defaults["geometry_dwell"],
  395. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  396. "ppname_g": self.app.defaults["geometry_ppname_g"],
  397. "extracut": self.app.defaults["geometry_extracut"],
  398. "extracut_length": float(self.app.defaults["geometry_extracut_length"]),
  399. "toolchange": self.app.defaults["geometry_toolchange"],
  400. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  401. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  402. "startz": self.app.defaults["geometry_startz"],
  403. "endz": float(self.app.defaults["geometry_endz"]),
  404. # NCC
  405. "tools_nccoperation": self.app.defaults["tools_nccoperation"],
  406. "tools_nccmilling_type": self.app.defaults["tools_nccmilling_type"],
  407. "tools_nccoverlap": float(self.app.defaults["tools_nccoverlap"]),
  408. "tools_nccmargin": float(self.app.defaults["tools_nccmargin"]),
  409. "tools_nccmethod": self.app.defaults["tools_nccmethod"],
  410. "tools_nccconnect": self.app.defaults["tools_nccconnect"],
  411. "tools_ncccontour": self.app.defaults["tools_ncccontour"],
  412. "tools_ncc_offset_choice": self.app.defaults["tools_ncc_offset_choice"],
  413. "tools_ncc_offset_value": float(self.app.defaults["tools_ncc_offset_value"]),
  414. # Paint
  415. "tools_paintoverlap": float(self.app.defaults["tools_paintoverlap"]),
  416. "tools_paintmargin": float(self.app.defaults["tools_paintmargin"]),
  417. "tools_paintmethod": self.app.defaults["tools_paintmethod"],
  418. "tools_pathconnect": self.app.defaults["tools_pathconnect"],
  419. "tools_paintcontour": self.app.defaults["tools_paintcontour"],
  420. })
  421. def on_freeform_cutout(self):
  422. log.debug("Cutout.on_freeform_cutout() was launched ...")
  423. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  424. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  425. # obj_.subtract_polygon(pts)
  426. name = self.obj_combo.currentText()
  427. # Get source object.
  428. try:
  429. cutout_obj = self.app.collection.get_by_name(str(name))
  430. except Exception as e:
  431. log.debug("CutOut.on_freeform_cutout() --> %s" % str(e))
  432. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  433. return "Could not retrieve object: %s" % name
  434. if cutout_obj is None:
  435. self.app.inform.emit('[ERROR_NOTCL] %s' %
  436. _("There is no object selected for Cutout.\nSelect one and try again."))
  437. return
  438. dia = float(self.dia.get_value())
  439. if 0 in {dia}:
  440. self.app.inform.emit('[WARNING_NOTCL] %s' %
  441. _("Tool Diameter is zero value. Change it to a positive real number."))
  442. return "Tool Diameter is zero value. Change it to a positive real number."
  443. try:
  444. kind = self.obj_kind_combo.get_value()
  445. except ValueError:
  446. return
  447. margin = float(self.margin.get_value())
  448. gapsize = float(self.gapsize.get_value())
  449. try:
  450. gaps = self.gaps.get_value()
  451. except TypeError:
  452. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Number of gaps value is missing. Add it and retry."))
  453. return
  454. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  455. self.app.inform.emit('[WARNING_NOTCL] %s' %
  456. _("Gaps value can be only one of: 'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  457. "Fill in a correct value and retry. "))
  458. return
  459. if cutout_obj.multigeo is True:
  460. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  461. "Optionally, this Multi-geo Geometry can be converted to "
  462. "Single-geo Geometry,\n"
  463. "and after that perform Cutout."))
  464. return
  465. convex_box = self.convex_box.get_value()
  466. gapsize = gapsize / 2 + (dia / 2)
  467. def geo_init(geo_obj, app_obj):
  468. solid_geo = []
  469. if cutout_obj.kind == 'gerber':
  470. if isinstance(cutout_obj.solid_geometry, list):
  471. cutout_obj.solid_geometry = MultiPolygon(cutout_obj.solid_geometry)
  472. try:
  473. if convex_box:
  474. object_geo = cutout_obj.solid_geometry.convex_hull
  475. else:
  476. object_geo = cutout_obj.solid_geometry
  477. except Exception as err:
  478. log.debug("CutOut.on_freeform_cutout().geo_init() --> %s" % str(err))
  479. object_geo = cutout_obj.solid_geometry
  480. else:
  481. object_geo = cutout_obj.solid_geometry
  482. def cutout_handler(geom):
  483. # Get min and max data for each object as we just cut rectangles across X or Y
  484. xxmin, yymin, xxmax, yymax = recursive_bounds(geom)
  485. px = 0.5 * (xxmin + xxmax) + margin
  486. py = 0.5 * (yymin + yymax) + margin
  487. lenx = (xxmax - xxmin) + (margin * 2)
  488. leny = (yymax - yymin) + (margin * 2)
  489. proc_geometry = []
  490. if gaps == 'None':
  491. pass
  492. else:
  493. if gaps == '8' or gaps == '2LR':
  494. geom = self.subtract_poly_from_geo(geom,
  495. xxmin - gapsize, # botleft_x
  496. py - gapsize + leny / 4, # botleft_y
  497. xxmax + gapsize, # topright_x
  498. py + gapsize + leny / 4) # topright_y
  499. geom = self.subtract_poly_from_geo(geom,
  500. xxmin - gapsize,
  501. py - gapsize - leny / 4,
  502. xxmax + gapsize,
  503. py + gapsize - leny / 4)
  504. if gaps == '8' or gaps == '2TB':
  505. geom = self.subtract_poly_from_geo(geom,
  506. px - gapsize + lenx / 4,
  507. yymin - gapsize,
  508. px + gapsize + lenx / 4,
  509. yymax + gapsize)
  510. geom = self.subtract_poly_from_geo(geom,
  511. px - gapsize - lenx / 4,
  512. yymin - gapsize,
  513. px + gapsize - lenx / 4,
  514. yymax + gapsize)
  515. if gaps == '4' or gaps == 'LR':
  516. geom = self.subtract_poly_from_geo(geom,
  517. xxmin - gapsize,
  518. py - gapsize,
  519. xxmax + gapsize,
  520. py + gapsize)
  521. if gaps == '4' or gaps == 'TB':
  522. geom = self.subtract_poly_from_geo(geom,
  523. px - gapsize,
  524. yymin - gapsize,
  525. px + gapsize,
  526. yymax + gapsize)
  527. try:
  528. for g in geom:
  529. proc_geometry.append(g)
  530. except TypeError:
  531. proc_geometry.append(geom)
  532. return proc_geometry
  533. if kind == 'single':
  534. object_geo = unary_union(object_geo)
  535. # for geo in object_geo:
  536. if cutout_obj.kind == 'gerber':
  537. if isinstance(object_geo, MultiPolygon):
  538. x0, y0, x1, y1 = object_geo.bounds
  539. object_geo = box(x0, y0, x1, y1)
  540. if margin >= 0:
  541. geo_buf = object_geo.buffer(margin + abs(dia / 2))
  542. else:
  543. geo_buf = object_geo.buffer(margin - abs(dia / 2))
  544. geo = geo_buf.exterior
  545. else:
  546. geo = object_geo
  547. solid_geo = cutout_handler(geom=geo)
  548. else:
  549. try:
  550. __ = iter(object_geo)
  551. except TypeError:
  552. object_geo = [object_geo]
  553. for geom_struct in object_geo:
  554. if cutout_obj.kind == 'gerber':
  555. if margin >= 0:
  556. geom_struct = (geom_struct.buffer(margin + abs(dia / 2))).exterior
  557. else:
  558. geom_struct_buff = geom_struct.buffer(-margin + abs(dia / 2))
  559. geom_struct = geom_struct_buff.interiors
  560. solid_geo += cutout_handler(geom=geom_struct)
  561. xmin, ymin, xmax, ymax = recursive_bounds(geo_obj.solid_geometry)
  562. geo_obj.solid_geometry = deepcopy(solid_geo)
  563. geo_obj.options['xmin'] = xmin
  564. geo_obj.options['ymin'] = ymin
  565. geo_obj.options['xmax'] = xmax
  566. geo_obj.options['ymax'] = ymax
  567. geo_obj.options['cnctooldia'] = str(dia)
  568. geo_obj.options['cutz'] = self.cutz_entry.get_value()
  569. geo_obj.options['multidepth'] = self.mpass_cb.get_value()
  570. geo_obj.options['depthperpass'] = self.maxdepth_entry.get_value()
  571. geo_obj.tools.update({
  572. 1: {
  573. 'tooldia': str(dia),
  574. 'offset': 'Path',
  575. 'offset_value': 0.0,
  576. 'type': _('Rough'),
  577. 'tool_type': 'C1',
  578. 'data': self.default_data,
  579. 'solid_geometry': geo_obj.solid_geometry
  580. }
  581. })
  582. geo_obj.multigeo = True
  583. geo_obj.tools[1]['data']['name'] = outname
  584. geo_obj.tools[1]['data']['cutz'] = self.cutz_entry.get_value()
  585. geo_obj.tools[1]['data']['multidepth'] = self.mpass_cb.get_value()
  586. geo_obj.tools[1]['data']['depthperpass'] = self.maxdepth_entry.get_value()
  587. outname = cutout_obj.options["name"] + "_cutout"
  588. self.app.new_object('geometry', outname, geo_init)
  589. cutout_obj.plot()
  590. self.app.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  591. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  592. self.app.should_we_save = True
  593. def on_rectangular_cutout(self):
  594. log.debug("Cutout.on_rectangular_cutout() was launched ...")
  595. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  596. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  597. # obj_.subtract_polygon(pts)
  598. name = self.obj_combo.currentText()
  599. # Get source object.
  600. try:
  601. cutout_obj = self.app.collection.get_by_name(str(name))
  602. except Exception as e:
  603. log.debug("CutOut.on_rectangular_cutout() --> %s" % str(e))
  604. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  605. return "Could not retrieve object: %s" % name
  606. if cutout_obj is None:
  607. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(name)))
  608. dia = float(self.dia.get_value())
  609. if 0 in {dia}:
  610. self.app.inform.emit('[ERROR_NOTCL] %s' %
  611. _("Tool Diameter is zero value. Change it to a positive real number."))
  612. return "Tool Diameter is zero value. Change it to a positive real number."
  613. try:
  614. kind = self.obj_kind_combo.get_value()
  615. except ValueError:
  616. return
  617. margin = float(self.margin.get_value())
  618. gapsize = float(self.gapsize.get_value())
  619. try:
  620. gaps = self.gaps.get_value()
  621. except TypeError:
  622. self.app.inform.emit('[WARNING_NOTCL] %s' %
  623. _("Number of gaps value is missing. Add it and retry."))
  624. return
  625. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  626. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Gaps value can be only one of: "
  627. "'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  628. "Fill in a correct value and retry. "))
  629. return
  630. if cutout_obj.multigeo is True:
  631. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  632. "Optionally, this Multi-geo Geometry can be converted to "
  633. "Single-geo Geometry,\n"
  634. "and after that perform Cutout."))
  635. return
  636. # Get min and max data for each object as we just cut rectangles across X or Y
  637. gapsize = gapsize / 2 + (dia / 2)
  638. def geo_init(geo_obj, app_obj):
  639. solid_geo = []
  640. object_geo = cutout_obj.solid_geometry
  641. def cutout_rect_handler(geom):
  642. proc_geometry = []
  643. px = 0.5 * (xmin + xmax) + margin
  644. py = 0.5 * (ymin + ymax) + margin
  645. lenx = (xmax - xmin) + (margin * 2)
  646. leny = (ymax - ymin) + (margin * 2)
  647. if gaps == 'None':
  648. pass
  649. else:
  650. if gaps == '8' or gaps == '2LR':
  651. geom = self.subtract_poly_from_geo(geom,
  652. xmin - gapsize, # botleft_x
  653. py - gapsize + leny / 4, # botleft_y
  654. xmax + gapsize, # topright_x
  655. py + gapsize + leny / 4) # topright_y
  656. geom = self.subtract_poly_from_geo(geom,
  657. xmin - gapsize,
  658. py - gapsize - leny / 4,
  659. xmax + gapsize,
  660. py + gapsize - leny / 4)
  661. if gaps == '8' or gaps == '2TB':
  662. geom = self.subtract_poly_from_geo(geom,
  663. px - gapsize + lenx / 4,
  664. ymin - gapsize,
  665. px + gapsize + lenx / 4,
  666. ymax + gapsize)
  667. geom = self.subtract_poly_from_geo(geom,
  668. px - gapsize - lenx / 4,
  669. ymin - gapsize,
  670. px + gapsize - lenx / 4,
  671. ymax + gapsize)
  672. if gaps == '4' or gaps == 'LR':
  673. geom = self.subtract_poly_from_geo(geom,
  674. xmin - gapsize,
  675. py - gapsize,
  676. xmax + gapsize,
  677. py + gapsize)
  678. if gaps == '4' or gaps == 'TB':
  679. geom = self.subtract_poly_from_geo(geom,
  680. px - gapsize,
  681. ymin - gapsize,
  682. px + gapsize,
  683. ymax + gapsize)
  684. try:
  685. for g in geom:
  686. proc_geometry.append(g)
  687. except TypeError:
  688. proc_geometry.append(geom)
  689. return proc_geometry
  690. if kind == 'single':
  691. # fuse the lines
  692. object_geo = unary_union(object_geo)
  693. xmin, ymin, xmax, ymax = object_geo.bounds
  694. geo = box(xmin, ymin, xmax, ymax)
  695. # if Gerber create a buffer at a distance
  696. # if Geometry then cut through the geometry
  697. if cutout_obj.kind == 'gerber':
  698. if margin >= 0:
  699. geo = geo.buffer(margin + abs(dia / 2))
  700. else:
  701. geo = geo.buffer(margin - abs(dia / 2))
  702. solid_geo = cutout_rect_handler(geom=geo)
  703. else:
  704. if cutout_obj.kind == 'geometry':
  705. try:
  706. __ = iter(object_geo)
  707. except TypeError:
  708. object_geo = [object_geo]
  709. for geom_struct in object_geo:
  710. geom_struct = unary_union(geom_struct)
  711. xmin, ymin, xmax, ymax = geom_struct.bounds
  712. geom_struct = box(xmin, ymin, xmax, ymax)
  713. solid_geo += cutout_rect_handler(geom=geom_struct)
  714. elif cutout_obj.kind == 'gerber' and margin >= 0:
  715. try:
  716. __ = iter(object_geo)
  717. except TypeError:
  718. object_geo = [object_geo]
  719. for geom_struct in object_geo:
  720. geom_struct = unary_union(geom_struct)
  721. xmin, ymin, xmax, ymax = geom_struct.bounds
  722. geom_struct = box(xmin, ymin, xmax, ymax)
  723. geom_struct = geom_struct.buffer(margin + abs(dia / 2))
  724. solid_geo += cutout_rect_handler(geom=geom_struct)
  725. elif cutout_obj.kind == 'gerber' and margin < 0:
  726. self.app.inform.emit('[WARNING_NOTCL] %s' %
  727. _("Rectangular cutout with negative margin is not possible."))
  728. return "fail"
  729. geo_obj.options['cnctooldia'] = str(dia)
  730. geo_obj.options['cutz'] = self.cutz_entry.get_value()
  731. geo_obj.options['multidepth'] = self.mpass_cb.get_value()
  732. geo_obj.options['depthperpass'] = self.maxdepth_entry.get_value()
  733. geo_obj.solid_geometry = deepcopy(solid_geo)
  734. geo_obj.tools.update({
  735. 1: {
  736. 'tooldia': str(dia),
  737. 'offset': 'Path',
  738. 'offset_value': 0.0,
  739. 'type': _('Rough'),
  740. 'tool_type': 'C1',
  741. 'data': self.default_data,
  742. 'solid_geometry': geo_obj.solid_geometry
  743. }
  744. })
  745. geo_obj.multigeo = True
  746. geo_obj.tools[1]['data']['name'] = outname
  747. geo_obj.tools[1]['data']['cutz'] = self.cutz_entry.get_value()
  748. geo_obj.tools[1]['data']['multidepth'] = self.mpass_cb.get_value()
  749. geo_obj.tools[1]['data']['depthperpass'] = self.maxdepth_entry.get_value()
  750. outname = cutout_obj.options["name"] + "_cutout"
  751. ret = self.app.new_object('geometry', outname, geo_init)
  752. if ret != 'fail':
  753. # cutout_obj.plot()
  754. self.app.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  755. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  756. self.app.should_we_save = True
  757. def on_manual_gap_click(self):
  758. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  759. self.app.geo_editor.tool_shape.enabled = True
  760. self.cutting_dia = float(self.dia.get_value())
  761. if 0 in {self.cutting_dia}:
  762. self.app.inform.emit('[ERROR_NOTCL] %s' %
  763. _("Tool Diameter is zero value. Change it to a positive real number."))
  764. return "Tool Diameter is zero value. Change it to a positive real number."
  765. self.cutting_gapsize = float(self.gapsize.get_value())
  766. name = self.man_object_combo.currentText()
  767. # Get Geometry source object to be used as target for Manual adding Gaps
  768. try:
  769. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  770. except Exception as e:
  771. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  772. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  773. return "Could not retrieve object: %s" % name
  774. if self.app.is_legacy is False:
  775. self.app.plotcanvas.graph_event_disconnect('key_press', self.app.ui.keyPressEvent)
  776. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  777. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  778. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  779. else:
  780. self.app.plotcanvas.graph_event_disconnect(self.app.kp)
  781. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  782. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  783. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  784. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  785. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  786. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  787. def on_manual_cutout(self, click_pos):
  788. name = self.man_object_combo.currentText()
  789. # Get source object.
  790. try:
  791. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  792. except Exception as e:
  793. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  794. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  795. return "Could not retrieve object: %s" % name
  796. if self.man_cutout_obj is None:
  797. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  798. (_("Geometry object for manual cutout not found"), self.man_cutout_obj))
  799. return
  800. # use the snapped position as reference
  801. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  802. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  803. self.man_cutout_obj.subtract_polygon(cut_poly)
  804. self.man_cutout_obj.plot()
  805. self.app.inform.emit('[success] %s' % _("Added manual Bridge Gap."))
  806. self.app.should_we_save = True
  807. def on_manual_geo(self):
  808. name = self.obj_combo.currentText()
  809. # Get source object.
  810. try:
  811. cutout_obj = self.app.collection.get_by_name(str(name))
  812. except Exception as e:
  813. log.debug("CutOut.on_manual_geo() --> %s" % str(e))
  814. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Gerber object"), name))
  815. return "Could not retrieve object: %s" % name
  816. if cutout_obj is None:
  817. self.app.inform.emit('[ERROR_NOTCL] %s' %
  818. _("There is no Gerber object selected for Cutout.\n"
  819. "Select one and try again."))
  820. return
  821. if cutout_obj.kind != 'gerber':
  822. self.app.inform.emit('[ERROR_NOTCL] %s' %
  823. _("The selected object has to be of Gerber type.\n"
  824. "Select a Gerber file and try again."))
  825. return
  826. dia = float(self.dia.get_value())
  827. if 0 in {dia}:
  828. self.app.inform.emit('[ERROR_NOTCL] %s' %
  829. _("Tool Diameter is zero value. Change it to a positive real number."))
  830. return "Tool Diameter is zero value. Change it to a positive real number."
  831. try:
  832. kind = self.obj_kind_combo.get_value()
  833. except ValueError:
  834. return
  835. margin = float(self.margin.get_value())
  836. convex_box = self.convex_box.get_value()
  837. def geo_init(geo_obj, app_obj):
  838. geo_union = unary_union(cutout_obj.solid_geometry)
  839. if convex_box:
  840. geo = geo_union.convex_hull
  841. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  842. elif kind == 'single':
  843. if isinstance(geo_union, Polygon) or \
  844. (isinstance(geo_union, list) and len(geo_union) == 1) or \
  845. (isinstance(geo_union, MultiPolygon) and len(geo_union) == 1):
  846. geo_obj.solid_geometry = geo_union.buffer(margin + abs(dia / 2)).exterior
  847. elif isinstance(geo_union, MultiPolygon):
  848. x0, y0, x1, y1 = geo_union.bounds
  849. geo = box(x0, y0, x1, y1)
  850. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  851. else:
  852. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  853. (_("Geometry not supported for cutout"), type(geo_union)))
  854. return 'fail'
  855. else:
  856. geo = geo_union
  857. geo = geo.buffer(margin + abs(dia / 2))
  858. if isinstance(geo, Polygon):
  859. geo_obj.solid_geometry = geo.exterior
  860. elif isinstance(geo, MultiPolygon):
  861. solid_geo = []
  862. for poly in geo:
  863. solid_geo.append(poly.exterior)
  864. geo_obj.solid_geometry = deepcopy(solid_geo)
  865. geo_obj.options['cnctooldia'] = str(dia)
  866. geo_obj.options['cutz'] = self.cutz_entry.get_value()
  867. geo_obj.options['multidepth'] = self.mpass_cb.get_value()
  868. geo_obj.options['depthperpass'] = self.maxdepth_entry.get_value()
  869. geo_obj.tools.update({
  870. 1: {
  871. 'tooldia': str(dia),
  872. 'offset': 'Path',
  873. 'offset_value': 0.0,
  874. 'type': _('Rough'),
  875. 'tool_type': 'C1',
  876. 'data': self.default_data,
  877. 'solid_geometry': geo_obj.solid_geometry
  878. }
  879. })
  880. geo_obj.multigeo = True
  881. geo_obj.tools[1]['data']['name'] = outname
  882. geo_obj.tools[1]['data']['cutz'] = self.cutz_entry.get_value()
  883. geo_obj.tools[1]['data']['multidepth'] = self.mpass_cb.get_value()
  884. geo_obj.tools[1]['data']['depthperpass'] = self.maxdepth_entry.get_value()
  885. outname = cutout_obj.options["name"] + "_cutout"
  886. self.app.new_object('geometry', outname, geo_init)
  887. def cutting_geo(self, pos):
  888. self.cutting_dia = float(self.dia.get_value())
  889. self.cutting_gapsize = float(self.gapsize.get_value())
  890. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  891. # cutting area definition
  892. orig_x = pos[0]
  893. orig_y = pos[1]
  894. xmin = orig_x - offset
  895. ymin = orig_y - offset
  896. xmax = orig_x + offset
  897. ymax = orig_y + offset
  898. cut_poly = box(xmin, ymin, xmax, ymax)
  899. return cut_poly
  900. # To be called after clicking on the plot.
  901. def on_mouse_click_release(self, event):
  902. if self.app.is_legacy is False:
  903. event_pos = event.pos
  904. # event_is_dragging = event.is_dragging
  905. right_button = 2
  906. else:
  907. event_pos = (event.xdata, event.ydata)
  908. # event_is_dragging = self.app.plotcanvas.is_dragging
  909. right_button = 3
  910. try:
  911. x = float(event_pos[0])
  912. y = float(event_pos[1])
  913. except TypeError:
  914. return
  915. event_pos = (x, y)
  916. # do paint single only for left mouse clicks
  917. if event.button == 1:
  918. self.app.inform.emit(_("Making manual bridge gap..."))
  919. pos = self.app.plotcanvas.translate_coords(event_pos)
  920. self.on_manual_cutout(click_pos=pos)
  921. # if RMB then we exit
  922. elif event.button == right_button and self.mouse_is_dragging is False:
  923. if self.app.is_legacy is False:
  924. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  925. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  926. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  927. else:
  928. self.app.plotcanvas.graph_event_disconnect(self.kp)
  929. self.app.plotcanvas.graph_event_disconnect(self.mm)
  930. self.app.plotcanvas.graph_event_disconnect(self.mr)
  931. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  932. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  933. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  934. self.app.on_mouse_click_release_over_plot)
  935. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  936. # Remove any previous utility shape
  937. self.app.geo_editor.tool_shape.clear(update=True)
  938. self.app.geo_editor.tool_shape.enabled = False
  939. def on_mouse_move(self, event):
  940. self.app.on_mouse_move_over_plot(event=event)
  941. if self.app.is_legacy is False:
  942. event_pos = event.pos
  943. event_is_dragging = event.is_dragging
  944. # right_button = 2
  945. else:
  946. event_pos = (event.xdata, event.ydata)
  947. event_is_dragging = self.app.plotcanvas.is_dragging
  948. # right_button = 3
  949. try:
  950. x = float(event_pos[0])
  951. y = float(event_pos[1])
  952. except TypeError:
  953. return
  954. event_pos = (x, y)
  955. pos = self.canvas.translate_coords(event_pos)
  956. event.xdata, event.ydata = pos[0], pos[1]
  957. if event_is_dragging is True:
  958. self.mouse_is_dragging = True
  959. else:
  960. self.mouse_is_dragging = False
  961. try:
  962. x = float(event.xdata)
  963. y = float(event.ydata)
  964. except TypeError:
  965. return
  966. if self.app.grid_status():
  967. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  968. else:
  969. snap_x, snap_y = x, y
  970. self.x_pos, self.y_pos = snap_x, snap_y
  971. # #################################################
  972. # ### This section makes the cutting geo to #######
  973. # ### rotate if it intersects the target geo ######
  974. # #################################################
  975. cut_geo = self.cutting_geo(pos=(snap_x, snap_y))
  976. man_geo = self.man_cutout_obj.solid_geometry
  977. def get_angle(geo):
  978. line = cut_geo.intersection(geo)
  979. try:
  980. pt1_x = line.coords[0][0]
  981. pt1_y = line.coords[0][1]
  982. pt2_x = line.coords[1][0]
  983. pt2_y = line.coords[1][1]
  984. dx = pt1_x - pt2_x
  985. dy = pt1_y - pt2_y
  986. if dx == 0 or dy == 0:
  987. angle = 0
  988. else:
  989. radian = math.atan(dx / dy)
  990. angle = radian * 180 / math.pi
  991. except Exception:
  992. angle = 0
  993. return angle
  994. try:
  995. rot_angle = 0
  996. for geo_el in man_geo:
  997. if isinstance(geo_el, Polygon):
  998. work_geo = geo_el.exterior
  999. if cut_geo.intersects(work_geo):
  1000. rot_angle = get_angle(geo=work_geo)
  1001. else:
  1002. rot_angle = 0
  1003. else:
  1004. rot_angle = 0
  1005. if cut_geo.intersects(geo_el):
  1006. rot_angle = get_angle(geo=geo_el)
  1007. if rot_angle != 0:
  1008. break
  1009. except TypeError:
  1010. if isinstance(man_geo, Polygon):
  1011. work_geo = man_geo.exterior
  1012. if cut_geo.intersects(work_geo):
  1013. rot_angle = get_angle(geo=work_geo)
  1014. else:
  1015. rot_angle = 0
  1016. else:
  1017. rot_angle = 0
  1018. if cut_geo.intersects(man_geo):
  1019. rot_angle = get_angle(geo=man_geo)
  1020. # rotate only if there is an angle to rotate to
  1021. if rot_angle != 0:
  1022. cut_geo = affinity.rotate(cut_geo, -rot_angle)
  1023. # Remove any previous utility shape
  1024. self.app.geo_editor.tool_shape.clear(update=True)
  1025. self.draw_utility_geometry(geo=cut_geo)
  1026. def draw_utility_geometry(self, geo):
  1027. self.app.geo_editor.tool_shape.add(
  1028. shape=geo,
  1029. color=(self.app.defaults["global_draw_color"] + '80'),
  1030. update=False,
  1031. layer=0,
  1032. tolerance=None)
  1033. self.app.geo_editor.tool_shape.redraw()
  1034. def on_key_press(self, event):
  1035. # events out of the self.app.collection view (it's about Project Tab) are of type int
  1036. if type(event) is int:
  1037. key = event
  1038. # events from the GUI are of type QKeyEvent
  1039. elif type(event) == QtGui.QKeyEvent:
  1040. key = event.key()
  1041. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1042. key = event.key
  1043. key = QtGui.QKeySequence(key)
  1044. # check for modifiers
  1045. key_string = key.toString().lower()
  1046. if '+' in key_string:
  1047. mod, __, key_text = key_string.rpartition('+')
  1048. if mod.lower() == 'ctrl':
  1049. # modifiers = QtCore.Qt.ControlModifier
  1050. pass
  1051. elif mod.lower() == 'alt':
  1052. # modifiers = QtCore.Qt.AltModifier
  1053. pass
  1054. elif mod.lower() == 'shift':
  1055. # modifiers = QtCore.Qt.ShiftModifier
  1056. pass
  1057. else:
  1058. # modifiers = QtCore.Qt.NoModifier
  1059. pass
  1060. key = QtGui.QKeySequence(key_text)
  1061. # events from Vispy are of type KeyEvent
  1062. else:
  1063. key = event.key
  1064. # Escape = Deselect All
  1065. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1066. if self.app.is_legacy is False:
  1067. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1068. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1069. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  1070. else:
  1071. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1072. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1073. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1074. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  1075. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1076. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1077. self.app.on_mouse_click_release_over_plot)
  1078. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1079. # Remove any previous utility shape
  1080. self.app.geo_editor.tool_shape.clear(update=True)
  1081. self.app.geo_editor.tool_shape.enabled = False
  1082. # Grid toggle
  1083. if key == QtCore.Qt.Key_G or key == 'G':
  1084. self.app.ui.grid_snap_btn.trigger()
  1085. # Jump to coords
  1086. if key == QtCore.Qt.Key_J or key == 'J':
  1087. l_x, l_y = self.app.on_jump_to()
  1088. self.app.geo_editor.tool_shape.clear(update=True)
  1089. geo = self.cutting_geo(pos=(l_x, l_y))
  1090. self.draw_utility_geometry(geo=geo)
  1091. @staticmethod
  1092. def subtract_poly_from_geo(solid_geo, x0, y0, x1, y1):
  1093. """
  1094. Subtract polygon made from points from the given object.
  1095. This only operates on the paths in the original geometry,
  1096. i.e. it converts polygons into paths.
  1097. :param x0: x coord for lower left vertice of the polygon.
  1098. :param y0: y coord for lower left vertice of the polygon.
  1099. :param x1: x coord for upper right vertice of the polygon.
  1100. :param y1: y coord for upper right vertice of the polygon.
  1101. :param solid_geo: Geometry from which to substract. If none, use the solid_geomety property of the object
  1102. :return: none
  1103. """
  1104. points = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  1105. # pathonly should be allways True, otherwise polygons are not subtracted
  1106. flat_geometry = flatten(geometry=solid_geo)
  1107. log.debug("%d paths" % len(flat_geometry))
  1108. polygon = Polygon(points)
  1109. toolgeo = cascaded_union(polygon)
  1110. diffs = []
  1111. for target in flat_geometry:
  1112. if type(target) == LineString or type(target) == LinearRing:
  1113. diffs.append(target.difference(toolgeo))
  1114. else:
  1115. log.warning("Not implemented.")
  1116. return unary_union(diffs)
  1117. def reset_fields(self):
  1118. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1119. def flatten(geometry):
  1120. """
  1121. Creates a list of non-iterable linear geometry objects.
  1122. Polygons are expanded into its exterior and interiors.
  1123. Results are placed in self.flat_geometry
  1124. :param geometry: Shapely type or list or list of list of such.
  1125. """
  1126. flat_geo = []
  1127. try:
  1128. for geo in geometry:
  1129. if type(geo) == Polygon:
  1130. flat_geo.append(geo.exterior)
  1131. for subgeo in geo.interiors:
  1132. flat_geo.append(subgeo)
  1133. else:
  1134. flat_geo.append(geo)
  1135. except TypeError:
  1136. if type(geometry) == Polygon:
  1137. flat_geo.append(geometry.exterior)
  1138. for subgeo in geometry.interiors:
  1139. flat_geo.append(subgeo)
  1140. else:
  1141. flat_geo.append(geometry)
  1142. return flat_geo
  1143. def recursive_bounds(geometry):
  1144. """
  1145. :param geometry: a iterable object that holds geometry
  1146. :return: Returns coordinates of rectangular bounds of geometry: (xmin, ymin, xmax, ymax).
  1147. """
  1148. # now it can get bounds for nested lists of objects
  1149. def bounds_rec(obj):
  1150. try:
  1151. minx = Inf
  1152. miny = Inf
  1153. maxx = -Inf
  1154. maxy = -Inf
  1155. for k in obj:
  1156. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1157. minx = min(minx, minx_)
  1158. miny = min(miny, miny_)
  1159. maxx = max(maxx, maxx_)
  1160. maxy = max(maxy, maxy_)
  1161. return minx, miny, maxx, maxy
  1162. except TypeError:
  1163. # it's a Shapely object, return it's bounds
  1164. return obj.bounds
  1165. return bounds_rec(geometry)