ToolCutOut.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  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 appTool import AppTool
  9. from appGUI.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 appTranslation 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(AppTool):
  31. toolName = _("Cutout PCB")
  32. def __init__(self, app):
  33. AppTool.__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. AppTool.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. AppTool.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. # use the current selected object and make it visible in the Paint object combobox
  382. sel_list = self.app.collection.get_selected()
  383. if len(sel_list) == 1:
  384. active = self.app.collection.get_active()
  385. kind = active.kind
  386. if kind == 'gerber':
  387. self.type_obj_radio.set_value('grb')
  388. else:
  389. self.type_obj_radio.set_value('geo')
  390. # run those once so the obj_type attribute is updated for the FCComboboxes
  391. # so the last loaded object is displayed
  392. if kind == 'gerber':
  393. self.on_type_obj_changed(val='grb')
  394. else:
  395. self.on_type_obj_changed(val='geo')
  396. self.obj_combo.set_value(active.options['name'])
  397. else:
  398. kind = 'gerber'
  399. self.type_obj_radio.set_value('grb')
  400. # run those once so the obj_type attribute is updated for the FCComboboxes
  401. # so the last loaded object is displayed
  402. if kind == 'gerber':
  403. self.on_type_obj_changed(val='grb')
  404. else:
  405. self.on_type_obj_changed(val='geo')
  406. # self.type_obj_radio.set_value('grb')
  407. self.default_data.update({
  408. "plot": True,
  409. "cutz": float(self.app.defaults["geometry_cutz"]),
  410. "multidepth": self.app.defaults["geometry_multidepth"],
  411. "depthperpass": float(self.app.defaults["geometry_depthperpass"]),
  412. "vtipdia": float(self.app.defaults["geometry_vtipdia"]),
  413. "vtipangle": float(self.app.defaults["geometry_vtipangle"]),
  414. "travelz": float(self.app.defaults["geometry_travelz"]),
  415. "feedrate": float(self.app.defaults["geometry_feedrate"]),
  416. "feedrate_z": float(self.app.defaults["geometry_feedrate_z"]),
  417. "feedrate_rapid": float(self.app.defaults["geometry_feedrate_rapid"]),
  418. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  419. "dwell": self.app.defaults["geometry_dwell"],
  420. "dwelltime": float(self.app.defaults["geometry_dwelltime"]),
  421. "ppname_g": self.app.defaults["geometry_ppname_g"],
  422. "extracut": self.app.defaults["geometry_extracut"],
  423. "extracut_length": float(self.app.defaults["geometry_extracut_length"]),
  424. "toolchange": self.app.defaults["geometry_toolchange"],
  425. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  426. "toolchangez": float(self.app.defaults["geometry_toolchangez"]),
  427. "startz": self.app.defaults["geometry_startz"],
  428. "endz": float(self.app.defaults["geometry_endz"]),
  429. "area_exclusion": self.app.defaults["geometry_area_exclusion"],
  430. "area_shape": self.app.defaults["geometry_area_shape"],
  431. "area_strategy": self.app.defaults["geometry_area_strategy"],
  432. "area_overz": float(self.app.defaults["geometry_area_overz"]),
  433. # NCC
  434. "tools_nccoperation": self.app.defaults["tools_nccoperation"],
  435. "tools_nccmilling_type": self.app.defaults["tools_nccmilling_type"],
  436. "tools_nccoverlap": float(self.app.defaults["tools_nccoverlap"]),
  437. "tools_nccmargin": float(self.app.defaults["tools_nccmargin"]),
  438. "tools_nccmethod": self.app.defaults["tools_nccmethod"],
  439. "tools_nccconnect": self.app.defaults["tools_nccconnect"],
  440. "tools_ncccontour": self.app.defaults["tools_ncccontour"],
  441. "tools_ncc_offset_choice": self.app.defaults["tools_ncc_offset_choice"],
  442. "tools_ncc_offset_value": float(self.app.defaults["tools_ncc_offset_value"]),
  443. # Paint
  444. "tools_paintoverlap": float(self.app.defaults["tools_paintoverlap"]),
  445. "tools_paintmargin": float(self.app.defaults["tools_paintmargin"]),
  446. "tools_paintmethod": self.app.defaults["tools_paintmethod"],
  447. "tools_pathconnect": self.app.defaults["tools_pathconnect"],
  448. "tools_paintcontour": self.app.defaults["tools_paintcontour"],
  449. # Isolation Tool
  450. "tools_iso_passes": self.app.defaults["tools_iso_passes"],
  451. "tools_iso_overlap": self.app.defaults["tools_iso_overlap"],
  452. "tools_iso_milling_type": self.app.defaults["tools_iso_milling_type"],
  453. "tools_iso_follow": self.app.defaults["tools_iso_follow"],
  454. "tools_iso_isotype": self.app.defaults["tools_iso_isotype"],
  455. })
  456. def on_freeform_cutout(self):
  457. log.debug("Cutout.on_freeform_cutout() was launched ...")
  458. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  459. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  460. # obj_.subtract_polygon(pts)
  461. name = self.obj_combo.currentText()
  462. # Get source object.
  463. try:
  464. cutout_obj = self.app.collection.get_by_name(str(name))
  465. except Exception as e:
  466. log.debug("CutOut.on_freeform_cutout() --> %s" % str(e))
  467. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  468. return "Could not retrieve object: %s" % name
  469. if cutout_obj is None:
  470. self.app.inform.emit('[ERROR_NOTCL] %s' %
  471. _("There is no object selected for Cutout.\nSelect one and try again."))
  472. return
  473. dia = float(self.dia.get_value())
  474. if 0 in {dia}:
  475. self.app.inform.emit('[WARNING_NOTCL] %s' %
  476. _("Tool Diameter is zero value. Change it to a positive real number."))
  477. return "Tool Diameter is zero value. Change it to a positive real number."
  478. try:
  479. kind = self.obj_kind_combo.get_value()
  480. except ValueError:
  481. return
  482. margin = float(self.margin.get_value())
  483. gapsize = float(self.gapsize.get_value())
  484. try:
  485. gaps = self.gaps.get_value()
  486. except TypeError:
  487. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Number of gaps value is missing. Add it and retry."))
  488. return
  489. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  490. self.app.inform.emit('[WARNING_NOTCL] %s' %
  491. _("Gaps value can be only one of: 'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  492. "Fill in a correct value and retry. "))
  493. return
  494. if cutout_obj.multigeo is True:
  495. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  496. "Optionally, this Multi-geo Geometry can be converted to "
  497. "Single-geo Geometry,\n"
  498. "and after that perform Cutout."))
  499. return
  500. convex_box = self.convex_box.get_value()
  501. gapsize = gapsize / 2 + (dia / 2)
  502. def geo_init(geo_obj, app_obj):
  503. solid_geo = []
  504. if cutout_obj.kind == 'gerber':
  505. if isinstance(cutout_obj.solid_geometry, list):
  506. cutout_obj.solid_geometry = MultiPolygon(cutout_obj.solid_geometry)
  507. try:
  508. if convex_box:
  509. object_geo = cutout_obj.solid_geometry.convex_hull
  510. else:
  511. object_geo = cutout_obj.solid_geometry
  512. except Exception as err:
  513. log.debug("CutOut.on_freeform_cutout().geo_init() --> %s" % str(err))
  514. object_geo = cutout_obj.solid_geometry
  515. else:
  516. object_geo = cutout_obj.solid_geometry
  517. def cutout_handler(geom):
  518. # Get min and max data for each object as we just cut rectangles across X or Y
  519. xxmin, yymin, xxmax, yymax = recursive_bounds(geom)
  520. px = 0.5 * (xxmin + xxmax) + margin
  521. py = 0.5 * (yymin + yymax) + margin
  522. lenx = (xxmax - xxmin) + (margin * 2)
  523. leny = (yymax - yymin) + (margin * 2)
  524. proc_geometry = []
  525. if gaps == 'None':
  526. pass
  527. else:
  528. if gaps == '8' or gaps == '2LR':
  529. geom = self.subtract_poly_from_geo(geom,
  530. xxmin - gapsize, # botleft_x
  531. py - gapsize + leny / 4, # botleft_y
  532. xxmax + gapsize, # topright_x
  533. py + gapsize + leny / 4) # topright_y
  534. geom = self.subtract_poly_from_geo(geom,
  535. xxmin - gapsize,
  536. py - gapsize - leny / 4,
  537. xxmax + gapsize,
  538. py + gapsize - leny / 4)
  539. if gaps == '8' or gaps == '2TB':
  540. geom = self.subtract_poly_from_geo(geom,
  541. px - gapsize + lenx / 4,
  542. yymin - gapsize,
  543. px + gapsize + lenx / 4,
  544. yymax + gapsize)
  545. geom = self.subtract_poly_from_geo(geom,
  546. px - gapsize - lenx / 4,
  547. yymin - gapsize,
  548. px + gapsize - lenx / 4,
  549. yymax + gapsize)
  550. if gaps == '4' or gaps == 'LR':
  551. geom = self.subtract_poly_from_geo(geom,
  552. xxmin - gapsize,
  553. py - gapsize,
  554. xxmax + gapsize,
  555. py + gapsize)
  556. if gaps == '4' or gaps == 'TB':
  557. geom = self.subtract_poly_from_geo(geom,
  558. px - gapsize,
  559. yymin - gapsize,
  560. px + gapsize,
  561. yymax + gapsize)
  562. try:
  563. for g in geom:
  564. proc_geometry.append(g)
  565. except TypeError:
  566. proc_geometry.append(geom)
  567. return proc_geometry
  568. if kind == 'single':
  569. object_geo = unary_union(object_geo)
  570. # for geo in object_geo:
  571. if cutout_obj.kind == 'gerber':
  572. if isinstance(object_geo, MultiPolygon):
  573. x0, y0, x1, y1 = object_geo.bounds
  574. object_geo = box(x0, y0, x1, y1)
  575. if margin >= 0:
  576. geo_buf = object_geo.buffer(margin + abs(dia / 2))
  577. else:
  578. geo_buf = object_geo.buffer(margin - abs(dia / 2))
  579. geo = geo_buf.exterior
  580. else:
  581. geo = object_geo
  582. solid_geo = cutout_handler(geom=geo)
  583. else:
  584. try:
  585. __ = iter(object_geo)
  586. except TypeError:
  587. object_geo = [object_geo]
  588. for geom_struct in object_geo:
  589. if cutout_obj.kind == 'gerber':
  590. if margin >= 0:
  591. geom_struct = (geom_struct.buffer(margin + abs(dia / 2))).exterior
  592. else:
  593. geom_struct_buff = geom_struct.buffer(-margin + abs(dia / 2))
  594. geom_struct = geom_struct_buff.interiors
  595. solid_geo += cutout_handler(geom=geom_struct)
  596. geo_obj.solid_geometry = deepcopy(solid_geo)
  597. xmin, ymin, xmax, ymax = recursive_bounds(geo_obj.solid_geometry)
  598. geo_obj.options['xmin'] = xmin
  599. geo_obj.options['ymin'] = ymin
  600. geo_obj.options['xmax'] = xmax
  601. geo_obj.options['ymax'] = ymax
  602. geo_obj.options['cnctooldia'] = str(dia)
  603. geo_obj.options['cutz'] = self.cutz_entry.get_value()
  604. geo_obj.options['multidepth'] = self.mpass_cb.get_value()
  605. geo_obj.options['depthperpass'] = self.maxdepth_entry.get_value()
  606. geo_obj.tools.update({
  607. 1: {
  608. 'tooldia': str(dia),
  609. 'offset': 'Path',
  610. 'offset_value': 0.0,
  611. 'type': _('Rough'),
  612. 'tool_type': 'C1',
  613. 'data': self.default_data,
  614. 'solid_geometry': geo_obj.solid_geometry
  615. }
  616. })
  617. geo_obj.multigeo = True
  618. geo_obj.tools[1]['data']['name'] = outname
  619. geo_obj.tools[1]['data']['cutz'] = self.cutz_entry.get_value()
  620. geo_obj.tools[1]['data']['multidepth'] = self.mpass_cb.get_value()
  621. geo_obj.tools[1]['data']['depthperpass'] = self.maxdepth_entry.get_value()
  622. outname = cutout_obj.options["name"] + "_cutout"
  623. self.app.app_obj.new_object('geometry', outname, geo_init)
  624. cutout_obj.plot()
  625. self.app.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  626. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  627. self.app.should_we_save = True
  628. def on_rectangular_cutout(self):
  629. log.debug("Cutout.on_rectangular_cutout() was launched ...")
  630. # def subtract_rectangle(obj_, x0, y0, x1, y1):
  631. # pts = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  632. # obj_.subtract_polygon(pts)
  633. name = self.obj_combo.currentText()
  634. # Get source object.
  635. try:
  636. cutout_obj = self.app.collection.get_by_name(str(name))
  637. except Exception as e:
  638. log.debug("CutOut.on_rectangular_cutout() --> %s" % str(e))
  639. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), name))
  640. return "Could not retrieve object: %s" % name
  641. if cutout_obj is None:
  642. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Object not found"), str(name)))
  643. dia = float(self.dia.get_value())
  644. if 0 in {dia}:
  645. self.app.inform.emit('[ERROR_NOTCL] %s' %
  646. _("Tool Diameter is zero value. Change it to a positive real number."))
  647. return "Tool Diameter is zero value. Change it to a positive real number."
  648. try:
  649. kind = self.obj_kind_combo.get_value()
  650. except ValueError:
  651. return
  652. margin = float(self.margin.get_value())
  653. gapsize = float(self.gapsize.get_value())
  654. try:
  655. gaps = self.gaps.get_value()
  656. except TypeError:
  657. self.app.inform.emit('[WARNING_NOTCL] %s' %
  658. _("Number of gaps value is missing. Add it and retry."))
  659. return
  660. if gaps not in ['None', 'LR', 'TB', '2LR', '2TB', '4', '8']:
  661. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Gaps value can be only one of: "
  662. "'None', 'lr', 'tb', '2lr', '2tb', 4 or 8. "
  663. "Fill in a correct value and retry. "))
  664. return
  665. if cutout_obj.multigeo is True:
  666. self.app.inform.emit('[ERROR] %s' % _("Cutout operation cannot be done on a multi-geo Geometry.\n"
  667. "Optionally, this Multi-geo Geometry can be converted to "
  668. "Single-geo Geometry,\n"
  669. "and after that perform Cutout."))
  670. return
  671. # Get min and max data for each object as we just cut rectangles across X or Y
  672. gapsize = gapsize / 2 + (dia / 2)
  673. def geo_init(geo_obj, app_obj):
  674. solid_geo = []
  675. object_geo = cutout_obj.solid_geometry
  676. def cutout_rect_handler(geom):
  677. proc_geometry = []
  678. px = 0.5 * (xmin + xmax) + margin
  679. py = 0.5 * (ymin + ymax) + margin
  680. lenx = (xmax - xmin) + (margin * 2)
  681. leny = (ymax - ymin) + (margin * 2)
  682. if gaps == 'None':
  683. pass
  684. else:
  685. if gaps == '8' or gaps == '2LR':
  686. geom = self.subtract_poly_from_geo(geom,
  687. xmin - gapsize, # botleft_x
  688. py - gapsize + leny / 4, # botleft_y
  689. xmax + gapsize, # topright_x
  690. py + gapsize + leny / 4) # topright_y
  691. geom = self.subtract_poly_from_geo(geom,
  692. xmin - gapsize,
  693. py - gapsize - leny / 4,
  694. xmax + gapsize,
  695. py + gapsize - leny / 4)
  696. if gaps == '8' or gaps == '2TB':
  697. geom = self.subtract_poly_from_geo(geom,
  698. px - gapsize + lenx / 4,
  699. ymin - gapsize,
  700. px + gapsize + lenx / 4,
  701. ymax + gapsize)
  702. geom = self.subtract_poly_from_geo(geom,
  703. px - gapsize - lenx / 4,
  704. ymin - gapsize,
  705. px + gapsize - lenx / 4,
  706. ymax + gapsize)
  707. if gaps == '4' or gaps == 'LR':
  708. geom = self.subtract_poly_from_geo(geom,
  709. xmin - gapsize,
  710. py - gapsize,
  711. xmax + gapsize,
  712. py + gapsize)
  713. if gaps == '4' or gaps == 'TB':
  714. geom = self.subtract_poly_from_geo(geom,
  715. px - gapsize,
  716. ymin - gapsize,
  717. px + gapsize,
  718. ymax + gapsize)
  719. try:
  720. for g in geom:
  721. proc_geometry.append(g)
  722. except TypeError:
  723. proc_geometry.append(geom)
  724. return proc_geometry
  725. if kind == 'single':
  726. # fuse the lines
  727. object_geo = unary_union(object_geo)
  728. xmin, ymin, xmax, ymax = object_geo.bounds
  729. geo = box(xmin, ymin, xmax, ymax)
  730. # if Gerber create a buffer at a distance
  731. # if Geometry then cut through the geometry
  732. if cutout_obj.kind == 'gerber':
  733. if margin >= 0:
  734. geo = geo.buffer(margin + abs(dia / 2))
  735. else:
  736. geo = geo.buffer(margin - abs(dia / 2))
  737. solid_geo = cutout_rect_handler(geom=geo)
  738. else:
  739. if cutout_obj.kind == 'geometry':
  740. try:
  741. __ = iter(object_geo)
  742. except TypeError:
  743. object_geo = [object_geo]
  744. for geom_struct in object_geo:
  745. geom_struct = unary_union(geom_struct)
  746. xmin, ymin, xmax, ymax = geom_struct.bounds
  747. geom_struct = box(xmin, ymin, xmax, ymax)
  748. solid_geo += cutout_rect_handler(geom=geom_struct)
  749. elif cutout_obj.kind == 'gerber' and margin >= 0:
  750. try:
  751. __ = iter(object_geo)
  752. except TypeError:
  753. object_geo = [object_geo]
  754. for geom_struct in object_geo:
  755. geom_struct = unary_union(geom_struct)
  756. xmin, ymin, xmax, ymax = geom_struct.bounds
  757. geom_struct = box(xmin, ymin, xmax, ymax)
  758. geom_struct = geom_struct.buffer(margin + abs(dia / 2))
  759. solid_geo += cutout_rect_handler(geom=geom_struct)
  760. elif cutout_obj.kind == 'gerber' and margin < 0:
  761. self.app.inform.emit('[WARNING_NOTCL] %s' %
  762. _("Rectangular cutout with negative margin is not possible."))
  763. return "fail"
  764. geo_obj.options['cnctooldia'] = str(dia)
  765. geo_obj.options['cutz'] = self.cutz_entry.get_value()
  766. geo_obj.options['multidepth'] = self.mpass_cb.get_value()
  767. geo_obj.options['depthperpass'] = self.maxdepth_entry.get_value()
  768. geo_obj.solid_geometry = deepcopy(solid_geo)
  769. geo_obj.tools.update({
  770. 1: {
  771. 'tooldia': str(dia),
  772. 'offset': 'Path',
  773. 'offset_value': 0.0,
  774. 'type': _('Rough'),
  775. 'tool_type': 'C1',
  776. 'data': self.default_data,
  777. 'solid_geometry': geo_obj.solid_geometry
  778. }
  779. })
  780. geo_obj.multigeo = True
  781. geo_obj.tools[1]['data']['name'] = outname
  782. geo_obj.tools[1]['data']['cutz'] = self.cutz_entry.get_value()
  783. geo_obj.tools[1]['data']['multidepth'] = self.mpass_cb.get_value()
  784. geo_obj.tools[1]['data']['depthperpass'] = self.maxdepth_entry.get_value()
  785. outname = cutout_obj.options["name"] + "_cutout"
  786. ret = self.app.app_obj.new_object('geometry', outname, geo_init)
  787. if ret != 'fail':
  788. # cutout_obj.plot()
  789. self.app.inform.emit('[success] %s' % _("Any form CutOut operation finished."))
  790. # self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  791. self.app.should_we_save = True
  792. def on_manual_gap_click(self):
  793. self.app.inform.emit(_("Click on the selected geometry object perimeter to create a bridge gap ..."))
  794. self.app.geo_editor.tool_shape.enabled = True
  795. self.cutting_dia = float(self.dia.get_value())
  796. if 0 in {self.cutting_dia}:
  797. self.app.inform.emit('[ERROR_NOTCL] %s' %
  798. _("Tool Diameter is zero value. Change it to a positive real number."))
  799. return
  800. self.cutting_gapsize = float(self.gapsize.get_value())
  801. name = self.man_object_combo.currentText()
  802. # Get Geometry source object to be used as target for Manual adding Gaps
  803. try:
  804. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  805. except Exception as e:
  806. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  807. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  808. return
  809. if self.app.is_legacy is False:
  810. self.app.plotcanvas.graph_event_disconnect('key_press', self.app.ui.keyPressEvent)
  811. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  812. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  813. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  814. else:
  815. self.app.plotcanvas.graph_event_disconnect(self.app.kp)
  816. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  817. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  818. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  819. self.kp = self.app.plotcanvas.graph_event_connect('key_press', self.on_key_press)
  820. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  821. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release)
  822. def on_manual_cutout(self, click_pos):
  823. name = self.man_object_combo.currentText()
  824. # Get source object.
  825. try:
  826. self.man_cutout_obj = self.app.collection.get_by_name(str(name))
  827. except Exception as e:
  828. log.debug("CutOut.on_manual_cutout() --> %s" % str(e))
  829. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Geometry object"), name))
  830. return "Could not retrieve object: %s" % name
  831. if self.man_cutout_obj is None:
  832. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  833. (_("Geometry object for manual cutout not found"), self.man_cutout_obj))
  834. return
  835. # use the snapped position as reference
  836. snapped_pos = self.app.geo_editor.snap(click_pos[0], click_pos[1])
  837. cut_poly = self.cutting_geo(pos=(snapped_pos[0], snapped_pos[1]))
  838. self.man_cutout_obj.subtract_polygon(cut_poly)
  839. self.man_cutout_obj.plot()
  840. self.app.inform.emit('[success] %s' % _("Added manual Bridge Gap."))
  841. self.app.should_we_save = True
  842. def on_manual_geo(self):
  843. name = self.obj_combo.currentText()
  844. # Get source object.
  845. try:
  846. cutout_obj = self.app.collection.get_by_name(str(name))
  847. except Exception as e:
  848. log.debug("CutOut.on_manual_geo() --> %s" % str(e))
  849. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve Gerber object"), name))
  850. return "Could not retrieve object: %s" % name
  851. if cutout_obj is None:
  852. self.app.inform.emit('[ERROR_NOTCL] %s' %
  853. _("There is no Gerber object selected for Cutout.\n"
  854. "Select one and try again."))
  855. return
  856. if cutout_obj.kind != 'gerber':
  857. self.app.inform.emit('[ERROR_NOTCL] %s' %
  858. _("The selected object has to be of Gerber type.\n"
  859. "Select a Gerber file and try again."))
  860. return
  861. dia = float(self.dia.get_value())
  862. if 0 in {dia}:
  863. self.app.inform.emit('[ERROR_NOTCL] %s' %
  864. _("Tool Diameter is zero value. Change it to a positive real number."))
  865. return "Tool Diameter is zero value. Change it to a positive real number."
  866. try:
  867. kind = self.obj_kind_combo.get_value()
  868. except ValueError:
  869. return
  870. margin = float(self.margin.get_value())
  871. convex_box = self.convex_box.get_value()
  872. def geo_init(geo_obj, app_obj):
  873. geo_union = unary_union(cutout_obj.solid_geometry)
  874. if convex_box:
  875. geo = geo_union.convex_hull
  876. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  877. elif kind == 'single':
  878. if isinstance(geo_union, Polygon) or \
  879. (isinstance(geo_union, list) and len(geo_union) == 1) or \
  880. (isinstance(geo_union, MultiPolygon) and len(geo_union) == 1):
  881. geo_obj.solid_geometry = geo_union.buffer(margin + abs(dia / 2)).exterior
  882. elif isinstance(geo_union, MultiPolygon):
  883. x0, y0, x1, y1 = geo_union.bounds
  884. geo = box(x0, y0, x1, y1)
  885. geo_obj.solid_geometry = geo.buffer(margin + abs(dia / 2))
  886. else:
  887. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  888. (_("Geometry not supported for cutout"), type(geo_union)))
  889. return 'fail'
  890. else:
  891. geo = geo_union
  892. geo = geo.buffer(margin + abs(dia / 2))
  893. if isinstance(geo, Polygon):
  894. geo_obj.solid_geometry = geo.exterior
  895. elif isinstance(geo, MultiPolygon):
  896. solid_geo = []
  897. for poly in geo:
  898. solid_geo.append(poly.exterior)
  899. geo_obj.solid_geometry = deepcopy(solid_geo)
  900. geo_obj.options['cnctooldia'] = str(dia)
  901. geo_obj.options['cutz'] = self.cutz_entry.get_value()
  902. geo_obj.options['multidepth'] = self.mpass_cb.get_value()
  903. geo_obj.options['depthperpass'] = self.maxdepth_entry.get_value()
  904. geo_obj.tools.update({
  905. 1: {
  906. 'tooldia': str(dia),
  907. 'offset': 'Path',
  908. 'offset_value': 0.0,
  909. 'type': _('Rough'),
  910. 'tool_type': 'C1',
  911. 'data': self.default_data,
  912. 'solid_geometry': geo_obj.solid_geometry
  913. }
  914. })
  915. geo_obj.multigeo = True
  916. geo_obj.tools[1]['data']['name'] = outname
  917. geo_obj.tools[1]['data']['cutz'] = self.cutz_entry.get_value()
  918. geo_obj.tools[1]['data']['multidepth'] = self.mpass_cb.get_value()
  919. geo_obj.tools[1]['data']['depthperpass'] = self.maxdepth_entry.get_value()
  920. outname = cutout_obj.options["name"] + "_cutout"
  921. self.app.app_obj.new_object('geometry', outname, geo_init)
  922. def cutting_geo(self, pos):
  923. self.cutting_dia = float(self.dia.get_value())
  924. self.cutting_gapsize = float(self.gapsize.get_value())
  925. offset = self.cutting_dia / 2 + self.cutting_gapsize / 2
  926. # cutting area definition
  927. orig_x = pos[0]
  928. orig_y = pos[1]
  929. xmin = orig_x - offset
  930. ymin = orig_y - offset
  931. xmax = orig_x + offset
  932. ymax = orig_y + offset
  933. cut_poly = box(xmin, ymin, xmax, ymax)
  934. return cut_poly
  935. # To be called after clicking on the plot.
  936. def on_mouse_click_release(self, event):
  937. if self.app.is_legacy is False:
  938. event_pos = event.pos
  939. # event_is_dragging = event.is_dragging
  940. right_button = 2
  941. else:
  942. event_pos = (event.xdata, event.ydata)
  943. # event_is_dragging = self.app.plotcanvas.is_dragging
  944. right_button = 3
  945. try:
  946. x = float(event_pos[0])
  947. y = float(event_pos[1])
  948. except TypeError:
  949. return
  950. event_pos = (x, y)
  951. # do paint single only for left mouse clicks
  952. if event.button == 1:
  953. self.app.inform.emit(_("Making manual bridge gap..."))
  954. pos = self.app.plotcanvas.translate_coords(event_pos)
  955. self.on_manual_cutout(click_pos=pos)
  956. # if RMB then we exit
  957. elif event.button == right_button and self.mouse_is_dragging is False:
  958. if self.app.is_legacy is False:
  959. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  960. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  961. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  962. else:
  963. self.app.plotcanvas.graph_event_disconnect(self.kp)
  964. self.app.plotcanvas.graph_event_disconnect(self.mm)
  965. self.app.plotcanvas.graph_event_disconnect(self.mr)
  966. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  967. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  968. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  969. self.app.on_mouse_click_release_over_plot)
  970. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  971. # Remove any previous utility shape
  972. self.app.geo_editor.tool_shape.clear(update=True)
  973. self.app.geo_editor.tool_shape.enabled = False
  974. def on_mouse_move(self, event):
  975. self.app.on_mouse_move_over_plot(event=event)
  976. if self.app.is_legacy is False:
  977. event_pos = event.pos
  978. event_is_dragging = event.is_dragging
  979. # right_button = 2
  980. else:
  981. event_pos = (event.xdata, event.ydata)
  982. event_is_dragging = self.app.plotcanvas.is_dragging
  983. # right_button = 3
  984. try:
  985. x = float(event_pos[0])
  986. y = float(event_pos[1])
  987. except TypeError:
  988. return
  989. event_pos = (x, y)
  990. pos = self.canvas.translate_coords(event_pos)
  991. event.xdata, event.ydata = pos[0], pos[1]
  992. if event_is_dragging is True:
  993. self.mouse_is_dragging = True
  994. else:
  995. self.mouse_is_dragging = False
  996. try:
  997. x = float(event.xdata)
  998. y = float(event.ydata)
  999. except TypeError:
  1000. return
  1001. if self.app.grid_status():
  1002. snap_x, snap_y = self.app.geo_editor.snap(x, y)
  1003. else:
  1004. snap_x, snap_y = x, y
  1005. self.x_pos, self.y_pos = snap_x, snap_y
  1006. # #################################################
  1007. # ### This section makes the cutting geo to #######
  1008. # ### rotate if it intersects the target geo ######
  1009. # #################################################
  1010. cut_geo = self.cutting_geo(pos=(snap_x, snap_y))
  1011. man_geo = self.man_cutout_obj.solid_geometry
  1012. def get_angle(geo):
  1013. line = cut_geo.intersection(geo)
  1014. try:
  1015. pt1_x = line.coords[0][0]
  1016. pt1_y = line.coords[0][1]
  1017. pt2_x = line.coords[1][0]
  1018. pt2_y = line.coords[1][1]
  1019. dx = pt1_x - pt2_x
  1020. dy = pt1_y - pt2_y
  1021. if dx == 0 or dy == 0:
  1022. angle = 0
  1023. else:
  1024. radian = math.atan(dx / dy)
  1025. angle = radian * 180 / math.pi
  1026. except Exception:
  1027. angle = 0
  1028. return angle
  1029. try:
  1030. rot_angle = 0
  1031. for geo_el in man_geo:
  1032. if isinstance(geo_el, Polygon):
  1033. work_geo = geo_el.exterior
  1034. if cut_geo.intersects(work_geo):
  1035. rot_angle = get_angle(geo=work_geo)
  1036. else:
  1037. rot_angle = 0
  1038. else:
  1039. rot_angle = 0
  1040. if cut_geo.intersects(geo_el):
  1041. rot_angle = get_angle(geo=geo_el)
  1042. if rot_angle != 0:
  1043. break
  1044. except TypeError:
  1045. if isinstance(man_geo, Polygon):
  1046. work_geo = man_geo.exterior
  1047. if cut_geo.intersects(work_geo):
  1048. rot_angle = get_angle(geo=work_geo)
  1049. else:
  1050. rot_angle = 0
  1051. else:
  1052. rot_angle = 0
  1053. if cut_geo.intersects(man_geo):
  1054. rot_angle = get_angle(geo=man_geo)
  1055. # rotate only if there is an angle to rotate to
  1056. if rot_angle != 0:
  1057. cut_geo = affinity.rotate(cut_geo, -rot_angle)
  1058. # Remove any previous utility shape
  1059. self.app.geo_editor.tool_shape.clear(update=True)
  1060. self.draw_utility_geometry(geo=cut_geo)
  1061. def draw_utility_geometry(self, geo):
  1062. self.app.geo_editor.tool_shape.add(
  1063. shape=geo,
  1064. color=(self.app.defaults["global_draw_color"] + '80'),
  1065. update=False,
  1066. layer=0,
  1067. tolerance=None)
  1068. self.app.geo_editor.tool_shape.redraw()
  1069. def on_key_press(self, event):
  1070. # events out of the self.app.collection view (it's about Project Tab) are of type int
  1071. if type(event) is int:
  1072. key = event
  1073. # events from the GUI are of type QKeyEvent
  1074. elif type(event) == QtGui.QKeyEvent:
  1075. key = event.key()
  1076. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1077. key = event.key
  1078. key = QtGui.QKeySequence(key)
  1079. # check for modifiers
  1080. key_string = key.toString().lower()
  1081. if '+' in key_string:
  1082. mod, __, key_text = key_string.rpartition('+')
  1083. if mod.lower() == 'ctrl':
  1084. # modifiers = QtCore.Qt.ControlModifier
  1085. pass
  1086. elif mod.lower() == 'alt':
  1087. # modifiers = QtCore.Qt.AltModifier
  1088. pass
  1089. elif mod.lower() == 'shift':
  1090. # modifiers = QtCore.Qt.ShiftModifier
  1091. pass
  1092. else:
  1093. # modifiers = QtCore.Qt.NoModifier
  1094. pass
  1095. key = QtGui.QKeySequence(key_text)
  1096. # events from Vispy are of type KeyEvent
  1097. else:
  1098. key = event.key
  1099. # Escape = Deselect All
  1100. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1101. if self.app.is_legacy is False:
  1102. self.app.plotcanvas.graph_event_disconnect('key_press', self.on_key_press)
  1103. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  1104. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release)
  1105. else:
  1106. self.app.plotcanvas.graph_event_disconnect(self.kp)
  1107. self.app.plotcanvas.graph_event_disconnect(self.mm)
  1108. self.app.plotcanvas.graph_event_disconnect(self.mr)
  1109. self.app.kp = self.app.plotcanvas.graph_event_connect('key_press', self.app.ui.keyPressEvent)
  1110. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press', self.app.on_mouse_click_over_plot)
  1111. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  1112. self.app.on_mouse_click_release_over_plot)
  1113. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.app.on_mouse_move_over_plot)
  1114. # Remove any previous utility shape
  1115. self.app.geo_editor.tool_shape.clear(update=True)
  1116. self.app.geo_editor.tool_shape.enabled = False
  1117. # Grid toggle
  1118. if key == QtCore.Qt.Key_G or key == 'G':
  1119. self.app.ui.grid_snap_btn.trigger()
  1120. # Jump to coords
  1121. if key == QtCore.Qt.Key_J or key == 'J':
  1122. l_x, l_y = self.app.on_jump_to()
  1123. self.app.geo_editor.tool_shape.clear(update=True)
  1124. geo = self.cutting_geo(pos=(l_x, l_y))
  1125. self.draw_utility_geometry(geo=geo)
  1126. @staticmethod
  1127. def subtract_poly_from_geo(solid_geo, x0, y0, x1, y1):
  1128. """
  1129. Subtract polygon made from points from the given object.
  1130. This only operates on the paths in the original geometry,
  1131. i.e. it converts polygons into paths.
  1132. :param x0: x coord for lower left vertex of the polygon.
  1133. :param y0: y coord for lower left vertex of the polygon.
  1134. :param x1: x coord for upper right vertex of the polygon.
  1135. :param y1: y coord for upper right vertex of the polygon.
  1136. :param solid_geo: Geometry from which to substract. If none, use the solid_geomety property of the object
  1137. :return: none
  1138. """
  1139. points = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
  1140. # pathonly should be allways True, otherwise polygons are not subtracted
  1141. flat_geometry = flatten(geometry=solid_geo)
  1142. log.debug("%d paths" % len(flat_geometry))
  1143. polygon = Polygon(points)
  1144. toolgeo = cascaded_union(polygon)
  1145. diffs = []
  1146. for target in flat_geometry:
  1147. if type(target) == LineString or type(target) == LinearRing:
  1148. diffs.append(target.difference(toolgeo))
  1149. else:
  1150. log.warning("Not implemented.")
  1151. return unary_union(diffs)
  1152. def reset_fields(self):
  1153. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1154. def flatten(geometry):
  1155. """
  1156. Creates a list of non-iterable linear geometry objects.
  1157. Polygons are expanded into its exterior and interiors.
  1158. Results are placed in self.flat_geometry
  1159. :param geometry: Shapely type or list or list of list of such.
  1160. """
  1161. flat_geo = []
  1162. try:
  1163. for geo in geometry:
  1164. if type(geo) == Polygon:
  1165. flat_geo.append(geo.exterior)
  1166. for subgeo in geo.interiors:
  1167. flat_geo.append(subgeo)
  1168. else:
  1169. flat_geo.append(geo)
  1170. except TypeError:
  1171. if type(geometry) == Polygon:
  1172. flat_geo.append(geometry.exterior)
  1173. for subgeo in geometry.interiors:
  1174. flat_geo.append(subgeo)
  1175. else:
  1176. flat_geo.append(geometry)
  1177. return flat_geo
  1178. def recursive_bounds(geometry):
  1179. """
  1180. Return the bounds of the biggest bounding box in geometry, one that include all.
  1181. :param geometry: a iterable object that holds geometry
  1182. :return: Returns coordinates of rectangular bounds of geometry: (xmin, ymin, xmax, ymax).
  1183. """
  1184. # now it can get bounds for nested lists of objects
  1185. def bounds_rec(obj):
  1186. try:
  1187. minx = Inf
  1188. miny = Inf
  1189. maxx = -Inf
  1190. maxy = -Inf
  1191. for k in obj:
  1192. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1193. minx = min(minx, minx_)
  1194. miny = min(miny, miny_)
  1195. maxx = max(maxx, maxx_)
  1196. maxy = max(maxy, maxy_)
  1197. return minx, miny, maxx, maxy
  1198. except TypeError:
  1199. # it's a Shapely object, return it's bounds
  1200. if obj:
  1201. return obj.bounds
  1202. return bounds_rec(geometry)