ParseGerber.py 109 KB

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