FlatCAMObj.py 54 KB

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