ParseGerber.py 106 KB

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