FlatCAMObj.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. from cStringIO import StringIO
  9. from PyQt4 import QtCore
  10. from copy import copy
  11. from ObjectUI import *
  12. import FlatCAMApp
  13. import inspect # TODO: For debugging only.
  14. from camlib import *
  15. from FlatCAMCommon import LoudDict
  16. from FlatCAMDraw import FlatCAMDraw
  17. ########################################
  18. ## FlatCAMObj ##
  19. ########################################
  20. class FlatCAMObj(QtCore.QObject):
  21. """
  22. Base type of objects handled in FlatCAM. These become interactive
  23. in the GUI, can be plotted, and their options can be modified
  24. by the user in their respective forms.
  25. """
  26. # Instance of the application to which these are related.
  27. # The app should set this value.
  28. app = None
  29. option_changed = QtCore.pyqtSignal(QtCore.QObject, str)
  30. def __init__(self, name):
  31. """
  32. Constructor.
  33. :param name: Name of the object given by the user.
  34. :return: FlatCAMObj
  35. """
  36. QtCore.QObject.__init__(self)
  37. # View
  38. self.ui = None
  39. self.options = LoudDict(name=name)
  40. self.options.set_change_callback(self.on_options_change)
  41. self.form_fields = {}
  42. self.axes = None # Matplotlib axes
  43. self.kind = None # Override with proper name
  44. self.muted_ui = False
  45. # assert isinstance(self.ui, ObjectUI)
  46. # self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  47. # self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  48. # self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  49. def from_dict(self, d):
  50. """
  51. This supersedes ``from_dict`` in derived classes. Derived classes
  52. must inherit from FlatCAMObj first, then from derivatives of Geometry.
  53. ``self.options`` is only updated, not overwritten. This ensures that
  54. options set by the app do not vanish when reading the objects
  55. from a project file.
  56. :param d: Dictionary with attributes to set.
  57. :return: None
  58. """
  59. for attr in self.ser_attrs:
  60. if attr == 'options':
  61. self.options.update(d[attr])
  62. else:
  63. setattr(self, attr, d[attr])
  64. def on_options_change(self, key):
  65. #self.emit(QtCore.SIGNAL("optionChanged()"), key)
  66. self.option_changed.emit(self, key)
  67. def set_ui(self, ui):
  68. self.ui = ui
  69. self.form_fields = {"name": self.ui.name_entry}
  70. assert isinstance(self.ui, ObjectUI)
  71. self.ui.name_entry.returnPressed.connect(self.on_name_activate)
  72. self.ui.offset_button.clicked.connect(self.on_offset_button_click)
  73. self.ui.scale_button.clicked.connect(self.on_scale_button_click)
  74. def __str__(self):
  75. return "<FlatCAMObj({:12s}): {:20s}>".format(self.kind, self.options["name"])
  76. def on_name_activate(self):
  77. old_name = copy(self.options["name"])
  78. new_name = self.ui.name_entry.get_value()
  79. self.options["name"] = self.ui.name_entry.get_value()
  80. self.app.inform.emit("Name changed from %s to %s" % (old_name, new_name))
  81. def on_offset_button_click(self):
  82. self.app.report_usage("obj_on_offset_button")
  83. self.read_form()
  84. vect = self.ui.offsetvector_entry.get_value()
  85. self.offset(vect)
  86. self.plot()
  87. def on_scale_button_click(self):
  88. self.app.report_usage("obj_on_scale_button")
  89. self.read_form()
  90. factor = self.ui.scale_entry.get_value()
  91. self.scale(factor)
  92. self.plot()
  93. def setup_axes(self, figure):
  94. """
  95. 1) Creates axes if they don't exist. 2) Clears axes. 3) Attaches
  96. them to figure if not part of the figure. 4) Sets transparent
  97. background. 5) Sets 1:1 scale aspect ratio.
  98. :param figure: A Matplotlib.Figure on which to add/configure axes.
  99. :type figure: matplotlib.figure.Figure
  100. :return: None
  101. :rtype: None
  102. """
  103. if self.axes is None:
  104. FlatCAMApp.App.log.debug("setup_axes(): New axes")
  105. self.axes = figure.add_axes([0.05, 0.05, 0.9, 0.9],
  106. label=self.options["name"])
  107. elif self.axes not in figure.axes:
  108. FlatCAMApp.App.log.debug("setup_axes(): Clearing and attaching axes")
  109. self.axes.cla()
  110. figure.add_axes(self.axes)
  111. else:
  112. FlatCAMApp.App.log.debug("setup_axes(): Clearing Axes")
  113. self.axes.cla()
  114. # Remove all decoration. The app's axes will have
  115. # the ticks and grid.
  116. self.axes.set_frame_on(False) # No frame
  117. self.axes.set_xticks([]) # No tick
  118. self.axes.set_yticks([]) # No ticks
  119. self.axes.patch.set_visible(False) # No background
  120. self.axes.set_aspect(1)
  121. def to_form(self):
  122. """
  123. Copies options to the UI form.
  124. :return: None
  125. """
  126. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.to_form()")
  127. for option in self.options:
  128. try:
  129. self.set_form_item(option)
  130. except:
  131. self.app.log.warning("Unexpected error:", sys.exc_info())
  132. def read_form(self):
  133. """
  134. Reads form into ``self.options``.
  135. :return: None
  136. :rtype: None
  137. """
  138. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.read_form()")
  139. for option in self.options:
  140. try:
  141. self.read_form_item(option)
  142. except:
  143. self.app.log.warning("Unexpected error:", sys.exc_info())
  144. def build_ui(self):
  145. """
  146. Sets up the UI/form for this object. Show the UI
  147. in the App.
  148. :return: None
  149. :rtype: None
  150. """
  151. self.muted_ui = True
  152. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + "--> FlatCAMObj.build_ui()")
  153. # Remove anything else in the box
  154. # box_children = self.app.ui.notebook.selected_contents.get_children()
  155. # for child in box_children:
  156. # self.app.ui.notebook.selected_contents.remove(child)
  157. # while self.app.ui.selected_layout.count():
  158. # self.app.ui.selected_layout.takeAt(0)
  159. # Put in the UI
  160. # box_selected.pack_start(sw, True, True, 0)
  161. # self.app.ui.notebook.selected_contents.add(self.ui)
  162. # self.app.ui.selected_layout.addWidget(self.ui)
  163. try:
  164. self.app.ui.selected_scroll_area.takeWidget()
  165. except:
  166. self.app.log.debug("Nothing to remove")
  167. self.app.ui.selected_scroll_area.setWidget(self.ui)
  168. self.to_form()
  169. self.muted_ui = False
  170. def set_form_item(self, option):
  171. """
  172. Copies the specified option to the UI form.
  173. :param option: Name of the option (Key in ``self.options``).
  174. :type option: str
  175. :return: None
  176. """
  177. try:
  178. self.form_fields[option].set_value(self.options[option])
  179. except KeyError:
  180. self.app.log.warn("Tried to set an option or field that does not exist: %s" % option)
  181. def read_form_item(self, option):
  182. """
  183. Reads the specified option from the UI form into ``self.options``.
  184. :param option: Name of the option.
  185. :type option: str
  186. :return: None
  187. """
  188. try:
  189. self.options[option] = self.form_fields[option].get_value()
  190. except KeyError:
  191. self.app.log.warning("Failed to read option from field: %s" % option)
  192. # #try read field only when option have equivalent in form_fields
  193. # if option in self.form_fields:
  194. # option_type=type(self.options[option])
  195. # try:
  196. # value=self.form_fields[option].get_value()
  197. # #catch per option as it was ignored anyway, also when syntax error (probably uninitialized field),don't read either.
  198. # except (KeyError,SyntaxError):
  199. # self.app.log.warning("Failed to read option from field: %s" % option)
  200. # else:
  201. # self.app.log.warning("Form fied does not exists: %s" % option)
  202. def plot(self):
  203. """
  204. Plot this object (Extend this method to implement the actual plotting).
  205. Axes get created, appended to canvas and cleared before plotting.
  206. Call this in descendants before doing the plotting.
  207. :return: Whether to continue plotting or not depending on the "plot" option.
  208. :rtype: bool
  209. """
  210. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMObj.plot()")
  211. # Axes must exist and be attached to canvas.
  212. if self.axes is None or self.axes not in self.app.plotcanvas.figure.axes:
  213. self.axes = self.app.plotcanvas.new_axes(self.options['name'])
  214. if not self.options["plot"]:
  215. self.axes.cla()
  216. self.app.plotcanvas.auto_adjust_axes()
  217. return False
  218. # Clear axes or we will plot on top of them.
  219. self.axes.cla() # TODO: Thread safe?
  220. return True
  221. def serialize(self):
  222. """
  223. Returns a representation of the object as a dictionary so
  224. it can be later exported as JSON. Override this method.
  225. :return: Dictionary representing the object
  226. :rtype: dict
  227. """
  228. return
  229. def deserialize(self, obj_dict):
  230. """
  231. Re-builds an object from its serialized version.
  232. :param obj_dict: Dictionary representing a FlatCAMObj
  233. :type obj_dict: dict
  234. :return: None
  235. """
  236. return
  237. class FlatCAMGerber(FlatCAMObj, Gerber):
  238. """
  239. Represents Gerber code.
  240. """
  241. ui_type = GerberObjectUI
  242. def __init__(self, name):
  243. Gerber.__init__(self)
  244. FlatCAMObj.__init__(self, name)
  245. self.kind = "gerber"
  246. # The 'name' is already in self.options from FlatCAMObj
  247. # Automatically updates the UI
  248. self.options.update({
  249. "plot": True,
  250. "multicolored": False,
  251. "solid": False,
  252. "isotooldia": 0.016,
  253. "isopasses": 1,
  254. "isooverlap": 0.15,
  255. "combine_passes": True,
  256. "cutouttooldia": 0.07,
  257. "cutoutmargin": 0.2,
  258. "cutoutgapsize": 0.15,
  259. "gaps": "tb",
  260. "noncoppermargin": 0.0,
  261. "noncopperrounded": False,
  262. "bboxmargin": 0.0,
  263. "bboxrounded": False
  264. })
  265. # Attributes to be included in serialization
  266. # Always append to it because it carries contents
  267. # from predecessors.
  268. self.ser_attrs += ['options', 'kind']
  269. # assert isinstance(self.ui, GerberObjectUI)
  270. # self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  271. # self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  272. # self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  273. # self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  274. # self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
  275. # self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  276. # self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  277. def set_ui(self, ui):
  278. """
  279. Maps options with GUI inputs.
  280. Connects GUI events to methods.
  281. :param ui: GUI object.
  282. :type ui: GerberObjectUI
  283. :return: None
  284. """
  285. FlatCAMObj.set_ui(self, ui)
  286. FlatCAMApp.App.log.debug("FlatCAMGerber.set_ui()")
  287. self.form_fields.update({
  288. "plot": self.ui.plot_cb,
  289. "multicolored": self.ui.multicolored_cb,
  290. "solid": self.ui.solid_cb,
  291. "isotooldia": self.ui.iso_tool_dia_entry,
  292. "isopasses": self.ui.iso_width_entry,
  293. "isooverlap": self.ui.iso_overlap_entry,
  294. "combine_passes": self.ui.combine_passes_cb,
  295. "cutouttooldia": self.ui.cutout_tooldia_entry,
  296. "cutoutmargin": self.ui.cutout_margin_entry,
  297. "cutoutgapsize": self.ui.cutout_gap_entry,
  298. "gaps": self.ui.gaps_radio,
  299. "noncoppermargin": self.ui.noncopper_margin_entry,
  300. "noncopperrounded": self.ui.noncopper_rounded_cb,
  301. "bboxmargin": self.ui.bbmargin_entry,
  302. "bboxrounded": self.ui.bbrounded_cb
  303. })
  304. assert isinstance(self.ui, GerberObjectUI)
  305. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  306. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  307. self.ui.multicolored_cb.stateChanged.connect(self.on_multicolored_cb_click)
  308. self.ui.generate_iso_button.clicked.connect(self.on_iso_button_click)
  309. self.ui.generate_cutout_button.clicked.connect(self.on_generatecutout_button_click)
  310. self.ui.generate_bb_button.clicked.connect(self.on_generatebb_button_click)
  311. self.ui.generate_noncopper_button.clicked.connect(self.on_generatenoncopper_button_click)
  312. def on_generatenoncopper_button_click(self, *args):
  313. self.app.report_usage("gerber_on_generatenoncopper_button")
  314. self.read_form()
  315. name = self.options["name"] + "_noncopper"
  316. def geo_init(geo_obj, app_obj):
  317. assert isinstance(geo_obj, FlatCAMGeometry)
  318. bounding_box = self.solid_geometry.envelope.buffer(self.options["noncoppermargin"])
  319. if not self.options["noncopperrounded"]:
  320. bounding_box = bounding_box.envelope
  321. non_copper = bounding_box.difference(self.solid_geometry)
  322. geo_obj.solid_geometry = non_copper
  323. # TODO: Check for None
  324. self.app.new_object("geometry", name, geo_init)
  325. def on_generatebb_button_click(self, *args):
  326. self.app.report_usage("gerber_on_generatebb_button")
  327. self.read_form()
  328. name = self.options["name"] + "_bbox"
  329. def geo_init(geo_obj, app_obj):
  330. assert isinstance(geo_obj, FlatCAMGeometry)
  331. # Bounding box with rounded corners
  332. bounding_box = self.solid_geometry.envelope.buffer(self.options["bboxmargin"])
  333. if not self.options["bboxrounded"]: # Remove rounded corners
  334. bounding_box = bounding_box.envelope
  335. geo_obj.solid_geometry = bounding_box
  336. self.app.new_object("geometry", name, geo_init)
  337. def on_generatecutout_button_click(self, *args):
  338. self.app.report_usage("gerber_on_generatecutout_button")
  339. self.read_form()
  340. name = self.options["name"] + "_cutout"
  341. def geo_init(geo_obj, app_obj):
  342. margin = self.options["cutoutmargin"] + self.options["cutouttooldia"]/2
  343. gap_size = self.options["cutoutgapsize"] + self.options["cutouttooldia"]
  344. minx, miny, maxx, maxy = self.bounds()
  345. minx -= margin
  346. maxx += margin
  347. miny -= margin
  348. maxy += margin
  349. midx = 0.5 * (minx + maxx)
  350. midy = 0.5 * (miny + maxy)
  351. hgap = 0.5 * gap_size
  352. pts = [[midx - hgap, maxy],
  353. [minx, maxy],
  354. [minx, midy + hgap],
  355. [minx, midy - hgap],
  356. [minx, miny],
  357. [midx - hgap, miny],
  358. [midx + hgap, miny],
  359. [maxx, miny],
  360. [maxx, midy - hgap],
  361. [maxx, midy + hgap],
  362. [maxx, maxy],
  363. [midx + hgap, maxy]]
  364. cases = {"tb": [[pts[0], pts[1], pts[4], pts[5]],
  365. [pts[6], pts[7], pts[10], pts[11]]],
  366. "lr": [[pts[9], pts[10], pts[1], pts[2]],
  367. [pts[3], pts[4], pts[7], pts[8]]],
  368. "4": [[pts[0], pts[1], pts[2]],
  369. [pts[3], pts[4], pts[5]],
  370. [pts[6], pts[7], pts[8]],
  371. [pts[9], pts[10], pts[11]]]}
  372. cuts = cases[self.options['gaps']]
  373. geo_obj.solid_geometry = cascaded_union([LineString(segment) for segment in cuts])
  374. # TODO: Check for None
  375. self.app.new_object("geometry", name, geo_init)
  376. def on_iso_button_click(self, *args):
  377. self.app.report_usage("gerber_on_iso_button")
  378. self.read_form()
  379. self.isolate()
  380. def follow(self, outname=None):
  381. """
  382. Creates a geometry object "following" the gerber paths.
  383. :return: None
  384. """
  385. default_name = self.options["name"] + "_follow"
  386. follow_name = outname or default_name
  387. def follow_init(follow_obj, app_obj):
  388. # Propagate options
  389. follow_obj.options["cnctooldia"] = self.options["isotooldia"]
  390. follow_obj.solid_geometry = self.solid_geometry
  391. app_obj.inform.emit("Follow geometry created: %s" % follow_obj.options["name"])
  392. # TODO: Do something if this is None. Offer changing name?
  393. self.app.new_object("geometry", follow_name, follow_init)
  394. def isolate(self, dia=None, passes=None, overlap=None, outname=None, combine=None):
  395. """
  396. Creates an isolation routing geometry object in the project.
  397. :param dia: Tool diameter
  398. :param passes: Number of tool widths to cut
  399. :param overlap: Overlap between passes in fraction of tool diameter
  400. :param outname: Base name of the output object
  401. :return: None
  402. """
  403. if dia is None:
  404. dia = self.options["isotooldia"]
  405. if passes is None:
  406. passes = int(self.options["isopasses"])
  407. if overlap is None:
  408. overlap = self.options["isooverlap"]
  409. if combine is None:
  410. combine = self.options["combine_passes"]
  411. else:
  412. combine = bool(combine)
  413. base_name = self.options["name"] + "_iso"
  414. base_name = outname or base_name
  415. def generate_envelope(offset, invert):
  416. # isolation_geometry produces an envelope that is going on the left of the geometry
  417. # (the copper features). To leave the least amount of burrs on the features
  418. # the tool needs to travel on the right side of the features (this is called conventional milling)
  419. # the first pass is the one cutting all of the features, so it needs to be reversed
  420. # the other passes overlap preceding ones and cut the left over copper. It is better for them
  421. # to cut on the right side of the left over copper i.e on the left side of the features.
  422. geom = self.isolation_geometry(offset)
  423. if invert:
  424. if type(geom) is MultiPolygon:
  425. pl = []
  426. for p in geom:
  427. pl.append(Polygon(p.exterior.coords[::-1], p.interiors))
  428. geom = MultiPolygon(pl)
  429. elif type(geom) is Polygon:
  430. geom = Polygon(geom.exterior.coords[::-1], geom.interiors)
  431. else:
  432. raise str("Unexpected Geometry")
  433. return geom
  434. if combine:
  435. iso_name = base_name
  436. # TODO: This is ugly. Create way to pass data into init function.
  437. def iso_init(geo_obj, app_obj):
  438. # Propagate options
  439. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  440. geo_obj.solid_geometry = []
  441. for i in range(passes):
  442. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  443. geom = generate_envelope (offset, i == 0)
  444. geo_obj.solid_geometry.append(geom)
  445. app_obj.inform.emit("Isolation geometry created: %s" % geo_obj.options["name"])
  446. # TODO: Do something if this is None. Offer changing name?
  447. self.app.new_object("geometry", iso_name, iso_init)
  448. else:
  449. for i in range(passes):
  450. offset = (2 * i + 1) / 2.0 * dia - i * overlap * dia
  451. if passes > 1:
  452. iso_name = base_name + str(i + 1)
  453. else:
  454. iso_name = base_name
  455. # TODO: This is ugly. Create way to pass data into init function.
  456. def iso_init(geo_obj, app_obj):
  457. # Propagate options
  458. geo_obj.options["cnctooldia"] = self.options["isotooldia"]
  459. geo_obj.solid_geometry = generate_envelope (offset, i == 0)
  460. app_obj.inform.emit("Isolation geometry created: %s" % geo_obj.options["name"])
  461. # TODO: Do something if this is None. Offer changing name?
  462. self.app.new_object("geometry", iso_name, iso_init)
  463. def on_plot_cb_click(self, *args):
  464. if self.muted_ui:
  465. return
  466. self.read_form_item('plot')
  467. self.plot()
  468. def on_solid_cb_click(self, *args):
  469. if self.muted_ui:
  470. return
  471. self.read_form_item('solid')
  472. self.plot()
  473. def on_multicolored_cb_click(self, *args):
  474. if self.muted_ui:
  475. return
  476. self.read_form_item('multicolored')
  477. self.plot()
  478. def convert_units(self, units):
  479. """
  480. Converts the units of the object by scaling dimensions in all geometry
  481. and options.
  482. :param units: Units to which to convert the object: "IN" or "MM".
  483. :type units: str
  484. :return: None
  485. :rtype: None
  486. """
  487. factor = Gerber.convert_units(self, units)
  488. self.options['isotooldia'] *= factor
  489. self.options['cutoutmargin'] *= factor
  490. self.options['cutoutgapsize'] *= factor
  491. self.options['noncoppermargin'] *= factor
  492. self.options['bboxmargin'] *= factor
  493. def plot(self):
  494. FlatCAMApp.App.log.debug(str(inspect.stack()[1][3]) + " --> FlatCAMGerber.plot()")
  495. # Does all the required setup and returns False
  496. # if the 'ptint' option is set to False.
  497. if not FlatCAMObj.plot(self):
  498. return
  499. geometry = self.solid_geometry
  500. # Make sure geometry is iterable.
  501. try:
  502. _ = iter(geometry)
  503. except TypeError:
  504. geometry = [geometry]
  505. if self.options["multicolored"]:
  506. linespec = '-'
  507. else:
  508. linespec = 'k-'
  509. if self.options["solid"]:
  510. for poly in geometry:
  511. # TODO: Too many things hardcoded.
  512. try:
  513. patch = PolygonPatch(poly,
  514. facecolor="#BBF268",
  515. edgecolor="#006E20",
  516. alpha=0.75,
  517. zorder=2)
  518. self.axes.add_patch(patch)
  519. except AssertionError:
  520. FlatCAMApp.App.log.warning("A geometry component was not a polygon:")
  521. FlatCAMApp.App.log.warning(str(poly))
  522. else:
  523. for poly in geometry:
  524. x, y = poly.exterior.xy
  525. self.axes.plot(x, y, linespec)
  526. for ints in poly.interiors:
  527. x, y = ints.coords.xy
  528. self.axes.plot(x, y, linespec)
  529. self.app.plotcanvas.auto_adjust_axes()
  530. def serialize(self):
  531. return {
  532. "options": self.options,
  533. "kind": self.kind
  534. }
  535. class FlatCAMExcellon(FlatCAMObj, Excellon):
  536. """
  537. Represents Excellon/Drill code.
  538. """
  539. ui_type = ExcellonObjectUI
  540. def __init__(self, name):
  541. Excellon.__init__(self)
  542. FlatCAMObj.__init__(self, name)
  543. self.kind = "excellon"
  544. self.options.update({
  545. "plot": True,
  546. "solid": False,
  547. "drillz": -0.1,
  548. "travelz": 0.1,
  549. "feedrate": 5.0,
  550. # "toolselection": ""
  551. "tooldia": 0.1,
  552. "toolchange": False,
  553. "toolchangez": 1.0,
  554. "spindlespeed": None
  555. })
  556. # TODO: Document this.
  557. self.tool_cbs = {}
  558. # Attributes to be included in serialization
  559. # Always append to it because it carries contents
  560. # from predecessors.
  561. self.ser_attrs += ['options', 'kind']
  562. @staticmethod
  563. def merge(exc_list, exc_final):
  564. """
  565. Merge excellons in exc_list into exc_final.
  566. Options are allways copied from source .
  567. Tools are also merged, if name for tool is same and size differs, then as name is used next available number from both lists
  568. if only one object is specified in exc_list then this acts as copy only
  569. :param exc_list: List or one object of FlatCAMExcellon Objects to join.
  570. :param exc_final: Destination FlatCAMExcellon object.
  571. :return: None
  572. """
  573. if type(exc_list) is not list:
  574. exc_list_real= list()
  575. exc_list_real.append(exc_list)
  576. else:
  577. exc_list_real=exc_list
  578. for exc in exc_list_real:
  579. # Expand lists
  580. if type(exc) is list:
  581. FlatCAMExcellon.merge(exc, exc_final)
  582. # If not list, merge excellons
  583. else:
  584. # TODO: I realize forms does not save values into options , when object is deselected
  585. # leave this here for future use
  586. # this reinitialize options based on forms, all steps may not be necessary
  587. # exc.app.collection.set_active(exc.options['name'])
  588. # exc.to_form()
  589. # exc.read_form()
  590. for option in exc.options:
  591. if option is not 'name':
  592. try:
  593. exc_final.options[option] = exc.options[option]
  594. except:
  595. exc.app.log.warning("Failed to copy option.",option)
  596. #deep copy of all drills,to avoid any references
  597. for drill in exc.drills:
  598. point = Point(drill['point'].x,drill['point'].y)
  599. exc_final.drills.append({"point": point, "tool": drill['tool']})
  600. toolsrework=dict()
  601. max_numeric_tool=0
  602. for toolname in exc.tools.iterkeys():
  603. numeric_tool=int(toolname)
  604. if numeric_tool>max_numeric_tool:
  605. max_numeric_tool=numeric_tool
  606. toolsrework[exc.tools[toolname]['C']]=toolname
  607. #exc_final as last because names from final tools will be used
  608. for toolname in exc_final.tools.iterkeys():
  609. numeric_tool=int(toolname)
  610. if numeric_tool>max_numeric_tool:
  611. max_numeric_tool=numeric_tool
  612. toolsrework[exc_final.tools[toolname]['C']]=toolname
  613. for toolvalues in toolsrework.iterkeys():
  614. if toolsrework[toolvalues] in exc_final.tools:
  615. if exc_final.tools[toolsrework[toolvalues]]!={"C": toolvalues}:
  616. exc_final.tools[str(max_numeric_tool+1)]={"C": toolvalues}
  617. else:
  618. exc_final.tools[toolsrework[toolvalues]]={"C": toolvalues}
  619. #this value was not co
  620. exc_final.zeros=exc.zeros
  621. exc_final.create_geometry()
  622. def build_ui(self):
  623. FlatCAMObj.build_ui(self)
  624. # Populate tool list
  625. n = len(self.tools)
  626. self.ui.tools_table.setColumnCount(3)
  627. self.ui.tools_table.setHorizontalHeaderLabels(['#', 'Diameter', 'Count'])
  628. self.ui.tools_table.setRowCount(n)
  629. self.ui.tools_table.setSortingEnabled(False)
  630. i = 0
  631. for tool in self.tools:
  632. drill_cnt = 0 # variable to store the nr of drills per tool
  633. # Find no of drills for the current tool
  634. for drill in self.drills:
  635. if drill.get('tool') == tool:
  636. drill_cnt += 1
  637. id = QtGui.QTableWidgetItem(tool)
  638. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  639. self.ui.tools_table.setItem(i, 0, id) # Tool name/id
  640. dia = QtGui.QTableWidgetItem(str(self.tools[tool]['C']))
  641. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  642. drill_count = QtGui.QTableWidgetItem('%d' % drill_cnt)
  643. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  644. self.ui.tools_table.setItem(i, 1, dia) # Diameter
  645. self.ui.tools_table.setItem(i, 2, drill_count) # Number of drills per tool
  646. i += 1
  647. # sort the tool diameter column
  648. self.ui.tools_table.sortItems(1)
  649. # all the tools are selected by default
  650. self.ui.tools_table.selectColumn(0)
  651. self.ui.tools_table.resizeColumnsToContents()
  652. self.ui.tools_table.resizeRowsToContents()
  653. horizontal_header = self.ui.tools_table.horizontalHeader()
  654. horizontal_header.setResizeMode(0, QtGui.QHeaderView.ResizeToContents)
  655. horizontal_header.setResizeMode(1, QtGui.QHeaderView.Stretch)
  656. horizontal_header.setResizeMode(2, QtGui.QHeaderView.ResizeToContents)
  657. # horizontal_header.setStretchLastSection(True)
  658. self.ui.tools_table.verticalHeader().hide()
  659. self.ui.tools_table.setSortingEnabled(True)
  660. def set_ui(self, ui):
  661. """
  662. Configures the user interface for this object.
  663. Connects options to form fields.
  664. :param ui: User interface object.
  665. :type ui: ExcellonObjectUI
  666. :return: None
  667. """
  668. FlatCAMObj.set_ui(self, ui)
  669. FlatCAMApp.App.log.debug("FlatCAMExcellon.set_ui()")
  670. self.form_fields.update({
  671. "plot": self.ui.plot_cb,
  672. "solid": self.ui.solid_cb,
  673. "drillz": self.ui.cutz_entry,
  674. "travelz": self.ui.travelz_entry,
  675. "feedrate": self.ui.feedrate_entry,
  676. "tooldia": self.ui.tooldia_entry,
  677. "toolchange": self.ui.toolchange_cb,
  678. "toolchangez": self.ui.toolchangez_entry,
  679. "spindlespeed": self.ui.spindlespeed_entry
  680. })
  681. assert isinstance(self.ui, ExcellonObjectUI), \
  682. "Expected a ExcellonObjectUI, got %s" % type(self.ui)
  683. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  684. self.ui.solid_cb.stateChanged.connect(self.on_solid_cb_click)
  685. self.ui.generate_cnc_button.clicked.connect(self.on_create_cncjob_button_click)
  686. self.ui.generate_milling_button.clicked.connect(self.on_generate_milling_button_click)
  687. def get_selected_tools_list(self):
  688. """
  689. Returns the keys to the self.tools dictionary corresponding
  690. to the selections on the tool list in the GUI.
  691. :return: List of tools.
  692. :rtype: list
  693. """
  694. return [str(x.text()) for x in self.ui.tools_table.selectedItems()]
  695. def generate_milling(self, tools=None, outname=None, tooldia=None):
  696. """
  697. Note: This method is a good template for generic operations as
  698. it takes it's options from parameters or otherwise from the
  699. object's options and returns a (success, msg) tuple as feedback
  700. for shell operations.
  701. :return: Success/failure condition tuple (bool, str).
  702. :rtype: tuple
  703. """
  704. # Get the tools from the list. These are keys
  705. # to self.tools
  706. if tools is None:
  707. tools = self.get_selected_tools_list()
  708. if outname is None:
  709. outname = self.options["name"] + "_mill"
  710. if tooldia is None:
  711. tooldia = self.options["tooldia"]
  712. # Sort tools by diameter. items() -> [('name', diameter), ...]
  713. sorted_tools = sorted(self.tools.items(), key=lambda tl: tl[1])
  714. if tools == "all":
  715. tools = [i[0] for i in sorted_tools] # List if ordered tool names.
  716. log.debug("Tools 'all' and sorted are: %s" % str(tools))
  717. if len(tools) == 0:
  718. self.app.inform.emit("Please select one or more tools from the list and try again.")
  719. return False, "Error: No tools."
  720. for tool in tools:
  721. if self.tools[tool]["C"] < tooldia:
  722. self.app.inform.emit("[warning] Milling tool is larger than hole size. Cancelled.")
  723. return False, "Error: Milling tool is larger than hole."
  724. def geo_init(geo_obj, app_obj):
  725. assert isinstance(geo_obj, FlatCAMGeometry), \
  726. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  727. app_obj.progress.emit(20)
  728. geo_obj.solid_geometry = []
  729. for hole in self.drills:
  730. if hole['tool'] in tools:
  731. geo_obj.solid_geometry.append(
  732. Point(hole['point']).buffer(self.tools[hole['tool']]["C"] / 2 -
  733. tooldia / 2).exterior
  734. )
  735. def geo_thread(app_obj):
  736. app_obj.new_object("geometry", outname, geo_init)
  737. app_obj.progress.emit(100)
  738. # Create a promise with the new name
  739. self.app.collection.promise(outname)
  740. # Send to worker
  741. self.app.worker_task.emit({'fcn': geo_thread, 'params': [self.app]})
  742. return True, ""
  743. def on_generate_milling_button_click(self, *args):
  744. self.app.report_usage("excellon_on_create_milling_button")
  745. self.read_form()
  746. self.generate_milling()
  747. def on_create_cncjob_button_click(self, *args):
  748. self.app.report_usage("excellon_on_create_cncjob_button")
  749. self.read_form()
  750. # Get the tools from the list
  751. tools = self.get_selected_tools_list()
  752. if len(tools) == 0:
  753. self.app.inform.emit("Please select one or more tools from the list and try again.")
  754. return
  755. job_name = self.options["name"] + "_cnc"
  756. # Object initialization function for app.new_object()
  757. def job_init(job_obj, app_obj):
  758. assert isinstance(job_obj, FlatCAMCNCjob), \
  759. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  760. app_obj.progress.emit(20)
  761. job_obj.z_cut = self.options["drillz"]
  762. job_obj.z_move = self.options["travelz"]
  763. job_obj.feedrate = self.options["feedrate"]
  764. job_obj.spindlespeed = self.options["spindlespeed"]
  765. # There could be more than one drill size...
  766. # job_obj.tooldia = # TODO: duplicate variable!
  767. # job_obj.options["tooldia"] =
  768. tools_csv = ','.join(tools)
  769. job_obj.generate_from_excellon_by_tool(self, tools_csv,
  770. toolchange=self.options["toolchange"],
  771. toolchangez=self.options["toolchangez"])
  772. app_obj.progress.emit(50)
  773. job_obj.gcode_parse()
  774. app_obj.progress.emit(60)
  775. job_obj.create_geometry()
  776. app_obj.progress.emit(80)
  777. # To be run in separate thread
  778. def job_thread(app_obj):
  779. app_obj.new_object("cncjob", job_name, job_init)
  780. app_obj.progress.emit(100)
  781. # Create promise for the new name.
  782. self.app.collection.promise(job_name)
  783. # Send to worker
  784. # self.app.worker.add_task(job_thread, [self.app])
  785. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  786. def on_plot_cb_click(self, *args):
  787. if self.muted_ui:
  788. return
  789. self.read_form_item('plot')
  790. self.plot()
  791. def on_solid_cb_click(self, *args):
  792. if self.muted_ui:
  793. return
  794. self.read_form_item('solid')
  795. self.plot()
  796. def convert_units(self, units):
  797. factor = Excellon.convert_units(self, units)
  798. self.options['drillz'] *= factor
  799. self.options['travelz'] *= factor
  800. self.options['feedrate'] *= factor
  801. def plot(self):
  802. # Does all the required setup and returns False
  803. # if the 'ptint' option is set to False.
  804. if not FlatCAMObj.plot(self):
  805. return
  806. try:
  807. _ = iter(self.solid_geometry)
  808. except TypeError:
  809. self.solid_geometry = [self.solid_geometry]
  810. # Plot excellon (All polygons?)
  811. if self.options["solid"]:
  812. for geo in self.solid_geometry:
  813. patch = PolygonPatch(geo,
  814. facecolor="#C40000",
  815. edgecolor="#750000",
  816. alpha=0.75,
  817. zorder=3)
  818. self.axes.add_patch(patch)
  819. else:
  820. for geo in self.solid_geometry:
  821. x, y = geo.exterior.coords.xy
  822. self.axes.plot(x, y, 'r-')
  823. for ints in geo.interiors:
  824. x, y = ints.coords.xy
  825. self.axes.plot(x, y, 'g-')
  826. self.app.plotcanvas.auto_adjust_axes()
  827. class FlatCAMCNCjob(FlatCAMObj, CNCjob):
  828. """
  829. Represents G-Code.
  830. """
  831. ui_type = CNCObjectUI
  832. def __init__(self, name, units="in", kind="generic", z_move=0.1,
  833. feedrate=3.0, z_cut=-0.002, tooldia=0.0,
  834. spindlespeed=None):
  835. FlatCAMApp.App.log.debug("Creating CNCJob object...")
  836. CNCjob.__init__(self, units=units, kind=kind, z_move=z_move,
  837. feedrate=feedrate, z_cut=z_cut, tooldia=tooldia,
  838. spindlespeed=spindlespeed)
  839. FlatCAMObj.__init__(self, name)
  840. self.kind = "cncjob"
  841. self.options.update({
  842. "plot": True,
  843. "tooldia": 0.4 / 25.4, # 0.4mm in inches
  844. "append": "",
  845. "prepend": "",
  846. "dwell": False,
  847. "dwelltime": 1
  848. })
  849. # Attributes to be included in serialization
  850. # Always append to it because it carries contents
  851. # from predecessors.
  852. self.ser_attrs += ['options', 'kind']
  853. def set_ui(self, ui):
  854. FlatCAMObj.set_ui(self, ui)
  855. FlatCAMApp.App.log.debug("FlatCAMCNCJob.set_ui()")
  856. assert isinstance(self.ui, CNCObjectUI), \
  857. "Expected a CNCObjectUI, got %s" % type(self.ui)
  858. self.form_fields.update({
  859. "plot": self.ui.plot_cb,
  860. "tooldia": self.ui.tooldia_entry,
  861. "append": self.ui.append_text,
  862. "prepend": self.ui.prepend_text,
  863. "postprocess": self.ui.process_script,
  864. "dwell": self.ui.dwell_cb,
  865. "dwelltime": self.ui.dwelltime_entry
  866. })
  867. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  868. self.ui.updateplot_button.clicked.connect(self.on_updateplot_button_click)
  869. self.ui.export_gcode_button.clicked.connect(self.on_exportgcode_button_click)
  870. def on_updateplot_button_click(self, *args):
  871. """
  872. Callback for the "Updata Plot" button. Reads the form for updates
  873. and plots the object.
  874. """
  875. self.read_form()
  876. self.plot()
  877. def on_exportgcode_button_click(self, *args):
  878. self.app.report_usage("cncjob_on_exportgcode_button")
  879. self.read_form()
  880. try:
  881. filename = unicode(QtGui.QFileDialog.getSaveFileName(caption="Export G-Code ...",
  882. directory=self.app.defaults["last_folder"]))
  883. except TypeError:
  884. filename = unicode(QtGui.QFileDialog.getSaveFileName(caption="Export G-Code ..."))
  885. preamble = str(self.ui.prepend_text.get_value())
  886. postamble = str(self.ui.append_text.get_value())
  887. processor = str(self.ui.process_script.get_value())
  888. self.export_gcode(filename, preamble=preamble, postamble=postamble, processor=processor)
  889. def dwell_generator(self, lines):
  890. """
  891. Inserts "G4 P..." instructions after spindle-start
  892. instructions (M03 or M04).
  893. """
  894. log.debug("dwell_generator()...")
  895. m3m4re = re.compile(r'^\s*[mM]0[34]')
  896. g4re = re.compile(r'^\s*[gG]4\s+([\d\.\+\-e]+)')
  897. bufline = None
  898. for line in lines:
  899. # If the buffer contains a G4, yield that.
  900. # If current line is a G4, discard it.
  901. if bufline is not None:
  902. yield bufline
  903. bufline = None
  904. if not g4re.search(line):
  905. yield line
  906. continue
  907. # If start spindle, buffer a G4.
  908. if m3m4re.search(line):
  909. log.debug("Found M03/4")
  910. bufline = "G4 P{}\n".format(self.options['dwelltime'])
  911. yield line
  912. raise StopIteration
  913. def export_gcode(self, filename, preamble='', postamble='', processor=''):
  914. lines = StringIO(self.gcode)
  915. ## Post processing
  916. # Dwell?
  917. if self.options['dwell']:
  918. log.debug("Will add G04!")
  919. lines = self.dwell_generator(lines)
  920. ## Write
  921. with open(filename, 'w') as f:
  922. f.write(preamble + "\n")
  923. for line in lines:
  924. f.write(line)
  925. f.write(postamble)
  926. # Just for adding it to the recent files list.
  927. self.app.file_opened.emit("cncjob", filename)
  928. self.app.inform.emit("Saved to: " + filename)
  929. def get_gcode(self, preamble='', postamble=''):
  930. #we need this to beable get_gcode separatelly for shell command export_code
  931. return preamble + '\n' + self.gcode + "\n" + postamble
  932. def on_plot_cb_click(self, *args):
  933. if self.muted_ui:
  934. return
  935. self.read_form_item('plot')
  936. self.plot()
  937. def plot(self):
  938. # Does all the required setup and returns False
  939. # if the 'ptint' option is set to False.
  940. if not FlatCAMObj.plot(self):
  941. return
  942. self.plot2(self.axes, tooldia=self.options["tooldia"])
  943. self.app.plotcanvas.auto_adjust_axes()
  944. def convert_units(self, units):
  945. factor = CNCjob.convert_units(self, units)
  946. FlatCAMApp.App.log.debug("FlatCAMCNCjob.convert_units()")
  947. self.options["tooldia"] *= factor
  948. class FlatCAMGeometry(FlatCAMObj, Geometry):
  949. """
  950. Geometric object not associated with a specific
  951. format.
  952. """
  953. ui_type = GeometryObjectUI
  954. @staticmethod
  955. def merge(geo_list, geo_final):
  956. """
  957. Merges the geometry of objects in geo_list into
  958. the geometry of geo_final.
  959. :param geo_list: List of FlatCAMGeometry Objects to join.
  960. :param geo_final: Destination FlatCAMGeometry object.
  961. :return: None
  962. """
  963. if geo_final.solid_geometry is None:
  964. geo_final.solid_geometry = []
  965. if type(geo_final.solid_geometry) is not list:
  966. geo_final.solid_geometry = [geo_final.solid_geometry]
  967. for geo in geo_list:
  968. # Expand lists
  969. if type(geo) is list:
  970. FlatCAMGeometry.merge(geo, geo_final)
  971. # If not list, just append
  972. else:
  973. geo_final.solid_geometry.append(geo.solid_geometry)
  974. # try: # Iterable
  975. # for shape in geo.solid_geometry:
  976. # geo_final.solid_geometry.append(shape)
  977. #
  978. # except TypeError: # Non-iterable
  979. # geo_final.solid_geometry.append(geo.solid_geometry)
  980. def __init__(self, name):
  981. FlatCAMObj.__init__(self, name)
  982. Geometry.__init__(self)
  983. self.kind = "geometry"
  984. self.options.update({
  985. "plot": True,
  986. "cutz": -0.002,
  987. "travelz": 0.1,
  988. "feedrate": 5.0,
  989. "spindlespeed": None,
  990. "cnctooldia": 0.4 / 25.4,
  991. "painttooldia": 0.0625,
  992. "paintoverlap": 0.15,
  993. "paintmargin": 0.01,
  994. "paintmethod": "standard",
  995. "pathconnect": True,
  996. "paintcontour": True,
  997. "multidepth": False,
  998. "depthperpass": 0.002,
  999. "selectmethod": "single"
  1000. })
  1001. # Attributes to be included in serialization
  1002. # Always append to it because it carries contents
  1003. # from predecessors.
  1004. self.ser_attrs += ['options', 'kind']
  1005. def build_ui(self):
  1006. FlatCAMObj.build_ui(self)
  1007. def set_ui(self, ui):
  1008. FlatCAMObj.set_ui(self, ui)
  1009. FlatCAMApp.App.log.debug("FlatCAMGeometry.set_ui()")
  1010. assert isinstance(self.ui, GeometryObjectUI), \
  1011. "Expected a GeometryObjectUI, got %s" % type(self.ui)
  1012. self.form_fields.update({
  1013. "plot": self.ui.plot_cb,
  1014. "cutz": self.ui.cutz_entry,
  1015. "travelz": self.ui.travelz_entry,
  1016. "feedrate": self.ui.cncfeedrate_entry,
  1017. "spindlespeed": self.ui.cncspindlespeed_entry,
  1018. "cnctooldia": self.ui.cnctooldia_entry,
  1019. "painttooldia": self.ui.painttooldia_entry,
  1020. "paintoverlap": self.ui.paintoverlap_entry,
  1021. "paintmargin": self.ui.paintmargin_entry,
  1022. "paintmethod": self.ui.paintmethod_combo,
  1023. "pathconnect": self.ui.pathconnect_cb,
  1024. "paintcontour": self.ui.paintcontour_cb,
  1025. "multidepth": self.ui.mpass_cb,
  1026. "depthperpass": self.ui.maxdepth_entry,
  1027. "selectmethod": self.ui.selectmethod_combo
  1028. })
  1029. self.ui.plot_cb.stateChanged.connect(self.on_plot_cb_click)
  1030. self.ui.generate_cnc_button.clicked.connect(self.on_generatecnc_button_click)
  1031. self.ui.generate_paint_button.clicked.connect(self.on_paint_button_click)
  1032. def on_paint_button_click(self, *args):
  1033. self.app.report_usage("geometry_on_paint_button")
  1034. self.read_form()
  1035. tooldia = self.options["painttooldia"]
  1036. overlap = self.options["paintoverlap"]
  1037. if self.options["selectmethod"] == "all":
  1038. self.paint_poly_all(tooldia, overlap,
  1039. connect=self.options["pathconnect"],
  1040. contour=self.options["paintcontour"])
  1041. return
  1042. if self.options["selectmethod"] == "single":
  1043. self.app.inform.emit("Click inside the desired polygon.")
  1044. # To be called after clicking on the plot.
  1045. def doit(event):
  1046. self.app.inform.emit("Painting polygon...")
  1047. self.app.plotcanvas.mpl_disconnect(subscription)
  1048. point = [event.xdata, event.ydata]
  1049. self.paint_poly_single_click(point, tooldia, overlap,
  1050. connect=self.options["pathconnect"],
  1051. contour=self.options["paintcontour"])
  1052. subscription = self.app.plotcanvas.mpl_connect('button_press_event', doit)
  1053. def paint_poly_single_click(self, inside_pt, tooldia, overlap,
  1054. outname=None, connect=True, contour=True):
  1055. """
  1056. Paints a polygon selected by clicking on its interior.
  1057. Note:
  1058. * The margin is taken directly from the form.
  1059. :param inside_pt: [x, y]
  1060. :param tooldia: Diameter of the painting tool
  1061. :param overlap: Overlap of the tool between passes.
  1062. :param outname: Name of the resulting Geometry Object.
  1063. :param connect: Connect lines to avoid tool lifts.
  1064. :param contour: Paint around the edges.
  1065. :return: None
  1066. """
  1067. # Which polygon.
  1068. poly = self.find_polygon(inside_pt)
  1069. # No polygon?
  1070. if poly is None:
  1071. self.app.log.warning('No polygon found.')
  1072. self.app.inform.emit('[warning] No polygon found.')
  1073. return
  1074. proc = self.app.proc_container.new("Painting polygon.")
  1075. name = outname or self.options["name"] + "_paint"
  1076. # Initializes the new geometry object
  1077. def gen_paintarea(geo_obj, app_obj):
  1078. assert isinstance(geo_obj, FlatCAMGeometry), \
  1079. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1080. #assert isinstance(app_obj, App)
  1081. if self.options["paintmethod"] == "seed":
  1082. # Type(cp) == FlatCAMRTreeStorage | None
  1083. cp = self.clear_polygon2(poly.buffer(-self.options["paintmargin"]),
  1084. tooldia, overlap=overlap, connect=connect,
  1085. contour=contour)
  1086. elif self.options["paintmethod"] == "lines":
  1087. # Type(cp) == FlatCAMRTreeStorage | None
  1088. cp = self.clear_polygon3(poly.buffer(-self.options["paintmargin"]),
  1089. tooldia, overlap=overlap, connect=connect,
  1090. contour=contour)
  1091. else:
  1092. # Type(cp) == FlatCAMRTreeStorage | None
  1093. cp = self.clear_polygon(poly.buffer(-self.options["paintmargin"]),
  1094. tooldia, overlap=overlap, connect=connect,
  1095. contour=contour)
  1096. if cp is not None:
  1097. geo_obj.solid_geometry = list(cp.get_objects())
  1098. geo_obj.options["cnctooldia"] = tooldia
  1099. # Experimental...
  1100. print "Indexing...",
  1101. geo_obj.make_index()
  1102. print "Done"
  1103. self.app.inform.emit("Done.")
  1104. def job_thread(app_obj):
  1105. try:
  1106. app_obj.new_object("geometry", name, gen_paintarea)
  1107. except Exception as e:
  1108. proc.done()
  1109. raise e
  1110. proc.done()
  1111. self.app.inform.emit("Polygon Paint started ...")
  1112. # Promise object with the new name
  1113. self.app.collection.promise(name)
  1114. # Background
  1115. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1116. def paint_poly_all(self, tooldia, overlap, outname=None,
  1117. connect=True, contour=True):
  1118. """
  1119. Paints all polygons in this object.
  1120. :param tooldia:
  1121. :param overlap:
  1122. :param outname:
  1123. :param connect: Connect lines to avoid tool lifts.
  1124. :param contour: Paint around the edges.
  1125. :return:
  1126. """
  1127. proc = self.app.proc_container.new("Painting polygon.")
  1128. name = outname or self.options["name"] + "_paint"
  1129. # This is a recursive generator of individual Polygons.
  1130. # Note: Double check correct implementation. Might exit
  1131. # early if it finds something that is not a Polygon?
  1132. def recurse(geo):
  1133. try:
  1134. for subg in geo:
  1135. for subsubg in recurse(subg):
  1136. yield subsubg
  1137. except TypeError:
  1138. if isinstance(geo, Polygon):
  1139. yield geo
  1140. raise StopIteration
  1141. # Initializes the new geometry object
  1142. def gen_paintarea(geo_obj, app_obj):
  1143. assert isinstance(geo_obj, FlatCAMGeometry), \
  1144. "Initializer expected a FlatCAMGeometry, got %s" % type(geo_obj)
  1145. geo_obj.solid_geometry = []
  1146. for poly in recurse(self.solid_geometry):
  1147. if self.options["paintmethod"] == "seed":
  1148. # Type(cp) == FlatCAMRTreeStorage | None
  1149. cp = self.clear_polygon2(poly.buffer(-self.options["paintmargin"]),
  1150. tooldia, overlap=overlap, contour=contour,
  1151. connect=connect)
  1152. elif self.options["paintmethod"] == "lines":
  1153. # Type(cp) == FlatCAMRTreeStorage | None
  1154. cp = self.clear_polygon3(poly.buffer(-self.options["paintmargin"]),
  1155. tooldia, overlap=overlap, contour=contour,
  1156. connect=connect)
  1157. else:
  1158. # Type(cp) == FlatCAMRTreeStorage | None
  1159. cp = self.clear_polygon(poly.buffer(-self.options["paintmargin"]),
  1160. tooldia, overlap=overlap, contour=contour,
  1161. connect=connect)
  1162. if cp is not None:
  1163. geo_obj.solid_geometry += list(cp.get_objects())
  1164. geo_obj.options["cnctooldia"] = tooldia
  1165. # Experimental...
  1166. print "Indexing...",
  1167. geo_obj.make_index()
  1168. print "Done"
  1169. self.app.inform.emit("Done.")
  1170. def job_thread(app_obj):
  1171. try:
  1172. app_obj.new_object("geometry", name, gen_paintarea)
  1173. except Exception as e:
  1174. proc.done()
  1175. traceback.print_stack()
  1176. raise e
  1177. proc.done()
  1178. self.app.inform.emit("Polygon Paint started ...")
  1179. # Promise object with the new name
  1180. self.app.collection.promise(name)
  1181. # Background
  1182. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1183. def on_generatecnc_button_click(self, *args):
  1184. self.app.report_usage("geometry_on_generatecnc_button")
  1185. self.read_form()
  1186. self.generatecncjob()
  1187. def generatecncjob(self,
  1188. z_cut=None,
  1189. z_move=None,
  1190. feedrate=None,
  1191. tooldia=None,
  1192. outname=None,
  1193. spindlespeed=None,
  1194. multidepth=None,
  1195. depthperpass=None,
  1196. use_thread=True):
  1197. """
  1198. Creates a CNCJob out of this Geometry object. The actual
  1199. work is done by the target FlatCAMCNCjob object's
  1200. `generate_from_geometry_2()` method.
  1201. :param z_cut: Cut depth (negative)
  1202. :param z_move: Hight of the tool when travelling (not cutting)
  1203. :param feedrate: Feed rate while cutting
  1204. :param tooldia: Tool diameter
  1205. :param outname: Name of the new object
  1206. :param spindlespeed: Spindle speed (RPM)
  1207. :return: None
  1208. """
  1209. outname = outname if outname is not None else self.options["name"] + "_cnc"
  1210. z_cut = z_cut if z_cut is not None else self.options["cutz"]
  1211. z_move = z_move if z_move is not None else self.options["travelz"]
  1212. feedrate = feedrate if feedrate is not None else self.options["feedrate"]
  1213. tooldia = tooldia if tooldia is not None else self.options["cnctooldia"]
  1214. multidepth = multidepth if multidepth is not None else self.options["multidepth"]
  1215. depthperpass = depthperpass if depthperpass is not None else self.options["depthperpass"]
  1216. # To allow default value to be "" (optional in gui) and translate to None
  1217. # if not isinstance(spindlespeed, int):
  1218. # if isinstance(self.options["spindlespeed"], int) or \
  1219. # isinstance(self.options["spindlespeed"], float):
  1220. # spindlespeed = int(self.options["spindlespeed"])
  1221. # else:
  1222. # spindlespeed = None
  1223. if spindlespeed is None:
  1224. # int or None.
  1225. spindlespeed = self.options['spindlespeed']
  1226. # Object initialization function for app.new_object()
  1227. # RUNNING ON SEPARATE THREAD!
  1228. def job_init(job_obj, app_obj):
  1229. assert isinstance(job_obj, FlatCAMCNCjob), \
  1230. "Initializer expected a FlatCAMCNCjob, got %s" % type(job_obj)
  1231. # Propagate options
  1232. job_obj.options["tooldia"] = tooldia
  1233. app_obj.progress.emit(20)
  1234. job_obj.z_cut = z_cut
  1235. job_obj.z_move = z_move
  1236. job_obj.feedrate = feedrate
  1237. job_obj.spindlespeed = spindlespeed
  1238. app_obj.progress.emit(40)
  1239. # TODO: The tolerance should not be hard coded. Just for testing.
  1240. job_obj.generate_from_geometry_2(self,
  1241. multidepth=multidepth,
  1242. depthpercut=depthperpass,
  1243. tolerance=0.0005)
  1244. app_obj.progress.emit(50)
  1245. job_obj.gcode_parse()
  1246. app_obj.progress.emit(80)
  1247. if use_thread:
  1248. # To be run in separate thread
  1249. def job_thread(app_obj):
  1250. with self.app.proc_container.new("Generating CNC Job."):
  1251. app_obj.new_object("cncjob", outname, job_init)
  1252. app_obj.inform.emit("CNCjob created: %s" % outname)
  1253. app_obj.progress.emit(100)
  1254. # Create a promise with the name
  1255. self.app.collection.promise(outname)
  1256. # Send to worker
  1257. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  1258. else:
  1259. self.app.new_object("cncjob", outname, job_init)
  1260. def on_plot_cb_click(self, *args): # TODO: args not needed
  1261. if self.muted_ui:
  1262. return
  1263. self.read_form_item('plot')
  1264. self.plot()
  1265. def scale(self, factor):
  1266. """
  1267. Scales all geometry by a given factor.
  1268. :param factor: Factor by which to scale the object's geometry/
  1269. :type factor: float
  1270. :return: None
  1271. :rtype: None
  1272. """
  1273. if type(self.solid_geometry) == list:
  1274. self.solid_geometry = [affinity.scale(g, factor, factor, origin=(0, 0))
  1275. for g in self.solid_geometry]
  1276. else:
  1277. self.solid_geometry = affinity.scale(self.solid_geometry, factor, factor,
  1278. origin=(0, 0))
  1279. def offset(self, vect):
  1280. """
  1281. Offsets all geometry by a given vector/
  1282. :param vect: (x, y) vector by which to offset the object's geometry.
  1283. :type vect: tuple
  1284. :return: None
  1285. :rtype: None
  1286. """
  1287. dx, dy = vect
  1288. def translate_recursion(geom):
  1289. if type(geom) == list:
  1290. geoms=list()
  1291. for local_geom in geom:
  1292. geoms.append(translate_recursion(local_geom))
  1293. return geoms
  1294. else:
  1295. return affinity.translate(geom, xoff=dx, yoff=dy)
  1296. self.solid_geometry=translate_recursion(self.solid_geometry)
  1297. def convert_units(self, units):
  1298. factor = Geometry.convert_units(self, units)
  1299. self.options['cutz'] *= factor
  1300. self.options['travelz'] *= factor
  1301. self.options['feedrate'] *= factor
  1302. self.options['cnctooldia'] *= factor
  1303. self.options['painttooldia'] *= factor
  1304. self.options['paintmargin'] *= factor
  1305. return factor
  1306. def plot_element(self, element):
  1307. try:
  1308. for sub_el in element:
  1309. self.plot_element(sub_el)
  1310. except TypeError: # Element is not iterable...
  1311. if type(element) == Polygon:
  1312. x, y = element.exterior.coords.xy
  1313. self.axes.plot(x, y, 'r-')
  1314. for ints in element.interiors:
  1315. x, y = ints.coords.xy
  1316. self.axes.plot(x, y, 'r-')
  1317. return
  1318. if type(element) == LineString or type(element) == LinearRing:
  1319. x, y = element.coords.xy
  1320. self.axes.plot(x, y, 'r-')
  1321. return
  1322. FlatCAMApp.App.log.warning("Did not plot:" + str(type(element)))
  1323. def plot(self):
  1324. """
  1325. Plots the object into its axes. If None, of if the axes
  1326. are not part of the app's figure, it fetches new ones.
  1327. :return: None
  1328. """
  1329. # Does all the required setup and returns False
  1330. # if the 'ptint' option is set to False.
  1331. if not FlatCAMObj.plot(self):
  1332. return
  1333. # Make sure solid_geometry is iterable.
  1334. # TODO: This method should not modify the object !!!
  1335. # try:
  1336. # _ = iter(self.solid_geometry)
  1337. # except TypeError:
  1338. # if self.solid_geometry is None:
  1339. # self.solid_geometry = []
  1340. # else:
  1341. # self.solid_geometry = [self.solid_geometry]
  1342. #
  1343. # for geo in self.solid_geometry:
  1344. #
  1345. # if type(geo) == Polygon:
  1346. # x, y = geo.exterior.coords.xy
  1347. # self.axes.plot(x, y, 'r-')
  1348. # for ints in geo.interiors:
  1349. # x, y = ints.coords.xy
  1350. # self.axes.plot(x, y, 'r-')
  1351. # continue
  1352. #
  1353. # if type(geo) == LineString or type(geo) == LinearRing:
  1354. # x, y = geo.coords.xy
  1355. # self.axes.plot(x, y, 'r-')
  1356. # continue
  1357. #
  1358. # if type(geo) == MultiPolygon:
  1359. # for poly in geo:
  1360. # x, y = poly.exterior.coords.xy
  1361. # self.axes.plot(x, y, 'r-')
  1362. # for ints in poly.interiors:
  1363. # x, y = ints.coords.xy
  1364. # self.axes.plot(x, y, 'r-')
  1365. # continue
  1366. #
  1367. # FlatCAMApp.App.log.warning("Did not plot:", str(type(geo)))
  1368. self.plot_element(self.solid_geometry)
  1369. self.app.plotcanvas.auto_adjust_axes()