ParseGerber.py 113 KB

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