ToolPaint.py 105 KB

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