ParseGerber.py 110 KB

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