ToolPaint.py 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342
  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 painting:\n"
  198. "- Standard: Fixed step inwards.\n"
  199. "- Seed-based: Outwards from seed.\n"
  200. "- Line-based: 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 Polygons to be painted.\n\n"
  243. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  244. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  245. "- 'All Polygons' - the Paint will start after click.\n"
  246. "- 'Reference Object' - will do non copper clearing within the area\n"
  247. "specified by another 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 Polygons to be painted.\n\n"
  259. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  260. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  261. "- 'All Polygons' - the Paint will start after click.\n"
  262. "- 'Reference Object' - will do non copper clearing within the area\n"
  263. "specified by another 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. _("- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  295. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  296. "- 'All Polygons' - the Paint will start after click.\n"
  297. "- 'Reference Object' - will do non copper clearing within the area\n"
  298. "specified by another object.")
  299. )
  300. self.tools_box.addWidget(self.generate_paint_button)
  301. self.tools_box.addStretch()
  302. self.obj_name = ""
  303. self.paint_obj = None
  304. self.units = ''
  305. self.paint_tools = {}
  306. self.tooluid = 0
  307. self.first_click = False
  308. self.cursor_pos = None
  309. self.mouse_is_dragging = False
  310. self.sel_rect = []
  311. # store here the default data for Geometry Data
  312. self.default_data = {}
  313. self.default_data.update({
  314. "name": '_paint',
  315. "plot": self.app.defaults["geometry_plot"],
  316. "cutz": self.app.defaults["geometry_cutz"],
  317. "vtipdia": 0.1,
  318. "vtipangle": 30,
  319. "travelz": self.app.defaults["geometry_travelz"],
  320. "feedrate": self.app.defaults["geometry_feedrate"],
  321. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  322. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  323. "dwell": self.app.defaults["geometry_dwell"],
  324. "dwelltime": self.app.defaults["geometry_dwelltime"],
  325. "multidepth": self.app.defaults["geometry_multidepth"],
  326. "ppname_g": self.app.defaults["geometry_ppname_g"],
  327. "depthperpass": self.app.defaults["geometry_depthperpass"],
  328. "extracut": self.app.defaults["geometry_extracut"],
  329. "toolchange": self.app.defaults["geometry_toolchange"],
  330. "toolchangez": self.app.defaults["geometry_toolchangez"],
  331. "endz": self.app.defaults["geometry_endz"],
  332. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  333. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  334. "startz": self.app.defaults["geometry_startz"],
  335. "tooldia": self.app.defaults["tools_painttooldia"],
  336. "paintmargin": self.app.defaults["tools_paintmargin"],
  337. "paintmethod": self.app.defaults["tools_paintmethod"],
  338. "selectmethod": self.app.defaults["tools_selectmethod"],
  339. "pathconnect": self.app.defaults["tools_pathconnect"],
  340. "paintcontour": self.app.defaults["tools_paintcontour"],
  341. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  342. })
  343. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  344. # ## Signals
  345. self.addtool_btn.clicked.connect(self.on_tool_add)
  346. self.addtool_entry.returnPressed.connect(self.on_tool_add)
  347. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  348. self.tools_table.itemChanged.connect(self.on_tool_edit)
  349. self.deltool_btn.clicked.connect(self.on_tool_delete)
  350. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  351. self.selectmethod_combo.activated_custom.connect(self.on_radio_selection)
  352. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  353. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  354. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  355. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  356. def on_type_obj_index_changed(self, index):
  357. obj_type = self.type_obj_combo.currentIndex()
  358. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  359. self.obj_combo.setCurrentIndex(0)
  360. def install(self, icon=None, separator=None, **kwargs):
  361. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  362. def run(self, toggle=True):
  363. self.app.report_usage("ToolPaint()")
  364. if toggle:
  365. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  366. if self.app.ui.splitter.sizes()[0] == 0:
  367. self.app.ui.splitter.setSizes([1, 1])
  368. else:
  369. try:
  370. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  371. # if tab is populated with the tool but it does not have the focus, focus on it
  372. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  373. # focus on Tool Tab
  374. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  375. else:
  376. self.app.ui.splitter.setSizes([0, 1])
  377. except AttributeError:
  378. pass
  379. else:
  380. if self.app.ui.splitter.sizes()[0] == 0:
  381. self.app.ui.splitter.setSizes([1, 1])
  382. FlatCAMTool.run(self)
  383. self.set_tool_ui()
  384. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  385. def reset_usage(self):
  386. self.obj_name = ""
  387. self.paint_obj = None
  388. self.bound_obj = None
  389. self.first_click = False
  390. self.cursor_pos = None
  391. self.mouse_is_dragging = False
  392. self.sel_rect = []
  393. def on_radio_selection(self):
  394. if self.selectmethod_combo.get_value() == "ref":
  395. self.box_combo.show()
  396. self.box_combo_label.show()
  397. self.box_combo_type.show()
  398. self.box_combo_type_label.show()
  399. else:
  400. self.box_combo.hide()
  401. self.box_combo_label.hide()
  402. self.box_combo_type.hide()
  403. self.box_combo_type_label.hide()
  404. if self.selectmethod_combo.get_value() == 'single':
  405. # disable rest-machining for single polygon painting
  406. self.rest_cb.set_value(False)
  407. self.rest_cb.setDisabled(True)
  408. # delete all tools except first row / tool for single polygon painting
  409. # list_to_del = list(range(1, self.tools_table.rowCount()))
  410. # if list_to_del:
  411. # self.on_tool_delete(rows_to_delete=list_to_del)
  412. # # disable addTool and delTool
  413. # self.addtool_entry.setDisabled(True)
  414. # self.addtool_btn.setDisabled(True)
  415. # self.deltool_btn.setDisabled(True)
  416. # self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  417. if self.selectmethod_combo.get_value() == 'area':
  418. # disable rest-machining for single polygon painting
  419. self.rest_cb.set_value(False)
  420. self.rest_cb.setDisabled(True)
  421. else:
  422. self.rest_cb.setDisabled(False)
  423. self.addtool_entry.setDisabled(False)
  424. self.addtool_btn.setDisabled(False)
  425. self.deltool_btn.setDisabled(False)
  426. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  427. def on_order_changed(self, order):
  428. if order != 'no':
  429. self.build_ui()
  430. def on_rest_machining_check(self, state):
  431. if state:
  432. self.order_radio.set_value('rev')
  433. self.order_label.setDisabled(True)
  434. self.order_radio.setDisabled(True)
  435. else:
  436. self.order_label.setDisabled(False)
  437. self.order_radio.setDisabled(False)
  438. def set_tool_ui(self):
  439. self.tools_frame.show()
  440. self.reset_fields()
  441. # ## Init the GUI interface
  442. self.order_radio.set_value(self.app.defaults["tools_paintorder"])
  443. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  444. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  445. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  446. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  447. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  448. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  449. # updated units
  450. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  451. if self.units == "IN":
  452. self.addtool_entry.set_value(0.039)
  453. else:
  454. self.addtool_entry.set_value(1)
  455. self.tools_table.setupContextMenu()
  456. self.tools_table.addContextMenu(
  457. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  458. self.tools_table.addContextMenu(
  459. "Delete", lambda:
  460. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  461. # set the working variables to a known state
  462. self.paint_tools.clear()
  463. self.tooluid = 0
  464. self.default_data.clear()
  465. self.default_data.update({
  466. "name": '_paint',
  467. "plot": self.app.defaults["geometry_plot"],
  468. "cutz": self.app.defaults["geometry_cutz"],
  469. "vtipdia": 0.1,
  470. "vtipangle": 30,
  471. "travelz": self.app.defaults["geometry_travelz"],
  472. "feedrate": self.app.defaults["geometry_feedrate"],
  473. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  474. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  475. "dwell": self.app.defaults["geometry_dwell"],
  476. "dwelltime": self.app.defaults["geometry_dwelltime"],
  477. "multidepth": self.app.defaults["geometry_multidepth"],
  478. "ppname_g": self.app.defaults["geometry_ppname_g"],
  479. "depthperpass": self.app.defaults["geometry_depthperpass"],
  480. "extracut": self.app.defaults["geometry_extracut"],
  481. "toolchange": self.app.defaults["geometry_toolchange"],
  482. "toolchangez": self.app.defaults["geometry_toolchangez"],
  483. "endz": self.app.defaults["geometry_endz"],
  484. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  485. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  486. "startz": self.app.defaults["geometry_startz"],
  487. "tooldia": self.app.defaults["tools_painttooldia"],
  488. "paintmargin": self.app.defaults["tools_paintmargin"],
  489. "paintmethod": self.app.defaults["tools_paintmethod"],
  490. "selectmethod": self.app.defaults["tools_selectmethod"],
  491. "pathconnect": self.app.defaults["tools_pathconnect"],
  492. "paintcontour": self.app.defaults["tools_paintcontour"],
  493. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  494. })
  495. # call on self.on_tool_add() counts as an call to self.build_ui()
  496. # through this, we add a initial row / tool in the tool_table
  497. self.on_tool_add(self.app.defaults["tools_painttooldia"], muted=True)
  498. # if the Paint Method is "Single" disable the tool table context menu
  499. if self.default_data["selectmethod"] == "single":
  500. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  501. def build_ui(self):
  502. try:
  503. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  504. self.tools_table.itemChanged.disconnect()
  505. except (TypeError, AttributeError):
  506. pass
  507. # updated units
  508. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  509. sorted_tools = []
  510. for k, v in self.paint_tools.items():
  511. sorted_tools.append(float('%.4f' % float(v['tooldia'])))
  512. order = self.order_radio.get_value()
  513. if order == 'fwd':
  514. sorted_tools.sort(reverse=False)
  515. elif order == 'rev':
  516. sorted_tools.sort(reverse=True)
  517. else:
  518. pass
  519. n = len(sorted_tools)
  520. self.tools_table.setRowCount(n)
  521. tool_id = 0
  522. for tool_sorted in sorted_tools:
  523. for tooluid_key, tooluid_value in self.paint_tools.items():
  524. if float('%.4f' % tooluid_value['tooldia']) == tool_sorted:
  525. tool_id += 1
  526. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  527. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  528. row_no = tool_id - 1
  529. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  530. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  531. # There are no drill bits in MM with more than 3 decimals diameter
  532. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  533. if self.units == 'MM':
  534. dia = QtWidgets.QTableWidgetItem('%.2f' % tooluid_value['tooldia'])
  535. else:
  536. dia = QtWidgets.QTableWidgetItem('%.4f' % tooluid_value['tooldia'])
  537. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  538. tool_type_item = QtWidgets.QComboBox()
  539. for item in self.tool_type_item_options:
  540. tool_type_item.addItem(item)
  541. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  542. idx = tool_type_item.findText(tooluid_value['tool_type'])
  543. tool_type_item.setCurrentIndex(idx)
  544. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  545. self.tools_table.setItem(row_no, 1, dia) # Diameter
  546. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  547. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  548. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  549. # make the diameter column editable
  550. for row in range(tool_id):
  551. self.tools_table.item(row, 1).setFlags(
  552. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  553. # all the tools are selected by default
  554. self.tools_table.selectColumn(0)
  555. #
  556. self.tools_table.resizeColumnsToContents()
  557. self.tools_table.resizeRowsToContents()
  558. vertical_header = self.tools_table.verticalHeader()
  559. vertical_header.hide()
  560. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  561. horizontal_header = self.tools_table.horizontalHeader()
  562. horizontal_header.setMinimumSectionSize(10)
  563. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  564. horizontal_header.resizeSection(0, 20)
  565. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  566. # self.tools_table.setSortingEnabled(True)
  567. # sort by tool diameter
  568. # self.tools_table.sortItems(1)
  569. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  570. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  571. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  572. self.tools_table.itemChanged.connect(self.on_tool_edit)
  573. def on_combo_box_type(self):
  574. obj_type = self.box_combo_type.currentIndex()
  575. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  576. self.box_combo.setCurrentIndex(0)
  577. def on_tool_add(self, dia=None, muted=None):
  578. try:
  579. self.tools_table.itemChanged.disconnect()
  580. except Exception as e:
  581. log.debug("ToolPaint.on_tool_add() --> %s" % str(e))
  582. if dia:
  583. tool_dia = dia
  584. else:
  585. try:
  586. tool_dia = float(self.addtool_entry.get_value())
  587. except ValueError:
  588. # try to convert comma to decimal point. if it's still not working error message and return
  589. try:
  590. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  591. except ValueError:
  592. self.app.inform.emit('[ERROR_NOTCL] %s' %
  593. _("Wrong value format entered, use a number."))
  594. return
  595. if tool_dia is None:
  596. self.build_ui()
  597. self.app.inform.emit('[WARNING_NOTCL] %s' %
  598. _("Please enter a tool diameter to add, in Float format."))
  599. return
  600. # construct a list of all 'tooluid' in the self.tools
  601. tool_uid_list = []
  602. for tooluid_key in self.paint_tools:
  603. tool_uid_item = int(tooluid_key)
  604. tool_uid_list.append(tool_uid_item)
  605. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  606. if not tool_uid_list:
  607. max_uid = 0
  608. else:
  609. max_uid = max(tool_uid_list)
  610. self.tooluid = int(max_uid + 1)
  611. tool_dias = []
  612. for k, v in self.paint_tools.items():
  613. for tool_v in v.keys():
  614. if tool_v == 'tooldia':
  615. tool_dias.append(float('%.4f' % v[tool_v]))
  616. if float('%.4f' % tool_dia) in tool_dias:
  617. if muted is None:
  618. self.app.inform.emit('[WARNING_NOTCL] %s' %
  619. _("Adding tool cancelled. Tool already in Tool Table."))
  620. self.tools_table.itemChanged.connect(self.on_tool_edit)
  621. return
  622. else:
  623. if muted is None:
  624. self.app.inform.emit('[success] %s' %
  625. _("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] %s' %
  658. _("Wrong value format entered, 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] %s' %
  665. _("Tool from Tool Table was edited."))
  666. self.build_ui()
  667. return
  668. else:
  669. # identify the old tool_dia and restore the text in tool table
  670. for k, v in self.paint_tools.items():
  671. if k == tooluid:
  672. old_tool_dia = v['tooldia']
  673. break
  674. restore_dia_item = self.tools_table.item(row, 1)
  675. restore_dia_item.setText(str(old_tool_dia))
  676. self.app.inform.emit('[WARNING_NOTCL] %s' %
  677. _("Edit cancelled. New diameter value is already in the Tool Table."))
  678. self.build_ui()
  679. # def on_tool_copy(self, all=None):
  680. # try:
  681. # self.tools_table.itemChanged.disconnect()
  682. # except:
  683. # pass
  684. #
  685. # # find the tool_uid maximum value in the self.tools
  686. # uid_list = []
  687. # for key in self.paint_tools:
  688. # uid_list.append(int(key))
  689. # try:
  690. # max_uid = max(uid_list, key=int)
  691. # except ValueError:
  692. # max_uid = 0
  693. #
  694. # if all is None:
  695. # if self.tools_table.selectedItems():
  696. # for current_row in self.tools_table.selectedItems():
  697. # # sometime the header get selected and it has row number -1
  698. # # we don't want to do anything with the header :)
  699. # if current_row.row() < 0:
  700. # continue
  701. # try:
  702. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  703. # max_uid += 1
  704. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  705. # for td in self.paint_tools:
  706. # print("COPIED", self.paint_tools[td])
  707. # self.build_ui()
  708. # except AttributeError:
  709. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  710. # self.build_ui()
  711. # return
  712. # except Exception as e:
  713. # log.debug("on_tool_copy() --> " + str(e))
  714. # # deselect the table
  715. # # self.ui.geo_tools_table.clearSelection()
  716. # else:
  717. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  718. # self.build_ui()
  719. # return
  720. # else:
  721. # # we copy all tools in geo_tools_table
  722. # try:
  723. # temp_tools = dict(self.paint_tools)
  724. # max_uid += 1
  725. # for tooluid in temp_tools:
  726. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  727. # temp_tools.clear()
  728. # self.build_ui()
  729. # except Exception as e:
  730. # log.debug("on_tool_copy() --> " + str(e))
  731. #
  732. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  733. def on_tool_delete(self, rows_to_delete=None, all=None):
  734. try:
  735. self.tools_table.itemChanged.disconnect()
  736. except Exception as e:
  737. log.debug("ToolPaint.on_tool_delete() --> %s" % str(e))
  738. pass
  739. deleted_tools_list = []
  740. if all:
  741. self.paint_tools.clear()
  742. self.build_ui()
  743. return
  744. if rows_to_delete:
  745. try:
  746. for row in rows_to_delete:
  747. tooluid_del = int(self.tools_table.item(row, 3).text())
  748. deleted_tools_list.append(tooluid_del)
  749. except TypeError:
  750. deleted_tools_list.append(rows_to_delete)
  751. for t in deleted_tools_list:
  752. self.paint_tools.pop(t, None)
  753. self.build_ui()
  754. return
  755. try:
  756. if self.tools_table.selectedItems():
  757. for row_sel in self.tools_table.selectedItems():
  758. row = row_sel.row()
  759. if row < 0:
  760. continue
  761. tooluid_del = int(self.tools_table.item(row, 3).text())
  762. deleted_tools_list.append(tooluid_del)
  763. for t in deleted_tools_list:
  764. self.paint_tools.pop(t, None)
  765. except AttributeError:
  766. self.app.inform.emit('[WARNING_NOTCL] %s' %
  767. _("Delete failed. Select a tool to delete."))
  768. return
  769. except Exception as e:
  770. log.debug(str(e))
  771. self.app.inform.emit('[success] %s' %
  772. _("Tool(s) deleted from Tool Table."))
  773. self.build_ui()
  774. def on_paint_button_click(self):
  775. # init values for the next usage
  776. self.reset_usage()
  777. self.app.report_usage(_("on_paint_button_click"))
  778. # self.app.call_source = 'paint'
  779. # #####################################################
  780. # ######### Reading Parameters ########################
  781. # #####################################################
  782. self.app.inform.emit(_("Paint Tool. Reading parameters."))
  783. try:
  784. overlap = float(self.paintoverlap_entry.get_value())
  785. except ValueError:
  786. # try to convert comma to decimal point. if it's still not working error message and return
  787. try:
  788. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  789. except ValueError:
  790. self.app.inform.emit('[ERROR_NOTCL] %s' %
  791. _("Wrong value format entered, use a number."))
  792. return
  793. if overlap >= 1 or overlap < 0:
  794. self.app.inform.emit('[ERROR_NOTCL] %s' %
  795. _("Overlap value must be between 0 (inclusive) and 1 (exclusive)"))
  796. return
  797. self.app.inform.emit('[WARNING_NOTCL] %s' %
  798. _("Click inside the desired polygon."))
  799. connect = self.pathconnect_cb.get_value()
  800. contour = self.paintcontour_cb.get_value()
  801. select_method = self.selectmethod_combo.get_value()
  802. self.obj_name = self.obj_combo.currentText()
  803. # Get source object.
  804. try:
  805. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  806. except Exception as e:
  807. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  808. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  809. (_("Could not retrieve object: %s"),
  810. self.obj_name))
  811. return
  812. if self.paint_obj is None:
  813. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  814. (_("Object not found"),
  815. self.paint_obj))
  816. return
  817. # test if the Geometry Object is multigeo and return Fail if True because
  818. # for now Paint don't work on MultiGeo
  819. if self.paint_obj.multigeo is True:
  820. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  821. _("Can't do Paint on MultiGeo geometries"))
  822. return 'Fail'
  823. o_name = '%s_multitool_paint' % self.obj_name
  824. # use the selected tools in the tool table; get diameters
  825. tooldia_list = list()
  826. if self.tools_table.selectedItems():
  827. for x in self.tools_table.selectedItems():
  828. try:
  829. tooldia = float(self.tools_table.item(x.row(), 1).text())
  830. except ValueError:
  831. # try to convert comma to decimal point. if it's still not working error message and return
  832. try:
  833. tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  834. except ValueError:
  835. self.app.inform.emit('[ERROR_NOTCL] %s' %
  836. _("Wrong value format entered, use a number."))
  837. continue
  838. tooldia_list.append(tooldia)
  839. else:
  840. self.app.inform.emit('[ERROR_NOTCL] %s' %
  841. _("No selected tools in Tool Table."))
  842. return
  843. if select_method == "all":
  844. self.paint_poly_all(self.paint_obj,
  845. tooldia=tooldia_list,
  846. outname=o_name,
  847. overlap=overlap,
  848. connect=connect,
  849. contour=contour)
  850. elif select_method == "single":
  851. self.app.inform.emit('[WARNING_NOTCL] %s' %
  852. _("Click inside the desired polygon."))
  853. # use the first tool in the tool table; get the diameter
  854. # tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  855. # To be called after clicking on the plot.
  856. def doit(event):
  857. # do paint single only for left mouse clicks
  858. if event.button == 1:
  859. self.app.inform.emit(_("Painting polygon..."))
  860. self.app.plotcanvas.vis_disconnect('mouse_press', doit)
  861. pos = self.app.plotcanvas.translate_coords(event.pos)
  862. if self.app.grid_status() == True:
  863. pos = self.app.geo_editor.snap(pos[0], pos[1])
  864. self.paint_poly(self.paint_obj,
  865. inside_pt=[pos[0], pos[1]],
  866. tooldia=tooldia_list,
  867. overlap=overlap,
  868. connect=connect,
  869. contour=contour)
  870. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  871. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  872. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  873. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  874. self.app.plotcanvas.vis_connect('mouse_press', doit)
  875. elif select_method == "area":
  876. self.app.inform.emit('[WARNING_NOTCL] %s' %
  877. _("Click the start point of the paint area."))
  878. # use the first tool in the tool table; get the diameter
  879. # tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  880. # To be called after clicking on the plot.
  881. def on_mouse_release(event):
  882. # do paint single only for left mouse clicks
  883. if event.button == 1:
  884. if not self.first_click:
  885. self.first_click = True
  886. self.app.inform.emit('[WARNING_NOTCL] %s' %
  887. _("Click the end point of the paint area."))
  888. self.cursor_pos = self.app.plotcanvas.translate_coords(event.pos)
  889. if self.app.grid_status() == True:
  890. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  891. else:
  892. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  893. self.app.delete_selection_shape()
  894. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  895. if self.app.grid_status() == True:
  896. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  897. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  898. x1, y1 = curr_pos[0], curr_pos[1]
  899. pt1 = (x0, y0)
  900. pt2 = (x1, y0)
  901. pt3 = (x1, y1)
  902. pt4 = (x0, y1)
  903. self.sel_rect.append(Polygon([pt1, pt2, pt3, pt4]))
  904. self.first_click = False
  905. return
  906. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  907. #
  908. # if modifiers == QtCore.Qt.ShiftModifier:
  909. # mod_key = 'Shift'
  910. # elif modifiers == QtCore.Qt.ControlModifier:
  911. # mod_key = 'Control'
  912. # else:
  913. # mod_key = None
  914. #
  915. # if mod_key == self.app.defaults["global_mselect_key"]:
  916. # self.first_click = False
  917. # return
  918. #
  919. # self.sel_rect = cascaded_union(self.sel_rect)
  920. # self.paint_poly_area(obj=self.paint_obj,
  921. # tooldia=tooldia_list,
  922. # sel_obj= self.sel_rect,
  923. # outname=o_name,
  924. # overlap=overlap,
  925. # connect=connect,
  926. # contour=contour)
  927. #
  928. # self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  929. # self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  930. #
  931. # self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  932. # self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  933. # self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  934. elif event.button == 2 and self.mouse_is_dragging is False:
  935. self.first_click = False
  936. self.app.plotcanvas.vis_disconnect('mouse_release', on_mouse_release)
  937. self.app.plotcanvas.vis_disconnect('mouse_move', on_mouse_move)
  938. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  939. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  940. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  941. if len(self.sel_rect) == 0:
  942. return
  943. self.sel_rect = cascaded_union(self.sel_rect)
  944. self.paint_poly_area(obj=self.paint_obj,
  945. tooldia=tooldia_list,
  946. sel_obj=self.sel_rect,
  947. outname=o_name,
  948. overlap=overlap,
  949. connect=connect,
  950. contour=contour)
  951. # called on mouse move
  952. def on_mouse_move(event):
  953. curr_pos = self.app.plotcanvas.translate_coords(event.pos)
  954. self.app.app_cursor.enabled = False
  955. # detect mouse dragging motion
  956. if event.is_dragging is True:
  957. self.mouse_is_dragging = True
  958. else:
  959. self.mouse_is_dragging = False
  960. # update the cursor position
  961. if self.app.grid_status() == True:
  962. self.app.app_cursor.enabled = True
  963. # Update cursor
  964. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  965. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  966. symbol='++', edge_color='black', size=20)
  967. # draw the utility geometry
  968. if self.first_click:
  969. self.app.delete_selection_shape()
  970. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  971. coords=(curr_pos[0], curr_pos[1]),
  972. face_alpha=0.0)
  973. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  974. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  975. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  976. self.app.plotcanvas.vis_connect('mouse_release', on_mouse_release)
  977. self.app.plotcanvas.vis_connect('mouse_move', on_mouse_move)
  978. elif select_method == 'ref':
  979. self.bound_obj_name = self.box_combo.currentText()
  980. # Get source object.
  981. try:
  982. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  983. except Exception as e:
  984. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  985. (_("Could not retrieve object"),
  986. self.obj_name))
  987. return "Could not retrieve object: %s" % self.obj_name
  988. self.paint_poly_ref(obj=self.paint_obj,
  989. sel_obj=self.bound_obj,
  990. tooldia=tooldia_list,
  991. overlap=overlap,
  992. outname=o_name,
  993. connect=connect,
  994. contour=contour)
  995. def paint_poly(self, obj,
  996. inside_pt=None,
  997. tooldia=None,
  998. overlap=None,
  999. order=None,
  1000. margin=None,
  1001. method=None,
  1002. outname=None,
  1003. connect=None,
  1004. contour=None,
  1005. tools_storage=None):
  1006. """
  1007. Paints a polygon selected by clicking on its interior or by having a point coordinates given
  1008. Note:
  1009. * The margin is taken directly from the form.
  1010. :param obj: painted object
  1011. :param inside_pt: [x, y]
  1012. :param tooldia: Diameter of the painting tool
  1013. :param overlap: Overlap of the tool between passes.
  1014. :param order: if the tools are ordered and how
  1015. :param margin: a border around painting area
  1016. :param outname: Name of the resulting Geometry Object.
  1017. :param connect: Connect lines to avoid tool lifts.
  1018. :param contour: Paint around the edges.
  1019. :param method: choice out of 'seed', 'normal', 'lines'
  1020. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1021. Usage of the different one is related to when this function is called from a TcL command.
  1022. :return: None
  1023. """
  1024. # Which polygon.
  1025. # poly = find_polygon(self.solid_geometry, inside_pt)
  1026. poly = self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)
  1027. paint_method = method if method is None else self.paintmethod_combo.get_value()
  1028. if margin is not None:
  1029. paint_margin = margin
  1030. else:
  1031. try:
  1032. paint_margin = float(self.paintmargin_entry.get_value())
  1033. except ValueError:
  1034. # try to convert comma to decimal point. if it's still not working error message and return
  1035. try:
  1036. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1037. except ValueError:
  1038. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1039. _("Wrong value format entered, use a number."))
  1040. return
  1041. # No polygon?
  1042. if poly is None:
  1043. self.app.log.warning('No polygon found.')
  1044. self.app.inform.emit(_('[WARNING] No polygon found.'))
  1045. return
  1046. proc = self.app.proc_container.new(_("Painting polygon..."))
  1047. self.app.inform.emit(_("Paint Tool. Painting polygon at location: %s") % str(inside_pt))
  1048. name = outname if outname is not None else self.obj_name + "_paint"
  1049. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1050. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1051. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1052. order = order if order is not None else self.order_radio.get_value()
  1053. sorted_tools = []
  1054. if tooldia is not None:
  1055. try:
  1056. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1057. except AttributeError:
  1058. if not isinstance(tooldia, list):
  1059. sorted_tools = [float(tooldia)]
  1060. else:
  1061. sorted_tools = tooldia
  1062. else:
  1063. for row in range(self.tools_table.rowCount()):
  1064. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1065. if tools_storage is not None:
  1066. tools_storage = tools_storage
  1067. else:
  1068. tools_storage = self.paint_tools
  1069. # Initializes the new geometry object
  1070. def gen_paintarea(geo_obj, app_obj):
  1071. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1072. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1073. # assert isinstance(app_obj, App)
  1074. tool_dia = None
  1075. if order == 'fwd':
  1076. sorted_tools.sort(reverse=False)
  1077. elif order == 'rev':
  1078. sorted_tools.sort(reverse=True)
  1079. else:
  1080. pass
  1081. def paint_p(polyg, tooldia):
  1082. cpoly = None
  1083. try:
  1084. if paint_method == "seed":
  1085. # Type(cp) == FlatCAMRTreeStorage | None
  1086. cpoly = self.clear_polygon2(polyg,
  1087. tooldia=tooldia,
  1088. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1089. overlap=over,
  1090. contour=cont,
  1091. connect=conn)
  1092. elif paint_method == "lines":
  1093. # Type(cp) == FlatCAMRTreeStorage | None
  1094. cpoly = self.clear_polygon3(polyg,
  1095. tooldia=tooldia,
  1096. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1097. overlap=over,
  1098. contour=cont,
  1099. connect=conn)
  1100. else:
  1101. # Type(cp) == FlatCAMRTreeStorage | None
  1102. cpoly = self.clear_polygon(polyg,
  1103. tooldia=tooldia,
  1104. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1105. overlap=over,
  1106. contour=cont,
  1107. connect=conn)
  1108. except FlatCAMApp.GracefulException:
  1109. return "fail"
  1110. except Exception as e:
  1111. log.debug("ToolPaint.paint_poly().gen_paintarea().paint_p() --> %s" % str(e))
  1112. if cpoly is not None:
  1113. geo_obj.solid_geometry += list(cpoly.get_objects())
  1114. return cpoly
  1115. else:
  1116. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1117. _('Geometry could not be painted completely'))
  1118. return None
  1119. try:
  1120. a, b, c, d = poly.bounds
  1121. geo_obj.options['xmin'] = a
  1122. geo_obj.options['ymin'] = b
  1123. geo_obj.options['xmax'] = c
  1124. geo_obj.options['ymax'] = d
  1125. except Exception as e:
  1126. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1127. return
  1128. total_geometry = []
  1129. current_uid = int(1)
  1130. geo_obj.solid_geometry = []
  1131. for tool_dia in sorted_tools:
  1132. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1133. for k, v in tools_storage.items():
  1134. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1135. current_uid = int(k)
  1136. break
  1137. try:
  1138. poly_buf = poly.buffer(-paint_margin)
  1139. if isinstance(poly_buf, MultiPolygon):
  1140. cp = []
  1141. for pp in poly_buf:
  1142. cp.append(paint_p(pp, tooldia=tool_dia))
  1143. else:
  1144. cp = paint_p(poly_buf, tooldia=tool_dia)
  1145. if cp is not None:
  1146. if isinstance(cp, list):
  1147. for x in cp:
  1148. total_geometry += list(x.get_objects())
  1149. else:
  1150. total_geometry = list(cp.get_objects())
  1151. except FlatCAMApp.GracefulException:
  1152. return "fail"
  1153. except Exception as e:
  1154. log.debug("Could not Paint the polygons. %s" % str(e))
  1155. self.app.inform.emit('[ERROR] %s\n%s' %
  1156. (_("Could not do Paint. Try a different combination of parameters. "
  1157. "Or a different strategy of paint"),
  1158. str(e)))
  1159. return "fail"
  1160. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1161. # dictionary and then reset the temporary list that stored that solid_geometry
  1162. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1163. tools_storage[current_uid]['data']['name'] = name
  1164. total_geometry[:] = []
  1165. # delete tools with empty geometry
  1166. keys_to_delete = []
  1167. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1168. for uid in tools_storage:
  1169. # if the solid_geometry (type=list) is empty
  1170. if not tools_storage[uid]['solid_geometry']:
  1171. keys_to_delete.append(uid)
  1172. # actual delete of keys from the tools_storage dict
  1173. for k in keys_to_delete:
  1174. tools_storage.pop(k, None)
  1175. geo_obj.options["cnctooldia"] = str(tool_dia)
  1176. # this turn on the FlatCAMCNCJob plot for multiple tools
  1177. geo_obj.multigeo = True
  1178. geo_obj.multitool = True
  1179. geo_obj.tools.clear()
  1180. geo_obj.tools = dict(tools_storage)
  1181. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1182. has_solid_geo = 0
  1183. for tooluid in geo_obj.tools:
  1184. if geo_obj.tools[tooluid]['solid_geometry']:
  1185. has_solid_geo += 1
  1186. if has_solid_geo == 0:
  1187. self.app.inform.emit('[ERROR] %s' %
  1188. _("There is no Painting Geometry in the file.\n"
  1189. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1190. "Change the painting parameters and try again."))
  1191. return
  1192. self.app.inform.emit('[success] %s' % _("Paint Single Done."))
  1193. # Experimental...
  1194. # print("Indexing...", end=' ')
  1195. # geo_obj.make_index()
  1196. # if errors == 0:
  1197. # print("[success] Paint single polygon Done")
  1198. # self.app.inform.emit("[success] Paint single polygon Done")
  1199. # else:
  1200. # print("[WARNING] Paint single polygon done with errors")
  1201. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  1202. # "%d area(s) could not be painted.\n"
  1203. # "Use different paint parameters or edit the paint geometry and correct"
  1204. # "the issue."
  1205. # % errors)
  1206. def job_thread(app_obj):
  1207. try:
  1208. app_obj.new_object("geometry", name, gen_paintarea)
  1209. except FlatCAMApp.GracefulException:
  1210. proc.done()
  1211. return
  1212. except Exception as e:
  1213. proc.done()
  1214. self.app.inform.emit('[ERROR_NOTCL] %s --> %s' %
  1215. (_('PaintTool.paint_poly()'),
  1216. str(e)))
  1217. return
  1218. proc.done()
  1219. # focus on Selected Tab
  1220. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1221. self.app.inform.emit(_("Polygon Paint started ..."))
  1222. # Promise object with the new name
  1223. self.app.collection.promise(name)
  1224. # Background
  1225. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1226. def paint_poly_all(self, obj,
  1227. tooldia=None,
  1228. overlap=None,
  1229. order=None,
  1230. margin=None,
  1231. method=None,
  1232. outname=None,
  1233. connect=None,
  1234. contour=None,
  1235. tools_storage=None):
  1236. """
  1237. Paints all polygons in this object.
  1238. :param obj: painted object
  1239. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1240. :param overlap: value by which the paths will overlap
  1241. :param order: if the tools are ordered and how
  1242. :param margin: a border around painting area
  1243. :param outname: name of the resulting object
  1244. :param connect: Connect lines to avoid tool lifts.
  1245. :param contour: Paint around the edges.
  1246. :param method: choice out of 'seed', 'normal', 'lines'
  1247. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1248. Usage of the different one is related to when this function is called from a TcL command.
  1249. :return:
  1250. """
  1251. paint_method = method if method is None else self.paintmethod_combo.get_value()
  1252. if margin is not None:
  1253. paint_margin = margin
  1254. else:
  1255. try:
  1256. paint_margin = float(self.paintmargin_entry.get_value())
  1257. except ValueError:
  1258. # try to convert comma to decimal point. if it's still not working error message and return
  1259. try:
  1260. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1261. except ValueError:
  1262. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1263. _("Wrong value format entered, use a number."))
  1264. return
  1265. proc = self.app.proc_container.new(_("Painting polygons..."))
  1266. name = outname if outname is not None else self.obj_name + "_paint"
  1267. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1268. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1269. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1270. order = order if order is not None else self.order_radio.get_value()
  1271. sorted_tools = []
  1272. if tooldia is not None:
  1273. try:
  1274. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1275. except AttributeError:
  1276. if not isinstance(tooldia, list):
  1277. sorted_tools = [float(tooldia)]
  1278. else:
  1279. sorted_tools = tooldia
  1280. else:
  1281. for row in range(self.tools_table.rowCount()):
  1282. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1283. if tools_storage is not None:
  1284. tools_storage = tools_storage
  1285. else:
  1286. tools_storage = self.paint_tools
  1287. # This is a recursive generator of individual Polygons.
  1288. # Note: Double check correct implementation. Might exit
  1289. # early if it finds something that is not a Polygon?
  1290. # def recurse(geo):
  1291. # try:
  1292. # for subg in geo:
  1293. # for subsubg in recurse(subg):
  1294. # yield subsubg
  1295. # except TypeError:
  1296. # if isinstance(geo, Polygon):
  1297. # yield geo
  1298. #
  1299. # raise StopIteration
  1300. def recurse(geometry, reset=True):
  1301. """
  1302. Creates a list of non-iterable linear geometry objects.
  1303. Results are placed in self.flat_geometry
  1304. :param geometry: Shapely type or list or list of list of such.
  1305. :param reset: Clears the contents of self.flat_geometry.
  1306. """
  1307. if self.app.abort_flag:
  1308. # graceful abort requested by the user
  1309. raise FlatCAMApp.GracefulException
  1310. if geometry is None:
  1311. return
  1312. if reset:
  1313. self.flat_geometry = []
  1314. # ## If iterable, expand recursively.
  1315. try:
  1316. for geo in geometry:
  1317. if geo is not None:
  1318. recurse(geometry=geo, reset=False)
  1319. # ## Not iterable, do the actual indexing and add.
  1320. except TypeError:
  1321. if isinstance(geometry, LinearRing):
  1322. g = Polygon(geometry)
  1323. self.flat_geometry.append(g)
  1324. else:
  1325. self.flat_geometry.append(geometry)
  1326. return self.flat_geometry
  1327. # Initializes the new geometry object
  1328. def gen_paintarea(geo_obj, app_obj):
  1329. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1330. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1331. log.debug("Paint Tool. Normal painting all task started.")
  1332. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1333. tool_dia = None
  1334. if order == 'fwd':
  1335. sorted_tools.sort(reverse=False)
  1336. elif order == 'rev':
  1337. sorted_tools.sort(reverse=True)
  1338. else:
  1339. pass
  1340. try:
  1341. a, b, c, d = obj.bounds()
  1342. geo_obj.options['xmin'] = a
  1343. geo_obj.options['ymin'] = b
  1344. geo_obj.options['xmax'] = c
  1345. geo_obj.options['ymax'] = d
  1346. except Exception as e:
  1347. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1348. return
  1349. total_geometry = []
  1350. current_uid = int(1)
  1351. geo_obj.solid_geometry = []
  1352. for tool_dia in sorted_tools:
  1353. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1354. app_obj.inform.emit(
  1355. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1356. str(tool_dia),
  1357. self.units.lower(),
  1358. _('started'))
  1359. )
  1360. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1361. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1362. for k, v in tools_storage.items():
  1363. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1364. current_uid = int(k)
  1365. break
  1366. painted_area = recurse(obj.solid_geometry)
  1367. # variables to display the percentage of work done
  1368. geo_len = len(painted_area)
  1369. disp_number = 0
  1370. old_disp_number = 0
  1371. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1372. pol_nr = 0
  1373. for geo in painted_area:
  1374. try:
  1375. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1376. if not isinstance(geo, Polygon):
  1377. continue
  1378. poly_buf = geo.buffer(-paint_margin)
  1379. if paint_method == "seed":
  1380. # Type(cp) == FlatCAMRTreeStorage | None
  1381. cp = self.clear_polygon2(poly_buf,
  1382. tooldia=tool_dia,
  1383. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1384. overlap=over,
  1385. contour=cont,
  1386. connect=conn)
  1387. elif paint_method == "lines":
  1388. # Type(cp) == FlatCAMRTreeStorage | None
  1389. cp = self.clear_polygon3(poly_buf,
  1390. tooldia=tool_dia,
  1391. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1392. overlap=over,
  1393. contour=cont,
  1394. connect=conn)
  1395. else:
  1396. # Type(cp) == FlatCAMRTreeStorage | None
  1397. cp = self.clear_polygon(poly_buf,
  1398. tooldia=tool_dia,
  1399. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1400. overlap=over,
  1401. contour=cont,
  1402. connect=conn)
  1403. if cp is not None:
  1404. total_geometry += list(cp.get_objects())
  1405. except FlatCAMApp.GracefulException:
  1406. return "fail"
  1407. except Exception as e:
  1408. log.debug("Could not Paint the polygons. %s" % str(e))
  1409. self.app.inform.emit('[ERROR] %s\n%s' %
  1410. (_("Could not do Paint All. Try a different combination of parameters. "
  1411. "Or a different Method of paint"),
  1412. str(e)))
  1413. return "fail"
  1414. pol_nr += 1
  1415. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 99]))
  1416. # log.debug("Polygons cleared: %d" % pol_nr)
  1417. if old_disp_number < disp_number <= 100:
  1418. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1419. old_disp_number = disp_number
  1420. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1421. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1422. # dictionary and then reset the temporary list that stored that solid_geometry
  1423. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1424. tools_storage[current_uid]['data']['name'] = name
  1425. total_geometry[:] = []
  1426. # delete tools with empty geometry
  1427. keys_to_delete = []
  1428. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1429. for uid in tools_storage:
  1430. # if the solid_geometry (type=list) is empty
  1431. if not tools_storage[uid]['solid_geometry']:
  1432. keys_to_delete.append(uid)
  1433. # actual delete of keys from the tools_storage dict
  1434. for k in keys_to_delete:
  1435. tools_storage.pop(k, None)
  1436. geo_obj.options["cnctooldia"] = str(tool_dia)
  1437. # this turn on the FlatCAMCNCJob plot for multiple tools
  1438. geo_obj.multigeo = True
  1439. geo_obj.multitool = True
  1440. geo_obj.tools.clear()
  1441. geo_obj.tools = dict(tools_storage)
  1442. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1443. has_solid_geo = 0
  1444. for tooluid in geo_obj.tools:
  1445. if geo_obj.tools[tooluid]['solid_geometry']:
  1446. has_solid_geo += 1
  1447. if has_solid_geo == 0:
  1448. self.app.inform.emit('[ERROR] %s' %
  1449. _("There is no Painting Geometry in the file.\n"
  1450. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1451. "Change the painting parameters and try again."))
  1452. return
  1453. # Experimental...
  1454. # print("Indexing...", end=' ')
  1455. # geo_obj.make_index()
  1456. self.app.inform.emit(_("[success] Paint All Done."))
  1457. # Initializes the new geometry object
  1458. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1459. assert isinstance(geo_obj, FlatCAMGeometry), \
  1460. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1461. log.debug("Paint Tool. Rest machining painting all task started.")
  1462. app_obj.inform.emit(_("Paint Tool. Rest machining painting all task started."))
  1463. tool_dia = None
  1464. sorted_tools.sort(reverse=True)
  1465. cleared_geo = []
  1466. current_uid = int(1)
  1467. geo_obj.solid_geometry = []
  1468. try:
  1469. a, b, c, d = obj.bounds()
  1470. geo_obj.options['xmin'] = a
  1471. geo_obj.options['ymin'] = b
  1472. geo_obj.options['xmax'] = c
  1473. geo_obj.options['ymax'] = d
  1474. except Exception as e:
  1475. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1476. return
  1477. for tool_dia in sorted_tools:
  1478. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1479. app_obj.inform.emit(
  1480. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1481. str(tool_dia),
  1482. self.units.lower(),
  1483. _('started'))
  1484. )
  1485. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1486. painted_area = recurse(obj.solid_geometry)
  1487. # variables to display the percentage of work done
  1488. geo_len = int(len(painted_area) / 100)
  1489. disp_number = 0
  1490. old_disp_number = 0
  1491. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1492. pol_nr = 0
  1493. for geo in painted_area:
  1494. try:
  1495. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1496. poly_buf = geo.buffer(-paint_margin)
  1497. cp = None
  1498. if paint_method == "standard":
  1499. # Type(cp) == FlatCAMRTreeStorage | None
  1500. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1501. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1502. overlap=over, contour=cont, connect=conn)
  1503. elif paint_method == "seed":
  1504. # Type(cp) == FlatCAMRTreeStorage | None
  1505. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1506. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1507. overlap=over, contour=cont, connect=conn)
  1508. elif paint_method == "lines":
  1509. # Type(cp) == FlatCAMRTreeStorage | None
  1510. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1511. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1512. overlap=over, contour=cont, connect=conn)
  1513. if cp is not None:
  1514. cleared_geo += list(cp.get_objects())
  1515. except FlatCAMApp.GracefulException:
  1516. return "fail"
  1517. except Exception as e:
  1518. log.debug("Could not Paint the polygons. %s" % str(e))
  1519. self.app.inform.emit('[ERROR] %s\n%s' %
  1520. (_("Could not do Paint All. Try a different combination of parameters. "
  1521. "Or a different Method of paint"),
  1522. str(e)))
  1523. return "fail"
  1524. pol_nr += 1
  1525. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 99]))
  1526. # log.debug("Polygons cleared: %d" % pol_nr)
  1527. if old_disp_number < disp_number <= 100:
  1528. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1529. old_disp_number = disp_number
  1530. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1531. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1532. for k, v in tools_storage.items():
  1533. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1534. current_uid = int(k)
  1535. break
  1536. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  1537. # then reset the temporary list that stored that solid_geometry
  1538. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1539. tools_storage[current_uid]['data']['name'] = name
  1540. cleared_geo[:] = []
  1541. geo_obj.options["cnctooldia"] = str(tool_dia)
  1542. # this turn on the FlatCAMCNCJob plot for multiple tools
  1543. geo_obj.multigeo = True
  1544. geo_obj.multitool = True
  1545. geo_obj.tools.clear()
  1546. geo_obj.tools = dict(tools_storage)
  1547. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1548. has_solid_geo = 0
  1549. for tooluid in geo_obj.tools:
  1550. if geo_obj.tools[tooluid]['solid_geometry']:
  1551. has_solid_geo += 1
  1552. if has_solid_geo == 0:
  1553. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1554. _("There is no Painting Geometry in the file.\n"
  1555. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1556. "Change the painting parameters and try again."))
  1557. return
  1558. # Experimental...
  1559. # print("Indexing...", end=' ')
  1560. # geo_obj.make_index()
  1561. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  1562. def job_thread(app_obj):
  1563. try:
  1564. if self.rest_cb.isChecked():
  1565. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1566. else:
  1567. app_obj.new_object("geometry", name, gen_paintarea)
  1568. except FlatCAMApp.GracefulException:
  1569. proc.done()
  1570. return
  1571. except Exception as e:
  1572. proc.done()
  1573. traceback.print_stack()
  1574. return
  1575. proc.done()
  1576. # focus on Selected Tab
  1577. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1578. self.app.inform.emit(_("Polygon Paint started ..."))
  1579. # Promise object with the new name
  1580. self.app.collection.promise(name)
  1581. # Background
  1582. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1583. def paint_poly_area(self, obj, sel_obj,
  1584. tooldia=None,
  1585. overlap=None,
  1586. order=None,
  1587. margin=None,
  1588. method=None,
  1589. outname=None,
  1590. connect=None,
  1591. contour=None,
  1592. tools_storage=None):
  1593. """
  1594. Paints all polygons in this object that are within the sel_obj object
  1595. :param obj: painted object
  1596. :param sel_obj: paint only what is inside this object bounds
  1597. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1598. :param overlap: value by which the paths will overlap
  1599. :param order: if the tools are ordered and how
  1600. :param margin: a border around painting area
  1601. :param outname: name of the resulting object
  1602. :param connect: Connect lines to avoid tool lifts.
  1603. :param contour: Paint around the edges.
  1604. :param method: choice out of 'seed', 'normal', 'lines'
  1605. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1606. Usage of the different one is related to when this function is called from a TcL command.
  1607. :return:
  1608. """
  1609. paint_method = method if method is None else self.paintmethod_combo.get_value()
  1610. if margin is not None:
  1611. paint_margin = margin
  1612. else:
  1613. try:
  1614. paint_margin = float(self.paintmargin_entry.get_value())
  1615. except ValueError:
  1616. # try to convert comma to decimal point. if it's still not working error message and return
  1617. try:
  1618. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1619. except ValueError:
  1620. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1621. _("Wrong value format entered, use a number."))
  1622. return
  1623. proc = self.app.proc_container.new(_("Painting polygons..."))
  1624. name = outname if outname is not None else self.obj_name + "_paint"
  1625. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1626. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1627. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1628. order = order if order is not None else self.order_radio.get_value()
  1629. sorted_tools = []
  1630. if tooldia is not None:
  1631. try:
  1632. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1633. except AttributeError:
  1634. if not isinstance(tooldia, list):
  1635. sorted_tools = [float(tooldia)]
  1636. else:
  1637. sorted_tools = tooldia
  1638. else:
  1639. for row in range(self.tools_table.rowCount()):
  1640. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1641. if tools_storage is not None:
  1642. tools_storage = tools_storage
  1643. else:
  1644. tools_storage = self.paint_tools
  1645. def recurse(geometry, reset=True):
  1646. """
  1647. Creates a list of non-iterable linear geometry objects.
  1648. Results are placed in self.flat_geometry
  1649. :param geometry: Shapely type or list or list of list of such.
  1650. :param reset: Clears the contents of self.flat_geometry.
  1651. """
  1652. if self.app.abort_flag:
  1653. # graceful abort requested by the user
  1654. raise FlatCAMApp.GracefulException
  1655. if geometry is None:
  1656. return
  1657. if reset:
  1658. self.flat_geometry = []
  1659. # ## If iterable, expand recursively.
  1660. try:
  1661. for geo in geometry:
  1662. if geo is not None:
  1663. recurse(geometry=geo, reset=False)
  1664. # ## Not iterable, do the actual indexing and add.
  1665. except TypeError:
  1666. if isinstance(geometry, LinearRing):
  1667. g = Polygon(geometry)
  1668. self.flat_geometry.append(g)
  1669. else:
  1670. self.flat_geometry.append(geometry)
  1671. return self.flat_geometry
  1672. # Initializes the new geometry object
  1673. def gen_paintarea(geo_obj, app_obj):
  1674. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1675. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1676. log.debug("Paint Tool. Normal painting area task started.")
  1677. app_obj.inform.emit(_("Paint Tool. Normal painting area task started."))
  1678. tool_dia = None
  1679. if order == 'fwd':
  1680. sorted_tools.sort(reverse=False)
  1681. elif order == 'rev':
  1682. sorted_tools.sort(reverse=True)
  1683. else:
  1684. pass
  1685. # this is were heavy lifting is done and creating the geometry to be painted
  1686. geo_to_paint = []
  1687. if not isinstance(obj.solid_geometry, list):
  1688. target_geo = [obj.solid_geometry]
  1689. else:
  1690. target_geo = obj.solid_geometry
  1691. for poly in target_geo:
  1692. new_pol = poly.intersection(sel_obj)
  1693. geo_to_paint.append(new_pol)
  1694. try:
  1695. a, b, c, d = self.paint_bounds(geo_to_paint)
  1696. geo_obj.options['xmin'] = a
  1697. geo_obj.options['ymin'] = b
  1698. geo_obj.options['xmax'] = c
  1699. geo_obj.options['ymax'] = d
  1700. except Exception as e:
  1701. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1702. return
  1703. total_geometry = []
  1704. current_uid = int(1)
  1705. geo_obj.solid_geometry = []
  1706. for tool_dia in sorted_tools:
  1707. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1708. app_obj.inform.emit(
  1709. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1710. str(tool_dia),
  1711. self.units.lower(),
  1712. _('started'))
  1713. )
  1714. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1715. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1716. for k, v in tools_storage.items():
  1717. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1718. current_uid = int(k)
  1719. break
  1720. painted_area = recurse(geo_to_paint)
  1721. # variables to display the percentage of work done
  1722. geo_len = len(painted_area)
  1723. disp_number = 0
  1724. old_disp_number = 0
  1725. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1726. pol_nr = 0
  1727. for geo in painted_area:
  1728. try:
  1729. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1730. if not isinstance(geo, Polygon):
  1731. continue
  1732. poly_buf = geo.buffer(-paint_margin)
  1733. cp = None
  1734. if paint_method == "seed":
  1735. # Type(cp) == FlatCAMRTreeStorage | None
  1736. cp = self.clear_polygon2(poly_buf,
  1737. tooldia=tool_dia,
  1738. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1739. overlap=over,
  1740. contour=cont,
  1741. connect=conn)
  1742. elif paint_method == "lines":
  1743. # Type(cp) == FlatCAMRTreeStorage | None
  1744. cp = self.clear_polygon3(poly_buf,
  1745. tooldia=tool_dia,
  1746. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1747. overlap=over,
  1748. contour=cont,
  1749. connect=conn)
  1750. else:
  1751. # Type(cp) == FlatCAMRTreeStorage | None
  1752. cp = self.clear_polygon(poly_buf,
  1753. tooldia=tool_dia,
  1754. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1755. overlap=over,
  1756. contour=cont,
  1757. connect=conn)
  1758. if cp is not None:
  1759. total_geometry += list(cp.get_objects())
  1760. except FlatCAMApp.GracefulException:
  1761. return "fail"
  1762. except Exception as e:
  1763. log.debug("Could not Paint the polygons. %s" % str(e))
  1764. self.app.inform.emit('[ERROR] %s' %
  1765. _("Could not do Paint All. Try a different combination of parameters. "
  1766. "Or a different Method of paint\n%s") % str(e))
  1767. return
  1768. pol_nr += 1
  1769. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 99]))
  1770. # log.debug("Polygons cleared: %d" % pol_nr)
  1771. if old_disp_number < disp_number <= 100:
  1772. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1773. old_disp_number = disp_number
  1774. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1775. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1776. # dictionary and then reset the temporary list that stored that solid_geometry
  1777. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1778. tools_storage[current_uid]['data']['name'] = name
  1779. total_geometry[:] = []
  1780. # delete tools with empty geometry
  1781. keys_to_delete = []
  1782. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1783. for uid in tools_storage:
  1784. # if the solid_geometry (type=list) is empty
  1785. if not tools_storage[uid]['solid_geometry']:
  1786. keys_to_delete.append(uid)
  1787. # actual delete of keys from the tools_storage dict
  1788. for k in keys_to_delete:
  1789. tools_storage.pop(k, None)
  1790. geo_obj.options["cnctooldia"] = str(tool_dia)
  1791. # this turn on the FlatCAMCNCJob plot for multiple tools
  1792. geo_obj.multigeo = True
  1793. geo_obj.multitool = True
  1794. geo_obj.tools.clear()
  1795. geo_obj.tools = dict(tools_storage)
  1796. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1797. has_solid_geo = 0
  1798. for tooluid in geo_obj.tools:
  1799. if geo_obj.tools[tooluid]['solid_geometry']:
  1800. has_solid_geo += 1
  1801. if has_solid_geo == 0:
  1802. self.app.inform.emit('[ERROR] %s' %
  1803. _("There is no Painting Geometry in the file.\n"
  1804. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1805. "Change the painting parameters and try again."))
  1806. return
  1807. # Experimental...
  1808. # print("Indexing...", end=' ')
  1809. # geo_obj.make_index()
  1810. self.app.inform.emit(_("[success] Paint Area Done."))
  1811. # Initializes the new geometry object
  1812. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1813. assert isinstance(geo_obj, FlatCAMGeometry), \
  1814. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1815. log.debug("Paint Tool. Rest machining painting area task started.")
  1816. app_obj.inform.emit(_("Paint Tool. Rest machining painting area task started."))
  1817. tool_dia = None
  1818. sorted_tools.sort(reverse=True)
  1819. cleared_geo = []
  1820. current_uid = int(1)
  1821. geo_obj.solid_geometry = []
  1822. try:
  1823. a, b, c, d = obj.bounds()
  1824. geo_obj.options['xmin'] = a
  1825. geo_obj.options['ymin'] = b
  1826. geo_obj.options['xmax'] = c
  1827. geo_obj.options['ymax'] = d
  1828. except Exception as e:
  1829. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1830. return
  1831. for tool_dia in sorted_tools:
  1832. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1833. app_obj.inform.emit(
  1834. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1835. str(tool_dia),
  1836. self.units.lower(),
  1837. _('started'))
  1838. )
  1839. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1840. painted_area = recurse(obj.solid_geometry)
  1841. # variables to display the percentage of work done
  1842. geo_len = len(painted_area)
  1843. disp_number = 0
  1844. old_disp_number = 0
  1845. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1846. pol_nr = 0
  1847. for geo in painted_area:
  1848. try:
  1849. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1850. poly_buf = geo.buffer(-paint_margin)
  1851. cp = None
  1852. if paint_method == "standard":
  1853. # Type(cp) == FlatCAMRTreeStorage | None
  1854. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1855. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1856. overlap=over, contour=cont, connect=conn)
  1857. elif paint_method == "seed":
  1858. # Type(cp) == FlatCAMRTreeStorage | None
  1859. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1860. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1861. overlap=over, contour=cont, connect=conn)
  1862. elif paint_method == "lines":
  1863. # Type(cp) == FlatCAMRTreeStorage | None
  1864. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1865. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1866. overlap=over, contour=cont, connect=conn)
  1867. if cp is not None:
  1868. cleared_geo += list(cp.get_objects())
  1869. except FlatCAMApp.GracefulException:
  1870. return "fail"
  1871. except Exception as e:
  1872. log.debug("Could not Paint the polygons. %s" % str(e))
  1873. self.app.inform.emit('[ERROR] %s' %
  1874. _("Could not do Paint All. Try a different combination of parameters. "
  1875. "Or a different Method of paint\n%s") % str(e))
  1876. return
  1877. pol_nr += 1
  1878. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 99]))
  1879. # log.debug("Polygons cleared: %d" % pol_nr)
  1880. if old_disp_number < disp_number <= 100:
  1881. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1882. old_disp_number = disp_number
  1883. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1884. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1885. for k, v in tools_storage.items():
  1886. if float('%.4f' % v['tooldia']) == float('%.4f' % tool_dia):
  1887. current_uid = int(k)
  1888. break
  1889. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  1890. # then reset the temporary list that stored that solid_geometry
  1891. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1892. tools_storage[current_uid]['data']['name'] = name
  1893. cleared_geo[:] = []
  1894. geo_obj.options["cnctooldia"] = str(tool_dia)
  1895. # this turn on the FlatCAMCNCJob plot for multiple tools
  1896. geo_obj.multigeo = True
  1897. geo_obj.multitool = True
  1898. geo_obj.tools.clear()
  1899. geo_obj.tools = dict(self.paint_tools)
  1900. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1901. has_solid_geo = 0
  1902. for tooluid in geo_obj.tools:
  1903. if geo_obj.tools[tooluid]['solid_geometry']:
  1904. has_solid_geo += 1
  1905. if has_solid_geo == 0:
  1906. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1907. _("There is no Painting Geometry in the file.\n"
  1908. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1909. "Change the painting parameters and try again."))
  1910. return
  1911. # Experimental...
  1912. # print("Indexing...", end=' ')
  1913. # geo_obj.make_index()
  1914. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  1915. def job_thread(app_obj):
  1916. try:
  1917. if self.rest_cb.isChecked():
  1918. app_obj.new_object("geometry", name, gen_paintarea_rest_machining)
  1919. else:
  1920. app_obj.new_object("geometry", name, gen_paintarea)
  1921. except FlatCAMApp.GracefulException:
  1922. proc.done()
  1923. return
  1924. except Exception as e:
  1925. proc.done()
  1926. traceback.print_stack()
  1927. return
  1928. proc.done()
  1929. # focus on Selected Tab
  1930. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1931. self.app.inform.emit(_("Polygon Paint started ..."))
  1932. # Promise object with the new name
  1933. self.app.collection.promise(name)
  1934. # Background
  1935. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1936. def paint_poly_ref(self, obj, sel_obj,
  1937. tooldia=None,
  1938. overlap=None,
  1939. order=None,
  1940. margin=None,
  1941. method=None,
  1942. outname=None,
  1943. connect=None,
  1944. contour=None,
  1945. tools_storage=None):
  1946. """
  1947. Paints all polygons in this object that are within the sel_obj object
  1948. :param obj: painted object
  1949. :param sel_obj: paint only what is inside this object bounds
  1950. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1951. :param overlap: value by which the paths will overlap
  1952. :param order: if the tools are ordered and how
  1953. :param margin: a border around painting area
  1954. :param outname: name of the resulting object
  1955. :param connect: Connect lines to avoid tool lifts.
  1956. :param contour: Paint around the edges.
  1957. :param method: choice out of 'seed', 'normal', 'lines'
  1958. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1959. Usage of the different one is related to when this function is called from a TcL command.
  1960. :return:
  1961. """
  1962. geo = sel_obj.solid_geometry
  1963. try:
  1964. if isinstance(geo, MultiPolygon):
  1965. env_obj = geo.convex_hull
  1966. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  1967. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  1968. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  1969. else:
  1970. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  1971. env_obj = env_obj.convex_hull
  1972. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  1973. except Exception as e:
  1974. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  1975. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  1976. return
  1977. self.paint_poly_area(obj=obj,
  1978. sel_obj=sel_rect,
  1979. tooldia=tooldia,
  1980. overlap=overlap,
  1981. order=order,
  1982. margin=margin,
  1983. method=method,
  1984. outname=outname,
  1985. connect=connect,
  1986. contour=contour,
  1987. tools_storage=tools_storage)
  1988. @staticmethod
  1989. def paint_bounds(geometry):
  1990. def bounds_rec(o):
  1991. if type(o) is list:
  1992. minx = Inf
  1993. miny = Inf
  1994. maxx = -Inf
  1995. maxy = -Inf
  1996. for k in o:
  1997. try:
  1998. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1999. except Exception as e:
  2000. log.debug("ToolPaint.bounds() --> %s" % str(e))
  2001. return
  2002. minx = min(minx, minx_)
  2003. miny = min(miny, miny_)
  2004. maxx = max(maxx, maxx_)
  2005. maxy = max(maxy, maxy_)
  2006. return minx, miny, maxx, maxy
  2007. else:
  2008. # it's a Shapely object, return it's bounds
  2009. return o.bounds
  2010. return bounds_rec(geometry)
  2011. def reset_fields(self):
  2012. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))