FlatCAMGeometry.py 117 KB

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