FlatCAMObj.py 60 KB

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