ToolPaint.py 109 KB

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