PageRenderTime 52ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/skeinforge_application/skeinforge_plugins/craft_plugins/Obsolete/coil.py

https://github.com/jmil/SFACT
Python | 252 lines | 242 code | 5 blank | 5 comment | 2 complexity | 6822be42c774e57aa8596c9242bb9587 MD5 | raw file
  1. """
  2. This page is in the table of contents.
  3. Coil is a script to coil wire or filament around an object.
  4. ==Operation==
  5. The default 'Activate Coil' checkbox is on. When it is on, the functions described below will work, when it is off, the functions will not be called.
  6. ==Settings==
  7. ===Minimum Tool Distance===
  8. Default is twenty millimeters.
  9. Defines the minimum distance between the wire dispenser and the object. The 'Minimum Tool Distance' should be set to the maximum radius of the wire dispenser, times at least 1.3 to get a reasonable safety margin.
  10. ==Examples==
  11. The following examples coil the file Screw Holder Bottom.stl. The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and coil.py.
  12. > python coil.py
  13. This brings up the coil dialog.
  14. > python coil.py Screw Holder Bottom.stl
  15. The coil tool is parsing the file:
  16. Screw Holder Bottom.stl
  17. ..
  18. The coil tool has created the file:
  19. Screw Holder Bottom_coil.gcode
  20. """
  21. from __future__ import absolute_import
  22. #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.
  23. import __init__
  24. from fabmetheus_utilities.fabmetheus_tools import fabmetheus_interpret
  25. from fabmetheus_utilities.geometry.solids import triangle_mesh
  26. from fabmetheus_utilities.vector3 import Vector3
  27. from fabmetheus_utilities import archive
  28. from fabmetheus_utilities import euclidean
  29. from fabmetheus_utilities import gcodec
  30. from fabmetheus_utilities import intercircle
  31. from fabmetheus_utilities import settings
  32. from skeinforge_application.skeinforge_utilities import skeinforge_craft
  33. from skeinforge_application.skeinforge_utilities import skeinforge_polyfile
  34. from skeinforge_application.skeinforge_utilities import skeinforge_profile
  35. import os
  36. import sys
  37. __author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
  38. __date__ = '$Date: 2008/21/04 $'
  39. __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
  40. def getCraftedText( fileName, gcodeText = '', repository=None):
  41. """Coil the file or gcodeText."""
  42. return getCraftedTextFromText( archive.getTextIfEmpty(fileName, gcodeText), repository )
  43. def getCraftedTextFromText(gcodeText, repository=None):
  44. """Coil a gcode linear move gcodeText."""
  45. if gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'coil'):
  46. return gcodeText
  47. if repository is None:
  48. repository = settings.getReadRepository( CoilRepository() )
  49. if not repository.activateCoil.value:
  50. return gcodeText
  51. return CoilSkein().getCraftedGcode(gcodeText, repository)
  52. def getNewRepository():
  53. """Get new repository."""
  54. return CoilRepository()
  55. def writeOutput(fileName, shouldAnalyze=True):
  56. """Coil a gcode linear move file."""
  57. skeinforge_craft.writeChainTextWithNounMessage(fileName, 'coil', shouldAnalyze)
  58. class CoilRepository:
  59. """A class to handle the coil settings."""
  60. def __init__(self):
  61. """Set the default settings, execute title & settings fileName."""
  62. skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.coil.html', self )
  63. self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Coil', self, '')
  64. self.activateCoil = settings.BooleanSetting().getFromValue('Activate Coil', self, True )
  65. self.minimumToolDistance = settings.FloatSpin().getFromValue( 10.0, 'Minimum Tool Distance (millimeters):', self, 50.0, 20.0 )
  66. self.executeTitle = 'Coil'
  67. def execute(self):
  68. """Coil button has been clicked."""
  69. fileNames = skeinforge_polyfile.getFileOrDirectoryTypesUnmodifiedGcode(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled)
  70. for fileName in fileNames:
  71. writeOutput(fileName)
  72. class CoilSkein:
  73. """A class to coil a skein of extrusions."""
  74. def __init__(self):
  75. self.boundaryLayers = []
  76. self.distanceFeedRate = gcodec.DistanceFeedRate()
  77. self.lineIndex = 0
  78. self.lines = None
  79. self.oldLocationComplex = complex()
  80. self.extrusionWidth = 0.6
  81. self.shutdownLines = []
  82. def addCoilLayer( self, boundaryLayers, radius, z ):
  83. """Add a coil layer."""
  84. self.distanceFeedRate.addLine('(<layer> %s )' % z ) # Indicate that a new layer is starting.
  85. self.distanceFeedRate.addLine('(<nestedRing>)')
  86. thread = []
  87. for boundaryLayerIndex in xrange(1, len(boundaryLayers) - 1):
  88. boundaryLayer = boundaryLayers[boundaryLayerIndex]
  89. boundaryLayerBegin = boundaryLayers[boundaryLayerIndex - 1]
  90. boundaryLayerEnd = boundaryLayers[boundaryLayerIndex + 1]
  91. beginLocation = Vector3(0.0, 0.0, 0.5 * (boundaryLayerBegin.z + boundaryLayer.z))
  92. outsetLoop = intercircle.getLargestInsetLoopFromLoop(boundaryLayer.loops[0], - radius)
  93. self.addCoilToThread(beginLocation, 0.5 * (boundaryLayer.z + boundaryLayerEnd.z), outsetLoop, thread)
  94. self.addGcodeFromThread(thread)
  95. self.distanceFeedRate.addLine('(</nestedRing>)')
  96. self.distanceFeedRate.addLine('(</layer>)')
  97. def addCoilLayers(self):
  98. """Add the coil layers."""
  99. numberOfLayersFloat = round( self.extrusionWidth / self.extrusionHeight )
  100. numberOfLayers = int( numberOfLayersFloat )
  101. halfLayerThickness = 0.5 * self.extrusionHeight
  102. startOutset = self.repository.minimumToolDistance.value + halfLayerThickness
  103. startZ = self.boundaryLayers[0].z + halfLayerThickness
  104. zRange = self.boundaryLayers[-1].z - self.boundaryLayers[0].z
  105. zIncrement = 0.0
  106. if zRange >= 0.0:
  107. zIncrement = zRange / numberOfLayersFloat
  108. for layerIndex in xrange( numberOfLayers ):
  109. settings.printProgressByNumber(layerIndex, numberOfLayers, 'coil')
  110. boundaryLayers = self.boundaryLayers
  111. if layerIndex % 2 == 1:
  112. boundaryLayers = self.boundaryReverseLayers
  113. radius = startOutset + layerIndex * self.extrusionHeight
  114. z = startZ + layerIndex * zIncrement
  115. self.addCoilLayer( boundaryLayers, radius, z )
  116. def addCoilToThread(self, beginLocation, endZ, loop, thread):
  117. """Add a coil to the thread."""
  118. if len(loop) < 1:
  119. return
  120. loop = euclidean.getLoopStartingNearest(self.halfPerimeterWidth, self.oldLocationComplex, loop)
  121. length = euclidean.getLoopLength(loop)
  122. if length <= 0.0:
  123. return
  124. oldPoint = loop[0]
  125. pathLength = 0.0
  126. for point in loop[1 :]:
  127. pathLength += abs(point - oldPoint)
  128. along = pathLength / length
  129. z = (1.0 - along) * beginLocation.z + along * endZ
  130. location = Vector3(point.real, point.imag, z)
  131. thread.append(location)
  132. oldPoint = point
  133. self.oldLocationComplex = loop[-1]
  134. def addGcodeFromThread( self, thread ):
  135. """Add a thread to the output."""
  136. if len(thread) > 0:
  137. firstLocation = thread[0]
  138. self.distanceFeedRate.addGcodeMovementZ( firstLocation.dropAxis(), firstLocation.z )
  139. else:
  140. print( "zero length vertex positions array which was skipped over, this should never happen" )
  141. if len(thread) < 2:
  142. print( "thread of only one point in addGcodeFromThread in coil, this should never happen" )
  143. print(thread)
  144. return
  145. self.distanceFeedRate.addLine('M101') # Turn extruder on.
  146. for location in thread[1 :]:
  147. self.distanceFeedRate.addGcodeMovementZ( location.dropAxis(), location.z )
  148. self.distanceFeedRate.addLine('M103') # Turn extruder off.
  149. def getCraftedGcode(self, gcodeText, repository):
  150. """Parse gcode text and store the coil gcode."""
  151. self.repository = repository
  152. self.lines = archive.getTextLines(gcodeText)
  153. self.parseInitialization()
  154. self.parseBoundaries()
  155. self.parseUntilLayer()
  156. self.addCoilLayers()
  157. self.distanceFeedRate.addLines( self.shutdownLines )
  158. return self.distanceFeedRate.output.getvalue()
  159. def parseBoundaries(self):
  160. """Parse the boundaries and add them to the boundary layers."""
  161. boundaryLoop = None
  162. boundaryLayer = None
  163. for line in self.lines[self.lineIndex :]:
  164. splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line)
  165. firstWord = gcodec.getFirstWord(splitLine)
  166. if len( self.shutdownLines ) > 0:
  167. self.shutdownLines.append(line)
  168. if firstWord == '(</boundaryPerimeter>)':
  169. boundaryLoop = None
  170. elif firstWord == '(<boundaryPoint>':
  171. location = gcodec.getLocationFromSplitLine(None, splitLine)
  172. if boundaryLoop is None:
  173. boundaryLoop = []
  174. boundaryLayer.loops.append(boundaryLoop)
  175. boundaryLoop.append(location.dropAxis())
  176. elif firstWord == '(<layer>':
  177. boundaryLayer = euclidean.LoopLayer(float(splitLine[1]))
  178. self.boundaryLayers.append(boundaryLayer)
  179. elif firstWord == '(</crafting>)':
  180. self.shutdownLines = [ line ]
  181. for boundaryLayer in self.boundaryLayers:
  182. if not euclidean.isWiddershins( boundaryLayer.loops[0] ):
  183. boundaryLayer.loops[0].reverse()
  184. self.boundaryReverseLayers = self.boundaryLayers[:]
  185. self.boundaryReverseLayers.reverse()
  186. def parseInitialization(self):
  187. """Parse gcode initialization and store the parameters."""
  188. for self.lineIndex in xrange(len(self.lines)):
  189. line = self.lines[self.lineIndex]
  190. splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line)
  191. firstWord = gcodec.getFirstWord(splitLine)
  192. self.distanceFeedRate.parseSplitLine(firstWord, splitLine)
  193. if firstWord == '(</extruderInitialization>)':
  194. self.distanceFeedRate.addLine('(<procedureName> coil </procedureName>)')
  195. return
  196. elif firstWord == '(<extrusionHeight>':
  197. self.extrusionHeight = float(splitLine[1])
  198. elif firstWord == '(<extrusionWidth>':
  199. self.extrusionWidth = float(splitLine[1])
  200. self.halfPerimeterWidth = 0.5 * self.extrusionWidth
  201. self.distanceFeedRate.addLine(line)
  202. def parseUntilLayer(self):
  203. """Parse until the layer line and add it to the coil skein."""
  204. for self.lineIndex in xrange(self.lineIndex, len(self.lines)):
  205. line = self.lines[self.lineIndex]
  206. splitLine = gcodec.getSplitLineBeforeBracketSemicolon(line)
  207. firstWord = gcodec.getFirstWord(splitLine)
  208. self.distanceFeedRate.parseSplitLine(firstWord, splitLine)
  209. if firstWord == '(<layer>':
  210. return
  211. self.distanceFeedRate.addLine(line)
  212. def main():
  213. """Display the coil dialog."""
  214. if len(sys.argv) > 1:
  215. writeOutput(' '.join(sys.argv[1 :]))
  216. else:
  217. settings.startMainLoopFromConstructor( getNewRepository() )
  218. if __name__ == "__main__":
  219. main()