FlatCAMObj.py 50 KB

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