ToolPaint.py 113 KB

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