ParseGerber.py 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181
  1. from camlib import Geometry, arc, arc_angle, ApertureMacro
  2. import FlatCAMApp
  3. import numpy as np
  4. import re
  5. import logging
  6. import traceback
  7. from copy import deepcopy
  8. import sys
  9. from shapely.ops import cascaded_union, unary_union
  10. from shapely.geometry import Polygon, MultiPolygon, LineString, Point
  11. import shapely.affinity as affinity
  12. from shapely.geometry import box as shply_box
  13. from lxml import etree as ET
  14. from flatcamParsers.ParseSVG import *
  15. import FlatCAMTranslation as fcTranslate
  16. import gettext
  17. import builtins
  18. if '_' not in builtins.__dict__:
  19. _ = gettext.gettext
  20. log = logging.getLogger('base')
  21. class Gerber(Geometry):
  22. """
  23. Here it is done all the Gerber parsing.
  24. **ATTRIBUTES**
  25. * ``apertures`` (dict): The keys are names/identifiers of each aperture.
  26. The values are dictionaries key/value pairs which describe the aperture. The
  27. type key is always present and the rest depend on the key:
  28. +-----------+-----------------------------------+
  29. | Key | Value |
  30. +===========+===================================+
  31. | type | (str) "C", "R", "O", "P", or "AP" |
  32. +-----------+-----------------------------------+
  33. | others | Depend on ``type`` |
  34. +-----------+-----------------------------------+
  35. | solid_geometry | (list) |
  36. +-----------+-----------------------------------+
  37. * ``aperture_macros`` (dictionary): Are predefined geometrical structures
  38. that can be instantiated with different parameters in an aperture
  39. definition. See ``apertures`` above. The key is the name of the macro,
  40. and the macro itself, the value, is a ``Aperture_Macro`` object.
  41. * ``flash_geometry`` (list): List of (Shapely) geometric object resulting
  42. from ``flashes``. These are generated from ``flashes`` in ``do_flashes()``.
  43. * ``buffered_paths`` (list): List of (Shapely) polygons resulting from
  44. *buffering* (or thickening) the ``paths`` with the aperture. These are
  45. generated from ``paths`` in ``buffer_paths()``.
  46. **USAGE**::
  47. g = Gerber()
  48. g.parse_file(filename)
  49. g.create_geometry()
  50. do_something(s.solid_geometry)
  51. """
  52. # defaults = {
  53. # "steps_per_circle": 128,
  54. # "use_buffer_for_union": True
  55. # }
  56. def __init__(self, steps_per_circle=None):
  57. """
  58. The constructor takes no parameters. Use ``gerber.parse_files()``
  59. or ``gerber.parse_lines()`` to populate the object from Gerber source.
  60. :return: Gerber object
  61. :rtype: Gerber
  62. """
  63. # How to approximate a circle with lines.
  64. self.steps_per_circle = int(self.app.defaults["gerber_circle_steps"])
  65. self.decimals = self.app.decimals
  66. # Initialize parent
  67. Geometry.__init__(self, geo_steps_per_circle=self.steps_per_circle)
  68. # Number format
  69. self.int_digits = 3
  70. """Number of integer digits in Gerber numbers. Used during parsing."""
  71. self.frac_digits = 4
  72. """Number of fraction digits in Gerber numbers. Used during parsing."""
  73. self.gerber_zeros = self.app.defaults['gerber_def_zeros']
  74. """Zeros in Gerber numbers. If 'L' then remove leading zeros, if 'T' remove trailing zeros. Used during parsing.
  75. """
  76. # ## Gerber elements # ##
  77. '''
  78. apertures = {
  79. 'id':{
  80. 'type':string,
  81. 'size':float,
  82. 'width':float,
  83. 'height':float,
  84. 'geometry': [],
  85. }
  86. }
  87. apertures['geometry'] list elements are dicts
  88. dict = {
  89. 'solid': [],
  90. 'follow': [],
  91. 'clear': []
  92. }
  93. '''
  94. # store the file units here:
  95. self.units = self.app.defaults['gerber_def_units']
  96. # aperture storage
  97. self.apertures = {}
  98. # Aperture Macros
  99. self.aperture_macros = {}
  100. # will store the Gerber geometry's as solids
  101. self.solid_geometry = Polygon()
  102. # will store the Gerber geometry's as paths
  103. self.follow_geometry = []
  104. # made True when the LPC command is encountered in Gerber parsing
  105. # it allows adding data into the clear_geometry key of the self.apertures[aperture] dict
  106. self.is_lpc = False
  107. self.source_file = ''
  108. # Attributes to be included in serialization
  109. # Always append to it because it carries contents
  110. # from Geometry.
  111. self.ser_attrs += ['int_digits', 'frac_digits', 'apertures',
  112. 'aperture_macros', 'solid_geometry', 'source_file']
  113. # ### Parser patterns ## ##
  114. # FS - Format Specification
  115. # The format of X and Y must be the same!
  116. # L-omit leading zeros, T-omit trailing zeros, D-no zero supression
  117. # A-absolute notation, I-incremental notation
  118. self.fmt_re = re.compile(r'%?FS([LTD])?([AI])X(\d)(\d)Y\d\d\*%?$')
  119. self.fmt_re_alt = re.compile(r'%FS([LTD])?([AI])X(\d)(\d)Y\d\d\*MO(IN|MM)\*%$')
  120. self.fmt_re_orcad = re.compile(r'(G\d+)*\**%FS([LTD])?([AI]).*X(\d)(\d)Y\d\d\*%$')
  121. # Mode (IN/MM)
  122. self.mode_re = re.compile(r'^%?MO(IN|MM)\*%?$')
  123. # Comment G04|G4
  124. self.comm_re = re.compile(r'^G0?4(.*)$')
  125. # AD - Aperture definition
  126. # Aperture Macro names: Name = [a-zA-Z_.$]{[a-zA-Z_.0-9]+}
  127. # NOTE: Adding "-" to support output from Upverter.
  128. self.ad_re = re.compile(r'^%ADD(\d\d+)([a-zA-Z_$\.][a-zA-Z0-9_$\.\-]*)(?:,(.*))?\*%$')
  129. # AM - Aperture Macro
  130. # Beginning of macro (Ends with *%):
  131. # self.am_re = re.compile(r'^%AM([a-zA-Z0-9]*)\*')
  132. # Tool change
  133. # May begin with G54 but that is deprecated
  134. self.tool_re = re.compile(r'^(?:G54)?D(\d\d+)\*$')
  135. # G01... - Linear interpolation plus flashes with coordinates
  136. # Operation code (D0x) missing is deprecated... oh well I will support it.
  137. self.lin_re = re.compile(r'^(?:G0?(1))?(?=.*X([\+-]?\d+))?(?=.*Y([\+-]?\d+))?[XY][^DIJ]*(?:D0?([123]))?\*$')
  138. # Operation code alone, usually just D03 (Flash)
  139. self.opcode_re = re.compile(r'^D0?([123])\*$')
  140. # G02/3... - Circular interpolation with coordinates
  141. # 2-clockwise, 3-counterclockwise
  142. # Operation code (D0x) missing is deprecated... oh well I will support it.
  143. # Optional start with G02 or G03, optional end with D01 or D02 with
  144. # optional coordinates but at least one in any order.
  145. self.circ_re = re.compile(r'^(?:G0?([23]))?(?=.*X([\+-]?\d+))?(?=.*Y([\+-]?\d+))' +
  146. '?(?=.*I([\+-]?\d+))?(?=.*J([\+-]?\d+))?[XYIJ][^D]*(?:D0([12]))?\*$')
  147. # G01/2/3 Occurring without coordinates
  148. self.interp_re = re.compile(r'^(?:G0?([123]))\*')
  149. # Single G74 or multi G75 quadrant for circular interpolation
  150. self.quad_re = re.compile(r'^G7([45]).*\*$')
  151. # Region mode on
  152. # In region mode, D01 starts a region
  153. # and D02 ends it. A new region can be started again
  154. # with D01. All contours must be closed before
  155. # D02 or G37.
  156. self.regionon_re = re.compile(r'^G36\*$')
  157. # Region mode off
  158. # Will end a region and come off region mode.
  159. # All contours must be closed before D02 or G37.
  160. self.regionoff_re = re.compile(r'^G37\*$')
  161. # End of file
  162. self.eof_re = re.compile(r'^M02\*')
  163. # IP - Image polarity
  164. self.pol_re = re.compile(r'^%?IP(POS|NEG)\*%?$')
  165. # LP - Level polarity
  166. self.lpol_re = re.compile(r'^%LP([DC])\*%$')
  167. # Units (OBSOLETE)
  168. self.units_re = re.compile(r'^G7([01])\*$')
  169. # Absolute/Relative G90/1 (OBSOLETE)
  170. self.absrel_re = re.compile(r'^G9([01])\*$')
  171. # Aperture macros
  172. self.am1_re = re.compile(r'^%AM([^\*]+)\*([^%]+)?(%)?$')
  173. self.am2_re = re.compile(r'(.*)%$')
  174. # flag to store if a conversion was done. It is needed because multiple units declarations can be found
  175. # in a Gerber file (normal or obsolete ones)
  176. self.conversion_done = False
  177. self.use_buffer_for_union = self.app.defaults["gerber_use_buffer_for_union"]
  178. def aperture_parse(self, apertureId, apertureType, apParameters):
  179. """
  180. Parse gerber aperture definition into dictionary of apertures.
  181. The following kinds and their attributes are supported:
  182. * *Circular (C)*: size (float)
  183. * *Rectangle (R)*: width (float), height (float)
  184. * *Obround (O)*: width (float), height (float).
  185. * *Polygon (P)*: diameter(float), vertices(int), [rotation(float)]
  186. * *Aperture Macro (AM)*: macro (ApertureMacro), modifiers (list)
  187. :param apertureId: Id of the aperture being defined.
  188. :param apertureType: Type of the aperture.
  189. :param apParameters: Parameters of the aperture.
  190. :type apertureId: str
  191. :type apertureType: str
  192. :type apParameters: str
  193. :return: Identifier of the aperture.
  194. :rtype: str
  195. """
  196. if self.app.abort_flag:
  197. # graceful abort requested by the user
  198. raise FlatCAMApp.GracefulException
  199. # Found some Gerber with a leading zero in the aperture id and the
  200. # referenced it without the zero, so this is a hack to handle that.
  201. apid = str(int(apertureId))
  202. try: # Could be empty for aperture macros
  203. paramList = apParameters.split('X')
  204. except Exception:
  205. paramList = None
  206. if apertureType == "C": # Circle, example: %ADD11C,0.1*%
  207. self.apertures[apid] = {"type": "C",
  208. "size": float(paramList[0])}
  209. return apid
  210. if apertureType == "R": # Rectangle, example: %ADD15R,0.05X0.12*%
  211. self.apertures[apid] = {"type": "R",
  212. "width": float(paramList[0]),
  213. "height": float(paramList[1]),
  214. "size": np.sqrt(float(paramList[0]) ** 2 + float(paramList[1]) ** 2)} # Hack
  215. return apid
  216. if apertureType == "O": # Obround
  217. self.apertures[apid] = {"type": "O",
  218. "width": float(paramList[0]),
  219. "height": float(paramList[1]),
  220. "size": np.sqrt(float(paramList[0]) ** 2 + float(paramList[1]) ** 2)} # Hack
  221. return apid
  222. if apertureType == "P": # Polygon (regular)
  223. self.apertures[apid] = {"type": "P",
  224. "diam": float(paramList[0]),
  225. "nVertices": int(paramList[1]),
  226. "size": float(paramList[0])} # Hack
  227. if len(paramList) >= 3:
  228. self.apertures[apid]["rotation"] = float(paramList[2])
  229. return apid
  230. if apertureType in self.aperture_macros:
  231. self.apertures[apid] = {"type": "AM",
  232. "macro": self.aperture_macros[apertureType],
  233. "modifiers": paramList}
  234. return apid
  235. log.warning("Aperture not implemented: %s" % str(apertureType))
  236. return None
  237. def parse_file(self, filename, follow=False):
  238. """
  239. Calls Gerber.parse_lines() with generator of lines
  240. read from the given file. Will split the lines if multiple
  241. statements are found in a single original line.
  242. The following line is split into two::
  243. G54D11*G36*
  244. First is ``G54D11*`` and seconds is ``G36*``.
  245. :param filename: Gerber file to parse.
  246. :type filename: str
  247. :param follow: If true, will not create polygons, just lines
  248. following the gerber path.
  249. :type follow: bool
  250. :return: None
  251. """
  252. with open(filename, 'r') as gfile:
  253. def line_generator():
  254. for line in gfile:
  255. line = line.strip(' \r\n')
  256. while len(line) > 0:
  257. # If ends with '%' leave as is.
  258. if line[-1] == '%':
  259. yield line
  260. break
  261. # Split after '*' if any.
  262. starpos = line.find('*')
  263. if starpos > -1:
  264. cleanline = line[:starpos + 1]
  265. yield cleanline
  266. line = line[starpos + 1:]
  267. # Otherwise leave as is.
  268. else:
  269. # yield clean line
  270. yield line
  271. break
  272. processed_lines = list(line_generator())
  273. self.parse_lines(processed_lines)
  274. # @profile
  275. def parse_lines(self, glines):
  276. """
  277. Main Gerber parser. Reads Gerber and populates ``self.paths``, ``self.apertures``,
  278. ``self.flashes``, ``self.regions`` and ``self.units``.
  279. :param glines: Gerber code as list of strings, each element being
  280. one line of the source file.
  281. :type glines: list
  282. :return: None
  283. :rtype: None
  284. """
  285. # Coordinates of the current path, each is [x, y]
  286. path = []
  287. # this is for temporary storage of solid geometry until it is added to poly_buffer
  288. geo_s = None
  289. # this is for temporary storage of follow geometry until it is added to follow_buffer
  290. geo_f = None
  291. # Polygons are stored here until there is a change in polarity.
  292. # Only then they are combined via cascaded_union and added or
  293. # subtracted from solid_geometry. This is ~100 times faster than
  294. # applying a union for every new polygon.
  295. poly_buffer = []
  296. # store here the follow geometry
  297. follow_buffer = []
  298. last_path_aperture = None
  299. current_aperture = None
  300. # 1,2 or 3 from "G01", "G02" or "G03"
  301. current_interpolation_mode = None
  302. # 1 or 2 from "D01" or "D02"
  303. # Note this is to support deprecated Gerber not putting
  304. # an operation code at the end of every coordinate line.
  305. current_operation_code = None
  306. # Current coordinates
  307. current_x = None
  308. current_y = None
  309. previous_x = None
  310. previous_y = None
  311. current_d = None
  312. # Absolute or Relative/Incremental coordinates
  313. # Not implemented
  314. absolute = True
  315. # How to interpret circular interpolation: SINGLE or MULTI
  316. quadrant_mode = None
  317. # Indicates we are parsing an aperture macro
  318. current_macro = None
  319. # Indicates the current polarity: D-Dark, C-Clear
  320. current_polarity = 'D'
  321. # If a region is being defined
  322. making_region = False
  323. # ### Parsing starts here ## ##
  324. line_num = 0
  325. gline = ""
  326. s_tol = float(self.app.defaults["gerber_simp_tolerance"])
  327. self.app.inform.emit('%s %d %s.' % (_("Gerber processing. Parsing"), len(glines), _("lines")))
  328. try:
  329. for gline in glines:
  330. if self.app.abort_flag:
  331. # graceful abort requested by the user
  332. raise FlatCAMApp.GracefulException
  333. line_num += 1
  334. self.source_file += gline + '\n'
  335. # Cleanup #
  336. gline = gline.strip(' \r\n')
  337. # log.debug("Line=%3s %s" % (line_num, gline))
  338. # ###################
  339. # Ignored lines #####
  340. # Comments #####
  341. # ###################
  342. match = self.comm_re.search(gline)
  343. if match:
  344. continue
  345. # Polarity change ###### ##
  346. # Example: %LPD*% or %LPC*%
  347. # If polarity changes, creates geometry from current
  348. # buffer, then adds or subtracts accordingly.
  349. match = self.lpol_re.search(gline)
  350. if match:
  351. new_polarity = match.group(1)
  352. # log.info("Polarity CHANGE, LPC = %s, poly_buff = %s" % (self.is_lpc, poly_buffer))
  353. self.is_lpc = True if new_polarity == 'C' else False
  354. if len(path) > 1 and current_polarity != new_polarity:
  355. # finish the current path and add it to the storage
  356. # --- Buffered ----
  357. width = self.apertures[last_path_aperture]["size"]
  358. geo_dict = dict()
  359. geo_f = LineString(path)
  360. if not geo_f.is_empty:
  361. follow_buffer.append(geo_f)
  362. geo_dict['follow'] = geo_f
  363. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  364. if not geo_s.is_empty:
  365. if self.app.defaults['gerber_simplification']:
  366. poly_buffer.append(geo_s.simplify(s_tol))
  367. else:
  368. poly_buffer.append(geo_s)
  369. if self.is_lpc is True:
  370. geo_dict['clear'] = geo_s
  371. else:
  372. geo_dict['solid'] = geo_s
  373. if last_path_aperture not in self.apertures:
  374. self.apertures[last_path_aperture] = dict()
  375. if 'geometry' not in self.apertures[last_path_aperture]:
  376. self.apertures[last_path_aperture]['geometry'] = []
  377. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  378. path = [path[-1]]
  379. # --- Apply buffer ---
  380. # If added for testing of bug #83
  381. # TODO: Remove when bug fixed
  382. if len(poly_buffer) > 0:
  383. if current_polarity == 'D':
  384. # self.follow_geometry = self.follow_geometry.union(cascaded_union(follow_buffer))
  385. self.solid_geometry = self.solid_geometry.union(cascaded_union(poly_buffer))
  386. else:
  387. # self.follow_geometry = self.follow_geometry.difference(cascaded_union(follow_buffer))
  388. self.solid_geometry = self.solid_geometry.difference(cascaded_union(poly_buffer))
  389. # follow_buffer = []
  390. poly_buffer = []
  391. current_polarity = new_polarity
  392. continue
  393. # ############################################################# ##
  394. # Number format ############################################### ##
  395. # Example: %FSLAX24Y24*%
  396. # ############################################################# ##
  397. # TODO: This is ignoring most of the format. Implement the rest.
  398. match = self.fmt_re.search(gline)
  399. if match:
  400. absolute = {'A': 'Absolute', 'I': 'Relative'}[match.group(2)]
  401. if match.group(1) is not None:
  402. self.gerber_zeros = match.group(1)
  403. self.int_digits = int(match.group(3))
  404. self.frac_digits = int(match.group(4))
  405. log.debug("Gerber format found. (%s) " % str(gline))
  406. log.debug(
  407. "Gerber format found. Gerber zeros = %s (L-omit leading zeros, T-omit trailing zeros, "
  408. "D-no zero supression)" % self.gerber_zeros)
  409. log.debug("Gerber format found. Coordinates type = %s (Absolute or Relative)" % absolute)
  410. continue
  411. # ## Mode (IN/MM)
  412. # Example: %MOIN*%
  413. match = self.mode_re.search(gline)
  414. if match:
  415. self.units = match.group(1)
  416. log.debug("Gerber units found = %s" % self.units)
  417. # Changed for issue #80
  418. # self.convert_units(match.group(1))
  419. self.conversion_done = True
  420. continue
  421. # ############################################################# ##
  422. # Combined Number format and Mode --- Allegro does this ####### ##
  423. # ############################################################# ##
  424. match = self.fmt_re_alt.search(gline)
  425. if match:
  426. absolute = {'A': 'Absolute', 'I': 'Relative'}[match.group(2)]
  427. if match.group(1) is not None:
  428. self.gerber_zeros = match.group(1)
  429. self.int_digits = int(match.group(3))
  430. self.frac_digits = int(match.group(4))
  431. log.debug("Gerber format found. (%s) " % str(gline))
  432. log.debug(
  433. "Gerber format found. Gerber zeros = %s (L-omit leading zeros, T-omit trailing zeros, "
  434. "D-no zero suppression)" % self.gerber_zeros)
  435. log.debug("Gerber format found. Coordinates type = %s (Absolute or Relative)" % absolute)
  436. self.units = match.group(5)
  437. log.debug("Gerber units found = %s" % self.units)
  438. # Changed for issue #80
  439. # self.convert_units(match.group(5))
  440. self.conversion_done = True
  441. continue
  442. # ############################################################# ##
  443. # Search for OrCAD way for having Number format
  444. # ############################################################# ##
  445. match = self.fmt_re_orcad.search(gline)
  446. if match:
  447. if match.group(1) is not None:
  448. if match.group(1) == 'G74':
  449. quadrant_mode = 'SINGLE'
  450. elif match.group(1) == 'G75':
  451. quadrant_mode = 'MULTI'
  452. absolute = {'A': 'Absolute', 'I': 'Relative'}[match.group(3)]
  453. if match.group(2) is not None:
  454. self.gerber_zeros = match.group(2)
  455. self.int_digits = int(match.group(4))
  456. self.frac_digits = int(match.group(5))
  457. log.debug("Gerber format found. (%s) " % str(gline))
  458. log.debug(
  459. "Gerber format found. Gerber zeros = %s (L-omit leading zeros, T-omit trailing zeros, "
  460. "D-no zerosuppressionn)" % self.gerber_zeros)
  461. log.debug("Gerber format found. Coordinates type = %s (Absolute or Relative)" % absolute)
  462. self.units = match.group(1)
  463. log.debug("Gerber units found = %s" % self.units)
  464. # Changed for issue #80
  465. # self.convert_units(match.group(5))
  466. self.conversion_done = True
  467. continue
  468. # ############################################################# ##
  469. # Units (G70/1) OBSOLETE
  470. # ############################################################# ##
  471. match = self.units_re.search(gline)
  472. if match:
  473. obs_gerber_units = {'0': 'IN', '1': 'MM'}[match.group(1)]
  474. log.warning("Gerber obsolete units found = %s" % obs_gerber_units)
  475. # Changed for issue #80
  476. # self.convert_units({'0': 'IN', '1': 'MM'}[match.group(1)])
  477. self.conversion_done = True
  478. continue
  479. # ############################################################# ##
  480. # Absolute/relative coordinates G90/1 OBSOLETE ######## ##
  481. # ##################################################### ##
  482. match = self.absrel_re.search(gline)
  483. if match:
  484. absolute = {'0': "Absolute", '1': "Relative"}[match.group(1)]
  485. log.warning("Gerber obsolete coordinates type found = %s (Absolute or Relative) " % absolute)
  486. continue
  487. # ############################################################# ##
  488. # Aperture Macros ##################################### ##
  489. # Having this at the beginning will slow things down
  490. # but macros can have complicated statements than could
  491. # be caught by other patterns.
  492. # ############################################################# ##
  493. if current_macro is None: # No macro started yet
  494. match = self.am1_re.search(gline)
  495. # Start macro if match, else not an AM, carry on.
  496. if match:
  497. log.debug("Starting macro. Line %d: %s" % (line_num, gline))
  498. current_macro = match.group(1)
  499. self.aperture_macros[current_macro] = ApertureMacro(name=current_macro)
  500. if match.group(2): # Append
  501. self.aperture_macros[current_macro].append(match.group(2))
  502. if match.group(3): # Finish macro
  503. # self.aperture_macros[current_macro].parse_content()
  504. current_macro = None
  505. log.debug("Macro complete in 1 line.")
  506. continue
  507. else: # Continue macro
  508. log.debug("Continuing macro. Line %d." % line_num)
  509. match = self.am2_re.search(gline)
  510. if match: # Finish macro
  511. log.debug("End of macro. Line %d." % line_num)
  512. self.aperture_macros[current_macro].append(match.group(1))
  513. # self.aperture_macros[current_macro].parse_content()
  514. current_macro = None
  515. else: # Append
  516. self.aperture_macros[current_macro].append(gline)
  517. continue
  518. # ## Aperture definitions %ADD...
  519. match = self.ad_re.search(gline)
  520. if match:
  521. # log.info("Found aperture definition. Line %d: %s" % (line_num, gline))
  522. self.aperture_parse(match.group(1), match.group(2), match.group(3))
  523. continue
  524. # ############################################################# ##
  525. # Operation code alone ###################### ##
  526. # Operation code alone, usually just D03 (Flash)
  527. # self.opcode_re = re.compile(r'^D0?([123])\*$')
  528. # ############################################################# ##
  529. match = self.opcode_re.search(gline)
  530. if match:
  531. current_operation_code = int(match.group(1))
  532. current_d = current_operation_code
  533. if current_operation_code == 3:
  534. # --- Buffered ---
  535. try:
  536. # log.debug("Bare op-code %d." % current_operation_code)
  537. geo_dict = dict()
  538. flash = self.create_flash_geometry(
  539. Point(current_x, current_y), self.apertures[current_aperture],
  540. self.steps_per_circle)
  541. geo_dict['follow'] = Point([current_x, current_y])
  542. if not flash.is_empty:
  543. if self.app.defaults['gerber_simplification']:
  544. poly_buffer.append(flash.simplify(s_tol))
  545. else:
  546. poly_buffer.append(flash)
  547. if self.is_lpc is True:
  548. geo_dict['clear'] = flash
  549. else:
  550. geo_dict['solid'] = flash
  551. if current_aperture not in self.apertures:
  552. self.apertures[current_aperture] = dict()
  553. if 'geometry' not in self.apertures[current_aperture]:
  554. self.apertures[current_aperture]['geometry'] = []
  555. self.apertures[current_aperture]['geometry'].append(deepcopy(geo_dict))
  556. except IndexError:
  557. log.warning("Line %d: %s -> Nothing there to flash!" % (line_num, gline))
  558. continue
  559. # ############################################################# ##
  560. # Tool/aperture change
  561. # Example: D12*
  562. # ############################################################# ##
  563. match = self.tool_re.search(gline)
  564. if match:
  565. current_aperture = match.group(1)
  566. # log.debug("Line %d: Aperture change to (%s)" % (line_num, current_aperture))
  567. # If the aperture value is zero then make it something quite small but with a non-zero value
  568. # so it can be processed by FlatCAM.
  569. # But first test to see if the aperture type is "aperture macro". In that case
  570. # we should not test for "size" key as it does not exist in this case.
  571. if self.apertures[current_aperture]["type"] is not "AM":
  572. if self.apertures[current_aperture]["size"] == 0:
  573. self.apertures[current_aperture]["size"] = 1e-12
  574. # log.debug(self.apertures[current_aperture])
  575. # Take care of the current path with the previous tool
  576. if len(path) > 1:
  577. if self.apertures[last_path_aperture]["type"] == 'R':
  578. # do nothing because 'R' type moving aperture is none at once
  579. pass
  580. else:
  581. geo_dict = dict()
  582. geo_f = LineString(path)
  583. if not geo_f.is_empty:
  584. follow_buffer.append(geo_f)
  585. geo_dict['follow'] = geo_f
  586. # --- Buffered ----
  587. width = self.apertures[last_path_aperture]["size"]
  588. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  589. if not geo_s.is_empty:
  590. if self.app.defaults['gerber_simplification']:
  591. poly_buffer.append(geo_s.simplify(s_tol))
  592. else:
  593. poly_buffer.append(geo_s)
  594. if self.is_lpc is True:
  595. geo_dict['clear'] = geo_s
  596. else:
  597. geo_dict['solid'] = geo_s
  598. if last_path_aperture not in self.apertures:
  599. self.apertures[last_path_aperture] = dict()
  600. if 'geometry' not in self.apertures[last_path_aperture]:
  601. self.apertures[last_path_aperture]['geometry'] = []
  602. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  603. path = [path[-1]]
  604. continue
  605. # ############################################################# ##
  606. # G36* - Begin region
  607. # ############################################################# ##
  608. if self.regionon_re.search(gline):
  609. if len(path) > 1:
  610. # Take care of what is left in the path
  611. geo_dict = dict()
  612. geo_f = LineString(path)
  613. if not geo_f.is_empty:
  614. follow_buffer.append(geo_f)
  615. geo_dict['follow'] = geo_f
  616. # --- Buffered ----
  617. width = self.apertures[last_path_aperture]["size"]
  618. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  619. if not geo_s.is_empty:
  620. if self.app.defaults['gerber_simplification']:
  621. poly_buffer.append(geo_s.simplify(s_tol))
  622. else:
  623. poly_buffer.append(geo_s)
  624. if self.is_lpc is True:
  625. geo_dict['clear'] = geo_s
  626. else:
  627. geo_dict['solid'] = geo_s
  628. if last_path_aperture not in self.apertures:
  629. self.apertures[last_path_aperture] = dict()
  630. if 'geometry' not in self.apertures[last_path_aperture]:
  631. self.apertures[last_path_aperture]['geometry'] = []
  632. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  633. path = [path[-1]]
  634. making_region = True
  635. continue
  636. # ############################################################# ##
  637. # G37* - End region
  638. # ############################################################# ##
  639. if self.regionoff_re.search(gline):
  640. making_region = False
  641. if '0' not in self.apertures:
  642. self.apertures['0'] = {}
  643. self.apertures['0']['type'] = 'REG'
  644. self.apertures['0']['size'] = 0.0
  645. self.apertures['0']['geometry'] = list()
  646. # if D02 happened before G37 we now have a path with 1 element only; we have to add the current
  647. # geo to the poly_buffer otherwise we loose it
  648. if current_operation_code == 2:
  649. if len(path) == 1:
  650. # this means that the geometry was prepared previously and we just need to add it
  651. geo_dict = dict()
  652. if geo_f:
  653. if not geo_f.is_empty:
  654. follow_buffer.append(geo_f)
  655. geo_dict['follow'] = geo_f
  656. if geo_s:
  657. if not geo_s.is_empty:
  658. if self.app.defaults['gerber_simplification']:
  659. poly_buffer.append(geo_s.simplify(s_tol))
  660. else:
  661. poly_buffer.append(geo_s)
  662. if self.is_lpc is True:
  663. geo_dict['clear'] = geo_s
  664. else:
  665. geo_dict['solid'] = geo_s
  666. if geo_s or geo_f:
  667. self.apertures['0']['geometry'].append(deepcopy(geo_dict))
  668. path = [[current_x, current_y]] # Start new path
  669. # Only one path defines region?
  670. # This can happen if D02 happened before G37 and
  671. # is not and error.
  672. if len(path) < 3:
  673. # print "ERROR: Path contains less than 3 points:"
  674. # path = [[current_x, current_y]]
  675. continue
  676. # For regions we may ignore an aperture that is None
  677. # --- Buffered ---
  678. geo_dict = dict()
  679. region_f = Polygon(path).exterior
  680. if not region_f.is_empty:
  681. follow_buffer.append(region_f)
  682. geo_dict['follow'] = region_f
  683. region_s = Polygon(path)
  684. if not region_s.is_valid:
  685. region_s = region_s.buffer(0, int(self.steps_per_circle / 4))
  686. if not region_s.is_empty:
  687. if self.app.defaults['gerber_simplification']:
  688. poly_buffer.append(region_s.simplify(s_tol))
  689. else:
  690. poly_buffer.append(region_s)
  691. if self.is_lpc is True:
  692. geo_dict['clear'] = region_s
  693. else:
  694. geo_dict['solid'] = region_s
  695. if not region_s.is_empty or not region_f.is_empty:
  696. self.apertures['0']['geometry'].append(deepcopy(geo_dict))
  697. path = [[current_x, current_y]] # Start new path
  698. continue
  699. # ## G01/2/3* - Interpolation mode change
  700. # Can occur along with coordinates and operation code but
  701. # sometimes by itself (handled here).
  702. # Example: G01*
  703. match = self.interp_re.search(gline)
  704. if match:
  705. current_interpolation_mode = int(match.group(1))
  706. continue
  707. # ## G01 - Linear interpolation plus flashes
  708. # Operation code (D0x) missing is deprecated... oh well I will support it.
  709. # REGEX: r'^(?:G0?(1))?(?:X(-?\d+))?(?:Y(-?\d+))?(?:D0([123]))?\*$'
  710. match = self.lin_re.search(gline)
  711. if match:
  712. # Dxx alone?
  713. # if match.group(1) is None and match.group(2) is None and match.group(3) is None:
  714. # try:
  715. # current_operation_code = int(match.group(4))
  716. # except Exception:
  717. # pass # A line with just * will match too.
  718. # continue
  719. # NOTE: Letting it continue allows it to react to the
  720. # operation code.
  721. # Parse coordinates
  722. if match.group(2) is not None:
  723. linear_x = parse_gerber_number(match.group(2),
  724. self.int_digits, self.frac_digits, self.gerber_zeros)
  725. current_x = linear_x
  726. else:
  727. linear_x = current_x
  728. if match.group(3) is not None:
  729. linear_y = parse_gerber_number(match.group(3),
  730. self.int_digits, self.frac_digits, self.gerber_zeros)
  731. current_y = linear_y
  732. else:
  733. linear_y = current_y
  734. # Parse operation code
  735. if match.group(4) is not None:
  736. current_operation_code = int(match.group(4))
  737. # Pen down: add segment
  738. if current_operation_code == 1:
  739. # if linear_x or linear_y are None, ignore those
  740. if current_x is not None and current_y is not None:
  741. # only add the point if it's a new one otherwise skip it (harder to process)
  742. if path[-1] != [current_x, current_y]:
  743. path.append([current_x, current_y])
  744. if making_region is False:
  745. # if the aperture is rectangle then add a rectangular shape having as parameters the
  746. # coordinates of the start and end point and also the width and height
  747. # of the 'R' aperture
  748. try:
  749. if self.apertures[current_aperture]["type"] == 'R':
  750. width = self.apertures[current_aperture]['width']
  751. height = self.apertures[current_aperture]['height']
  752. minx = min(path[0][0], path[1][0]) - width / 2
  753. maxx = max(path[0][0], path[1][0]) + width / 2
  754. miny = min(path[0][1], path[1][1]) - height / 2
  755. maxy = max(path[0][1], path[1][1]) + height / 2
  756. log.debug("Coords: %s - %s - %s - %s" % (minx, miny, maxx, maxy))
  757. geo_dict = dict()
  758. geo_f = Point([current_x, current_y])
  759. follow_buffer.append(geo_f)
  760. geo_dict['follow'] = geo_f
  761. geo_s = shply_box(minx, miny, maxx, maxy)
  762. if self.app.defaults['gerber_simplification']:
  763. poly_buffer.append(geo_s.simplify(s_tol))
  764. else:
  765. poly_buffer.append(geo_s)
  766. if self.is_lpc is True:
  767. geo_dict['clear'] = geo_s
  768. else:
  769. geo_dict['solid'] = geo_s
  770. if current_aperture not in self.apertures:
  771. self.apertures[current_aperture] = dict()
  772. if 'geometry' not in self.apertures[current_aperture]:
  773. self.apertures[current_aperture]['geometry'] = []
  774. self.apertures[current_aperture]['geometry'].append(deepcopy(geo_dict))
  775. except Exception as e:
  776. pass
  777. last_path_aperture = current_aperture
  778. # we do this for the case that a region is done without having defined any aperture
  779. if last_path_aperture is None:
  780. if '0' not in self.apertures:
  781. self.apertures['0'] = {}
  782. self.apertures['0']['type'] = 'REG'
  783. self.apertures['0']['size'] = 0.0
  784. self.apertures['0']['geometry'] = []
  785. last_path_aperture = '0'
  786. else:
  787. self.app.inform.emit('[WARNING] %s: %s' %
  788. (_("Coordinates missing, line ignored"), str(gline)))
  789. self.app.inform.emit('[WARNING_NOTCL] %s' %
  790. _("GERBER file might be CORRUPT. Check the file !!!"))
  791. elif current_operation_code == 2:
  792. if len(path) > 1:
  793. geo_s = None
  794. geo_dict = dict()
  795. # --- BUFFERED ---
  796. # this treats the case when we are storing geometry as paths only
  797. if making_region:
  798. # we do this for the case that a region is done without having defined any aperture
  799. if last_path_aperture is None:
  800. if '0' not in self.apertures:
  801. self.apertures['0'] = {}
  802. self.apertures['0']['type'] = 'REG'
  803. self.apertures['0']['size'] = 0.0
  804. self.apertures['0']['geometry'] = []
  805. last_path_aperture = '0'
  806. geo_f = Polygon()
  807. else:
  808. geo_f = LineString(path)
  809. try:
  810. if self.apertures[last_path_aperture]["type"] != 'R':
  811. if not geo_f.is_empty:
  812. follow_buffer.append(geo_f)
  813. geo_dict['follow'] = geo_f
  814. except Exception as e:
  815. log.debug("camlib.Gerber.parse_lines() --> %s" % str(e))
  816. if not geo_f.is_empty:
  817. follow_buffer.append(geo_f)
  818. geo_dict['follow'] = geo_f
  819. # this treats the case when we are storing geometry as solids
  820. if making_region:
  821. # we do this for the case that a region is done without having defined any aperture
  822. if last_path_aperture is None:
  823. if '0' not in self.apertures:
  824. self.apertures['0'] = {}
  825. self.apertures['0']['type'] = 'REG'
  826. self.apertures['0']['size'] = 0.0
  827. self.apertures['0']['geometry'] = []
  828. last_path_aperture = '0'
  829. try:
  830. geo_s = Polygon(path)
  831. except ValueError:
  832. log.warning("Problem %s %s" % (gline, line_num))
  833. self.app.inform.emit('[ERROR] %s: %s' %
  834. (_("Region does not have enough points. "
  835. "File will be processed but there are parser errors. "
  836. "Line number"), str(line_num)))
  837. else:
  838. if last_path_aperture is None:
  839. log.warning("No aperture defined for curent path. (%d)" % line_num)
  840. width = self.apertures[last_path_aperture]["size"] # TODO: WARNING this should fail!
  841. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  842. try:
  843. if self.apertures[last_path_aperture]["type"] != 'R':
  844. if not geo_s.is_empty:
  845. if self.app.defaults['gerber_simplification']:
  846. poly_buffer.append(geo_s.simplify(s_tol))
  847. else:
  848. poly_buffer.append(geo_s)
  849. if self.is_lpc is True:
  850. geo_dict['clear'] = geo_s
  851. else:
  852. geo_dict['solid'] = geo_s
  853. except Exception as e:
  854. log.debug("camlib.Gerber.parse_lines() --> %s" % str(e))
  855. if self.app.defaults['gerber_simplification']:
  856. poly_buffer.append(geo_s.simplify(s_tol))
  857. else:
  858. poly_buffer.append(geo_s)
  859. if self.is_lpc is True:
  860. geo_dict['clear'] = geo_s
  861. else:
  862. geo_dict['solid'] = geo_s
  863. if last_path_aperture not in self.apertures:
  864. self.apertures[last_path_aperture] = dict()
  865. if 'geometry' not in self.apertures[last_path_aperture]:
  866. self.apertures[last_path_aperture]['geometry'] = []
  867. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  868. # if linear_x or linear_y are None, ignore those
  869. if linear_x is not None and linear_y is not None:
  870. path = [[linear_x, linear_y]] # Start new path
  871. else:
  872. self.app.inform.emit('[WARNING] %s: %s' %
  873. (_("Coordinates missing, line ignored"), str(gline)))
  874. self.app.inform.emit('[WARNING_NOTCL] %s' %
  875. _("GERBER file might be CORRUPT. Check the file !!!"))
  876. # Flash
  877. # Not allowed in region mode.
  878. elif current_operation_code == 3:
  879. # Create path draw so far.
  880. if len(path) > 1:
  881. # --- Buffered ----
  882. geo_dict = dict()
  883. # this treats the case when we are storing geometry as paths
  884. geo_f = LineString(path)
  885. if not geo_f.is_empty:
  886. try:
  887. if self.apertures[last_path_aperture]["type"] != 'R':
  888. follow_buffer.append(geo_f)
  889. geo_dict['follow'] = geo_f
  890. except Exception as e:
  891. log.debug("camlib.Gerber.parse_lines() --> G01 match D03 --> %s" % str(e))
  892. follow_buffer.append(geo_f)
  893. geo_dict['follow'] = geo_f
  894. # this treats the case when we are storing geometry as solids
  895. width = self.apertures[last_path_aperture]["size"]
  896. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  897. if not geo_s.is_empty:
  898. try:
  899. if self.apertures[last_path_aperture]["type"] != 'R':
  900. if self.app.defaults['gerber_simplification']:
  901. poly_buffer.append(geo_s.simplify(s_tol))
  902. else:
  903. poly_buffer.append(geo_s)
  904. if self.is_lpc is True:
  905. geo_dict['clear'] = geo_s
  906. else:
  907. geo_dict['solid'] = geo_s
  908. except Exception:
  909. if self.app.defaults['gerber_simplification']:
  910. poly_buffer.append(geo_s.simplify(s_tol))
  911. else:
  912. poly_buffer.append(geo_s)
  913. if self.is_lpc is True:
  914. geo_dict['clear'] = geo_s
  915. else:
  916. geo_dict['solid'] = geo_s
  917. if last_path_aperture not in self.apertures:
  918. self.apertures[last_path_aperture] = dict()
  919. if 'geometry' not in self.apertures[last_path_aperture]:
  920. self.apertures[last_path_aperture]['geometry'] = []
  921. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  922. # Reset path starting point
  923. path = [[linear_x, linear_y]]
  924. # --- BUFFERED ---
  925. # Draw the flash
  926. # this treats the case when we are storing geometry as paths
  927. geo_dict = dict()
  928. geo_flash = Point([linear_x, linear_y])
  929. follow_buffer.append(geo_flash)
  930. geo_dict['follow'] = geo_flash
  931. # this treats the case when we are storing geometry as solids
  932. flash = self.create_flash_geometry(
  933. Point([linear_x, linear_y]),
  934. self.apertures[current_aperture],
  935. self.steps_per_circle
  936. )
  937. if not flash.is_empty:
  938. if self.app.defaults['gerber_simplification']:
  939. poly_buffer.append(flash.simplify(s_tol))
  940. else:
  941. poly_buffer.append(flash)
  942. if self.is_lpc is True:
  943. geo_dict['clear'] = flash
  944. else:
  945. geo_dict['solid'] = flash
  946. if current_aperture not in self.apertures:
  947. self.apertures[current_aperture] = dict()
  948. if 'geometry' not in self.apertures[current_aperture]:
  949. self.apertures[current_aperture]['geometry'] = []
  950. self.apertures[current_aperture]['geometry'].append(deepcopy(geo_dict))
  951. # maybe those lines are not exactly needed but it is easier to read the program as those coordinates
  952. # are used in case that circular interpolation is encountered within the Gerber file
  953. current_x = linear_x
  954. current_y = linear_y
  955. # log.debug("Line_number=%3s X=%s Y=%s (%s)" % (line_num, linear_x, linear_y, gline))
  956. continue
  957. # ## G74/75* - Single or multiple quadrant arcs
  958. match = self.quad_re.search(gline)
  959. if match:
  960. if match.group(1) == '4':
  961. quadrant_mode = 'SINGLE'
  962. else:
  963. quadrant_mode = 'MULTI'
  964. continue
  965. # ## G02/3 - Circular interpolation
  966. # 2-clockwise, 3-counterclockwise
  967. # Ex. format: G03 X0 Y50 I-50 J0 where the X, Y coords are the coords of the End Point
  968. match = self.circ_re.search(gline)
  969. if match:
  970. arcdir = [None, None, "cw", "ccw"]
  971. mode, circular_x, circular_y, i, j, d = match.groups()
  972. try:
  973. circular_x = parse_gerber_number(circular_x,
  974. self.int_digits, self.frac_digits, self.gerber_zeros)
  975. except Exception as e:
  976. circular_x = current_x
  977. try:
  978. circular_y = parse_gerber_number(circular_y,
  979. self.int_digits, self.frac_digits, self.gerber_zeros)
  980. except Exception as e:
  981. circular_y = current_y
  982. # According to Gerber specification i and j are not modal, which means that when i or j are missing,
  983. # they are to be interpreted as being zero
  984. try:
  985. i = parse_gerber_number(i, self.int_digits, self.frac_digits, self.gerber_zeros)
  986. except Exception as e:
  987. i = 0
  988. try:
  989. j = parse_gerber_number(j, self.int_digits, self.frac_digits, self.gerber_zeros)
  990. except Exception as e:
  991. j = 0
  992. if quadrant_mode is None:
  993. log.error("Found arc without preceding quadrant specification G74 or G75. (%d)" % line_num)
  994. log.error(gline)
  995. continue
  996. if mode is None and current_interpolation_mode not in [2, 3]:
  997. log.error("Found arc without circular interpolation mode defined. (%d)" % line_num)
  998. log.error(gline)
  999. continue
  1000. elif mode is not None:
  1001. current_interpolation_mode = int(mode)
  1002. # Set operation code if provided
  1003. if d is not None:
  1004. current_operation_code = int(d)
  1005. # Nothing created! Pen Up.
  1006. if current_operation_code == 2:
  1007. log.warning("Arc with D2. (%d)" % line_num)
  1008. if len(path) > 1:
  1009. geo_dict = dict()
  1010. if last_path_aperture is None:
  1011. log.warning("No aperture defined for curent path. (%d)" % line_num)
  1012. # --- BUFFERED ---
  1013. width = self.apertures[last_path_aperture]["size"]
  1014. # this treats the case when we are storing geometry as paths
  1015. geo_f = LineString(path)
  1016. if not geo_f.is_empty:
  1017. follow_buffer.append(geo_f)
  1018. geo_dict['follow'] = geo_f
  1019. # this treats the case when we are storing geometry as solids
  1020. buffered = LineString(path).buffer(width / 1.999, int(self.steps_per_circle))
  1021. if not buffered.is_empty:
  1022. if self.app.defaults['gerber_simplification']:
  1023. poly_buffer.append(buffered.simplify(s_tol))
  1024. else:
  1025. poly_buffer.append(buffered)
  1026. if self.is_lpc is True:
  1027. geo_dict['clear'] = buffered
  1028. else:
  1029. geo_dict['solid'] = buffered
  1030. if last_path_aperture not in self.apertures:
  1031. self.apertures[last_path_aperture] = dict()
  1032. if 'geometry' not in self.apertures[last_path_aperture]:
  1033. self.apertures[last_path_aperture]['geometry'] = []
  1034. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  1035. current_x = circular_x
  1036. current_y = circular_y
  1037. path = [[current_x, current_y]] # Start new path
  1038. continue
  1039. # Flash should not happen here
  1040. if current_operation_code == 3:
  1041. log.error("Trying to flash within arc. (%d)" % line_num)
  1042. continue
  1043. if quadrant_mode == 'MULTI':
  1044. center = [i + current_x, j + current_y]
  1045. radius = np.sqrt(i ** 2 + j ** 2)
  1046. start = np.arctan2(-j, -i) # Start angle
  1047. # Numerical errors might prevent start == stop therefore
  1048. # we check ahead of time. This should result in a
  1049. # 360 degree arc.
  1050. if current_x == circular_x and current_y == circular_y:
  1051. stop = start
  1052. else:
  1053. stop = np.arctan2(-center[1] + circular_y, -center[0] + circular_x) # Stop angle
  1054. this_arc = arc(center, radius, start, stop,
  1055. arcdir[current_interpolation_mode],
  1056. self.steps_per_circle)
  1057. # The last point in the computed arc can have
  1058. # numerical errors. The exact final point is the
  1059. # specified (x, y). Replace.
  1060. this_arc[-1] = (circular_x, circular_y)
  1061. # Last point in path is current point
  1062. # current_x = this_arc[-1][0]
  1063. # current_y = this_arc[-1][1]
  1064. current_x, current_y = circular_x, circular_y
  1065. # Append
  1066. path += this_arc
  1067. last_path_aperture = current_aperture
  1068. continue
  1069. if quadrant_mode == 'SINGLE':
  1070. center_candidates = [
  1071. [i + current_x, j + current_y],
  1072. [-i + current_x, j + current_y],
  1073. [i + current_x, -j + current_y],
  1074. [-i + current_x, -j + current_y]
  1075. ]
  1076. valid = False
  1077. log.debug("I: %f J: %f" % (i, j))
  1078. for center in center_candidates:
  1079. radius = np.sqrt(i ** 2 + j ** 2)
  1080. # Make sure radius to start is the same as radius to end.
  1081. radius2 = np.sqrt((center[0] - circular_x) ** 2 + (center[1] - circular_y) ** 2)
  1082. if radius2 < radius * 0.95 or radius2 > radius * 1.05:
  1083. continue # Not a valid center.
  1084. # Correct i and j and continue as with multi-quadrant.
  1085. i = center[0] - current_x
  1086. j = center[1] - current_y
  1087. start = np.arctan2(-j, -i) # Start angle
  1088. stop = np.arctan2(-center[1] + circular_y, -center[0] + circular_x) # Stop angle
  1089. angle = abs(arc_angle(start, stop, arcdir[current_interpolation_mode]))
  1090. log.debug("ARC START: %f, %f CENTER: %f, %f STOP: %f, %f" %
  1091. (current_x, current_y, center[0], center[1], circular_x, circular_y))
  1092. log.debug("START Ang: %f, STOP Ang: %f, DIR: %s, ABS: %.12f <= %.12f: %s" %
  1093. (start * 180 / np.pi, stop * 180 / np.pi, arcdir[current_interpolation_mode],
  1094. angle * 180 / np.pi, np.pi / 2 * 180 / np.pi, angle <= (np.pi + 1e-6) / 2))
  1095. if angle <= (np.pi + 1e-6) / 2:
  1096. log.debug("########## ACCEPTING ARC ############")
  1097. this_arc = arc(center, radius, start, stop,
  1098. arcdir[current_interpolation_mode],
  1099. self.steps_per_circle)
  1100. # Replace with exact values
  1101. this_arc[-1] = (circular_x, circular_y)
  1102. # current_x = this_arc[-1][0]
  1103. # current_y = this_arc[-1][1]
  1104. current_x, current_y = circular_x, circular_y
  1105. path += this_arc
  1106. last_path_aperture = current_aperture
  1107. valid = True
  1108. break
  1109. if valid:
  1110. continue
  1111. else:
  1112. log.warning("Invalid arc in line %d." % line_num)
  1113. # ## EOF
  1114. match = self.eof_re.search(gline)
  1115. if match:
  1116. continue
  1117. # ## Line did not match any pattern. Warn user.
  1118. log.warning("Line ignored (%d): %s" % (line_num, gline))
  1119. if len(path) > 1:
  1120. # In case that G01 (moving) aperture is rectangular, there is no need to still create
  1121. # another geo since we already created a shapely box using the start and end coordinates found in
  1122. # path variable. We do it only for other apertures than 'R' type
  1123. if self.apertures[last_path_aperture]["type"] == 'R':
  1124. pass
  1125. else:
  1126. # EOF, create shapely LineString if something still in path
  1127. # ## --- Buffered ---
  1128. geo_dict = dict()
  1129. # this treats the case when we are storing geometry as paths
  1130. geo_f = LineString(path)
  1131. if not geo_f.is_empty:
  1132. follow_buffer.append(geo_f)
  1133. geo_dict['follow'] = geo_f
  1134. # this treats the case when we are storing geometry as solids
  1135. width = self.apertures[last_path_aperture]["size"]
  1136. geo_s = LineString(path).buffer(width / 1.999, int(self.steps_per_circle / 4))
  1137. if not geo_s.is_empty:
  1138. if self.app.defaults['gerber_simplification']:
  1139. poly_buffer.append(geo_s.simplify(s_tol))
  1140. else:
  1141. poly_buffer.append(geo_s)
  1142. if self.is_lpc is True:
  1143. geo_dict['clear'] = geo_s
  1144. else:
  1145. geo_dict['solid'] = geo_s
  1146. if last_path_aperture not in self.apertures:
  1147. self.apertures[last_path_aperture] = dict()
  1148. if 'geometry' not in self.apertures[last_path_aperture]:
  1149. self.apertures[last_path_aperture]['geometry'] = []
  1150. self.apertures[last_path_aperture]['geometry'].append(deepcopy(geo_dict))
  1151. # --- Apply buffer ---
  1152. # this treats the case when we are storing geometry as paths
  1153. self.follow_geometry = follow_buffer
  1154. # this treats the case when we are storing geometry as solids
  1155. if len(poly_buffer) == 0 and len(self.solid_geometry) == 0:
  1156. log.error("Object is not Gerber file or empty. Aborting Object creation.")
  1157. return 'fail'
  1158. log.warning("Joining %d polygons." % len(poly_buffer))
  1159. self.app.inform.emit('%s: %d.' % (_("Gerber processing. Joining polygons"), len(poly_buffer)))
  1160. if self.use_buffer_for_union:
  1161. log.debug("Union by buffer...")
  1162. new_poly = MultiPolygon(poly_buffer)
  1163. if self.app.defaults["gerber_buffering"] == 'full':
  1164. new_poly = new_poly.buffer(0.00000001)
  1165. new_poly = new_poly.buffer(-0.00000001)
  1166. log.warning("Union(buffer) done.")
  1167. else:
  1168. log.debug("Union by union()...")
  1169. new_poly = cascaded_union(poly_buffer)
  1170. new_poly = new_poly.buffer(0, int(self.steps_per_circle / 4))
  1171. log.warning("Union done.")
  1172. if current_polarity == 'D':
  1173. self.app.inform.emit('%s' % _("Gerber processing. Applying Gerber polarity."))
  1174. if new_poly.is_valid:
  1175. self.solid_geometry = self.solid_geometry.union(new_poly)
  1176. else:
  1177. # I do this so whenever the parsed geometry of the file is not valid (intersections) it is still
  1178. # loaded. Instead of applying a union I add to a list of polygons.
  1179. final_poly = []
  1180. try:
  1181. for poly in new_poly:
  1182. final_poly.append(poly)
  1183. except TypeError:
  1184. final_poly.append(new_poly)
  1185. try:
  1186. for poly in self.solid_geometry:
  1187. final_poly.append(poly)
  1188. except TypeError:
  1189. final_poly.append(self.solid_geometry)
  1190. self.solid_geometry = final_poly
  1191. # try:
  1192. # self.solid_geometry = self.solid_geometry.union(new_poly)
  1193. # except Exception as e:
  1194. # # in case in the new_poly are some self intersections try to avoid making union with them
  1195. # for poly in new_poly:
  1196. # try:
  1197. # self.solid_geometry = self.solid_geometry.union(poly)
  1198. # except Exception:
  1199. # pass
  1200. else:
  1201. self.solid_geometry = self.solid_geometry.difference(new_poly)
  1202. # init this for the following operations
  1203. self.conversion_done = False
  1204. except Exception as err:
  1205. ex_type, ex, tb = sys.exc_info()
  1206. traceback.print_tb(tb)
  1207. # print traceback.format_exc()
  1208. log.error("Gerber PARSING FAILED. Line %d: %s" % (line_num, gline))
  1209. loc = '%s #%d %s: %s\n' % (_("Gerber Line"), line_num, _("Gerber Line Content"), gline) + repr(err)
  1210. self.app.inform.emit('[ERROR] %s\n%s:' %
  1211. (_("Gerber Parser ERROR"), loc))
  1212. @staticmethod
  1213. def create_flash_geometry(location, aperture, steps_per_circle=None):
  1214. # log.debug('Flashing @%s, Aperture: %s' % (location, aperture))
  1215. if type(location) == list:
  1216. location = Point(location)
  1217. if aperture['type'] == 'C': # Circles
  1218. return location.buffer(aperture['size'] / 2, int(steps_per_circle / 4))
  1219. if aperture['type'] == 'R': # Rectangles
  1220. loc = location.coords[0]
  1221. width = aperture['width']
  1222. height = aperture['height']
  1223. minx = loc[0] - width / 2
  1224. maxx = loc[0] + width / 2
  1225. miny = loc[1] - height / 2
  1226. maxy = loc[1] + height / 2
  1227. return shply_box(minx, miny, maxx, maxy)
  1228. if aperture['type'] == 'O': # Obround
  1229. loc = location.coords[0]
  1230. width = aperture['width']
  1231. height = aperture['height']
  1232. if width > height:
  1233. p1 = Point(loc[0] + 0.5 * (width - height), loc[1])
  1234. p2 = Point(loc[0] - 0.5 * (width - height), loc[1])
  1235. c1 = p1.buffer(height * 0.5, int(steps_per_circle / 4))
  1236. c2 = p2.buffer(height * 0.5, int(steps_per_circle / 4))
  1237. else:
  1238. p1 = Point(loc[0], loc[1] + 0.5 * (height - width))
  1239. p2 = Point(loc[0], loc[1] - 0.5 * (height - width))
  1240. c1 = p1.buffer(width * 0.5, int(steps_per_circle / 4))
  1241. c2 = p2.buffer(width * 0.5, int(steps_per_circle / 4))
  1242. return cascaded_union([c1, c2]).convex_hull
  1243. if aperture['type'] == 'P': # Regular polygon
  1244. loc = location.coords[0]
  1245. diam = aperture['diam']
  1246. n_vertices = aperture['nVertices']
  1247. points = []
  1248. for i in range(0, n_vertices):
  1249. x = loc[0] + 0.5 * diam * (np.cos(2 * np.pi * i / n_vertices))
  1250. y = loc[1] + 0.5 * diam * (np.sin(2 * np.pi * i / n_vertices))
  1251. points.append((x, y))
  1252. ply = Polygon(points)
  1253. if 'rotation' in aperture:
  1254. ply = affinity.rotate(ply, aperture['rotation'])
  1255. return ply
  1256. if aperture['type'] == 'AM': # Aperture Macro
  1257. loc = location.coords[0]
  1258. flash_geo = aperture['macro'].make_geometry(aperture['modifiers'])
  1259. if flash_geo.is_empty:
  1260. log.warning("Empty geometry for Aperture Macro: %s" % str(aperture['macro'].name))
  1261. return affinity.translate(flash_geo, xoff=loc[0], yoff=loc[1])
  1262. log.warning("Unknown aperture type: %s" % aperture['type'])
  1263. return None
  1264. def create_geometry(self):
  1265. """
  1266. Geometry from a Gerber file is made up entirely of polygons.
  1267. Every stroke (linear or circular) has an aperture which gives
  1268. it thickness. Additionally, aperture strokes have non-zero area,
  1269. and regions naturally do as well.
  1270. :rtype : None
  1271. :return: None
  1272. """
  1273. pass
  1274. # self.buffer_paths()
  1275. #
  1276. # self.fix_regions()
  1277. #
  1278. # self.do_flashes()
  1279. #
  1280. # self.solid_geometry = cascaded_union(self.buffered_paths +
  1281. # [poly['polygon'] for poly in self.regions] +
  1282. # self.flash_geometry)
  1283. def get_bounding_box(self, margin=0.0, rounded=False):
  1284. """
  1285. Creates and returns a rectangular polygon bounding at a distance of
  1286. margin from the object's ``solid_geometry``. If margin > 0, the polygon
  1287. can optionally have rounded corners of radius equal to margin.
  1288. :param margin: Distance to enlarge the rectangular bounding
  1289. box in both positive and negative, x and y axes.
  1290. :type margin: float
  1291. :param rounded: Wether or not to have rounded corners.
  1292. :type rounded: bool
  1293. :return: The bounding box.
  1294. :rtype: Shapely.Polygon
  1295. """
  1296. bbox = self.solid_geometry.envelope.buffer(margin)
  1297. if not rounded:
  1298. bbox = bbox.envelope
  1299. return bbox
  1300. def bounds(self):
  1301. """
  1302. Returns coordinates of rectangular bounds
  1303. of Gerber geometry: (xmin, ymin, xmax, ymax).
  1304. """
  1305. # fixed issue of getting bounds only for one level lists of objects
  1306. # now it can get bounds for nested lists of objects
  1307. log.debug("parseGerber.Gerber.bounds()")
  1308. if self.solid_geometry is None:
  1309. log.debug("solid_geometry is None")
  1310. return 0, 0, 0, 0
  1311. def bounds_rec(obj):
  1312. if type(obj) is list and type(obj) is not MultiPolygon:
  1313. minx = np.Inf
  1314. miny = np.Inf
  1315. maxx = -np.Inf
  1316. maxy = -np.Inf
  1317. for k in obj:
  1318. if type(k) is dict:
  1319. for key in k:
  1320. minx_, miny_, maxx_, maxy_ = bounds_rec(k[key])
  1321. minx = min(minx, minx_)
  1322. miny = min(miny, miny_)
  1323. maxx = max(maxx, maxx_)
  1324. maxy = max(maxy, maxy_)
  1325. else:
  1326. if not k.is_empty:
  1327. try:
  1328. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1329. except Exception as e:
  1330. log.debug("camlib.Gerber.bounds() --> %s" % str(e))
  1331. return
  1332. minx = min(minx, minx_)
  1333. miny = min(miny, miny_)
  1334. maxx = max(maxx, maxx_)
  1335. maxy = max(maxy, maxy_)
  1336. return minx, miny, maxx, maxy
  1337. else:
  1338. # it's a Shapely object, return it's bounds
  1339. return obj.bounds
  1340. bounds_coords = bounds_rec(self.solid_geometry)
  1341. return bounds_coords
  1342. def convert_units(self, obj_units):
  1343. """
  1344. Converts the units of the object to ``units`` by scaling all
  1345. the geometry appropriately. This call ``scale()``. Don't call
  1346. it again in descendants.
  1347. :param obj_units: "IN" or "MM"
  1348. :type obj_units: str
  1349. :return: Scaling factor resulting from unit change.
  1350. :rtype: float
  1351. """
  1352. if obj_units.upper() == self.units.upper():
  1353. log.debug("parseGerber.Gerber.convert_units() --> Factor: 1")
  1354. return 1.0
  1355. if obj_units.upper() == "MM":
  1356. factor = 25.4
  1357. log.debug("parseGerber.Gerber.convert_units() --> Factor: 25.4")
  1358. elif obj_units.upper() == "IN":
  1359. factor = 1 / 25.4
  1360. log.debug("parseGerber.Gerber.convert_units() --> Factor: %s" % str(1 / 25.4))
  1361. else:
  1362. log.error("Unsupported units: %s" % str(obj_units))
  1363. log.debug("parseGerber.Gerber.convert_units() --> Factor: 1")
  1364. return 1.0
  1365. self.units = obj_units
  1366. self.file_units_factor = factor
  1367. self.scale(factor, factor)
  1368. return factor
  1369. def import_svg(self, filename, object_type='gerber', flip=True, units='MM'):
  1370. """
  1371. Imports shapes from an SVG file into the object's geometry.
  1372. :param filename: Path to the SVG file.
  1373. :type filename: str
  1374. :param object_type: parameter passed further along
  1375. :param flip: Flip the vertically.
  1376. :type flip: bool
  1377. :param units: FlatCAM units
  1378. :return: None
  1379. """
  1380. log.debug("flatcamParsers.ParseGerber.Gerber.import_svg()")
  1381. # Parse into list of shapely objects
  1382. svg_tree = ET.parse(filename)
  1383. svg_root = svg_tree.getroot()
  1384. # Change origin to bottom left
  1385. # h = float(svg_root.get('height'))
  1386. # w = float(svg_root.get('width'))
  1387. h = svgparselength(svg_root.get('height'))[0] # TODO: No units support yet
  1388. geos = getsvggeo(svg_root, 'gerber')
  1389. if flip:
  1390. geos = [translate(scale(g, 1.0, -1.0, origin=(0, 0)), yoff=h) for g in geos]
  1391. # Add to object
  1392. if self.solid_geometry is None:
  1393. self.solid_geometry = list()
  1394. # if type(self.solid_geometry) == list:
  1395. # if type(geos) == list:
  1396. # self.solid_geometry += geos
  1397. # else:
  1398. # self.solid_geometry.append(geos)
  1399. # else: # It's shapely geometry
  1400. # self.solid_geometry = [self.solid_geometry, geos]
  1401. if type(geos) == list:
  1402. # HACK for importing QRCODE exported by FlatCAM
  1403. if len(geos) == 1:
  1404. geo_qrcode = list()
  1405. geo_qrcode.append(Polygon(geos[0].exterior))
  1406. for i_el in geos[0].interiors:
  1407. geo_qrcode.append(Polygon(i_el).buffer(0))
  1408. for poly in geo_qrcode:
  1409. geos.append(poly)
  1410. if type(self.solid_geometry) == list:
  1411. self.solid_geometry += geos
  1412. else:
  1413. geos.append(self.solid_geometry)
  1414. self.solid_geometry = geos
  1415. else:
  1416. if type(self.solid_geometry) == list:
  1417. self.solid_geometry.append(geos)
  1418. else:
  1419. self.solid_geometry = [self.solid_geometry, geos]
  1420. # flatten the self.solid_geometry list for import_svg() to import SVG as Gerber
  1421. self.solid_geometry = list(self.flatten_list(self.solid_geometry))
  1422. try:
  1423. __ = iter(self.solid_geometry)
  1424. except TypeError:
  1425. self.solid_geometry = [self.solid_geometry]
  1426. if '0' not in self.apertures:
  1427. self.apertures['0'] = dict()
  1428. self.apertures['0']['type'] = 'REG'
  1429. self.apertures['0']['size'] = 0.0
  1430. self.apertures['0']['geometry'] = list()
  1431. for pol in self.solid_geometry:
  1432. new_el = dict()
  1433. new_el['solid'] = pol
  1434. new_el['follow'] = pol.exterior
  1435. self.apertures['0']['geometry'].append(deepcopy(new_el))
  1436. def scale(self, xfactor, yfactor=None, point=None):
  1437. """
  1438. Scales the objects' geometry on the XY plane by a given factor.
  1439. These are:
  1440. * ``buffered_paths``
  1441. * ``flash_geometry``
  1442. * ``solid_geometry``
  1443. * ``regions``
  1444. NOTE:
  1445. Does not modify the data used to create these elements. If these
  1446. are recreated, the scaling will be lost. This behavior was modified
  1447. because of the complexity reached in this class.
  1448. :param xfactor: Number by which to scale on X axis.
  1449. :type xfactor: float
  1450. :param yfactor: Number by which to scale on Y axis.
  1451. :type yfactor: float
  1452. :param point: reference point for scaling operation
  1453. :rtype : None
  1454. """
  1455. log.debug("parseGerber.Gerber.scale()")
  1456. try:
  1457. xfactor = float(xfactor)
  1458. except Exception:
  1459. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1460. _("Scale factor has to be a number: integer or float."))
  1461. return
  1462. if yfactor is None:
  1463. yfactor = xfactor
  1464. else:
  1465. try:
  1466. yfactor = float(yfactor)
  1467. except Exception:
  1468. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1469. _("Scale factor has to be a number: integer or float."))
  1470. return
  1471. if xfactor == 0 and yfactor == 0:
  1472. return
  1473. if point is None:
  1474. px = 0
  1475. py = 0
  1476. else:
  1477. px, py = point
  1478. # variables to display the percentage of work done
  1479. self.geo_len = 0
  1480. try:
  1481. self.geo_len = len(self.solid_geometry)
  1482. except TypeError:
  1483. self.geo_len = 1
  1484. self.old_disp_number = 0
  1485. self.el_count = 0
  1486. def scale_geom(obj):
  1487. if type(obj) is list:
  1488. new_obj = []
  1489. for g in obj:
  1490. new_obj.append(scale_geom(g))
  1491. return new_obj
  1492. else:
  1493. try:
  1494. self.el_count += 1
  1495. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 99]))
  1496. if self.old_disp_number < disp_number <= 100:
  1497. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1498. self.old_disp_number = disp_number
  1499. return affinity.scale(obj, xfactor, yfactor, origin=(px, py))
  1500. except AttributeError:
  1501. return obj
  1502. self.solid_geometry = scale_geom(self.solid_geometry)
  1503. self.follow_geometry = scale_geom(self.follow_geometry)
  1504. # we need to scale the geometry stored in the Gerber apertures, too
  1505. try:
  1506. for apid in self.apertures:
  1507. new_geometry = list()
  1508. if 'geometry' in self.apertures[apid]:
  1509. for geo_el in self.apertures[apid]['geometry']:
  1510. new_geo_el = dict()
  1511. if 'solid' in geo_el:
  1512. new_geo_el['solid'] = scale_geom(geo_el['solid'])
  1513. if 'follow' in geo_el:
  1514. new_geo_el['follow'] = scale_geom(geo_el['follow'])
  1515. if 'clear' in geo_el:
  1516. new_geo_el['clear'] = scale_geom(geo_el['clear'])
  1517. new_geometry.append(new_geo_el)
  1518. self.apertures[apid]['geometry'] = deepcopy(new_geometry)
  1519. try:
  1520. if str(self.apertures[apid]['type']) == 'R' or str(self.apertures[apid]['type']) == 'O':
  1521. self.apertures[apid]['width'] *= xfactor
  1522. self.apertures[apid]['height'] *= xfactor
  1523. elif str(self.apertures[apid]['type']) == 'P':
  1524. self.apertures[apid]['diam'] *= xfactor
  1525. self.apertures[apid]['nVertices'] *= xfactor
  1526. except KeyError:
  1527. pass
  1528. try:
  1529. if self.apertures[apid]['size'] is not None:
  1530. self.apertures[apid]['size'] = float(self.apertures[apid]['size'] * xfactor)
  1531. except KeyError:
  1532. pass
  1533. except Exception as e:
  1534. log.debug('camlib.Gerber.scale() Exception --> %s' % str(e))
  1535. return 'fail'
  1536. self.app.inform.emit('[success] %s' % _("Gerber Scale done."))
  1537. self.app.proc_container.new_text = ''
  1538. # ## solid_geometry ???
  1539. # It's a cascaded union of objects.
  1540. # self.solid_geometry = affinity.scale(self.solid_geometry, factor,
  1541. # factor, origin=(0, 0))
  1542. # # Now buffered_paths, flash_geometry and solid_geometry
  1543. # self.create_geometry()
  1544. def offset(self, vect):
  1545. """
  1546. Offsets the objects' geometry on the XY plane by a given vector.
  1547. These are:
  1548. * ``buffered_paths``
  1549. * ``flash_geometry``
  1550. * ``solid_geometry``
  1551. * ``regions``
  1552. NOTE:
  1553. Does not modify the data used to create these elements. If these
  1554. are recreated, the scaling will be lost. This behavior was modified
  1555. because of the complexity reached in this class.
  1556. :param vect: (x, y) offset vector.
  1557. :type vect: tuple
  1558. :return: None
  1559. """
  1560. log.debug("parseGerber.Gerber.offset()")
  1561. try:
  1562. dx, dy = vect
  1563. except TypeError:
  1564. self.app.inform.emit('[ERROR_NOTCL] %s' %
  1565. _("An (x,y) pair of values are needed. "
  1566. "Probable you entered only one value in the Offset field."))
  1567. return
  1568. if dx == 0 and dy == 0:
  1569. return
  1570. # variables to display the percentage of work done
  1571. self.geo_len = 0
  1572. try:
  1573. for __ in self.solid_geometry:
  1574. self.geo_len += 1
  1575. except TypeError:
  1576. self.geo_len = 1
  1577. self.old_disp_number = 0
  1578. self.el_count = 0
  1579. def offset_geom(obj):
  1580. if type(obj) is list:
  1581. new_obj = []
  1582. for g in obj:
  1583. new_obj.append(offset_geom(g))
  1584. return new_obj
  1585. else:
  1586. try:
  1587. self.el_count += 1
  1588. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 99]))
  1589. if self.old_disp_number < disp_number <= 100:
  1590. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1591. self.old_disp_number = disp_number
  1592. return affinity.translate(obj, xoff=dx, yoff=dy)
  1593. except AttributeError:
  1594. return obj
  1595. # ## Solid geometry
  1596. self.solid_geometry = offset_geom(self.solid_geometry)
  1597. self.follow_geometry = offset_geom(self.follow_geometry)
  1598. # we need to offset the geometry stored in the Gerber apertures, too
  1599. try:
  1600. for apid in self.apertures:
  1601. if 'geometry' in self.apertures[apid]:
  1602. for geo_el in self.apertures[apid]['geometry']:
  1603. if 'solid' in geo_el:
  1604. geo_el['solid'] = offset_geom(geo_el['solid'])
  1605. if 'follow' in geo_el:
  1606. geo_el['follow'] = offset_geom(geo_el['follow'])
  1607. if 'clear' in geo_el:
  1608. geo_el['clear'] = offset_geom(geo_el['clear'])
  1609. except Exception as e:
  1610. log.debug('camlib.Gerber.offset() Exception --> %s' % str(e))
  1611. return 'fail'
  1612. self.app.inform.emit('[success] %s' %
  1613. _("Gerber Offset done."))
  1614. self.app.proc_container.new_text = ''
  1615. def mirror(self, axis, point):
  1616. """
  1617. Mirrors the object around a specified axis passing through
  1618. the given point. What is affected:
  1619. * ``buffered_paths``
  1620. * ``flash_geometry``
  1621. * ``solid_geometry``
  1622. * ``regions``
  1623. NOTE:
  1624. Does not modify the data used to create these elements. If these
  1625. are recreated, the scaling will be lost. This behavior was modified
  1626. because of the complexity reached in this class.
  1627. :param axis: "X" or "Y" indicates around which axis to mirror.
  1628. :type axis: str
  1629. :param point: [x, y] point belonging to the mirror axis.
  1630. :type point: list
  1631. :return: None
  1632. """
  1633. log.debug("parseGerber.Gerber.mirror()")
  1634. px, py = point
  1635. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1636. # variables to display the percentage of work done
  1637. self.geo_len = 0
  1638. try:
  1639. for __ in self.solid_geometry:
  1640. self.geo_len += 1
  1641. except TypeError:
  1642. self.geo_len = 1
  1643. self.old_disp_number = 0
  1644. self.el_count = 0
  1645. def mirror_geom(obj):
  1646. if type(obj) is list:
  1647. new_obj = []
  1648. for g in obj:
  1649. new_obj.append(mirror_geom(g))
  1650. return new_obj
  1651. else:
  1652. try:
  1653. self.el_count += 1
  1654. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 99]))
  1655. if self.old_disp_number < disp_number <= 100:
  1656. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1657. self.old_disp_number = disp_number
  1658. return affinity.scale(obj, xscale, yscale, origin=(px, py))
  1659. except AttributeError:
  1660. return obj
  1661. self.solid_geometry = mirror_geom(self.solid_geometry)
  1662. self.follow_geometry = mirror_geom(self.follow_geometry)
  1663. # we need to mirror the geometry stored in the Gerber apertures, too
  1664. try:
  1665. for apid in self.apertures:
  1666. if 'geometry' in self.apertures[apid]:
  1667. for geo_el in self.apertures[apid]['geometry']:
  1668. if 'solid' in geo_el:
  1669. geo_el['solid'] = mirror_geom(geo_el['solid'])
  1670. if 'follow' in geo_el:
  1671. geo_el['follow'] = mirror_geom(geo_el['follow'])
  1672. if 'clear' in geo_el:
  1673. geo_el['clear'] = mirror_geom(geo_el['clear'])
  1674. except Exception as e:
  1675. log.debug('camlib.Gerber.mirror() Exception --> %s' % str(e))
  1676. return 'fail'
  1677. self.app.inform.emit('[success] %s' %
  1678. _("Gerber Mirror done."))
  1679. self.app.proc_container.new_text = ''
  1680. def skew(self, angle_x, angle_y, point):
  1681. """
  1682. Shear/Skew the geometries of an object by angles along x and y dimensions.
  1683. Parameters
  1684. ----------
  1685. angle_x, angle_y : float, float
  1686. The shear angle(s) for the x and y axes respectively. These can be
  1687. specified in either degrees (default) or radians by setting
  1688. use_radians=True.
  1689. See shapely manual for more information:
  1690. http://toblerity.org/shapely/manual.html#affine-transformations
  1691. :param angle_x: the angle on X axis for skewing
  1692. :param angle_y: the angle on Y axis for skewing
  1693. :param point: reference point for skewing operation
  1694. :return None
  1695. """
  1696. log.debug("parseGerber.Gerber.skew()")
  1697. px, py = point
  1698. if angle_x == 0 and angle_y == 0:
  1699. return
  1700. # variables to display the percentage of work done
  1701. self.geo_len = 0
  1702. try:
  1703. self.geo_len = len(self.solid_geometry)
  1704. except TypeError:
  1705. self.geo_len = 1
  1706. self.old_disp_number = 0
  1707. self.el_count = 0
  1708. def skew_geom(obj):
  1709. if type(obj) is list:
  1710. new_obj = []
  1711. for g in obj:
  1712. new_obj.append(skew_geom(g))
  1713. return new_obj
  1714. else:
  1715. try:
  1716. self.el_count += 1
  1717. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1718. if self.old_disp_number < disp_number <= 100:
  1719. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1720. self.old_disp_number = disp_number
  1721. return affinity.skew(obj, angle_x, angle_y, origin=(px, py))
  1722. except AttributeError:
  1723. return obj
  1724. self.solid_geometry = skew_geom(self.solid_geometry)
  1725. self.follow_geometry = skew_geom(self.follow_geometry)
  1726. # we need to skew the geometry stored in the Gerber apertures, too
  1727. try:
  1728. for apid in self.apertures:
  1729. if 'geometry' in self.apertures[apid]:
  1730. for geo_el in self.apertures[apid]['geometry']:
  1731. if 'solid' in geo_el:
  1732. geo_el['solid'] = skew_geom(geo_el['solid'])
  1733. if 'follow' in geo_el:
  1734. geo_el['follow'] = skew_geom(geo_el['follow'])
  1735. if 'clear' in geo_el:
  1736. geo_el['clear'] = skew_geom(geo_el['clear'])
  1737. except Exception as e:
  1738. log.debug('camlib.Gerber.skew() Exception --> %s' % str(e))
  1739. return 'fail'
  1740. self.app.inform.emit('[success] %s' % _("Gerber Skew done."))
  1741. self.app.proc_container.new_text = ''
  1742. def rotate(self, angle, point):
  1743. """
  1744. Rotate an object by a given angle around given coords (point)
  1745. :param angle:
  1746. :param point:
  1747. :return:
  1748. """
  1749. log.debug("parseGerber.Gerber.rotate()")
  1750. px, py = point
  1751. if angle == 0:
  1752. return
  1753. # variables to display the percentage of work done
  1754. self.geo_len = 0
  1755. try:
  1756. for __ in self.solid_geometry:
  1757. self.geo_len += 1
  1758. except TypeError:
  1759. self.geo_len = 1
  1760. self.old_disp_number = 0
  1761. self.el_count = 0
  1762. def rotate_geom(obj):
  1763. if type(obj) is list:
  1764. new_obj = []
  1765. for g in obj:
  1766. new_obj.append(rotate_geom(g))
  1767. return new_obj
  1768. else:
  1769. try:
  1770. self.el_count += 1
  1771. disp_number = int(np.interp(self.el_count, [0, self.geo_len], [0, 100]))
  1772. if self.old_disp_number < disp_number <= 100:
  1773. self.app.proc_container.update_view_text(' %d%%' % disp_number)
  1774. self.old_disp_number = disp_number
  1775. return affinity.rotate(obj, angle, origin=(px, py))
  1776. except AttributeError:
  1777. return obj
  1778. self.solid_geometry = rotate_geom(self.solid_geometry)
  1779. self.follow_geometry = rotate_geom(self.follow_geometry)
  1780. # we need to rotate the geometry stored in the Gerber apertures, too
  1781. try:
  1782. for apid in self.apertures:
  1783. if 'geometry' in self.apertures[apid]:
  1784. for geo_el in self.apertures[apid]['geometry']:
  1785. if 'solid' in geo_el:
  1786. geo_el['solid'] = rotate_geom(geo_el['solid'])
  1787. if 'follow' in geo_el:
  1788. geo_el['follow'] = rotate_geom(geo_el['follow'])
  1789. if 'clear' in geo_el:
  1790. geo_el['clear'] = rotate_geom(geo_el['clear'])
  1791. except Exception as e:
  1792. log.debug('camlib.Gerber.rotate() Exception --> %s' % str(e))
  1793. return 'fail'
  1794. self.app.inform.emit('[success] %s' %
  1795. _("Gerber Rotate done."))
  1796. self.app.proc_container.new_text = ''
  1797. def parse_gerber_number(strnumber, int_digits, frac_digits, zeros):
  1798. """
  1799. Parse a single number of Gerber coordinates.
  1800. :param strnumber: String containing a number in decimal digits
  1801. from a coordinate data block, possibly with a leading sign.
  1802. :type strnumber: str
  1803. :param int_digits: Number of digits used for the integer
  1804. part of the number
  1805. :type frac_digits: int
  1806. :param frac_digits: Number of digits used for the fractional
  1807. part of the number
  1808. :type frac_digits: int
  1809. :param zeros: If 'L', leading zeros are removed and trailing zeros are kept. Same situation for 'D' when
  1810. no zero suppression is done. If 'T', is in reverse.
  1811. :type zeros: str
  1812. :return: The number in floating point.
  1813. :rtype: float
  1814. """
  1815. ret_val = None
  1816. if zeros == 'L' or zeros == 'D':
  1817. ret_val = int(strnumber) * (10 ** (-frac_digits))
  1818. if zeros == 'T':
  1819. int_val = int(strnumber)
  1820. ret_val = (int_val * (10 ** ((int_digits + frac_digits) - len(strnumber)))) * (10 ** (-frac_digits))
  1821. return ret_val