PageRenderTime 75ms CodeModel.GetById 33ms RepoModel.GetById 1ms app.codeStats 0ms

/Program_Files/replicatorg-0025/skein_engines/skeinforge-35/skeinforge_application/skeinforge_plugins/analyze_plugins/vectorwrite.py

https://github.com/sialan/autonomous-sprayer
Python | 324 lines | 302 code | 11 blank | 11 comment | 3 complexity | ced8d25d6f5b2487aee2e5783ba77e1d MD5 | raw file
  1. """
  2. This page is in the table of contents.
  3. Vectorwrite is a script to write Scalable Vector Graphics for a gcode file.
  4. The vectorwrite manual page is at:
  5. http://www.bitsfrombytes.com/wiki/index.php?title=Skeinforge_Vectorwrite
  6. Vectorwrite generates a Scalable Vector Graphics file which can be opened by an SVG viewer or an SVG capable browser like Mozilla:
  7. http://www.mozilla.com/firefox/
  8. ==Operation==
  9. The default 'Activate Vectorwrite' checkbox is on. When it is on, the functions described below will work when called from the skeinforge toolchain, when it is off, the functions will not be called from the toolchain. The functions will still be called, whether or not the 'Activate Vectorwrite' checkbox is on, when vectorwrite is run directly.
  10. ==Settings==
  11. ===Layers===
  12. ====Layers From====
  13. Default is zero.
  14. The "Layers From" is the index of the bottom layer that will be displayed. If the layer from is the default zero, the display will start from the lowest layer. If the the layer from index is negative, then the display will start from the layer from index below the top layer.
  15. ====Layers To====
  16. Default is a huge number, which will be limited to the highest index layer.
  17. The "Layers To" is the index of the top layer that will be displayed. If the layer to index is a huge number like the default, the display will go to the top of the model, at least until we model habitats:) If the layer to index is negative, then the display will go to the layer to index below the top layer. The layer from until layer to index is a python slice.
  18. ===SVG Viewer===
  19. Default is webbrowser.
  20. If the 'SVG Viewer' is set to the default 'webbrowser', the scalable vector graphics file will be sent to the default browser to be opened. If the 'SVG Viewer' is set to a program name, the scalable vector graphics file will be sent to that program to be opened.
  21. ==Examples==
  22. Below are examples of vectorwrite being used. These examples are run in a terminal in the folder which contains Screw Holder_penultimate.gcode and vectorwrite.py.
  23. > python vectorwrite.py
  24. This brings up the vectorwrite dialog.
  25. > python vectorwrite.py Screw Holder_penultimate.gcode
  26. The vectorwrite file is saved as Screw_Holder_penultimate_vectorwrite.svg
  27. > python
  28. Python 2.5.1 (r251:54863, Sep 22 2007, 01:43:31)
  29. [GCC 4.2.1 (SUSE Linux)] on linux2
  30. Type "help", "copyright", "credits" or "license" for more information.
  31. >>> import vectorwrite
  32. >>> vectorwrite.main()
  33. This brings up the vectorwrite dialog.
  34. >>> vectorwrite.getWindowAnalyzeFile('Screw Holder_penultimate.gcode')
  35. The vectorwrite file is saved as Screw_Holder_penultimate_vectorwrite.svg
  36. """
  37. from __future__ import absolute_import
  38. #Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
  39. import __init__
  40. from fabmetheus_utilities.vector3 import Vector3
  41. from fabmetheus_utilities import archive
  42. from fabmetheus_utilities import euclidean
  43. from fabmetheus_utilities import gcodec
  44. from fabmetheus_utilities import settings
  45. from fabmetheus_utilities import svg_writer
  46. from skeinforge_application.skeinforge_utilities import skeinforge_polyfile
  47. from skeinforge_application.skeinforge_utilities import skeinforge_profile
  48. import cStringIO
  49. import os
  50. import sys
  51. import time
  52. __author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
  53. __credits__ = 'Nophead <http://hydraraptor.blogspot.com/>'
  54. __date__ = '$Date: 2008/21/04 $'
  55. __license__ = 'GPL 3.0'
  56. def getNewRepository():
  57. "Get the repository constructor."
  58. return VectorwriteRepository()
  59. def getWindowAnalyzeFile(fileName):
  60. "Write scalable vector graphics for a gcode file."
  61. gcodeText = archive.getFileText(fileName)
  62. return getWindowAnalyzeFileGivenText(fileName, gcodeText)
  63. def getWindowAnalyzeFileGivenText( fileName, gcodeText, repository=None):
  64. "Write scalable vector graphics for a gcode file given the settings."
  65. if gcodeText == '':
  66. return None
  67. if repository == None:
  68. repository = settings.getReadRepository( VectorwriteRepository() )
  69. startTime = time.time()
  70. vectorwriteGcode = VectorwriteSkein().getCarvedSVG( fileName, gcodeText, repository )
  71. if vectorwriteGcode == '':
  72. return None
  73. suffixFileName = fileName[ : fileName.rfind('.') ] + '_vectorwrite.svg'
  74. suffixDirectoryName = os.path.dirname(suffixFileName)
  75. suffixReplacedBaseName = os.path.basename(suffixFileName).replace(' ', '_')
  76. suffixFileName = os.path.join( suffixDirectoryName, suffixReplacedBaseName )
  77. archive.writeFileText( suffixFileName, vectorwriteGcode )
  78. print('The vectorwrite file is saved as ' + archive.getSummarizedFileName(suffixFileName) )
  79. print('It took %s to vectorwrite the file.' % euclidean.getDurationString( time.time() - startTime ) )
  80. settings.openSVGPage( suffixFileName, repository.svgViewer.value )
  81. def writeOutput( fileName, fileNameSuffix, gcodeText = ''):
  82. "Write scalable vector graphics for a skeinforge gcode file, if activate vectorwrite is selected."
  83. repository = settings.getReadRepository( VectorwriteRepository() )
  84. if not repository.activateVectorwrite.value:
  85. return
  86. gcodeText = archive.getTextIfEmpty( fileNameSuffix, gcodeText )
  87. getWindowAnalyzeFileGivenText( fileNameSuffix, gcodeText, repository )
  88. class SVGWriterVectorwrite( svg_writer.SVGWriter ):
  89. "A class to vectorwrite a carving."
  90. def addPaths( self, colorName, paths, transformString ):
  91. "Add paths to the output."
  92. pathString = ''
  93. for path in paths:
  94. pathString += self.getSVGStringForPath(path) + ' '
  95. if len( pathString ) < 1:
  96. return
  97. pathXMLElementCopy = self.pathXMLElement.getCopy('', self.pathXMLElement.parent )
  98. pathCopyDictionary = pathXMLElementCopy.attributeDictionary
  99. pathCopyDictionary['d'] = pathString[ : - 1 ]
  100. pathCopyDictionary['fill'] = 'none'
  101. pathCopyDictionary['stroke'] = colorName
  102. pathCopyDictionary['transform'] = transformString
  103. def addRotatedLoopLayerToOutput( self, layerIndex, rotatedBoundaryLayer ):
  104. "Add rotated boundary layer to the output."
  105. self.addLayerBegin( layerIndex, rotatedBoundaryLayer )
  106. transformString = self.getTransformString()
  107. self.pathDictionary['d'] = self.getSVGStringForLoops( rotatedBoundaryLayer.boundaryLoops )
  108. self.pathDictionary['transform'] = transformString
  109. self.addPaths('#fa0', rotatedBoundaryLayer.innerPerimeters, transformString ) #orange
  110. self.addPaths('#ff0', rotatedBoundaryLayer.loops, transformString ) #yellow
  111. self.addPaths('#f00', rotatedBoundaryLayer.outerPerimeters, transformString ) #red
  112. self.addPaths('#f5c', rotatedBoundaryLayer.paths, transformString ) #light violetred
  113. class ThreadLayer:
  114. "Threads with a z."
  115. def __init__( self, z ):
  116. self.boundaryLoops = []
  117. self.innerPerimeters = []
  118. self.loops = []
  119. self.outerPerimeters = []
  120. self.paths = []
  121. self.z = z
  122. def __repr__(self):
  123. "Get the string representation of this loop layer."
  124. return '%s, %s' % ( self.innerLoops, self.innerPerimeters, self.outerLoops, self.outerPerimeters, self.paths, self.z )
  125. class VectorwriteRepository:
  126. "A class to handle the vectorwrite settings."
  127. def __init__(self):
  128. "Set the default settings, execute title & settings fileName."
  129. skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.analyze_plugins.vectorwrite.html', self )
  130. self.activateVectorwrite = settings.BooleanSetting().getFromValue('Activate Vectorwrite', self, False )
  131. self.fileNameInput = settings.FileNameInput().getFromFileName( [ ('Gcode text files', '*.gcode') ], 'Open File to Write Vector Graphics for', self, '')
  132. self.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('http://www.bitsfrombytes.com/wiki/index.php?title=Skeinforge_Vectorwrite')
  133. settings.LabelSeparator().getFromRepository(self)
  134. settings.LabelDisplay().getFromName('- Layers -', self )
  135. self.layersFrom = settings.IntSpin().getFromValue( 0, 'Layers From (index):', self, 20, 0 )
  136. self.layersTo = settings.IntSpin().getSingleIncrementFromValue( 0, 'Layers To (index):', self, 912345678, 912345678 )
  137. settings.LabelSeparator().getFromRepository(self)
  138. self.svgViewer = settings.StringSetting().getFromValue('SVG Viewer:', self, 'webbrowser')
  139. settings.LabelSeparator().getFromRepository(self)
  140. self.executeTitle = 'Vectorwrite'
  141. def execute(self):
  142. "Write button has been clicked."
  143. fileNames = skeinforge_polyfile.getFileOrGcodeDirectory( self.fileNameInput.value, self.fileNameInput.wasCancelled )
  144. for fileName in fileNames:
  145. getWindowAnalyzeFile(fileName)
  146. class VectorwriteSkein:
  147. "A class to vectorwrite a carving."
  148. def __init__(self):
  149. 'Initialize.'
  150. self.layerCount = settings.LayerCount()
  151. def addRotatedLoopLayer( self, z ):
  152. "Add rotated loop layer."
  153. self.layerCount.printProgressIncrement('vectorwrite')
  154. self.rotatedBoundaryLayer = ThreadLayer(z)
  155. self.rotatedBoundaryLayers.append( self.rotatedBoundaryLayer )
  156. def addToLoops(self):
  157. "Add the thread to the loops."
  158. self.isLoop = False
  159. if len( self.thread ) < 1:
  160. return
  161. self.rotatedBoundaryLayer.loops.append( self.thread )
  162. self.thread = []
  163. def addToPerimeters(self):
  164. "Add the thread to the perimeters."
  165. self.isPerimeter = False
  166. if len( self.thread ) < 1:
  167. return
  168. if self.isOuter:
  169. self.rotatedBoundaryLayer.outerPerimeters.append( self.thread )
  170. else:
  171. self.rotatedBoundaryLayer.innerPerimeters.append( self.thread )
  172. self.thread = []
  173. def getCarveCornerMaximum(self):
  174. "Get the corner maximum of the vertexes."
  175. return self.cornerMaximum
  176. def getCarveCornerMinimum(self):
  177. "Get the corner minimum of the vertexes."
  178. return self.cornerMinimum
  179. def getCarveLayerThickness(self):
  180. "Get the layer thickness."
  181. return self.layerThickness
  182. def getCarvedSVG(self, fileName, gcodeText, repository):
  183. "Parse gnu triangulated surface text and store the vectorwrite gcode."
  184. self.boundaryLoop = None
  185. self.cornerMaximum = Vector3(-999999999.0, -999999999.0, -999999999.0)
  186. self.cornerMinimum = Vector3(999999999.0, 999999999.0, 999999999.0)
  187. self.extruderActive = False
  188. self.isLoop = False
  189. self.isOuter = False
  190. self.isPerimeter = False
  191. self.lines = archive.getTextLines(gcodeText)
  192. self.oldLocation = None
  193. self.thread = []
  194. self.rotatedBoundaryLayers = []
  195. self.repository = repository
  196. self.parseInitialization()
  197. for line in self.lines[self.lineIndex :]:
  198. self.parseLine(line)
  199. svgWriter = SVGWriterVectorwrite(True, self, self.decimalPlacesCarried, self.perimeterWidth)
  200. return svgWriter.getReplacedSVGTemplate(fileName, 'vectorwrite', self.rotatedBoundaryLayers)
  201. def linearMove( self, splitLine ):
  202. "Get statistics for a linear move."
  203. location = gcodec.getLocationFromSplitLine(self.oldLocation, splitLine)
  204. self.cornerMaximum = euclidean.getPointMaximum( self.cornerMaximum, location )
  205. self.cornerMinimum = euclidean.getPointMinimum( self.cornerMinimum, location )
  206. if self.extruderActive:
  207. if len( self.thread ) == 0:
  208. self.thread = [ self.oldLocation.dropAxis(2) ]
  209. self.thread.append( location.dropAxis(2) )
  210. self.oldLocation = location
  211. def parseInitialization(self):
  212. 'Parse gcode initialization and store the parameters.'
  213. for self.lineIndex in xrange(len(self.lines)):
  214. line = self.lines[self.lineIndex]
  215. splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line)
  216. firstWord = gcodec.getFirstWord(splitLine)
  217. if firstWord == '(<decimalPlacesCarried>':
  218. self.decimalPlacesCarried = int(splitLine[1])
  219. elif firstWord == '(<layerThickness>':
  220. self.layerThickness = float(splitLine[1])
  221. elif firstWord == '(<extrusion>)':
  222. return
  223. elif firstWord == '(<perimeterWidth>':
  224. self.perimeterWidth = float(splitLine[1])
  225. def parseLine(self, line):
  226. "Parse a gcode line and add it to the outset skein."
  227. splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line)
  228. if len(splitLine) < 1:
  229. return
  230. firstWord = splitLine[0]
  231. if firstWord == 'G1':
  232. self.linearMove(splitLine)
  233. elif firstWord == 'M101':
  234. self.extruderActive = True
  235. elif firstWord == 'M103':
  236. self.extruderActive = False
  237. if self.isLoop:
  238. self.addToLoops()
  239. return
  240. if self.isPerimeter:
  241. self.addToPerimeters()
  242. return
  243. self.rotatedBoundaryLayer.paths.append( self.thread )
  244. self.thread = []
  245. elif firstWord == '(</boundaryPerimeter>)':
  246. self.boundaryLoop = None
  247. elif firstWord == '(<boundaryPoint>':
  248. location = gcodec.getLocationFromSplitLine(None, splitLine)
  249. if self.boundaryLoop == None:
  250. self.boundaryLoop = []
  251. self.rotatedBoundaryLayer.boundaryLoops.append( self.boundaryLoop )
  252. self.boundaryLoop.append( location.dropAxis(2) )
  253. elif firstWord == '(<layer>':
  254. self.addRotatedLoopLayer(float(splitLine[1]))
  255. elif firstWord == '(</loop>)':
  256. self.addToLoops()
  257. elif firstWord == '(<loop>':
  258. self.isLoop = True
  259. elif firstWord == '(<perimeter>':
  260. self.isPerimeter = True
  261. self.isOuter = ( splitLine[1] == 'outer')
  262. elif firstWord == '(</perimeter>)':
  263. self.addToPerimeters()
  264. def main():
  265. "Display the vectorwrite dialog."
  266. if len(sys.argv) > 1:
  267. getWindowAnalyzeFile(' '.join(sys.argv[1 :]))
  268. else:
  269. settings.startMainLoopFromConstructor( getNewRepository() )
  270. if __name__ == "__main__":
  271. main()