FlatCAMGeometry.py 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # ##########################################################
  8. # ##########################################################
  9. # File modified by: Marius Stanciu #
  10. # ##########################################################
  11. from shapely.geometry import Polygon, MultiPolygon, MultiLineString, LineString, LinearRing
  12. import shapely.affinity as affinity
  13. from camlib import Geometry
  14. from flatcamObjects.FlatCAMObj import *
  15. import ezdxf
  16. import math
  17. import numpy as np
  18. from copy import deepcopy
  19. import traceback
  20. import gettext
  21. import FlatCAMTranslation as fcTranslate
  22. import builtins
  23. fcTranslate.apply_language('strings')
  24. if '_' not in builtins.__dict__:
  25. _ = gettext.gettext
  26. class GeometryObject(FlatCAMObj, Geometry):
  27. """
  28. Geometric object not associated with a specific
  29. format.
  30. """
  31. optionChanged = QtCore.pyqtSignal(str)
  32. ui_type = GeometryObjectUI
  33. def __init__(self, name):
  34. self.decimals = self.app.decimals
  35. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  36. FlatCAMObj.__init__(self, name)
  37. Geometry.__init__(self, geo_steps_per_circle=self.circle_steps)
  38. self.kind = "geometry"
  39. self.options.update({
  40. "plot": True,
  41. "cutz": -0.002,
  42. "vtipdia": 0.1,
  43. "vtipangle": 30,
  44. "travelz": 0.1,
  45. "feedrate": 5.0,
  46. "feedrate_z": 5.0,
  47. "feedrate_rapid": 5.0,
  48. "spindlespeed": 0,
  49. "dwell": True,
  50. "dwelltime": 1000,
  51. "multidepth": False,
  52. "depthperpass": 0.002,
  53. "extracut": False,
  54. "extracut_length": 0.1,
  55. "endz": 2.0,
  56. "endxy": '',
  57. "area_exclusion": False,
  58. "area_shape": "polygon",
  59. "area_strategy": "over",
  60. "area_overz": 1.0,
  61. "startz": None,
  62. "toolchange": False,
  63. "toolchangez": 1.0,
  64. "toolchangexy": "0.0, 0.0",
  65. "ppname_g": 'default',
  66. "z_pdepth": -0.02,
  67. "feedrate_probe": 3.0,
  68. })
  69. if "cnctooldia" not in self.options:
  70. if type(self.app.defaults["geometry_cnctooldia"]) == float:
  71. self.options["cnctooldia"] = self.app.defaults["geometry_cnctooldia"]
  72. else:
  73. try:
  74. tools_string = self.app.defaults["geometry_cnctooldia"].split(",")
  75. tools_diameters = [eval(a) for a in tools_string if a != '']
  76. self.options["cnctooldia"] = tools_diameters[0] if tools_diameters else 0.0
  77. except Exception as e:
  78. log.debug("FlatCAMObj.GeometryObject.init() --> %s" % str(e))
  79. self.options["startz"] = self.app.defaults["geometry_startz"]
  80. # this will hold the tool unique ID that is useful when having multiple tools with same diameter
  81. self.tooluid = 0
  82. '''
  83. self.tools = {}
  84. This is a dictionary. Each dict key is associated with a tool used in geo_tools_table. The key is the
  85. tool_id of the tools and the value is another dict that will hold the data under the following form:
  86. {tooluid: {
  87. 'tooldia': 1,
  88. 'offset': 'Path',
  89. 'offset_value': 0.0
  90. 'type': 'Rough',
  91. 'tool_type': 'C1',
  92. 'data': self.default_tool_data
  93. 'solid_geometry': []
  94. }
  95. }
  96. '''
  97. self.tools = {}
  98. # this dict is to store those elements (tools) of self.tools that are selected in the self.geo_tools_table
  99. # those elements are the ones used for generating GCode
  100. self.sel_tools = {}
  101. self.offset_item_options = ["Path", "In", "Out", "Custom"]
  102. self.type_item_options = [_("Iso"), _("Rough"), _("Finish")]
  103. self.tool_type_item_options = ["C1", "C2", "C3", "C4", "B", "V"]
  104. # flag to store if the V-Shape tool is selected in self.ui.geo_tools_table
  105. self.v_tool_type = None
  106. # flag to store if the Geometry is type 'multi-geometry' meaning that each tool has it's own geometry
  107. # the default value is False
  108. self.multigeo = False
  109. # flag to store if the geometry is part of a special group of geometries that can't be processed by the default
  110. # engine of FlatCAM. Most likely are generated by some of tools and are special cases of geometries.
  111. self.special_group = None
  112. self.old_pp_state = self.app.defaults["geometry_multidepth"]
  113. self.old_toolchangeg_state = self.app.defaults["geometry_toolchange"]
  114. self.units_found = self.app.defaults['units']
  115. # this variable can be updated by the Object that generates the geometry
  116. self.tool_type = 'C1'
  117. # save here the old value for the Cut Z before it is changed by selecting a V-shape type tool in the tool table
  118. self.old_cutz = self.app.defaults["geometry_cutz"]
  119. self.fill_color = self.app.defaults['geometry_plot_line']
  120. self.outline_color = self.app.defaults['geometry_plot_line']
  121. self.alpha_level = 'FF'
  122. self.param_fields = {}
  123. # Attributes to be included in serialization
  124. # Always append to it because it carries contents
  125. # from predecessors.
  126. self.ser_attrs += ['options', 'kind', 'tools', 'multigeo']
  127. def build_ui(self):
  128. self.ui_disconnect()
  129. FlatCAMObj.build_ui(self)
  130. self.units = self.app.defaults['units']
  131. tool_idx = 0
  132. n = len(self.tools)
  133. self.ui.geo_tools_table.setRowCount(n)
  134. for tooluid_key, tooluid_value in self.tools.items():
  135. tool_idx += 1
  136. row_no = tool_idx - 1
  137. tool_id = QtWidgets.QTableWidgetItem('%d' % int(tool_idx))
  138. tool_id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  139. self.ui.geo_tools_table.setItem(row_no, 0, tool_id) # Tool name/id
  140. # Make sure that the tool diameter when in MM is with no more than 2 decimals.
  141. # There are no tool bits in MM with more than 3 decimals diameter.
  142. # For INCH the decimals should be no more than 3. There are no tools under 10mils.
  143. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, float(tooluid_value['tooldia'])))
  144. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  145. offset_item = FCComboBox()
  146. for item in self.offset_item_options:
  147. offset_item.addItem(item)
  148. # offset_item.setStyleSheet('background-color: rgb(255,255,255)')
  149. idx = offset_item.findText(tooluid_value['offset'])
  150. offset_item.setCurrentIndex(idx)
  151. type_item = FCComboBox()
  152. for item in self.type_item_options:
  153. type_item.addItem(item)
  154. # type_item.setStyleSheet('background-color: rgb(255,255,255)')
  155. idx = type_item.findText(tooluid_value['type'])
  156. type_item.setCurrentIndex(idx)
  157. tool_type_item = FCComboBox()
  158. for item in self.tool_type_item_options:
  159. tool_type_item.addItem(item)
  160. # tool_type_item.setStyleSheet('background-color: rgb(255,255,255)')
  161. idx = tool_type_item.findText(tooluid_value['tool_type'])
  162. tool_type_item.setCurrentIndex(idx)
  163. tool_uid_item = QtWidgets.QTableWidgetItem(str(tooluid_key))
  164. plot_item = FCCheckBox()
  165. plot_item.setLayoutDirection(QtCore.Qt.RightToLeft)
  166. if self.ui.plot_cb.isChecked():
  167. plot_item.setChecked(True)
  168. self.ui.geo_tools_table.setItem(row_no, 1, dia_item) # Diameter
  169. self.ui.geo_tools_table.setCellWidget(row_no, 2, offset_item)
  170. self.ui.geo_tools_table.setCellWidget(row_no, 3, type_item)
  171. self.ui.geo_tools_table.setCellWidget(row_no, 4, tool_type_item)
  172. # ## REMEMBER: THIS COLUMN IS HIDDEN IN OBJECTUI.PY ###
  173. self.ui.geo_tools_table.setItem(row_no, 5, tool_uid_item) # Tool unique ID
  174. self.ui.geo_tools_table.setCellWidget(row_no, 6, plot_item)
  175. try:
  176. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  177. except Exception as e:
  178. log.debug("build_ui() --> Could not set the 'offset_value' key in self.tools. Error: %s" % str(e))
  179. # make the diameter column editable
  180. for row in range(tool_idx):
  181. self.ui.geo_tools_table.item(row, 1).setFlags(QtCore.Qt.ItemIsSelectable |
  182. QtCore.Qt.ItemIsEditable |
  183. QtCore.Qt.ItemIsEnabled)
  184. # sort the tool diameter column
  185. # self.ui.geo_tools_table.sortItems(1)
  186. # all the tools are selected by default
  187. # self.ui.geo_tools_table.selectColumn(0)
  188. self.ui.geo_tools_table.resizeColumnsToContents()
  189. self.ui.geo_tools_table.resizeRowsToContents()
  190. vertical_header = self.ui.geo_tools_table.verticalHeader()
  191. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  192. vertical_header.hide()
  193. self.ui.geo_tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  194. horizontal_header = self.ui.geo_tools_table.horizontalHeader()
  195. horizontal_header.setMinimumSectionSize(10)
  196. horizontal_header.setDefaultSectionSize(70)
  197. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  198. horizontal_header.resizeSection(0, 20)
  199. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  200. # horizontal_header.setColumnWidth(2, QtWidgets.QHeaderView.ResizeToContents)
  201. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  202. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.Fixed)
  203. horizontal_header.resizeSection(4, 40)
  204. horizontal_header.setSectionResizeMode(6, QtWidgets.QHeaderView.Fixed)
  205. horizontal_header.resizeSection(4, 17)
  206. # horizontal_header.setStretchLastSection(True)
  207. self.ui.geo_tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  208. self.ui.geo_tools_table.setColumnWidth(0, 20)
  209. self.ui.geo_tools_table.setColumnWidth(4, 40)
  210. self.ui.geo_tools_table.setColumnWidth(6, 17)
  211. # self.ui.geo_tools_table.setSortingEnabled(True)
  212. self.ui.geo_tools_table.setMinimumHeight(self.ui.geo_tools_table.getHeight())
  213. self.ui.geo_tools_table.setMaximumHeight(self.ui.geo_tools_table.getHeight())
  214. # update UI for all rows - useful after units conversion but only if there is at least one row
  215. row_cnt = self.ui.geo_tools_table.rowCount()
  216. if row_cnt > 0:
  217. for r in range(row_cnt):
  218. self.update_ui(r)
  219. # select only the first tool / row
  220. selected_row = 0
  221. try:
  222. self.select_tools_table_row(selected_row, clearsel=True)
  223. # update the Geometry UI
  224. self.update_ui()
  225. except Exception as e:
  226. # when the tools table is empty there will be this error but once the table is populated it will go away
  227. log.debug(str(e))
  228. # disable the Plot column in Tool Table if the geometry is SingleGeo as it is not needed
  229. # and can create some problems
  230. if self.multigeo is False:
  231. self.ui.geo_tools_table.setColumnHidden(6, True)
  232. else:
  233. self.ui.geo_tools_table.setColumnHidden(6, False)
  234. self.set_tool_offset_visibility(selected_row)
  235. # HACK: for whatever reasons the name in Selected tab is reverted to the original one after a successful rename
  236. # done in the collection view but only for Geometry objects. Perhaps some references remains. Should be fixed.
  237. self.ui.name_entry.set_value(self.options['name'])
  238. self.ui_connect()
  239. self.ui.e_cut_entry.setDisabled(False) if self.ui.extracut_cb.get_value() else \
  240. self.ui.e_cut_entry.setDisabled(True)
  241. # set the text on tool_data_label after loading the object
  242. sel_rows = []
  243. sel_items = self.ui.geo_tools_table.selectedItems()
  244. for it in sel_items:
  245. sel_rows.append(it.row())
  246. if len(sel_rows) > 1:
  247. self.ui.tool_data_label.setText(
  248. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  249. )
  250. def set_ui(self, ui):
  251. FlatCAMObj.set_ui(self, ui)
  252. log.debug("GeometryObject.set_ui()")
  253. assert isinstance(self.ui, GeometryObjectUI), \
  254. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  255. self.units = self.app.defaults['units'].upper()
  256. self.units_found = self.app.defaults['units']
  257. # populate preprocessor names in the combobox
  258. for name in list(self.app.preprocessors.keys()):
  259. self.ui.pp_geometry_name_cb.addItem(name)
  260. self.form_fields.update({
  261. "plot": self.ui.plot_cb,
  262. "cutz": self.ui.cutz_entry,
  263. "vtipdia": self.ui.tipdia_entry,
  264. "vtipangle": self.ui.tipangle_entry,
  265. "travelz": self.ui.travelz_entry,
  266. "feedrate": self.ui.cncfeedrate_entry,
  267. "feedrate_z": self.ui.feedrate_z_entry,
  268. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  269. "spindlespeed": self.ui.cncspindlespeed_entry,
  270. "dwell": self.ui.dwell_cb,
  271. "dwelltime": self.ui.dwelltime_entry,
  272. "multidepth": self.ui.mpass_cb,
  273. "ppname_g": self.ui.pp_geometry_name_cb,
  274. "z_pdepth": self.ui.pdepth_entry,
  275. "feedrate_probe": self.ui.feedrate_probe_entry,
  276. "depthperpass": self.ui.maxdepth_entry,
  277. "extracut": self.ui.extracut_cb,
  278. "extracut_length": self.ui.e_cut_entry,
  279. "toolchange": self.ui.toolchangeg_cb,
  280. "toolchangez": self.ui.toolchangez_entry,
  281. "endz": self.ui.endz_entry,
  282. "endxy": self.ui.endxy_entry,
  283. "cnctooldia": self.ui.addtool_entry,
  284. "area_exclusion": self.ui.exclusion_cb,
  285. "area_shape": self.ui.area_shape_radio,
  286. "area_strategy": self.ui.strategy_radio,
  287. "area_overz": self.ui.over_z_entry,
  288. })
  289. self.param_fields.update({
  290. "vtipdia": self.ui.tipdia_entry,
  291. "vtipangle": self.ui.tipangle_entry,
  292. "cutz": self.ui.cutz_entry,
  293. "depthperpass": self.ui.maxdepth_entry,
  294. "multidepth": self.ui.mpass_cb,
  295. "travelz": self.ui.travelz_entry,
  296. "feedrate": self.ui.cncfeedrate_entry,
  297. "feedrate_z": self.ui.feedrate_z_entry,
  298. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  299. "extracut": self.ui.extracut_cb,
  300. "extracut_length": self.ui.e_cut_entry,
  301. "spindlespeed": self.ui.cncspindlespeed_entry,
  302. "dwelltime": self.ui.dwelltime_entry,
  303. "dwell": self.ui.dwell_cb,
  304. "pdepth": self.ui.pdepth_entry,
  305. "pfeedrate": self.ui.feedrate_probe_entry,
  306. })
  307. # Fill form fields only on object create
  308. self.to_form()
  309. # update the changes in UI depending on the selected preprocessor in Preferences
  310. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  311. # self.ui.pp_geometry_name_cb combobox
  312. self.on_pp_changed()
  313. self.ui.tipdialabel.hide()
  314. self.ui.tipdia_entry.hide()
  315. self.ui.tipanglelabel.hide()
  316. self.ui.tipangle_entry.hide()
  317. self.ui.cutz_entry.setDisabled(False)
  318. # store here the default data for Geometry Data
  319. self.default_data = {}
  320. self.default_data.update({
  321. "name": None,
  322. "plot": None,
  323. "cutz": None,
  324. "vtipdia": None,
  325. "vtipangle": None,
  326. "travelz": None,
  327. "feedrate": None,
  328. "feedrate_z": None,
  329. "feedrate_rapid": None,
  330. "dwell": None,
  331. "dwelltime": None,
  332. "multidepth": None,
  333. "ppname_g": None,
  334. "depthperpass": None,
  335. "extracut": None,
  336. "extracut_length": None,
  337. "toolchange": None,
  338. "toolchangez": None,
  339. "endz": None,
  340. "endxy": '',
  341. "area_exclusion": None,
  342. "area_shape": None,
  343. "area_strategy": None,
  344. "area_overz": None,
  345. "spindlespeed": 0,
  346. "toolchangexy": None,
  347. "startz": None
  348. })
  349. # fill in self.default_data values from self.options
  350. for def_key in self.default_data:
  351. for opt_key, opt_val in self.options.items():
  352. if def_key == opt_key:
  353. self.default_data[def_key] = deepcopy(opt_val)
  354. if type(self.options["cnctooldia"]) == float:
  355. tools_list = [self.options["cnctooldia"]]
  356. else:
  357. try:
  358. temp_tools = self.options["cnctooldia"].split(",")
  359. tools_list = [
  360. float(eval(dia)) for dia in temp_tools if dia != ''
  361. ]
  362. except Exception as e:
  363. log.error("GeometryObject.set_ui() -> At least one tool diameter needed. "
  364. "Verify in Edit -> Preferences -> Geometry General -> Tool dia. %s" % str(e))
  365. return
  366. self.tooluid += 1
  367. if not self.tools:
  368. for toold in tools_list:
  369. new_data = deepcopy(self.default_data)
  370. self.tools.update({
  371. self.tooluid: {
  372. 'tooldia': float('%.*f' % (self.decimals, float(toold))),
  373. 'offset': 'Path',
  374. 'offset_value': 0.0,
  375. 'type': _('Rough'),
  376. 'tool_type': self.tool_type,
  377. 'data': new_data,
  378. 'solid_geometry': self.solid_geometry
  379. }
  380. })
  381. self.tooluid += 1
  382. else:
  383. # if self.tools is not empty then it can safely be assumed that it comes from an opened project.
  384. # Because of the serialization the self.tools list on project save, the dict keys (members of self.tools
  385. # are each a dict) are turned into strings so we rebuild the self.tools elements so the keys are
  386. # again float type; dict's don't like having keys changed when iterated through therefore the need for the
  387. # following convoluted way of changing the keys from string to float type
  388. temp_tools = {}
  389. for tooluid_key in self.tools:
  390. val = deepcopy(self.tools[tooluid_key])
  391. new_key = deepcopy(int(tooluid_key))
  392. temp_tools[new_key] = val
  393. self.tools.clear()
  394. self.tools = deepcopy(temp_tools)
  395. self.ui.tool_offset_entry.hide()
  396. self.ui.tool_offset_lbl.hide()
  397. # used to store the state of the mpass_cb if the selected preprocessor for geometry is hpgl
  398. self.old_pp_state = self.default_data['multidepth']
  399. self.old_toolchangeg_state = self.default_data['toolchange']
  400. if not isinstance(self.ui, GeometryObjectUI):
  401. log.debug("Expected a GeometryObjectUI, got %s" % type(self.ui))
  402. return
  403. self.ui.geo_tools_table.setupContextMenu()
  404. self.ui.geo_tools_table.addContextMenu(
  405. _("Add from Tool DB"), self.on_tool_add_from_db_clicked,
  406. icon=QtGui.QIcon(self.app.resource_location + "/plus16.png"))
  407. self.ui.geo_tools_table.addContextMenu(
  408. _("Copy"), self.on_tool_copy,
  409. icon=QtGui.QIcon(self.app.resource_location + "/copy16.png"))
  410. self.ui.geo_tools_table.addContextMenu(
  411. _("Delete"), lambda: self.on_tool_delete(all_tools=None),
  412. icon=QtGui.QIcon(self.app.resource_location + "/delete32.png"))
  413. # Show/Hide Advanced Options
  414. if self.app.defaults["global_app_level"] == 'b':
  415. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  416. self.ui.geo_tools_table.setColumnHidden(2, True)
  417. self.ui.geo_tools_table.setColumnHidden(3, True)
  418. # self.ui.geo_tools_table.setColumnHidden(4, True)
  419. self.ui.addtool_entry_lbl.hide()
  420. self.ui.addtool_entry.hide()
  421. self.ui.addtool_btn.hide()
  422. self.ui.copytool_btn.hide()
  423. self.ui.deltool_btn.hide()
  424. # self.ui.endz_label.hide()
  425. # self.ui.endz_entry.hide()
  426. self.ui.fr_rapidlabel.hide()
  427. self.ui.feedrate_rapid_entry.hide()
  428. self.ui.extracut_cb.hide()
  429. self.ui.e_cut_entry.hide()
  430. self.ui.pdepth_label.hide()
  431. self.ui.pdepth_entry.hide()
  432. self.ui.feedrate_probe_label.hide()
  433. self.ui.feedrate_probe_entry.hide()
  434. else:
  435. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  436. self.ui.e_cut_entry.setDisabled(False) if self.app.defaults['geometry_extracut'] else \
  437. self.ui.e_cut_entry.setDisabled(True)
  438. self.ui.extracut_cb.toggled.connect(lambda state: self.ui.e_cut_entry.setDisabled(not state))
  439. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  440. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  441. self.ui.paint_tool_button.clicked.connect(lambda: self.app.paint_tool.run(toggle=False))
  442. self.ui.generate_ncc_button.clicked.connect(lambda: self.app.ncclear_tool.run(toggle=False))
  443. self.ui.pp_geometry_name_cb.activated.connect(self.on_pp_changed)
  444. self.ui.tipdia_entry.valueChanged.connect(self.update_cutz)
  445. self.ui.tipangle_entry.valueChanged.connect(self.update_cutz)
  446. self.ui.addtool_from_db_btn.clicked.connect(self.on_tool_add_from_db_clicked)
  447. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  448. self.ui.cutz_entry.returnPressed.connect(self.on_cut_z_changed)
  449. self.ui.add_area_button.clicked.connect(self.on_add_area_click)
  450. self.ui.delete_area_button.clicked.connect(self.on_clear_area_click)
  451. def on_cut_z_changed(self):
  452. self.old_cutz = self.ui.cutz_entry.get_value()
  453. def set_tool_offset_visibility(self, current_row):
  454. if current_row is None:
  455. return
  456. try:
  457. tool_offset = self.ui.geo_tools_table.cellWidget(current_row, 2)
  458. if tool_offset is not None:
  459. tool_offset_txt = tool_offset.currentText()
  460. if tool_offset_txt == 'Custom':
  461. self.ui.tool_offset_entry.show()
  462. self.ui.tool_offset_lbl.show()
  463. else:
  464. self.ui.tool_offset_entry.hide()
  465. self.ui.tool_offset_lbl.hide()
  466. except Exception as e:
  467. log.debug("set_tool_offset_visibility() --> " + str(e))
  468. return
  469. def on_offset_value_edited(self):
  470. """
  471. This will save the offset_value into self.tools storage whenever the offset value is edited
  472. :return:
  473. """
  474. for current_row in self.ui.geo_tools_table.selectedItems():
  475. # sometime the header get selected and it has row number -1
  476. # we don't want to do anything with the header :)
  477. if current_row.row() < 0:
  478. continue
  479. tool_uid = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  480. self.set_tool_offset_visibility(current_row.row())
  481. for tooluid_key, tooluid_value in self.tools.items():
  482. if int(tooluid_key) == tool_uid:
  483. try:
  484. tooluid_value['offset_value'] = float(self.ui.tool_offset_entry.get_value())
  485. except ValueError:
  486. # try to convert comma to decimal point. if it's still not working error message and return
  487. try:
  488. tooluid_value['offset_value'] = float(
  489. self.ui.tool_offset_entry.get_value().replace(',', '.')
  490. )
  491. except ValueError:
  492. self.app.inform.emit('[ERROR_NOTCL] %s' %
  493. _("Wrong value format entered, use a number."))
  494. return
  495. def ui_connect(self):
  496. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  497. # changes in geometry UI
  498. for i in self.param_fields:
  499. current_widget = self.param_fields[i]
  500. if isinstance(current_widget, FCCheckBox):
  501. current_widget.stateChanged.connect(self.gui_form_to_storage)
  502. elif isinstance(current_widget, FCComboBox):
  503. current_widget.currentIndexChanged.connect(self.gui_form_to_storage)
  504. elif isinstance(current_widget, FloatEntry) or isinstance(current_widget, LengthEntry) or \
  505. isinstance(current_widget, FCEntry) or isinstance(current_widget, IntEntry):
  506. current_widget.editingFinished.connect(self.gui_form_to_storage)
  507. elif isinstance(current_widget, FCSpinner) or isinstance(current_widget, FCDoubleSpinner):
  508. current_widget.returnPressed.connect(self.gui_form_to_storage)
  509. for row in range(self.ui.geo_tools_table.rowCount()):
  510. for col in [2, 3, 4]:
  511. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.connect(
  512. self.on_tooltable_cellwidget_change)
  513. # I use lambda's because the connected functions have parameters that could be used in certain scenarios
  514. self.ui.addtool_btn.clicked.connect(lambda: self.on_tool_add())
  515. self.ui.copytool_btn.clicked.connect(lambda: self.on_tool_copy())
  516. self.ui.deltool_btn.clicked.connect(lambda: self.on_tool_delete())
  517. # self.ui.geo_tools_table.currentItemChanged.connect(self.on_row_selection_change)
  518. self.ui.geo_tools_table.clicked.connect(self.on_row_selection_change)
  519. self.ui.geo_tools_table.horizontalHeader().sectionClicked.connect(self.on_row_selection_change)
  520. self.ui.geo_tools_table.itemChanged.connect(self.on_tool_edit)
  521. self.ui.tool_offset_entry.returnPressed.connect(self.on_offset_value_edited)
  522. for row in range(self.ui.geo_tools_table.rowCount()):
  523. self.ui.geo_tools_table.cellWidget(row, 6).clicked.connect(self.on_plot_cb_click_table)
  524. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  525. # common parameters update
  526. self.ui.pp_geometry_name_cb.currentIndexChanged.connect(self.update_common_param_in_storage)
  527. def ui_disconnect(self):
  528. # on any change to the widgets that matter it will be called self.gui_form_to_storage which will save the
  529. # changes in geometry UI
  530. for i in self.param_fields:
  531. # current_widget = self.ui.grid3.itemAt(i).widget()
  532. current_widget = self.param_fields[i]
  533. if isinstance(current_widget, FCCheckBox):
  534. try:
  535. current_widget.stateChanged.disconnect(self.gui_form_to_storage)
  536. except (TypeError, AttributeError):
  537. pass
  538. elif isinstance(current_widget, FCComboBox):
  539. try:
  540. current_widget.currentIndexChanged.disconnect(self.gui_form_to_storage)
  541. except (TypeError, AttributeError):
  542. pass
  543. elif isinstance(current_widget, LengthEntry) or isinstance(current_widget, IntEntry) or \
  544. isinstance(current_widget, FCEntry) or isinstance(current_widget, FloatEntry):
  545. try:
  546. current_widget.editingFinished.disconnect(self.gui_form_to_storage)
  547. except (TypeError, AttributeError):
  548. pass
  549. elif isinstance(current_widget, FCSpinner) or isinstance(current_widget, FCDoubleSpinner):
  550. try:
  551. current_widget.returnPressed.disconnect(self.gui_form_to_storage)
  552. except TypeError:
  553. pass
  554. for row in range(self.ui.geo_tools_table.rowCount()):
  555. for col in [2, 3, 4]:
  556. try:
  557. self.ui.geo_tools_table.cellWidget(row, col).currentIndexChanged.disconnect()
  558. except (TypeError, AttributeError):
  559. pass
  560. try:
  561. self.ui.addtool_btn.clicked.disconnect()
  562. except (TypeError, AttributeError):
  563. pass
  564. try:
  565. self.ui.copytool_btn.clicked.disconnect()
  566. except (TypeError, AttributeError):
  567. pass
  568. try:
  569. self.ui.deltool_btn.clicked.disconnect()
  570. except (TypeError, AttributeError):
  571. pass
  572. try:
  573. self.ui.geo_tools_table.clicked.disconnect()
  574. except (TypeError, AttributeError):
  575. pass
  576. try:
  577. self.ui.geo_tools_table.horizontalHeader().sectionClicked.disconnect()
  578. except (TypeError, AttributeError):
  579. pass
  580. try:
  581. self.ui.geo_tools_table.itemChanged.disconnect()
  582. except (TypeError, AttributeError):
  583. pass
  584. try:
  585. self.ui.tool_offset_entry.returnPressed.disconnect()
  586. except (TypeError, AttributeError):
  587. pass
  588. for row in range(self.ui.geo_tools_table.rowCount()):
  589. try:
  590. self.ui.geo_tools_table.cellWidget(row, 6).clicked.disconnect()
  591. except (TypeError, AttributeError):
  592. pass
  593. try:
  594. self.ui.plot_cb.stateChanged.disconnect()
  595. except (TypeError, AttributeError):
  596. pass
  597. def on_row_selection_change(self):
  598. self.update_ui()
  599. def update_ui(self, row=None):
  600. self.ui_disconnect()
  601. if row is None:
  602. sel_rows = []
  603. sel_items = self.ui.geo_tools_table.selectedItems()
  604. for it in sel_items:
  605. sel_rows.append(it.row())
  606. else:
  607. sel_rows = row if type(row) == list else [row]
  608. if not sel_rows:
  609. sel_rows = [0]
  610. for current_row in sel_rows:
  611. self.set_tool_offset_visibility(current_row)
  612. # populate the form with the data from the tool associated with the row parameter
  613. try:
  614. item = self.ui.geo_tools_table.item(current_row, 5)
  615. if type(item) is not None:
  616. tooluid = int(item.text())
  617. else:
  618. self.ui_connect()
  619. return
  620. except Exception as e:
  621. log.debug("Tool missing. Add a tool in Geo Tool Table. %s" % str(e))
  622. self.ui_connect()
  623. return
  624. # update the QLabel that shows for which Tool we have the parameters in the UI form
  625. if len(sel_rows) == 1:
  626. self.ui.tool_data_label.setText(
  627. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  628. )
  629. # update the form with the V-Shape fields if V-Shape selected in the geo_tool_table
  630. # also modify the Cut Z form entry to reflect the calculated Cut Z from values got from V-Shape Fields
  631. try:
  632. item = self.ui.geo_tools_table.cellWidget(current_row, 4)
  633. if item is not None:
  634. tool_type_txt = item.currentText()
  635. self.ui_update_v_shape(tool_type_txt=tool_type_txt)
  636. else:
  637. self.ui_connect()
  638. return
  639. except Exception as e:
  640. log.debug("Tool missing in ui_update_v_shape(). Add a tool in Geo Tool Table. %s" % str(e))
  641. return
  642. try:
  643. # set the form with data from the newly selected tool
  644. for tooluid_key, tooluid_value in list(self.tools.items()):
  645. if int(tooluid_key) == tooluid:
  646. for key, value in list(tooluid_value.items()):
  647. if key == 'data':
  648. form_value_storage = tooluid_value['data']
  649. self.update_form(form_value_storage)
  650. if key == 'offset_value':
  651. # update the offset value in the entry even if the entry is hidden
  652. self.ui.tool_offset_entry.set_value(tooluid_value['offset_value'])
  653. if key == 'tool_type' and value == 'V':
  654. self.update_cutz()
  655. except Exception as e:
  656. log.debug("GeometryObject.update_ui() -> %s " % str(e))
  657. else:
  658. self.ui.tool_data_label.setText(
  659. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  660. )
  661. self.ui_connect()
  662. def on_tool_add(self, dia=None):
  663. self.ui_disconnect()
  664. self.units = self.app.defaults['units'].upper()
  665. if dia is not None:
  666. tooldia = dia
  667. else:
  668. tooldia = float(self.ui.addtool_entry.get_value())
  669. # construct a list of all 'tooluid' in the self.tools
  670. # tool_uid_list = []
  671. # for tooluid_key in self.tools:
  672. # tool_uid_list.append(int(tooluid_key))
  673. tool_uid_list = [int(tooluid_key) for tooluid_key in self.tools]
  674. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  675. max_uid = max(tool_uid_list) if tool_uid_list else 0
  676. self.tooluid = max_uid + 1
  677. tooldia = float('%.*f' % (self.decimals, tooldia))
  678. # here we actually add the new tool; if there is no tool in the tool table we add a tool with default data
  679. # otherwise we add a tool with data copied from last tool
  680. if self.tools:
  681. last_data = self.tools[max_uid]['data']
  682. last_offset = self.tools[max_uid]['offset']
  683. last_offset_value = self.tools[max_uid]['offset_value']
  684. last_type = self.tools[max_uid]['type']
  685. last_tool_type = self.tools[max_uid]['tool_type']
  686. last_solid_geometry = self.tools[max_uid]['solid_geometry']
  687. # if previous geometry was empty (it may happen for the first tool added)
  688. # then copy the object.solid_geometry
  689. if not last_solid_geometry:
  690. last_solid_geometry = self.solid_geometry
  691. self.tools.update({
  692. self.tooluid: {
  693. 'tooldia': tooldia,
  694. 'offset': last_offset,
  695. 'offset_value': last_offset_value,
  696. 'type': last_type,
  697. 'tool_type': last_tool_type,
  698. 'data': deepcopy(last_data),
  699. 'solid_geometry': deepcopy(last_solid_geometry)
  700. }
  701. })
  702. else:
  703. self.tools.update({
  704. self.tooluid: {
  705. 'tooldia': tooldia,
  706. 'offset': 'Path',
  707. 'offset_value': 0.0,
  708. 'type': _('Rough'),
  709. 'tool_type': 'C1',
  710. 'data': deepcopy(self.default_data),
  711. 'solid_geometry': self.solid_geometry
  712. }
  713. })
  714. self.tools[self.tooluid]['data']['name'] = self.options['name']
  715. self.ui.tool_offset_entry.hide()
  716. self.ui.tool_offset_lbl.hide()
  717. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  718. try:
  719. self.ser_attrs.remove('tools')
  720. except TypeError:
  721. pass
  722. self.ser_attrs.append('tools')
  723. self.app.inform.emit('[success] %s' % _("Tool added in Tool Table."))
  724. self.ui_connect()
  725. self.build_ui()
  726. # if there is no tool left in the Tools Table, enable the parameters GUI
  727. if self.ui.geo_tools_table.rowCount() != 0:
  728. self.ui.geo_param_frame.setDisabled(False)
  729. def on_tool_add_from_db_clicked(self):
  730. """
  731. Called when the user wants to add a new tool from Tools Database. It will create the Tools Database object
  732. and display the Tools Database tab in the form needed for the Tool adding
  733. :return: None
  734. """
  735. # if the Tools Database is already opened focus on it
  736. for idx in range(self.app.ui.plot_tab_area.count()):
  737. if self.app.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  738. self.app.ui.plot_tab_area.setCurrentWidget(self.app.tools_db_tab)
  739. break
  740. self.app.on_tools_database()
  741. self.app.tools_db_tab.ok_to_add = True
  742. self.app.tools_db_tab.buttons_frame.hide()
  743. self.app.tools_db_tab.add_tool_from_db.show()
  744. self.app.tools_db_tab.cancel_tool_from_db.show()
  745. def on_tool_from_db_inserted(self, tool):
  746. """
  747. Called from the Tools DB object through a App method when adding a tool from Tools Database
  748. :param tool: a dict with the tool data
  749. :return: None
  750. """
  751. self.ui_disconnect()
  752. self.units = self.app.defaults['units'].upper()
  753. tooldia = float(tool['tooldia'])
  754. # construct a list of all 'tooluid' in the self.tools
  755. tool_uid_list = []
  756. for tooluid_key in self.tools:
  757. tool_uid_item = int(tooluid_key)
  758. tool_uid_list.append(tool_uid_item)
  759. # find maximum from the temp_uid, add 1 and this is the new 'tooluid'
  760. if not tool_uid_list:
  761. max_uid = 0
  762. else:
  763. max_uid = max(tool_uid_list)
  764. self.tooluid = max_uid + 1
  765. tooldia = float('%.*f' % (self.decimals, tooldia))
  766. self.tools.update({
  767. self.tooluid: {
  768. 'tooldia': tooldia,
  769. 'offset': tool['offset'],
  770. 'offset_value': float(tool['offset_value']),
  771. 'type': tool['type'],
  772. 'tool_type': tool['tool_type'],
  773. 'data': deepcopy(tool['data']),
  774. 'solid_geometry': self.solid_geometry
  775. }
  776. })
  777. self.tools[self.tooluid]['data']['name'] = self.options['name']
  778. self.ui.tool_offset_entry.hide()
  779. self.ui.tool_offset_lbl.hide()
  780. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  781. try:
  782. self.ser_attrs.remove('tools')
  783. except TypeError:
  784. pass
  785. self.ser_attrs.append('tools')
  786. self.ui_connect()
  787. self.build_ui()
  788. # if there is no tool left in the Tools Table, enable the parameters GUI
  789. if self.ui.geo_tools_table.rowCount() != 0:
  790. self.ui.geo_param_frame.setDisabled(False)
  791. def on_tool_copy(self, all_tools=None):
  792. self.ui_disconnect()
  793. # find the tool_uid maximum value in the self.tools
  794. uid_list = []
  795. for key in self.tools:
  796. uid_list.append(int(key))
  797. try:
  798. max_uid = max(uid_list, key=int)
  799. except ValueError:
  800. max_uid = 0
  801. if all_tools is None:
  802. if self.ui.geo_tools_table.selectedItems():
  803. for current_row in self.ui.geo_tools_table.selectedItems():
  804. # sometime the header get selected and it has row number -1
  805. # we don't want to do anything with the header :)
  806. if current_row.row() < 0:
  807. continue
  808. try:
  809. tooluid_copy = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  810. self.set_tool_offset_visibility(current_row.row())
  811. max_uid += 1
  812. self.tools[int(max_uid)] = deepcopy(self.tools[tooluid_copy])
  813. except AttributeError:
  814. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to copy."))
  815. self.ui_connect()
  816. self.build_ui()
  817. return
  818. except Exception as e:
  819. log.debug("on_tool_copy() --> " + str(e))
  820. # deselect the table
  821. # self.ui.geo_tools_table.clearSelection()
  822. else:
  823. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to copy."))
  824. self.ui_connect()
  825. self.build_ui()
  826. return
  827. else:
  828. # we copy all tools in geo_tools_table
  829. try:
  830. temp_tools = deepcopy(self.tools)
  831. max_uid += 1
  832. for tooluid in temp_tools:
  833. self.tools[int(max_uid)] = deepcopy(temp_tools[tooluid])
  834. temp_tools.clear()
  835. except Exception as e:
  836. log.debug("on_tool_copy() --> " + str(e))
  837. # if there are no more tools in geo tools table then hide the tool offset
  838. if not self.tools:
  839. self.ui.tool_offset_entry.hide()
  840. self.ui.tool_offset_lbl.hide()
  841. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  842. try:
  843. self.ser_attrs.remove('tools')
  844. except ValueError:
  845. pass
  846. self.ser_attrs.append('tools')
  847. self.ui_connect()
  848. self.build_ui()
  849. self.app.inform.emit('[success] %s' % _("Tool was copied in Tool Table."))
  850. def on_tool_edit(self, current_item):
  851. self.ui_disconnect()
  852. current_row = current_item.row()
  853. try:
  854. d = float(self.ui.geo_tools_table.item(current_row, 1).text())
  855. except ValueError:
  856. # try to convert comma to decimal point. if it's still not working error message and return
  857. try:
  858. d = float(self.ui.geo_tools_table.item(current_row, 1).text().replace(',', '.'))
  859. except ValueError:
  860. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  861. return
  862. tool_dia = float('%.*f' % (self.decimals, d))
  863. tooluid = int(self.ui.geo_tools_table.item(current_row, 5).text())
  864. self.tools[tooluid]['tooldia'] = tool_dia
  865. try:
  866. self.ser_attrs.remove('tools')
  867. self.ser_attrs.append('tools')
  868. except (TypeError, ValueError):
  869. pass
  870. self.app.inform.emit('[success] %s' % _("Tool was edited in Tool Table."))
  871. self.ui_connect()
  872. self.build_ui()
  873. def on_tool_delete(self, all_tools=None):
  874. self.ui_disconnect()
  875. if all_tools is None:
  876. if self.ui.geo_tools_table.selectedItems():
  877. for current_row in self.ui.geo_tools_table.selectedItems():
  878. # sometime the header get selected and it has row number -1
  879. # we don't want to do anything with the header :)
  880. if current_row.row() < 0:
  881. continue
  882. try:
  883. tooluid_del = int(self.ui.geo_tools_table.item(current_row.row(), 5).text())
  884. self.set_tool_offset_visibility(current_row.row())
  885. temp_tools = deepcopy(self.tools)
  886. for tooluid_key in self.tools:
  887. if int(tooluid_key) == tooluid_del:
  888. # if the self.tools has only one tool and we delete it then we move the solid_geometry
  889. # as a property of the object otherwise there will be nothing to hold it
  890. if len(self.tools) == 1:
  891. self.solid_geometry = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  892. temp_tools.pop(tooluid_del, None)
  893. self.tools = deepcopy(temp_tools)
  894. temp_tools.clear()
  895. except AttributeError:
  896. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to delete."))
  897. self.ui_connect()
  898. self.build_ui()
  899. return
  900. except Exception as e:
  901. log.debug("on_tool_delete() --> " + str(e))
  902. # deselect the table
  903. # self.ui.geo_tools_table.clearSelection()
  904. else:
  905. self.app.inform.emit('[WARNING_NOTCL] %s' % _("Failed. Select a tool to delete."))
  906. self.ui_connect()
  907. self.build_ui()
  908. return
  909. else:
  910. # we delete all tools in geo_tools_table
  911. self.tools.clear()
  912. self.app.plot_all()
  913. # if there are no more tools in geo tools table then hide the tool offset
  914. if not self.tools:
  915. self.ui.tool_offset_entry.hide()
  916. self.ui.tool_offset_lbl.hide()
  917. # we do this HACK to make sure the tools attribute to be serialized is updated in the self.ser_attrs list
  918. try:
  919. self.ser_attrs.remove('tools')
  920. except TypeError:
  921. pass
  922. self.ser_attrs.append('tools')
  923. self.ui_connect()
  924. self.build_ui()
  925. self.app.inform.emit('[success] %s' % _("Tool was deleted in Tool Table."))
  926. obj_active = self.app.collection.get_active()
  927. # if the object was MultiGeo and now it has no tool at all (therefore no geometry)
  928. # we make it back SingleGeo
  929. if self.ui.geo_tools_table.rowCount() <= 0:
  930. obj_active.multigeo = False
  931. obj_active.options['xmin'] = 0
  932. obj_active.options['ymin'] = 0
  933. obj_active.options['xmax'] = 0
  934. obj_active.options['ymax'] = 0
  935. if obj_active.multigeo is True:
  936. try:
  937. xmin, ymin, xmax, ymax = obj_active.bounds()
  938. obj_active.options['xmin'] = xmin
  939. obj_active.options['ymin'] = ymin
  940. obj_active.options['xmax'] = xmax
  941. obj_active.options['ymax'] = ymax
  942. except Exception:
  943. obj_active.options['xmin'] = 0
  944. obj_active.options['ymin'] = 0
  945. obj_active.options['xmax'] = 0
  946. obj_active.options['ymax'] = 0
  947. # if there is no tool left in the Tools Table, disable the parameters GUI
  948. if self.ui.geo_tools_table.rowCount() == 0:
  949. self.ui.geo_param_frame.setDisabled(True)
  950. def ui_update_v_shape(self, tool_type_txt):
  951. if tool_type_txt == 'V':
  952. self.ui.tipdialabel.show()
  953. self.ui.tipdia_entry.show()
  954. self.ui.tipanglelabel.show()
  955. self.ui.tipangle_entry.show()
  956. self.ui.cutz_entry.setDisabled(True)
  957. self.ui.cutzlabel.setToolTip(
  958. _("Disabled because the tool is V-shape.\n"
  959. "For V-shape tools the depth of cut is\n"
  960. "calculated from other parameters like:\n"
  961. "- 'V-tip Angle' -> angle at the tip of the tool\n"
  962. "- 'V-tip Dia' -> diameter at the tip of the tool \n"
  963. "- Tool Dia -> 'Dia' column found in the Tool Table\n"
  964. "NB: a value of zero means that Tool Dia = 'V-tip Dia'")
  965. )
  966. self.ui.cutz_entry.setToolTip(
  967. _("Disabled because the tool is V-shape.\n"
  968. "For V-shape tools the depth of cut is\n"
  969. "calculated from other parameters like:\n"
  970. "- 'V-tip Angle' -> angle at the tip of the tool\n"
  971. "- 'V-tip Dia' -> diameter at the tip of the tool \n"
  972. "- Tool Dia -> 'Dia' column found in the Tool Table\n"
  973. "NB: a value of zero means that Tool Dia = 'V-tip Dia'")
  974. )
  975. self.update_cutz()
  976. else:
  977. self.ui.tipdialabel.hide()
  978. self.ui.tipdia_entry.hide()
  979. self.ui.tipanglelabel.hide()
  980. self.ui.tipangle_entry.hide()
  981. self.ui.cutz_entry.setDisabled(False)
  982. self.ui.cutzlabel.setToolTip(
  983. _("Cutting depth (negative)\n"
  984. "below the copper surface.")
  985. )
  986. self.ui.cutz_entry.setToolTip('')
  987. def update_cutz(self):
  988. vdia = float(self.ui.tipdia_entry.get_value())
  989. half_vangle = float(self.ui.tipangle_entry.get_value()) / 2
  990. row = self.ui.geo_tools_table.currentRow()
  991. tool_uid_item = self.ui.geo_tools_table.item(row, 5)
  992. if tool_uid_item is None:
  993. return
  994. tool_uid = int(tool_uid_item.text())
  995. tool_dia_item = self.ui.geo_tools_table.item(row, 1)
  996. if tool_dia_item is None:
  997. return
  998. tooldia = float(tool_dia_item.text())
  999. try:
  1000. new_cutz = (tooldia - vdia) / (2 * math.tan(math.radians(half_vangle)))
  1001. except ZeroDivisionError:
  1002. new_cutz = self.old_cutz
  1003. new_cutz = float('%.*f' % (self.decimals, new_cutz)) * -1.0 # this value has to be negative
  1004. self.ui.cutz_entry.set_value(new_cutz)
  1005. # store the new CutZ value into storage (self.tools)
  1006. for tooluid_key, tooluid_value in self.tools.items():
  1007. if int(tooluid_key) == tool_uid:
  1008. tooluid_value['data']['cutz'] = new_cutz
  1009. def on_tooltable_cellwidget_change(self):
  1010. cw = self.sender()
  1011. # assert isinstance(cw, FCComboBox) or isinstance(cw, FCCheckBox),\
  1012. # "Expected a FCCombobox or a FCCheckbox got %s" % type(cw)
  1013. cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  1014. cw_row = cw_index.row()
  1015. cw_col = cw_index.column()
  1016. current_uid = int(self.ui.geo_tools_table.item(cw_row, 5).text())
  1017. # store the text of the cellWidget that changed it's index in the self.tools
  1018. for tooluid_key, tooluid_value in self.tools.items():
  1019. if int(tooluid_key) == current_uid:
  1020. cb_txt = cw.currentText()
  1021. if cw_col == 2:
  1022. tooluid_value['offset'] = cb_txt
  1023. if cb_txt == 'Custom':
  1024. self.ui.tool_offset_entry.show()
  1025. self.ui.tool_offset_lbl.show()
  1026. else:
  1027. self.ui.tool_offset_entry.hide()
  1028. self.ui.tool_offset_lbl.hide()
  1029. # reset the offset_value in storage self.tools
  1030. tooluid_value['offset_value'] = 0.0
  1031. elif cw_col == 3:
  1032. # force toolpath type as 'Iso' if the tool type is V-Shape
  1033. if self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText() == 'V':
  1034. tooluid_value['type'] = _('Iso')
  1035. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  1036. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  1037. else:
  1038. tooluid_value['type'] = cb_txt
  1039. elif cw_col == 4:
  1040. tooluid_value['tool_type'] = cb_txt
  1041. # if the tool_type selected is V-Shape then autoselect the toolpath type as Iso
  1042. if cb_txt == 'V':
  1043. idx = self.ui.geo_tools_table.cellWidget(cw_row, 3).findText(_('Iso'))
  1044. self.ui.geo_tools_table.cellWidget(cw_row, 3).setCurrentIndex(idx)
  1045. else:
  1046. self.ui.cutz_entry.set_value(self.old_cutz)
  1047. self.ui_update_v_shape(tool_type_txt=self.ui.geo_tools_table.cellWidget(cw_row, 4).currentText())
  1048. def update_form(self, dict_storage):
  1049. for form_key in self.form_fields:
  1050. for storage_key in dict_storage:
  1051. if form_key == storage_key:
  1052. try:
  1053. self.form_fields[form_key].set_value(dict_storage[form_key])
  1054. except Exception as e:
  1055. log.debug(str(e))
  1056. # this is done here because those buttons control through OptionalInputSelection if some entry's are Enabled
  1057. # or not. But due of using the ui_disconnect() status is no longer updated and I had to do it here
  1058. self.ui.ois_dwell_geo.on_cb_change()
  1059. self.ui.ois_mpass_geo.on_cb_change()
  1060. self.ui.ois_tcz_geo.on_cb_change()
  1061. def on_apply_param_to_all_clicked(self):
  1062. if self.ui.geo_tools_table.rowCount() == 0:
  1063. # there is no tool in tool table so we can't save the GUI elements values to storage
  1064. log.debug("GeometryObject.gui_form_to_storage() --> no tool in Tools Table, aborting.")
  1065. return
  1066. self.ui_disconnect()
  1067. row = self.ui.geo_tools_table.currentRow()
  1068. if row < 0:
  1069. row = 0
  1070. # store all the data associated with the row parameter to the self.tools storage
  1071. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  1072. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  1073. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  1074. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  1075. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  1076. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  1077. temp_tools = {}
  1078. temp_dia = {}
  1079. temp_data = {}
  1080. for tooluid_key, tooluid_value in self.tools.items():
  1081. for key, value in tooluid_value.items():
  1082. if key == 'tooldia':
  1083. temp_dia[key] = tooldia_item
  1084. # update the 'offset', 'type' and 'tool_type' sections
  1085. if key == 'offset':
  1086. temp_dia[key] = offset_item
  1087. if key == 'type':
  1088. temp_dia[key] = type_item
  1089. if key == 'tool_type':
  1090. temp_dia[key] = tool_type_item
  1091. if key == 'offset_value':
  1092. temp_dia[key] = offset_value_item
  1093. if key == 'data':
  1094. # update the 'data' section
  1095. for data_key in tooluid_value[key].keys():
  1096. for form_key, form_value in self.form_fields.items():
  1097. if form_key == data_key:
  1098. temp_data[data_key] = form_value.get_value()
  1099. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  1100. # updated from self.app.defaults
  1101. if data_key not in self.form_fields:
  1102. temp_data[data_key] = value[data_key]
  1103. temp_dia[key] = deepcopy(temp_data)
  1104. temp_data.clear()
  1105. if key == 'solid_geometry':
  1106. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  1107. temp_tools[tooluid_key] = deepcopy(temp_dia)
  1108. self.tools.clear()
  1109. self.tools = deepcopy(temp_tools)
  1110. temp_tools.clear()
  1111. self.ui_connect()
  1112. def gui_form_to_storage(self):
  1113. if self.ui.geo_tools_table.rowCount() == 0:
  1114. # there is no tool in tool table so we can't save the GUI elements values to storage
  1115. log.debug("GeometryObject.gui_form_to_storage() --> no tool in Tools Table, aborting.")
  1116. return
  1117. self.ui_disconnect()
  1118. widget_changed = self.sender()
  1119. try:
  1120. widget_idx = self.ui.grid3.indexOf(widget_changed)
  1121. except Exception:
  1122. return
  1123. # those are the indexes for the V-Tip Dia and V-Tip Angle, if edited calculate the new Cut Z
  1124. if widget_idx == 1 or widget_idx == 3:
  1125. self.update_cutz()
  1126. # the original connect() function of the OptionalInputSelection is no longer working because of the
  1127. # ui_diconnect() so I use this 'hack'
  1128. if isinstance(widget_changed, FCCheckBox):
  1129. if widget_changed.text() == 'Multi-Depth:':
  1130. self.ui.ois_mpass_geo.on_cb_change()
  1131. if widget_changed.text() == 'Tool change':
  1132. self.ui.ois_tcz_geo.on_cb_change()
  1133. if widget_changed.text() == 'Dwell:':
  1134. self.ui.ois_dwell_geo.on_cb_change()
  1135. row = self.ui.geo_tools_table.currentRow()
  1136. if row < 0:
  1137. row = 0
  1138. # store all the data associated with the row parameter to the self.tools storage
  1139. tooldia_item = float(self.ui.geo_tools_table.item(row, 1).text())
  1140. offset_item = self.ui.geo_tools_table.cellWidget(row, 2).currentText()
  1141. type_item = self.ui.geo_tools_table.cellWidget(row, 3).currentText()
  1142. tool_type_item = self.ui.geo_tools_table.cellWidget(row, 4).currentText()
  1143. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  1144. offset_value_item = float(self.ui.tool_offset_entry.get_value())
  1145. # this new dict will hold the actual useful data, another dict that is the value of key 'data'
  1146. temp_tools = {}
  1147. temp_dia = {}
  1148. temp_data = {}
  1149. for tooluid_key, tooluid_value in self.tools.items():
  1150. if int(tooluid_key) == tooluid_item:
  1151. for key, value in tooluid_value.items():
  1152. if key == 'tooldia':
  1153. temp_dia[key] = tooldia_item
  1154. # update the 'offset', 'type' and 'tool_type' sections
  1155. if key == 'offset':
  1156. temp_dia[key] = offset_item
  1157. if key == 'type':
  1158. temp_dia[key] = type_item
  1159. if key == 'tool_type':
  1160. temp_dia[key] = tool_type_item
  1161. if key == 'offset_value':
  1162. temp_dia[key] = offset_value_item
  1163. if key == 'data':
  1164. # update the 'data' section
  1165. for data_key in tooluid_value[key].keys():
  1166. for form_key, form_value in self.form_fields.items():
  1167. if form_key == data_key:
  1168. temp_data[data_key] = form_value.get_value()
  1169. # make sure we make a copy of the keys not in the form (we may use 'data' keys that are
  1170. # updated from self.app.defaults
  1171. if data_key not in self.form_fields:
  1172. temp_data[data_key] = value[data_key]
  1173. temp_dia[key] = deepcopy(temp_data)
  1174. temp_data.clear()
  1175. if key == 'solid_geometry':
  1176. temp_dia[key] = deepcopy(self.tools[tooluid_key]['solid_geometry'])
  1177. temp_tools[tooluid_key] = deepcopy(temp_dia)
  1178. else:
  1179. temp_tools[tooluid_key] = deepcopy(tooluid_value)
  1180. self.tools.clear()
  1181. self.tools = deepcopy(temp_tools)
  1182. temp_tools.clear()
  1183. self.ui_connect()
  1184. def update_common_param_in_storage(self):
  1185. for tooluid_value in self.tools.values():
  1186. tooluid_value['data']['ppname_g'] = self.ui.pp_geometry_name_cb.get_value()
  1187. def select_tools_table_row(self, row, clearsel=None):
  1188. if clearsel:
  1189. self.ui.geo_tools_table.clearSelection()
  1190. if self.ui.geo_tools_table.rowCount() > 0:
  1191. # self.ui.geo_tools_table.item(row, 0).setSelected(True)
  1192. self.ui.geo_tools_table.setCurrentItem(self.ui.geo_tools_table.item(row, 0))
  1193. def export_dxf(self):
  1194. dwg = None
  1195. try:
  1196. dwg = ezdxf.new('R2010')
  1197. msp = dwg.modelspace()
  1198. def g2dxf(dxf_space, geo_obj):
  1199. if isinstance(geo_obj, MultiPolygon):
  1200. for poly in geo_obj:
  1201. ext_points = list(poly.exterior.coords)
  1202. dxf_space.add_lwpolyline(ext_points)
  1203. for interior in poly.interiors:
  1204. dxf_space.add_lwpolyline(list(interior.coords))
  1205. if isinstance(geo_obj, Polygon):
  1206. ext_points = list(geo_obj.exterior.coords)
  1207. dxf_space.add_lwpolyline(ext_points)
  1208. for interior in geo_obj.interiors:
  1209. dxf_space.add_lwpolyline(list(interior.coords))
  1210. if isinstance(geo_obj, MultiLineString):
  1211. for line in geo_obj:
  1212. dxf_space.add_lwpolyline(list(line.coords))
  1213. if isinstance(geo_obj, LineString) or isinstance(geo_obj, LinearRing):
  1214. dxf_space.add_lwpolyline(list(geo_obj.coords))
  1215. multigeo_solid_geometry = []
  1216. if self.multigeo:
  1217. for tool in self.tools:
  1218. multigeo_solid_geometry += self.tools[tool]['solid_geometry']
  1219. else:
  1220. multigeo_solid_geometry = self.solid_geometry
  1221. for geo in multigeo_solid_geometry:
  1222. if type(geo) == list:
  1223. for g in geo:
  1224. g2dxf(msp, g)
  1225. else:
  1226. g2dxf(msp, geo)
  1227. # points = GeometryObject.get_pts(geo)
  1228. # msp.add_lwpolyline(points)
  1229. except Exception as e:
  1230. log.debug(str(e))
  1231. return dwg
  1232. def get_selected_tools_table_items(self):
  1233. """
  1234. Returns a list of lists, each list in the list is made out of row elements
  1235. :return: List of table_tools items.
  1236. :rtype: list
  1237. """
  1238. table_tools_items = []
  1239. if self.multigeo:
  1240. for x in self.ui.geo_tools_table.selectedItems():
  1241. elem = []
  1242. txt = ''
  1243. for column in range(0, self.ui.geo_tools_table.columnCount()):
  1244. try:
  1245. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  1246. except AttributeError:
  1247. try:
  1248. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  1249. except AttributeError:
  1250. pass
  1251. elem.append(txt)
  1252. table_tools_items.append(deepcopy(elem))
  1253. # table_tools_items.append([self.ui.geo_tools_table.item(x.row(), column).text()
  1254. # for column in range(0, self.ui.geo_tools_table.columnCount())])
  1255. else:
  1256. for x in self.ui.geo_tools_table.selectedItems():
  1257. r = []
  1258. txt = ''
  1259. # the last 2 columns for single-geo geometry are irrelevant and create problems reading
  1260. # so we don't read them
  1261. for column in range(0, self.ui.geo_tools_table.columnCount() - 2):
  1262. # the columns have items that have text but also have items that are widgets
  1263. # for which the text they hold has to be read differently
  1264. try:
  1265. txt = self.ui.geo_tools_table.item(x.row(), column).text()
  1266. except AttributeError:
  1267. try:
  1268. txt = self.ui.geo_tools_table.cellWidget(x.row(), column).currentText()
  1269. except AttributeError:
  1270. pass
  1271. r.append(txt)
  1272. table_tools_items.append(r)
  1273. for item in table_tools_items:
  1274. item[0] = str(item[0])
  1275. return table_tools_items
  1276. def on_pp_changed(self):
  1277. current_pp = self.ui.pp_geometry_name_cb.get_value()
  1278. if current_pp == 'hpgl':
  1279. self.old_pp_state = self.ui.mpass_cb.get_value()
  1280. self.old_toolchangeg_state = self.ui.toolchangeg_cb.get_value()
  1281. self.ui.mpass_cb.set_value(False)
  1282. self.ui.mpass_cb.setDisabled(True)
  1283. self.ui.toolchangeg_cb.set_value(True)
  1284. self.ui.toolchangeg_cb.setDisabled(True)
  1285. else:
  1286. self.ui.mpass_cb.set_value(self.old_pp_state)
  1287. self.ui.mpass_cb.setDisabled(False)
  1288. self.ui.toolchangeg_cb.set_value(self.old_toolchangeg_state)
  1289. self.ui.toolchangeg_cb.setDisabled(False)
  1290. if "toolchange_probe" in current_pp.lower():
  1291. self.ui.pdepth_entry.setVisible(True)
  1292. self.ui.pdepth_label.show()
  1293. self.ui.feedrate_probe_entry.setVisible(True)
  1294. self.ui.feedrate_probe_label.show()
  1295. else:
  1296. self.ui.pdepth_entry.setVisible(False)
  1297. self.ui.pdepth_label.hide()
  1298. self.ui.feedrate_probe_entry.setVisible(False)
  1299. self.ui.feedrate_probe_label.hide()
  1300. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  1301. self.ui.fr_rapidlabel.show()
  1302. self.ui.feedrate_rapid_entry.show()
  1303. else:
  1304. self.ui.fr_rapidlabel.hide()
  1305. self.ui.feedrate_rapid_entry.hide()
  1306. if 'laser' in current_pp.lower():
  1307. self.ui.cutzlabel.hide()
  1308. self.ui.cutz_entry.hide()
  1309. try:
  1310. self.ui.mpass_cb.hide()
  1311. self.ui.maxdepth_entry.hide()
  1312. except AttributeError:
  1313. pass
  1314. if 'marlin' in current_pp.lower():
  1315. self.ui.travelzlabel.setText('%s:' % _("Focus Z"))
  1316. self.ui.endz_label.show()
  1317. self.ui.endz_entry.show()
  1318. else:
  1319. self.ui.travelzlabel.hide()
  1320. self.ui.travelz_entry.hide()
  1321. self.ui.endz_label.hide()
  1322. self.ui.endz_entry.hide()
  1323. try:
  1324. self.ui.frzlabel.hide()
  1325. self.ui.feedrate_z_entry.hide()
  1326. except AttributeError:
  1327. pass
  1328. self.ui.dwell_cb.hide()
  1329. self.ui.dwelltime_entry.hide()
  1330. self.ui.spindle_label.setText('%s:' % _("Laser Power"))
  1331. try:
  1332. self.ui.tool_offset_label.hide()
  1333. self.ui.offset_entry.hide()
  1334. except AttributeError:
  1335. pass
  1336. else:
  1337. self.ui.cutzlabel.show()
  1338. self.ui.cutz_entry.show()
  1339. try:
  1340. self.ui.mpass_cb.show()
  1341. self.ui.maxdepth_entry.show()
  1342. except AttributeError:
  1343. pass
  1344. self.ui.travelzlabel.setText('%s:' % _('Travel Z'))
  1345. self.ui.travelzlabel.show()
  1346. self.ui.travelz_entry.show()
  1347. self.ui.endz_label.show()
  1348. self.ui.endz_entry.show()
  1349. try:
  1350. self.ui.frzlabel.show()
  1351. self.ui.feedrate_z_entry.show()
  1352. except AttributeError:
  1353. pass
  1354. self.ui.dwell_cb.show()
  1355. self.ui.dwelltime_entry.show()
  1356. self.ui.spindle_label.setText('%s:' % _('Spindle speed'))
  1357. try:
  1358. self.ui.tool_offset_lbl.show()
  1359. self.ui.offset_entry.show()
  1360. except AttributeError:
  1361. pass
  1362. def on_generatecnc_button_click(self, *args):
  1363. log.debug("Generating CNCJob from Geometry ...")
  1364. self.app.defaults.report_usage("geometry_on_generatecnc_button")
  1365. # this reads the values in the UI form to the self.options dictionary
  1366. self.read_form()
  1367. self.sel_tools = {}
  1368. try:
  1369. if self.special_group:
  1370. self.app.inform.emit(
  1371. '[WARNING_NOTCL] %s %s %s.' %
  1372. (_("This Geometry can't be processed because it is"), str(self.special_group), _("geometry"))
  1373. )
  1374. return
  1375. except AttributeError:
  1376. pass
  1377. # test to see if we have tools available in the tool table
  1378. if self.ui.geo_tools_table.selectedItems():
  1379. for x in self.ui.geo_tools_table.selectedItems():
  1380. # try:
  1381. # tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text())
  1382. # except ValueError:
  1383. # # try to convert comma to decimal point. if it's still not working error message and return
  1384. # try:
  1385. # tooldia = float(self.ui.geo_tools_table.item(x.row(), 1).text().replace(',', '.'))
  1386. # except ValueError:
  1387. # self.app.inform.emit('[ERROR_NOTCL] %s' %
  1388. # _("Wrong value format entered, use a number."))
  1389. # return
  1390. tooluid = int(self.ui.geo_tools_table.item(x.row(), 5).text())
  1391. for tooluid_key, tooluid_value in self.tools.items():
  1392. if int(tooluid_key) == tooluid:
  1393. self.sel_tools.update({
  1394. tooluid: deepcopy(tooluid_value)
  1395. })
  1396. self.mtool_gen_cncjob()
  1397. self.ui.geo_tools_table.clearSelection()
  1398. elif self.ui.geo_tools_table.rowCount() == 1:
  1399. tooluid = int(self.ui.geo_tools_table.item(0, 5).text())
  1400. for tooluid_key, tooluid_value in self.tools.items():
  1401. if int(tooluid_key) == tooluid:
  1402. self.sel_tools.update({
  1403. tooluid: deepcopy(tooluid_value)
  1404. })
  1405. self.mtool_gen_cncjob()
  1406. self.ui.geo_tools_table.clearSelection()
  1407. else:
  1408. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No tool selected in the tool table ..."))
  1409. def mtool_gen_cncjob(self, outname=None, tools_dict=None, tools_in_use=None, segx=None, segy=None,
  1410. plot=True, use_thread=True):
  1411. """
  1412. Creates a multi-tool CNCJob out of this Geometry object.
  1413. The actual work is done by the target CNCJobObject object's
  1414. `generate_from_geometry_2()` method.
  1415. :param outname:
  1416. :param tools_dict: a dictionary that holds the whole data needed to create the Gcode
  1417. (including the solid_geometry)
  1418. :param tools_in_use: the tools that are used, needed by some preprocessors
  1419. :type tools_in_use list of lists, each list in the list is made out of row elements of tools table from GUI
  1420. :param segx: number of segments on the X axis, for auto-levelling
  1421. :param segy: number of segments on the Y axis, for auto-levelling
  1422. :param plot: if True the generated object will be plotted; if False will not be plotted
  1423. :param use_thread: if True use threading
  1424. :return: None
  1425. """
  1426. # use the name of the first tool selected in self.geo_tools_table which has the diameter passed as tool_dia
  1427. outname = "%s_%s" % (self.options["name"], 'cnc') if outname is None else outname
  1428. tools_dict = self.sel_tools if tools_dict is None else tools_dict
  1429. tools_in_use = tools_in_use if tools_in_use is not None else self.get_selected_tools_table_items()
  1430. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  1431. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  1432. try:
  1433. xmin = self.options['xmin']
  1434. ymin = self.options['ymin']
  1435. xmax = self.options['xmax']
  1436. ymax = self.options['ymax']
  1437. except Exception as e:
  1438. log.debug("FlatCAMObj.GeometryObject.mtool_gen_cncjob() --> %s\n" % str(e))
  1439. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  1440. msg += '%s %s' % ('FlatCAMObj.GeometryObject.mtool_gen_cncjob() -->', str(e))
  1441. msg += traceback.format_exc()
  1442. self.app.inform.emit(msg)
  1443. return
  1444. # Object initialization function for app.new_object()
  1445. # RUNNING ON SEPARATE THREAD!
  1446. def job_init_single_geometry(job_obj, app_obj):
  1447. log.debug("Creating a CNCJob out of a single-geometry")
  1448. assert job_obj.kind == 'cncjob', "Initializer expected a CNCJobObject, got %s" % type(job_obj)
  1449. job_obj.options['xmin'] = xmin
  1450. job_obj.options['ymin'] = ymin
  1451. job_obj.options['xmax'] = xmax
  1452. job_obj.options['ymax'] = ymax
  1453. # count the tools
  1454. tool_cnt = 0
  1455. # dia_cnc_dict = {}
  1456. # this turn on the FlatCAMCNCJob plot for multiple tools
  1457. job_obj.multitool = True
  1458. job_obj.multigeo = False
  1459. job_obj.cnc_tools.clear()
  1460. job_obj.options['Tools_in_use'] = tools_in_use
  1461. job_obj.segx = segx if segx else float(self.app.defaults["geometry_segx"])
  1462. job_obj.segy = segy if segy else float(self.app.defaults["geometry_segy"])
  1463. job_obj.z_pdepth = float(self.app.defaults["geometry_z_pdepth"])
  1464. job_obj.feedrate_probe = float(self.app.defaults["geometry_feedrate_probe"])
  1465. for tooluid_key in list(tools_dict.keys()):
  1466. tool_cnt += 1
  1467. dia_cnc_dict = deepcopy(tools_dict[tooluid_key])
  1468. tooldia_val = float('%.*f' % (self.decimals, float(tools_dict[tooluid_key]['tooldia'])))
  1469. dia_cnc_dict.update({
  1470. 'tooldia': tooldia_val
  1471. })
  1472. if dia_cnc_dict['offset'] == 'in':
  1473. tool_offset = -dia_cnc_dict['tooldia'] / 2
  1474. elif dia_cnc_dict['offset'].lower() == 'out':
  1475. tool_offset = dia_cnc_dict['tooldia'] / 2
  1476. elif dia_cnc_dict['offset'].lower() == 'custom':
  1477. try:
  1478. offset_value = float(self.ui.tool_offset_entry.get_value())
  1479. except ValueError:
  1480. # try to convert comma to decimal point. if it's still not working error message and return
  1481. try:
  1482. offset_value = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  1483. except ValueError:
  1484. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Wrong value format entered, use a number."))
  1485. return
  1486. if offset_value:
  1487. tool_offset = float(offset_value)
  1488. else:
  1489. self.app.inform.emit(
  1490. '[WARNING] %s' % _("Tool Offset is selected in Tool Table but no value is provided.\n"
  1491. "Add a Tool Offset or change the Offset Type.")
  1492. )
  1493. return
  1494. else:
  1495. tool_offset = 0.0
  1496. dia_cnc_dict.update({
  1497. 'offset_value': tool_offset
  1498. })
  1499. z_cut = tools_dict[tooluid_key]['data']["cutz"]
  1500. z_move = tools_dict[tooluid_key]['data']["travelz"]
  1501. feedrate = tools_dict[tooluid_key]['data']["feedrate"]
  1502. feedrate_z = tools_dict[tooluid_key]['data']["feedrate_z"]
  1503. feedrate_rapid = tools_dict[tooluid_key]['data']["feedrate_rapid"]
  1504. multidepth = tools_dict[tooluid_key]['data']["multidepth"]
  1505. extracut = tools_dict[tooluid_key]['data']["extracut"]
  1506. extracut_length = tools_dict[tooluid_key]['data']["extracut_length"]
  1507. depthpercut = tools_dict[tooluid_key]['data']["depthperpass"]
  1508. toolchange = tools_dict[tooluid_key]['data']["toolchange"]
  1509. toolchangez = tools_dict[tooluid_key]['data']["toolchangez"]
  1510. toolchangexy = tools_dict[tooluid_key]['data']["toolchangexy"]
  1511. startz = tools_dict[tooluid_key]['data']["startz"]
  1512. endz = tools_dict[tooluid_key]['data']["endz"]
  1513. endxy = self.options["endxy"]
  1514. spindlespeed = tools_dict[tooluid_key]['data']["spindlespeed"]
  1515. dwell = tools_dict[tooluid_key]['data']["dwell"]
  1516. dwelltime = tools_dict[tooluid_key]['data']["dwelltime"]
  1517. pp_geometry_name = tools_dict[tooluid_key]['data']["ppname_g"]
  1518. spindledir = self.app.defaults['geometry_spindledir']
  1519. tool_solid_geometry = self.solid_geometry
  1520. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  1521. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  1522. # Propagate options
  1523. job_obj.options["tooldia"] = tooldia_val
  1524. job_obj.options['type'] = 'Geometry'
  1525. job_obj.options['tool_dia'] = tooldia_val
  1526. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  1527. # to a value of 0.0005 which is 20 times less than 0.01
  1528. tol = float(self.app.defaults['global_tolerance']) / 20
  1529. res = job_obj.generate_from_geometry_2(
  1530. self, tooldia=tooldia_val, offset=tool_offset, tolerance=tol,
  1531. z_cut=z_cut, z_move=z_move,
  1532. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  1533. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  1534. multidepth=multidepth, depthpercut=depthpercut,
  1535. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz, endxy=endxy,
  1536. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  1537. pp_geometry_name=pp_geometry_name,
  1538. tool_no=tool_cnt)
  1539. if res == 'fail':
  1540. log.debug("GeometryObject.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  1541. return 'fail'
  1542. else:
  1543. dia_cnc_dict['gcode'] = res
  1544. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  1545. # object is the source of gcode
  1546. job_obj.toolchange_xy_type = "geometry"
  1547. self.app.inform.emit('[success] %s' % _("G-Code parsing in progress..."))
  1548. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  1549. self.app.inform.emit('[success] %s' % _("G-Code parsing finished..."))
  1550. # TODO this serve for bounding box creation only; should be optimized
  1551. # commented this; there is no need for the actual GCode geometry - the original one will serve as well
  1552. # for bounding box values
  1553. # dia_cnc_dict['solid_geometry'] = cascaded_union([geo['geom'] for geo in dia_cnc_dict['gcode_parsed']])
  1554. try:
  1555. dia_cnc_dict['solid_geometry'] = tool_solid_geometry
  1556. self.app.inform.emit('[success] %s...' % _("Finished G-Code processing"))
  1557. except Exception as er:
  1558. self.app.inform.emit('[ERROR] %s: %s' % (_("G-Code processing failed with error"), str(er)))
  1559. job_obj.cnc_tools.update({
  1560. tooluid_key: deepcopy(dia_cnc_dict)
  1561. })
  1562. dia_cnc_dict.clear()
  1563. # Object initialization function for app.new_object()
  1564. # RUNNING ON SEPARATE THREAD!
  1565. def job_init_multi_geometry(job_obj, app_obj):
  1566. log.debug("Creating a CNCJob out of a multi-geometry")
  1567. assert job_obj.kind == 'cncjob', "Initializer expected a CNCJobObject, got %s" % type(job_obj)
  1568. job_obj.options['xmin'] = xmin
  1569. job_obj.options['ymin'] = ymin
  1570. job_obj.options['xmax'] = xmax
  1571. job_obj.options['ymax'] = ymax
  1572. # count the tools
  1573. tool_cnt = 0
  1574. # dia_cnc_dict = {}
  1575. # this turn on the FlatCAMCNCJob plot for multiple tools
  1576. job_obj.multitool = True
  1577. job_obj.multigeo = True
  1578. job_obj.cnc_tools.clear()
  1579. job_obj.options['Tools_in_use'] = tools_in_use
  1580. job_obj.segx = segx if segx else float(self.app.defaults["geometry_segx"])
  1581. job_obj.segy = segy if segy else float(self.app.defaults["geometry_segy"])
  1582. job_obj.z_pdepth = float(self.app.defaults["geometry_z_pdepth"])
  1583. job_obj.feedrate_probe = float(self.app.defaults["geometry_feedrate_probe"])
  1584. # make sure that trying to make a CNCJob from an empty file is not creating an app crash
  1585. if not self.solid_geometry:
  1586. a = 0
  1587. for tooluid_key in self.tools:
  1588. if self.tools[tooluid_key]['solid_geometry'] is None:
  1589. a += 1
  1590. if a == len(self.tools):
  1591. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('Cancelled. Empty file, it has no geometry'))
  1592. return 'fail'
  1593. for tooluid_key in list(tools_dict.keys()):
  1594. tool_cnt += 1
  1595. dia_cnc_dict = deepcopy(tools_dict[tooluid_key])
  1596. tooldia_val = float('%.*f' % (self.decimals, float(tools_dict[tooluid_key]['tooldia'])))
  1597. dia_cnc_dict.update({
  1598. 'tooldia': tooldia_val
  1599. })
  1600. # find the tool_dia associated with the tooluid_key
  1601. # search in the self.tools for the sel_tool_dia and when found see what tooluid has
  1602. # on the found tooluid in self.tools we also have the solid_geometry that interest us
  1603. # for k, v in self.tools.items():
  1604. # if float('%.*f' % (self.decimals, float(v['tooldia']))) == tooldia_val:
  1605. # current_uid = int(k)
  1606. # break
  1607. if dia_cnc_dict['offset'] == 'in':
  1608. tool_offset = -tooldia_val / 2
  1609. elif dia_cnc_dict['offset'].lower() == 'out':
  1610. tool_offset = tooldia_val / 2
  1611. elif dia_cnc_dict['offset'].lower() == 'custom':
  1612. offset_value = float(self.ui.tool_offset_entry.get_value())
  1613. if offset_value:
  1614. tool_offset = float(offset_value)
  1615. else:
  1616. self.app.inform.emit('[WARNING] %s' %
  1617. _("Tool Offset is selected in Tool Table but "
  1618. "no value is provided.\n"
  1619. "Add a Tool Offset or change the Offset Type."))
  1620. return
  1621. else:
  1622. tool_offset = 0.0
  1623. dia_cnc_dict.update({
  1624. 'offset_value': tool_offset
  1625. })
  1626. z_cut = tools_dict[tooluid_key]['data']["cutz"]
  1627. z_move = tools_dict[tooluid_key]['data']["travelz"]
  1628. feedrate = tools_dict[tooluid_key]['data']["feedrate"]
  1629. feedrate_z = tools_dict[tooluid_key]['data']["feedrate_z"]
  1630. feedrate_rapid = tools_dict[tooluid_key]['data']["feedrate_rapid"]
  1631. multidepth = tools_dict[tooluid_key]['data']["multidepth"]
  1632. extracut = tools_dict[tooluid_key]['data']["extracut"]
  1633. extracut_length = tools_dict[tooluid_key]['data']["extracut_length"]
  1634. depthpercut = tools_dict[tooluid_key]['data']["depthperpass"]
  1635. toolchange = tools_dict[tooluid_key]['data']["toolchange"]
  1636. toolchangez = tools_dict[tooluid_key]['data']["toolchangez"]
  1637. toolchangexy = tools_dict[tooluid_key]['data']["toolchangexy"]
  1638. startz = tools_dict[tooluid_key]['data']["startz"]
  1639. endz = tools_dict[tooluid_key]['data']["endz"]
  1640. endxy = self.options["endxy"]
  1641. spindlespeed = tools_dict[tooluid_key]['data']["spindlespeed"]
  1642. dwell = tools_dict[tooluid_key]['data']["dwell"]
  1643. dwelltime = tools_dict[tooluid_key]['data']["dwelltime"]
  1644. pp_geometry_name = tools_dict[tooluid_key]['data']["ppname_g"]
  1645. spindledir = self.app.defaults['geometry_spindledir']
  1646. tool_solid_geometry = self.tools[tooluid_key]['solid_geometry']
  1647. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  1648. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  1649. # Propagate options
  1650. job_obj.options["tooldia"] = tooldia_val
  1651. job_obj.options['type'] = 'Geometry'
  1652. job_obj.options['tool_dia'] = tooldia_val
  1653. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  1654. # to a value of 0.0005 which is 20 times less than 0.01
  1655. tol = float(self.app.defaults['global_tolerance']) / 20
  1656. res = job_obj.generate_from_multitool_geometry(
  1657. tool_solid_geometry, tooldia=tooldia_val, offset=tool_offset,
  1658. tolerance=tol, z_cut=z_cut, z_move=z_move,
  1659. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  1660. spindlespeed=spindlespeed, spindledir=spindledir, dwell=dwell, dwelltime=dwelltime,
  1661. multidepth=multidepth, depthpercut=depthpercut,
  1662. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz, endxy=endxy,
  1663. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  1664. pp_geometry_name=pp_geometry_name,
  1665. tool_no=tool_cnt)
  1666. if res == 'fail':
  1667. log.debug("GeometryObject.mtool_gen_cncjob() --> generate_from_geometry2() failed")
  1668. return 'fail'
  1669. else:
  1670. dia_cnc_dict['gcode'] = res
  1671. self.app.inform.emit('[success] %s' % _("G-Code parsing in progress..."))
  1672. dia_cnc_dict['gcode_parsed'] = job_obj.gcode_parse()
  1673. self.app.inform.emit('[success] %s' % _("G-Code parsing finished..."))
  1674. # TODO this serve for bounding box creation only; should be optimized
  1675. # commented this; there is no need for the actual GCode geometry - the original one will serve as well
  1676. # for bounding box values
  1677. # geo_for_bound_values = cascaded_union([
  1678. # geo['geom'] for geo in dia_cnc_dict['gcode_parsed'] if geo['geom'].is_valid is True
  1679. # ])
  1680. try:
  1681. dia_cnc_dict['solid_geometry'] = deepcopy(tool_solid_geometry)
  1682. self.app.inform.emit('[success] %s' % _("Finished G-Code processing..."))
  1683. except Exception as ee:
  1684. self.app.inform.emit('[ERROR] %s: %s' % (_("G-Code processing failed with error"), str(ee)))
  1685. # tell gcode_parse from which point to start drawing the lines depending on what kind of
  1686. # object is the source of gcode
  1687. job_obj.toolchange_xy_type = "geometry"
  1688. job_obj.cnc_tools.update({
  1689. tooluid_key: deepcopy(dia_cnc_dict)
  1690. })
  1691. dia_cnc_dict.clear()
  1692. if use_thread:
  1693. # To be run in separate thread
  1694. def job_thread(app_obj):
  1695. if self.multigeo is False:
  1696. with self.app.proc_container.new(_("Generating CNC Code")):
  1697. if app_obj.new_object("cncjob", outname, job_init_single_geometry, plot=plot) != 'fail':
  1698. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created"), outname))
  1699. else:
  1700. with self.app.proc_container.new(_("Generating CNC Code")):
  1701. if app_obj.new_object("cncjob", outname, job_init_multi_geometry) != 'fail':
  1702. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created"), outname))
  1703. # Create a promise with the name
  1704. self.app.collection.promise(outname)
  1705. # Send to worker
  1706. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1707. else:
  1708. if self.solid_geometry:
  1709. self.app.new_object("cncjob", outname, job_init_single_geometry, plot=plot)
  1710. else:
  1711. self.app.new_object("cncjob", outname, job_init_multi_geometry, plot=plot)
  1712. def generatecncjob(
  1713. self, outname=None,
  1714. dia=None, offset=None,
  1715. z_cut=None, z_move=None,
  1716. feedrate=None, feedrate_z=None, feedrate_rapid=None,
  1717. spindlespeed=None, dwell=None, dwelltime=None,
  1718. multidepth=None, depthperpass=None,
  1719. toolchange=None, toolchangez=None, toolchangexy=None,
  1720. extracut=None, extracut_length=None, startz=None, endz=None,
  1721. pp=None,
  1722. segx=None, segy=None,
  1723. use_thread=True,
  1724. plot=True):
  1725. """
  1726. Only used by the TCL Command Cncjob.
  1727. Creates a CNCJob out of this Geometry object. The actual
  1728. work is done by the target camlib.CNCjob
  1729. `generate_from_geometry_2()` method.
  1730. :param outname: Name of the new object
  1731. :param dia: Tool diameter
  1732. :param offset:
  1733. :param z_cut: Cut depth (negative value)
  1734. :param z_move: Height of the tool when travelling (not cutting)
  1735. :param feedrate: Feed rate while cutting on X - Y plane
  1736. :param feedrate_z: Feed rate while cutting on Z plane
  1737. :param feedrate_rapid: Feed rate while moving with rapids
  1738. :param spindlespeed: Spindle speed (RPM)
  1739. :param dwell:
  1740. :param dwelltime:
  1741. :param multidepth:
  1742. :param depthperpass:
  1743. :param toolchange:
  1744. :param toolchangez:
  1745. :param toolchangexy:
  1746. :param extracut:
  1747. :param extracut_length:
  1748. :param startz:
  1749. :param endz:
  1750. :param pp: Name of the preprocessor
  1751. :param segx:
  1752. :param segy:
  1753. :param use_thread:
  1754. :param plot:
  1755. :return: None
  1756. """
  1757. tooldia = dia if dia else float(self.options["cnctooldia"])
  1758. outname = outname if outname is not None else self.options["name"]
  1759. z_cut = z_cut if z_cut is not None else float(self.options["cutz"])
  1760. z_move = z_move if z_move is not None else float(self.options["travelz"])
  1761. feedrate = feedrate if feedrate is not None else float(self.options["feedrate"])
  1762. feedrate_z = feedrate_z if feedrate_z is not None else float(self.options["feedrate_z"])
  1763. feedrate_rapid = feedrate_rapid if feedrate_rapid is not None else float(self.options["feedrate_rapid"])
  1764. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  1765. depthperpass = depthperpass if depthperpass is not None else float(self.options["depthperpass"])
  1766. segx = segx if segx is not None else float(self.app.defaults['geometry_segx'])
  1767. segy = segy if segy is not None else float(self.app.defaults['geometry_segy'])
  1768. extracut = extracut if extracut is not None else float(self.options["extracut"])
  1769. extracut_length = extracut_length if extracut_length is not None else float(self.options["extracut_length"])
  1770. startz = startz if startz is not None else self.options["startz"]
  1771. endz = endz if endz is not None else float(self.options["endz"])
  1772. endxy = self.options["endxy"]
  1773. toolchangez = toolchangez if toolchangez else float(self.options["toolchangez"])
  1774. toolchangexy = toolchangexy if toolchangexy else self.options["toolchangexy"]
  1775. toolchange = toolchange if toolchange else self.options["toolchange"]
  1776. offset = offset if offset else 0.0
  1777. # int or None.
  1778. spindlespeed = spindlespeed if spindlespeed else self.options['spindlespeed']
  1779. dwell = dwell if dwell else self.options["dwell"]
  1780. dwelltime = dwelltime if dwelltime else float(self.options["dwelltime"])
  1781. ppname_g = pp if pp else self.options["ppname_g"]
  1782. # Object initialization function for app.new_object()
  1783. # RUNNING ON SEPARATE THREAD!
  1784. def job_init(job_obj, app_obj):
  1785. assert job_obj.kind == 'cncjob', "Initializer expected a CNCJobObject, got %s" % type(job_obj)
  1786. # Propagate options
  1787. job_obj.options["tooldia"] = tooldia
  1788. job_obj.coords_decimals = self.app.defaults["cncjob_coords_decimals"]
  1789. job_obj.fr_decimals = self.app.defaults["cncjob_fr_decimals"]
  1790. job_obj.options['type'] = 'Geometry'
  1791. job_obj.options['tool_dia'] = tooldia
  1792. job_obj.segx = segx
  1793. job_obj.segy = segy
  1794. job_obj.z_pdepth = float(self.options["z_pdepth"])
  1795. job_obj.feedrate_probe = float(self.options["feedrate_probe"])
  1796. job_obj.options['xmin'] = self.options['xmin']
  1797. job_obj.options['ymin'] = self.options['ymin']
  1798. job_obj.options['xmax'] = self.options['xmax']
  1799. job_obj.options['ymax'] = self.options['ymax']
  1800. # it seems that the tolerance needs to be a lot lower value than 0.01 and it was hardcoded initially
  1801. # to a value of 0.0005 which is 20 times less than 0.01
  1802. tol = float(self.app.defaults['global_tolerance']) / 20
  1803. job_obj.generate_from_geometry_2(
  1804. self, tooldia=tooldia, offset=offset, tolerance=tol,
  1805. z_cut=z_cut, z_move=z_move,
  1806. feedrate=feedrate, feedrate_z=feedrate_z, feedrate_rapid=feedrate_rapid,
  1807. spindlespeed=spindlespeed, dwell=dwell, dwelltime=dwelltime,
  1808. multidepth=multidepth, depthpercut=depthperpass,
  1809. toolchange=toolchange, toolchangez=toolchangez, toolchangexy=toolchangexy,
  1810. extracut=extracut, extracut_length=extracut_length, startz=startz, endz=endz, endxy=endxy,
  1811. pp_geometry_name=ppname_g
  1812. )
  1813. # tell gcode_parse from which point to start drawing the lines depending on what kind of object is the
  1814. # source of gcode
  1815. job_obj.toolchange_xy_type = "geometry"
  1816. job_obj.gcode_parse()
  1817. self.app.inform.emit('[success] %s' % _("Finished G-Code processing..."))
  1818. if use_thread:
  1819. # To be run in separate thread
  1820. def job_thread(app_obj):
  1821. with self.app.proc_container.new(_("Generating CNC Code")):
  1822. app_obj.new_object("cncjob", outname, job_init, plot=plot)
  1823. app_obj.inform.emit('[success] %s: %s' % (_("CNCjob created")), outname)
  1824. # Create a promise with the name
  1825. self.app.collection.promise(outname)
  1826. # Send to worker
  1827. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1828. else:
  1829. self.app.new_object("cncjob", outname, job_init, plot=plot)
  1830. # def on_plot_cb_click(self, *args):
  1831. # if self.muted_ui:
  1832. # return
  1833. # self.read_form_item('plot')
  1834. def scale(self, xfactor, yfactor=None, point=None):
  1835. """
  1836. Scales all geometry by a given factor.
  1837. :param xfactor: Factor by which to scale the object's geometry/
  1838. :type xfactor: float
  1839. :param yfactor: Factor by which to scale the object's geometry/
  1840. :type yfactor: float
  1841. :param point: Point around which to scale
  1842. :return: None
  1843. :rtype: None
  1844. """
  1845. log.debug("FlatCAMObj.GeometryObject.scale()")
  1846. try:
  1847. xfactor = float(xfactor)
  1848. except Exception:
  1849. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scale factor has to be a number: integer or float."))
  1850. return
  1851. if yfactor is None:
  1852. yfactor = xfactor
  1853. else:
  1854. try:
  1855. yfactor = float(yfactor)
  1856. except Exception:
  1857. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Scale factor has to be a number: integer or float."))
  1858. return
  1859. if xfactor == 1 and yfactor == 1:
  1860. return
  1861. if point is None:
  1862. px = 0
  1863. py = 0
  1864. else:
  1865. px, py = point
  1866. self.geo_len = 0
  1867. self.old_disp_number = 0
  1868. self.el_count = 0
  1869. def scale_recursion(geom):
  1870. if type(geom) is list:
  1871. geoms = []
  1872. for local_geom in geom:
  1873. geoms.append(scale_recursion(local_geom))
  1874. return geoms
  1875. else:
  1876. try:
  1877. self.el_count += 1
  1878. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1879. if self.old_disp_number < disp_number <= 100:
  1880. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1881. self.old_disp_number = disp_number
  1882. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  1883. except AttributeError:
  1884. return geom
  1885. if self.multigeo is True:
  1886. for tool in self.tools:
  1887. # variables to display the percentage of work done
  1888. self.geo_len = 0
  1889. try:
  1890. self.geo_len = len(self.tools[tool]['solid_geometry'])
  1891. except TypeError:
  1892. self.geo_len = 1
  1893. self.old_disp_number = 0
  1894. self.el_count = 0
  1895. self.tools[tool]['solid_geometry'] = scale_recursion(self.tools[tool]['solid_geometry'])
  1896. try:
  1897. # variables to display the percentage of work done
  1898. self.geo_len = 0
  1899. try:
  1900. self.geo_len = len(self.solid_geometry)
  1901. except TypeError:
  1902. self.geo_len = 1
  1903. self.old_disp_number = 0
  1904. self.el_count = 0
  1905. self.solid_geometry = scale_recursion(self.solid_geometry)
  1906. except AttributeError:
  1907. self.solid_geometry = []
  1908. return
  1909. self.app.proc_container.new_text = ''
  1910. self.app.inform.emit('[success] %s' % _("Geometry Scale done."))
  1911. def offset(self, vect):
  1912. """
  1913. Offsets all geometry by a given vector/
  1914. :param vect: (x, y) vector by which to offset the object's geometry.
  1915. :type vect: tuple
  1916. :return: None
  1917. :rtype: None
  1918. """
  1919. log.debug("FlatCAMObj.GeometryObject.offset()")
  1920. try:
  1921. dx, dy = vect
  1922. except TypeError:
  1923. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1924. _("An (x,y) pair of values are needed. "
  1925. "Probable you entered only one value in the Offset field.")
  1926. )
  1927. return
  1928. if dx == 0 and dy == 0:
  1929. return
  1930. self.geo_len = 0
  1931. self.old_disp_number = 0
  1932. self.el_count = 0
  1933. def translate_recursion(geom):
  1934. if type(geom) is list:
  1935. geoms = []
  1936. for local_geom in geom:
  1937. geoms.append(translate_recursion(local_geom))
  1938. return geoms
  1939. else:
  1940. try:
  1941. self.el_count += 1
  1942. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1943. if self.old_disp_number < disp_number <= 100:
  1944. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1945. self.old_disp_number = disp_number
  1946. return affinity.translate(geom, xoff=dx, yoff=dy)
  1947. except AttributeError:
  1948. return geom
  1949. if self.multigeo is True:
  1950. for tool in self.tools:
  1951. # variables to display the percentage of work done
  1952. self.geo_len = 0
  1953. try:
  1954. self.geo_len = len(self.tools[tool]['solid_geometry'])
  1955. except TypeError:
  1956. self.geo_len = 1
  1957. self.old_disp_number = 0
  1958. self.el_count = 0
  1959. self.tools[tool]['solid_geometry'] = translate_recursion(self.tools[tool]['solid_geometry'])
  1960. # variables to display the percentage of work done
  1961. self.geo_len = 0
  1962. try:
  1963. self.geo_len = len(self.solid_geometry)
  1964. except TypeError:
  1965. self.geo_len = 1
  1966. self.old_disp_number = 0
  1967. self.el_count = 0
  1968. self.solid_geometry = translate_recursion(self.solid_geometry)
  1969. self.app.proc_container.new_text = ''
  1970. self.app.inform.emit('[success] %s' % _("Geometry Offset done."))
  1971. def convert_units(self, units):
  1972. log.debug("FlatCAMObj.GeometryObject.convert_units()")
  1973. self.ui_disconnect()
  1974. factor = Geometry.convert_units(self, units)
  1975. self.options['cutz'] = float(self.options['cutz']) * factor
  1976. self.options['depthperpass'] = float(self.options['depthperpass']) * factor
  1977. self.options['travelz'] = float(self.options['travelz']) * factor
  1978. self.options['feedrate'] = float(self.options['feedrate']) * factor
  1979. self.options['feedrate_z'] = float(self.options['feedrate_z']) * factor
  1980. self.options['feedrate_rapid'] = float(self.options['feedrate_rapid']) * factor
  1981. self.options['endz'] = float(self.options['endz']) * factor
  1982. # self.options['cnctooldia'] *= factor
  1983. # self.options['painttooldia'] *= factor
  1984. # self.options['paintmargin'] *= factor
  1985. # self.options['paintoverlap'] *= factor
  1986. self.options["toolchangez"] = float(self.options["toolchangez"]) * factor
  1987. if self.app.defaults["geometry_toolchangexy"] == '':
  1988. self.options['toolchangexy'] = "0.0, 0.0"
  1989. else:
  1990. coords_xy = [float(eval(coord)) for coord in self.app.defaults["geometry_toolchangexy"].split(",")]
  1991. if len(coords_xy) < 2:
  1992. self.app.inform.emit('[ERROR] %s' %
  1993. _("The Toolchange X,Y field in Edit -> Preferences "
  1994. "has to be in the format (x, y)\n"
  1995. "but now there is only one value, not two.")
  1996. )
  1997. return 'fail'
  1998. coords_xy[0] *= factor
  1999. coords_xy[1] *= factor
  2000. self.options['toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2001. if self.options['startz'] is not None:
  2002. self.options['startz'] = float(self.options['startz']) * factor
  2003. param_list = ['cutz', 'depthperpass', 'travelz', 'feedrate', 'feedrate_z', 'feedrate_rapid',
  2004. 'endz', 'toolchangez']
  2005. if isinstance(self, GeometryObject):
  2006. temp_tools_dict = {}
  2007. tool_dia_copy = {}
  2008. data_copy = {}
  2009. for tooluid_key, tooluid_value in self.tools.items():
  2010. for dia_key, dia_value in tooluid_value.items():
  2011. if dia_key == 'tooldia':
  2012. dia_value *= factor
  2013. dia_value = float('%.*f' % (self.decimals, dia_value))
  2014. tool_dia_copy[dia_key] = dia_value
  2015. if dia_key == 'offset':
  2016. tool_dia_copy[dia_key] = dia_value
  2017. if dia_key == 'offset_value':
  2018. dia_value *= factor
  2019. tool_dia_copy[dia_key] = dia_value
  2020. # convert the value in the Custom Tool Offset entry in UI
  2021. custom_offset = None
  2022. try:
  2023. custom_offset = float(self.ui.tool_offset_entry.get_value())
  2024. except ValueError:
  2025. # try to convert comma to decimal point. if it's still not working error message and return
  2026. try:
  2027. custom_offset = float(self.ui.tool_offset_entry.get_value().replace(',', '.'))
  2028. except ValueError:
  2029. self.app.inform.emit('[ERROR_NOTCL] %s' %
  2030. _("Wrong value format entered, use a number."))
  2031. return
  2032. except TypeError:
  2033. pass
  2034. if custom_offset:
  2035. custom_offset *= factor
  2036. self.ui.tool_offset_entry.set_value(custom_offset)
  2037. if dia_key == 'type':
  2038. tool_dia_copy[dia_key] = dia_value
  2039. if dia_key == 'tool_type':
  2040. tool_dia_copy[dia_key] = dia_value
  2041. if dia_key == 'data':
  2042. for data_key, data_value in dia_value.items():
  2043. # convert the form fields that are convertible
  2044. for param in param_list:
  2045. if data_key == param and data_value is not None:
  2046. data_copy[data_key] = data_value * factor
  2047. # copy the other dict entries that are not convertible
  2048. if data_key not in param_list:
  2049. data_copy[data_key] = data_value
  2050. tool_dia_copy[dia_key] = deepcopy(data_copy)
  2051. data_copy.clear()
  2052. temp_tools_dict.update({
  2053. tooluid_key: deepcopy(tool_dia_copy)
  2054. })
  2055. tool_dia_copy.clear()
  2056. self.tools.clear()
  2057. self.tools = deepcopy(temp_tools_dict)
  2058. # if there is a value in the new tool field then convert that one too
  2059. try:
  2060. self.ui.addtool_entry.returnPressed.disconnect()
  2061. except TypeError:
  2062. pass
  2063. tooldia = self.ui.addtool_entry.get_value()
  2064. if tooldia:
  2065. tooldia *= factor
  2066. tooldia = float('%.*f' % (self.decimals, tooldia))
  2067. self.ui.addtool_entry.set_value(tooldia)
  2068. self.ui.addtool_entry.returnPressed.connect(self.on_tool_add)
  2069. return factor
  2070. def on_add_area_click(self):
  2071. shape_button = self.ui.area_shape_radio
  2072. overz_button = self.ui.over_z_entry
  2073. strategy_radio = self.ui.strategy_radio
  2074. cnc_button = self.ui.generate_cnc_button
  2075. solid_geo = self.solid_geometry
  2076. obj_type = self.kind
  2077. self.app.exc_areas.on_add_area_click(
  2078. shape_button=shape_button, overz_button=overz_button, cnc_button=cnc_button, strategy_radio=strategy_radio,
  2079. solid_geo=solid_geo, obj_type=obj_type)
  2080. def on_clear_area_click(self):
  2081. self.app.exc_areas.on_clear_area_click()
  2082. def plot_element(self, element, color=None, visible=None):
  2083. if color is None:
  2084. color = '#FF0000FF'
  2085. visible = visible if visible else self.options['plot']
  2086. try:
  2087. for sub_el in element:
  2088. self.plot_element(sub_el, color=color)
  2089. except TypeError: # Element is not iterable...
  2090. # if self.app.is_legacy is False:
  2091. self.add_shape(shape=element, color=color, visible=visible, layer=0)
  2092. def plot(self, visible=None, kind=None):
  2093. """
  2094. Plot the object.
  2095. :param visible: Controls if the added shape is visible of not
  2096. :param kind: added so there is no error when a project is loaded and it has both geometry and CNCJob, because
  2097. CNCJob require the 'kind' parameter. Perhaps the FlatCAMObj.plot() has to be rewrited
  2098. :return:
  2099. """
  2100. # Does all the required setup and returns False
  2101. # if the 'ptint' option is set to False.
  2102. if not FlatCAMObj.plot(self):
  2103. return
  2104. try:
  2105. # plot solid geometries found as members of self.tools attribute dict
  2106. # for MultiGeo
  2107. if self.multigeo is True: # geo multi tool usage
  2108. for tooluid_key in self.tools:
  2109. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  2110. self.plot_element(solid_geometry, visible=visible,
  2111. color=self.app.defaults["geometry_plot_line"])
  2112. else:
  2113. # plot solid geometry that may be an direct attribute of the geometry object
  2114. # for SingleGeo
  2115. if self.solid_geometry:
  2116. self.plot_element(self.solid_geometry, visible=visible,
  2117. color=self.app.defaults["geometry_plot_line"])
  2118. # self.plot_element(self.solid_geometry, visible=self.options['plot'])
  2119. self.shapes.redraw()
  2120. except (ObjectDeleted, AttributeError):
  2121. self.shapes.clear(update=True)
  2122. def on_plot_cb_click(self, *args):
  2123. if self.muted_ui:
  2124. return
  2125. self.read_form_item('plot')
  2126. self.plot()
  2127. self.ui_disconnect()
  2128. cb_flag = self.ui.plot_cb.isChecked()
  2129. for row in range(self.ui.geo_tools_table.rowCount()):
  2130. table_cb = self.ui.geo_tools_table.cellWidget(row, 6)
  2131. if cb_flag:
  2132. table_cb.setChecked(True)
  2133. else:
  2134. table_cb.setChecked(False)
  2135. self.ui_connect()
  2136. def on_plot_cb_click_table(self):
  2137. # self.ui.cnc_tools_table.cellWidget(row, 2).widget().setCheckState(QtCore.Qt.Unchecked)
  2138. self.ui_disconnect()
  2139. # cw = self.sender()
  2140. # cw_index = self.ui.geo_tools_table.indexAt(cw.pos())
  2141. # cw_row = cw_index.row()
  2142. check_row = 0
  2143. self.shapes.clear(update=True)
  2144. for tooluid_key in self.tools:
  2145. solid_geometry = self.tools[tooluid_key]['solid_geometry']
  2146. # find the geo_tool_table row associated with the tooluid_key
  2147. for row in range(self.ui.geo_tools_table.rowCount()):
  2148. tooluid_item = int(self.ui.geo_tools_table.item(row, 5).text())
  2149. if tooluid_item == int(tooluid_key):
  2150. check_row = row
  2151. break
  2152. if self.ui.geo_tools_table.cellWidget(check_row, 6).isChecked():
  2153. self.plot_element(element=solid_geometry, visible=True)
  2154. self.shapes.redraw()
  2155. # make sure that the general plot is disabled if one of the row plot's are disabled and
  2156. # if all the row plot's are enabled also enable the general plot checkbox
  2157. cb_cnt = 0
  2158. total_row = self.ui.geo_tools_table.rowCount()
  2159. for row in range(total_row):
  2160. if self.ui.geo_tools_table.cellWidget(row, 6).isChecked():
  2161. cb_cnt += 1
  2162. else:
  2163. cb_cnt -= 1
  2164. if cb_cnt < total_row:
  2165. self.ui.plot_cb.setChecked(False)
  2166. else:
  2167. self.ui.plot_cb.setChecked(True)
  2168. self.ui_connect()
  2169. @staticmethod
  2170. def merge(geo_list, geo_final, multigeo=None):
  2171. """
  2172. Merges the geometry of objects in grb_list into the geometry of geo_final.
  2173. :param geo_list: List of GerberObject Objects to join.
  2174. :param geo_final: Destination GerberObject object.
  2175. :param multigeo: if the merged geometry objects are of type MultiGeo
  2176. :return: None
  2177. """
  2178. if geo_final.solid_geometry is None:
  2179. geo_final.solid_geometry = []
  2180. try:
  2181. __ = iter(geo_final.solid_geometry)
  2182. except TypeError:
  2183. geo_final.solid_geometry = [geo_final.solid_geometry]
  2184. new_solid_geometry = []
  2185. new_options = {}
  2186. new_tools = {}
  2187. for geo_obj in geo_list:
  2188. for option in geo_obj.options:
  2189. if option != 'name':
  2190. try:
  2191. new_options[option] = deepcopy(geo_obj.options[option])
  2192. except Exception as e:
  2193. log.warning("Failed to copy option %s. Error: %s" % (str(option), str(e)))
  2194. # Expand lists
  2195. if type(geo_obj) is list:
  2196. GeometryObject.merge(geo_list=geo_obj, geo_final=geo_final)
  2197. # If not list, just append
  2198. else:
  2199. if multigeo is None or multigeo is False:
  2200. geo_final.multigeo = False
  2201. else:
  2202. geo_final.multigeo = True
  2203. try:
  2204. new_solid_geometry += deepcopy(geo_obj.solid_geometry)
  2205. except Exception as e:
  2206. log.debug("GeometryObject.merge() --> %s" % str(e))
  2207. # find the tool_uid maximum value in the geo_final
  2208. try:
  2209. max_uid = max([int(i) for i in new_tools.keys()])
  2210. except ValueError:
  2211. max_uid = 0
  2212. # add and merge tools. If what we try to merge as Geometry is Excellon's and/or Gerber's then don't try
  2213. # to merge the obj.tools as it is likely there is none to merge.
  2214. if geo_obj.kind != 'gerber' and geo_obj.kind != 'excellon':
  2215. for tool_uid in geo_obj.tools:
  2216. max_uid += 1
  2217. new_tools[max_uid] = deepcopy(geo_obj.tools[tool_uid])
  2218. geo_final.options.update(new_options)
  2219. geo_final.solid_geometry = new_solid_geometry
  2220. geo_final.tools = new_tools
  2221. @staticmethod
  2222. def get_pts(o):
  2223. """
  2224. Returns a list of all points in the object, where
  2225. the object can be a MultiPolygon, Polygon, Not a polygon, or a list
  2226. of such. Search is done recursively.
  2227. :param: geometric object
  2228. :return: List of points
  2229. :rtype: list
  2230. """
  2231. pts = []
  2232. # Iterable: descend into each item.
  2233. try:
  2234. for subo in o:
  2235. pts += GeometryObject.get_pts(subo)
  2236. # Non-iterable
  2237. except TypeError:
  2238. if o is not None:
  2239. if type(o) == MultiPolygon:
  2240. for poly in o:
  2241. pts += GeometryObject.get_pts(poly)
  2242. # ## Descend into .exerior and .interiors
  2243. elif type(o) == Polygon:
  2244. pts += GeometryObject.get_pts(o.exterior)
  2245. for i in o.interiors:
  2246. pts += GeometryObject.get_pts(i)
  2247. elif type(o) == MultiLineString:
  2248. for line in o:
  2249. pts += GeometryObject.get_pts(line)
  2250. # ## Has .coords: list them.
  2251. else:
  2252. pts += list(o.coords)
  2253. else:
  2254. return
  2255. return pts