ToolDrilling.py 136 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File by: Marius Adrian Stanciu (c) #
  4. # Date: 6/15/2020 #
  5. # License: MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore, QtGui
  8. from appTool import AppTool
  9. from appGUI.GUIElements import FCCheckBox, FCDoubleSpinner, RadioSet, FCTable, FCButton, \
  10. FCComboBox, OptionalInputSection, FCSpinner, NumericalEvalEntry, OptionalHideInputSection, FCLabel
  11. from appParsers.ParseExcellon import Excellon
  12. from copy import deepcopy
  13. import numpy as np
  14. import math
  15. from shapely.ops import unary_union
  16. from shapely.geometry import Point, LineString
  17. from matplotlib.backend_bases import KeyEvent as mpl_key_event
  18. import logging
  19. import gettext
  20. import appTranslation as fcTranslate
  21. import builtins
  22. import platform
  23. import re
  24. import traceback
  25. from Common import GracefulException as grace
  26. fcTranslate.apply_language('strings')
  27. if '_' not in builtins.__dict__:
  28. _ = gettext.gettext
  29. if platform.architecture()[0] == '64bit':
  30. from ortools.constraint_solver import pywrapcp
  31. from ortools.constraint_solver import routing_enums_pb2
  32. log = logging.getLogger('base')
  33. settings = QtCore.QSettings("Open Source", "FlatCAM")
  34. if settings.contains("machinist"):
  35. machinist_setting = settings.value('machinist', type=int)
  36. else:
  37. machinist_setting = 0
  38. class ToolDrilling(AppTool, Excellon):
  39. def __init__(self, app):
  40. self.app = app
  41. self.decimals = self.app.decimals
  42. AppTool.__init__(self, app)
  43. Excellon.__init__(self, geo_steps_per_circle=self.app.defaults["geometry_circle_steps"])
  44. # #############################################################################
  45. # ######################### Tool GUI ##########################################
  46. # #############################################################################
  47. self.ui = DrillingUI(layout=self.layout, app=self.app)
  48. self.toolName = self.ui.toolName
  49. # #############################################################################
  50. # ########################## VARIABLES ########################################
  51. # #############################################################################
  52. self.units = ''
  53. self.excellon_tools = {}
  54. self.tooluid = 0
  55. # dict that holds the object names and the option name
  56. # the key is the object name (defines in ObjectUI) for each UI element that is a parameter
  57. # particular for a tool and the value is the actual name of the option that the UI element is changing
  58. self.name2option = {}
  59. # store here the default data for Geometry Data
  60. self.default_data = {}
  61. self.obj_name = ""
  62. self.excellon_obj = None
  63. self.first_click = False
  64. self.cursor_pos = None
  65. self.mouse_is_dragging = False
  66. # store here the points for the "Polygon" area selection shape
  67. self.points = []
  68. self.mm = None
  69. self.mr = None
  70. self.kp = None
  71. # variable to store the total amount of drills per job
  72. self.tot_drill_cnt = 0
  73. self.tool_row = 0
  74. # variable to store the total amount of slots per job
  75. self.tot_slot_cnt = 0
  76. self.tool_row_slots = 0
  77. # variable to store the distance travelled
  78. self.travel_distance = 0.0
  79. self.grid_status_memory = self.app.ui.grid_snap_btn.isChecked()
  80. # store here the state of the exclusion checkbox state to be restored after building the UI
  81. # TODO add this in the sel.app.defaults dict and in Preferences
  82. self.exclusion_area_cb_is_checked = False
  83. # store here solid_geometry when there are tool with isolation job
  84. self.solid_geometry = []
  85. self.circle_steps = int(self.app.defaults["geometry_circle_steps"])
  86. self.tooldia = None
  87. # multiprocessing
  88. self.pool = self.app.pool
  89. self.results = []
  90. # disconnect flags
  91. self.area_sel_disconnect_flag = False
  92. self.poly_sel_disconnect_flag = False
  93. self.form_fields = {
  94. "cutz": self.ui.cutz_entry,
  95. "multidepth": self.ui.mpass_cb,
  96. "depthperpass": self.ui.maxdepth_entry,
  97. "travelz": self.ui.travelz_entry,
  98. "feedrate_z": self.ui.feedrate_z_entry,
  99. "feedrate_rapid": self.ui.feedrate_rapid_entry,
  100. "spindlespeed": self.ui.spindlespeed_entry,
  101. "dwell": self.ui.dwell_cb,
  102. "dwelltime": self.ui.dwelltime_entry,
  103. "offset": self.ui.offset_entry
  104. }
  105. self.name2option = {
  106. "e_cutz": "cutz",
  107. "e_multidepth": "multidepth",
  108. "e_depthperpass": "depthperpass",
  109. "e_travelz": "travelz",
  110. "e_feedratez": "feedrate_z",
  111. "e_fr_rapid": "feedrate_rapid",
  112. "e_spindlespeed": "spindlespeed",
  113. "e_dwell": "dwell",
  114. "e_dwelltime": "dwelltime",
  115. "e_offset": "offset"
  116. }
  117. self.old_tool_dia = None
  118. self.poly_drawn = False
  119. self.connect_signals_at_init()
  120. def install(self, icon=None, separator=None, **kwargs):
  121. AppTool.install(self, icon, separator, shortcut='Alt+D', **kwargs)
  122. def run(self, toggle=True):
  123. self.app.defaults.report_usage("ToolDrilling()")
  124. log.debug("ToolDrilling().run() was launched ...")
  125. if toggle:
  126. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  127. if self.app.ui.splitter.sizes()[0] == 0:
  128. self.app.ui.splitter.setSizes([1, 1])
  129. else:
  130. try:
  131. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  132. # if tab is populated with the tool but it does not have the focus, focus on it
  133. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  134. # focus on Tool Tab
  135. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  136. else:
  137. self.app.ui.splitter.setSizes([0, 1])
  138. except AttributeError:
  139. pass
  140. else:
  141. if self.app.ui.splitter.sizes()[0] == 0:
  142. self.app.ui.splitter.setSizes([1, 1])
  143. AppTool.run(self)
  144. self.set_tool_ui()
  145. # reset those objects on a new run
  146. self.excellon_obj = None
  147. self.obj_name = ''
  148. self.build_ui()
  149. # all the tools are selected by default
  150. self.ui.tools_table.selectAll()
  151. self.app.ui.notebook.setTabText(2, _("Drilling Tool"))
  152. def connect_signals_at_init(self):
  153. # #############################################################################
  154. # ############################ SIGNALS ########################################
  155. # #############################################################################
  156. self.ui.apply_param_to_all.clicked.connect(self.on_apply_param_to_all_clicked)
  157. self.ui.generate_cnc_button.clicked.connect(self.on_cnc_button_click)
  158. self.ui.tools_table.drag_drop_sig.connect(self.rebuild_ui)
  159. # Exclusion areas signals
  160. self.ui.exclusion_table.horizontalHeader().sectionClicked.connect(self.exclusion_table_toggle_all)
  161. self.ui.exclusion_table.lost_focus.connect(self.clear_selection)
  162. self.ui.exclusion_table.itemClicked.connect(self.draw_sel_shape)
  163. self.ui.add_area_button.clicked.connect(self.on_add_area_click)
  164. self.ui.delete_area_button.clicked.connect(self.on_clear_area_click)
  165. self.ui.delete_sel_area_button.clicked.connect(self.on_delete_sel_areas)
  166. self.ui.strategy_radio.activated_custom.connect(self.on_strategy)
  167. self.ui.pp_excellon_name_cb.activated.connect(self.on_pp_changed)
  168. self.ui.reset_button.clicked.connect(self.set_tool_ui)
  169. # Cleanup on Graceful exit (CTRL+ALT+X combo key)
  170. self.app.cleanup.connect(self.set_tool_ui)
  171. def set_tool_ui(self):
  172. self.units = self.app.defaults['units'].upper()
  173. self.old_tool_dia = self.app.defaults["tools_iso_newdia"]
  174. # try to select in the Excellon combobox the active object
  175. try:
  176. selected_obj = self.app.collection.get_active()
  177. if selected_obj.kind == 'excellon':
  178. current_name = selected_obj.options['name']
  179. self.ui.object_combo.set_value(current_name)
  180. except Exception:
  181. pass
  182. # populate Excellon preprocessor combobox list
  183. for name in list(self.app.preprocessors.keys()):
  184. # the HPGL preprocessor is only for Geometry not for Excellon job therefore don't add it
  185. if name == 'hpgl':
  186. continue
  187. self.ui.pp_excellon_name_cb.addItem(name)
  188. # update the changes in UI depending on the selected preprocessor in Preferences
  189. # after this moment all the changes in the Posprocessor combo will be handled by the activated signal of the
  190. # self.ui.pp_excellon_name_cb combobox
  191. self.on_pp_changed()
  192. app_mode = self.app.defaults["global_app_level"]
  193. # Show/Hide Advanced Options
  194. if app_mode == 'b':
  195. self.ui.level.setText('<span style="color:green;"><b>%s</b></span>' % _('Basic'))
  196. self.ui.estartz_label.hide()
  197. self.ui.estartz_entry.hide()
  198. self.ui.feedrate_rapid_label.hide()
  199. self.ui.feedrate_rapid_entry.hide()
  200. self.ui.pdepth_label.hide()
  201. self.ui.pdepth_entry.hide()
  202. self.ui.feedrate_probe_label.hide()
  203. self.ui.feedrate_probe_entry.hide()
  204. else:
  205. self.ui.level.setText('<span style="color:red;"><b>%s</b></span>' % _('Advanced'))
  206. self.ui.tools_frame.show()
  207. self.ui.order_radio.set_value(self.app.defaults["excellon_tool_order"])
  208. loaded_obj = self.app.collection.get_by_name(self.ui.object_combo.get_value())
  209. if loaded_obj:
  210. outname = loaded_obj.options['name']
  211. else:
  212. outname = ''
  213. # init the working variables
  214. self.default_data.clear()
  215. self.default_data = {
  216. "name": outname + '_iso',
  217. "plot": self.app.defaults["excellon_plot"],
  218. "solid": self.app.defaults["excellon_solid"],
  219. "multicolored": self.app.defaults["excellon_multicolored"],
  220. "merge_fuse_tools": self.app.defaults["excellon_merge_fuse_tools"],
  221. "format_upper_in": self.app.defaults["excellon_format_upper_in"],
  222. "format_lower_in": self.app.defaults["excellon_format_lower_in"],
  223. "format_upper_mm": self.app.defaults["excellon_format_upper_mm"],
  224. "lower_mm": self.app.defaults["excellon_format_lower_mm"],
  225. "zeros": self.app.defaults["excellon_zeros"],
  226. "excellon_units": self.app.defaults["excellon_units"],
  227. "excellon_update": self.app.defaults["excellon_update"],
  228. "excellon_optimization_type": self.app.defaults["excellon_optimization_type"],
  229. "excellon_search_time": self.app.defaults["excellon_search_time"],
  230. "excellon_plot_fill": self.app.defaults["excellon_plot_fill"],
  231. "excellon_plot_line": self.app.defaults["excellon_plot_line"],
  232. # Excellon Options
  233. "excellon_tool_order": self.app.defaults["excellon_tool_order"],
  234. "cutz": self.app.defaults["excellon_cutz"],
  235. "multidepth": self.app.defaults["excellon_multidepth"],
  236. "depthperpass": self.app.defaults["excellon_depthperpass"],
  237. "travelz": self.app.defaults["excellon_travelz"],
  238. "endz": self.app.defaults["excellon_endz"],
  239. "endxy": self.app.defaults["excellon_endxy"],
  240. "feedrate_z": self.app.defaults["excellon_feedrate_z"],
  241. "spindlespeed": self.app.defaults["excellon_spindlespeed"],
  242. "dwell": self.app.defaults["excellon_dwell"],
  243. "dwelltime": self.app.defaults["excellon_dwelltime"],
  244. "toolchange": self.app.defaults["excellon_toolchange"],
  245. "toolchangez": self.app.defaults["excellon_toolchangez"],
  246. "ppname_e": self.app.defaults["excellon_ppname_e"],
  247. "tooldia": self.app.defaults["excellon_tooldia"],
  248. "slot_tooldia": self.app.defaults["excellon_slot_tooldia"],
  249. "gcode_type": self.app.defaults["excellon_gcode_type"],
  250. "excellon_area_exclusion": self.app.defaults["excellon_area_exclusion"],
  251. "excellon_area_shape": self.app.defaults["excellon_area_shape"],
  252. "excellon_area_strategy": self.app.defaults["excellon_area_strategy"],
  253. "excellon_area_overz": self.app.defaults["excellon_area_overz"],
  254. # Excellon Advanced Options
  255. "offset": self.app.defaults["excellon_offset"],
  256. "toolchangexy": self.app.defaults["excellon_toolchangexy"],
  257. "startz": self.app.defaults["excellon_startz"],
  258. "feedrate_rapid": self.app.defaults["excellon_feedrate_rapid"],
  259. "z_pdepth": self.app.defaults["excellon_z_pdepth"],
  260. "feedrate_probe": self.app.defaults["excellon_feedrate_probe"],
  261. "spindledir": self.app.defaults["excellon_spindledir"],
  262. "f_plunge": self.app.defaults["excellon_f_plunge"],
  263. "f_retract": self.app.defaults["excellon_f_retract"],
  264. "gcode": '',
  265. "gcode_parsed": '',
  266. "geometry": [],
  267. }
  268. # fill in self.default_data values from self.options
  269. for opt_key, opt_val in self.app.options.items():
  270. if opt_key.find('excellon_') == 0:
  271. self.default_data[opt_key] = deepcopy(opt_val)
  272. for opt_key, opt_val in self.app.options.items():
  273. if opt_key.find('geometry_') == 0:
  274. self.default_data[opt_key] = deepcopy(opt_val)
  275. self.obj_name = ""
  276. self.excellon_obj = None
  277. self.first_click = False
  278. self.cursor_pos = None
  279. self.mouse_is_dragging = False
  280. self.units = self.app.defaults['units'].upper()
  281. # ########################################
  282. # #######3 TEMP SETTINGS #################
  283. # ########################################
  284. self.on_object_changed()
  285. if self.excellon_obj:
  286. self.build_ui()
  287. try:
  288. self.ui.object_combo.currentIndexChanged.disconnect()
  289. except (AttributeError, TypeError):
  290. pass
  291. self.ui.object_combo.currentIndexChanged.connect(self.on_object_changed)
  292. def rebuild_ui(self):
  293. # read the table tools uid
  294. current_uid_list = []
  295. for row in range(self.ui.tools_table.rowCount()):
  296. uid = int(self.ui.tools_table.item(row, 3).text())
  297. current_uid_list.append(uid)
  298. new_tools = {}
  299. new_uid = 1
  300. for current_uid in current_uid_list:
  301. new_tools[new_uid] = deepcopy(self.iso_tools[current_uid])
  302. new_uid += 1
  303. self.iso_tools = new_tools
  304. # the tools table changed therefore we need to rebuild it
  305. QtCore.QTimer.singleShot(20, self.build_ui)
  306. def build_ui(self):
  307. self.ui_disconnect()
  308. # updated units
  309. self.units = self.app.defaults['units'].upper()
  310. self.obj_name = self.ui.object_combo.currentText()
  311. # Get source object.
  312. try:
  313. self.excellon_obj = self.app.collection.get_by_name(self.obj_name)
  314. except Exception:
  315. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  316. return
  317. if self.excellon_obj:
  318. self.ui.exc_param_frame.setDisabled(False)
  319. tools = [k for k in self.excellon_tools]
  320. else:
  321. tools = []
  322. n = len(tools)
  323. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  324. self.ui.tools_table.setRowCount(n + 2)
  325. self.tool_row = 0
  326. for tool_no in tools:
  327. drill_cnt = 0 # variable to store the nr of drills per tool
  328. slot_cnt = 0 # variable to store the nr of slots per tool
  329. # Find no of drills for the current tool
  330. try:
  331. drill_cnt = len(self.excellon_tools[tool_no]["drills"])
  332. except KeyError:
  333. drill_cnt = 0
  334. self.tot_drill_cnt += drill_cnt
  335. # Find no of slots for the current tool
  336. try:
  337. slot_cnt = len(self.excellon_tools[tool_no]["slots"])
  338. except KeyError:
  339. slot_cnt = 0
  340. self.tot_slot_cnt += slot_cnt
  341. # Tool name/id
  342. exc_id_item = QtWidgets.QTableWidgetItem('%d' % int(tool_no))
  343. exc_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  344. self.ui.tools_table.setItem(self.tool_row, 0, exc_id_item)
  345. # Tool Diameter
  346. dia_item = QtWidgets.QTableWidgetItem('%.*f' % (self.decimals, self.excellon_tools[tool_no]['tooldia']))
  347. dia_item.setFlags(QtCore.Qt.ItemIsEnabled)
  348. self.ui.tools_table.setItem(self.tool_row, 1, dia_item)
  349. # Number of drills per tool
  350. drill_count_item = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  351. drill_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  352. self.ui.tools_table.setItem(self.tool_row, 2, drill_count_item)
  353. # Tool unique ID
  354. tool_uid_item = QtWidgets.QTableWidgetItem(str(int(tool_no)))
  355. # ## REMEMBER: THIS COLUMN IS HIDDEN in UI
  356. self.ui.tools_table.setItem(self.tool_row, 3, tool_uid_item)
  357. # Number of slots per tool
  358. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  359. slot_count_str = '%d' % slot_cnt if slot_cnt > 0 else ''
  360. slot_count_item = QtWidgets.QTableWidgetItem(slot_count_str)
  361. slot_count_item.setFlags(QtCore.Qt.ItemIsEnabled)
  362. self.ui.tools_table.setItem(self.tool_row, 4, slot_count_item)
  363. self.tool_row += 1
  364. # add a last row with the Total number of drills
  365. empty_1 = QtWidgets.QTableWidgetItem('')
  366. empty_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  367. empty_1_1 = QtWidgets.QTableWidgetItem('')
  368. empty_1_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  369. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  370. label_tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  371. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  372. tot_drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  373. self.ui.tools_table.setItem(self.tool_row, 0, empty_1)
  374. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_drill_count)
  375. self.ui.tools_table.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  376. self.ui.tools_table.setItem(self.tool_row, 4, empty_1_1)
  377. font = QtGui.QFont()
  378. font.setBold(True)
  379. font.setWeight(75)
  380. for k in [1, 2]:
  381. self.ui.tools_table.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  382. self.ui.tools_table.item(self.tool_row, k).setFont(font)
  383. self.tool_row += 1
  384. # add a last row with the Total number of slots
  385. empty_2 = QtWidgets.QTableWidgetItem('')
  386. empty_2.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  387. empty_2_1 = QtWidgets.QTableWidgetItem('')
  388. empty_2_1.setFlags(~QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  389. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  390. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  391. label_tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  392. tot_slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  393. self.ui.tools_table.setItem(self.tool_row, 0, empty_2)
  394. self.ui.tools_table.setItem(self.tool_row, 1, label_tot_slot_count)
  395. self.ui.tools_table.setItem(self.tool_row, 2, empty_2_1)
  396. self.ui.tools_table.setItem(self.tool_row, 4, tot_slot_count) # Total number of slots
  397. for kl in [1, 2, 4]:
  398. self.ui.tools_table.item(self.tool_row, kl).setFont(font)
  399. self.ui.tools_table.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  400. # make the diameter column editable
  401. for row in range(self.ui.tools_table.rowCount() - 2):
  402. self.ui.tools_table.item(row, 1).setFlags(
  403. QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  404. self.ui.tools_table.resizeColumnsToContents()
  405. self.ui.tools_table.resizeRowsToContents()
  406. vertical_header = self.ui.tools_table.verticalHeader()
  407. vertical_header.hide()
  408. self.ui.tools_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  409. horizontal_header = self.ui.tools_table.horizontalHeader()
  410. self.ui.tools_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  411. horizontal_header.setMinimumSectionSize(10)
  412. horizontal_header.setDefaultSectionSize(70)
  413. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  414. horizontal_header.resizeSection(0, 20)
  415. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  416. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  417. horizontal_header.setSectionResizeMode(4, QtWidgets.QHeaderView.ResizeToContents)
  418. self.ui.tools_table.setSortingEnabled(False)
  419. self.ui.tools_table.setMinimumHeight(self.ui.tools_table.getHeight())
  420. self.ui.tools_table.setMaximumHeight(self.ui.tools_table.getHeight())
  421. # all the tools are selected by default
  422. self.ui.tools_table.selectAll()
  423. # Build Exclusion Areas section
  424. e_len = len(self.app.exc_areas.exclusion_areas_storage)
  425. self.ui.exclusion_table.setRowCount(e_len)
  426. area_id = 0
  427. for area in range(e_len):
  428. area_id += 1
  429. area_dict = self.app.exc_areas.exclusion_areas_storage[area]
  430. area_id_item = QtWidgets.QTableWidgetItem('%d' % int(area_id))
  431. area_id_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  432. self.ui.exclusion_table.setItem(area, 0, area_id_item) # Area id
  433. object_item = QtWidgets.QTableWidgetItem('%s' % area_dict["obj_type"])
  434. object_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  435. self.ui.exclusion_table.setItem(area, 1, object_item) # Origin Object
  436. strategy_item = QtWidgets.QTableWidgetItem('%s' % area_dict["strategy"])
  437. strategy_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  438. self.ui.exclusion_table.setItem(area, 2, strategy_item) # Strategy
  439. overz_item = QtWidgets.QTableWidgetItem('%s' % area_dict["overz"])
  440. overz_item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  441. self.ui.exclusion_table.setItem(area, 3, overz_item) # Over Z
  442. self.ui.exclusion_table.resizeColumnsToContents()
  443. self.ui.exclusion_table.resizeRowsToContents()
  444. area_vheader = self.ui.exclusion_table.verticalHeader()
  445. area_vheader.hide()
  446. self.ui.exclusion_table.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  447. area_hheader = self.ui.exclusion_table.horizontalHeader()
  448. area_hheader.setMinimumSectionSize(10)
  449. area_hheader.setDefaultSectionSize(70)
  450. area_hheader.setSectionResizeMode(0, QtWidgets.QHeaderView.Fixed)
  451. area_hheader.resizeSection(0, 20)
  452. area_hheader.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  453. area_hheader.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  454. area_hheader.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  455. # area_hheader.setStretchLastSection(True)
  456. self.ui.exclusion_table.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  457. self.ui.exclusion_table.setColumnWidth(0, 20)
  458. self.ui.exclusion_table.setMinimumHeight(self.ui.exclusion_table.getHeight())
  459. self.ui.exclusion_table.setMaximumHeight(self.ui.exclusion_table.getHeight())
  460. self.ui_connect()
  461. # set the text on tool_data_label after loading the object
  462. sel_rows = set()
  463. sel_items = self.ui.tools_table.selectedItems()
  464. for it in sel_items:
  465. sel_rows.add(it.row())
  466. if len(sel_rows) > 1:
  467. self.ui.tool_data_label.setText(
  468. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  469. )
  470. def on_object_changed(self):
  471. # load the Excellon object
  472. self.obj_name = self.ui.object_combo.currentText()
  473. # Get source object.
  474. try:
  475. self.excellon_obj = self.app.collection.get_by_name(self.obj_name)
  476. except Exception as e:
  477. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(self.obj_name)))
  478. return
  479. if self.excellon_obj is None:
  480. self.ui.exc_param_frame.setDisabled(True)
  481. else:
  482. self.ui.exc_param_frame.setDisabled(False)
  483. self.excellon_tools = self.excellon_obj.tools
  484. self.build_ui()
  485. def ui_connect(self):
  486. # Area Exception - exclusion shape added signal
  487. # first disconnect it from any other object
  488. try:
  489. self.app.exc_areas.e_shape_modified.disconnect()
  490. except (TypeError, AttributeError):
  491. pass
  492. # then connect it to the current build_ui() method
  493. self.app.exc_areas.e_shape_modified.connect(self.update_exclusion_table)
  494. # rows selected
  495. self.ui.tools_table.clicked.connect(self.on_row_selection_change)
  496. self.ui.tools_table.horizontalHeader().sectionClicked.connect(self.on_toggle_all_rows)
  497. # Tool Parameters
  498. for opt in self.form_fields:
  499. current_widget = self.form_fields[opt]
  500. if isinstance(current_widget, FCCheckBox):
  501. current_widget.stateChanged.connect(self.form_to_storage)
  502. if isinstance(current_widget, RadioSet):
  503. current_widget.activated_custom.connect(self.form_to_storage)
  504. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  505. current_widget.returnPressed.connect(self.form_to_storage)
  506. elif isinstance(current_widget, FCComboBox):
  507. current_widget.currentIndexChanged.connect(self.form_to_storage)
  508. self.ui.order_radio.activated_custom[str].connect(self.on_order_changed)
  509. def ui_disconnect(self):
  510. # rows selected
  511. try:
  512. self.ui.tools_table.clicked.disconnect()
  513. except (TypeError, AttributeError):
  514. pass
  515. try:
  516. self.ui.tools_table.horizontalHeader().sectionClicked.disconnect()
  517. except (TypeError, AttributeError):
  518. pass
  519. # tool table widgets
  520. for row in range(self.ui.tools_table.rowCount()):
  521. try:
  522. self.ui.tools_table.cellWidget(row, 2).currentIndexChanged.disconnect()
  523. except (TypeError, AttributeError):
  524. pass
  525. # Tool Parameters
  526. for opt in self.form_fields:
  527. current_widget = self.form_fields[opt]
  528. if isinstance(current_widget, FCCheckBox):
  529. try:
  530. current_widget.stateChanged.disconnect(self.form_to_storage)
  531. except (TypeError, ValueError):
  532. pass
  533. if isinstance(current_widget, RadioSet):
  534. try:
  535. current_widget.activated_custom.disconnect(self.form_to_storage)
  536. except (TypeError, ValueError):
  537. pass
  538. elif isinstance(current_widget, FCDoubleSpinner) or isinstance(current_widget, FCSpinner):
  539. try:
  540. current_widget.returnPressed.disconnect(self.form_to_storage)
  541. except (TypeError, ValueError):
  542. pass
  543. elif isinstance(current_widget, FCComboBox):
  544. try:
  545. current_widget.currentIndexChanged.disconnect(self.form_to_storage)
  546. except (TypeError, ValueError):
  547. pass
  548. try:
  549. self.ui.order_radio.activated_custom[str].disconnect()
  550. except (TypeError, ValueError):
  551. pass
  552. def on_toggle_all_rows(self):
  553. """
  554. will toggle the selection of all rows in Tools table
  555. :return:
  556. """
  557. sel_model = self.ui.tools_table.selectionModel()
  558. sel_indexes = sel_model.selectedIndexes()
  559. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  560. sel_rows = set()
  561. for idx in sel_indexes:
  562. sel_rows.add(idx.row())
  563. if len(sel_rows) == self.ui.tools_table.rowCount():
  564. self.ui.tools_table.clearSelection()
  565. else:
  566. self.ui.tools_table.selectAll()
  567. self.update_ui()
  568. def on_row_selection_change(self):
  569. self.update_ui()
  570. def update_ui(self):
  571. self.blockSignals(True)
  572. sel_rows = set()
  573. table_items = self.ui.tools_table.selectedItems()
  574. if table_items:
  575. for it in table_items:
  576. sel_rows.add(it.row())
  577. # sel_rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  578. if not sel_rows or len(sel_rows) == 0:
  579. self.ui.generate_cnc_button.setDisabled(True)
  580. self.ui.tool_data_label.setText(
  581. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("No Tool Selected"))
  582. )
  583. self.blockSignals(False)
  584. return
  585. else:
  586. self.ui.generate_cnc_button.setDisabled(False)
  587. if len(sel_rows) == 1:
  588. # update the QLabel that shows for which Tool we have the parameters in the UI form
  589. tooluid = int(self.ui.tools_table.item(list(sel_rows)[0], 0).text())
  590. self.ui.tool_data_label.setText(
  591. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), tooluid)
  592. )
  593. else:
  594. self.ui.tool_data_label.setText(
  595. "<b>%s: <font color='#0000FF'>%s</font></b>" % (_('Parameters for'), _("Multiple Tools"))
  596. )
  597. for c_row in sel_rows:
  598. # populate the form with the data from the tool associated with the row parameter
  599. try:
  600. item = self.ui.tools_table.item(c_row, 3)
  601. if type(item) is not None:
  602. tooluid = int(item.text())
  603. self.storage_to_form(self.excellon_tools[tooluid]['data'])
  604. else:
  605. self.blockSignals(False)
  606. return
  607. except Exception as e:
  608. log.debug("Tool missing. Add a tool in the Tool Table. %s" % str(e))
  609. self.blockSignals(False)
  610. return
  611. self.blockSignals(False)
  612. def storage_to_form(self, dict_storage):
  613. """
  614. Will update the GUI with data from the "storage" in this case the dict self.tools
  615. :param dict_storage: A dictionary holding the data relevant for gnerating Gcode from Excellon
  616. :type dict_storage: dict
  617. :return: None
  618. :rtype:
  619. """
  620. for form_key in self.form_fields:
  621. for storage_key in dict_storage:
  622. if form_key == storage_key and form_key not in \
  623. ["toolchange", "toolchangez", "startz", "endz", "ppname_e", "ppname_g"]:
  624. try:
  625. self.form_fields[form_key].set_value(dict_storage[form_key])
  626. except Exception as e:
  627. log.debug("ToolDrilling.storage_to_form() --> %s" % str(e))
  628. pass
  629. def form_to_storage(self):
  630. """
  631. Will update the 'storage' attribute which is the dict self.tools with data collected from GUI
  632. :return: None
  633. :rtype:
  634. """
  635. if self.ui.tools_table.rowCount() == 2:
  636. # there is no tool in tool table so we can't save the GUI elements values to storage
  637. # Excellon Tool Table has 2 rows by default
  638. return
  639. self.blockSignals(True)
  640. widget_changed = self.sender()
  641. wdg_objname = widget_changed.objectName()
  642. option_changed = self.name2option[wdg_objname]
  643. # row = self.ui.tools_table.currentRow()
  644. rows = sorted(set(index.row() for index in self.ui.tools_table.selectedIndexes()))
  645. for row in rows:
  646. if row < 0:
  647. row = 0
  648. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  649. for tooluid_key, tooluid_val in self.excellon_tools.items():
  650. if int(tooluid_key) == tooluid_item:
  651. new_option_value = self.form_fields[option_changed].get_value()
  652. if option_changed in tooluid_val:
  653. tooluid_val[option_changed] = new_option_value
  654. if option_changed in tooluid_val['data']:
  655. tooluid_val['data'][option_changed] = new_option_value
  656. self.blockSignals(False)
  657. def get_selected_tools_list(self):
  658. """
  659. Returns the keys to the self.tools dictionary corresponding
  660. to the selections on the tool list in the appGUI.
  661. :return: List of tools.
  662. :rtype: list
  663. """
  664. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  665. def get_selected_tools_table_items(self):
  666. """
  667. Returns a list of lists, each list in the list is made out of row elements
  668. :return: List of table_tools items.
  669. :rtype: list
  670. """
  671. table_tools_items = []
  672. for x in self.ui.tools_table.selectedItems():
  673. # from the columnCount we subtract a value of 1 which represent the last column (plot column)
  674. # which does not have text
  675. txt = ''
  676. elem = []
  677. for column in range(0, self.ui.tools_table.columnCount() - 1):
  678. try:
  679. txt = self.ui.tools_table.item(x.row(), column).text()
  680. except AttributeError:
  681. try:
  682. txt = self.ui.tools_table.cellWidget(x.row(), column).currentText()
  683. except AttributeError:
  684. pass
  685. elem.append(txt)
  686. table_tools_items.append(deepcopy(elem))
  687. # table_tools_items.append([self.ui.tools_table.item(x.row(), column).text()
  688. # for column in range(0, self.ui.tools_table.columnCount() - 1)])
  689. for item in table_tools_items:
  690. item[0] = str(item[0])
  691. return table_tools_items
  692. def on_apply_param_to_all_clicked(self):
  693. if self.ui.tools_table.rowCount() == 0:
  694. # there is no tool in tool table so we can't save the GUI elements values to storage
  695. log.debug("ToolDrilling.on_apply_param_to_all_clicked() --> no tool in Tools Table, aborting.")
  696. return
  697. self.blockSignals(True)
  698. row = self.ui.tools_table.currentRow()
  699. if row < 0:
  700. row = 0
  701. tooluid_item = int(self.ui.tools_table.item(row, 3).text())
  702. temp_tool_data = {}
  703. for tooluid_key, tooluid_val in self.iso_tools.items():
  704. if int(tooluid_key) == tooluid_item:
  705. # this will hold the 'data' key of the self.tools[tool] dictionary that corresponds to
  706. # the current row in the tool table
  707. temp_tool_data = tooluid_val['data']
  708. break
  709. for tooluid_key, tooluid_val in self.iso_tools.items():
  710. tooluid_val['data'] = deepcopy(temp_tool_data)
  711. self.app.inform.emit('[success] %s' % _("Current Tool parameters were applied to all tools."))
  712. self.blockSignals(False)
  713. def on_order_changed(self, order):
  714. if order != 'no':
  715. self.build_ui()
  716. def on_tooltable_cellwidget_change(self):
  717. cw = self.sender()
  718. assert isinstance(cw, QtWidgets.QComboBox), \
  719. "Expected a QtWidgets.QComboBox, got %s" % isinstance(cw, QtWidgets.QComboBox)
  720. cw_index = self.ui.tools_table.indexAt(cw.pos())
  721. cw_row = cw_index.row()
  722. cw_col = cw_index.column()
  723. current_uid = int(self.ui.tools_table.item(cw_row, 3).text())
  724. # if the sender is in the column with index 2 then we update the tool_type key
  725. if cw_col == 2:
  726. tt = cw.currentText()
  727. typ = 'Iso' if tt == 'V' else "Rough"
  728. self.iso_tools[current_uid].update({
  729. 'type': typ,
  730. 'tool_type': tt,
  731. })
  732. def generate_milling_drills(self, tools=None, outname=None, tooldia=None, plot=False, use_thread=False):
  733. """
  734. Will generate an Geometry Object allowing to cut a drill hole instead of drilling it.
  735. Note: This method is a good template for generic operations as
  736. it takes it's options from parameters or otherwise from the
  737. object's options and returns a (success, msg) tuple as feedback
  738. for shell operations.
  739. :param tools: A list of tools where the drills are to be milled or a string: "all"
  740. :type tools:
  741. :param outname: the name of the resulting Geometry object
  742. :type outname: str
  743. :param tooldia: the tool diameter to be used in creation of the milling path (Geometry Object)
  744. :type tooldia: float
  745. :param plot: if to plot the resulting object
  746. :type plot: bool
  747. :param use_thread: if to use threading for creation of the Geometry object
  748. :type use_thread: bool
  749. :return: Success/failure condition tuple (bool, str).
  750. :rtype: tuple
  751. """
  752. # Get the tools from the list. These are keys
  753. # to self.tools
  754. if tools is None:
  755. tools = self.get_selected_tools_list()
  756. if outname is None:
  757. outname = self.options["name"] + "_mill"
  758. if tooldia is None:
  759. tooldia = float(self.options["tooldia"])
  760. # Sort tools by diameter. items() -> [('name', diameter), ...]
  761. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  762. sort = []
  763. for k, v in self.tools.items():
  764. sort.append((k, v.get('tooldia')))
  765. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  766. if tools == "all":
  767. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  768. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  769. if len(tools) == 0:
  770. self.app.inform.emit('[ERROR_NOTCL] %s' %
  771. _("Please select one or more tools from the list and try again."))
  772. return False, "Error: No tools."
  773. for tool in tools:
  774. if tooldia > self.tools[tool]["C"]:
  775. self.app.inform.emit(
  776. '[ERROR_NOTCL] %s %s: %s' % (
  777. _("Milling tool for DRILLS is larger than hole size. Cancelled."),
  778. _("Tool"),
  779. str(tool)
  780. )
  781. )
  782. return False, "Error: Milling tool is larger than hole."
  783. def geo_init(geo_obj, app_obj):
  784. """
  785. :param geo_obj: New object
  786. :type geo_obj: GeometryObject
  787. :param app_obj: App
  788. :type app_obj: FlatCAMApp.App
  789. :return:
  790. :rtype:
  791. """
  792. assert geo_obj.kind == 'geometry', "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  793. app_obj.inform.emit(_("Generating drills milling geometry..."))
  794. # ## Add properties to the object
  795. # get the tool_table items in a list of row items
  796. tool_table_items = self.get_selected_tools_table_items()
  797. # insert an information only element in the front
  798. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  799. geo_obj.options['Tools_in_use'] = tool_table_items
  800. geo_obj.options['type'] = 'Excellon Geometry'
  801. geo_obj.options["cnctooldia"] = str(tooldia)
  802. geo_obj.options["multidepth"] = self.options["multidepth"]
  803. geo_obj.solid_geometry = []
  804. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  805. # for FlatCAM is 6 decimals,
  806. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  807. for hole in self.drills:
  808. if hole['tool'] in tools:
  809. buffer_value = self.tools[hole['tool']]["C"] / 2 - tooldia / 2
  810. if buffer_value == 0:
  811. geo_obj.solid_geometry.append(
  812. Point(hole['point']).buffer(0.0000001).exterior)
  813. else:
  814. geo_obj.solid_geometry.append(
  815. Point(hole['point']).buffer(buffer_value).exterior)
  816. if use_thread:
  817. def geo_thread(a_obj):
  818. a_obj.app_obj.new_object("geometry", outname, geo_init, plot=plot)
  819. # Create a promise with the new name
  820. self.app.collection.promise(outname)
  821. # Send to worker
  822. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  823. else:
  824. self.app.app_obj.new_object("geometry", outname, geo_init, plot=plot)
  825. return True, ""
  826. def generate_milling_slots(self, tools=None, outname=None, tooldia=None, plot=False, use_thread=False):
  827. """
  828. Will generate an Geometry Object allowing to cut/mill a slot hole.
  829. Note: This method is a good template for generic operations as
  830. it takes it's options from parameters or otherwise from the
  831. object's options and returns a (success, msg) tuple as feedback
  832. for shell operations.
  833. :param tools: A list of tools where the drills are to be milled or a string: "all"
  834. :type tools:
  835. :param outname: the name of the resulting Geometry object
  836. :type outname: str
  837. :param tooldia: the tool diameter to be used in creation of the milling path (Geometry Object)
  838. :type tooldia: float
  839. :param plot: if to plot the resulting object
  840. :type plot: bool
  841. :param use_thread: if to use threading for creation of the Geometry object
  842. :type use_thread: bool
  843. :return: Success/failure condition tuple (bool, str).
  844. :rtype: tuple
  845. """
  846. # Get the tools from the list. These are keys
  847. # to self.tools
  848. if tools is None:
  849. tools = self.get_selected_tools_list()
  850. if outname is None:
  851. outname = self.options["name"] + "_mill"
  852. if tooldia is None:
  853. tooldia = float(self.options["slot_tooldia"])
  854. # Sort tools by diameter. items() -> [('name', diameter), ...]
  855. # sorted_tools = sorted(list(self.tools.items()), key=lambda tl: tl[1]) # no longer works in Python3
  856. sort = []
  857. for k, v in self.tools.items():
  858. sort.append((k, v.get('tooldia')))
  859. sorted_tools = sorted(sort, key=lambda t1: t1[1])
  860. if tools == "all":
  861. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  862. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  863. if len(tools) == 0:
  864. self.app.inform.emit('[ERROR_NOTCL] %s' %
  865. _("Please select one or more tools from the list and try again."))
  866. return False, "Error: No tools."
  867. for tool in tools:
  868. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  869. adj_toolstable_tooldia = float('%.*f' % (self.decimals, float(tooldia)))
  870. adj_file_tooldia = float('%.*f' % (self.decimals, float(self.tools[tool]["C"])))
  871. if adj_toolstable_tooldia > adj_file_tooldia + 0.0001:
  872. self.app.inform.emit('[ERROR_NOTCL] %s' %
  873. _("Milling tool for SLOTS is larger than hole size. Cancelled."))
  874. return False, "Error: Milling tool is larger than hole."
  875. def geo_init(geo_obj, app_obj):
  876. assert geo_obj.kind == 'geometry', "Initializer expected a GeometryObject, got %s" % type(geo_obj)
  877. app_obj.inform.emit(_("Generating slot milling geometry..."))
  878. # ## Add properties to the object
  879. # get the tool_table items in a list of row items
  880. tool_table_items = self.get_selected_tools_table_items()
  881. # insert an information only element in the front
  882. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  883. geo_obj.options['Tools_in_use'] = tool_table_items
  884. geo_obj.options['type'] = 'Excellon Geometry'
  885. geo_obj.options["cnctooldia"] = str(tooldia)
  886. geo_obj.options["multidepth"] = self.options["multidepth"]
  887. geo_obj.solid_geometry = []
  888. # in case that the tool used has the same diameter with the hole, and since the maximum resolution
  889. # for FlatCAM is 6 decimals,
  890. # we add a tenth of the minimum value, meaning 0.0000001, which from our point of view is "almost zero"
  891. for slot in self.slots:
  892. if slot['tool'] in tools:
  893. toolstable_tool = float('%.*f' % (self.decimals, float(tooldia)))
  894. file_tool = float('%.*f' % (self.decimals, float(self.tools[tool]["C"])))
  895. # I add the 0.0001 value to account for the rounding error in converting from IN to MM and reverse
  896. # for the file_tool (tooldia actually)
  897. buffer_value = float(file_tool / 2) - float(toolstable_tool / 2) + 0.0001
  898. if buffer_value == 0:
  899. start = slot['start']
  900. stop = slot['stop']
  901. lines_string = LineString([start, stop])
  902. poly = lines_string.buffer(0.0000001, int(self.geo_steps_per_circle)).exterior
  903. geo_obj.solid_geometry.append(poly)
  904. else:
  905. start = slot['start']
  906. stop = slot['stop']
  907. lines_string = LineString([start, stop])
  908. poly = lines_string.buffer(buffer_value, int(self.geo_steps_per_circle)).exterior
  909. geo_obj.solid_geometry.append(poly)
  910. if use_thread:
  911. def geo_thread(a_obj):
  912. a_obj.app_obj.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  913. # Create a promise with the new name
  914. self.app.collection.promise(outname)
  915. # Send to worker
  916. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  917. else:
  918. self.app.app_obj.new_object("geometry", outname + '_slot', geo_init, plot=plot)
  919. return True, ""
  920. def on_pp_changed(self):
  921. current_pp = self.ui.pp_excellon_name_cb.get_value()
  922. if "toolchange_probe" in current_pp.lower():
  923. self.ui.pdepth_entry.setVisible(True)
  924. self.ui.pdepth_label.show()
  925. self.ui.feedrate_probe_entry.setVisible(True)
  926. self.ui.feedrate_probe_label.show()
  927. else:
  928. self.ui.pdepth_entry.setVisible(False)
  929. self.ui.pdepth_label.hide()
  930. self.ui.feedrate_probe_entry.setVisible(False)
  931. self.ui.feedrate_probe_label.hide()
  932. if 'marlin' in current_pp.lower() or 'custom' in current_pp.lower():
  933. self.ui.feedrate_rapid_label.show()
  934. self.ui.feedrate_rapid_entry.show()
  935. else:
  936. self.ui.feedrate_rapid_label.hide()
  937. self.ui.feedrate_rapid_entry.hide()
  938. if 'laser' in current_pp.lower():
  939. self.ui.cutzlabel.hide()
  940. self.ui.cutz_entry.hide()
  941. try:
  942. self.ui.mpass_cb.hide()
  943. self.ui.maxdepth_entry.hide()
  944. except AttributeError:
  945. pass
  946. if 'marlin' in current_pp.lower():
  947. self.ui.travelzlabel.setText('%s:' % _("Focus Z"))
  948. self.ui.endz_label.show()
  949. self.ui.endz_entry.show()
  950. else:
  951. self.ui.travelzlabel.hide()
  952. self.ui.travelz_entry.hide()
  953. self.ui.endz_label.hide()
  954. self.ui.endz_entry.hide()
  955. try:
  956. self.ui.frzlabel.hide()
  957. self.ui.feedrate_z_entry.hide()
  958. except AttributeError:
  959. pass
  960. self.ui.dwell_cb.hide()
  961. self.ui.dwelltime_entry.hide()
  962. self.ui.spindle_label.setText('%s:' % _("Laser Power"))
  963. try:
  964. self.ui.tool_offset_label.hide()
  965. self.ui.offset_entry.hide()
  966. except AttributeError:
  967. pass
  968. else:
  969. self.ui.cutzlabel.show()
  970. self.ui.cutz_entry.show()
  971. try:
  972. self.ui.mpass_cb.show()
  973. self.ui.maxdepth_entry.show()
  974. except AttributeError:
  975. pass
  976. self.ui.travelzlabel.setText('%s:' % _('Travel Z'))
  977. self.ui.travelzlabel.show()
  978. self.ui.travelz_entry.show()
  979. self.ui.endz_label.show()
  980. self.ui.endz_entry.show()
  981. try:
  982. self.ui.frzlabel.show()
  983. self.ui.feedrate_z_entry.show()
  984. except AttributeError:
  985. pass
  986. self.ui.dwell_cb.show()
  987. self.ui.dwelltime_entry.show()
  988. self.ui.spindle_label.setText('%s:' % _('Spindle speed'))
  989. try:
  990. # self.ui.tool_offset_lbl.show()
  991. self.ui.offset_entry.show()
  992. except AttributeError:
  993. pass
  994. def on_key_press(self, event):
  995. # modifiers = QtWidgets.QApplication.keyboardModifiers()
  996. # matplotlib_key_flag = False
  997. # events out of the self.app.collection view (it's about Project Tab) are of type int
  998. if type(event) is int:
  999. key = event
  1000. # events from the GUI are of type QKeyEvent
  1001. elif type(event) == QtGui.QKeyEvent:
  1002. key = event.key()
  1003. elif isinstance(event, mpl_key_event): # MatPlotLib key events are trickier to interpret than the rest
  1004. # matplotlib_key_flag = True
  1005. key = event.key
  1006. key = QtGui.QKeySequence(key)
  1007. # check for modifiers
  1008. key_string = key.toString().lower()
  1009. if '+' in key_string:
  1010. mod, __, key_text = key_string.rpartition('+')
  1011. if mod.lower() == 'ctrl':
  1012. # modifiers = QtCore.Qt.ControlModifier
  1013. pass
  1014. elif mod.lower() == 'alt':
  1015. # modifiers = QtCore.Qt.AltModifier
  1016. pass
  1017. elif mod.lower() == 'shift':
  1018. # modifiers = QtCore.Qt.ShiftModifier
  1019. pass
  1020. else:
  1021. # modifiers = QtCore.Qt.NoModifier
  1022. pass
  1023. key = QtGui.QKeySequence(key_text)
  1024. # events from Vispy are of type KeyEvent
  1025. else:
  1026. key = event.key
  1027. if key == QtCore.Qt.Key_Escape or key == 'Escape':
  1028. self.points = []
  1029. self.poly_drawn = False
  1030. self.delete_moving_selection_shape()
  1031. self.delete_tool_selection_shape()
  1032. def on_add_area_click(self):
  1033. shape_button = self.ui.area_shape_radio
  1034. overz_button = self.ui.over_z_entry
  1035. strategy_radio = self.ui.strategy_radio
  1036. cnc_button = self.ui.generate_cnc_button
  1037. solid_geo = self.solid_geometry
  1038. obj_type = self.kind
  1039. self.app.exc_areas.on_add_area_click(
  1040. shape_button=shape_button, overz_button=overz_button, cnc_button=cnc_button, strategy_radio=strategy_radio,
  1041. solid_geo=solid_geo, obj_type=obj_type)
  1042. def on_clear_area_click(self):
  1043. if not self.app.exc_areas.exclusion_areas_storage:
  1044. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Delete failed. There are no exclusion areas to delete."))
  1045. return
  1046. self.app.exc_areas.on_clear_area_click()
  1047. self.app.exc_areas.e_shape_modified.emit()
  1048. def on_delete_sel_areas(self):
  1049. sel_model = self.ui.exclusion_table.selectionModel()
  1050. sel_indexes = sel_model.selectedIndexes()
  1051. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  1052. # so the duplicate rows will not be added
  1053. sel_rows = set()
  1054. for idx in sel_indexes:
  1055. sel_rows.add(idx.row())
  1056. if not sel_rows:
  1057. self.app.inform.emit("[WARNING_NOTCL] %s" % _("Delete failed. Nothing is selected."))
  1058. return
  1059. self.app.exc_areas.delete_sel_shapes(idxs=list(sel_rows))
  1060. self.app.exc_areas.e_shape_modified.emit()
  1061. def draw_sel_shape(self):
  1062. sel_model = self.ui.exclusion_table.selectionModel()
  1063. sel_indexes = sel_model.selectedIndexes()
  1064. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  1065. sel_rows = set()
  1066. for idx in sel_indexes:
  1067. sel_rows.add(idx.row())
  1068. self.delete_sel_shape()
  1069. if self.app.is_legacy is False:
  1070. face = self.app.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  1071. outline = self.app.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  1072. else:
  1073. face = self.app.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  1074. outline = self.app.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  1075. for row in sel_rows:
  1076. sel_rect = self.app.exc_areas.exclusion_areas_storage[row]['shape']
  1077. self.app.move_tool.sel_shapes.add(sel_rect, color=outline, face_color=face, update=True, layer=0,
  1078. tolerance=None)
  1079. if self.app.is_legacy is True:
  1080. self.app.move_tool.sel_shapes.redraw()
  1081. def clear_selection(self):
  1082. self.app.delete_selection_shape()
  1083. # self.ui.exclusion_table.clearSelection()
  1084. def delete_sel_shape(self):
  1085. self.app.delete_selection_shape()
  1086. def update_exclusion_table(self):
  1087. self.exclusion_area_cb_is_checked = True if self.ui.exclusion_cb.isChecked() else False
  1088. self.build_ui()
  1089. self.ui.exclusion_cb.set_value(self.exclusion_area_cb_is_checked)
  1090. def on_strategy(self, val):
  1091. if val == 'around':
  1092. self.ui.over_z_label.setDisabled(True)
  1093. self.ui.over_z_entry.setDisabled(True)
  1094. else:
  1095. self.ui.over_z_label.setDisabled(False)
  1096. self.ui.over_z_entry.setDisabled(False)
  1097. def exclusion_table_toggle_all(self):
  1098. """
  1099. will toggle the selection of all rows in Exclusion Areas table
  1100. :return:
  1101. """
  1102. sel_model = self.ui.exclusion_table.selectionModel()
  1103. sel_indexes = sel_model.selectedIndexes()
  1104. # it will iterate over all indexes which means all items in all columns too but I'm interested only on rows
  1105. sel_rows = set()
  1106. for idx in sel_indexes:
  1107. sel_rows.add(idx.row())
  1108. if sel_rows:
  1109. self.ui.exclusion_table.clearSelection()
  1110. self.delete_sel_shape()
  1111. else:
  1112. self.ui.exclusion_table.selectAll()
  1113. self.draw_sel_shape()
  1114. def on_cnc_button_click(self):
  1115. obj_name = self.ui.object_combo.currentText()
  1116. # Get source object.
  1117. try:
  1118. self.excellon_obj = self.app.collection.get_by_name(obj_name)
  1119. except Exception as e:
  1120. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Could not retrieve object"), str(obj_name)))
  1121. return
  1122. if self.excellon_obj is None:
  1123. self.app.inform.emit('[ERROR_NOTCL] %s.' % _("Object not found"))
  1124. return
  1125. # Get the tools from the Tool Table
  1126. selected_uid = set()
  1127. for it in self.ui.tools_table.selectedItems():
  1128. uid = self.ui.tools_table.item(it.row(), 3).text()
  1129. selected_uid.add(uid)
  1130. tools = list(selected_uid)
  1131. if len(tools) == 0:
  1132. # if there is a single tool in the table (remember that the last 2 rows are for totals and do not count in
  1133. # tool number) it means that there are 3 rows (1 tool and 2 totals).
  1134. # in this case regardless of the selection status of that tool, use it.
  1135. if self.ui.tools_table.rowCount() == 3:
  1136. tools.append(self.ui.tools_table.item(0, 0).text())
  1137. else:
  1138. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1139. _("Please select one or more tools from the list and try again."))
  1140. return
  1141. xmin = self.excellon_obj.options['xmin']
  1142. ymin = self.excellon_obj.options['ymin']
  1143. xmax = self.excellon_obj.options['xmax']
  1144. ymax = self.excellon_obj.options['ymax']
  1145. job_name = self.excellon_obj.options["name"] + "_cnc"
  1146. pp_excellon_name = self.ui.pp_excellon_name_cb.get_value()
  1147. # z_pdepth = self.ui.pdepth_entry.get_value()
  1148. # feedrate_probe = self.ui.feedrate_probe_entry.get_value()
  1149. # toolchange = self.ui.toolchange_cb.get_value()
  1150. # z_toolchange = self.ui.toolchangez_entry.get_value()
  1151. # startz = self.ui.estartz_entry.get_value()
  1152. # endz = self.ui.endz_entry.get_value()
  1153. # xy_end = self.ui.endxy_entry.get_value()
  1154. # Object initialization function for app.app_obj.new_object()
  1155. def job_init(job_obj, app_obj):
  1156. assert job_obj.kind == 'cncjob', "Initializer expected a CNCJobObject, got %s" % type(job_obj)
  1157. app_obj.inform.emit(_("Generating Excellon CNCJob..."))
  1158. # get the tool_table items in a list of row items
  1159. tool_table_items = self.get_selected_tools_table_items()
  1160. # insert an information only element in the front
  1161. tool_table_items.insert(0, [_("Tool_nr"), _("Diameter"), _("Drills_Nr"), _("Slots_Nr")])
  1162. # ## Add properties to the object
  1163. job_obj.origin_kind = 'excellon'
  1164. job_obj.options['Tools_in_use'] = tool_table_items
  1165. job_obj.options['type'] = 'Excellon'
  1166. job_obj.options['ppname_e'] = pp_excellon_name
  1167. job_obj.pp_excellon_name = pp_excellon_name
  1168. job_obj.toolchange_xy_type = "excellon"
  1169. job_obj.coords_decimals = int(self.app.defaults["cncjob_coords_decimals"])
  1170. job_obj.fr_decimals = int(self.app.defaults["cncjob_fr_decimals"])
  1171. job_obj.options['xmin'] = xmin
  1172. job_obj.options['ymin'] = ymin
  1173. job_obj.options['xmax'] = xmax
  1174. job_obj.options['ymax'] = ymax
  1175. # job_obj.z_pdepth = z_pdepth
  1176. # job_obj.feedrate_probe = feedrate_probe
  1177. #
  1178. # job_obj.toolchange = toolchange
  1179. # job_obj.xy_toolchange = self.app.defaults["excellon_toolchangexy"]
  1180. # job_obj.z_toolchange = z_toolchange
  1181. # job_obj.startz = startz
  1182. # job_obj.endz = endz
  1183. # job_obj.xy_end = xy_end
  1184. # job_obj.excellon_optimization_type = self.app.defaults["excellon_optimization_type"]
  1185. tools_csv = ','.join(tools)
  1186. job_obj.gcode = self.generate_from_excellon_by_tool(tools_csv, self.tools)
  1187. print(job_obj.gcode)
  1188. if job_obj.gcode == 'fail':
  1189. return 'fail'
  1190. job_obj.gcode_parse()
  1191. job_obj.create_geometry()
  1192. # To be run in separate thread
  1193. def job_thread(a_obj):
  1194. with self.app.proc_container.new(_("Generating CNC Code")):
  1195. a_obj.app_obj.new_object("cncjob", job_name, job_init)
  1196. # Create promise for the new name.
  1197. self.app.collection.promise(job_name)
  1198. # Send to worker
  1199. # self.app.worker.add_task(job_thread, [self.app])
  1200. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1201. def drilling_handler(self, obj):
  1202. pass
  1203. # Distance callback
  1204. class CreateDistanceCallback(object):
  1205. """Create callback to calculate distances between points."""
  1206. def __init__(self, locs, manager):
  1207. self.manager = manager
  1208. self.matrix = {}
  1209. if locs:
  1210. size = len(locs)
  1211. for from_node in range(size):
  1212. self.matrix[from_node] = {}
  1213. for to_node in range(size):
  1214. if from_node == to_node:
  1215. self.matrix[from_node][to_node] = 0
  1216. else:
  1217. x1 = locs[from_node][0]
  1218. y1 = locs[from_node][1]
  1219. x2 = locs[to_node][0]
  1220. y2 = locs[to_node][1]
  1221. self.matrix[from_node][to_node] = distance_euclidian(x1, y1, x2, y2)
  1222. # def Distance(self, from_node, to_node):
  1223. # return int(self.matrix[from_node][to_node])
  1224. def Distance(self, from_index, to_index):
  1225. # Convert from routing variable Index to distance matrix NodeIndex.
  1226. from_node = self.manager.IndexToNode(from_index)
  1227. to_node = self.manager.IndexToNode(to_index)
  1228. return self.matrix[from_node][to_node]
  1229. @staticmethod
  1230. def create_tool_data_array(points):
  1231. # Create the data.
  1232. loc_list = []
  1233. for pt in points:
  1234. loc_list.append((pt.coords.xy[0][0], pt.coords.xy[1][0]))
  1235. return loc_list
  1236. def optimized_ortools_meta(self, locations, start=None):
  1237. optimized_path = []
  1238. tsp_size = len(locations)
  1239. num_routes = 1 # The number of routes, which is 1 in the TSP.
  1240. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  1241. depot = 0 if start is None else start
  1242. # Create routing model.
  1243. if tsp_size > 0:
  1244. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  1245. routing = pywrapcp.RoutingModel(manager)
  1246. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  1247. search_parameters.local_search_metaheuristic = (
  1248. routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH)
  1249. # Set search time limit in milliseconds.
  1250. if float(self.app.defaults["excellon_search_time"]) != 0:
  1251. search_parameters.time_limit.seconds = int(
  1252. float(self.app.defaults["excellon_search_time"]))
  1253. else:
  1254. search_parameters.time_limit.seconds = 3
  1255. # Callback to the distance function. The callback takes two
  1256. # arguments (the from and to node indices) and returns the distance between them.
  1257. dist_between_locations = self.CreateDistanceCallback(locs=locations, manager=manager)
  1258. # if there are no distances then go to the next tool
  1259. if not dist_between_locations:
  1260. return
  1261. dist_callback = dist_between_locations.Distance
  1262. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  1263. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  1264. # Solve, returns a solution if any.
  1265. assignment = routing.SolveWithParameters(search_parameters)
  1266. if assignment:
  1267. # Solution cost.
  1268. log.info("OR-tools metaheuristics - Total distance: " + str(assignment.ObjectiveValue()))
  1269. # Inspect solution.
  1270. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  1271. route_number = 0
  1272. node = routing.Start(route_number)
  1273. start_node = node
  1274. while not routing.IsEnd(node):
  1275. if self.app.abort_flag:
  1276. # graceful abort requested by the user
  1277. raise grace
  1278. optimized_path.append(node)
  1279. node = assignment.Value(routing.NextVar(node))
  1280. else:
  1281. log.warning('OR-tools metaheuristics - No solution found.')
  1282. else:
  1283. log.warning('OR-tools metaheuristics - Specify an instance greater than 0.')
  1284. return optimized_path
  1285. # ############################################# ##
  1286. def optimized_ortools_basic(self, locations, start=None):
  1287. optimized_path = []
  1288. tsp_size = len(locations)
  1289. num_routes = 1 # The number of routes, which is 1 in the TSP.
  1290. # Nodes are indexed from 0 to tsp_size - 1. The depot is the starting node of the route.
  1291. depot = 0 if start is None else start
  1292. # Create routing model.
  1293. if tsp_size > 0:
  1294. manager = pywrapcp.RoutingIndexManager(tsp_size, num_routes, depot)
  1295. routing = pywrapcp.RoutingModel(manager)
  1296. search_parameters = pywrapcp.DefaultRoutingSearchParameters()
  1297. # Callback to the distance function. The callback takes two
  1298. # arguments (the from and to node indices) and returns the distance between them.
  1299. dist_between_locations = self.CreateDistanceCallback(locs=locations, manager=manager)
  1300. # if there are no distances then go to the next tool
  1301. if not dist_between_locations:
  1302. return
  1303. dist_callback = dist_between_locations.Distance
  1304. transit_callback_index = routing.RegisterTransitCallback(dist_callback)
  1305. routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)
  1306. # Solve, returns a solution if any.
  1307. assignment = routing.SolveWithParameters(search_parameters)
  1308. if assignment:
  1309. # Solution cost.
  1310. log.info("Total distance: " + str(assignment.ObjectiveValue()))
  1311. # Inspect solution.
  1312. # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1.
  1313. route_number = 0
  1314. node = routing.Start(route_number)
  1315. start_node = node
  1316. while not routing.IsEnd(node):
  1317. optimized_path.append(node)
  1318. node = assignment.Value(routing.NextVar(node))
  1319. else:
  1320. log.warning('No solution found.')
  1321. else:
  1322. log.warning('Specify an instance greater than 0.')
  1323. return optimized_path
  1324. # ############################################# ##
  1325. def optimized_travelling_salesman(self, points, start=None):
  1326. """
  1327. As solving the problem in the brute force way is too slow,
  1328. this function implements a simple heuristic: always
  1329. go to the nearest city.
  1330. Even if this algorithm is extremely simple, it works pretty well
  1331. giving a solution only about 25%% longer than the optimal one (cit. Wikipedia),
  1332. and runs very fast in O(N^2) time complexity.
  1333. >>> optimized_travelling_salesman([[i,j] for i in range(5) for j in range(5)])
  1334. [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 4], [1, 3], [1, 2], [1, 1], [1, 0], [2, 0], [2, 1], [2, 2],
  1335. [2, 3], [2, 4], [3, 4], [3, 3], [3, 2], [3, 1], [3, 0], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]
  1336. >>> optimized_travelling_salesman([[0,0],[10,0],[6,0]])
  1337. [[0, 0], [6, 0], [10, 0]]
  1338. :param points: List of tuples with x, y coordinates
  1339. :type points: list
  1340. :param start: a tuple with a x,y coordinates of the start point
  1341. :type start: tuple
  1342. :return: List of points ordered in a optimized way
  1343. :rtype: list
  1344. """
  1345. if start is None:
  1346. start = points[0]
  1347. must_visit = points
  1348. path = [start]
  1349. # must_visit.remove(start)
  1350. while must_visit:
  1351. nearest = min(must_visit, key=lambda x: distance(path[-1], x))
  1352. path.append(nearest)
  1353. must_visit.remove(nearest)
  1354. return path
  1355. def check_zcut(self, zcut):
  1356. if zcut > 0:
  1357. self.app.inform.emit('[WARNING] %s' %
  1358. _("The Cut Z parameter has positive value. "
  1359. "It is the depth value to drill into material.\n"
  1360. "The Cut Z parameter needs to have a negative value, assuming it is a typo "
  1361. "therefore the app will convert the value to negative. "
  1362. "Check the resulting CNC code (Gcode etc)."))
  1363. return -zcut
  1364. elif zcut == 0:
  1365. self.app.inform.emit('[WARNING] %s.' % _("The Cut Z parameter is zero. There will be no cut, aborting"))
  1366. return 'fail'
  1367. def generate_from_excellon_by_tool(self, sel_tools, tools, order='fwd'):
  1368. """
  1369. Creates Gcode for this object from an Excellon object
  1370. for the specified tools.
  1371. :return: Tool GCode
  1372. :rtype: str
  1373. """
  1374. log.debug("Creating CNC Job from Excellon...")
  1375. settings = QtCore.QSettings("Open Source", "FlatCAM")
  1376. if settings.contains("machinist"):
  1377. machinist_setting = settings.value('machinist', type=int)
  1378. else:
  1379. machinist_setting = 0
  1380. # #############################################################################################################
  1381. # #############################################################################################################
  1382. # TOOLS
  1383. # sort the tools list by the second item in tuple (here we have a dict with diameter of the tool)
  1384. # so we actually are sorting the tools by diameter
  1385. # #############################################################################################################
  1386. # #############################################################################################################
  1387. all_tools = []
  1388. for tool_as_key, v in list(tools.items()):
  1389. all_tools.append((int(tool_as_key), float(v['tooldia'])))
  1390. if order == 'fwd':
  1391. sorted_tools = sorted(all_tools, key=lambda t1: t1[1])
  1392. elif order == 'rev':
  1393. sorted_tools = sorted(all_tools, key=lambda t1: t1[1], reverse=True)
  1394. else:
  1395. sorted_tools = all_tools
  1396. if sel_tools == "all":
  1397. selected_tools = [i[0] for i in all_tools] # we get a array of ordered sel_tools
  1398. else:
  1399. selected_tools = eval(sel_tools)
  1400. # Create a sorted list of selected sel_tools from the sorted_tools list
  1401. sel_tools = [i for i, j in sorted_tools for k in selected_tools if i == k]
  1402. log.debug("Tools sorted are: %s" % str(sel_tools))
  1403. # #############################################################################################################
  1404. # #############################################################################################################
  1405. # #############################################################################################################
  1406. # #############################################################################################################
  1407. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case of
  1408. # running this method from a Tcl Command
  1409. # #############################################################################################################
  1410. # #############################################################################################################
  1411. build_tools_in_use_list = False
  1412. if 'Tools_in_use' not in self.excellon_obj.options:
  1413. self.excellon_obj.options['Tools_in_use'] = []
  1414. # if the list is empty (either we just added the key or it was already there but empty) signal to build it
  1415. if not self.excellon_obj.options['Tools_in_use']:
  1416. build_tools_in_use_list = True
  1417. # #############################################################################################################
  1418. # #############################################################################################################
  1419. # fill the data into the self.exc_cnc_tools dictionary
  1420. # #############################################################################################################
  1421. # #############################################################################################################
  1422. for it in all_tools:
  1423. for to_ol in sel_tools:
  1424. if to_ol == it[0]:
  1425. sol_geo = []
  1426. drill_no = 0
  1427. if 'drills' in tools[to_ol]:
  1428. drill_no = len(tools[to_ol]['drills'])
  1429. for drill in tools[to_ol]['drills']:
  1430. sol_geo.append(drill.buffer((it[1] / 2.0), resolution=self.geo_steps_per_circle))
  1431. slot_no = 0
  1432. if 'slots' in tools[to_ol]:
  1433. slot_no = len(tools[to_ol]['slots'])
  1434. for slot in tools[to_ol]['slots']:
  1435. start = (slot[0].x, slot[0].y)
  1436. stop = (slot[1].x, slot[1].y)
  1437. sol_geo.append(
  1438. LineString([start, stop]).buffer((it[1] / 2.0), resolution=self.geo_steps_per_circle)
  1439. )
  1440. if self.use_ui:
  1441. try:
  1442. z_off = float(tools[it[0]]['data']['offset']) * (-1)
  1443. except KeyError:
  1444. z_off = 0
  1445. else:
  1446. z_off = 0
  1447. default_data = {}
  1448. for k, v in list(self.options.items()):
  1449. default_data[k] = deepcopy(v)
  1450. self.exc_cnc_tools[it[1]] = {}
  1451. self.exc_cnc_tools[it[1]]['tool'] = it[0]
  1452. self.exc_cnc_tools[it[1]]['nr_drills'] = drill_no
  1453. self.exc_cnc_tools[it[1]]['nr_slots'] = slot_no
  1454. self.exc_cnc_tools[it[1]]['offset_z'] = z_off
  1455. self.exc_cnc_tools[it[1]]['data'] = default_data
  1456. self.exc_cnc_tools[it[1]]['solid_geometry'] = deepcopy(sol_geo)
  1457. # build a self.options['Tools_in_use'] list from scratch if we don't have one like in the case of
  1458. # running this method from a Tcl Command
  1459. if build_tools_in_use_list is True:
  1460. self.options['Tools_in_use'].append(
  1461. [it[0], it[1], drill_no, slot_no]
  1462. )
  1463. # #############################################################################################################
  1464. # #############################################################################################################
  1465. # Points (Group by tool): a dictionary of shapely Point geo elements grouped by tool number
  1466. # #############################################################################################################
  1467. # #############################################################################################################
  1468. self.app.inform.emit(_("Creating a list of points to drill..."))
  1469. points = {}
  1470. for tool, tl_dict in tools.items():
  1471. if tool in sel_tools:
  1472. if self.app.abort_flag:
  1473. # graceful abort requested by the user
  1474. raise grace
  1475. if 'drills' in tl_dict and tl_dict['drills']:
  1476. for drill_pt in tl_dict['drills']:
  1477. try:
  1478. points[tool].append(drill_pt)
  1479. except KeyError:
  1480. points[tool] = [drill_pt]
  1481. log.debug("Found %d TOOLS with drills." % len(points))
  1482. # check if there are drill points in the exclusion areas.
  1483. # If we find any within the exclusion areas return 'fail'
  1484. for tool in points:
  1485. for pt in points[tool]:
  1486. for area in self.app.exc_areas.exclusion_areas_storage:
  1487. pt_buf = pt.buffer(self.exc_tools[tool]['tooldia'] / 2.0)
  1488. if pt_buf.within(area['shape']) or pt_buf.intersects(area['shape']):
  1489. self.app.inform.emit("[ERROR_NOTCL] %s" % _("Failed. Drill points inside the exclusion zones."))
  1490. return 'fail'
  1491. # #############################################################################################################
  1492. # General Parameters
  1493. # #############################################################################################################
  1494. used_excellon_optimization_type = self.app.defaults["excellon_optimization_type"]
  1495. self.f_plunge = self.app.defaults["excellon_f_plunge"]
  1496. self.f_retract = self.app.defaults["excellon_f_retract"]
  1497. # Prepprocessor
  1498. self.pp_excellon_name = self.default_data["excellon_ppname_e"]
  1499. self.pp_excellon = self.app.preprocessors[self.pp_excellon_name]
  1500. p = self.pp_excellon
  1501. # this holds the resulting GCode
  1502. gcode = ''
  1503. # #############################################################################################################
  1504. # #############################################################################################################
  1505. # Initialization
  1506. # #############################################################################################################
  1507. # #############################################################################################################
  1508. gcode += self.doformat(p.start_code)
  1509. if self.toolchange is False:
  1510. if self.xy_toolchange is not None:
  1511. gcode += self.doformat(p.lift_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  1512. gcode += self.doformat(p.startz_code, x=self.xy_toolchange[0], y=self.xy_toolchange[1])
  1513. else:
  1514. gcode += self.doformat(p.lift_code, x=0.0, y=0.0)
  1515. gcode += self.doformat(p.startz_code, x=0.0, y=0.0)
  1516. if self.xy_toolchange is not None:
  1517. self.oldx = self.xy_toolchange[0]
  1518. self.oldy = self.xy_toolchange[1]
  1519. else:
  1520. self.oldx = 0.0
  1521. self.oldy = 0.0
  1522. measured_distance = 0.0
  1523. measured_down_distance = 0.0
  1524. measured_up_to_zero_distance = 0.0
  1525. measured_lift_distance = 0.0
  1526. # #############################################################################################################
  1527. # #############################################################################################################
  1528. # GCODE creation
  1529. # #############################################################################################################
  1530. # #############################################################################################################
  1531. self.app.inform.emit('%s...' % _("Starting G-Code"))
  1532. has_drills = None
  1533. for tool, tool_dict in self.exc_tools.items():
  1534. if 'drills' in tool_dict and tool_dict['drills']:
  1535. has_drills = True
  1536. break
  1537. if not has_drills:
  1538. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> "
  1539. "The loaded Excellon file has no drills ...")
  1540. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('The loaded Excellon file has no drills'))
  1541. return 'fail'
  1542. current_platform = platform.architecture()[0]
  1543. if current_platform != '64bit':
  1544. used_excellon_optimization_type = 'T'
  1545. # #############################################################################################################
  1546. # #############################################################################################################
  1547. # ################################## DRILLING !!! #########################################################
  1548. # #############################################################################################################
  1549. # #############################################################################################################
  1550. if used_excellon_optimization_type == 'M':
  1551. log.debug("Using OR-Tools Metaheuristic Guided Local Search drill path optimization.")
  1552. elif used_excellon_optimization_type == 'B':
  1553. log.debug("Using OR-Tools Basic drill path optimization.")
  1554. elif used_excellon_optimization_type == 'T':
  1555. log.debug("Using Travelling Salesman drill path optimization.")
  1556. else:
  1557. log.debug("Using no path optimization.")
  1558. if self.toolchange is True:
  1559. for tool in sel_tools:
  1560. tool_dict = tools[tool]['data']
  1561. # check if it has drills
  1562. if not tools[tool]['drills']:
  1563. continue
  1564. if self.app.abort_flag:
  1565. # graceful abort requested by the user
  1566. raise grace
  1567. self.tool = tool
  1568. self.tooldia = tools[tool]["tooldia"]
  1569. self.postdata['toolC'] = self.tooldia
  1570. self.z_feedrate = tool_dict['feedrate_z']
  1571. self.feedrate = tool_dict['feedrate']
  1572. self.z_cut = tool_dict['cutz']
  1573. gcode += self.doformat(p.z_feedrate_code)
  1574. # Z_cut parameter
  1575. if machinist_setting == 0:
  1576. self.z_cut = self.check_zcut(zcut=tool_dict["excellon_cutz"])
  1577. if self.z_cut == 'fail':
  1578. return 'fail'
  1579. # multidepth use this
  1580. old_zcut = tool_dict["excellon_cutz"]
  1581. self.z_move = tool_dict['travelz']
  1582. self.spindlespeed = tool_dict['spindlespeed']
  1583. self.dwell = tool_dict['dwell']
  1584. self.dwelltime = tool_dict['dwelltime']
  1585. self.multidepth = tool_dict['multidepth']
  1586. self.z_depthpercut = tool_dict['depthperpass']
  1587. # XY_toolchange parameter
  1588. self.xy_toolchange = tool_dict["excellon_toolchangexy"]
  1589. try:
  1590. if self.xy_toolchange == '':
  1591. self.xy_toolchange = None
  1592. else:
  1593. self.xy_toolchange = re.sub('[()\[\]]', '',
  1594. str(self.xy_toolchange)) if self.xy_toolchange else None
  1595. if self.xy_toolchange:
  1596. self.xy_toolchange = [float(eval(a)) for a in self.xy_toolchange.split(",")]
  1597. if self.xy_toolchange and len(self.xy_toolchange) != 2:
  1598. self.app.inform.emit('[ERROR]%s' %
  1599. _("The Toolchange X,Y field in Edit -> Preferences has to be "
  1600. "in the format (x, y) \nbut now there is only one value, not two. "))
  1601. return 'fail'
  1602. except Exception as e:
  1603. log.debug("camlib.CNCJob.generate_from_excellon_by_tool() --> %s" % str(e))
  1604. pass
  1605. # XY_end parameter
  1606. self.xy_end = tool_dict["excellon_endxy"]
  1607. self.xy_end = re.sub('[()\[\]]', '', str(self.xy_end)) if self.xy_end else None
  1608. if self.xy_end and self.xy_end != '':
  1609. self.xy_end = [float(eval(a)) for a in self.xy_end.split(",")]
  1610. if self.xy_end and len(self.xy_end) < 2:
  1611. self.app.inform.emit(
  1612. '[ERROR] %s' % _("The End Move X,Y field in Edit -> Preferences has to be "
  1613. "in the format (x, y) but now there is only one value, not two."))
  1614. return 'fail'
  1615. # #########################################################################################################
  1616. # ############ Create the data. #################
  1617. # #########################################################################################################
  1618. locations = []
  1619. altPoints = []
  1620. optimized_path = []
  1621. if used_excellon_optimization_type == 'M':
  1622. if tool in points:
  1623. locations = self.create_tool_data_array(points=points[tool])
  1624. # if there are no locations then go to the next tool
  1625. if not locations:
  1626. continue
  1627. optimized_path = self.optimized_ortools_meta(locations=locations)
  1628. elif used_excellon_optimization_type == 'B':
  1629. if tool in points:
  1630. locations = self.create_tool_data_array(points=points[tool])
  1631. # if there are no locations then go to the next tool
  1632. if not locations:
  1633. continue
  1634. optimized_path = self.optimized_ortools_basic(locations=locations)
  1635. elif used_excellon_optimization_type == 'T':
  1636. for point in points[tool]:
  1637. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  1638. optimized_path = self.optimized_travelling_salesman(altPoints)
  1639. else:
  1640. # it's actually not optimized path but here we build a list of (x,y) coordinates
  1641. # out of the tool's drills
  1642. for drill in self.exc_tools[tool]['drills']:
  1643. unoptimized_coords = (
  1644. drill.x,
  1645. drill.y
  1646. )
  1647. optimized_path.append(unoptimized_coords)
  1648. # #########################################################################################################
  1649. # #########################################################################################################
  1650. # Only if there are locations to drill
  1651. if not optimized_path:
  1652. continue
  1653. if self.app.abort_flag:
  1654. # graceful abort requested by the user
  1655. raise grace
  1656. # Tool change sequence (optional)
  1657. if self.toolchange:
  1658. gcode += self.doformat(p.toolchange_code, toolchangexy=(self.oldx, self.oldy))
  1659. # Spindle start
  1660. gcode += self.doformat(p.spindle_code)
  1661. # Dwell time
  1662. if self.dwell is True:
  1663. gcode += self.doformat(p.dwell_code)
  1664. current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[tool]["tooldia"])))
  1665. self.app.inform.emit(
  1666. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  1667. str(current_tooldia),
  1668. str(self.units))
  1669. )
  1670. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  1671. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  1672. # because the values for Z offset are created in build_ui()
  1673. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  1674. try:
  1675. z_offset = float(tool_dict['offset']) * (-1)
  1676. except KeyError:
  1677. z_offset = 0
  1678. self.z_cut = z_offset + old_zcut
  1679. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  1680. if self.coordinates_type == "G90":
  1681. # Drillling! for Absolute coordinates type G90
  1682. # variables to display the percentage of work done
  1683. geo_len = len(optimized_path)
  1684. old_disp_number = 0
  1685. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  1686. loc_nr = 0
  1687. for point in optimized_path:
  1688. if self.app.abort_flag:
  1689. # graceful abort requested by the user
  1690. raise grace
  1691. if used_excellon_optimization_type == 'T':
  1692. locx = point[0]
  1693. locy = point[1]
  1694. else:
  1695. locx = locations[point][0]
  1696. locy = locations[point][1]
  1697. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  1698. end_point=(locx, locy),
  1699. tooldia=current_tooldia)
  1700. prev_z = None
  1701. for travel in travels:
  1702. locx = travel[1][0]
  1703. locy = travel[1][1]
  1704. if travel[0] is not None:
  1705. # move to next point
  1706. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  1707. # raise to safe Z (travel[0]) each time because safe Z may be different
  1708. self.z_move = travel[0]
  1709. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  1710. # restore z_move
  1711. self.z_move = tool_dict['travelz']
  1712. else:
  1713. if prev_z is not None:
  1714. # move to next point
  1715. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  1716. # we assume that previously the z_move was altered therefore raise to
  1717. # the travel_z (z_move)
  1718. self.z_move = tool_dict['travelz']
  1719. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  1720. else:
  1721. # move to next point
  1722. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  1723. # store prev_z
  1724. prev_z = travel[0]
  1725. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  1726. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  1727. doc = deepcopy(self.z_cut)
  1728. self.z_cut = 0.0
  1729. while abs(self.z_cut) < abs(doc):
  1730. self.z_cut -= self.z_depthpercut
  1731. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  1732. self.z_cut = doc
  1733. gcode += self.doformat(p.down_code, x=locx, y=locy)
  1734. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  1735. if self.f_retract is False:
  1736. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  1737. measured_up_to_zero_distance += abs(self.z_cut)
  1738. measured_lift_distance += abs(self.z_move)
  1739. else:
  1740. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  1741. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  1742. else:
  1743. gcode += self.doformat(p.down_code, x=locx, y=locy)
  1744. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  1745. if self.f_retract is False:
  1746. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  1747. measured_up_to_zero_distance += abs(self.z_cut)
  1748. measured_lift_distance += abs(self.z_move)
  1749. else:
  1750. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  1751. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  1752. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  1753. self.oldx = locx
  1754. self.oldy = locy
  1755. loc_nr += 1
  1756. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  1757. if old_disp_number < disp_number <= 100:
  1758. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1759. old_disp_number = disp_number
  1760. else:
  1761. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  1762. return 'fail'
  1763. self.z_cut = deepcopy(old_zcut)
  1764. else:
  1765. # We are not using Toolchange therefore we need to decide which tool properties to use
  1766. one_tool = 1
  1767. all_points = []
  1768. for tool in points:
  1769. # check if it has drills
  1770. if not points[tool]:
  1771. continue
  1772. all_points += points[tool]
  1773. if self.app.abort_flag:
  1774. # graceful abort requested by the user
  1775. raise grace
  1776. self.tool = one_tool
  1777. self.tooldia = self.exc_tools[one_tool]["tooldia"]
  1778. self.postdata['toolC'] = self.tooldia
  1779. if self.use_ui:
  1780. self.z_feedrate = self.exc_tools[one_tool]['data']['feedrate_z']
  1781. self.feedrate = self.exc_tools[one_tool]['data']['feedrate']
  1782. self.z_cut = self.exc_tools[one_tool]['data']['cutz']
  1783. gcode += self.doformat(p.z_feedrate_code)
  1784. if self.machinist_setting == 0:
  1785. if self.z_cut > 0:
  1786. self.app.inform.emit('[WARNING] %s' %
  1787. _("The Cut Z parameter has positive value. "
  1788. "It is the depth value to drill into material.\n"
  1789. "The Cut Z parameter needs to have a negative value, "
  1790. "assuming it is a typo "
  1791. "therefore the app will convert the value to negative. "
  1792. "Check the resulting CNC code (Gcode etc)."))
  1793. self.z_cut = -self.z_cut
  1794. elif self.z_cut == 0:
  1795. self.app.inform.emit('[WARNING] %s.' %
  1796. _("The Cut Z parameter is zero. There will be no cut, skipping file"))
  1797. return 'fail'
  1798. old_zcut = deepcopy(self.z_cut)
  1799. self.z_move = self.exc_tools[one_tool]['data']['travelz']
  1800. self.spindlespeed = self.exc_tools[one_tool]['data']['spindlespeed']
  1801. self.dwell = self.exc_tools[one_tool]['data']['dwell']
  1802. self.dwelltime = self.exc_tools[one_tool]['data']['dwelltime']
  1803. self.multidepth = self.exc_tools[one_tool]['data']['multidepth']
  1804. self.z_depthpercut = self.exc_tools[one_tool]['data']['depthperpass']
  1805. else:
  1806. old_zcut = deepcopy(self.z_cut)
  1807. # #########################################################################################################
  1808. # ############ Create the data. #################
  1809. # #########################################################################################################
  1810. locations = []
  1811. altPoints = []
  1812. optimized_path = []
  1813. if used_excellon_optimization_type == 'M':
  1814. if all_points:
  1815. locations = self.create_tool_data_array(points=all_points)
  1816. # if there are no locations then go to the next tool
  1817. if not locations:
  1818. return 'fail'
  1819. optimized_path = self.optimized_ortools_meta(locations=locations)
  1820. elif used_excellon_optimization_type == 'B':
  1821. if all_points:
  1822. locations = self.create_tool_data_array(points=all_points)
  1823. # if there are no locations then go to the next tool
  1824. if not locations:
  1825. return 'fail'
  1826. optimized_path = self.optimized_ortools_basic(locations=locations)
  1827. elif used_excellon_optimization_type == 'T':
  1828. for point in all_points:
  1829. altPoints.append((point.coords.xy[0][0], point.coords.xy[1][0]))
  1830. optimized_path = self.optimized_travelling_salesman(altPoints)
  1831. else:
  1832. # it's actually not optimized path but here we build a list of (x,y) coordinates
  1833. # out of the tool's drills
  1834. for pt in all_points:
  1835. unoptimized_coords = (
  1836. pt.x,
  1837. pt.y
  1838. )
  1839. optimized_path.append(unoptimized_coords)
  1840. # #########################################################################################################
  1841. # #########################################################################################################
  1842. # Only if there are locations to drill
  1843. if not optimized_path:
  1844. return 'fail'
  1845. if self.app.abort_flag:
  1846. # graceful abort requested by the user
  1847. raise grace
  1848. # Spindle start
  1849. gcode += self.doformat(p.spindle_code)
  1850. # Dwell time
  1851. if self.dwell is True:
  1852. gcode += self.doformat(p.dwell_code)
  1853. current_tooldia = float('%.*f' % (self.decimals, float(self.exc_tools[one_tool]["tooldia"])))
  1854. self.app.inform.emit(
  1855. '%s: %s%s.' % (_("Starting G-Code for tool with diameter"),
  1856. str(current_tooldia),
  1857. str(self.units))
  1858. )
  1859. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  1860. # APPLY Offset only when using the appGUI, for TclCommand this will create an error
  1861. # because the values for Z offset are created in build_ui()
  1862. # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  1863. try:
  1864. z_offset = float(self.exc_tools[one_tool]['data']['offset']) * (-1)
  1865. except KeyError:
  1866. z_offset = 0
  1867. self.z_cut = z_offset + old_zcut
  1868. self.coordinates_type = self.app.defaults["cncjob_coords_type"]
  1869. if self.coordinates_type == "G90":
  1870. # Drillling! for Absolute coordinates type G90
  1871. # variables to display the percentage of work done
  1872. geo_len = len(optimized_path)
  1873. old_disp_number = 0
  1874. log.warning("Number of drills for which to generate GCode: %s" % str(geo_len))
  1875. loc_nr = 0
  1876. for point in optimized_path:
  1877. if self.app.abort_flag:
  1878. # graceful abort requested by the user
  1879. raise grace
  1880. if used_excellon_optimization_type == 'T':
  1881. locx = point[0]
  1882. locy = point[1]
  1883. else:
  1884. locx = locations[point][0]
  1885. locy = locations[point][1]
  1886. travels = self.app.exc_areas.travel_coordinates(start_point=(self.oldx, self.oldy),
  1887. end_point=(locx, locy),
  1888. tooldia=current_tooldia)
  1889. prev_z = None
  1890. for travel in travels:
  1891. locx = travel[1][0]
  1892. locy = travel[1][1]
  1893. if travel[0] is not None:
  1894. # move to next point
  1895. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  1896. # raise to safe Z (travel[0]) each time because safe Z may be different
  1897. self.z_move = travel[0]
  1898. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  1899. # restore z_move
  1900. self.z_move = self.exc_tools[one_tool]['data']['travelz']
  1901. else:
  1902. if prev_z is not None:
  1903. # move to next point
  1904. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  1905. # we assume that previously the z_move was altered therefore raise to
  1906. # the travel_z (z_move)
  1907. self.z_move = self.exc_tools[one_tool]['data']['travelz']
  1908. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  1909. else:
  1910. # move to next point
  1911. gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  1912. # store prev_z
  1913. prev_z = travel[0]
  1914. # gcode += self.doformat(p.rapid_code, x=locx, y=locy)
  1915. if self.multidepth and abs(self.z_cut) > abs(self.z_depthpercut):
  1916. doc = deepcopy(self.z_cut)
  1917. self.z_cut = 0.0
  1918. while abs(self.z_cut) < abs(doc):
  1919. self.z_cut -= self.z_depthpercut
  1920. if abs(doc) < abs(self.z_cut) < (abs(doc) + self.z_depthpercut):
  1921. self.z_cut = doc
  1922. gcode += self.doformat(p.down_code, x=locx, y=locy)
  1923. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  1924. if self.f_retract is False:
  1925. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  1926. measured_up_to_zero_distance += abs(self.z_cut)
  1927. measured_lift_distance += abs(self.z_move)
  1928. else:
  1929. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  1930. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  1931. else:
  1932. gcode += self.doformat(p.down_code, x=locx, y=locy)
  1933. measured_down_distance += abs(self.z_cut) + abs(self.z_move)
  1934. if self.f_retract is False:
  1935. gcode += self.doformat(p.up_to_zero_code, x=locx, y=locy)
  1936. measured_up_to_zero_distance += abs(self.z_cut)
  1937. measured_lift_distance += abs(self.z_move)
  1938. else:
  1939. measured_lift_distance += abs(self.z_cut) + abs(self.z_move)
  1940. gcode += self.doformat(p.lift_code, x=locx, y=locy)
  1941. measured_distance += abs(distance_euclidian(locx, locy, self.oldx, self.oldy))
  1942. self.oldx = locx
  1943. self.oldy = locy
  1944. loc_nr += 1
  1945. disp_number = int(np.interp(loc_nr, [0, geo_len], [0, 100]))
  1946. if old_disp_number < disp_number <= 100:
  1947. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1948. old_disp_number = disp_number
  1949. else:
  1950. self.app.inform.emit('[ERROR_NOTCL] %s...' % _('G91 coordinates not implemented'))
  1951. return 'fail'
  1952. self.z_cut = deepcopy(old_zcut)
  1953. if used_excellon_optimization_type == 'M':
  1954. log.debug("The total travel distance with OR-TOOLS Metaheuristics is: %s" % str(measured_distance))
  1955. elif used_excellon_optimization_type == 'B':
  1956. log.debug("The total travel distance with OR-TOOLS Basic Algorithm is: %s" % str(measured_distance))
  1957. elif used_excellon_optimization_type == 'T':
  1958. log.debug("The total travel distance with Travelling Salesman Algorithm is: %s" % str(measured_distance))
  1959. else:
  1960. log.debug("The total travel distance with with no optimization is: %s" % str(measured_distance))
  1961. gcode += self.doformat(p.spindle_stop_code)
  1962. # Move to End position
  1963. gcode += self.doformat(p.end_code, x=0, y=0)
  1964. # #############################################################################################################
  1965. # ############################# Calculate DISTANCE and ESTIMATED TIME #########################################
  1966. # #############################################################################################################
  1967. measured_distance += abs(distance_euclidian(self.oldx, self.oldy, 0, 0))
  1968. log.debug("The total travel distance including travel to end position is: %s" %
  1969. str(measured_distance) + '\n')
  1970. self.travel_distance = measured_distance
  1971. # I use the value of self.feedrate_rapid for the feadrate in case of the measure_lift_distance and for
  1972. # traveled_time because it is not always possible to determine the feedrate that the CNC machine uses
  1973. # for G0 move (the fastest speed available to the CNC router). Although self.feedrate_rapids is used only with
  1974. # Marlin preprocessor and derivatives.
  1975. self.routing_time = (measured_down_distance + measured_up_to_zero_distance) / self.feedrate
  1976. lift_time = measured_lift_distance / self.feedrate_rapid
  1977. traveled_time = measured_distance / self.feedrate_rapid
  1978. self.routing_time += lift_time + traveled_time
  1979. self.app.inform.emit(_("Finished G-Code generation..."))
  1980. return gcode
  1981. def reset_fields(self):
  1982. self.object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  1983. def doformat(self, fun, **kwargs):
  1984. return self.doformat2(fun, **kwargs) + "\n"
  1985. def doformat2(self, fun, **kwargs):
  1986. """
  1987. This method will call one of the current preprocessor methods having as parameters all the attributes of
  1988. current class to which will add the kwargs parameters
  1989. :param fun: One of the methods inside the preprocessor classes which get loaded here in the 'p' object
  1990. :type fun: class 'function'
  1991. :param kwargs: keyword args which will update attributes of the current class
  1992. :type kwargs: dict
  1993. :return: Gcode line
  1994. :rtype: str
  1995. """
  1996. attributes = AttrDict()
  1997. attributes.update(self.postdata)
  1998. attributes.update(kwargs)
  1999. try:
  2000. returnvalue = fun(attributes)
  2001. return returnvalue
  2002. except Exception:
  2003. self.app.log.error('Exception occurred within a preprocessor: ' + traceback.format_exc())
  2004. return ''
  2005. @property
  2006. def postdata(self):
  2007. """
  2008. This will return all the attributes of the class in the form of a dictionary
  2009. :return: Class attributes
  2010. :rtype: dict
  2011. """
  2012. return self.__dict__
  2013. class DrillingUI:
  2014. toolName = _("Drilling Tool")
  2015. def __init__(self, layout, app):
  2016. self.app = app
  2017. self.decimals = self.app.decimals
  2018. self.layout = layout
  2019. self.tools_frame = QtWidgets.QFrame()
  2020. self.tools_frame.setContentsMargins(0, 0, 0, 0)
  2021. self.layout.addWidget(self.tools_frame)
  2022. self.tools_box = QtWidgets.QVBoxLayout()
  2023. self.tools_box.setContentsMargins(0, 0, 0, 0)
  2024. self.tools_frame.setLayout(self.tools_box)
  2025. self.title_box = QtWidgets.QHBoxLayout()
  2026. self.tools_box.addLayout(self.title_box)
  2027. # ## Title
  2028. title_label = QtWidgets.QLabel("%s" % self.toolName)
  2029. title_label.setStyleSheet("""
  2030. QLabel
  2031. {
  2032. font-size: 16px;
  2033. font-weight: bold;
  2034. }
  2035. """)
  2036. title_label.setToolTip(
  2037. _("Create CNCJob with toolpaths for drilling or milling holes.")
  2038. )
  2039. self.title_box.addWidget(title_label)
  2040. # App Level label
  2041. self.level = QtWidgets.QLabel("")
  2042. self.level.setToolTip(
  2043. _(
  2044. "BASIC is suitable for a beginner. Many parameters\n"
  2045. "are hidden from the user in this mode.\n"
  2046. "ADVANCED mode will make available all parameters.\n\n"
  2047. "To change the application LEVEL, go to:\n"
  2048. "Edit -> Preferences -> General and check:\n"
  2049. "'APP. LEVEL' radio button."
  2050. )
  2051. )
  2052. self.level.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  2053. self.title_box.addWidget(self.level)
  2054. # Grid Layout
  2055. grid0 = QtWidgets.QGridLayout()
  2056. grid0.setColumnStretch(0, 0)
  2057. grid0.setColumnStretch(1, 1)
  2058. self.tools_box.addLayout(grid0)
  2059. self.obj_combo_label = QtWidgets.QLabel('<b>%s</b>:' % _("EXCELLON"))
  2060. self.obj_combo_label.setToolTip(
  2061. _("Excellon object for drilling/milling operation.")
  2062. )
  2063. grid0.addWidget(self.obj_combo_label, 0, 0, 1, 2)
  2064. # ################################################
  2065. # ##### The object to be drilled #################
  2066. # ################################################
  2067. self.object_combo = FCComboBox()
  2068. self.object_combo.setModel(self.app.collection)
  2069. self.object_combo.setRootModelIndex(self.app.collection.index(1, 0, QtCore.QModelIndex()))
  2070. # self.object_combo.setCurrentIndex(1)
  2071. self.object_combo.is_last = True
  2072. grid0.addWidget(self.object_combo, 1, 0, 1, 2)
  2073. separator_line = QtWidgets.QFrame()
  2074. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2075. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2076. grid0.addWidget(separator_line, 2, 0, 1, 2)
  2077. # ################################################
  2078. # ########## Excellon Tool Table #################
  2079. # ################################################
  2080. self.tools_table = FCTable(drag_drop=True)
  2081. grid0.addWidget(self.tools_table, 3, 0, 1, 2)
  2082. self.tools_table.setColumnCount(5)
  2083. self.tools_table.setColumnHidden(3, True)
  2084. self.tools_table.setSortingEnabled(False)
  2085. self.tools_table.setHorizontalHeaderLabels(['#', _('Diameter'), _('Drills'), '', _('Slots')])
  2086. self.tools_table.horizontalHeaderItem(0).setToolTip(
  2087. _("This is the Tool Number.\n"
  2088. "When ToolChange is checked, on toolchange event this value\n"
  2089. "will be showed as a T1, T2 ... Tn in the Machine Code.\n\n"
  2090. "Here the tools are selected for G-code generation."))
  2091. self.tools_table.horizontalHeaderItem(1).setToolTip(
  2092. _("Tool Diameter. It's value (in current FlatCAM units) \n"
  2093. "is the cut width into the material."))
  2094. self.tools_table.horizontalHeaderItem(2).setToolTip(
  2095. _("The number of Drill holes. Holes that are drilled with\n"
  2096. "a drill bit."))
  2097. self.tools_table.horizontalHeaderItem(4).setToolTip(
  2098. _("The number of Slot holes. Holes that are created by\n"
  2099. "milling them with an endmill bit."))
  2100. # Tool order
  2101. self.order_label = QtWidgets.QLabel('%s:' % _('Tool order'))
  2102. self.order_label.setToolTip(_("This set the way that the tools in the tools table are used.\n"
  2103. "'No' --> means that the used order is the one in the tool table\n"
  2104. "'Forward' --> means that the tools will be ordered from small to big\n"
  2105. "'Reverse' --> means that the tools will ordered from big to small\n\n"
  2106. "WARNING: using rest machining will automatically set the order\n"
  2107. "in reverse and disable this control."))
  2108. self.order_radio = RadioSet([{'label': _('No'), 'value': 'no'},
  2109. {'label': _('Forward'), 'value': 'fwd'},
  2110. {'label': _('Reverse'), 'value': 'rev'}])
  2111. grid0.addWidget(self.order_label, 4, 0)
  2112. grid0.addWidget(self.order_radio, 4, 1)
  2113. separator_line = QtWidgets.QFrame()
  2114. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2115. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2116. grid0.addWidget(separator_line, 5, 0, 1, 2)
  2117. # ###########################################################
  2118. # ############# Create CNC Job ##############################
  2119. # ###########################################################
  2120. self.tool_data_label = QtWidgets.QLabel(
  2121. "<b>%s: <font color='#0000FF'>%s %d</font></b>" % (_('Parameters for'), _("Tool"), int(1)))
  2122. self.tool_data_label.setToolTip(
  2123. _(
  2124. "The data used for creating GCode.\n"
  2125. "Each tool store it's own set of such data."
  2126. )
  2127. )
  2128. grid0.addWidget(self.tool_data_label, 6, 0, 1, 2)
  2129. self.exc_param_frame = QtWidgets.QFrame()
  2130. self.exc_param_frame.setContentsMargins(0, 0, 0, 0)
  2131. grid0.addWidget(self.exc_param_frame, 7, 0, 1, 2)
  2132. self.exc_tools_box = QtWidgets.QVBoxLayout()
  2133. self.exc_tools_box.setContentsMargins(0, 0, 0, 0)
  2134. self.exc_param_frame.setLayout(self.exc_tools_box)
  2135. # #################################################################
  2136. # ################# GRID LAYOUT 3 ###############################
  2137. # #################################################################
  2138. self.grid1 = QtWidgets.QGridLayout()
  2139. self.grid1.setColumnStretch(0, 0)
  2140. self.grid1.setColumnStretch(1, 1)
  2141. self.exc_tools_box.addLayout(self.grid1)
  2142. # Cut Z
  2143. self.cutzlabel = QtWidgets.QLabel('%s:' % _('Cut Z'))
  2144. self.cutzlabel.setToolTip(
  2145. _("Drill depth (negative)\n"
  2146. "below the copper surface.")
  2147. )
  2148. self.cutz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2149. self.cutz_entry.set_precision(self.decimals)
  2150. if machinist_setting == 0:
  2151. self.cutz_entry.set_range(-9999.9999, 0.0000)
  2152. else:
  2153. self.cutz_entry.set_range(-9999.9999, 9999.9999)
  2154. self.cutz_entry.setSingleStep(0.1)
  2155. self.cutz_entry.setObjectName("e_cutz")
  2156. self.grid1.addWidget(self.cutzlabel, 4, 0)
  2157. self.grid1.addWidget(self.cutz_entry, 4, 1)
  2158. # Multi-Depth
  2159. self.mpass_cb = FCCheckBox('%s:' % _("Multi-Depth"))
  2160. self.mpass_cb.setToolTip(
  2161. _(
  2162. "Use multiple passes to limit\n"
  2163. "the cut depth in each pass. Will\n"
  2164. "cut multiple times until Cut Z is\n"
  2165. "reached."
  2166. )
  2167. )
  2168. self.mpass_cb.setObjectName("e_multidepth")
  2169. self.maxdepth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2170. self.maxdepth_entry.set_precision(self.decimals)
  2171. self.maxdepth_entry.set_range(0, 9999.9999)
  2172. self.maxdepth_entry.setSingleStep(0.1)
  2173. self.maxdepth_entry.setToolTip(_("Depth of each pass (positive)."))
  2174. self.maxdepth_entry.setObjectName("e_depthperpass")
  2175. self.mis_mpass_geo = OptionalInputSection(self.mpass_cb, [self.maxdepth_entry])
  2176. self.grid1.addWidget(self.mpass_cb, 5, 0)
  2177. self.grid1.addWidget(self.maxdepth_entry, 5, 1)
  2178. # Travel Z (z_move)
  2179. self.travelzlabel = QtWidgets.QLabel('%s:' % _('Travel Z'))
  2180. self.travelzlabel.setToolTip(
  2181. _("Tool height when travelling\n"
  2182. "across the XY plane.")
  2183. )
  2184. self.travelz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2185. self.travelz_entry.set_precision(self.decimals)
  2186. if machinist_setting == 0:
  2187. self.travelz_entry.set_range(0.00001, 9999.9999)
  2188. else:
  2189. self.travelz_entry.set_range(-9999.9999, 9999.9999)
  2190. self.travelz_entry.setSingleStep(0.1)
  2191. self.travelz_entry.setObjectName("e_travelz")
  2192. self.grid1.addWidget(self.travelzlabel, 6, 0)
  2193. self.grid1.addWidget(self.travelz_entry, 6, 1)
  2194. # Excellon Feedrate Z
  2195. self.frzlabel = QtWidgets.QLabel('%s:' % _('Feedrate Z'))
  2196. self.frzlabel.setToolTip(
  2197. _("Tool speed while drilling\n"
  2198. "(in units per minute).\n"
  2199. "So called 'Plunge' feedrate.\n"
  2200. "This is for linear move G01.")
  2201. )
  2202. self.feedrate_z_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2203. self.feedrate_z_entry.set_precision(self.decimals)
  2204. self.feedrate_z_entry.set_range(0.0, 99999.9999)
  2205. self.feedrate_z_entry.setSingleStep(0.1)
  2206. self.feedrate_z_entry.setObjectName("e_feedratez")
  2207. self.grid1.addWidget(self.frzlabel, 14, 0)
  2208. self.grid1.addWidget(self.feedrate_z_entry, 14, 1)
  2209. # Excellon Rapid Feedrate
  2210. self.feedrate_rapid_label = QtWidgets.QLabel('%s:' % _('Feedrate Rapids'))
  2211. self.feedrate_rapid_label.setToolTip(
  2212. _("Tool speed while drilling\n"
  2213. "(in units per minute).\n"
  2214. "This is for the rapid move G00.\n"
  2215. "It is useful only for Marlin,\n"
  2216. "ignore for any other cases.")
  2217. )
  2218. self.feedrate_rapid_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2219. self.feedrate_rapid_entry.set_precision(self.decimals)
  2220. self.feedrate_rapid_entry.set_range(0.0, 99999.9999)
  2221. self.feedrate_rapid_entry.setSingleStep(0.1)
  2222. self.feedrate_rapid_entry.setObjectName("e_fr_rapid")
  2223. self.grid1.addWidget(self.feedrate_rapid_label, 16, 0)
  2224. self.grid1.addWidget(self.feedrate_rapid_entry, 16, 1)
  2225. # default values is to hide
  2226. self.feedrate_rapid_label.hide()
  2227. self.feedrate_rapid_entry.hide()
  2228. # Spindlespeed
  2229. self.spindle_label = QtWidgets.QLabel('%s:' % _('Spindle speed'))
  2230. self.spindle_label.setToolTip(
  2231. _("Speed of the spindle\n"
  2232. "in RPM (optional)")
  2233. )
  2234. self.spindlespeed_entry = FCSpinner(callback=self.confirmation_message_int)
  2235. self.spindlespeed_entry.set_range(0, 1000000)
  2236. self.spindlespeed_entry.set_step(100)
  2237. self.spindlespeed_entry.setObjectName("e_spindlespeed")
  2238. self.grid1.addWidget(self.spindle_label, 19, 0)
  2239. self.grid1.addWidget(self.spindlespeed_entry, 19, 1)
  2240. # Dwell
  2241. self.dwell_cb = FCCheckBox('%s:' % _('Dwell'))
  2242. self.dwell_cb.setToolTip(
  2243. _("Pause to allow the spindle to reach its\n"
  2244. "speed before cutting.")
  2245. )
  2246. self.dwell_cb.setObjectName("e_dwell")
  2247. # Dwelltime
  2248. self.dwelltime_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2249. self.dwelltime_entry.set_precision(self.decimals)
  2250. self.dwelltime_entry.set_range(0.0, 9999.9999)
  2251. self.dwelltime_entry.setSingleStep(0.1)
  2252. self.dwelltime_entry.setToolTip(
  2253. _("Number of time units for spindle to dwell.")
  2254. )
  2255. self.dwelltime_entry.setObjectName("e_dwelltime")
  2256. self.grid1.addWidget(self.dwell_cb, 20, 0)
  2257. self.grid1.addWidget(self.dwelltime_entry, 20, 1)
  2258. self.ois_dwell = OptionalInputSection(self.dwell_cb, [self.dwelltime_entry])
  2259. # Tool Offset
  2260. self.tool_offset_label = QtWidgets.QLabel('%s:' % _('Offset Z'))
  2261. self.tool_offset_label.setToolTip(
  2262. _("Some drill bits (the larger ones) need to drill deeper\n"
  2263. "to create the desired exit hole diameter due of the tip shape.\n"
  2264. "The value here can compensate the Cut Z parameter.")
  2265. )
  2266. self.offset_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2267. self.offset_entry.set_precision(self.decimals)
  2268. self.offset_entry.set_range(-9999.9999, 9999.9999)
  2269. self.offset_entry.setObjectName("e_offset")
  2270. self.grid1.addWidget(self.tool_offset_label, 25, 0)
  2271. self.grid1.addWidget(self.offset_entry, 25, 1)
  2272. # #################################################################
  2273. # ################# GRID LAYOUT 5 ###############################
  2274. # #################################################################
  2275. # ################# COMMON PARAMETERS #############################
  2276. self.grid3 = QtWidgets.QGridLayout()
  2277. self.grid3.setColumnStretch(0, 0)
  2278. self.grid3.setColumnStretch(1, 1)
  2279. self.exc_tools_box.addLayout(self.grid3)
  2280. separator_line2 = QtWidgets.QFrame()
  2281. separator_line2.setFrameShape(QtWidgets.QFrame.HLine)
  2282. separator_line2.setFrameShadow(QtWidgets.QFrame.Sunken)
  2283. self.grid3.addWidget(separator_line2, 0, 0, 1, 2)
  2284. self.apply_param_to_all = FCButton(_("Apply parameters to all tools"))
  2285. self.apply_param_to_all.setToolTip(
  2286. _("The parameters in the current form will be applied\n"
  2287. "on all the tools from the Tool Table.")
  2288. )
  2289. self.grid3.addWidget(self.apply_param_to_all, 1, 0, 1, 2)
  2290. separator_line2 = QtWidgets.QFrame()
  2291. separator_line2.setFrameShape(QtWidgets.QFrame.HLine)
  2292. separator_line2.setFrameShadow(QtWidgets.QFrame.Sunken)
  2293. self.grid3.addWidget(separator_line2, 2, 0, 1, 2)
  2294. # General Parameters
  2295. self.gen_param_label = QtWidgets.QLabel('<b>%s</b>' % _("Common Parameters"))
  2296. self.gen_param_label.setToolTip(
  2297. _("Parameters that are common for all tools.")
  2298. )
  2299. self.grid3.addWidget(self.gen_param_label, 3, 0, 1, 2)
  2300. # Tool change Z:
  2301. self.toolchange_cb = FCCheckBox('%s:' % _("Tool change Z"))
  2302. self.toolchange_cb.setToolTip(
  2303. _("Include tool-change sequence\n"
  2304. "in G-Code (Pause for tool change).")
  2305. )
  2306. self.toolchangez_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2307. self.toolchangez_entry.set_precision(self.decimals)
  2308. self.toolchangez_entry.setToolTip(
  2309. _("Z-axis position (height) for\n"
  2310. "tool change.")
  2311. )
  2312. if machinist_setting == 0:
  2313. self.toolchangez_entry.set_range(0.0, 9999.9999)
  2314. else:
  2315. self.toolchangez_entry.set_range(-9999.9999, 9999.9999)
  2316. self.toolchangez_entry.setSingleStep(0.1)
  2317. self.ois_tcz_e = OptionalInputSection(self.toolchange_cb, [self.toolchangez_entry])
  2318. self.grid3.addWidget(self.toolchange_cb, 8, 0)
  2319. self.grid3.addWidget(self.toolchangez_entry, 8, 1)
  2320. # Start move Z:
  2321. self.estartz_label = QtWidgets.QLabel('%s:' % _("Start Z"))
  2322. self.estartz_label.setToolTip(
  2323. _("Height of the tool just after start.\n"
  2324. "Delete the value if you don't need this feature.")
  2325. )
  2326. self.estartz_entry = NumericalEvalEntry(border_color='#0069A9')
  2327. self.grid3.addWidget(self.estartz_label, 9, 0)
  2328. self.grid3.addWidget(self.estartz_entry, 9, 1)
  2329. # End move Z:
  2330. self.endz_label = QtWidgets.QLabel('%s:' % _("End move Z"))
  2331. self.endz_label.setToolTip(
  2332. _("Height of the tool after\n"
  2333. "the last move at the end of the job.")
  2334. )
  2335. self.endz_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2336. self.endz_entry.set_precision(self.decimals)
  2337. if machinist_setting == 0:
  2338. self.endz_entry.set_range(0.0, 9999.9999)
  2339. else:
  2340. self.endz_entry.set_range(-9999.9999, 9999.9999)
  2341. self.endz_entry.setSingleStep(0.1)
  2342. self.grid3.addWidget(self.endz_label, 11, 0)
  2343. self.grid3.addWidget(self.endz_entry, 11, 1)
  2344. # End Move X,Y
  2345. endmove_xy_label = QtWidgets.QLabel('%s:' % _('End move X,Y'))
  2346. endmove_xy_label.setToolTip(
  2347. _("End move X,Y position. In format (x,y).\n"
  2348. "If no value is entered then there is no move\n"
  2349. "on X,Y plane at the end of the job.")
  2350. )
  2351. self.endxy_entry = NumericalEvalEntry(border_color='#0069A9')
  2352. self.endxy_entry.setPlaceholderText(_("X,Y coordinates"))
  2353. self.grid3.addWidget(endmove_xy_label, 12, 0)
  2354. self.grid3.addWidget(self.endxy_entry, 12, 1)
  2355. # Probe depth
  2356. self.pdepth_label = QtWidgets.QLabel('%s:' % _("Probe Z depth"))
  2357. self.pdepth_label.setToolTip(
  2358. _("The maximum depth that the probe is allowed\n"
  2359. "to probe. Negative value, in current units.")
  2360. )
  2361. self.pdepth_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2362. self.pdepth_entry.set_precision(self.decimals)
  2363. self.pdepth_entry.set_range(-9999.9999, 9999.9999)
  2364. self.pdepth_entry.setSingleStep(0.1)
  2365. self.pdepth_entry.setObjectName("e_depth_probe")
  2366. self.grid3.addWidget(self.pdepth_label, 13, 0)
  2367. self.grid3.addWidget(self.pdepth_entry, 13, 1)
  2368. self.pdepth_label.hide()
  2369. self.pdepth_entry.setVisible(False)
  2370. # Probe feedrate
  2371. self.feedrate_probe_label = QtWidgets.QLabel('%s:' % _("Feedrate Probe"))
  2372. self.feedrate_probe_label.setToolTip(
  2373. _("The feedrate used while the probe is probing.")
  2374. )
  2375. self.feedrate_probe_entry = FCDoubleSpinner(callback=self.confirmation_message)
  2376. self.feedrate_probe_entry.set_precision(self.decimals)
  2377. self.feedrate_probe_entry.set_range(0.0, 9999.9999)
  2378. self.feedrate_probe_entry.setSingleStep(0.1)
  2379. self.feedrate_probe_entry.setObjectName("e_fr_probe")
  2380. self.grid3.addWidget(self.feedrate_probe_label, 14, 0)
  2381. self.grid3.addWidget(self.feedrate_probe_entry, 14, 1)
  2382. self.feedrate_probe_label.hide()
  2383. self.feedrate_probe_entry.setVisible(False)
  2384. # Preprocessor Excellon selection
  2385. pp_excellon_label = QtWidgets.QLabel('%s:' % _("Preprocessor"))
  2386. pp_excellon_label.setToolTip(
  2387. _("The preprocessor JSON file that dictates\n"
  2388. "Gcode output for Excellon Objects.")
  2389. )
  2390. self.pp_excellon_name_cb = FCComboBox()
  2391. self.pp_excellon_name_cb.setFocusPolicy(QtCore.Qt.StrongFocus)
  2392. self.grid3.addWidget(pp_excellon_label, 15, 0)
  2393. self.grid3.addWidget(self.pp_excellon_name_cb, 15, 1)
  2394. # ------------------------------------------------------------------------------------------------------------
  2395. # ------------------------- EXCLUSION AREAS ------------------------------------------------------------------
  2396. # ------------------------------------------------------------------------------------------------------------
  2397. # Exclusion Areas
  2398. self.exclusion_cb = FCCheckBox('%s' % _("Add exclusion areas"))
  2399. self.exclusion_cb.setToolTip(
  2400. _(
  2401. "Include exclusion areas.\n"
  2402. "In those areas the travel of the tools\n"
  2403. "is forbidden."
  2404. )
  2405. )
  2406. self.grid3.addWidget(self.exclusion_cb, 20, 0, 1, 2)
  2407. self.exclusion_frame = QtWidgets.QFrame()
  2408. self.exclusion_frame.setContentsMargins(0, 0, 0, 0)
  2409. self.grid3.addWidget(self.exclusion_frame, 22, 0, 1, 2)
  2410. self.exclusion_box = QtWidgets.QVBoxLayout()
  2411. self.exclusion_box.setContentsMargins(0, 0, 0, 0)
  2412. self.exclusion_frame.setLayout(self.exclusion_box)
  2413. self.exclusion_table = FCTable()
  2414. self.exclusion_box.addWidget(self.exclusion_table)
  2415. self.exclusion_table.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
  2416. self.exclusion_table.setColumnCount(4)
  2417. self.exclusion_table.setColumnWidth(0, 20)
  2418. self.exclusion_table.setHorizontalHeaderLabels(['#', _('Object'), _('Strategy'), _('Over Z')])
  2419. self.exclusion_table.horizontalHeaderItem(0).setToolTip(_("This is the Area ID."))
  2420. self.exclusion_table.horizontalHeaderItem(1).setToolTip(
  2421. _("Type of the object where the exclusion area was added."))
  2422. self.exclusion_table.horizontalHeaderItem(2).setToolTip(
  2423. _("The strategy used for exclusion area. Go around the exclusion areas or over it."))
  2424. self.exclusion_table.horizontalHeaderItem(3).setToolTip(
  2425. _("If the strategy is to go over the area then this is the height at which the tool will go to avoid the "
  2426. "exclusion area."))
  2427. self.exclusion_table.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  2428. grid_a1 = QtWidgets.QGridLayout()
  2429. grid_a1.setColumnStretch(0, 0)
  2430. grid_a1.setColumnStretch(1, 1)
  2431. self.exclusion_box.addLayout(grid_a1)
  2432. # Chose Strategy
  2433. self.strategy_label = FCLabel('%s:' % _("Strategy"))
  2434. self.strategy_label.setToolTip(_("The strategy followed when encountering an exclusion area.\n"
  2435. "Can be:\n"
  2436. "- Over -> when encountering the area, the tool will go to a set height\n"
  2437. "- Around -> will avoid the exclusion area by going around the area"))
  2438. self.strategy_radio = RadioSet([{'label': _('Over'), 'value': 'over'},
  2439. {'label': _('Around'), 'value': 'around'}])
  2440. grid_a1.addWidget(self.strategy_label, 1, 0)
  2441. grid_a1.addWidget(self.strategy_radio, 1, 1)
  2442. # Over Z
  2443. self.over_z_label = FCLabel('%s:' % _("Over Z"))
  2444. self.over_z_label.setToolTip(_("The height Z to which the tool will rise in order to avoid\n"
  2445. "an interdiction area."))
  2446. self.over_z_entry = FCDoubleSpinner()
  2447. self.over_z_entry.set_range(0.000, 9999.9999)
  2448. self.over_z_entry.set_precision(self.decimals)
  2449. grid_a1.addWidget(self.over_z_label, 2, 0)
  2450. grid_a1.addWidget(self.over_z_entry, 2, 1)
  2451. # Button Add Area
  2452. self.add_area_button = QtWidgets.QPushButton(_('Add area:'))
  2453. self.add_area_button.setToolTip(_("Add an Exclusion Area."))
  2454. # Area Selection shape
  2455. self.area_shape_radio = RadioSet([{'label': _("Square"), 'value': 'square'},
  2456. {'label': _("Polygon"), 'value': 'polygon'}])
  2457. self.area_shape_radio.setToolTip(
  2458. _("The kind of selection shape used for area selection.")
  2459. )
  2460. grid_a1.addWidget(self.add_area_button, 4, 0)
  2461. grid_a1.addWidget(self.area_shape_radio, 4, 1)
  2462. h_lay_1 = QtWidgets.QHBoxLayout()
  2463. self.exclusion_box.addLayout(h_lay_1)
  2464. # Button Delete All Areas
  2465. self.delete_area_button = QtWidgets.QPushButton(_('Delete All'))
  2466. self.delete_area_button.setToolTip(_("Delete all exclusion areas."))
  2467. # Button Delete Selected Areas
  2468. self.delete_sel_area_button = QtWidgets.QPushButton(_('Delete Selected'))
  2469. self.delete_sel_area_button.setToolTip(_("Delete all exclusion areas that are selected in the table."))
  2470. h_lay_1.addWidget(self.delete_area_button)
  2471. h_lay_1.addWidget(self.delete_sel_area_button)
  2472. self.ois_exclusion_exc = OptionalHideInputSection(self.exclusion_cb, [self.exclusion_frame])
  2473. # -------------------------- EXCLUSION AREAS END -------------------------------------------------------------
  2474. # ------------------------------------------------------------------------------------------------------------
  2475. separator_line = QtWidgets.QFrame()
  2476. separator_line.setFrameShape(QtWidgets.QFrame.HLine)
  2477. separator_line.setFrameShadow(QtWidgets.QFrame.Sunken)
  2478. self.grid3.addWidget(separator_line, 25, 0, 1, 2)
  2479. # #################################################################
  2480. # ################# GRID LAYOUT 6 ###############################
  2481. # #################################################################
  2482. self.grid4 = QtWidgets.QGridLayout()
  2483. self.grid4.setColumnStretch(0, 0)
  2484. self.grid4.setColumnStretch(1, 1)
  2485. self.tools_box.addLayout(self.grid4)
  2486. self.generate_cnc_button = QtWidgets.QPushButton(_('Generate CNCJob object'))
  2487. self.generate_cnc_button.setToolTip(
  2488. _("Generate the CNC Job.\n"
  2489. "If milling then an additional Geometry object will be created.\n"
  2490. "Add / Select at least one tool in the tool-table.\n"
  2491. "Click the # header to select all, or Ctrl + LMB\n"
  2492. "for custom selection of tools.")
  2493. )
  2494. self.generate_cnc_button.setStyleSheet("""
  2495. QPushButton
  2496. {
  2497. font-weight: bold;
  2498. }
  2499. """)
  2500. self.grid4.addWidget(self.generate_cnc_button, 3, 0, 1, 3)
  2501. self.tools_box.addStretch()
  2502. # ## Reset Tool
  2503. self.reset_button = QtWidgets.QPushButton(_("Reset Tool"))
  2504. self.reset_button.setToolTip(
  2505. _("Will reset the tool parameters.")
  2506. )
  2507. self.reset_button.setStyleSheet("""
  2508. QPushButton
  2509. {
  2510. font-weight: bold;
  2511. }
  2512. """)
  2513. self.tools_box.addWidget(self.reset_button)
  2514. # ############################ FINSIHED GUI ###################################
  2515. # #############################################################################
  2516. def confirmation_message(self, accepted, minval, maxval):
  2517. if accepted is False:
  2518. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%.*f, %.*f]' % (_("Edited value is out of range"),
  2519. self.decimals,
  2520. minval,
  2521. self.decimals,
  2522. maxval), False)
  2523. else:
  2524. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  2525. def confirmation_message_int(self, accepted, minval, maxval):
  2526. if accepted is False:
  2527. self.app.inform[str, bool].emit('[WARNING_NOTCL] %s: [%d, %d]' %
  2528. (_("Edited value is out of range"), minval, maxval), False)
  2529. else:
  2530. self.app.inform[str, bool].emit('[success] %s' % _("Edited value is within limits."), False)
  2531. def distance(pt1, pt2):
  2532. return np.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  2533. def distance_euclidian(x1, y1, x2, y2):
  2534. return np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
  2535. class AttrDict(dict):
  2536. def __init__(self, *args, **kwargs):
  2537. super(AttrDict, self).__init__(*args, **kwargs)
  2538. self.__dict__ = self