ToolPaint.py 115 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549
  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. self.decimals = 4
  23. FlatCAMTool.__init__(self, app)
  24. Geometry.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  25. # ## Title
  26. title_label = QtWidgets.QLabel("%s" % self.toolName)
  27. title_label.setStyleSheet("""
  28. QLabel
  29. {
  30. font-size: 16px;
  31. font-weight: bold;
  32. }
  33. """)
  34. self.layout.addWidget(title_label)
  35. self.tools_frame = QtWidgets.QFrame()
  36. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  37. self.layout.addWidget(self.tools_frame)
  38. self.tools_box = QtWidgets.QVBoxLayout()
  39. self.tools_box.setContentsMargins(0, 0, 0, 0)
  40. self.tools_frame.setLayout(self.tools_box)
  41. # ## Form Layout
  42. form_layout = QtWidgets.QFormLayout()
  43. self.tools_box.addLayout(form_layout)
  44. # ################################################
  45. # ##### Type of object to be painted #############
  46. # ################################################
  47. self.type_obj_combo = QtWidgets.QComboBox()
  48. self.type_obj_combo.addItem("Gerber")
  49. self.type_obj_combo.addItem("Excellon")
  50. self.type_obj_combo.addItem("Geometry")
  51. # we get rid of item1 ("Excellon") as it is not suitable
  52. self.type_obj_combo.view().setRowHidden(1, True)
  53. self.type_obj_combo.setItemIcon(0, QtGui.QIcon("share/flatcam_icon16.png"))
  54. self.type_obj_combo.setItemIcon(2, QtGui.QIcon("share/geometry16.png"))
  55. self.type_obj_combo_label = QtWidgets.QLabel('%s:' % _("Obj Type"))
  56. self.type_obj_combo_label.setToolTip(
  57. _("Specify the type of object to be painted.\n"
  58. "It can be of type: Gerber or Geometry.\n"
  59. "What is selected here will dictate the kind\n"
  60. "of objects that will populate the 'Object' combobox.")
  61. )
  62. self.type_obj_combo_label.setMinimumWidth(60)
  63. form_layout.addRow(self.type_obj_combo_label, self.type_obj_combo)
  64. # ################################################
  65. # ##### The object to be painted #################
  66. # ################################################
  67. self.obj_combo = QtWidgets.QComboBox()
  68. self.obj_combo.setModel(self.app.collection)
  69. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  70. self.obj_combo.setCurrentIndex(1)
  71. self.object_label = QtWidgets.QLabel('%s:' % _("Object"))
  72. self.object_label.setToolTip(_("Object to be painted."))
  73. form_layout.addRow(self.object_label, self.obj_combo)
  74. e_lab_0 = QtWidgets.QLabel('')
  75. form_layout.addRow(e_lab_0)
  76. # ### Tools ## ##
  77. self.tools_table_label = QtWidgets.QLabel('<b>%s</b>' % _('Tools Table'))
  78. self.tools_table_label.setToolTip(
  79. _("Tools pool from which the algorithm\n"
  80. "will pick the ones used for painting.")
  81. )
  82. self.tools_box.addWidget(self.tools_table_label)
  83. self.tools_table = FCTable()
  84. self.tools_box.addWidget(self.tools_table)
  85. self.tools_table.setColumnCount(4)
  86. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('TT'), ''])
  87. self.tools_table.setColumnHidden(3, True)
  88. # self.tools_table.setSortingEnabled(False)
  89. # self.tools_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  90. self.tools_table.horizontalHeaderItem(0).setToolTip(
  91. _("This is the Tool Number.\n"
  92. "Painting will start with the tool with the biggest diameter,\n"
  93. "continuing until there are no more tools.\n"
  94. "Only tools that create painting geometry will still be present\n"
  95. "in the resulting geometry. This is because with some tools\n"
  96. "this function will not be able to create painting geometry.")
  97. )
  98. self.tools_table.horizontalHeaderItem(1).setToolTip(
  99. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  100. "is the cut width into the material."))
  101. self.tools_table.horizontalHeaderItem(2).setToolTip(
  102. _("The Tool Type (TT) can be:<BR>"
  103. "- <B>Circular</B> with 1 ... 4 teeth -> it is informative only. Being circular, <BR>"
  104. "the cut width in material is exactly the tool diameter.<BR>"
  105. "- <B>Ball</B> -> informative only and make reference to the Ball type endmill.<BR>"
  106. "- <B>V-Shape</B> -> it will disable de Z-Cut parameter in the resulting geometry UI form "
  107. "and enable two additional UI form fields in the resulting geometry: V-Tip Dia and "
  108. "V-Tip Angle. Adjusting those two values will adjust the Z-Cut parameter such "
  109. "as the cut width into material will be equal with the value in the Tool Diameter "
  110. "column of this table.<BR>"
  111. "Choosing the <B>V-Shape</B> Tool Type automatically will select the Operation Type "
  112. "in the resulting geometry as Isolation."))
  113. self.order_label = QtWidgets.QLabel('<b>%s:</b>' % _('Tool order'))
  114. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  115. "'No' --> means that the used order is the one in the tool table\n"
  116. "'Forward' --> means that the tools will be ordered from small to big\n"
  117. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  118. "WARNING: using rest machining will automatically set the order\n"
  119. "in reverse and disable this control."))
  120. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  121. {'label': _('Forward'), 'value': 'fwd'},
  122. {'label': _('Reverse'), 'value': 'rev'}])
  123. self.order_radio.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  124. "'No' --> means that the used order is the one in the tool table\n"
  125. "'Forward' --> means that the tools will be ordered from small to big\n"
  126. "'Reverse' --> menas that the tools will ordered from big to small\n\n"
  127. "WARNING: using rest machining will automatically set the order\n"
  128. "in reverse and disable this control."))
  129. form = QtWidgets.QFormLayout()
  130. self.tools_box.addLayout(form)
  131. form.addRow(QtWidgets.QLabel(''), QtWidgets.QLabel(''))
  132. form.addRow(self.order_label, self.order_radio)
  133. # ### Add a new Tool ## ##
  134. self.addtool_entry_lbl = QtWidgets.QLabel('<b>%s:</b>' % _('Tool Dia'))
  135. self.addtool_entry_lbl.setToolTip(
  136. _("Diameter for the new tool.")
  137. )
  138. self.addtool_entry = FCDoubleSpinner()
  139. self.addtool_entry.set_precision(self.decimals)
  140. form.addRow(self.addtool_entry_lbl, self.addtool_entry)
  141. grid2 = QtWidgets.QGridLayout()
  142. self.tools_box.addLayout(grid2)
  143. self.addtool_btn = QtWidgets.QPushButton(_('Add'))
  144. self.addtool_btn.setToolTip(
  145. _("Add a new tool to the Tool Table\n"
  146. "with the diameter specified above.")
  147. )
  148. # self.copytool_btn = QtWidgets.QPushButton('Copy')
  149. # self.copytool_btn.setToolTip(
  150. # "Copy a selection of tools in the Tool Table\n"
  151. # "by first selecting a row in the Tool Table."
  152. # )
  153. self.deltool_btn = QtWidgets.QPushButton(_('Delete'))
  154. self.deltool_btn.setToolTip(
  155. _("Delete a selection of tools in the Tool Table\n"
  156. "by first selecting a row(s) in the Tool Table.")
  157. )
  158. grid2.addWidget(self.addtool_btn, 0, 0)
  159. # grid2.addWidget(self.copytool_btn, 0, 1)
  160. grid2.addWidget(self.deltool_btn, 0, 2)
  161. self.empty_label_0 = QtWidgets.QLabel('')
  162. self.tools_box.addWidget(self.empty_label_0)
  163. grid3 = QtWidgets.QGridLayout()
  164. self.tools_box.addLayout(grid3)
  165. grid3.setColumnStretch(0, 0)
  166. grid3.setColumnStretch(1, 1)
  167. # Overlap
  168. ovlabel = QtWidgets.QLabel('%s:' % _('Overlap Rate'))
  169. ovlabel.setToolTip(
  170. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  171. "Example:\n"
  172. "A value here of 0.25 means 25%% from the tool diameter found above.\n\n"
  173. "Adjust the value starting with lower values\n"
  174. "and increasing it if areas that should be painted are still \n"
  175. "not painted.\n"
  176. "Lower values = faster processing, faster execution on PCB.\n"
  177. "Higher values = slow processing and slow execution on CNC\n"
  178. "due of too many paths.")
  179. )
  180. self.paintoverlap_entry = FCDoubleSpinner()
  181. self.paintoverlap_entry.set_precision(3)
  182. self.paintoverlap_entry.setWrapping(True)
  183. self.paintoverlap_entry.setRange(0.000, 0.999)
  184. self.paintoverlap_entry.setSingleStep(0.1)
  185. grid3.addWidget(ovlabel, 1, 0)
  186. grid3.addWidget(self.paintoverlap_entry, 1, 1)
  187. # Margin
  188. marginlabel = QtWidgets.QLabel('%s:' % _('Margin'))
  189. marginlabel.setToolTip(
  190. _("Distance by which to avoid\n"
  191. "the edges of the polygon to\n"
  192. "be painted.")
  193. )
  194. grid3.addWidget(marginlabel, 2, 0)
  195. self.paintmargin_entry = FCDoubleSpinner()
  196. self.paintmargin_entry.set_precision(self.decimals)
  197. grid3.addWidget(self.paintmargin_entry, 2, 1)
  198. # Method
  199. methodlabel = QtWidgets.QLabel('%s:' % _('Method'))
  200. methodlabel.setToolTip(
  201. _("Algorithm for painting:\n"
  202. "- Standard: Fixed step inwards.\n"
  203. "- Seed-based: Outwards from seed.\n"
  204. "- Line-based: Parallel lines.")
  205. )
  206. grid3.addWidget(methodlabel, 3, 0)
  207. self.paintmethod_combo = RadioSet([
  208. {"label": _("Standard"), "value": "standard"},
  209. {"label": _("Seed-based"), "value": "seed"},
  210. {"label": _("Straight lines"), "value": "lines"}
  211. ], orientation='vertical', stretch=False)
  212. grid3.addWidget(self.paintmethod_combo, 3, 1)
  213. # Connect lines
  214. pathconnectlabel = QtWidgets.QLabel('%s:' % _("Connect"))
  215. pathconnectlabel.setToolTip(
  216. _("Draw lines between resulting\n"
  217. "segments to minimize tool lifts.")
  218. )
  219. grid3.addWidget(pathconnectlabel, 4, 0)
  220. self.pathconnect_cb = FCCheckBox()
  221. grid3.addWidget(self.pathconnect_cb, 4, 1)
  222. contourlabel = QtWidgets.QLabel('%s:' % _("Contour"))
  223. contourlabel.setToolTip(
  224. _("Cut around the perimeter of the polygon\n"
  225. "to trim rough edges.")
  226. )
  227. grid3.addWidget(contourlabel, 5, 0)
  228. self.paintcontour_cb = FCCheckBox()
  229. grid3.addWidget(self.paintcontour_cb, 5, 1)
  230. restlabel = QtWidgets.QLabel('%s:' % _("Rest M."))
  231. restlabel.setToolTip(
  232. _("If checked, use 'rest machining'.\n"
  233. "Basically it will clear copper outside PCB features,\n"
  234. "using the biggest tool and continue with the next tools,\n"
  235. "from bigger to smaller, to clear areas of copper that\n"
  236. "could not be cleared by previous tool, until there is\n"
  237. "no more copper to clear or there are no more tools.\n\n"
  238. "If not checked, use the standard algorithm.")
  239. )
  240. grid3.addWidget(restlabel, 6, 0)
  241. self.rest_cb = FCCheckBox()
  242. grid3.addWidget(self.rest_cb, 6, 1)
  243. # Polygon selection
  244. selectlabel = QtWidgets.QLabel('%s:' % _('Selection'))
  245. selectlabel.setToolTip(
  246. _("How to select Polygons to be painted.\n\n"
  247. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  248. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  249. "- 'All Polygons' - the Paint will start after click.\n"
  250. "- 'Reference Object' - will do non copper clearing within the area\n"
  251. "specified by another object.")
  252. )
  253. grid3.addWidget(selectlabel, 7, 0)
  254. # grid3 = QtWidgets.QGridLayout()
  255. self.selectmethod_combo = RadioSet([
  256. {"label": _("Single Polygon"), "value": "single"},
  257. {"label": _("Area Selection"), "value": "area"},
  258. {"label": _("All Polygons"), "value": "all"},
  259. {"label": _("Reference Object"), "value": "ref"}
  260. ], orientation='vertical', stretch=False)
  261. self.selectmethod_combo.setToolTip(
  262. _("How to select Polygons to be painted.\n\n"
  263. "- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  264. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  265. "- 'All Polygons' - the Paint will start after click.\n"
  266. "- 'Reference Object' - will do non copper clearing within the area\n"
  267. "specified by another object.")
  268. )
  269. grid3.addWidget(self.selectmethod_combo, 7, 1)
  270. form1 = QtWidgets.QFormLayout()
  271. self.tools_box.addLayout(form1)
  272. self.box_combo_type_label = QtWidgets.QLabel('%s:' % _("Ref. Type"))
  273. self.box_combo_type_label.setToolTip(
  274. _("The type of FlatCAM object to be used as paint reference.\n"
  275. "It can be Gerber, Excellon or Geometry.")
  276. )
  277. self.box_combo_type = QtWidgets.QComboBox()
  278. self.box_combo_type.addItem(_("Gerber Reference Box Object"))
  279. self.box_combo_type.addItem(_("Excellon Reference Box Object"))
  280. self.box_combo_type.addItem(_("Geometry Reference Box Object"))
  281. form1.addRow(self.box_combo_type_label, self.box_combo_type)
  282. self.box_combo_label = QtWidgets.QLabel('%s:' % _("Ref. Object"))
  283. self.box_combo_label.setToolTip(
  284. _("The FlatCAM object to be used as non copper clearing reference.")
  285. )
  286. self.box_combo = QtWidgets.QComboBox()
  287. self.box_combo.setModel(self.app.collection)
  288. self.box_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  289. self.box_combo.setCurrentIndex(1)
  290. form1.addRow(self.box_combo_label, self.box_combo)
  291. self.box_combo.hide()
  292. self.box_combo_label.hide()
  293. self.box_combo_type.hide()
  294. self.box_combo_type_label.hide()
  295. # GO Button
  296. self.generate_paint_button = QtWidgets.QPushButton(_('Create Paint Geometry'))
  297. self.generate_paint_button.setToolTip(
  298. _("- 'Area Selection' - left mouse click to start selection of the area to be painted.\n"
  299. "Keeping a modifier key pressed (CTRL or SHIFT) will allow to add multiple areas.\n"
  300. "- 'All Polygons' - the Paint will start after click.\n"
  301. "- 'Reference Object' - will do non copper clearing within the area\n"
  302. "specified by another object.")
  303. )
  304. self.tools_box.addWidget(self.generate_paint_button)
  305. self.tools_box.addStretch()
  306. self.obj_name = ""
  307. self.paint_obj = None
  308. self.bound_obj_name = ""
  309. self.bound_obj = None
  310. self.tooldia_list = []
  311. self.sel_rect = None
  312. self.o_name = None
  313. self.overlap = None
  314. self.connect = None
  315. self.contour = None
  316. self.units = ''
  317. self.paint_tools = {}
  318. self.tooluid = 0
  319. self.first_click = False
  320. self.cursor_pos = None
  321. self.mouse_is_dragging = False
  322. self.mm = None
  323. self.mp = None
  324. self.sel_rect = []
  325. # store here the default data for Geometry Data
  326. self.default_data = {}
  327. self.default_data.update({
  328. "name": '_paint',
  329. "plot": self.app.defaults["geometry_plot"],
  330. "cutz": self.app.defaults["geometry_cutz"],
  331. "vtipdia": 0.1,
  332. "vtipangle": 30,
  333. "travelz": self.app.defaults["geometry_travelz"],
  334. "feedrate": self.app.defaults["geometry_feedrate"],
  335. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  336. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  337. "dwell": self.app.defaults["geometry_dwell"],
  338. "dwelltime": self.app.defaults["geometry_dwelltime"],
  339. "multidepth": self.app.defaults["geometry_multidepth"],
  340. "ppname_g": self.app.defaults["geometry_ppname_g"],
  341. "depthperpass": self.app.defaults["geometry_depthperpass"],
  342. "extracut": self.app.defaults["geometry_extracut"],
  343. "toolchange": self.app.defaults["geometry_toolchange"],
  344. "toolchangez": self.app.defaults["geometry_toolchangez"],
  345. "endz": self.app.defaults["geometry_endz"],
  346. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  347. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  348. "startz": self.app.defaults["geometry_startz"],
  349. "tooldia": self.app.defaults["tools_painttooldia"],
  350. "paintmargin": self.app.defaults["tools_paintmargin"],
  351. "paintmethod": self.app.defaults["tools_paintmethod"],
  352. "selectmethod": self.app.defaults["tools_selectmethod"],
  353. "pathconnect": self.app.defaults["tools_pathconnect"],
  354. "paintcontour": self.app.defaults["tools_paintcontour"],
  355. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  356. })
  357. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  358. # ## Signals
  359. self.addtool_btn.clicked.connect(self.on_tool_add)
  360. self.addtool_entry.editingFinished.connect(self.on_tool_add)
  361. # self.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  362. self.tools_table.itemChanged.connect(self.on_tool_edit)
  363. self.deltool_btn.clicked.connect(self.on_tool_delete)
  364. self.generate_paint_button.clicked.connect(self.on_paint_button_click)
  365. self.selectmethod_combo.activated_custom.connect(self.on_radio_selection)
  366. self.order_radio.activated_custom[str].connect(self.on_order_changed)
  367. self.rest_cb.stateChanged.connect(self.on_rest_machining_check)
  368. self.box_combo_type.currentIndexChanged.connect(self.on_combo_box_type)
  369. self.type_obj_combo.currentIndexChanged.connect(self.on_type_obj_index_changed)
  370. def on_type_obj_index_changed(self, index):
  371. obj_type = self.type_obj_combo.currentIndex()
  372. self.obj_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  373. self.obj_combo.setCurrentIndex(0)
  374. def install(self, icon=None, separator=None, **kwargs):
  375. FlatCAMTool.install(self, icon, separator, shortcut='ALT+P', **kwargs)
  376. def run(self, toggle=True):
  377. self.app.report_usage("ToolPaint()")
  378. if toggle:
  379. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  380. if self.app.ui.splitter.sizes()[0] == 0:
  381. self.app.ui.splitter.setSizes([1, 1])
  382. else:
  383. try:
  384. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  385. # if tab is populated with the tool but it does not have the focus, focus on it
  386. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  387. # focus on Tool Tab
  388. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  389. else:
  390. self.app.ui.splitter.setSizes([0, 1])
  391. except AttributeError:
  392. pass
  393. else:
  394. if self.app.ui.splitter.sizes()[0] == 0:
  395. self.app.ui.splitter.setSizes([1, 1])
  396. FlatCAMTool.run(self)
  397. self.set_tool_ui()
  398. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  399. def reset_usage(self):
  400. self.obj_name = ""
  401. self.paint_obj = None
  402. self.bound_obj = None
  403. self.first_click = False
  404. self.cursor_pos = None
  405. self.mouse_is_dragging = False
  406. self.sel_rect = []
  407. def on_radio_selection(self):
  408. if self.selectmethod_combo.get_value() == "ref":
  409. self.box_combo.show()
  410. self.box_combo_label.show()
  411. self.box_combo_type.show()
  412. self.box_combo_type_label.show()
  413. else:
  414. self.box_combo.hide()
  415. self.box_combo_label.hide()
  416. self.box_combo_type.hide()
  417. self.box_combo_type_label.hide()
  418. if self.selectmethod_combo.get_value() == 'single':
  419. # disable rest-machining for single polygon painting
  420. self.rest_cb.set_value(False)
  421. self.rest_cb.setDisabled(True)
  422. # delete all tools except first row / tool for single polygon painting
  423. # list_to_del = list(range(1, self.tools_table.rowCount()))
  424. # if list_to_del:
  425. # self.on_tool_delete(rows_to_delete=list_to_del)
  426. # # disable addTool and delTool
  427. # self.addtool_entry.setDisabled(True)
  428. # self.addtool_btn.setDisabled(True)
  429. # self.deltool_btn.setDisabled(True)
  430. # self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  431. if self.selectmethod_combo.get_value() == 'area':
  432. # disable rest-machining for single polygon painting
  433. self.rest_cb.set_value(False)
  434. self.rest_cb.setDisabled(True)
  435. else:
  436. self.rest_cb.setDisabled(False)
  437. self.addtool_entry.setDisabled(False)
  438. self.addtool_btn.setDisabled(False)
  439. self.deltool_btn.setDisabled(False)
  440. self.tools_table.setContextMenuPolicy(Qt.ActionsContextMenu)
  441. def on_order_changed(self, order):
  442. if order != 'no':
  443. self.build_ui()
  444. def on_rest_machining_check(self, state):
  445. if state:
  446. self.order_radio.set_value('rev')
  447. self.order_label.setDisabled(True)
  448. self.order_radio.setDisabled(True)
  449. else:
  450. self.order_label.setDisabled(False)
  451. self.order_radio.setDisabled(False)
  452. def set_tool_ui(self):
  453. self.tools_frame.show()
  454. self.reset_fields()
  455. # ## Init the GUI interface
  456. self.order_radio.set_value(self.app.defaults["tools_paintorder"])
  457. self.paintmargin_entry.set_value(self.default_data["paintmargin"])
  458. self.paintmethod_combo.set_value(self.default_data["paintmethod"])
  459. self.selectmethod_combo.set_value(self.default_data["selectmethod"])
  460. self.pathconnect_cb.set_value(self.default_data["pathconnect"])
  461. self.paintcontour_cb.set_value(self.default_data["paintcontour"])
  462. self.paintoverlap_entry.set_value(self.default_data["paintoverlap"])
  463. # make the default object type, "Geometry"
  464. self.type_obj_combo.setCurrentIndex(2)
  465. # updated units
  466. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  467. if self.units == "IN":
  468. self.decimals = 4
  469. self.addtool_entry.set_value(0.039)
  470. else:
  471. self.decimals = 2
  472. self.addtool_entry.set_value(1)
  473. self.tools_table.setupContextMenu()
  474. self.tools_table.addContextMenu(
  475. "Add", lambda: self.on_tool_add(dia=None, muted=None), icon=QtGui.QIcon("share/plus16.png"))
  476. self.tools_table.addContextMenu(
  477. "Delete", lambda:
  478. self.on_tool_delete(rows_to_delete=None, all=None), icon=QtGui.QIcon("share/delete32.png"))
  479. # set the working variables to a known state
  480. self.paint_tools.clear()
  481. self.tooluid = 0
  482. self.default_data.clear()
  483. self.default_data.update({
  484. "name": '_paint',
  485. "plot": self.app.defaults["geometry_plot"],
  486. "cutz": self.app.defaults["geometry_cutz"],
  487. "vtipdia": 0.1,
  488. "vtipangle": 30,
  489. "travelz": self.app.defaults["geometry_travelz"],
  490. "feedrate": self.app.defaults["geometry_feedrate"],
  491. "feedrate_z": self.app.defaults["geometry_feedrate_z"],
  492. "feedrate_rapid": self.app.defaults["geometry_feedrate_rapid"],
  493. "dwell": self.app.defaults["geometry_dwell"],
  494. "dwelltime": self.app.defaults["geometry_dwelltime"],
  495. "multidepth": self.app.defaults["geometry_multidepth"],
  496. "ppname_g": self.app.defaults["geometry_ppname_g"],
  497. "depthperpass": self.app.defaults["geometry_depthperpass"],
  498. "extracut": self.app.defaults["geometry_extracut"],
  499. "toolchange": self.app.defaults["geometry_toolchange"],
  500. "toolchangez": self.app.defaults["geometry_toolchangez"],
  501. "endz": self.app.defaults["geometry_endz"],
  502. "spindlespeed": self.app.defaults["geometry_spindlespeed"],
  503. "toolchangexy": self.app.defaults["geometry_toolchangexy"],
  504. "startz": self.app.defaults["geometry_startz"],
  505. "tooldia": self.app.defaults["tools_painttooldia"],
  506. "paintmargin": self.app.defaults["tools_paintmargin"],
  507. "paintmethod": self.app.defaults["tools_paintmethod"],
  508. "selectmethod": self.app.defaults["tools_selectmethod"],
  509. "pathconnect": self.app.defaults["tools_pathconnect"],
  510. "paintcontour": self.app.defaults["tools_paintcontour"],
  511. "paintoverlap": self.app.defaults["tools_paintoverlap"]
  512. })
  513. # call on self.on_tool_add() counts as an call to self.build_ui()
  514. # through this, we add a initial row / tool in the tool_table
  515. self.on_tool_add(self.app.defaults["tools_painttooldia"], muted=True)
  516. # if the Paint Method is "Single" disable the tool table context menu
  517. if self.default_data["selectmethod"] == "single":
  518. self.tools_table.setContextMenuPolicy(Qt.NoContextMenu)
  519. def build_ui(self):
  520. try:
  521. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  522. self.tools_table.itemChanged.disconnect()
  523. except (TypeError, AttributeError):
  524. pass
  525. # updated units
  526. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  527. sorted_tools = []
  528. for k, v in self.paint_tools.items():
  529. sorted_tools.append(float('%.*f' % (self.decimals, float(v['tooldia']))))
  530. order = self.order_radio.get_value()
  531. if order == 'fwd':
  532. sorted_tools.sort(reverse=False)
  533. elif order == 'rev':
  534. sorted_tools.sort(reverse=True)
  535. else:
  536. pass
  537. n = len(sorted_tools)
  538. self.tools_table.setRowCount(n)
  539. tool_id = 0
  540. for tool_sorted in sorted_tools:
  541. for tooluid_key, tooluid_value in self.paint_tools.items():
  542. if float('%.*f' % (self.decimals, tooluid_value['tooldia'])) == tool_sorted:
  543. tool_id += 1
  544. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  545. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  546. row_no = tool_id - 1
  547. self.tools_table.setItem(row_no, 0, id) # Tool name/id
  548. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  549. # There are no drill bits in MM with more than 2 decimals diameter
  550. # For INCH the decimals should be no more than 4. There are no drills under 10mils
  551. dia = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, tooluid_value['tooldia']))
  552. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  553. tool_type_item = QtWidgets.QComboBox()
  554. for item in self.tool_type_item_options:
  555. tool_type_item.addItem(item)
  556. tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  557. idx = tool_type_item.findText(tooluid_value['tool_type'])
  558. tool_type_item.setCurrentIndex(idx)
  559. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tooluid_key)))
  560. self.tools_table.setItem(row_no, 1, dia) # Diameter
  561. self.tools_table.setCellWidget(row_no, 2, tool_type_item)
  562. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY # ##
  563. self.tools_table.setItem(row_no, 3, tool_uid_item) # Tool unique ID
  564. # make the diameter column editable
  565. for row in range(tool_id):
  566. self.tools_table.item(row, 1).setFlags(
  567. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  568. # all the tools are selected by default
  569. self.tools_table.selectColumn(0)
  570. #
  571. self.tools_table.resizeColumnsToContents()
  572. self.tools_table.resizeRowsToContents()
  573. vertical_header = self.tools_table.verticalHeader()
  574. vertical_header.hide()
  575. self.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  576. horizontal_header = self.tools_table.horizontalHeader()
  577. horizontal_header.setMinimumSectionSize(10)
  578. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  579. horizontal_header.resizeSection(0, 20)
  580. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  581. # self.tools_table.setSortingEnabled(True)
  582. # sort by tool diameter
  583. # self.tools_table.sortItems(1)
  584. self.tools_table.setMinimumHeight(self.tools_table.getHeight())
  585. self.tools_table.setMaximumHeight(self.tools_table.getHeight())
  586. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  587. self.tools_table.itemChanged.connect(self.on_tool_edit)
  588. def on_combo_box_type(self):
  589. obj_type = self.box_combo_type.currentIndex()
  590. self.box_combo.setRootModelIndex(self.app.collection.index(obj_type, 0, QtCore.QModelIndex()))
  591. self.box_combo.setCurrentIndex(0)
  592. def on_tool_add(self, dia=None, muted=None):
  593. try:
  594. self.tools_table.itemChanged.disconnect()
  595. except TypeError:
  596. pass
  597. if dia:
  598. tool_dia = dia
  599. else:
  600. try:
  601. tool_dia = float(self.addtool_entry.get_value())
  602. except ValueError:
  603. # try to convert comma to decimal point. if it's still not working error message and return
  604. try:
  605. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  606. except ValueError:
  607. self.app.inform.emit('[ERROR_NOTCL] %s' %
  608. _("Wrong value format entered, use a number."))
  609. return
  610. if tool_dia is None:
  611. self.build_ui()
  612. self.app.inform.emit('[WARNING_NOTCL] %s' %
  613. _("Please enter a tool diameter to add, in Float format."))
  614. return
  615. # construct a list of all 'tooluid' in the self.tools
  616. tool_uid_list = []
  617. for tooluid_key in self.paint_tools:
  618. tool_uid_item = int(tooluid_key)
  619. tool_uid_list.append(tool_uid_item)
  620. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  621. if not tool_uid_list:
  622. max_uid = 0
  623. else:
  624. max_uid = max(tool_uid_list)
  625. self.tooluid = int(max_uid + 1)
  626. tool_dias = []
  627. for k, v in self.paint_tools.items():
  628. for tool_v in v.keys():
  629. if tool_v == 'tooldia':
  630. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  631. if float('%.*f' % (self.decimals, tool_dia)) in tool_dias:
  632. if muted is None:
  633. self.app.inform.emit('[WARNING_NOTCL] %s' %
  634. _("Adding tool cancelled. Tool already in Tool Table."))
  635. self.tools_table.itemChanged.connect(self.on_tool_edit)
  636. return
  637. else:
  638. if muted is None:
  639. self.app.inform.emit('[success] %s' %
  640. _("New tool added to Tool Table."))
  641. self.paint_tools.update({
  642. int(self.tooluid): {
  643. 'tooldia': float('%.*f' % (self.decimals, tool_dia)),
  644. 'offset': 'Path',
  645. 'offset_value': 0.0,
  646. 'type': 'Iso',
  647. 'tool_type': 'V',
  648. 'data': dict(self.default_data),
  649. 'solid_geometry': []
  650. }
  651. })
  652. self.build_ui()
  653. def on_tool_edit(self):
  654. old_tool_dia = ''
  655. try:
  656. self.tools_table.itemChanged.disconnect()
  657. except TypeError:
  658. pass
  659. tool_dias = []
  660. for k, v in self.paint_tools.items():
  661. for tool_v in v.keys():
  662. if tool_v == 'tooldia':
  663. tool_dias.append(float('%.*f' % (self.decimals, v[tool_v])))
  664. for row in range(self.tools_table.rowCount()):
  665. try:
  666. new_tool_dia = float(self.tools_table.item(row, 1).text())
  667. except ValueError:
  668. # try to convert comma to decimal point. if it's still not working error message and return
  669. try:
  670. new_tool_dia = float(self.tools_table.item(row, 1).text().replace(',', '.'))
  671. except ValueError:
  672. self.app.inform.emit('[ERROR_NOTCL] %s' %
  673. _("Wrong value format entered, use a number."))
  674. return
  675. tooluid = int(self.tools_table.item(row, 3).text())
  676. # identify the tool that was edited and get it's tooluid
  677. if new_tool_dia not in tool_dias:
  678. self.paint_tools[tooluid]['tooldia'] = new_tool_dia
  679. self.app.inform.emit('[success] %s' %
  680. _("Tool from Tool Table was edited."))
  681. self.build_ui()
  682. return
  683. else:
  684. # identify the old tool_dia and restore the text in tool table
  685. for k, v in self.paint_tools.items():
  686. if k == tooluid:
  687. old_tool_dia = v['tooldia']
  688. break
  689. restore_dia_item = self.tools_table.item(row, 1)
  690. restore_dia_item.setText(str(old_tool_dia))
  691. self.app.inform.emit('[WARNING_NOTCL] %s' %
  692. _("Edit cancelled. New diameter value is already in the Tool Table."))
  693. self.build_ui()
  694. # def on_tool_copy(self, all=None):
  695. # try:
  696. # self.tools_table.itemChanged.disconnect()
  697. # except:
  698. # pass
  699. #
  700. # # find the tool_uid maximum value in the self.tools
  701. # uid_list = []
  702. # for key in self.paint_tools:
  703. # uid_list.append(int(key))
  704. # try:
  705. # max_uid = max(uid_list, key=int)
  706. # except ValueError:
  707. # max_uid = 0
  708. #
  709. # if all is None:
  710. # if self.tools_table.selectedItems():
  711. # for current_row in self.tools_table.selectedItems():
  712. # # sometime the header get selected and it has row number -1
  713. # # we don't want to do anything with the header :)
  714. # if current_row.row() < 0:
  715. # continue
  716. # try:
  717. # tooluid_copy = int(self.tools_table.item(current_row.row(), 3).text())
  718. # max_uid += 1
  719. # self.paint_tools[int(max_uid)] = dict(self.paint_tools[tooluid_copy])
  720. # for td in self.paint_tools:
  721. # print("COPIED", self.paint_tools[td])
  722. # self.build_ui()
  723. # except AttributeError:
  724. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  725. # self.build_ui()
  726. # return
  727. # except Exception as e:
  728. # log.debug("on_tool_copy() --> " + str(e))
  729. # # deselect the table
  730. # # self.ui.geo_tools_table.clearSelection()
  731. # else:
  732. # self.app.inform.emit("[WARNING_NOTCL] Failed. Select a tool to copy.")
  733. # self.build_ui()
  734. # return
  735. # else:
  736. # # we copy all tools in geo_tools_table
  737. # try:
  738. # temp_tools = dict(self.paint_tools)
  739. # max_uid += 1
  740. # for tooluid in temp_tools:
  741. # self.paint_tools[int(max_uid)] = dict(temp_tools[tooluid])
  742. # temp_tools.clear()
  743. # self.build_ui()
  744. # except Exception as e:
  745. # log.debug("on_tool_copy() --> " + str(e))
  746. #
  747. # self.app.inform.emit("[success] Tool was copied in the Tool Table.")
  748. def on_tool_delete(self, rows_to_delete=None, all=None):
  749. try:
  750. self.tools_table.itemChanged.disconnect()
  751. except TypeError:
  752. pass
  753. deleted_tools_list = []
  754. if all:
  755. self.paint_tools.clear()
  756. self.build_ui()
  757. return
  758. if rows_to_delete:
  759. try:
  760. for row in rows_to_delete:
  761. tooluid_del = int(self.tools_table.item(row, 3).text())
  762. deleted_tools_list.append(tooluid_del)
  763. except TypeError:
  764. deleted_tools_list.append(rows_to_delete)
  765. for t in deleted_tools_list:
  766. self.paint_tools.pop(t, None)
  767. self.build_ui()
  768. return
  769. try:
  770. if self.tools_table.selectedItems():
  771. for row_sel in self.tools_table.selectedItems():
  772. row = row_sel.row()
  773. if row < 0:
  774. continue
  775. tooluid_del = int(self.tools_table.item(row, 3).text())
  776. deleted_tools_list.append(tooluid_del)
  777. for t in deleted_tools_list:
  778. self.paint_tools.pop(t, None)
  779. except AttributeError:
  780. self.app.inform.emit('[WARNING_NOTCL] %s' %
  781. _("Delete failed. Select a tool to delete."))
  782. return
  783. except Exception as e:
  784. log.debug(str(e))
  785. self.app.inform.emit('[success] %s' %
  786. _("Tool(s) deleted from Tool Table."))
  787. self.build_ui()
  788. def on_paint_button_click(self):
  789. # init values for the next usage
  790. self.reset_usage()
  791. self.app.report_usage("on_paint_button_click")
  792. # self.app.call_source = 'paint'
  793. # #####################################################
  794. # ######### Reading Parameters ########################
  795. # #####################################################
  796. self.app.inform.emit(_("Paint Tool. Reading parameters."))
  797. try:
  798. self.overlap = float(self.paintoverlap_entry.get_value())
  799. except ValueError:
  800. # try to convert comma to decimal point. if it's still not working error message and return
  801. try:
  802. self.overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  803. except ValueError:
  804. self.app.inform.emit('[ERROR_NOTCL] %s' %
  805. _("Wrong value format entered, use a number."))
  806. return
  807. if self.overlap >= 1 or self.overlap < 0:
  808. self.app.inform.emit('[ERROR_NOTCL] %s' %
  809. _("Overlap value must be between 0 (inclusive) and 1 (exclusive)"))
  810. return
  811. self.app.inform.emit('[WARNING_NOTCL] %s' %
  812. _("Click inside the desired polygon."))
  813. self.connect = self.pathconnect_cb.get_value()
  814. self.contour = self.paintcontour_cb.get_value()
  815. self.select_method = self.selectmethod_combo.get_value()
  816. self.obj_name = self.obj_combo.currentText()
  817. # Get source object.
  818. try:
  819. self.paint_obj = self.app.collection.get_by_name(str(self.obj_name))
  820. except Exception as e:
  821. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  822. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  823. (_("Could not retrieve object: %s"),
  824. self.obj_name))
  825. return
  826. if self.paint_obj is None:
  827. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  828. (_("Object not found"),
  829. self.paint_obj))
  830. return
  831. # test if the Geometry Object is multigeo and return Fail if True because
  832. # for now Paint don't work on MultiGeo
  833. if self.paint_obj.multigeo is True:
  834. self.app.inform.emit('[ERROR_NOTCL] %s...' %
  835. _("Can't do Paint on MultiGeo geometries"))
  836. return 'Fail'
  837. o_name = '%s_multitool_paint' % self.obj_name
  838. # use the selected tools in the tool table; get diameters
  839. self.tooldia_list = list()
  840. if self.tools_table.selectedItems():
  841. for x in self.tools_table.selectedItems():
  842. try:
  843. self.tooldia = float(self.tools_table.item(x.row(), 1).text())
  844. except ValueError:
  845. # try to convert comma to decimal point. if it's still not working error message and return
  846. try:
  847. self.tooldia = float(self.tools_table.item(x.row(), 1).text().replace(',', '.'))
  848. except ValueError:
  849. self.app.inform.emit('[ERROR_NOTCL] %s' %
  850. _("Wrong value format entered, use a number."))
  851. continue
  852. self.tooldia_list.append(self.tooldia)
  853. else:
  854. self.app.inform.emit('[ERROR_NOTCL] %s' %
  855. _("No selected tools in Tool Table."))
  856. return
  857. if self.select_method == "all":
  858. self.paint_poly_all(self.paint_obj,
  859. tooldia=self.tooldia_list,
  860. outname=self.o_name,
  861. overlap=self.overlap,
  862. connect=self.connect,
  863. contour=self.contour)
  864. elif self.select_method == "single":
  865. self.app.inform.emit('[WARNING_NOTCL] %s' %
  866. _("Click inside the desired polygon."))
  867. # use the first tool in the tool table; get the diameter
  868. # tooldia = float('%.4f' % float(self.tools_table.item(0, 1).text()))
  869. # To be called after clicking on the plot.
  870. def doit(event):
  871. # do paint single only for left mouse clicks
  872. if event.button == 1:
  873. self.app.inform.emit(_("Painting polygon..."))
  874. if self.app.is_legacy:
  875. self.app.plotcanvas.graph_event_disconnect('mouse_press', doit)
  876. else:
  877. self.app.plotcanvas.graph_event_disconnect(self.mp)
  878. pos = self.app.plotcanvas.translate_coords(event.pos)
  879. if self.app.grid_status() == True:
  880. pos = self.app.geo_editor.snap(pos[0], pos[1])
  881. self.paint_poly(self.paint_obj,
  882. inside_pt=[pos[0], pos[1]],
  883. tooldia=self.tooldia_list,
  884. overlap=self.overlap,
  885. connect=self.connect,
  886. contour=self.contour)
  887. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  888. self.app.on_mouse_click_over_plot)
  889. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  890. self.app.on_mouse_click_release_over_plot)
  891. if self.app.is_legacy is False:
  892. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  893. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  894. else:
  895. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  896. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  897. self.mp = self.app.plotcanvas.graph_event_connect('mouse_press', doit)
  898. elif self.select_method == "area":
  899. self.app.inform.emit('[WARNING_NOTCL] %s' %
  900. _("Click the start point of the paint area."))
  901. if self.app.is_legacy is False:
  902. self.app.plotcanvas.graph_event_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  903. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  904. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  905. else:
  906. self.app.plotcanvas.graph_event_disconnect(self.app.mp)
  907. self.app.plotcanvas.graph_event_disconnect(self.app.mm)
  908. self.app.plotcanvas.graph_event_disconnect(self.app.mr)
  909. self.mr = self.app.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_release)
  910. self.mm = self.app.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move)
  911. elif self.select_method == 'ref':
  912. self.bound_obj_name = self.box_combo.currentText()
  913. # Get source object.
  914. try:
  915. self.bound_obj = self.app.collection.get_by_name(self.bound_obj_name)
  916. except Exception as e:
  917. self.app.inform.emit('[ERROR_NOTCL] %s: %s' %
  918. (_("Could not retrieve object"),
  919. self.obj_name))
  920. return "Could not retrieve object: %s" % self.obj_name
  921. self.paint_poly_ref(obj=self.paint_obj,
  922. sel_obj=self.bound_obj,
  923. tooldia=self.tooldia_list,
  924. overlap=self.overlap,
  925. outname=self.o_name,
  926. connect=self.connect,
  927. contour=self.contour)
  928. # To be called after clicking on the plot.
  929. def on_mouse_release(self, event):
  930. if self.app.is_legacy is False:
  931. event_pos = event.pos
  932. event_is_dragging = event.is_dragging
  933. right_button = 2
  934. else:
  935. event_pos = (event.xdata, event.ydata)
  936. event_is_dragging = self.app.plotcanvas.is_dragging
  937. right_button = 3
  938. try:
  939. x = float(event_pos[0])
  940. y = float(event_pos[1])
  941. except TypeError:
  942. return
  943. event_pos = (x, y)
  944. # do paint single only for left mouse clicks
  945. if event.button == 1:
  946. if not self.first_click:
  947. self.first_click = True
  948. self.app.inform.emit('[WARNING_NOTCL] %s' %
  949. _("Click the end point of the paint area."))
  950. self.cursor_pos = self.app.plotcanvas.translate_coords(event_pos)
  951. if self.app.grid_status() == True:
  952. self.cursor_pos = self.app.geo_editor.snap(self.cursor_pos[0], self.cursor_pos[1])
  953. else:
  954. self.app.inform.emit(_("Zone added. Click to start adding next zone or right click to finish."))
  955. self.app.delete_selection_shape()
  956. curr_pos = self.app.plotcanvas.translate_coords(event_pos)
  957. if self.app.grid_status() == True:
  958. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  959. x0, y0 = self.cursor_pos[0], self.cursor_pos[1]
  960. x1, y1 = curr_pos[0], curr_pos[1]
  961. pt1 = (x0, y0)
  962. pt2 = (x1, y0)
  963. pt3 = (x1, y1)
  964. pt4 = (x0, y1)
  965. self.sel_rect.append(Polygon([pt1, pt2, pt3, pt4]))
  966. self.first_click = False
  967. return
  968. elif event.button == right_button and self.mouse_is_dragging is False:
  969. self.first_click = False
  970. if self.app.is_legacy is False:
  971. self.app.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_release)
  972. self.app.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move)
  973. else:
  974. self.app.plotcanvas.graph_event_disconnect(self.mr)
  975. self.app.plotcanvas.graph_event_disconnect(self.mm)
  976. self.app.mp = self.app.plotcanvas.graph_event_connect('mouse_press',
  977. self.app.on_mouse_click_over_plot)
  978. self.app.mm = self.app.plotcanvas.graph_event_connect('mouse_move',
  979. self.app.on_mouse_move_over_plot)
  980. self.app.mr = self.app.plotcanvas.graph_event_connect('mouse_release',
  981. self.app.on_mouse_click_release_over_plot)
  982. if len(self.sel_rect) == 0:
  983. return
  984. self.sel_rect = cascaded_union(self.sel_rect)
  985. self.paint_poly_area(obj=self.paint_obj,
  986. tooldia=self.tooldia_list,
  987. sel_obj=self.sel_rect,
  988. outname=self.o_name,
  989. overlap=self.overlap,
  990. connect=self.connect,
  991. contour=self.contour)
  992. # called on mouse move
  993. def on_mouse_move(self, event):
  994. if self.app.is_legacy is False:
  995. event_pos = event.pos
  996. event_is_dragging = event.is_dragging
  997. right_button = 2
  998. else:
  999. event_pos = (event.xdata, event.ydata)
  1000. event_is_dragging = self.app.plotcanvas.is_dragging
  1001. right_button = 3
  1002. try:
  1003. x = float(event_pos[0])
  1004. y = float(event_pos[1])
  1005. except TypeError:
  1006. return
  1007. curr_pos = self.app.plotcanvas.translate_coords((x, y))
  1008. # detect mouse dragging motion
  1009. if event_is_dragging == 1:
  1010. self.mouse_is_dragging = True
  1011. else:
  1012. self.mouse_is_dragging = False
  1013. # update the cursor position
  1014. if self.app.grid_status() == True:
  1015. # Update cursor
  1016. curr_pos = self.app.geo_editor.snap(curr_pos[0], curr_pos[1])
  1017. self.app.app_cursor.set_data(np.asarray([(curr_pos[0], curr_pos[1])]),
  1018. symbol='++', edge_color='black', size=self.app.defaults["global_cursor_size"])
  1019. # update the positions on status bar
  1020. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  1021. "<b>Y</b>: %.4f" % (curr_pos[0], curr_pos[1]))
  1022. if self.cursor_pos is None:
  1023. self.cursor_pos = (0, 0)
  1024. dx = curr_pos[0] - float(self.cursor_pos[0])
  1025. dy = curr_pos[1] - float(self.cursor_pos[1])
  1026. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  1027. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  1028. # draw the utility geometry
  1029. if self.first_click:
  1030. self.app.delete_selection_shape()
  1031. self.app.draw_moving_selection_shape(old_coords=(self.cursor_pos[0], self.cursor_pos[1]),
  1032. coords=(curr_pos[0], curr_pos[1]))
  1033. def paint_poly(self, obj,
  1034. inside_pt=None,
  1035. tooldia=None,
  1036. overlap=None,
  1037. order=None,
  1038. margin=None,
  1039. method=None,
  1040. outname=None,
  1041. connect=None,
  1042. contour=None,
  1043. tools_storage=None,
  1044. plot=True,
  1045. run_threaded=True):
  1046. """
  1047. Paints a polygon selected by clicking on its interior or by having a point coordinates given
  1048. Note:
  1049. * The margin is taken directly from the form.
  1050. :param obj: painted object
  1051. :param inside_pt: [x, y]
  1052. :param tooldia: Diameter of the painting tool
  1053. :param overlap: Overlap of the tool between passes.
  1054. :param order: if the tools are ordered and how
  1055. :param margin: a border around painting area
  1056. :param outname: Name of the resulting Geometry Object.
  1057. :param connect: Connect lines to avoid tool lifts.
  1058. :param contour: Paint around the edges.
  1059. :param method: choice out of 'seed', 'normal', 'lines'
  1060. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1061. Usage of the different one is related to when this function is called from a TcL command.
  1062. :return: None
  1063. """
  1064. # Which polygon.
  1065. # poly = find_polygon(self.solid_geometry, inside_pt)
  1066. if isinstance(obj, FlatCAMGerber):
  1067. if self.app.defaults["gerber_buffering"] == 'no':
  1068. self.app.inform.emit('%s %s %s' %
  1069. (_("Paint Tool."), _("Normal painting polygon task started."),
  1070. _("Buffering geometry...")))
  1071. else:
  1072. self.app.inform.emit('%s %s' %
  1073. (_("Paint Tool."), _("Normal painting polygon task started.")))
  1074. else:
  1075. self.app.inform.emit('%s %s' %
  1076. (_("Paint Tool."), _("Normal painting polygon task started.")))
  1077. if isinstance(obj, FlatCAMGerber):
  1078. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1079. if isinstance(obj.solid_geometry, list):
  1080. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1081. else:
  1082. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1083. poly = self.find_polygon(point=inside_pt, geoset=obj.solid_geometry)
  1084. paint_method = method if method is None else self.paintmethod_combo.get_value()
  1085. if margin is not None:
  1086. paint_margin = margin
  1087. else:
  1088. try:
  1089. paint_margin = float(self.paintmargin_entry.get_value())
  1090. except ValueError:
  1091. # try to convert comma to decimal point. if it's still not working error message and return
  1092. try:
  1093. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1094. except ValueError:
  1095. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1096. _("Wrong value format entered, use a number."))
  1097. return
  1098. # determine if to use the progressive plotting
  1099. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1100. prog_plot = True
  1101. else:
  1102. prog_plot = False
  1103. # No polygon?
  1104. if poly is None:
  1105. self.app.log.warning('No polygon found.')
  1106. self.app.inform.emit('[WARNING] %s' % _('No polygon found.'))
  1107. return
  1108. proc = self.app.proc_container.new(_("Painting polygon..."))
  1109. self.app.inform.emit('%s %s: %s' %
  1110. (_("Paint Tool."), _("Painting polygon at location"), str(inside_pt)))
  1111. name = outname if outname is not None else self.obj_name + "_paint"
  1112. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1113. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1114. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1115. order = order if order is not None else self.order_radio.get_value()
  1116. sorted_tools = []
  1117. if tooldia is not None:
  1118. try:
  1119. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1120. except AttributeError:
  1121. if not isinstance(tooldia, list):
  1122. sorted_tools = [float(tooldia)]
  1123. else:
  1124. sorted_tools = tooldia
  1125. else:
  1126. for row in range(self.tools_table.rowCount()):
  1127. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1128. if tools_storage is not None:
  1129. tools_storage = tools_storage
  1130. else:
  1131. tools_storage = self.paint_tools
  1132. # Initializes the new geometry object
  1133. def gen_paintarea(geo_obj, app_obj):
  1134. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1135. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1136. # assert isinstance(app_obj, App)
  1137. tool_dia = None
  1138. if order == 'fwd':
  1139. sorted_tools.sort(reverse=False)
  1140. elif order == 'rev':
  1141. sorted_tools.sort(reverse=True)
  1142. else:
  1143. pass
  1144. def paint_p(polyg, tooldiameter):
  1145. cpoly = None
  1146. try:
  1147. if paint_method == "seed":
  1148. # Type(cp) == FlatCAMRTreeStorage | None
  1149. cpoly = self.clear_polygon2(polyg,
  1150. tooldia=tooldiameter,
  1151. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1152. overlap=over,
  1153. contour=cont,
  1154. connect=conn,
  1155. prog_plot=prog_plot)
  1156. elif paint_method == "lines":
  1157. # Type(cp) == FlatCAMRTreeStorage | None
  1158. cpoly = self.clear_polygon3(polyg,
  1159. tooldia=tooldiameter,
  1160. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1161. overlap=over,
  1162. contour=cont,
  1163. connect=conn,
  1164. prog_plot=prog_plot)
  1165. else:
  1166. # Type(cp) == FlatCAMRTreeStorage | None
  1167. cpoly = self.clear_polygon(polyg,
  1168. tooldia=tooldiameter,
  1169. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1170. overlap=over,
  1171. contour=cont,
  1172. connect=conn,
  1173. prog_plot=prog_plot)
  1174. except FlatCAMApp.GracefulException:
  1175. return "fail"
  1176. except Exception as e:
  1177. log.debug("ToolPaint.paint_poly().gen_paintarea().paint_p() --> %s" % str(e))
  1178. if cpoly is not None:
  1179. geo_obj.solid_geometry += list(cpoly.get_objects())
  1180. return cpoly
  1181. else:
  1182. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  1183. _('Geometry could not be painted completely'))
  1184. return None
  1185. try:
  1186. a, b, c, d = poly.bounds
  1187. geo_obj.options['xmin'] = a
  1188. geo_obj.options['ymin'] = b
  1189. geo_obj.options['xmax'] = c
  1190. geo_obj.options['ymax'] = d
  1191. except Exception as e:
  1192. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1193. return
  1194. total_geometry = []
  1195. current_uid = int(1)
  1196. geo_obj.solid_geometry = []
  1197. for tool_dia in sorted_tools:
  1198. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1199. for k, v in tools_storage.items():
  1200. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1201. current_uid = int(k)
  1202. break
  1203. try:
  1204. poly_buf = poly.buffer(-paint_margin)
  1205. if isinstance(poly_buf, MultiPolygon):
  1206. cp = []
  1207. for pp in poly_buf:
  1208. cp.append(paint_p(pp, tooldia=tool_dia))
  1209. else:
  1210. cp = paint_p(poly_buf, tooldia=tool_dia)
  1211. if cp is not None:
  1212. if isinstance(cp, list):
  1213. for x in cp:
  1214. total_geometry += list(x.get_objects())
  1215. else:
  1216. total_geometry = list(cp.get_objects())
  1217. except FlatCAMApp.GracefulException:
  1218. return "fail"
  1219. except Exception as e:
  1220. log.debug("Could not Paint the polygons. %s" % str(e))
  1221. app_obj.inform.emit('[ERROR] %s\n%s' %
  1222. (_("Could not do Paint. Try a different combination of parameters. "
  1223. "Or a different strategy of paint"),
  1224. str(e)
  1225. )
  1226. )
  1227. return "fail"
  1228. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1229. # dictionary and then reset the temporary list that stored that solid_geometry
  1230. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1231. tools_storage[current_uid]['data']['name'] = name
  1232. total_geometry[:] = []
  1233. # clean the progressive plotted shapes if it was used
  1234. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1235. self.temp_shapes.clear(update=True)
  1236. # delete tools with empty geometry
  1237. keys_to_delete = []
  1238. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1239. for uid in tools_storage:
  1240. # if the solid_geometry (type=list) is empty
  1241. if not tools_storage[uid]['solid_geometry']:
  1242. keys_to_delete.append(uid)
  1243. # actual delete of keys from the tools_storage dict
  1244. for k in keys_to_delete:
  1245. tools_storage.pop(k, None)
  1246. geo_obj.options["cnctooldia"] = str(tool_dia)
  1247. # this turn on the FlatCAMCNCJob plot for multiple tools
  1248. geo_obj.multigeo = True
  1249. geo_obj.multitool = True
  1250. geo_obj.tools.clear()
  1251. geo_obj.tools = dict(tools_storage)
  1252. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1253. has_solid_geo = 0
  1254. for tooluid in geo_obj.tools:
  1255. if geo_obj.tools[tooluid]['solid_geometry']:
  1256. has_solid_geo += 1
  1257. if has_solid_geo == 0:
  1258. self.app.inform.emit('[ERROR] %s' %
  1259. _("There is no Painting Geometry in the file.\n"
  1260. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1261. "Change the painting parameters and try again."))
  1262. return
  1263. self.app.inform.emit('[success] %s' % _("Paint Single Done."))
  1264. # Experimental...
  1265. # print("Indexing...", end=' ')
  1266. # geo_obj.make_index()
  1267. # if errors == 0:
  1268. # print("[success] Paint single polygon Done")
  1269. # self.app.inform.emit("[success] Paint single polygon Done")
  1270. # else:
  1271. # print("[WARNING] Paint single polygon done with errors")
  1272. # self.app.inform.emit("[WARNING] Paint single polygon done with errors. "
  1273. # "%d area(s) could not be painted.\n"
  1274. # "Use different paint parameters or edit the paint geometry and correct"
  1275. # "the issue."
  1276. # % errors)
  1277. def job_thread(app_obj):
  1278. try:
  1279. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  1280. except FlatCAMApp.GracefulException:
  1281. proc.done()
  1282. return
  1283. except Exception as e:
  1284. proc.done()
  1285. self.app.inform.emit('[ERROR_NOTCL] %s --> %s' %
  1286. ('PaintTool.paint_poly()',
  1287. str(e)))
  1288. return
  1289. proc.done()
  1290. # focus on Selected Tab
  1291. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1292. self.app.inform.emit(_("Polygon Paint started ..."))
  1293. # Promise object with the new name
  1294. self.app.collection.promise(name)
  1295. if run_threaded:
  1296. # Background
  1297. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1298. else:
  1299. job_thread(app_obj=self.app)
  1300. def paint_poly_all(self, obj,
  1301. tooldia=None,
  1302. overlap=None,
  1303. order=None,
  1304. margin=None,
  1305. method=None,
  1306. outname=None,
  1307. connect=None,
  1308. contour=None,
  1309. tools_storage=None,
  1310. plot=True,
  1311. run_threaded=True):
  1312. """
  1313. Paints all polygons in this object.
  1314. :param obj: painted object
  1315. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1316. :param overlap: value by which the paths will overlap
  1317. :param order: if the tools are ordered and how
  1318. :param margin: a border around painting area
  1319. :param outname: name of the resulting object
  1320. :param connect: Connect lines to avoid tool lifts.
  1321. :param contour: Paint around the edges.
  1322. :param method: choice out of 'seed', 'normal', 'lines'
  1323. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1324. Usage of the different one is related to when this function is called from a TcL command.
  1325. :return:
  1326. """
  1327. paint_method = method if method is None else self.paintmethod_combo.get_value()
  1328. if margin is not None:
  1329. paint_margin = margin
  1330. else:
  1331. try:
  1332. paint_margin = float(self.paintmargin_entry.get_value())
  1333. except ValueError:
  1334. # try to convert comma to decimal point. if it's still not working error message and return
  1335. try:
  1336. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1337. except ValueError:
  1338. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1339. _("Wrong value format entered, use a number."))
  1340. return
  1341. # determine if to use the progressive plotting
  1342. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1343. prog_plot = True
  1344. else:
  1345. prog_plot = False
  1346. proc = self.app.proc_container.new(_("Painting polygons..."))
  1347. name = outname if outname is not None else self.obj_name + "_paint"
  1348. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1349. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1350. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1351. order = order if order is not None else self.order_radio.get_value()
  1352. sorted_tools = []
  1353. if tooldia is not None:
  1354. try:
  1355. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1356. except AttributeError:
  1357. if not isinstance(tooldia, list):
  1358. sorted_tools = [float(tooldia)]
  1359. else:
  1360. sorted_tools = tooldia
  1361. else:
  1362. for row in range(self.tools_table.rowCount()):
  1363. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1364. if tools_storage is not None:
  1365. tools_storage = tools_storage
  1366. else:
  1367. tools_storage = self.paint_tools
  1368. # This is a recursive generator of individual Polygons.
  1369. # Note: Double check correct implementation. Might exit
  1370. # early if it finds something that is not a Polygon?
  1371. # def recurse(geo):
  1372. # try:
  1373. # for subg in geo:
  1374. # for subsubg in recurse(subg):
  1375. # yield subsubg
  1376. # except TypeError:
  1377. # if isinstance(geo, Polygon):
  1378. # yield geo
  1379. #
  1380. # raise StopIteration
  1381. def recurse(geometry, reset=True):
  1382. """
  1383. Creates a list of non-iterable linear geometry objects.
  1384. Results are placed in self.flat_geometry
  1385. :param geometry: Shapely type or list or list of list of such.
  1386. :param reset: Clears the contents of self.flat_geometry.
  1387. """
  1388. if self.app.abort_flag:
  1389. # graceful abort requested by the user
  1390. raise FlatCAMApp.GracefulException
  1391. if geometry is None:
  1392. return
  1393. if reset:
  1394. self.flat_geometry = []
  1395. # ## If iterable, expand recursively.
  1396. try:
  1397. for geo in geometry:
  1398. if geo is not None:
  1399. recurse(geometry=geo, reset=False)
  1400. # ## Not iterable, do the actual indexing and add.
  1401. except TypeError:
  1402. if isinstance(geometry, LinearRing):
  1403. g = Polygon(geometry)
  1404. self.flat_geometry.append(g)
  1405. else:
  1406. self.flat_geometry.append(geometry)
  1407. return self.flat_geometry
  1408. # Initializes the new geometry object
  1409. def gen_paintarea(geo_obj, app_obj):
  1410. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1411. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1412. log.debug("Paint Tool. Normal painting all task started.")
  1413. if isinstance(obj, FlatCAMGerber):
  1414. if app_obj.defaults["gerber_buffering"] == 'no':
  1415. app_obj.inform.emit('%s %s' %
  1416. (_("Paint Tool. Normal painting all task started."),
  1417. _("Buffering geometry...")))
  1418. else:
  1419. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1420. else:
  1421. app_obj.inform.emit(_("Paint Tool. Normal painting all task started."))
  1422. tool_dia = None
  1423. if order == 'fwd':
  1424. sorted_tools.sort(reverse=False)
  1425. elif order == 'rev':
  1426. sorted_tools.sort(reverse=True)
  1427. else:
  1428. pass
  1429. if isinstance(obj, FlatCAMGerber):
  1430. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1431. if isinstance(obj.solid_geometry, list):
  1432. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1433. else:
  1434. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1435. try:
  1436. a, b, c, d = obj.bounds()
  1437. geo_obj.options['xmin'] = a
  1438. geo_obj.options['ymin'] = b
  1439. geo_obj.options['xmax'] = c
  1440. geo_obj.options['ymax'] = d
  1441. except Exception as e:
  1442. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1443. return
  1444. total_geometry = []
  1445. current_uid = int(1)
  1446. geo_obj.solid_geometry = []
  1447. for tool_dia in sorted_tools:
  1448. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1449. app_obj.inform.emit(
  1450. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1451. str(tool_dia),
  1452. self.units.lower(),
  1453. _('started'))
  1454. )
  1455. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1456. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1457. for k, v in tools_storage.items():
  1458. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1459. current_uid = int(k)
  1460. break
  1461. painted_area = recurse(obj.solid_geometry)
  1462. # variables to display the percentage of work done
  1463. geo_len = len(painted_area)
  1464. old_disp_number = 0
  1465. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1466. pol_nr = 0
  1467. for geo in painted_area:
  1468. try:
  1469. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1470. if not isinstance(geo, Polygon):
  1471. continue
  1472. poly_buf = geo.buffer(-paint_margin)
  1473. if paint_method == "seed":
  1474. # Type(cp) == FlatCAMRTreeStorage | None
  1475. cp = self.clear_polygon2(poly_buf,
  1476. tooldia=tool_dia,
  1477. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1478. overlap=over,
  1479. contour=cont,
  1480. connect=conn,
  1481. prog_plot=prog_plot)
  1482. elif paint_method == "lines":
  1483. # Type(cp) == FlatCAMRTreeStorage | None
  1484. cp = self.clear_polygon3(poly_buf,
  1485. tooldia=tool_dia,
  1486. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1487. overlap=over,
  1488. contour=cont,
  1489. connect=conn,
  1490. prog_plot=prog_plot)
  1491. else:
  1492. # Type(cp) == FlatCAMRTreeStorage | None
  1493. cp = self.clear_polygon(poly_buf,
  1494. tooldia=tool_dia,
  1495. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1496. overlap=over,
  1497. contour=cont,
  1498. connect=conn,
  1499. prog_plot=prog_plot)
  1500. if cp is not None:
  1501. total_geometry += list(cp.get_objects())
  1502. except FlatCAMApp.GracefulException:
  1503. return "fail"
  1504. except Exception as e:
  1505. log.debug("Could not Paint the polygons. %s" % str(e))
  1506. self.app.inform.emit('[ERROR] %s\n%s' %
  1507. (_("Could not do Paint All. Try a different combination of parameters. "
  1508. "Or a different Method of paint"),
  1509. str(e)))
  1510. return "fail"
  1511. pol_nr += 1
  1512. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1513. # log.debug("Polygons cleared: %d" % pol_nr)
  1514. if old_disp_number < disp_number <= 100:
  1515. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1516. old_disp_number = disp_number
  1517. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1518. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1519. # dictionary and then reset the temporary list that stored that solid_geometry
  1520. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1521. tools_storage[current_uid]['data']['name'] = name
  1522. total_geometry[:] = []
  1523. # clean the progressive plotted shapes if it was used
  1524. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1525. self.temp_shapes.clear(update=True)
  1526. # delete tools with empty geometry
  1527. keys_to_delete = []
  1528. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1529. for uid in tools_storage:
  1530. # if the solid_geometry (type=list) is empty
  1531. if not tools_storage[uid]['solid_geometry']:
  1532. keys_to_delete.append(uid)
  1533. # actual delete of keys from the tools_storage dict
  1534. for k in keys_to_delete:
  1535. tools_storage.pop(k, None)
  1536. geo_obj.options["cnctooldia"] = str(tool_dia)
  1537. # this turn on the FlatCAMCNCJob plot for multiple tools
  1538. geo_obj.multigeo = True
  1539. geo_obj.multitool = True
  1540. geo_obj.tools.clear()
  1541. geo_obj.tools = dict(tools_storage)
  1542. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1543. has_solid_geo = 0
  1544. for tooluid in geo_obj.tools:
  1545. if geo_obj.tools[tooluid]['solid_geometry']:
  1546. has_solid_geo += 1
  1547. if has_solid_geo == 0:
  1548. self.app.inform.emit('[ERROR] %s' %
  1549. _("There is no Painting Geometry in the file.\n"
  1550. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1551. "Change the painting parameters and try again."))
  1552. return
  1553. # Experimental...
  1554. # print("Indexing...", end=' ')
  1555. # geo_obj.make_index()
  1556. self.app.inform.emit('[success] %s' % _("Paint All Done."))
  1557. # Initializes the new geometry object
  1558. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1559. assert isinstance(geo_obj, FlatCAMGeometry), \
  1560. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1561. log.debug("Paint Tool. Rest machining painting all task started.")
  1562. if isinstance(obj, FlatCAMGerber):
  1563. if app_obj.defaults["gerber_buffering"] == 'no':
  1564. app_obj.inform.emit('%s %s %s' %
  1565. (_("Paint Tool."), _("Rest machining painting all task started."),
  1566. _("Buffering geometry...")))
  1567. else:
  1568. app_obj.inform.emit('%s %s' %
  1569. (_("Paint Tool."), _("Rest machining painting all task started.")))
  1570. else:
  1571. app_obj.inform.emit('%s %s' %
  1572. (_("Paint Tool."), _("Rest machining painting all task started.")))
  1573. tool_dia = None
  1574. sorted_tools.sort(reverse=True)
  1575. cleared_geo = []
  1576. current_uid = int(1)
  1577. geo_obj.solid_geometry = []
  1578. if isinstance(obj, FlatCAMGerber):
  1579. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1580. if isinstance(obj.solid_geometry, list):
  1581. obj.solid_geometry = MultiPolygon(obj.solid_geometry).buffer(0)
  1582. else:
  1583. obj.solid_geometry = obj.solid_geometry.buffer(0)
  1584. try:
  1585. a, b, c, d = obj.bounds()
  1586. geo_obj.options['xmin'] = a
  1587. geo_obj.options['ymin'] = b
  1588. geo_obj.options['xmax'] = c
  1589. geo_obj.options['ymax'] = d
  1590. except Exception as e:
  1591. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1592. return
  1593. for tool_dia in sorted_tools:
  1594. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1595. app_obj.inform.emit(
  1596. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1597. str(tool_dia),
  1598. self.units.lower(),
  1599. _('started'))
  1600. )
  1601. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1602. painted_area = recurse(obj.solid_geometry)
  1603. # variables to display the percentage of work done
  1604. geo_len = int(len(painted_area) / 100)
  1605. old_disp_number = 0
  1606. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1607. pol_nr = 0
  1608. for geo in painted_area:
  1609. try:
  1610. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  1611. poly_buf = geo.buffer(-paint_margin)
  1612. cp = None
  1613. if paint_method == "standard":
  1614. # Type(cp) == FlatCAMRTreeStorage | None
  1615. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  1616. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1617. overlap=over, contour=cont, connect=conn,
  1618. prog_plot=prog_plot)
  1619. elif paint_method == "seed":
  1620. # Type(cp) == FlatCAMRTreeStorage | None
  1621. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  1622. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1623. overlap=over, contour=cont, connect=conn,
  1624. prog_plot=prog_plot)
  1625. elif paint_method == "lines":
  1626. # Type(cp) == FlatCAMRTreeStorage | None
  1627. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  1628. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1629. overlap=over, contour=cont, connect=conn,
  1630. prog_plot=prog_plot)
  1631. if cp is not None:
  1632. cleared_geo += list(cp.get_objects())
  1633. except FlatCAMApp.GracefulException:
  1634. return "fail"
  1635. except Exception as e:
  1636. log.debug("Could not Paint the polygons. %s" % str(e))
  1637. self.app.inform.emit('[ERROR] %s\n%s' %
  1638. (_("Could not do Paint All. Try a different combination of parameters. "
  1639. "Or a different Method of paint"),
  1640. str(e)))
  1641. return "fail"
  1642. pol_nr += 1
  1643. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1644. # log.debug("Polygons cleared: %d" % pol_nr)
  1645. if old_disp_number < disp_number <= 100:
  1646. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1647. old_disp_number = disp_number
  1648. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1649. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1650. for k, v in tools_storage.items():
  1651. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1652. current_uid = int(k)
  1653. break
  1654. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  1655. # then reset the temporary list that stored that solid_geometry
  1656. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  1657. tools_storage[current_uid]['data']['name'] = name
  1658. cleared_geo[:] = []
  1659. geo_obj.options["cnctooldia"] = str(tool_dia)
  1660. # this turn on the FlatCAMCNCJob plot for multiple tools
  1661. geo_obj.multigeo = True
  1662. geo_obj.multitool = True
  1663. geo_obj.tools.clear()
  1664. geo_obj.tools = dict(tools_storage)
  1665. # clean the progressive plotted shapes if it was used
  1666. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1667. self.temp_shapes.clear(update=True)
  1668. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1669. has_solid_geo = 0
  1670. for tooluid in geo_obj.tools:
  1671. if geo_obj.tools[tooluid]['solid_geometry']:
  1672. has_solid_geo += 1
  1673. if has_solid_geo == 0:
  1674. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1675. _("There is no Painting Geometry in the file.\n"
  1676. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1677. "Change the painting parameters and try again."))
  1678. return
  1679. # Experimental...
  1680. # print("Indexing...", end=' ')
  1681. # geo_obj.make_index()
  1682. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  1683. def job_thread(app_obj):
  1684. try:
  1685. if self.rest_cb.isChecked():
  1686. app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  1687. else:
  1688. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  1689. except FlatCAMApp.GracefulException:
  1690. proc.done()
  1691. return
  1692. except Exception as e:
  1693. proc.done()
  1694. traceback.print_stack()
  1695. return
  1696. proc.done()
  1697. # focus on Selected Tab
  1698. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  1699. self.app.inform.emit(_("Polygon Paint started ..."))
  1700. # Promise object with the new name
  1701. self.app.collection.promise(name)
  1702. if run_threaded:
  1703. # Background
  1704. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1705. else:
  1706. job_thread(app_obj=self.app)
  1707. def paint_poly_area(self, obj, sel_obj,
  1708. tooldia=None,
  1709. overlap=None,
  1710. order=None,
  1711. margin=None,
  1712. method=None,
  1713. outname=None,
  1714. connect=None,
  1715. contour=None,
  1716. tools_storage=None,
  1717. plot=True,
  1718. run_threaded=True):
  1719. """
  1720. Paints all polygons in this object that are within the sel_obj object
  1721. :param obj: painted object
  1722. :param sel_obj: paint only what is inside this object bounds
  1723. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  1724. :param overlap: value by which the paths will overlap
  1725. :param order: if the tools are ordered and how
  1726. :param margin: a border around painting area
  1727. :param outname: name of the resulting object
  1728. :param connect: Connect lines to avoid tool lifts.
  1729. :param contour: Paint around the edges.
  1730. :param method: choice out of 'seed', 'normal', 'lines'
  1731. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  1732. Usage of the different one is related to when this function is called from a TcL command.
  1733. :return:
  1734. """
  1735. paint_method = method if method is None else self.paintmethod_combo.get_value()
  1736. if margin is not None:
  1737. paint_margin = margin
  1738. else:
  1739. try:
  1740. paint_margin = float(self.paintmargin_entry.get_value())
  1741. except ValueError:
  1742. # try to convert comma to decimal point. if it's still not working error message and return
  1743. try:
  1744. paint_margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  1745. except ValueError:
  1746. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1747. _("Wrong value format entered, use a number."))
  1748. return
  1749. # determine if to use the progressive plotting
  1750. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1751. prog_plot = True
  1752. else:
  1753. prog_plot = False
  1754. proc = self.app.proc_container.new(_("Painting polygons..."))
  1755. name = outname if outname is not None else self.obj_name + "_paint"
  1756. over = overlap if overlap is not None else float(self.app.defaults["tools_paintoverlap"])
  1757. conn = connect if connect is not None else self.app.defaults["tools_pathconnect"]
  1758. cont = contour if contour is not None else self.app.defaults["tools_paintcontour"]
  1759. order = order if order is not None else self.order_radio.get_value()
  1760. sorted_tools = []
  1761. if tooldia is not None:
  1762. try:
  1763. sorted_tools = [float(eval(dia)) for dia in tooldia.split(",") if dia != '']
  1764. except AttributeError:
  1765. if not isinstance(tooldia, list):
  1766. sorted_tools = [float(tooldia)]
  1767. else:
  1768. sorted_tools = tooldia
  1769. else:
  1770. for row in range(self.tools_table.rowCount()):
  1771. sorted_tools.append(float(self.tools_table.item(row, 1).text()))
  1772. if tools_storage is not None:
  1773. tools_storage = tools_storage
  1774. else:
  1775. tools_storage = self.paint_tools
  1776. def recurse(geometry, reset=True):
  1777. """
  1778. Creates a list of non-iterable linear geometry objects.
  1779. Results are placed in self.flat_geometry
  1780. :param geometry: Shapely type or list or list of list of such.
  1781. :param reset: Clears the contents of self.flat_geometry.
  1782. """
  1783. if self.app.abort_flag:
  1784. # graceful abort requested by the user
  1785. raise FlatCAMApp.GracefulException
  1786. if geometry is None:
  1787. return
  1788. if reset:
  1789. self.flat_geometry = []
  1790. # ## If iterable, expand recursively.
  1791. try:
  1792. for geo in geometry:
  1793. if geo is not None:
  1794. recurse(geometry=geo, reset=False)
  1795. # ## Not iterable, do the actual indexing and add.
  1796. except TypeError:
  1797. if isinstance(geometry, LinearRing):
  1798. g = Polygon(geometry)
  1799. self.flat_geometry.append(g)
  1800. else:
  1801. self.flat_geometry.append(geometry)
  1802. return self.flat_geometry
  1803. # Initializes the new geometry object
  1804. def gen_paintarea(geo_obj, app_obj):
  1805. # assert isinstance(geo_obj, FlatCAMGeometry), \
  1806. # "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1807. log.debug("Paint Tool. Normal painting area task started.")
  1808. if isinstance(obj, FlatCAMGerber):
  1809. if app_obj.defaults["gerber_buffering"] == 'no':
  1810. app_obj.inform.emit('%s %s %s' %
  1811. (_("Paint Tool."),
  1812. _("Normal painting area task started."),
  1813. _("Buffering geometry...")))
  1814. else:
  1815. app_obj.inform.emit('%s %s' %
  1816. (_("Paint Tool."), _("Normal painting area task started.")))
  1817. else:
  1818. app_obj.inform.emit('%s %s' %
  1819. (_("Paint Tool."), _("Normal painting area task started.")))
  1820. tool_dia = None
  1821. if order == 'fwd':
  1822. sorted_tools.sort(reverse=False)
  1823. elif order == 'rev':
  1824. sorted_tools.sort(reverse=True)
  1825. else:
  1826. pass
  1827. # this is were heavy lifting is done and creating the geometry to be painted
  1828. target_geo = MultiPolygon(obj.solid_geometry)
  1829. if isinstance(obj, FlatCAMGerber):
  1830. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1831. if isinstance(target_geo, list):
  1832. target_geo = MultiPolygon(target_geo).buffer(0)
  1833. else:
  1834. target_geo = target_geo.buffer(0)
  1835. geo_to_paint = target_geo.intersection(sel_obj)
  1836. painted_area = recurse(geo_to_paint)
  1837. try:
  1838. a, b, c, d = self.paint_bounds(geo_to_paint)
  1839. geo_obj.options['xmin'] = a
  1840. geo_obj.options['ymin'] = b
  1841. geo_obj.options['xmax'] = c
  1842. geo_obj.options['ymax'] = d
  1843. except Exception as e:
  1844. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1845. return
  1846. total_geometry = []
  1847. current_uid = int(1)
  1848. geo_obj.solid_geometry = []
  1849. for tool_dia in sorted_tools:
  1850. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1851. app_obj.inform.emit(
  1852. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  1853. str(tool_dia),
  1854. self.units.lower(),
  1855. _('started'))
  1856. )
  1857. app_obj.proc_container.update_view_text(' %d%%' % 0)
  1858. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  1859. for k, v in tools_storage.items():
  1860. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  1861. current_uid = int(k)
  1862. break
  1863. # variables to display the percentage of work done
  1864. geo_len = len(painted_area)
  1865. old_disp_number = 0
  1866. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  1867. pol_nr = 0
  1868. for geo in painted_area:
  1869. try:
  1870. # Polygons are the only really paintable geometries, lines in theory have no area to be painted
  1871. if not isinstance(geo, Polygon):
  1872. continue
  1873. poly_buf = geo.buffer(-paint_margin)
  1874. if paint_method == "seed":
  1875. # Type(cp) == FlatCAMRTreeStorage | None
  1876. cp = self.clear_polygon2(poly_buf,
  1877. tooldia=tool_dia,
  1878. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1879. overlap=over,
  1880. contour=cont,
  1881. connect=conn,
  1882. prog_plot=prog_plot)
  1883. elif paint_method == "lines":
  1884. # Type(cp) == FlatCAMRTreeStorage | None
  1885. cp = self.clear_polygon3(poly_buf,
  1886. tooldia=tool_dia,
  1887. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1888. overlap=over,
  1889. contour=cont,
  1890. connect=conn,
  1891. prog_plot=prog_plot)
  1892. else:
  1893. # Type(cp) == FlatCAMRTreeStorage | None
  1894. cp = self.clear_polygon(poly_buf,
  1895. tooldia=tool_dia,
  1896. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  1897. overlap=over,
  1898. contour=cont,
  1899. connect=conn,
  1900. prog_plot=prog_plot)
  1901. if cp is not None:
  1902. total_geometry += list(cp.get_objects())
  1903. except FlatCAMApp.GracefulException:
  1904. return "fail"
  1905. except Exception as e:
  1906. log.debug("Could not Paint the polygons. %s" % str(e))
  1907. self.app.inform.emit('[ERROR] %s\n%s' %
  1908. (_("Could not do Paint All. Try a different combination of parameters. "
  1909. "Or a different Method of paint"), str(e)))
  1910. return
  1911. pol_nr += 1
  1912. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  1913. # log.debug("Polygons cleared: %d" % pol_nr)
  1914. if old_disp_number < disp_number <= 100:
  1915. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  1916. old_disp_number = disp_number
  1917. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  1918. # add the solid_geometry to the current too in self.paint_tools (tools_storage)
  1919. # dictionary and then reset the temporary list that stored that solid_geometry
  1920. tools_storage[current_uid]['solid_geometry'] = deepcopy(total_geometry)
  1921. tools_storage[current_uid]['data']['name'] = name
  1922. total_geometry[:] = []
  1923. # clean the progressive plotted shapes if it was used
  1924. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1925. self.temp_shapes.clear(update=True)
  1926. # delete tools with empty geometry
  1927. keys_to_delete = []
  1928. # look for keys in the tools_storage dict that have 'solid_geometry' values empty
  1929. for uid in tools_storage:
  1930. # if the solid_geometry (type=list) is empty
  1931. if not tools_storage[uid]['solid_geometry']:
  1932. keys_to_delete.append(uid)
  1933. # actual delete of keys from the tools_storage dict
  1934. for k in keys_to_delete:
  1935. tools_storage.pop(k, None)
  1936. geo_obj.options["cnctooldia"] = str(tool_dia)
  1937. # this turn on the FlatCAMCNCJob plot for multiple tools
  1938. geo_obj.multigeo = True
  1939. geo_obj.multitool = True
  1940. geo_obj.tools.clear()
  1941. geo_obj.tools = dict(tools_storage)
  1942. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  1943. has_solid_geo = 0
  1944. for tooluid in geo_obj.tools:
  1945. if geo_obj.tools[tooluid]['solid_geometry']:
  1946. has_solid_geo += 1
  1947. if has_solid_geo == 0:
  1948. self.app.inform.emit('[ERROR] %s' %
  1949. _("There is no Painting Geometry in the file.\n"
  1950. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  1951. "Change the painting parameters and try again."))
  1952. return
  1953. # Experimental...
  1954. # print("Indexing...", end=' ')
  1955. # geo_obj.make_index()
  1956. self.app.inform.emit('[success] %s' % _("Paint Area Done."))
  1957. # Initializes the new geometry object
  1958. def gen_paintarea_rest_machining(geo_obj, app_obj):
  1959. assert isinstance(geo_obj, FlatCAMGeometry), \
  1960. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1961. log.debug("Paint Tool. Rest machining painting area task started.")
  1962. if isinstance(obj, FlatCAMGerber):
  1963. if app_obj.defaults["gerber_buffering"] == 'no':
  1964. app_obj.inform.emit('%s %s %s' %
  1965. (_("Paint Tool."),
  1966. _("Rest machining painting area task started."),
  1967. _("Buffering geometry...")))
  1968. else:
  1969. app_obj.inform.emit(_("Paint Tool. Rest machining painting area task started."))
  1970. else:
  1971. app_obj.inform.emit('%s %s' %
  1972. (_("Paint Tool."), _("Rest machining painting area task started.")))
  1973. tool_dia = None
  1974. sorted_tools.sort(reverse=True)
  1975. cleared_geo = []
  1976. current_uid = int(1)
  1977. geo_obj.solid_geometry = []
  1978. # this is were heavy lifting is done and creating the geometry to be painted
  1979. target_geo = obj.solid_geometry
  1980. if isinstance(obj, FlatCAMGerber):
  1981. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  1982. if isinstance(target_geo, list):
  1983. target_geo = MultiPolygon(target_geo).buffer(0)
  1984. else:
  1985. target_geo = target_geo.buffer(0)
  1986. geo_to_paint = target_geo.intersection(sel_obj)
  1987. painted_area = recurse(geo_to_paint)
  1988. try:
  1989. a, b, c, d = obj.bounds()
  1990. geo_obj.options['xmin'] = a
  1991. geo_obj.options['ymin'] = b
  1992. geo_obj.options['xmax'] = c
  1993. geo_obj.options['ymax'] = d
  1994. except Exception as e:
  1995. log.debug("ToolPaint.paint_poly.gen_paintarea() bounds error --> %s" % str(e))
  1996. return
  1997. for tool_dia in sorted_tools:
  1998. log.debug("Starting geometry processing for tool: %s" % str(tool_dia))
  1999. app_obj.inform.emit(
  2000. '[success] %s %s%s %s' % (_('Painting with tool diameter = '),
  2001. str(tool_dia),
  2002. self.units.lower(),
  2003. _('started'))
  2004. )
  2005. app_obj.proc_container.update_view_text(' %d%%' % 0)
  2006. # variables to display the percentage of work done
  2007. geo_len = len(painted_area)
  2008. old_disp_number = 0
  2009. log.warning("Total number of polygons to be cleared. %s" % str(geo_len))
  2010. pol_nr = 0
  2011. for geo in painted_area:
  2012. try:
  2013. geo = Polygon(geo) if not isinstance(geo, Polygon) else geo
  2014. poly_buf = geo.buffer(-paint_margin)
  2015. cp = None
  2016. if paint_method == "standard":
  2017. # Type(cp) == FlatCAMRTreeStorage | None
  2018. cp = self.clear_polygon(poly_buf, tooldia=tool_dia,
  2019. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2020. overlap=over, contour=cont, connect=conn,
  2021. prog_plot=prog_plot)
  2022. elif paint_method == "seed":
  2023. # Type(cp) == FlatCAMRTreeStorage | None
  2024. cp = self.clear_polygon2(poly_buf, tooldia=tool_dia,
  2025. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2026. overlap=over, contour=cont, connect=conn,
  2027. prog_plot=prog_plot)
  2028. elif paint_method == "lines":
  2029. # Type(cp) == FlatCAMRTreeStorage | None
  2030. cp = self.clear_polygon3(poly_buf, tooldia=tool_dia,
  2031. steps_per_circle=self.app.defaults["geometry_circle_steps"],
  2032. overlap=over, contour=cont, connect=conn,
  2033. prog_plot=prog_plot)
  2034. if cp is not None:
  2035. cleared_geo += list(cp.get_objects())
  2036. except FlatCAMApp.GracefulException:
  2037. return "fail"
  2038. except Exception as e:
  2039. log.debug("Could not Paint the polygons. %s" % str(e))
  2040. self.app.inform.emit('[ERROR] %s\n%s' %
  2041. (_("Could not do Paint All. Try a different combination of parameters. "
  2042. "Or a different Method of paint"), str(e)))
  2043. return
  2044. pol_nr += 1
  2045. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  2046. # log.debug("Polygons cleared: %d" % pol_nr)
  2047. if old_disp_number < disp_number <= 100:
  2048. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  2049. old_disp_number = disp_number
  2050. # log.debug("Polygons cleared: %d. Percentage done: %d%%" % (pol_nr, disp_number))
  2051. # find the tooluid associated with the current tool_dia so we know where to add the tool solid_geometry
  2052. for k, v in tools_storage.items():
  2053. if float('%.*f' % (self.decimals, v['tooldia'])) == float('%.*f' % (self.decimals, tool_dia)):
  2054. current_uid = int(k)
  2055. break
  2056. # add the solid_geometry to the current too in self.paint_tools (or tools_storage) dictionary and
  2057. # then reset the temporary list that stored that solid_geometry
  2058. tools_storage[current_uid]['solid_geometry'] = deepcopy(cleared_geo)
  2059. tools_storage[current_uid]['data']['name'] = name
  2060. cleared_geo[:] = []
  2061. geo_obj.options["cnctooldia"] = str(tool_dia)
  2062. # this turn on the FlatCAMCNCJob plot for multiple tools
  2063. geo_obj.multigeo = True
  2064. geo_obj.multitool = True
  2065. geo_obj.tools.clear()
  2066. geo_obj.tools = dict(self.paint_tools)
  2067. # clean the progressive plotted shapes if it was used
  2068. if self.app.defaults["tools_paint_plotting"] == 'progressive':
  2069. self.temp_shapes.clear(update=True)
  2070. # test if at least one tool has solid_geometry. If no tool has solid_geometry we raise an Exception
  2071. has_solid_geo = 0
  2072. for tooluid in geo_obj.tools:
  2073. if geo_obj.tools[tooluid]['solid_geometry']:
  2074. has_solid_geo += 1
  2075. if has_solid_geo == 0:
  2076. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2077. _("There is no Painting Geometry in the file.\n"
  2078. "Usually it means that the tool diameter is too big for the painted geometry.\n"
  2079. "Change the painting parameters and try again."))
  2080. return
  2081. # Experimental...
  2082. # print("Indexing...", end=' ')
  2083. # geo_obj.make_index()
  2084. self.app.inform.emit('[success] %s' % _("Paint All with Rest-Machining done."))
  2085. def job_thread(app_obj):
  2086. try:
  2087. if self.rest_cb.isChecked():
  2088. app_obj.new_object("geometry", name, gen_paintarea_rest_machining, plot=plot)
  2089. else:
  2090. app_obj.new_object("geometry", name, gen_paintarea, plot=plot)
  2091. except FlatCAMApp.GracefulException:
  2092. proc.done()
  2093. return
  2094. except Exception as e:
  2095. proc.done()
  2096. traceback.print_stack()
  2097. return
  2098. proc.done()
  2099. # focus on Selected Tab
  2100. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  2101. self.app.inform.emit(_("Polygon Paint started ..."))
  2102. # Promise object with the new name
  2103. self.app.collection.promise(name)
  2104. if run_threaded:
  2105. # Background
  2106. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  2107. else:
  2108. job_thread(app_obj=self.app)
  2109. def paint_poly_ref(self, obj, sel_obj,
  2110. tooldia=None,
  2111. overlap=None,
  2112. order=None,
  2113. margin=None,
  2114. method=None,
  2115. outname=None,
  2116. connect=None,
  2117. contour=None,
  2118. tools_storage=None,
  2119. plot=True,
  2120. run_threaded=True):
  2121. """
  2122. Paints all polygons in this object that are within the sel_obj object
  2123. :param obj: painted object
  2124. :param sel_obj: paint only what is inside this object bounds
  2125. :param tooldia: a tuple or single element made out of diameters of the tools to be used
  2126. :param overlap: value by which the paths will overlap
  2127. :param order: if the tools are ordered and how
  2128. :param margin: a border around painting area
  2129. :param outname: name of the resulting object
  2130. :param connect: Connect lines to avoid tool lifts.
  2131. :param contour: Paint around the edges.
  2132. :param method: choice out of 'seed', 'normal', 'lines'
  2133. :param tools_storage: whether to use the current tools_storage self.paints_tools or a different one.
  2134. Usage of the different one is related to when this function is called from a TcL command.
  2135. :return:
  2136. """
  2137. geo = sel_obj.solid_geometry
  2138. try:
  2139. if isinstance(geo, MultiPolygon):
  2140. env_obj = geo.convex_hull
  2141. elif (isinstance(geo, MultiPolygon) and len(geo) == 1) or \
  2142. (isinstance(geo, list) and len(geo) == 1) and isinstance(geo[0], Polygon):
  2143. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2144. else:
  2145. env_obj = cascaded_union(self.bound_obj.solid_geometry)
  2146. env_obj = env_obj.convex_hull
  2147. sel_rect = env_obj.buffer(distance=0.0000001, join_style=base.JOIN_STYLE.mitre)
  2148. except Exception as e:
  2149. log.debug("ToolPaint.on_paint_button_click() --> %s" % str(e))
  2150. self.app.inform.emit('[ERROR_NOTCL] %s' % _("No object available."))
  2151. return
  2152. self.paint_poly_area(obj=obj,
  2153. sel_obj=sel_rect,
  2154. tooldia=tooldia,
  2155. overlap=overlap,
  2156. order=order,
  2157. margin=margin,
  2158. method=method,
  2159. outname=outname,
  2160. connect=connect,
  2161. contour=contour,
  2162. tools_storage=tools_storage,
  2163. plot=plot,
  2164. run_threaded=run_threaded)
  2165. @staticmethod
  2166. def paint_bounds(geometry):
  2167. def bounds_rec(o):
  2168. if type(o) is list:
  2169. minx = Inf
  2170. miny = Inf
  2171. maxx = -Inf
  2172. maxy = -Inf
  2173. for k in o:
  2174. try:
  2175. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  2176. except Exception as e:
  2177. log.debug("ToolPaint.bounds() --> %s" % str(e))
  2178. return
  2179. minx = min(minx, minx_)
  2180. miny = min(miny, miny_)
  2181. maxx = max(maxx, maxx_)
  2182. maxy = max(maxy, maxy_)
  2183. return minx, miny, maxx, maxy
  2184. else:
  2185. # it's a Shapely object, return it's bounds
  2186. return o.bounds
  2187. return bounds_rec(geometry)
  2188. def reset_fields(self):
  2189. self.obj_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))