ParseExcellon.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506
  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 camlib import Geometry
  9. import FlatCAMApp
  10. import shapely.affinity as affinity
  11. from shapely.geometry import Point, LineString
  12. import numpy as np
  13. import re
  14. import logging
  15. import traceback
  16. from copy import deepcopy
  17. import FlatCAMTranslation as fcTranslate
  18. import gettext
  19. import builtins
  20. if '_' not in builtins.__dict__:
  21. _ = gettext.gettext
  22. log = logging.getLogger('base')
  23. class Excellon(Geometry):
  24. """
  25. Here it is done all the Excellon parsing.
  26. *ATTRIBUTES*
  27. * ``tools`` (dict): The key is the tool name and the value is
  28. a dictionary specifying the tool:
  29. ================ ====================================
  30. Key Value
  31. ================ ====================================
  32. C Diameter of the tool
  33. solid_geometry Geometry list for each tool
  34. data dictionary which holds the options for each tool
  35. Others Not supported (Ignored).
  36. ================ ====================================
  37. * ``drills`` (list): Each is a dictionary:
  38. ================ ====================================
  39. Key Value
  40. ================ ====================================
  41. point (Shapely.Point) Where to drill
  42. tool (str) A key in ``tools``
  43. ================ ====================================
  44. * ``slots`` (list): Each is a dictionary
  45. ================ ====================================
  46. Key Value
  47. ================ ====================================
  48. start (Shapely.Point) Start point of the slot
  49. stop (Shapely.Point) Stop point of the slot
  50. tool (str) A key in ``tools``
  51. ================ ====================================
  52. """
  53. defaults = {
  54. "zeros": "L",
  55. "excellon_format_upper_mm": '3',
  56. "excellon_format_lower_mm": '3',
  57. "excellon_format_upper_in": '2',
  58. "excellon_format_lower_in": '4',
  59. "excellon_units": 'INCH',
  60. "geo_steps_per_circle": '64'
  61. }
  62. def __init__(self, zeros=None, excellon_format_upper_mm=None, excellon_format_lower_mm=None,
  63. excellon_format_upper_in=None, excellon_format_lower_in=None, excellon_units=None,
  64. geo_steps_per_circle=None):
  65. """
  66. The constructor takes no parameters.
  67. :return: Excellon object.
  68. :rtype: Excellon
  69. """
  70. self.decimals = self.app.decimals
  71. if geo_steps_per_circle is None:
  72. geo_steps_per_circle = int(Excellon.defaults['geo_steps_per_circle'])
  73. self.geo_steps_per_circle = int(geo_steps_per_circle)
  74. Geometry.__init__(self, geo_steps_per_circle=int(geo_steps_per_circle))
  75. # dictionary to store tools, see above for description
  76. self.tools = {}
  77. # list to store the drills, see above for description
  78. self.drills = []
  79. # self.slots (list) to store the slots; each is a dictionary
  80. self.slots = []
  81. self.source_file = ''
  82. # it serve to flag if a start routing or a stop routing was encountered
  83. # if a stop is encounter and this flag is still 0 (so there is no stop for a previous start) issue error
  84. self.routing_flag = 1
  85. self.match_routing_start = None
  86. self.match_routing_stop = None
  87. self.num_tools = [] # List for keeping the tools sorted
  88. self.index_per_tool = {} # Dictionary to store the indexed points for each tool
  89. # ## IN|MM -> Units are inherited from Geometry
  90. self.units = self.app.defaults['units']
  91. # Trailing "T" or leading "L" (default)
  92. # self.zeros = "T"
  93. self.zeros = zeros or self.defaults["zeros"]
  94. self.zeros_found = deepcopy(self.zeros)
  95. self.units_found = deepcopy(self.units)
  96. # this will serve as a default if the Excellon file has no info regarding of tool diameters (this info may be
  97. # in another file like for PCB WIzard ECAD software
  98. self.toolless_diam = 1.0
  99. # signal that the Excellon file has no tool diameter informations and the tools have bogus (random) diameter
  100. self.diameterless = False
  101. # Excellon format
  102. self.excellon_format_upper_in = excellon_format_upper_in or self.defaults["excellon_format_upper_in"]
  103. self.excellon_format_lower_in = excellon_format_lower_in or self.defaults["excellon_format_lower_in"]
  104. self.excellon_format_upper_mm = excellon_format_upper_mm or self.defaults["excellon_format_upper_mm"]
  105. self.excellon_format_lower_mm = excellon_format_lower_mm or self.defaults["excellon_format_lower_mm"]
  106. self.excellon_units = excellon_units or self.defaults["excellon_units"]
  107. # detected Excellon format is stored here:
  108. self.excellon_format = None
  109. # Attributes to be included in serialization
  110. # Always append to it because it carries contents
  111. # from Geometry.
  112. self.ser_attrs += ['tools', 'drills', 'zeros', 'excellon_format_upper_mm', 'excellon_format_lower_mm',
  113. 'excellon_format_upper_in', 'excellon_format_lower_in', 'excellon_units', 'slots',
  114. 'source_file']
  115. # ### Patterns ####
  116. # Regex basics:
  117. # ^ - beginning
  118. # $ - end
  119. # *: 0 or more, +: 1 or more, ?: 0 or 1
  120. # M48 - Beginning of Part Program Header
  121. self.hbegin_re = re.compile(r'^M48$')
  122. # ;HEADER - Beginning of Allegro Program Header
  123. self.allegro_hbegin_re = re.compile(r'\;\s*(HEADER)')
  124. # M95 or % - End of Part Program Header
  125. # NOTE: % has different meaning in the body
  126. self.hend_re = re.compile(r'^(?:M95|%)$')
  127. # FMAT Excellon format
  128. # Ignored in the parser
  129. # self.fmat_re = re.compile(r'^FMAT,([12])$')
  130. # Uunits and possible Excellon zeros and possible Excellon format
  131. # INCH uses 6 digits
  132. # METRIC uses 5/6
  133. self.units_re = re.compile(r'^(INCH|METRIC)(?:,([TL])Z)?,?(\d*\.\d+)?.*$')
  134. # Tool definition/parameters (?= is look-ahead
  135. # NOTE: This might be an overkill!
  136. # self.toolset_re = re.compile(r'^T(0?\d|\d\d)(?=.*C(\d*\.?\d*))?' +
  137. # r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  138. # r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  139. # r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  140. self.toolset_re = re.compile(r'^T(\d+)(?=.*C,?(\d*\.?\d*))?' +
  141. r'(?=.*F(\d*\.?\d*))?(?=.*S(\d*\.?\d*))?' +
  142. r'(?=.*B(\d*\.?\d*))?(?=.*H(\d*\.?\d*))?' +
  143. r'(?=.*Z([-\+]?\d*\.?\d*))?[CFSBHT]')
  144. self.detect_gcode_re = re.compile(r'^G2([01])$')
  145. # Tool select
  146. # Can have additional data after tool number but
  147. # is ignored if present in the header.
  148. # Warning: This will match toolset_re too.
  149. # self.toolsel_re = re.compile(r'^T((?:\d\d)|(?:\d))')
  150. self.toolsel_re = re.compile(r'^T(\d+)')
  151. # Headerless toolset
  152. # self.toolset_hl_re = re.compile(r'^T(\d+)(?=.*C(\d*\.?\d*))')
  153. self.toolset_hl_re = re.compile(r'^T(\d+)(?:.?C(\d+\.?\d*))?')
  154. # Comment
  155. self.comm_re = re.compile(r'^;(.*)$')
  156. # Absolute/Incremental G90/G91
  157. self.absinc_re = re.compile(r'^G9([01])$')
  158. # Modes of operation
  159. # 1-linear, 2-circCW, 3-cirCCW, 4-vardwell, 5-Drill
  160. self.modes_re = re.compile(r'^G0([012345])')
  161. # Measuring mode
  162. # 1-metric, 2-inch
  163. self.meas_re = re.compile(r'^M7([12])$')
  164. # Coordinates
  165. # self.xcoord_re = re.compile(r'^X(\d*\.?\d*)(?:Y\d*\.?\d*)?$')
  166. # self.ycoord_re = re.compile(r'^(?:X\d*\.?\d*)?Y(\d*\.?\d*)$')
  167. coordsperiod_re_string = r'(?=.*X([-\+]?\d*\.\d*))?(?=.*Y([-\+]?\d*\.\d*))?[XY]'
  168. self.coordsperiod_re = re.compile(coordsperiod_re_string)
  169. coordsnoperiod_re_string = r'(?!.*\.)(?=.*X([-\+]?\d*))?(?=.*Y([-\+]?\d*))?[XY]'
  170. self.coordsnoperiod_re = re.compile(coordsnoperiod_re_string)
  171. # Slots parsing
  172. slots_re_string = r'^([^G]+)G85(.*)$'
  173. self.slots_re = re.compile(slots_re_string)
  174. # R - Repeat hole (# times, X offset, Y offset)
  175. self.rep_re = re.compile(r'^R(\d+)(?=.*[XY])+(?:X([-\+]?\d*\.?\d*))?(?:Y([-\+]?\d*\.?\d*))?$')
  176. # Various stop/pause commands
  177. self.stop_re = re.compile(r'^((G04)|(M09)|(M06)|(M00)|(M30))')
  178. # Allegro Excellon format support
  179. self.tool_units_re = re.compile(r'(\;\s*Holesize \d+.\s*\=\s*(\d+.\d+).*(MILS|MM))')
  180. # Altium Excellon format support
  181. # it's a comment like this: ";FILE_FORMAT=2:5"
  182. self.altium_format = re.compile(r'^;\s*(?:FILE_FORMAT)?(?:Format)?[=|:]\s*(\d+)[:|.](\d+).*$')
  183. # Parse coordinates
  184. self.leadingzeros_re = re.compile(r'^[-\+]?(0*)(\d*)')
  185. # Repeating command
  186. self.repeat_re = re.compile(r'R(\d+)')
  187. def parse_file(self, filename=None, file_obj=None):
  188. """
  189. Reads the specified file as array of lines as
  190. passes it to ``parse_lines()``.
  191. :param filename: The file to be read and parsed.
  192. :type filename: str
  193. :return: None
  194. """
  195. if file_obj:
  196. estr = file_obj
  197. else:
  198. if filename is None:
  199. return "fail"
  200. efile = open(filename, 'r')
  201. estr = efile.readlines()
  202. efile.close()
  203. try:
  204. self.parse_lines(estr)
  205. except Exception:
  206. return "fail"
  207. def parse_lines(self, elines):
  208. """
  209. Main Excellon parser.
  210. :param elines: List of strings, each being a line of Excellon code.
  211. :type elines: list
  212. :return: None
  213. """
  214. # State variables
  215. current_tool = ""
  216. in_header = False
  217. headerless = False
  218. current_x = None
  219. current_y = None
  220. slot_current_x = None
  221. slot_current_y = None
  222. name_tool = 0
  223. allegro_warning = False
  224. line_units_found = False
  225. repeating_x = 0
  226. repeating_y = 0
  227. repeat = 0
  228. line_units = ''
  229. # ## Parsing starts here ## ##
  230. line_num = 0 # Line number
  231. eline = ""
  232. try:
  233. for eline in elines:
  234. if self.app.abort_flag:
  235. # graceful abort requested by the user
  236. raise FlatCAMApp.GracefulException
  237. line_num += 1
  238. # log.debug("%3d %s" % (line_num, str(eline)))
  239. self.source_file += eline
  240. # Cleanup lines
  241. eline = eline.strip(' \r\n')
  242. # Excellon files and Gcode share some extensions therefore if we detect G20 or G21 it's GCODe
  243. # and we need to exit from here
  244. if self.detect_gcode_re.search(eline):
  245. log.warning("This is GCODE mark: %s" % eline)
  246. self.app.inform.emit('[ERROR_NOTCL] %s: %s' % (_('This is GCODE mark'), eline))
  247. return
  248. # Header Begin (M48) #
  249. if self.hbegin_re.search(eline):
  250. in_header = True
  251. headerless = False
  252. log.warning("Found start of the header: %s" % eline)
  253. continue
  254. # Allegro Header Begin (;HEADER) #
  255. if self.allegro_hbegin_re.search(eline):
  256. in_header = True
  257. allegro_warning = True
  258. log.warning("Found ALLEGRO start of the header: %s" % eline)
  259. continue
  260. # Search for Header End #
  261. # Since there might be comments in the header that include header end char (% or M95)
  262. # we ignore the lines starting with ';' that contains such header end chars because it is not a
  263. # real header end.
  264. if self.comm_re.search(eline):
  265. match = self.tool_units_re.search(eline)
  266. if match:
  267. if line_units_found is False:
  268. line_units_found = True
  269. line_units = match.group(3)
  270. self.convert_units({"MILS": "IN", "MM": "MM"}[line_units])
  271. log.warning("Type of Allegro UNITS found inline in comments: %s" % line_units)
  272. if match.group(2):
  273. name_tool += 1
  274. if line_units == 'MILS':
  275. spec = {"C": (float(match.group(2)) / 1000)}
  276. self.tools[str(name_tool)] = spec
  277. log.debug("Tool definition: %s %s" % (name_tool, spec))
  278. else:
  279. spec = {"C": float(match.group(2))}
  280. self.tools[str(name_tool)] = spec
  281. log.debug("Tool definition: %s %s" % (name_tool, spec))
  282. spec['solid_geometry'] = []
  283. continue
  284. # search for Altium Excellon Format / Sprint Layout who is included as a comment
  285. match = self.altium_format.search(eline)
  286. if match:
  287. self.excellon_format_upper_mm = match.group(1)
  288. self.excellon_format_lower_mm = match.group(2)
  289. self.excellon_format_upper_in = match.group(1)
  290. self.excellon_format_lower_in = match.group(2)
  291. log.warning("Altium Excellon format preset found in comments: %s:%s" %
  292. (match.group(1), match.group(2)))
  293. continue
  294. else:
  295. log.warning("Line ignored, it's a comment: %s" % eline)
  296. else:
  297. if self.hend_re.search(eline):
  298. if in_header is False or bool(self.tools) is False:
  299. log.warning("Found end of the header but there is no header: %s" % eline)
  300. log.warning("The only useful data in header are tools, units and format.")
  301. log.warning("Therefore we will create units and format based on defaults.")
  302. headerless = True
  303. try:
  304. self.convert_units({"INCH": "IN", "METRIC": "MM"}[self.excellon_units])
  305. except Exception as e:
  306. log.warning("Units could not be converted: %s" % str(e))
  307. in_header = False
  308. # for Allegro type of Excellons we reset name_tool variable so we can reuse it for toolchange
  309. if allegro_warning is True:
  310. name_tool = 0
  311. log.warning("Found end of the header: %s" % eline)
  312. continue
  313. # ## Alternative units format M71/M72
  314. # Supposed to be just in the body (yes, the body)
  315. # but some put it in the header (PADS for example).
  316. # Will detect anywhere. Occurrence will change the
  317. # object's units.
  318. match = self.meas_re.match(eline)
  319. if match:
  320. self.units = {"1": "MM", "2": "IN"}[match.group(1)]
  321. # Modified for issue #80
  322. log.debug("ALternative M71/M72 units found, before conversion: %s" % self.units)
  323. self.convert_units(self.units)
  324. log.debug("ALternative M71/M72 units found, after conversion: %s" % self.units)
  325. if self.units == 'MM':
  326. log.warning("Excellon format preset is: %s:%s" %
  327. (str(self.excellon_format_upper_mm), str(self.excellon_format_lower_mm)))
  328. else:
  329. log.warning("Excellon format preset is: %s:%s" %
  330. (str(self.excellon_format_upper_in), str(self.excellon_format_lower_in)))
  331. continue
  332. # ### Body ####
  333. if not in_header:
  334. # ## Tool change ###
  335. match = self.toolsel_re.search(eline)
  336. if match:
  337. current_tool = str(int(match.group(1)))
  338. log.debug("Tool change: %s" % current_tool)
  339. if bool(headerless):
  340. match = self.toolset_hl_re.search(eline)
  341. if match:
  342. name = str(int(match.group(1)))
  343. try:
  344. diam = float(match.group(2))
  345. except Exception:
  346. # it's possible that tool definition has only tool number and no diameter info
  347. # (those could be in another file like PCB Wizard do)
  348. # then match.group(2) = None and float(None) will create the exception
  349. # the bellow construction is so each tool will have a slightly different diameter
  350. # starting with a default value, to allow Excellon editing after that
  351. self.diameterless = True
  352. self.app.inform.emit('[WARNING] %s%s %s' %
  353. (_("No tool diameter info's. See shell.\n"
  354. "A tool change event: T"),
  355. str(current_tool),
  356. _("was found but the Excellon file "
  357. "have no informations regarding the tool "
  358. "diameters therefore the application will try to load it "
  359. "by using some 'fake' diameters.\n"
  360. "The user needs to edit the resulting Excellon object and "
  361. "change the diameters to reflect the real diameters.")
  362. )
  363. )
  364. if self.excellon_units == 'MM':
  365. diam = self.toolless_diam + (int(current_tool) - 1) / 100
  366. else:
  367. diam = (self.toolless_diam + (int(current_tool) - 1) / 100) / 25.4
  368. spec = {"C": diam, 'solid_geometry': []}
  369. self.tools[name] = spec
  370. log.debug("Tool definition out of header: %s %s" % (name, spec))
  371. continue
  372. # ## Allegro Type Tool change ###
  373. if allegro_warning is True:
  374. match = self.absinc_re.search(eline)
  375. match1 = self.stop_re.search(eline)
  376. if match or match1:
  377. name_tool += 1
  378. current_tool = str(name_tool)
  379. log.debug("Tool change for Allegro type of Excellon: %s" % current_tool)
  380. continue
  381. # ## Slots parsing for drilled slots (contain G85)
  382. # a Excellon drilled slot line may look like this:
  383. # X01125Y0022244G85Y0027756
  384. match = self.slots_re.search(eline)
  385. if match:
  386. # signal that there are milling slots operations
  387. self.defaults['excellon_drills'] = False
  388. # the slot start coordinates group is to the left of G85 command (group(1) )
  389. # the slot stop coordinates group is to the right of G85 command (group(2) )
  390. start_coords_match = match.group(1)
  391. stop_coords_match = match.group(2)
  392. # Slot coordinates without period # ##
  393. # get the coordinates for slot start and for slot stop into variables
  394. start_coords_noperiod = self.coordsnoperiod_re.search(start_coords_match)
  395. stop_coords_noperiod = self.coordsnoperiod_re.search(stop_coords_match)
  396. if start_coords_noperiod:
  397. try:
  398. slot_start_x = self.parse_number(start_coords_noperiod.group(1))
  399. slot_current_x = slot_start_x
  400. except TypeError:
  401. slot_start_x = slot_current_x
  402. except Exception:
  403. return
  404. try:
  405. slot_start_y = self.parse_number(start_coords_noperiod.group(2))
  406. slot_current_y = slot_start_y
  407. except TypeError:
  408. slot_start_y = slot_current_y
  409. except Exception:
  410. return
  411. try:
  412. slot_stop_x = self.parse_number(stop_coords_noperiod.group(1))
  413. slot_current_x = slot_stop_x
  414. except TypeError:
  415. slot_stop_x = slot_current_x
  416. except Exception:
  417. return
  418. try:
  419. slot_stop_y = self.parse_number(stop_coords_noperiod.group(2))
  420. slot_current_y = slot_stop_y
  421. except TypeError:
  422. slot_stop_y = slot_current_y
  423. except Exception:
  424. return
  425. if (slot_start_x is None or slot_start_y is None or
  426. slot_stop_x is None or slot_stop_y is None):
  427. log.error("Slots are missing some or all coordinates.")
  428. continue
  429. # we have a slot
  430. log.debug('Parsed a slot with coordinates: ' + str([slot_start_x,
  431. slot_start_y, slot_stop_x,
  432. slot_stop_y]))
  433. # store current tool diameter as slot diameter
  434. slot_dia = 0.05
  435. try:
  436. slot_dia = float(self.tools[current_tool]['C'])
  437. except Exception as e:
  438. pass
  439. log.debug(
  440. 'Milling/Drilling slot with tool %s, diam=%f' % (
  441. current_tool,
  442. slot_dia
  443. )
  444. )
  445. self.slots.append(
  446. {
  447. 'start': Point(slot_start_x, slot_start_y),
  448. 'stop': Point(slot_stop_x, slot_stop_y),
  449. 'tool': current_tool
  450. }
  451. )
  452. continue
  453. # Slot coordinates with period: Use literally. ###
  454. # get the coordinates for slot start and for slot stop into variables
  455. start_coords_period = self.coordsperiod_re.search(start_coords_match)
  456. stop_coords_period = self.coordsperiod_re.search(stop_coords_match)
  457. if start_coords_period:
  458. try:
  459. slot_start_x = float(start_coords_period.group(1))
  460. slot_current_x = slot_start_x
  461. except TypeError:
  462. slot_start_x = slot_current_x
  463. except Exception:
  464. return
  465. try:
  466. slot_start_y = float(start_coords_period.group(2))
  467. slot_current_y = slot_start_y
  468. except TypeError:
  469. slot_start_y = slot_current_y
  470. except Exception:
  471. return
  472. try:
  473. slot_stop_x = float(stop_coords_period.group(1))
  474. slot_current_x = slot_stop_x
  475. except TypeError:
  476. slot_stop_x = slot_current_x
  477. except Exception:
  478. return
  479. try:
  480. slot_stop_y = float(stop_coords_period.group(2))
  481. slot_current_y = slot_stop_y
  482. except TypeError:
  483. slot_stop_y = slot_current_y
  484. except Exception:
  485. return
  486. if (slot_start_x is None or slot_start_y is None or
  487. slot_stop_x is None or slot_stop_y is None):
  488. log.error("Slots are missing some or all coordinates.")
  489. continue
  490. # we have a slot
  491. log.debug('Parsed a slot with coordinates: ' + str([slot_start_x,
  492. slot_start_y, slot_stop_x,
  493. slot_stop_y]))
  494. # store current tool diameter as slot diameter
  495. slot_dia = 0.05
  496. try:
  497. slot_dia = float(self.tools[current_tool]['C'])
  498. except Exception as e:
  499. pass
  500. log.debug(
  501. 'Milling/Drilling slot with tool %s, diam=%f' % (
  502. current_tool,
  503. slot_dia
  504. )
  505. )
  506. self.slots.append(
  507. {
  508. 'start': Point(slot_start_x, slot_start_y),
  509. 'stop': Point(slot_stop_x, slot_stop_y),
  510. 'tool': current_tool
  511. }
  512. )
  513. continue
  514. # ## Coordinates without period # ##
  515. match = self.coordsnoperiod_re.search(eline)
  516. if match:
  517. matchr = self.repeat_re.search(eline)
  518. if matchr:
  519. repeat = int(matchr.group(1))
  520. try:
  521. x = self.parse_number(match.group(1))
  522. repeating_x = current_x
  523. current_x = x
  524. except TypeError:
  525. x = current_x
  526. repeating_x = 0
  527. except Exception:
  528. return
  529. try:
  530. y = self.parse_number(match.group(2))
  531. repeating_y = current_y
  532. current_y = y
  533. except TypeError:
  534. y = current_y
  535. repeating_y = 0
  536. except Exception:
  537. return
  538. if x is None or y is None:
  539. log.error("Missing coordinates")
  540. continue
  541. # ## Excellon Routing parse
  542. if len(re.findall("G00", eline)) > 0:
  543. self.match_routing_start = 'G00'
  544. # signal that there are milling slots operations
  545. self.defaults['excellon_drills'] = False
  546. self.routing_flag = 0
  547. slot_start_x = x
  548. slot_start_y = y
  549. continue
  550. if self.routing_flag == 0:
  551. if len(re.findall("G01", eline)) > 0:
  552. self.match_routing_stop = 'G01'
  553. # signal that there are milling slots operations
  554. self.defaults['excellon_drills'] = False
  555. self.routing_flag = 1
  556. slot_stop_x = x
  557. slot_stop_y = y
  558. self.slots.append(
  559. {
  560. 'start': Point(slot_start_x, slot_start_y),
  561. 'stop': Point(slot_stop_x, slot_stop_y),
  562. 'tool': current_tool
  563. }
  564. )
  565. continue
  566. if self.match_routing_start is None and self.match_routing_stop is None:
  567. if repeat == 0:
  568. # signal that there are drill operations
  569. self.defaults['excellon_drills'] = True
  570. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  571. else:
  572. coordx = x
  573. coordy = y
  574. while repeat > 0:
  575. if repeating_x:
  576. coordx = (repeat * x) + repeating_x
  577. if repeating_y:
  578. coordy = (repeat * y) + repeating_y
  579. self.drills.append({'point': Point((coordx, coordy)), 'tool': current_tool})
  580. repeat -= 1
  581. repeating_x = repeating_y = 0
  582. # log.debug("{:15} {:8} {:8}".format(eline, x, y))
  583. continue
  584. # ## Coordinates with period: Use literally. # ##
  585. match = self.coordsperiod_re.search(eline)
  586. if match:
  587. matchr = self.repeat_re.search(eline)
  588. if matchr:
  589. repeat = int(matchr.group(1))
  590. if match:
  591. # signal that there are drill operations
  592. self.defaults['excellon_drills'] = True
  593. try:
  594. x = float(match.group(1))
  595. repeating_x = current_x
  596. current_x = x
  597. except TypeError:
  598. x = current_x
  599. repeating_x = 0
  600. try:
  601. y = float(match.group(2))
  602. repeating_y = current_y
  603. current_y = y
  604. except TypeError:
  605. y = current_y
  606. repeating_y = 0
  607. if x is None or y is None:
  608. log.error("Missing coordinates")
  609. continue
  610. # ## Excellon Routing parse
  611. if len(re.findall("G00", eline)) > 0:
  612. self.match_routing_start = 'G00'
  613. # signal that there are milling slots operations
  614. self.defaults['excellon_drills'] = False
  615. self.routing_flag = 0
  616. slot_start_x = x
  617. slot_start_y = y
  618. continue
  619. if self.routing_flag == 0:
  620. if len(re.findall("G01", eline)) > 0:
  621. self.match_routing_stop = 'G01'
  622. # signal that there are milling slots operations
  623. self.defaults['excellon_drills'] = False
  624. self.routing_flag = 1
  625. slot_stop_x = x
  626. slot_stop_y = y
  627. self.slots.append(
  628. {
  629. 'start': Point(slot_start_x, slot_start_y),
  630. 'stop': Point(slot_stop_x, slot_stop_y),
  631. 'tool': current_tool
  632. }
  633. )
  634. continue
  635. if self.match_routing_start is None and self.match_routing_stop is None:
  636. # signal that there are drill operations
  637. if repeat == 0:
  638. # signal that there are drill operations
  639. self.defaults['excellon_drills'] = True
  640. self.drills.append({'point': Point((x, y)), 'tool': current_tool})
  641. else:
  642. coordx = x
  643. coordy = y
  644. while repeat > 0:
  645. if repeating_x:
  646. coordx = (repeat * x) + repeating_x
  647. if repeating_y:
  648. coordy = (repeat * y) + repeating_y
  649. self.drills.append({'point': Point((coordx, coordy)), 'tool': current_tool})
  650. repeat -= 1
  651. repeating_x = repeating_y = 0
  652. # log.debug("{:15} {:8} {:8}".format(eline, x, y))
  653. continue
  654. # ### Header ####
  655. if in_header:
  656. # ## Tool definitions # ##
  657. match = self.toolset_re.search(eline)
  658. if match:
  659. name = str(int(match.group(1)))
  660. spec = {"C": float(match.group(2)), 'solid_geometry': []}
  661. self.tools[name] = spec
  662. log.debug("Tool definition: %s %s" % (name, spec))
  663. continue
  664. # ## Units and number format # ##
  665. match = self.units_re.match(eline)
  666. if match:
  667. self.units = {"METRIC": "MM", "INCH": "IN"}[match.group(1)]
  668. self.zeros = match.group(2) # "T" or "L". Might be empty
  669. self.excellon_format = match.group(3)
  670. if self.excellon_format:
  671. upper = len(self.excellon_format.partition('.')[0])
  672. lower = len(self.excellon_format.partition('.')[2])
  673. if self.units == 'MM':
  674. self.excellon_format_upper_mm = upper
  675. self.excellon_format_lower_mm = lower
  676. else:
  677. self.excellon_format_upper_in = upper
  678. self.excellon_format_lower_in = lower
  679. # Modified for issue #80
  680. log.warning("UNITS found inline before conversion: %s" % self.units)
  681. self.convert_units(self.units)
  682. log.warning("UNITS found inline after conversion: %s" % self.units)
  683. if self.units == 'MM':
  684. log.warning("Excellon format preset is: %s:%s" %
  685. (str(self.excellon_format_upper_mm), str(self.excellon_format_lower_mm)))
  686. else:
  687. log.warning("Excellon format preset is: %s:%s" %
  688. (str(self.excellon_format_upper_in), str(self.excellon_format_lower_in)))
  689. log.warning("Type of ZEROS found inline, in header: %s" % self.zeros)
  690. continue
  691. # Search for units type again it might be alone on the line
  692. if "INCH" in eline:
  693. line_units = "IN"
  694. # Modified for issue #80
  695. log.warning("Type of UNITS found inline, in header, before conversion: %s" % line_units)
  696. self.convert_units(line_units)
  697. log.warning("Type of UNITS found inline, in header, after conversion: %s" % self.units)
  698. log.warning("Excellon format preset is: %s:%s" %
  699. (str(self.excellon_format_upper_in), str(self.excellon_format_lower_in)))
  700. continue
  701. elif "METRIC" in eline:
  702. line_units = "MM"
  703. # Modified for issue #80
  704. log.warning("Type of UNITS found inline, in header, before conversion: %s" % line_units)
  705. self.convert_units(line_units)
  706. log.warning("Type of UNITS found inline, in header, after conversion: %s" % self.units)
  707. log.warning("Excellon format preset is: %s:%s" %
  708. (str(self.excellon_format_upper_mm), str(self.excellon_format_lower_mm)))
  709. continue
  710. # Search for zeros type again because it might be alone on the line
  711. match = re.search(r'[LT]Z', eline)
  712. if match:
  713. self.zeros = match.group()
  714. log.warning("Type of ZEROS found: %s" % self.zeros)
  715. continue
  716. # ## Units and number format outside header# ##
  717. match = self.units_re.match(eline)
  718. if match:
  719. self.units = self.units = {"METRIC": "MM", "INCH": "IN"}[match.group(1)]
  720. self.zeros = match.group(2) # "T" or "L". Might be empty
  721. self.excellon_format = match.group(3)
  722. if self.excellon_format:
  723. upper = len(self.excellon_format.partition('.')[0])
  724. lower = len(self.excellon_format.partition('.')[2])
  725. if self.units == 'MM':
  726. self.excellon_format_upper_mm = upper
  727. self.excellon_format_lower_mm = lower
  728. else:
  729. self.excellon_format_upper_in = upper
  730. self.excellon_format_lower_in = lower
  731. # Modified for issue #80
  732. log.warning("Type of UNITS found outside header, inline before conversion: %s" % self.units)
  733. self.convert_units(self.units)
  734. log.warning("Type of UNITS found outside header, inline after conversion: %s" % self.units)
  735. if self.units == 'MM':
  736. log.warning("Excellon format preset is: %s:%s" %
  737. (str(self.excellon_format_upper_mm), str(self.excellon_format_lower_mm)))
  738. else:
  739. log.warning("Excellon format preset is: %s:%s" %
  740. (str(self.excellon_format_upper_in), str(self.excellon_format_lower_in)))
  741. log.warning("Type of ZEROS found outside header, inline: %s" % self.zeros)
  742. continue
  743. log.warning("Line ignored: %s" % eline)
  744. # make sure that since we are in headerless mode, we convert the tools only after the file parsing
  745. # is finished since the tools definitions are spread in the Excellon body. We use as units the value
  746. # from self.defaults['excellon_units']
  747. log.info("Zeros: %s, Units %s." % (self.zeros, self.units))
  748. except Exception:
  749. log.error("Excellon PARSING FAILED. Line %d: %s" % (line_num, eline))
  750. msg = '[ERROR_NOTCL] %s' % \
  751. _("An internal error has ocurred. See shell.\n")
  752. msg += ('{e_code} {tx} {l_nr}: {line}\n').format(
  753. e_code='[ERROR]',
  754. tx=_("Excellon Parser error.\nParsing Failed. Line"),
  755. l_nr=line_num,
  756. line=eline)
  757. msg += traceback.format_exc()
  758. self.app.inform.emit(msg)
  759. return "fail"
  760. def parse_number(self, number_str):
  761. """
  762. Parses coordinate numbers without period.
  763. :param number_str: String representing the numerical value.
  764. :type number_str: str
  765. :return: Floating point representation of the number
  766. :rtype: float
  767. """
  768. match = self.leadingzeros_re.search(number_str)
  769. nr_length = len(match.group(1)) + len(match.group(2))
  770. try:
  771. if self.zeros == "L" or self.zeros == "LZ": # Leading
  772. # With leading zeros, when you type in a coordinate,
  773. # the leading zeros must always be included. Trailing zeros
  774. # are unneeded and may be left off. The CNC-7 will automatically add them.
  775. # r'^[-\+]?(0*)(\d*)'
  776. # 6 digits are divided by 10^4
  777. # If less than size digits, they are automatically added,
  778. # 5 digits then are divided by 10^3 and so on.
  779. if self.units.lower() == "in":
  780. result = float(number_str) / (10 ** (float(nr_length) - float(self.excellon_format_upper_in)))
  781. else:
  782. result = float(number_str) / (10 ** (float(nr_length) - float(self.excellon_format_upper_mm)))
  783. return result
  784. else: # Trailing
  785. # You must show all zeros to the right of the number and can omit
  786. # all zeros to the left of the number. The CNC-7 will count the number
  787. # of digits you typed and automatically fill in the missing zeros.
  788. # ## flatCAM expects 6digits
  789. # flatCAM expects the number of digits entered into the defaults
  790. if self.units.lower() == "in": # Inches is 00.0000
  791. result = float(number_str) / (10 ** (float(self.excellon_format_lower_in)))
  792. else: # Metric is 000.000
  793. result = float(number_str) / (10 ** (float(self.excellon_format_lower_mm)))
  794. return result
  795. except Exception as e:
  796. log.error("Aborted. Operation could not be completed due of %s" % str(e))
  797. return
  798. def create_geometry(self):
  799. """
  800. Creates circles of the tool diameter at every point
  801. specified in ``self.drills``. Also creates geometries (polygons)
  802. for the slots as specified in ``self.slots``
  803. All the resulting geometry is stored into self.solid_geometry list.
  804. The list self.solid_geometry has 2 elements: first is a dict with the drills geometry,
  805. and second element is another similar dict that contain the slots geometry.
  806. Each dict has as keys the tool diameters and as values lists with Shapely objects, the geometries
  807. ================ ====================================
  808. Key Value
  809. ================ ====================================
  810. tool_diameter list of (Shapely.Point) Where to drill
  811. ================ ====================================
  812. :return: None
  813. """
  814. log.debug("flatcamParsers.ParseExcellon.Excellon.create_geometry()")
  815. self.solid_geometry = []
  816. try:
  817. # clear the solid_geometry in self.tools
  818. for tool in self.tools:
  819. self.tools[tool]['solid_geometry'] = []
  820. self.tools[tool]['data'] = {}
  821. for drill in self.drills:
  822. # poly = drill['point'].buffer(self.tools[drill['tool']]["C"]/2.0)
  823. if drill['tool'] == '':
  824. self.app.inform.emit('[WARNING] %s' %
  825. _("Excellon.create_geometry() -> a drill location was skipped "
  826. "due of not having a tool associated.\n"
  827. "Check the resulting GCode."))
  828. log.debug("flatcamParsers.ParseExcellon.Excellon.create_geometry() -> a drill location was skipped "
  829. "due of not having a tool associated")
  830. continue
  831. tooldia = self.tools[drill['tool']]['C']
  832. poly = drill['point'].buffer(tooldia / 2.0, int(int(self.geo_steps_per_circle) / 4))
  833. self.solid_geometry.append(poly)
  834. tool_in_drills = drill['tool']
  835. self.tools[tool_in_drills]['solid_geometry'].append(poly)
  836. self.tools[tool_in_drills]['data'] = deepcopy(self.default_data)
  837. for slot in self.slots:
  838. slot_tooldia = self.tools[slot['tool']]['C']
  839. start = slot['start']
  840. stop = slot['stop']
  841. lines_string = LineString([start, stop])
  842. poly = lines_string.buffer(slot_tooldia / 2.0, int(int(self.geo_steps_per_circle) / 4))
  843. self.solid_geometry.append(poly)
  844. tool_in_slots = slot['tool']
  845. self.tools[tool_in_slots]['solid_geometry'].append(poly)
  846. self.tools[tool_in_slots]['data'] = deepcopy(self.default_data)
  847. except Exception as e:
  848. log.debug("flatcamParsers.ParseExcellon.Excellon.create_geometry() -> "
  849. "Excellon geometry creation failed due of ERROR: %s" % str(e))
  850. return "fail"
  851. def bounds(self):
  852. """
  853. Returns coordinates of rectangular bounds
  854. of Excellon geometry: (xmin, ymin, xmax, ymax).
  855. """
  856. # fixed issue of getting bounds only for one level lists of objects
  857. # now it can get bounds for nested lists of objects
  858. log.debug("flatcamParsers.ParseExcellon.Excellon.bounds()")
  859. if self.solid_geometry is None or not self.tools:
  860. log.debug("flatcamParsers.ParseExcellon.Excellon -> solid_geometry is None")
  861. return 0, 0, 0, 0
  862. def bounds_rec(obj):
  863. if type(obj) is list:
  864. minx = np.Inf
  865. miny = np.Inf
  866. maxx = -np.Inf
  867. maxy = -np.Inf
  868. for k in obj:
  869. if type(k) is dict:
  870. for key in k:
  871. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  872. minx = min(minx, minx_)
  873. miny = min(miny, miny_)
  874. maxx = max(maxx, maxx_)
  875. maxy = max(maxy, maxy_)
  876. else:
  877. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  878. minx = min(minx, minx_)
  879. miny = min(miny, miny_)
  880. maxx = max(maxx, maxx_)
  881. maxy = max(maxy, maxy_)
  882. return minx, miny, maxx, maxy
  883. else:
  884. # it's a Shapely object, return it's bounds
  885. return obj.bounds
  886. minx_list = []
  887. miny_list = []
  888. maxx_list = []
  889. maxy_list = []
  890. for tool in self.tools:
  891. minx, miny, maxx, maxy = bounds_rec(self.tools[tool]['solid_geometry'])
  892. minx_list.append(minx)
  893. miny_list.append(miny)
  894. maxx_list.append(maxx)
  895. maxy_list.append(maxy)
  896. return min(minx_list), min(miny_list), max(maxx_list), max(maxy_list)
  897. def convert_units(self, units):
  898. """
  899. This function first convert to the the units found in the Excellon file but it converts tools that
  900. are not there yet so it has no effect other than it signal that the units are the ones in the file.
  901. On object creation, in new_object(), true conversion is done because this is done at the end of the
  902. Excellon file parsing, the tools are inside and self.tools is really converted from the units found
  903. inside the file to the FlatCAM units.
  904. Kind of convolute way to make the conversion and it is based on the assumption that the Excellon file
  905. will have detected the units before the tools are parsed and stored in self.tools
  906. :param units:
  907. :type str: IN or MM
  908. :return:
  909. """
  910. # factor = Geometry.convert_units(self, units)
  911. obj_units = units
  912. if obj_units.upper() == self.units.upper():
  913. factor = 1.0
  914. elif obj_units.upper() == "MM":
  915. factor = 25.4
  916. elif obj_units.upper() == "IN":
  917. factor = 1 / 25.4
  918. else:
  919. log.error("Unsupported units: %s" % str(obj_units))
  920. factor = 1.0
  921. log.debug("flatcamParsers.ParseExcellon.Excellon.convert_units() --> Factor: %s" % str(factor))
  922. self.units = obj_units
  923. self.scale(factor, factor)
  924. self.file_units_factor = factor
  925. # Tools
  926. for tname in self.tools:
  927. self.tools[tname]["C"] *= factor
  928. self.create_geometry()
  929. return factor
  930. def scale(self, xfactor, yfactor=None, point=None):
  931. """
  932. Scales geometry on the XY plane in the object by a given factor.
  933. Tool sizes, feedrates an Z-plane dimensions are untouched.
  934. :param xfactor: Number by which to scale the object.
  935. :type xfactor: float
  936. :param yfactor: Number by which to scale the object.
  937. :type yfactor: float
  938. :return: None
  939. :rtype: NOne
  940. """
  941. log.debug("flatcamParsers.ParseExcellon.Excellon.scale()")
  942. if yfactor is None:
  943. yfactor = xfactor
  944. if point is None:
  945. px = 0
  946. py = 0
  947. else:
  948. px, py = point
  949. if xfactor == 0 and yfactor == 0:
  950. return
  951. def scale_geom(obj):
  952. if type(obj) is list:
  953. new_obj = []
  954. for g in obj:
  955. new_obj.append(scale_geom(g))
  956. return new_obj
  957. else:
  958. try:
  959. return affinity.scale(obj, xfactor, yfactor, origin=(px, py))
  960. except AttributeError:
  961. return obj
  962. # variables to display the percentage of work done
  963. self.geo_len = 0
  964. try:
  965. for g in self.drills:
  966. self.geo_len += 1
  967. except TypeError:
  968. self.geo_len = 1
  969. self.old_disp_number = 0
  970. self.el_count = 0
  971. # Drills
  972. for drill in self.drills:
  973. drill['point'] = affinity.scale(drill['point'], xfactor, yfactor, origin=(px, py))
  974. self.el_count += 1
  975. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  976. if self.old_disp_number < disp_number <= 100:
  977. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  978. self.old_disp_number = disp_number
  979. # scale solid_geometry
  980. for tool in self.tools:
  981. self.tools[tool]['solid_geometry'] = scale_geom(self.tools[tool]['solid_geometry'])
  982. # Slots
  983. for slot in self.slots:
  984. slot['stop'] = affinity.scale(slot['stop'], xfactor, yfactor, origin=(px, py))
  985. slot['start'] = affinity.scale(slot['start'], xfactor, yfactor, origin=(px, py))
  986. self.create_geometry()
  987. self.app.proc_container.new_text = ''
  988. def offset(self, vect):
  989. """
  990. Offsets geometry on the XY plane in the object by a given vector.
  991. :param vect: (x, y) offset vector.
  992. :type vect: tuple
  993. :return: None
  994. """
  995. log.debug("flatcamParsers.ParseExcellon.Excellon.offset()")
  996. dx, dy = vect
  997. if dx == 0 and dy == 0:
  998. return
  999. def offset_geom(obj):
  1000. if type(obj) is list:
  1001. new_obj = []
  1002. for g in obj:
  1003. new_obj.append(offset_geom(g))
  1004. return new_obj
  1005. else:
  1006. try:
  1007. return affinity.translate(obj, xoff=dx, yoff=dy)
  1008. except AttributeError:
  1009. return obj
  1010. # variables to display the percentage of work done
  1011. self.geo_len = 0
  1012. try:
  1013. for g in self.drills:
  1014. self.geo_len += 1
  1015. except TypeError:
  1016. self.geo_len = 1
  1017. self.old_disp_number = 0
  1018. self.el_count = 0
  1019. # Drills
  1020. for drill in self.drills:
  1021. drill['point'] = affinity.translate(drill['point'], xoff=dx, yoff=dy)
  1022. self.el_count += 1
  1023. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1024. if self.old_disp_number < disp_number <= 100:
  1025. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1026. self.old_disp_number = disp_number
  1027. # offset solid_geometry
  1028. for tool in self.tools:
  1029. self.tools[tool]['solid_geometry'] = offset_geom(self.tools[tool]['solid_geometry'])
  1030. # Slots
  1031. for slot in self.slots:
  1032. slot['stop'] = affinity.translate(slot['stop'], xoff=dx, yoff=dy)
  1033. slot['start'] = affinity.translate(slot['start'], xoff=dx, yoff=dy)
  1034. # Recreate geometry
  1035. self.create_geometry()
  1036. self.app.proc_container.new_text = ''
  1037. def mirror(self, axis, point):
  1038. """
  1039. :param axis: "X" or "Y" indicates around which axis to mirror.
  1040. :type axis: str
  1041. :param point: [x, y] point belonging to the mirror axis.
  1042. :type point: list
  1043. :return: None
  1044. """
  1045. log.debug("flatcamParsers.ParseExcellon.Excellon.mirror()")
  1046. px, py = point
  1047. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1048. def mirror_geom(obj):
  1049. if type(obj) is list:
  1050. new_obj = []
  1051. for g in obj:
  1052. new_obj.append(mirror_geom(g))
  1053. return new_obj
  1054. else:
  1055. try:
  1056. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1057. except AttributeError:
  1058. return obj
  1059. # Modify data
  1060. # variables to display the percentage of work done
  1061. self.geo_len = 0
  1062. try:
  1063. for g in self.drills:
  1064. self.geo_len += 1
  1065. except TypeError:
  1066. self.geo_len = 1
  1067. self.old_disp_number = 0
  1068. self.el_count = 0
  1069. # Drills
  1070. for drill in self.drills:
  1071. drill['point'] = affinity.scale(drill['point'], xscale, yscale, origin=(px, py))
  1072. self.el_count += 1
  1073. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1074. if self.old_disp_number < disp_number <= 100:
  1075. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1076. self.old_disp_number = disp_number
  1077. # mirror solid_geometry
  1078. for tool in self.tools:
  1079. self.tools[tool]['solid_geometry'] = mirror_geom(self.tools[tool]['solid_geometry'])
  1080. # Slots
  1081. for slot in self.slots:
  1082. slot['stop'] = affinity.scale(slot['stop'], xscale, yscale, origin=(px, py))
  1083. slot['start'] = affinity.scale(slot['start'], xscale, yscale, origin=(px, py))
  1084. # Recreate geometry
  1085. self.create_geometry()
  1086. self.app.proc_container.new_text = ''
  1087. def skew(self, angle_x=None, angle_y=None, point=None):
  1088. """
  1089. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1090. Tool sizes, feedrates an Z-plane dimensions are untouched.
  1091. Parameters
  1092. ----------
  1093. xs, ys : float, float
  1094. The shear angle(s) for the x and y axes respectively. These can be
  1095. specified in either degrees (default) or radians by setting
  1096. use_radians=True.
  1097. See shapely manual for more information:
  1098. http://toblerity.org/shapely/manual.html#affine-transformations
  1099. """
  1100. log.debug("flatcamParsers.ParseExcellon.Excellon.skew()")
  1101. if angle_x is None:
  1102. angle_x = 0.0
  1103. if angle_y is None:
  1104. angle_y = 0.0
  1105. if angle_x == 0 and angle_y == 0:
  1106. return
  1107. def skew_geom(obj):
  1108. if type(obj) is list:
  1109. new_obj = []
  1110. for g in obj:
  1111. new_obj.append(skew_geom(g))
  1112. return new_obj
  1113. else:
  1114. try:
  1115. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1116. except AttributeError:
  1117. return obj
  1118. # variables to display the percentage of work done
  1119. self.geo_len = 0
  1120. try:
  1121. for g in self.drills:
  1122. self.geo_len += 1
  1123. except TypeError:
  1124. self.geo_len = 1
  1125. self.old_disp_number = 0
  1126. self.el_count = 0
  1127. if point is None:
  1128. px, py = 0, 0
  1129. # Drills
  1130. for drill in self.drills:
  1131. drill['point'] = affinity.skew(drill['point'], angle_x, angle_y,
  1132. origin=(px, py))
  1133. self.el_count += 1
  1134. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1135. if self.old_disp_number < disp_number <= 100:
  1136. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1137. self.old_disp_number = disp_number
  1138. # skew solid_geometry
  1139. for tool in self.tools:
  1140. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  1141. # Slots
  1142. for slot in self.slots:
  1143. slot['stop'] = affinity.skew(slot['stop'], angle_x, angle_y, origin=(px, py))
  1144. slot['start'] = affinity.skew(slot['start'], angle_x, angle_y, origin=(px, py))
  1145. else:
  1146. px, py = point
  1147. # Drills
  1148. for drill in self.drills:
  1149. drill['point'] = affinity.skew(drill['point'], angle_x, angle_y,
  1150. origin=(px, py))
  1151. self.el_count += 1
  1152. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1153. if self.old_disp_number < disp_number <= 100:
  1154. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1155. self.old_disp_number = disp_number
  1156. # skew solid_geometry
  1157. for tool in self.tools:
  1158. self.tools[tool]['solid_geometry'] = skew_geom(self.tools[tool]['solid_geometry'])
  1159. # Slots
  1160. for slot in self.slots:
  1161. slot['stop'] = affinity.skew(slot['stop'], angle_x, angle_y, origin=(px, py))
  1162. slot['start'] = affinity.skew(slot['start'], angle_x, angle_y, origin=(px, py))
  1163. self.create_geometry()
  1164. self.app.proc_container.new_text = ''
  1165. def rotate(self, angle, point=None):
  1166. """
  1167. Rotate the geometry of an object by an angle around the 'point' coordinates
  1168. :param angle:
  1169. :param point: tuple of coordinates (x, y)
  1170. :return:
  1171. """
  1172. log.debug("flatcamParsers.ParseExcellon.Excellon.rotate()")
  1173. if angle == 0:
  1174. return
  1175. def rotate_geom(obj, origin=None):
  1176. if type(obj) is list:
  1177. new_obj = []
  1178. for g in obj:
  1179. new_obj.append(rotate_geom(g))
  1180. return new_obj
  1181. else:
  1182. if origin:
  1183. try:
  1184. return affinity.rotate(obj, angle, origin=origin)
  1185. except AttributeError:
  1186. return obj
  1187. else:
  1188. try:
  1189. return affinity.rotate(obj, angle, origin=(px, py))
  1190. except AttributeError:
  1191. return obj
  1192. # variables to display the percentage of work done
  1193. self.geo_len = 0
  1194. try:
  1195. for g in self.drills:
  1196. self.geo_len += 1
  1197. except TypeError:
  1198. self.geo_len = 1
  1199. self.old_disp_number = 0
  1200. self.el_count = 0
  1201. if point is None:
  1202. # Drills
  1203. for drill in self.drills:
  1204. drill['point'] = affinity.rotate(drill['point'], angle, origin='center')
  1205. # rotate solid_geometry
  1206. for tool in self.tools:
  1207. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'], origin='center')
  1208. self.el_count += 1
  1209. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1210. if self.old_disp_number < disp_number <= 100:
  1211. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1212. self.old_disp_number = disp_number
  1213. # Slots
  1214. for slot in self.slots:
  1215. slot['stop'] = affinity.rotate(slot['stop'], angle, origin='center')
  1216. slot['start'] = affinity.rotate(slot['start'], angle, origin='center')
  1217. else:
  1218. px, py = point
  1219. # Drills
  1220. for drill in self.drills:
  1221. drill['point'] = affinity.rotate(drill['point'], angle, origin=(px, py))
  1222. self.el_count += 1
  1223. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1224. if self.old_disp_number < disp_number <= 100:
  1225. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1226. self.old_disp_number = disp_number
  1227. # rotate solid_geometry
  1228. for tool in self.tools:
  1229. self.tools[tool]['solid_geometry'] = rotate_geom(self.tools[tool]['solid_geometry'])
  1230. # Slots
  1231. for slot in self.slots:
  1232. slot['stop'] = affinity.rotate(slot['stop'], angle, origin=(px, py))
  1233. slot['start'] = affinity.rotate(slot['start'], angle, origin=(px, py))
  1234. self.create_geometry()
  1235. self.app.proc_container.new_text = ''
  1236. def buffer(self, distance, join, factor):
  1237. """
  1238. :param distance: if 'factor' is True then distance is the factor
  1239. :param factor: True or False (None)
  1240. :return:
  1241. """
  1242. log.debug("flatcamParsers.ParseExcellon.Excellon.buffer()")
  1243. if distance == 0:
  1244. return
  1245. def buffer_geom(obj):
  1246. if type(obj) is list:
  1247. new_obj = []
  1248. for g in obj:
  1249. new_obj.append(buffer_geom(g))
  1250. return new_obj
  1251. else:
  1252. try:
  1253. if factor is None:
  1254. return obj.buffer(distance, resolution=self.geo_steps_per_circle)
  1255. else:
  1256. return affinity.scale(obj, xfact=distance, yfact=distance, origin='center')
  1257. except AttributeError:
  1258. return obj
  1259. # buffer solid_geometry
  1260. for tool, tool_dict in list(self.tools.items()):
  1261. res = buffer_geom(tool_dict['solid_geometry'])
  1262. try:
  1263. __ = iter(res)
  1264. self.tools[tool]['solid_geometry'] = res
  1265. except TypeError:
  1266. self.tools[tool]['solid_geometry'] = [res]
  1267. if factor is None:
  1268. self.tools[tool]['C'] += distance
  1269. else:
  1270. self.tools[tool]['C'] *= distance
  1271. self.create_geometry()