summaryrefslogtreecommitdiff
path: root/trunk/reprap/miscellaneous/python-beanshell-scripts/skeinforge_tools/craft_plugins/preface.py
blob: bd78edc7e3c4be592e0943f3b7548b854909082e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
#! /usr/bin/env python
"""
This page is in the table of contents.
Preface converts the svg slices into gcode extrusion layers, optionally prefaced with some gcode commands.

The preface manual page is at:
http://www.bitsfrombytes.com/wiki/index.php?title=Skeinforge_Preface

==Settings==
===Meta===
Default is empty.

The 'Meta' field is to add meta tags or a note to all your files.  Whatever is in that field will be added in a meta tagged line to the output.

===Name of Alteration Files===
Preface looks for alteration files in the alterations folder in the .skeinforge folder in the home directory.  Preface does not care if the text file names are capitalized, but some file systems do not handle file name cases properly, so to be on the safe side you should give them lower case names.  If it doesn't find the file it then looks in the alterations folder in the skeinforge_tools folder. If it doesn't find anything there it looks in the craft_plugins folder.

====Name of End File====
Default is end.gcode.

If there is a file with the name of the "Name of End File" setting, it will be added to the very end.

====Name of Start File====
Default is end.gcode.

If there is a file with the name of the "Name of Start File" setting, it will be added to the very beginning of the gcode.

===Set Positioning to Absolute===
Default is on.

When selected, preface will add the G90 command to set positioning to absolute.

===Set Units to Millimeters===
Default is on.

When selected, preface will add the G21 command to set the units to millimeters.

===Start at Home===
Default is off.

When selected, the G28 go to home gcode will be added at the beginning of the file.

===Turn Extruder Off===
====Turn Extruder Off at Shut Down====
Default is on.

When selected, the M103 turn extruder off gcode will be added at the end of the file.

====Turn Extruder Off at Start Up====
Default is on.

When selected, the M103 turn extruder off gcode will be added at the beginning of the file.

==Examples==
The following examples preface the file Screw Holder Bottom.stl.  The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and preface.py.


> python preface.py
This brings up the preface dialog.


> python preface.py Screw Holder Bottom.stl
The preface tool is parsing the file:
Screw Holder Bottom.stl
..
The preface tool has created the file:
.. Screw Holder Bottom_preface.gcode


> python
Python 2.5.1 (r251:54863, Sep 22 2007, 01:43:31)
[GCC 4.2.1 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import preface
>>> preface.main()
This brings up the preface dialog.


>>> preface.writeOutput( 'Screw Holder Bottom.stl' )
The preface tool is parsing the file:
Screw Holder Bottom.stl
..
The preface tool has created the file:
.. Screw Holder Bottom_preface.gcode

"""

from __future__ import absolute_import
try:
	import psyco
	psyco.full()
except:
	pass
#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.
import __init__

from datetime import date
from skeinforge_tools import profile
from skeinforge_tools.meta_plugins import polyfile
from skeinforge_tools.skeinforge_utilities import consecution
from skeinforge_tools.skeinforge_utilities import euclidean
from skeinforge_tools.skeinforge_utilities import gcodec
from skeinforge_tools.skeinforge_utilities import intercircle
from skeinforge_tools.skeinforge_utilities import interpret
from skeinforge_tools.skeinforge_utilities import settings
import os
import sys


__author__ = "Enrique Perez (perez_enrique@yahoo.com)"
__date__ = "$Date: 2008/28/04 $"
__license__ = "GPL 3.0"


def getCraftedText( fileName, text = '', prefaceRepository = None ):
	"Preface and convert an svg file or text."
	return getCraftedTextFromText( gcodec.getTextIfEmpty( fileName, text ), prefaceRepository )

def getCraftedTextFromText( text, prefaceRepository = None ):
	"Preface and convert an svg text."
	if gcodec.isProcedureDoneOrFileIsEmpty( text, 'preface' ):
		return text
	if prefaceRepository == None:
		prefaceRepository = settings.getReadRepository( PrefaceRepository() )
	return PrefaceSkein().getCraftedGcode( prefaceRepository, text )

def getNewRepository():
	"Get the repository constructor."
	return PrefaceRepository()

def writeOutput( fileName = '' ):
	"Preface the carving of a gcode file.  If no fileName is specified, preface the first unmodified gcode file in this folder."
	fileName = interpret.getFirstTranslatorFileNameUnmodified( fileName )
	if fileName == '':
		return
	consecution.writeChainTextWithNounMessage( fileName, 'preface' )


class PrefaceRepository:
	"A class to handle the preface settings."
	def __init__( self ):
		"Set the default settings, execute title & settings fileName."
		profile.addListsToCraftTypeRepository( 'skeinforge_tools.craft_plugins.preface.html', self )
		self.fileNameInput = settings.FileNameInput().getFromFileName( interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Preface', self, '' )
		self.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute( 'http://www.bitsfrombytes.com/wiki/index.php?title=Skeinforge_Preface' )
		self.meta = settings.StringSetting().getFromValue( 'Meta:', self, '' )
		settings.LabelDisplay().getFromName( '- Name of Alteration Files -', self )
		self.nameOfEndFile = settings.StringSetting().getFromValue( 'Name of End File:', self, 'end.gcode' )
		self.nameOfStartFile = settings.StringSetting().getFromValue( 'Name of Start File:', self, 'start.gcode' )
		self.setPositioningToAbsolute = settings.BooleanSetting().getFromValue( 'Set Positioning to Absolute', self, True )
		self.setUnitsToMillimeters = settings.BooleanSetting().getFromValue( 'Set Units to Millimeters', self, True )
		self.startAtHome = settings.BooleanSetting().getFromValue( 'Start at Home', self, False )
		settings.LabelDisplay().getFromName( '- Turn Extruder Off -', self )
		self.turnExtruderOffAtShutDown = settings.BooleanSetting().getFromValue( 'Turn Extruder Off at Shut Down', self, True )
		self.turnExtruderOffAtStartUp = settings.BooleanSetting().getFromValue( 'Turn Extruder Off at Start Up', self, True )
		self.executeTitle = 'Preface'

	def execute( self ):
		"Preface button has been clicked."
		fileNames = polyfile.getFileOrDirectoryTypesUnmodifiedGcode( self.fileNameInput.value, interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled )
		for fileName in fileNames:
			writeOutput( fileName )


class PrefaceSkein:
	"A class to preface a skein of extrusions."
	def __init__( self ):
		self.distanceFeedRate = gcodec.DistanceFeedRate()
		self.extruderActive = False
		self.lineIndex = 0
		self.oldLocation = None
		self.rotatedBoundaryLayers = []

	def addFromUpperLowerFile( self, fileName ):
		"Add lines of text from the fileName or the lowercase fileName, if there is no file by the original fileName in the directory."
		fileText = settings.getFileInAlterationsOrGivenDirectory( os.path.dirname( __file__ ), fileName )
		fileLines = gcodec.getTextLines( fileText )
		self.distanceFeedRate.addLinesSetAbsoluteDistanceMode( fileLines )

	def addInitializationToOutput( self ):
		"Add initialization gcode to the output."
		self.addFromUpperLowerFile( self.prefaceRepository.nameOfStartFile.value ) # Add a start file if it exists.
		self.distanceFeedRate.addTagBracketedLine( 'creator', 'skeinforge' ) # GCode formatted comment
		absoluteFilePathUntilDot = os.path.abspath( __file__ )[ : os.path.abspath( __file__ ).rfind( '.' ) ]
		if absoluteFilePathUntilDot == '/home/enrique/Desktop/backup/babbleold/script/reprap/pyRepRap/skeinforge_tools/craft_plugins/preface': #check to see if this script is on Enrique's computer
			gcodec.writeFileText( gcodec.getVersionFileName(), date.today().isoformat() )
		versionText = gcodec.getFileText( gcodec.getVersionFileName() )
		self.distanceFeedRate.addTagBracketedLine( 'version', versionText ) # GCode formatted comment
		self.distanceFeedRate.addLine( '(<extruderInitialization>)' ) # GCode formatted comment
		if self.prefaceRepository.setPositioningToAbsolute.value:
			self.distanceFeedRate.addLine( 'G90' ) # Set positioning to absolute.
		if self.prefaceRepository.setUnitsToMillimeters.value:
			self.distanceFeedRate.addLine( 'G21' ) # Set units to millimeters.
		if self.prefaceRepository.startAtHome.value:
			self.distanceFeedRate.addLine( 'G28' ) # Start at home.
		if self.prefaceRepository.turnExtruderOffAtStartUp.value:
			self.distanceFeedRate.addLine( 'M103' ) # Turn extruder off.
		craftTypeName = profile.getCraftTypeName()
		self.distanceFeedRate.addTagBracketedLine( 'craftTypeName', craftTypeName )
		self.distanceFeedRate.addTagBracketedLine( 'decimalPlacesCarried', self.distanceFeedRate.decimalPlacesCarried )
		self.distanceFeedRate.addTagBracketedLine( 'layerThickness', self.distanceFeedRate.getRounded( self.layerThickness ) )
		if self.prefaceRepository.meta.value:
			self.distanceFeedRate.addTagBracketedLine( 'meta', self.prefaceRepository.meta.value )
		self.distanceFeedRate.addTagBracketedLine( 'perimeterWidth', self.distanceFeedRate.getRounded( self.perimeterWidth ) )
		self.distanceFeedRate.addTagBracketedLine( 'profileName', profile.getProfileName( craftTypeName ) )
		self.distanceFeedRate.addTagBracketedLine( 'procedureDone', 'carve' )
		self.distanceFeedRate.addTagBracketedLine( 'procedureDone', 'preface' )
		self.distanceFeedRate.addLine( '(</extruderInitialization>)' ) # Initialization is finished, extrusion is starting.
		self.distanceFeedRate.addLine( '(<extrusion>)' ) # Initialization is finished, extrusion is starting.

	def addPathData( self, line ):
		"Add the data from the path line."
		line = line.replace( '"', ' ' )
		splitLine = line.split()
		if splitLine[ 1 ] != 'transform=':
			return
		line = line.lower()
		line = line.replace( 'm', ' ' )
		line = line.replace( 'l', ' ' )
		line = line.replace( '/>', ' ' )
		splitLine = line.split()
		if 'd=' not in splitLine:
			return
		splitLine = splitLine[ splitLine.index( 'd=' ) + 1 : ]
		pathSequence = []
		for word in splitLine:
			if word == 'z':
				loop = []
				for pathSequenceIndex in xrange( 0, len( pathSequence ), 2 ):
					coordinate = complex( pathSequence[ pathSequenceIndex ], pathSequence[ pathSequenceIndex + 1 ] )
					loop.append( coordinate )
				self.rotatedBoundaryLayer.loops.append( loop )
				pathSequence = []
			else:
				pathSequence.append( float( word ) )

	def addPreface( self, rotatedBoundaryLayer ):
		"Add preface to the carve layer."
		self.distanceFeedRate.addLine( '(<layer> %s )' % rotatedBoundaryLayer.z ) # Indicate that a new layer is starting.
		if rotatedBoundaryLayer.rotation != None:
			self.distanceFeedRate.addTagBracketedLine( 'bridgeRotation', str( rotatedBoundaryLayer.rotation ) ) # Indicate the bridge rotation.
		for loop in rotatedBoundaryLayer.loops:
			self.distanceFeedRate.addGcodeFromLoop( loop, rotatedBoundaryLayer.z )
		self.distanceFeedRate.addLine( '(</layer>)' )

	def addRotatedLoopLayer( self, z ):
		"Add rotated loop layer."
		self.rotatedBoundaryLayer = euclidean.RotatedLoopLayer( z )
		self.rotatedBoundaryLayers.append( self.rotatedBoundaryLayer )

	def addShutdownToOutput( self ):
		"Add shutdown gcode to the output."
		self.distanceFeedRate.addLine( '(</extrusion>)' ) # GCode formatted comment
		if self.prefaceRepository.turnExtruderOffAtShutDown.value:
			self.distanceFeedRate.addLine( 'M103' ) # Turn extruder motor off.
		self.addFromUpperLowerFile( self.prefaceRepository.nameOfEndFile.value ) # Add an end file if it exists.

	def addTextData( self, line ):
		"Add the data from the text line."
		if line.find( 'layerThickness' ) != - 1:
			return
		line = line.replace( '>', ' ' )
		line = line.replace( '<', ' ' )
		line = line.replace( ',', ' ' )
		splitLine = line.split()
		if 'Layer' not in splitLine:
			return
		splitLine = splitLine[ splitLine.index( 'Layer' ) + 1 : ]
		if 'z' not in splitLine:
			return
		zIndex = splitLine.index( 'z' )
		self.addRotatedLoopLayer( float( splitLine[ zIndex + 1 ] ) )

	def getCraftedGcode( self, prefaceRepository, gcodeText ):
		"Parse gcode text and store the bevel gcode."
		self.prefaceRepository = prefaceRepository
		gcodeText = gcodeText.replace( '\t', ' ' )
		gcodeText = gcodeText.replace( ';', ' ' )
		self.lines = gcodec.getTextLines( gcodeText )
		self.parseInitialization()
		self.addInitializationToOutput()
		for lineIndex in xrange( self.lineIndex, len( self.lines ) ):
			self.parseLine( lineIndex )
		for rotatedBoundaryLayer in self.rotatedBoundaryLayers:
			self.addPreface( rotatedBoundaryLayer )
		self.addShutdownToOutput()
		return self.distanceFeedRate.output.getvalue()

	def parseInitialization( self ):
		"Parse gcode initialization and store the parameters."
		for self.lineIndex in xrange( len( self.lines ) ):
			line = self.lines[ self.lineIndex ].lstrip()
			splitLine = gcodec.getWithoutBracketsEqualTab( line ).split()
			firstWord = gcodec.getFirstWord( splitLine )
			self.distanceFeedRate.parseSplitLine( firstWord, splitLine )
			if firstWord == 'layerThickness':
				self.layerThickness = float( splitLine[ 1 ] )
			elif firstWord == 'extrusionStart':
				return
			elif firstWord == 'perimeterWidth':
				self.perimeterWidth = float( splitLine[ 1 ] )

	def parseLine( self, lineIndex ):
		"Parse a gcode line and add it to the preface skein."
		line = self.lines[ lineIndex ].lstrip()
		splitLine = line.split()
		if len( splitLine ) < 1:
			return
		firstWord = splitLine[ 0 ]
		if firstWord == '(<bridgeRotation>' or firstWord == '<!--bridgeRotation-->':
			secondWordWithoutBrackets = splitLine[ 1 ].replace( '(', '' ).replace( ')', '' )
			self.rotatedBoundaryLayer.rotation = complex( secondWordWithoutBrackets )
		elif firstWord == '<path':
			self.addPathData( line )
		elif firstWord == '<text':
			self.addTextData( line )


def main():
	"Display the preface dialog."
	if len( sys.argv ) > 1:
		writeOutput( ' '.join( sys.argv[ 1 : ] ) )
	else:
		settings.startMainLoopFromConstructor( getNewRepository() )

if __name__ == "__main__":
	main()