ToolPaint.py 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # File Modified: Marius Adrian Stanciu (c) #
  5. # Date: 3/10/2019 #
  6. # MIT Licence #
  7. # ##########################################################
  8. from FlatCAMTool import FlatCAMTool
  9. from copy import copy, deepcopy
  10. from ObjectCollection import *
  11. from shapely.geometry import base
  12. import gettext
  13. import FlatCAMTranslation as fcTranslate
  14. import builtins
  15. fcTranslate.apply_language('strings')
  16. if '_' not in builtins.__dict__:
  17. _ = gettext.gettext
  18. class ToolPaint(FlatCAMTool, Gerber):
  19. toolName = _("Paint Tool")
  20. def __init__(self, app):
  21. self.app = app
  22. FlatCAMTool.__init__(self, app)
  23. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  24. # ## Title
  25. title_label = QtWidgets.QLabel("%s" % self.toolName)
  26. title_label.setStyleSheet("""
  27. QLabel
  28. {
  29. font-size: 16px;
  30. font-weight: bold;
  31. }
  32. """)
  33. self.layout.addWidget(title_label)
  34. self.tools_frame = QtWidgets.QFrame()
  35. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  36. self.layout.addWidget(self.tools_frame)
  37. self.tools_box = QtWidgets.QVBoxLayout()
  38. self.tools_box.setContentsMargins(0, 0, 0, 0)
  39. self.tools_frame.setLayout(self.tools_box)
  40. # ## Form Layout
  41. form_layout = QtWidgets.QFormLayout()
  42. self.tools_box.addLayout(form_layout)
  43. # ################################################
  44. # ##### Type of object to be painted #############
  45. # ################################################
  46. self.type_obj_combo = QtWidgets.QComboBox()
  47. self.type_obj_combo.addItem("Gerber")
  48. self.type_obj_combo.addItem("Excellon")
  49. self.type_obj_combo.addItem("Geometry")
  50. # we get rid of item1 ("Excellon") as it is not suitable
  51. self.type_obj_combo.view().setRowHidden(1, True)
  52. self.type_obj_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  53. self.type_obj_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  54. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  55. self.type_obj_combo_label.setToolTip(
  56. _("Specify the type of object to be painted.\n"
  57. "It can be of type: Gerber or Geometry.\n"
  58. "What is selected here will dictate the kind\n"
  59. "of objects that will populate the 'Object' combobox.")
  60. )
  61. self.type_obj_combo_label.setMinimumWidth(60)
  62. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  63. # ################################################
  64. # ##### The object to be painted #################
  65. # ################################################
  66. self.obj_combo = QtWidgets.QComboBox()
  67. self.obj_combo.setModel(self.app.collection)
  68. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  69. self.obj_combo.setCurrentIndex(1)
  70. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  71. self.object_label.setToolTip(_("Object to be painted."))
  72. form_layout.addRow(self.object_label, self.obj_combo)
  73. e_lab_0 = QtWidgets.QLabel('')
  74. form_layout.addRow(e_lab_0)
  75. # ### Tools ## ##
  76. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  77. self.tools_table_label.setToolTip(
  78. _("Tools pool from which the algorithm\n"
  79. "will pick the ones used for painting.")
  80. )
  81. self.tools_box.addWidget(self.tools_table_label)
  82. self.tools_table = FCTable()
  83. self.tools_box.addWidget(self.tools_table)
  84. self.tools_table.setColumnCount(4)
  85. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  86. self.tools_table.setColumnHidden(3, True)
  87. # self.tools_table.setSortingEnabled(False)
  88. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  89. self.tools_table.horizontalHeaderItem(0).setToolTip(
  90. _("This is the Tool Number.\n"
  91. "Painting will start with the tool with the biggest diameter,\n"
  92. "continuing until there are no more tools.\n"
  93. "Only tools that create painting geometry will still be present\n"
  94. "in the resulting geometry. This is because with some tools\n"
  95. "this function will not be able to create painting geometry.")
  96. )
  97. self.tools_table.horizontalHeaderItem(1).setToolTip(
  98. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  99. "is the cut width into the material."))
  100. self.tools_table.horizontalHeaderItem(2).setToolTip(
  101. _("The Tool Type (TT) can be:<BR>"
  102. "- <B>Circular</B> with 1 ... 4 teeth -> it is informative only. Being circular, <BR>"
  103. "the cut width in material is exactly the tool diameter.<BR>"
  104. "- <B>Ball</B> -> informative only and make reference to the Ball type endmill.<BR>"
  105. "- <B>V-Shape</B> -> it will disable de Z-Cut parameter in the resulting geometry UI form "
  106. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and "
  107. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such "
  108. "as the cut width into material will be equal with the value in the Tool Diameter "
  109. "column of this table.<BR>"
  110. "Choosing the <B>V-Shape</B> Tool Type automatically will select the Operation Type "
  111. "in the resulting geometry as Isolation."))
  112. self.order_label = QtWidgets.QLabel('<b>%s:</b>' % _('Tool order'))
  113. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  114. "'No' --> means that the used order is the one in the tool table\n"
  115. "'Forward' --> means that the tools will be ordered from small to big\n"
  116. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  117. "WARNING: using rest machining will automatically set the order\n"
  118. "in reverse and disable this control."))
  119. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  120. {'label': _('Forward'), 'value': 'fwd'},
  121. {'label': _('Reverse'), 'value': 'rev'}])
  122. self.order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  123. "'No' --> means that the used order is the one in the tool table\n"
  124. "'Forward' --> means that the tools will be ordered from small to big\n"
  125. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  126. "WARNING: using rest machining will automatically set the order\n"
  127. "in reverse and disable this control."))
  128. form = QtWidgets.QFormLayout()
  129. self.tools_box.addLayout(form)
  130. form.addRow(QtWidgets.QLabel(''), QtWidgets.QLabel(''))
  131. form.addRow(self.order_label, self.order_radio)
  132. # ### Add a new Tool ## ##
  133. hlay = QtWidgets.QHBoxLayout()
  134. self.tools_box.addLayout(hlay)
  135. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  136. self.addtool_entry_lbl.setToolTip(
  137. _("Diameter for the new tool.")
  138. )
  139. self.addtool_entry = FCEntry2()
  140. # hlay.addWidget(self.addtool_label)
  141. # hlay.addStretch()
  142. hlay.addWidget(self.addtool_entry_lbl)
  143. hlay.addWidget(self.addtool_entry)
  144. grid2 = QtWidgets.QGridLayout()
  145. self.tools_box.addLayout(grid2)
  146. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  147. self.addtool_btn.setToolTip(
  148. _("Add a new tool to the Tool Table\n"
  149. "with the diameter specified above.")
  150. )
  151. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  152. # self.copytool_btn.setToolTip(
  153. # "Copy a selection of tools in the Tool Table\n"
  154. # "by first selecting a row in the Tool Table."
  155. # )
  156. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  157. self.deltool_btn.setToolTip(
  158. _("Delete a selection of tools in the Tool Table\n"
  159. "by first selecting a row(s) in the Tool Table.")
  160. )
  161. grid2.addWidget(self.addtool_btn, 0, 0)
  162. # grid2.addWidget(self.copytool_btn, 0, 1)
  163. grid2.addWidget(self.deltool_btn, 0, 2)
  164. self.empty_label_0 = QtWidgets.QLabel('')
  165. self.tools_box.addWidget(self.empty_label_0)
  166. grid3 = QtWidgets.QGridLayout()
  167. self.tools_box.addLayout(grid3)
  168. # Overlap
  169. ovlabel = QtWidgets.QLabel('%s:' % _('Overlap Rate'))
  170. ovlabel.setToolTip(
  171. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  172. "Example:\n"
  173. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  174. "Adjust the value starting with lower values\n"
  175. "and increasing it if areas that should be painted are still \n"
  176. "not painted.\n"
  177. "Lower values = faster processing, faster execution on PCB.\n"
  178. "Higher values = slow processing and slow execution on CNC\n"
  179. "due of too many paths.")
  180. )
  181. grid3.addWidget(ovlabel, 1, 0)
  182. self.paintoverlap_entry = FCEntry()
  183. grid3.addWidget(self.paintoverlap_entry, 1, 1)
  184. # Margin
  185. marginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  186. marginlabel.setToolTip(
  187. _("Distance by which to avoid\n"
  188. "the edges of the polygon to\n"
  189. "be painted.")
  190. )
  191. grid3.addWidget(marginlabel, 2, 0)
  192. self.paintmargin_entry = FCEntry()
  193. grid3.addWidget(self.paintmargin_entry, 2, 1)
  194. # Method
  195. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  196. methodlabel.setToolTip(
  197. _("Algorithm for non-copper clearing:<BR>"
  198. "<B>Standard</B>: Fixed step inwards.<BR>"
  199. "<B>Seed-based</B>: Outwards from seed.<BR>"
  200. "<B>Line-based</B>: Parallel lines.")
  201. )
  202. grid3.addWidget(methodlabel, 3, 0)
  203. self.paintmethod_combo = RadioSet([
  204. {"label": _("Standard"), "value": "standard"},
  205. {"label": _("Seed-based"), "value": "seed"},
  206. {"label": _("Straight lines"), "value": "lines"}
  207. ], orientation='vertical', stretch=False)
  208. grid3.addWidget(self.paintmethod_combo, 3, 1)
  209. # Connect lines
  210. pathconnectlabel = QtWidgets.QLabel('%s:' % _("Connect"))
  211. pathconnectlabel.setToolTip(
  212. _("Draw lines between resulting\n"
  213. "segments to minimize tool lifts.")
  214. )
  215. grid3.addWidget(pathconnectlabel, 4, 0)
  216. self.pathconnect_cb = FCCheckBox()
  217. grid3.addWidget(self.pathconnect_cb, 4, 1)
  218. contourlabel = QtWidgets.QLabel('%s:' % _("Contour"))
  219. contourlabel.setToolTip(
  220. _("Cut around the perimeter of the polygon\n"
  221. "to trim rough edges.")
  222. )
  223. grid3.addWidget(contourlabel, 5, 0)
  224. self.paintcontour_cb = FCCheckBox()
  225. grid3.addWidget(self.paintcontour_cb, 5, 1)
  226. restlabel = QtWidgets.QLabel('%s:' % _("Rest M."))
  227. restlabel.setToolTip(
  228. _("If checked, use 'rest machining'.\n"
  229. "Basically it will clear copper outside PCB features,\n"
  230. "using the biggest tool and continue with the next tools,\n"
  231. "from bigger to smaller, to clear areas of copper that\n"
  232. "could not be cleared by previous tool, until there is\n"
  233. "no more copper to clear or there are no more tools.\n\n"
  234. "If not checked, use the standard algorithm.")
  235. )
  236. grid3.addWidget(restlabel, 6, 0)
  237. self.rest_cb = FCCheckBox()
  238. grid3.addWidget(self.rest_cb, 6, 1)
  239. # Polygon selection
  240. selectlabel = QtWidgets.QLabel('%s:' % _('Selection'))
  241. selectlabel.setToolTip(
  242. _("How to select the polygons to paint.<BR>"
  243. "Options:<BR>"
  244. "- <B>Single Polygons</B>: left mouse click on the polygon to be painted.<BR>"
  245. "- <B>Area Selection</B>: left mouse click to start selection of the area to be painted.<BR>"
  246. "- <B>All Polygons</B>: paint all polygons.<BR>"
  247. "- <B>Reference Object</B>: paint an area described by an external reference object.")
  248. )
  249. grid3.addWidget(selectlabel, 7, 0)
  250. # grid3 = QtWidgets.QGridLayout()
  251. self.selectmethod_combo = RadioSet([
  252. {"label": _("Single Polygon"), "value": "single"},
  253. {"label": _("Area Selection"), "value": "area"},
  254. {"label": _("All Polygons"), "value": "all"},
  255. {"label": _("Reference Object"), "value": "ref"}
  256. ], orientation='vertical', stretch=False)
  257. self.selectmethod_combo.setToolTip(
  258. _("How to select the polygons to paint.<BR>"
  259. "Options:<BR>"
  260. "- <B>Single Polygons</B>: left mouse click on the polygon to be painted.<BR>"
  261. "- <B>Area Selection</B>: left mouse click to start selection of the area to be painted.<BR>"
  262. "- <B>All Polygons</B>: paint all polygons.<BR>"
  263. "- <B>Reference Object</B>: paint an area described by an external reference object.")
  264. )
  265. grid3.addWidget(self.selectmethod_combo, 7, 1)
  266. form1 = QtWidgets.QFormLayout()
  267. self.tools_box.addLayout(form1)
  268. self.box_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  269. self.box_combo_type_label.setToolTip(
  270. _("The type of FlatCAM object to be used as paint reference.\n"
  271. "It can be Gerber, Excellon or Geometry.")
  272. )
  273. self.box_combo_type = QtWidgets.QComboBox()
  274. self.box_combo_type.addItem(_("Gerber Reference Box Object"))
  275. self.box_combo_type.addItem(_("Excellon Reference Box Object"))
  276. self.box_combo_type.addItem(_("Geometry Reference Box Object"))
  277. form1.addRow(self.box_combo_type_label, self.box_combo_type)
  278. self.box_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  279. self.box_combo_label.setToolTip(
  280. _("The FlatCAM object to be used as non copper clearing reference.")
  281. )
  282. self.box_combo = QtWidgets.QComboBox()
  283. self.box_combo.setModel(self.app.collection)
  284. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  285. self.box_combo.setCurrentIndex(1)
  286. form1.addRow(self.box_combo_label, self.box_combo)
  287. self.box_combo.hide()
  288. self.box_combo_label.hide()
  289. self.box_combo_type.hide()
  290. self.box_combo_type_label.hide()
  291. # GO Button
  292. self.generate_paint_button = QtWidgets.QPushButton(_('Create Paint Geometry'))
  293. self.generate_paint_button.setToolTip(
  294. _("After clicking here, click inside<BR>"
  295. "the polygon you wish to be painted if <B>Single</B> is selected.<BR>"
  296. "If <B>Area</B> is selected, then the selection of the area to be painted<BR>"
  297. "will be initiated by a first click and finished by the second mouse click.<BR>"
  298. "If <B>All</B> is selected then the Paint will start after click.<BR>"
  299. "If <B>Ref</B> is selected then the Paint will start after click,<BR>"
  300. "and the painted area will be described by a selected object.<BR>"
  301. "A new Geometry object with the tool paths will be created.")
  302. )
  303. self.tools_box.addWidget(self.generate_paint_button)
  304. self.tools_box.addStretch()
  305. self.obj_name = ""
  306. self.paint_obj = None
  307. self.units = ''
  308. self.paint_tools = {}
  309. self.tooluid = 0
  310. self.first_click = False
  311. self.cursor_pos = None
  312. self.mouse_is_dragging = False
  313. self.sel_rect = []
  314. # store here the default data for Geometry Data
  315. self.default_data = {}
  316. self.default_data.update({
  317. "name": '_paint',
  318. "plot": self.app.defaults["geometry_plot"],
  319. "cutz": self.app.defaults["geometry_cutz"],
  320. "vtipdia": 0.1,
  321. "vtipangle": 30,
  322. "travelz": self.app.defaults["geometry_travelz"],
  323. "feedrate": self.app.defaults["geometry_feedrate"],
  324. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  325. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  326. "dwell": self.app.defaults["geometry_dwell"],
  327. "dwelltime": self.app.defaults["geometry_dwelltime"],
  328. "multidepth": self.app.defaults["geometry_multidepth"],
  329. "ppname_g": self.app.defaults["geometry_ppname_g"],
  330. "depthperpass": self.app.defaults["geometry_depthperpass"],
  331. "extracut": self.app.defaults["geometry_extracut"],
  332. "toolchange": self.app.defaults["geometry_toolchange"],
  333. "toolchangez": self.app.defaults["geometry_toolchangez"],
  334. "endz": self.app.defaults["geometry_endz"],
  335. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  336. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  337. "startz": self.app.defaults["geometry_startz"],
  338. "tooldia": self.app.defaults["tools_painttooldia"],
  339. "paintmargin": self.app.defaults["tools_paintmargin"],
  340. "paintmethod": self.app.defaults["tools_paintmethod"],
  341. "selectmethod": self.app.defaults["tools_selectmethod"],
  342. "pathconnect": self.app.defaults["tools_pathconnect"],
  343. "paintcontour": self.app.defaults["tools_paintcontour"],
  344. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  345. })
  346. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  347. # ## Signals
  348. self.addtool_btn.clicked.connect(self.on_tool_add)
  349. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  350. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  351. self.tools_table.itemChanged.connect(self.on_tool_edit)
  352. self.deltool_btn.clicked.connect(self.on_tool_delete)
  353. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  354. self.selectmethod_combo.activated_custom.connect(self.on_radio_selection)
  355. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  356. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  357. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  358. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  359. def on_type_obj_index_changed(self, index):
  360. obj_type = self.type_obj_combo.currentIndex()
  361. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  362. self.obj_combo.setCurrentIndex(0)
  363. def install(self, icon=None, separator=None, **kwargs):
  364. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  365. def run(self, toggle=True):
  366. self.app.report_usage("ToolPaint()")
  367. if toggle:
  368. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  369. if self.app.ui.splitter.sizes()[0] == 0:
  370. self.app.ui.splitter.setSizes([1, 1])
  371. else:
  372. try:
  373. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  374. # if tab is populated with the tool but it does not have the focus, focus on it
  375. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  376. # focus on Tool Tab
  377. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  378. else:
  379. self.app.ui.splitter.setSizes([0, 1])
  380. except AttributeError:
  381. pass
  382. else:
  383. if self.app.ui.splitter.sizes()[0] == 0:
  384. self.app.ui.splitter.setSizes([1, 1])
  385. FlatCAMTool.run(self)
  386. self.set_tool_ui()
  387. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  388. def reset_usage(self):
  389. self.obj_name = ""
  390. self.paint_obj = None
  391. self.bound_obj = None
  392. self.first_click = False
  393. self.cursor_pos = None
  394. self.mouse_is_dragging = False
  395. self.sel_rect = []
  396. def on_radio_selection(self):
  397. if self.selectmethod_combo.get_value() == "ref":
  398. self.box_combo.show()
  399. self.box_combo_label.show()
  400. self.box_combo_type.show()
  401. self.box_combo_type_label.show()
  402. else:
  403. self.box_combo.hide()
  404. self.box_combo_label.hide()
  405. self.box_combo_type.hide()
  406. self.box_combo_type_label.hide()
  407. if self.selectmethod_combo.get_value() == 'single':
  408. # disable rest-machining for single polygon painting
  409. self.rest_cb.set_value(False)
  410. self.rest_cb.setDisabled(True)
  411. # delete all tools except first row / tool for single polygon painting
  412. list_to_del = list(range(1, self.tools_table.rowCount()))
  413. if list_to_del:
  414. self.on_tool_delete(rows_to_delete=list_to_del)
  415. # disable addTool and delTool
  416. self.addtool_entry.setDisabled(True)
  417. self.addtool_btn.setDisabled(True)
  418. self.deltool_btn.setDisabled(True)
  419. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  420. if self.selectmethod_combo.get_value() == 'area':
  421. # disable rest-machining for single polygon painting
  422. self.rest_cb.set_value(False)
  423. self.rest_cb.setDisabled(True)
  424. else:
  425. self.rest_cb.setDisabled(False)
  426. self.addtool_entry.setDisabled(False)
  427. self.addtool_btn.setDisabled(False)
  428. self.deltool_btn.setDisabled(False)
  429. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  430. def on_order_changed(self, order):
  431. if order != 'no':
  432. self.build_ui()
  433. def on_rest_machining_check(self, state):
  434. if state:
  435. self.order_radio.set_value('rev')
  436. self.order_label.setDisabled(True)
  437. self.order_radio.setDisabled(True)
  438. else:
  439. self.order_label.setDisabled(False)
  440. self.order_radio.setDisabled(False)
  441. def set_tool_ui(self):
  442. self.tools_frame.show()
  443. self.reset_fields()
  444. # ## Init the GUI interface
  445. self.order_radio.set_value(self.app.defaults["tools_paintorder"])
  446. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  447. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  448. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  449. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  450. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  451. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  452. # updated units
  453. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  454. if self.units == "IN":
  455. self.addtool_entry.set_value(0.039)
  456. else:
  457. self.addtool_entry.set_value(1)
  458. self.tools_table.setupContextMenu()
  459. self.tools_table.addContextMenu(
  460. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  461. self.tools_table.addContextMenu(
  462. "Delete", lambda:
  463. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  464. # set the working variables to a known state
  465. self.paint_tools.clear()
  466. self.tooluid = 0
  467. self.default_data.clear()
  468. self.default_data.update({
  469. "name": '_paint',
  470. "plot": self.app.defaults["geometry_plot"],
  471. "cutz": self.app.defaults["geometry_cutz"],
  472. "vtipdia": 0.1,
  473. "vtipangle": 30,
  474. "travelz": self.app.defaults["geometry_travelz"],
  475. "feedrate": self.app.defaults["geometry_feedrate"],
  476. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  477. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  478. "dwell": self.app.defaults["geometry_dwell"],
  479. "dwelltime": self.app.defaults["geometry_dwelltime"],
  480. "multidepth": self.app.defaults["geometry_multidepth"],
  481. "ppname_g": self.app.defaults["geometry_ppname_g"],
  482. "depthperpass": self.app.defaults["geometry_depthperpass"],
  483. "extracut": self.app.defaults["geometry_extracut"],
  484. "toolchange": self.app.defaults["geometry_toolchange"],
  485. "toolchangez": self.app.defaults["geometry_toolchangez"],
  486. "endz": self.app.defaults["geometry_endz"],
  487. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  488. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  489. "startz": self.app.defaults["geometry_startz"],
  490. "tooldia": self.app.defaults["tools_painttooldia"],
  491. "paintmargin": self.app.defaults["tools_paintmargin"],
  492. "paintmethod": self.app.defaults["tools_paintmethod"],
  493. "selectmethod": self.app.defaults["tools_selectmethod"],
  494. "pathconnect": self.app.defaults["tools_pathconnect"],
  495. "paintcontour": self.app.defaults["tools_paintcontour"],
  496. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  497. })
  498. # call on self.on_tool_add() counts as an call to self.build_ui()
  499. # through this, we add a initial row / tool in the tool_table
  500. self.on_tool_add(self.app.defaults["tools_painttooldia"], muted=True)
  501. # if the Paint Method is "Single" disable the tool table context menu
  502. if self.default_data["selectmethod"] == "single":
  503. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  504. def build_ui(self):
  505. try:
  506. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  507. self.tools_table.itemChanged.disconnect()
  508. except (TypeError, AttributeError):
  509. pass
  510. # updated units
  511. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  512. sorted_tools = []
  513. for k, v in self.paint_tools.items():
  514. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  515. order = self.order_radio.get_value()
  516. if order == 'fwd':
  517. sorted_tools.sort(reverse=False)
  518. elif order == 'rev':
  519. sorted_tools.sort(reverse=True)
  520. else:
  521. pass
  522. n = len(sorted_tools)
  523. self.tools_table.setRowCount(n)
  524. tool_id = 0
  525. for tool_sorted in sorted_tools:
  526. for tooluid_key, tooluid_value in self.paint_tools.items():
  527. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  528. tool_id += 1
  529. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  530. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  531. row_no = tool_id - 1
  532. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  533. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  534. # There are no drill bits in MM with more than 3 decimals diameter
  535. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  536. if self.units == 'MM':
  537. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  538. else:
  539. dia = QtWidgets.QTableWidgetItem('%.4f' % tooluid_value['tooldia'])
  540. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  541. tool_type_item = QtWidgets.QComboBox()
  542. for item in self.tool_type_item_options:
  543. tool_type_item.addItem(item)
  544. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  545. idx = tool_type_item.findText(tooluid_value['tool_type'])
  546. tool_type_item.setCurrentIndex(idx)
  547. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  548. self.tools_table.setItem(row_no, 1, dia) # Diameter
  549. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  550. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  551. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  552. # make the diameter column editable
  553. for row in range(tool_id):
  554. self.tools_table.item(row, 1).setFlags(
  555. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  556. # all the tools are selected by default
  557. self.tools_table.selectColumn(0)
  558. #
  559. self.tools_table.resizeColumnsToContents()
  560. self.tools_table.resizeRowsToContents()
  561. vertical_header = self.tools_table.verticalHeader()
  562. vertical_header.hide()
  563. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  564. horizontal_header = self.tools_table.horizontalHeader()
  565. horizontal_header.setMinimumSectionSize(10)
  566. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  567. horizontal_header.resizeSection(0, 20)
  568. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  569. # self.tools_table.setSortingEnabled(True)
  570. # sort by tool diameter
  571. # self.tools_table.sortItems(1)
  572. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  573. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  574. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  575. self.tools_table.itemChanged.connect(self.on_tool_edit)
  576. def on_combo_box_type(self):
  577. obj_type = self.box_combo_type.currentIndex()
  578. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  579. self.box_combo.setCurrentIndex(0)
  580. def on_tool_add(self, dia=None, muted=None):
  581. try:
  582. self.tools_table.itemChanged.disconnect()
  583. except Exception as e:
  584. log.debug("ToolPaint.on_tool_add() --> %s" % str(e))
  585. if dia:
  586. tool_dia = dia
  587. else:
  588. try:
  589. tool_dia = float(self.addtool_entry.get_value())
  590. except ValueError:
  591. # try to convert comma to decimal point. if it's still not working error message and return
  592. try:
  593. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  594. except ValueError:
  595. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  596. "use a number."))
  597. return
  598. if tool_dia is None:
  599. self.build_ui()
  600. self.app.inform.emit(_("[WARNING_NOTCL] Please enter a tool diameter to add, in Float format."))
  601. return
  602. # construct a list of all 'tooluid' in the self.tools
  603. tool_uid_list = []
  604. for tooluid_key in self.paint_tools:
  605. tool_uid_item = int(tooluid_key)
  606. tool_uid_list.append(tool_uid_item)
  607. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  608. if not tool_uid_list:
  609. max_uid = 0
  610. else:
  611. max_uid = max(tool_uid_list)
  612. self.tooluid = int(max_uid + 1)
  613. tool_dias = []
  614. for k, v in self.paint_tools.items():
  615. for tool_v in v.keys():
  616. if tool_v == 'tooldia':
  617. tool_dias.append(float('%.4f' % v[tool_v]))
  618. if float('%.4f' % tool_dia) in tool_dias:
  619. if muted is None:
  620. self.app.inform.emit(_("[WARNING_NOTCL] Adding tool cancelled. Tool already in Tool Table."))
  621. self.tools_table.itemChanged.connect(self.on_tool_edit)
  622. return
  623. else:
  624. if muted is None:
  625. self.app.inform.emit(_("[success] New tool added to Tool Table."))
  626. self.paint_tools.update({
  627. int(self.tooluid): {
  628. 'tooldia': float('%.4f' % tool_dia),
  629. 'offset': 'Path',
  630. 'offset_value': 0.0,
  631. 'type': 'Iso',
  632. 'tool_type': 'V',
  633. 'data': dict(self.default_data),
  634. 'solid_geometry': []
  635. }
  636. })
  637. self.build_ui()
  638. def on_tool_edit(self):
  639. old_tool_dia = ''
  640. try:
  641. self.tools_table.itemChanged.disconnect()
  642. except Exception as e:
  643. log.debug("ToolPaint.on_tool_edit() --> %s" % str(e))
  644. tool_dias = []
  645. for k, v in self.paint_tools.items():
  646. for tool_v in v.keys():
  647. if tool_v == 'tooldia':
  648. tool_dias.append(float('%.4f' % v[tool_v]))
  649. for row in range(self.tools_table.rowCount()):
  650. try:
  651. new_tool_dia = float(self.tools_table.item(row, 1).text())
  652. except ValueError:
  653. # try to convert comma to decimal point. if it's still not working error message and return
  654. try:
  655. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  656. except ValueError:
  657. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  658. "use a number."))
  659. return
  660. tooluid = int(self.tools_table.item(row, 3).text())
  661. # identify the tool that was edited and get it's tooluid
  662. if new_tool_dia not in tool_dias:
  663. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  664. self.app.inform.emit(_("[success] Tool from Tool Table was edited."))
  665. self.build_ui()
  666. return
  667. else:
  668. # identify the old tool_dia and restore the text in tool table
  669. for k, v in self.paint_tools.items():
  670. if k == tooluid:
  671. old_tool_dia = v['tooldia']
  672. break
  673. restore_dia_item = self.tools_table.item(row, 1)
  674. restore_dia_item.setText(str(old_tool_dia))
  675. self.app.inform.emit(_("[WARNING_NOTCL] Edit cancelled. "
  676. "New diameter value is already in the Tool Table."))
  677. self.build_ui()
  678. # def on_tool_copy(self, all=None):
  679. # try:
  680. # self.tools_table.itemChanged.disconnect()
  681. # except:
  682. # pass
  683. #
  684. # # find the tool_uid maximum value in the self.tools
  685. # uid_list = []
  686. # for key in self.paint_tools:
  687. # uid_list.append(int(key))
  688. # try:
  689. # max_uid = max(uid_list, key=int)
  690. # except ValueError:
  691. # max_uid = 0
  692. #
  693. # if all is None:
  694. # if self.tools_table.selectedItems():
  695. # for current_row in self.tools_table.selectedItems():
  696. # # sometime the header get selected and it has row number -1
  697. # # we don't want to do anything with the header :)
  698. # if current_row.row() < 0:
  699. # continue
  700. # try:
  701. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  702. # max_uid += 1
  703. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  704. # for td in self.paint_tools:
  705. # print("COPIED", self.paint_tools[td])
  706. # self.build_ui()
  707. # except AttributeError:
  708. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  709. # self.build_ui()
  710. # return
  711. # except Exception as e:
  712. # log.debug("on_tool_copy() --> " + str(e))
  713. # # deselect the table
  714. # # self.ui.geo_tools_table.clearSelection()
  715. # else:
  716. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  717. # self.build_ui()
  718. # return
  719. # else:
  720. # # we copy all tools in geo_tools_table
  721. # try:
  722. # temp_tools = dict(self.paint_tools)
  723. # max_uid += 1
  724. # for tooluid in temp_tools:
  725. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  726. # temp_tools.clear()
  727. # self.build_ui()
  728. # except Exception as e:
  729. # log.debug("on_tool_copy() --> " + str(e))
  730. #
  731. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  732. def on_tool_delete(self, rows_to_delete=None, all=None):
  733. try:
  734. self.tools_table.itemChanged.disconnect()
  735. except Exception as e:
  736. log.debug("ToolPaint.on_tool_delete() --> %s" % str(e))
  737. pass
  738. deleted_tools_list = []
  739. if all:
  740. self.paint_tools.clear()
  741. self.build_ui()
  742. return
  743. if rows_to_delete:
  744. try:
  745. for row in rows_to_delete:
  746. tooluid_del = int(self.tools_table.item(row, 3).text())
  747. deleted_tools_list.append(tooluid_del)
  748. except TypeError:
  749. deleted_tools_list.append(rows_to_delete)
  750. for t in deleted_tools_list:
  751. self.paint_tools.pop(t, None)
  752. self.build_ui()
  753. return
  754. try:
  755. if self.tools_table.selectedItems():
  756. for row_sel in self.tools_table.selectedItems():
  757. row = row_sel.row()
  758. if row < 0:
  759. continue
  760. tooluid_del = int(self.tools_table.item(row, 3).text())
  761. deleted_tools_list.append(tooluid_del)
  762. for t in deleted_tools_list:
  763. self.paint_tools.pop(t, None)
  764. except AttributeError:
  765. self.app.inform.emit(_("[WARNING_NOTCL] Delete failed. Select a tool to delete."))
  766. return
  767. except Exception as e:
  768. log.debug(str(e))
  769. self.app.inform.emit(_("[success] Tool(s) deleted from Tool Table."))
  770. self.build_ui()
  771. def on_paint_button_click(self):
  772. # init values for the next usage
  773. self.reset_usage()
  774. self.app.report_usage(_("geometry_on_paint_button"))
  775. # self.app.call_source = 'paint'
  776. try:
  777. overlap = float(self.paintoverlap_entry.get_value())
  778. except ValueError:
  779. # try to convert comma to decimal point. if it's still not working error message and return
  780. try:
  781. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  782. except ValueError:
  783. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  784. "use a number."))
  785. return
  786. if overlap >= 1 or overlap < 0:
  787. self.app.inform.emit(_("[ERROR_NOTCL] Overlap value must be between "
  788. "0 (inclusive) and 1 (exclusive), "))
  789. return
  790. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  791. connect = self.pathconnect_cb.get_value()
  792. contour = self.paintcontour_cb.get_value()
  793. select_method = self.selectmethod_combo.get_value()
  794. self.obj_name = self.obj_combo.currentText()
  795. # Get source object.
  796. try:
  797. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  798. except Exception as e:
  799. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  800. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  801. return
  802. if self.paint_obj is None:
  803. self.app.inform.emit(_("[ERROR_NOTCL] Object not found: %s") % self.paint_obj)
  804. return
  805. # test if the Geometry Object is multigeo and return Fail if True because
  806. # for now Paint don't work on MultiGeo
  807. if self.paint_obj.multigeo is True:
  808. self.app.inform.emit(_("[ERROR_NOTCL] Can't do Paint on MultiGeo geometries ..."))
  809. return 'Fail'
  810. o_name = '%s_multitool_paint' % self.obj_name
  811. if select_method == "all":
  812. self.paint_poly_all(self.paint_obj,
  813. outname=o_name,
  814. overlap=overlap,
  815. connect=connect,
  816. contour=contour)
  817. elif select_method == "single":
  818. self.app.inform.emit(_("[WARNING_NOTCL] Click inside the desired polygon."))
  819. # use the first tool in the tool table; get the diameter
  820. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  821. # To be called after clicking on the plot.
  822. def doit(event):
  823. # do paint single only for left mouse clicks
  824. if event.button == 1:
  825. self.app.inform.emit(_("Painting polygon..."))
  826. self.app.plotcanvas.vis_disconnect('mouse_press', doit)
  827. pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  828. if self.app.grid_status() == True:
  829. pos = self.app.geo_editor.snap(pos[0], pos[1])
  830. self.paint_poly(self.paint_obj,
  831. inside_pt=[pos[0], pos[1]],
  832. tooldia=tooldia,
  833. overlap=overlap,
  834. connect=connect,
  835. contour=contour)
  836. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  837. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  838. self.app.plotcanvas.vis_connect('mouse_press', doit)
  839. elif select_method == "area":
  840. self.app.inform.emit(_("[WARNING_NOTCL] Click the start point of the paint area."))
  841. # use the first tool in the tool table; get the diameter
  842. tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  843. # To be called after clicking on the plot.
  844. def on_mouse_release(event):
  845. # do paint single only for left mouse clicks
  846. if event.button == 1:
  847. if not self.first_click:
  848. self.first_click = True
  849. self.app.inform.emit(_("[WARNING_NOTCL] Click the end point of the paint area."))
  850. self.cursor_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  851. if self.app.grid_status() == True:
  852. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  853. else:
  854. self.app.inform.emit(_("Zone added. Right click to finish."))
  855. self.app.delete_selection_shape()
  856. curr_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  857. if self.app.grid_status() == True:
  858. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  859. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  860. x1, y1 = curr_pos[0], curr_pos[1]
  861. pt1 = (x0, y0)
  862. pt2 = (x1, y0)
  863. pt3 = (x1, y1)
  864. pt4 = (x0, y1)
  865. self.sel_rect.append(Polygon([pt1, pt2, pt3, pt4]))
  866. modifiers = QtWidgets.QApplication.keyboardModifiers()
  867. if modifiers == QtCore.Qt.ShiftModifier:
  868. mod_key = 'Shift'
  869. elif modifiers == QtCore.Qt.ControlModifier:
  870. mod_key = 'Control'
  871. else:
  872. mod_key = None
  873. if mod_key == self.app.defaults["global_mselect_key"]:
  874. self.first_click = False
  875. return
  876. self.sel_rect = cascaded_union(self.sel_rect)
  877. self.paint_poly_area(obj=self.paint_obj,
  878. sel_obj= self.sel_rect,
  879. outname=o_name,
  880. overlap=overlap,
  881. connect=connect,
  882. contour=contour)
  883. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  884. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  885. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  886. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  887. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  888. elif event.button == 2 and self.first_click is False and self.mouse_is_dragging is False:
  889. self.first_click = False
  890. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  891. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  892. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  893. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  894. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  895. self.sel_rect = cascaded_union(self.sel_rect)
  896. self.paint_poly_area(obj=self.paint_obj,
  897. sel_obj=self.sel_rect,
  898. outname=o_name,
  899. overlap=overlap,
  900. connect=connect,
  901. contour=contour)
  902. # called on mouse move
  903. def on_mouse_move(event):
  904. curr_pos = self.app.plotcanvas.vispy_canvas.translate_coords(event.pos)
  905. self.app.app_cursor.enabled = False
  906. if event.button == 2:
  907. if event.is_dragging is True:
  908. self.mouse_is_dragging = True
  909. else:
  910. self.mouse_is_dragging = False
  911. if self.app.grid_status() == True:
  912. self.app.app_cursor.enabled = True
  913. # Update cursor
  914. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  915. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  916. symbol='++', edge_color='black', size=20)
  917. if self.first_click:
  918. self.app.delete_selection_shape()
  919. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  920. coords=(curr_pos[0], curr_pos[1]),
  921. face_alpha=0.0)
  922. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  923. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  924. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  925. self.app.plotcanvas.vis_connect('mouse_release', on_mouse_release)
  926. self.app.plotcanvas.vis_connect('mouse_move', on_mouse_move)
  927. elif select_method == 'ref':
  928. self.bound_obj_name = self.box_combo.currentText()
  929. # Get source object.
  930. try:
  931. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  932. except Exception as e:
  933. self.app.inform.emit(_("[ERROR_NOTCL] Could not retrieve object: %s") % self.obj_name)
  934. return "Could not retrieve object: %s" % self.obj_name
  935. geo = self.bound_obj.solid_geometry
  936. try:
  937. if isinstance(geo, MultiPolygon):
  938. env_obj = geo.convex_hull
  939. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  940. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  941. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  942. else:
  943. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  944. env_obj = env_obj.convex_hull
  945. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  946. except Exception as e:
  947. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  948. self.app.inform.emit(_("[ERROR_NOTCL] No object available."))
  949. return
  950. self.paint_poly_area(obj=self.paint_obj,
  951. sel_obj=sel_rect,
  952. outname=o_name,
  953. overlap=overlap,
  954. connect=connect,
  955. contour=contour)
  956. def paint_poly(self, obj, inside_pt, tooldia, overlap, outname=None, connect=True, contour=True):
  957. """
  958. Paints a polygon selected by clicking on its interior.
  959. Note:
  960. * The margin is taken directly from the form.
  961. :param obj: painted object
  962. :param inside_pt: [x, y]
  963. :param tooldia: Diameter of the painting tool
  964. :param overlap: Overlap of the tool between passes.
  965. :param outname: Name of the resulting Geometry Object.
  966. :param connect: Connect lines to avoid tool lifts.
  967. :param contour: Paint around the edges.
  968. :return: None
  969. """
  970. # Which polygon.
  971. # poly = find_polygon(self.solid_geometry, inside_pt)
  972. poly = self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)
  973. paint_method = self.paintmethod_combo.get_value()
  974. try:
  975. paint_margin = float(self.paintmargin_entry.get_value())
  976. except ValueError:
  977. # try to convert comma to decimal point. if it's still not working error message and return
  978. try:
  979. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  980. except ValueError:
  981. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  982. "use a number."))
  983. return
  984. # No polygon?
  985. if poly is None:
  986. self.app.log.warning('No polygon found.')
  987. self.app.inform.emit(_('[WARNING] No polygon found.'))
  988. return
  989. proc = self.app.proc_container.new(_("Painting polygon."))
  990. name = outname if outname else self.obj_name + "_paint"
  991. # Initializes the new geometry object
  992. def gen_paintarea(geo_obj, app_obj):
  993. assert isinstance(geo_obj, FlatCAMGeometry), \
  994. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  995. # assert isinstance(app_obj, App)
  996. def paint_p(polyg):
  997. if paint_method == "seed":
  998. # Type(cp) == FlatCAMRTreeStorage | None
  999. cpoly = self.clear_polygon2(polyg,
  1000. tooldia=tooldia,
  1001. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1002. overlap=overlap,
  1003. contour=contour,
  1004. connect=connect)
  1005. elif paint_method == "lines":
  1006. # Type(cp) == FlatCAMRTreeStorage | None
  1007. cpoly = self.clear_polygon3(polyg,
  1008. tooldia=tooldia,
  1009. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1010. overlap=overlap,
  1011. contour=contour,
  1012. connect=connect)
  1013. else:
  1014. # Type(cp) == FlatCAMRTreeStorage | None
  1015. cpoly = self.clear_polygon(polyg,
  1016. tooldia=tooldia,
  1017. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1018. overlap=overlap,
  1019. contour=contour,
  1020. connect=connect)
  1021. if cpoly is not None:
  1022. geo_obj.solid_geometry += list(cpoly.get_objects())
  1023. return cpoly
  1024. else:
  1025. self.app.inform.emit(_('[ERROR_NOTCL] Geometry could not be painted completely'))
  1026. return None
  1027. geo_obj.solid_geometry = []
  1028. try:
  1029. a, b, c, d = poly.bounds
  1030. geo_obj.options['xmin'] = a
  1031. geo_obj.options['ymin'] = b
  1032. geo_obj.options['xmax'] = c
  1033. geo_obj.options['ymax'] = d
  1034. except Exception as e:
  1035. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1036. return
  1037. try:
  1038. poly_buf = poly.buffer(-paint_margin)
  1039. if isinstance(poly_buf, MultiPolygon):
  1040. cp = []
  1041. for pp in poly_buf:
  1042. cp.append(paint_p(pp))
  1043. else:
  1044. cp = paint_p(poly_buf)
  1045. except Exception as e:
  1046. log.debug("Could not Paint the polygons. %s" % str(e))
  1047. self.app.inform.emit(
  1048. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  1049. "Or a different strategy of paint\n%s") % str(e))
  1050. return
  1051. if cp is not None:
  1052. if isinstance(cp, list):
  1053. for x in cp:
  1054. geo_obj.solid_geometry += list(x.get_objects())
  1055. else:
  1056. geo_obj.solid_geometry = list(cp.get_objects())
  1057. geo_obj.options["cnctooldia"] = str(tooldia)
  1058. # this turn on the FlatCAMCNCJob plot for multiple tools
  1059. geo_obj.multigeo = False
  1060. geo_obj.multitool = True
  1061. current_uid = int(self.tools_table.item(0, 3).text())
  1062. for k, v in self.paint_tools.items():
  1063. if k == current_uid:
  1064. v['data']['name'] = name
  1065. geo_obj.tools = dict(self.paint_tools)
  1066. # Experimental...
  1067. # print("Indexing...", end=' ')
  1068. # geo_obj.make_index()
  1069. # if errors == 0:
  1070. # print("[success] Paint single polygon Done")
  1071. # self.app.inform.emit("[success] Paint single polygon Done")
  1072. # else:
  1073. # print("[WARNING] Paint single polygon done with errors")
  1074. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  1075. # "%d area(s) could not be painted.\n"
  1076. # "Use different paint parameters or edit the paint geometry and correct"
  1077. # "the issue."
  1078. # % errors)
  1079. def job_thread(app_obj):
  1080. try:
  1081. app_obj.new_object("geometry", name, gen_paintarea)
  1082. except Exception as e:
  1083. proc.done()
  1084. self.app.inform.emit(_('[ERROR_NOTCL] PaintTool.paint_poly() --> %s') % str(e))
  1085. return
  1086. proc.done()
  1087. # focus on Selected Tab
  1088. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1089. self.app.inform.emit(_("Polygon Paint started ..."))
  1090. # Promise object with the new name
  1091. self.app.collection.promise(name)
  1092. # Background
  1093. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1094. def paint_poly_all(self, obj, overlap, outname=None, connect=True, contour=True):
  1095. """
  1096. Paints all polygons in this object.
  1097. :param obj: painted object
  1098. :param overlap:
  1099. :param outname:
  1100. :param connect: Connect lines to avoid tool lifts.
  1101. :param contour: Paint around the edges.
  1102. :return:
  1103. """
  1104. paint_method = self.paintmethod_combo.get_value()
  1105. try:
  1106. paint_margin = float(self.paintmargin_entry.get_value())
  1107. except ValueError:
  1108. # try to convert comma to decimal point. if it's still not working error message and return
  1109. try:
  1110. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1111. except ValueError:
  1112. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1113. "use a number."))
  1114. return
  1115. proc = self.app.proc_container.new(_("Painting polygon..."))
  1116. name = outname if outname else self.obj_name + "_paint"
  1117. over = overlap
  1118. conn = connect
  1119. cont = contour
  1120. # This is a recursive generator of individual Polygons.
  1121. # Note: Double check correct implementation. Might exit
  1122. # early if it finds something that is not a Polygon?
  1123. # def recurse(geo):
  1124. # try:
  1125. # for subg in geo:
  1126. # for subsubg in recurse(subg):
  1127. # yield subsubg
  1128. # except TypeError:
  1129. # if isinstance(geo, Polygon):
  1130. # yield geo
  1131. #
  1132. # raise StopIteration
  1133. def recurse(geometry, reset=True):
  1134. """
  1135. Creates a list of non-iterable linear geometry objects.
  1136. Results are placed in self.flat_geometry
  1137. :param geometry: Shapely type or list or list of list of such.
  1138. :param reset: Clears the contents of self.flat_geometry.
  1139. """
  1140. if geometry is None:
  1141. return
  1142. if reset:
  1143. self.flat_geometry = []
  1144. # ## If iterable, expand recursively.
  1145. try:
  1146. for geo in geometry:
  1147. if geo is not None:
  1148. recurse(geometry=geo, reset=False)
  1149. # ## Not iterable, do the actual indexing and add.
  1150. except TypeError:
  1151. if isinstance(geometry, LinearRing):
  1152. g = Polygon(geometry)
  1153. self.flat_geometry.append(g)
  1154. else:
  1155. self.flat_geometry.append(geometry)
  1156. return self.flat_geometry
  1157. # Initializes the new geometry object
  1158. def gen_paintarea(geo_obj, app_obj):
  1159. assert isinstance(geo_obj, FlatCAMGeometry), \
  1160. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1161. tool_dia = None
  1162. sorted_tools = []
  1163. for row in range(self.tools_table.rowCount()):
  1164. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1165. order = self.order_radio.get_value()
  1166. if order == 'fwd':
  1167. sorted_tools.sort(reverse=False)
  1168. elif order == 'rev':
  1169. sorted_tools.sort(reverse=True)
  1170. else:
  1171. pass
  1172. try:
  1173. a, b, c, d = obj.bounds()
  1174. geo_obj.options['xmin'] = a
  1175. geo_obj.options['ymin'] = b
  1176. geo_obj.options['xmax'] = c
  1177. geo_obj.options['ymax'] = d
  1178. except Exception as e:
  1179. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1180. return
  1181. total_geometry = []
  1182. current_uid = int(1)
  1183. geo_obj.solid_geometry = []
  1184. for tool_dia in sorted_tools:
  1185. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1186. for k, v in self.paint_tools.items():
  1187. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1188. current_uid = int(k)
  1189. break
  1190. for geo in recurse(obj.solid_geometry):
  1191. try:
  1192. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1193. if not isinstance(geo, Polygon):
  1194. continue
  1195. poly_buf = geo.buffer(-paint_margin)
  1196. if paint_method == "seed":
  1197. # Type(cp) == FlatCAMRTreeStorage | None
  1198. cp = self.clear_polygon2(poly_buf,
  1199. tooldia=tool_dia,
  1200. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1201. overlap=over,
  1202. contour=cont,
  1203. connect=conn)
  1204. elif paint_method == "lines":
  1205. # Type(cp) == FlatCAMRTreeStorage | None
  1206. cp = self.clear_polygon3(poly_buf,
  1207. tooldia=tool_dia,
  1208. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1209. overlap=over,
  1210. contour=cont,
  1211. connect=conn)
  1212. else:
  1213. # Type(cp) == FlatCAMRTreeStorage | None
  1214. cp = self.clear_polygon(poly_buf,
  1215. tooldia=tool_dia,
  1216. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1217. overlap=over,
  1218. contour=cont,
  1219. connect=conn)
  1220. if cp is not None:
  1221. total_geometry += list(cp.get_objects())
  1222. except Exception as e:
  1223. log.debug("Could not Paint the polygons. %s" % str(e))
  1224. self.app.inform.emit(
  1225. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1226. "Or a different Method of paint\n%s") % str(e))
  1227. return
  1228. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1229. # temporary list that stored that solid_geometry
  1230. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1231. self.paint_tools[current_uid]['data']['name'] = name
  1232. total_geometry[:] = []
  1233. geo_obj.options["cnctooldia"] = str(tool_dia)
  1234. # this turn on the FlatCAMCNCJob plot for multiple tools
  1235. geo_obj.multigeo = True
  1236. geo_obj.multitool = True
  1237. geo_obj.tools.clear()
  1238. geo_obj.tools = dict(self.paint_tools)
  1239. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1240. has_solid_geo = 0
  1241. for tooluid in geo_obj.tools:
  1242. if geo_obj.tools[tooluid]['solid_geometry']:
  1243. has_solid_geo += 1
  1244. if has_solid_geo == 0:
  1245. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1246. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1247. "Change the painting parameters and try again."))
  1248. return
  1249. # Experimental...
  1250. # print("Indexing...", end=' ')
  1251. # geo_obj.make_index()
  1252. self.app.inform.emit(_("[success] Paint All Done."))
  1253. # Initializes the new geometry object
  1254. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1255. assert isinstance(geo_obj, FlatCAMGeometry), \
  1256. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1257. tool_dia = None
  1258. sorted_tools = []
  1259. for row in range(self.tools_table.rowCount()):
  1260. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1261. sorted_tools.sort(reverse=True)
  1262. cleared_geo = []
  1263. current_uid = int(1)
  1264. geo_obj.solid_geometry = []
  1265. try:
  1266. a, b, c, d = obj.bounds()
  1267. geo_obj.options['xmin'] = a
  1268. geo_obj.options['ymin'] = b
  1269. geo_obj.options['xmax'] = c
  1270. geo_obj.options['ymax'] = d
  1271. except Exception as e:
  1272. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1273. return
  1274. for tool_dia in sorted_tools:
  1275. for geo in recurse(obj.solid_geometry):
  1276. try:
  1277. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1278. poly_buf = geo.buffer(-paint_margin)
  1279. cp = None
  1280. if paint_method == "standard":
  1281. # Type(cp) == FlatCAMRTreeStorage | None
  1282. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1283. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1284. overlap=over, contour=cont, connect=conn)
  1285. elif paint_method == "seed":
  1286. # Type(cp) == FlatCAMRTreeStorage | None
  1287. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1288. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1289. overlap=over, contour=cont, connect=conn)
  1290. elif paint_method == "lines":
  1291. # Type(cp) == FlatCAMRTreeStorage | None
  1292. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1293. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1294. overlap=over, contour=cont, connect=conn)
  1295. if cp is not None:
  1296. cleared_geo += list(cp.get_objects())
  1297. except Exception as e:
  1298. log.debug("Could not Paint the polygons. %s" % str(e))
  1299. self.app.inform.emit(
  1300. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1301. "Or a different Method of paint\n%s") % str(e))
  1302. return
  1303. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1304. for k, v in self.paint_tools.items():
  1305. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1306. current_uid = int(k)
  1307. break
  1308. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1309. # temporary list that stored that solid_geometry
  1310. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1311. self.paint_tools[current_uid]['data']['name'] = name
  1312. cleared_geo[:] = []
  1313. geo_obj.options["cnctooldia"] = str(tool_dia)
  1314. # this turn on the FlatCAMCNCJob plot for multiple tools
  1315. geo_obj.multigeo = True
  1316. geo_obj.multitool = True
  1317. geo_obj.tools.clear()
  1318. geo_obj.tools = dict(self.paint_tools)
  1319. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1320. has_solid_geo = 0
  1321. for tooluid in geo_obj.tools:
  1322. if geo_obj.tools[tooluid]['solid_geometry']:
  1323. has_solid_geo += 1
  1324. if has_solid_geo == 0:
  1325. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1326. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1327. "Change the painting parameters and try again."))
  1328. return
  1329. # Experimental...
  1330. # print("Indexing...", end=' ')
  1331. # geo_obj.make_index()
  1332. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1333. def job_thread(app_obj):
  1334. try:
  1335. if self.rest_cb.isChecked():
  1336. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1337. else:
  1338. app_obj.new_object("geometry", name, gen_paintarea)
  1339. except Exception as e:
  1340. proc.done()
  1341. traceback.print_stack()
  1342. return
  1343. proc.done()
  1344. # focus on Selected Tab
  1345. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1346. self.app.inform.emit(_("Polygon Paint started ..."))
  1347. # Promise object with the new name
  1348. self.app.collection.promise(name)
  1349. # Background
  1350. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1351. def paint_poly_area(self, obj, sel_obj, overlap, outname=None, connect=True, contour=True):
  1352. """
  1353. Paints all polygons in this object that are within the sel_obj object
  1354. :param obj: painted object
  1355. :param sel_obj: paint only what is inside this object bounds
  1356. :param overlap:
  1357. :param outname:
  1358. :param connect: Connect lines to avoid tool lifts.
  1359. :param contour: Paint around the edges.
  1360. :return:
  1361. """
  1362. paint_method = self.paintmethod_combo.get_value()
  1363. try:
  1364. paint_margin = float(self.paintmargin_entry.get_value())
  1365. except ValueError:
  1366. # try to convert comma to decimal point. if it's still not working error message and return
  1367. try:
  1368. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1369. except ValueError:
  1370. self.app.inform.emit(_("[ERROR_NOTCL] Wrong value format entered, "
  1371. "use a number."))
  1372. return
  1373. proc = self.app.proc_container.new(_("Painting polygon..."))
  1374. name = outname if outname else self.obj_name + "_paint"
  1375. over = overlap
  1376. conn = connect
  1377. cont = contour
  1378. def recurse(geometry, reset=True):
  1379. """
  1380. Creates a list of non-iterable linear geometry objects.
  1381. Results are placed in self.flat_geometry
  1382. :param geometry: Shapely type or list or list of list of such.
  1383. :param reset: Clears the contents of self.flat_geometry.
  1384. """
  1385. if geometry is None:
  1386. return
  1387. if reset:
  1388. self.flat_geometry = []
  1389. # ## If iterable, expand recursively.
  1390. try:
  1391. for geo in geometry:
  1392. if geo is not None:
  1393. recurse(geometry=geo, reset=False)
  1394. # ## Not iterable, do the actual indexing and add.
  1395. except TypeError:
  1396. if isinstance(geometry, LinearRing):
  1397. g = Polygon(geometry)
  1398. self.flat_geometry.append(g)
  1399. else:
  1400. self.flat_geometry.append(geometry)
  1401. return self.flat_geometry
  1402. # Initializes the new geometry object
  1403. def gen_paintarea(geo_obj, app_obj):
  1404. assert isinstance(geo_obj, FlatCAMGeometry), \
  1405. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1406. tool_dia = None
  1407. sorted_tools = []
  1408. for row in range(self.tools_table.rowCount()):
  1409. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1410. order = self.order_radio.get_value()
  1411. if order == 'fwd':
  1412. sorted_tools.sort(reverse=False)
  1413. elif order == 'rev':
  1414. sorted_tools.sort(reverse=True)
  1415. else:
  1416. pass
  1417. geo_to_paint = []
  1418. if not isinstance(obj.solid_geometry, list):
  1419. target_geo = [obj.solid_geometry]
  1420. else:
  1421. target_geo = obj.solid_geometry
  1422. for poly in target_geo:
  1423. new_pol = poly.intersection(sel_obj)
  1424. geo_to_paint.append(new_pol)
  1425. try:
  1426. a, b, c, d = self.paint_bounds(geo_to_paint)
  1427. geo_obj.options['xmin'] = a
  1428. geo_obj.options['ymin'] = b
  1429. geo_obj.options['xmax'] = c
  1430. geo_obj.options['ymax'] = d
  1431. except Exception as e:
  1432. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1433. return
  1434. total_geometry = []
  1435. current_uid = int(1)
  1436. geo_obj.solid_geometry = []
  1437. for tool_dia in sorted_tools:
  1438. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1439. for k, v in self.paint_tools.items():
  1440. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1441. current_uid = int(k)
  1442. break
  1443. for geo in recurse(geo_to_paint):
  1444. try:
  1445. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1446. if not isinstance(geo, Polygon):
  1447. continue
  1448. poly_buf = geo.buffer(-paint_margin)
  1449. if paint_method == "seed":
  1450. # Type(cp) == FlatCAMRTreeStorage | None
  1451. cp = self.clear_polygon2(poly_buf,
  1452. tooldia=tool_dia,
  1453. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1454. overlap=over,
  1455. contour=cont,
  1456. connect=conn)
  1457. elif paint_method == "lines":
  1458. # Type(cp) == FlatCAMRTreeStorage | None
  1459. cp = self.clear_polygon3(poly_buf,
  1460. tooldia=tool_dia,
  1461. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1462. overlap=over,
  1463. contour=cont,
  1464. connect=conn)
  1465. else:
  1466. # Type(cp) == FlatCAMRTreeStorage | None
  1467. cp = self.clear_polygon(poly_buf,
  1468. tooldia=tool_dia,
  1469. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1470. overlap=over,
  1471. contour=cont,
  1472. connect=conn)
  1473. if cp is not None:
  1474. total_geometry += list(cp.get_objects())
  1475. except Exception as e:
  1476. log.debug("Could not Paint the polygons. %s" % str(e))
  1477. self.app.inform.emit(
  1478. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1479. "Or a different Method of paint\n%s") % str(e))
  1480. return
  1481. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1482. # temporary list that stored that solid_geometry
  1483. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1484. self.paint_tools[current_uid]['data']['name'] = name
  1485. total_geometry[:] = []
  1486. geo_obj.options["cnctooldia"] = str(tool_dia)
  1487. # this turn on the FlatCAMCNCJob plot for multiple tools
  1488. geo_obj.multigeo = True
  1489. geo_obj.multitool = True
  1490. geo_obj.tools.clear()
  1491. geo_obj.tools = dict(self.paint_tools)
  1492. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1493. has_solid_geo = 0
  1494. for tooluid in geo_obj.tools:
  1495. if geo_obj.tools[tooluid]['solid_geometry']:
  1496. has_solid_geo += 1
  1497. if has_solid_geo == 0:
  1498. self.app.inform.emit(_("[ERROR] There is no Painting Geometry in the file.\n"
  1499. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1500. "Change the painting parameters and try again."))
  1501. return
  1502. # Experimental...
  1503. # print("Indexing...", end=' ')
  1504. # geo_obj.make_index()
  1505. self.app.inform.emit(_("[success] Paint All Done."))
  1506. # Initializes the new geometry object
  1507. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1508. assert isinstance(geo_obj, FlatCAMGeometry), \
  1509. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1510. tool_dia = None
  1511. sorted_tools = []
  1512. for row in range(self.tools_table.rowCount()):
  1513. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1514. sorted_tools.sort(reverse=True)
  1515. cleared_geo = []
  1516. current_uid = int(1)
  1517. geo_obj.solid_geometry = []
  1518. try:
  1519. a, b, c, d = obj.bounds()
  1520. geo_obj.options['xmin'] = a
  1521. geo_obj.options['ymin'] = b
  1522. geo_obj.options['xmax'] = c
  1523. geo_obj.options['ymax'] = d
  1524. except Exception as e:
  1525. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1526. return
  1527. for tool_dia in sorted_tools:
  1528. for geo in recurse(obj.solid_geometry):
  1529. try:
  1530. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1531. poly_buf = geo.buffer(-paint_margin)
  1532. cp = None
  1533. if paint_method == "standard":
  1534. # Type(cp) == FlatCAMRTreeStorage | None
  1535. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1536. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1537. overlap=over, contour=cont, connect=conn)
  1538. elif paint_method == "seed":
  1539. # Type(cp) == FlatCAMRTreeStorage | None
  1540. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1541. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1542. overlap=over, contour=cont, connect=conn)
  1543. elif paint_method == "lines":
  1544. # Type(cp) == FlatCAMRTreeStorage | None
  1545. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1546. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1547. overlap=over, contour=cont, connect=conn)
  1548. if cp is not None:
  1549. cleared_geo += list(cp.get_objects())
  1550. except Exception as e:
  1551. log.debug("Could not Paint the polygons. %s" % str(e))
  1552. self.app.inform.emit(
  1553. _("[ERROR] Could not do Paint All. Try a different combination of parameters. "
  1554. "Or a different Method of paint\n%s") % str(e))
  1555. return
  1556. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1557. for k, v in self.paint_tools.items():
  1558. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1559. current_uid = int(k)
  1560. break
  1561. # add the solid_geometry to the current too in self.paint_tools dictionary and then reset the
  1562. # temporary list that stored that solid_geometry
  1563. self.paint_tools[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1564. self.paint_tools[current_uid]['data']['name'] = name
  1565. cleared_geo[:] = []
  1566. geo_obj.options["cnctooldia"] = str(tool_dia)
  1567. # this turn on the FlatCAMCNCJob plot for multiple tools
  1568. geo_obj.multigeo = True
  1569. geo_obj.multitool = True
  1570. geo_obj.tools.clear()
  1571. geo_obj.tools = dict(self.paint_tools)
  1572. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1573. has_solid_geo = 0
  1574. for tooluid in geo_obj.tools:
  1575. if geo_obj.tools[tooluid]['solid_geometry']:
  1576. has_solid_geo += 1
  1577. if has_solid_geo == 0:
  1578. self.app.inform.emit(_("[ERROR_NOTCL] There is no Painting Geometry in the file.\n"
  1579. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1580. "Change the painting parameters and try again."))
  1581. return
  1582. # Experimental...
  1583. # print("Indexing...", end=' ')
  1584. # geo_obj.make_index()
  1585. self.app.inform.emit(_("[success] Paint All with Rest-Machining done."))
  1586. def job_thread(app_obj):
  1587. try:
  1588. if self.rest_cb.isChecked():
  1589. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1590. else:
  1591. app_obj.new_object("geometry", name, gen_paintarea)
  1592. except Exception as e:
  1593. proc.done()
  1594. traceback.print_stack()
  1595. return
  1596. proc.done()
  1597. # focus on Selected Tab
  1598. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1599. self.app.inform.emit(_("Polygon Paint started ..."))
  1600. # Promise object with the new name
  1601. self.app.collection.promise(name)
  1602. # Background
  1603. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1604. @staticmethod
  1605. def paint_bounds(geometry):
  1606. def bounds_rec(o):
  1607. if type(o) is list:
  1608. minx = Inf
  1609. miny = Inf
  1610. maxx = -Inf
  1611. maxy = -Inf
  1612. for k in o:
  1613. try:
  1614. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1615. except Exception as e:
  1616. log.debug("ToolPaint.bounds() --> %s" % str(e))
  1617. return
  1618. minx = min(minx, minx_)
  1619. miny = min(miny, miny_)
  1620. maxx = max(maxx, maxx_)
  1621. maxy = max(maxy, maxy_)
  1622. return minx, miny, maxx, maxy
  1623. else:
  1624. # it's a Shapely object, return it's bounds
  1625. return o.bounds
  1626. return bounds_rec(geometry)
  1627. def reset_fields(self):
  1628. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))