FlatCAMGeometry.py 113 KB

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