chiark / gitweb /
Move SF into its own directory, to seperate SF and Cura. Rename newui to gui.
[cura.git] / Cura / cura_sf / skeinforge_application / skeinforge_plugins / craft_plugins / chop.py
1 """
2 This page is in the table of contents.
3 Chop is a script to chop a shape into svg slice layers.
4
5 ==Settings==
6 ===Add Layer Template to SVG===
7 Default is on.
8
9 When selected, the layer template will be added to the svg output, which adds javascript control boxes.  So 'Add Layer Template to SVG' should be selected when the svg will be viewed in a browser.
10
11 When off, no controls will be added, the svg output will only include the fabrication paths.  So 'Add Layer Template to SVG' should be deselected when the svg will be used by other software, like Inkscape.
12
13 ===Add Extra Top Layer if Necessary===
14 Default is on.
15
16 When selected, chop will add an extra layer at the very top of the object if the top of the object is more than half the layer height above the first slice.  This is so the cutting tool doesn't cut too deeply through the top of the object on its first pass.
17
18 ===Extra Decimal Places===
19 Default is two.
20
21 Defines the number of extra decimal places export will output compared to the number of decimal places in the layer height.  The higher the 'Extra Decimal Places', the more significant figures the output numbers will have.
22
23 ===Import Coarseness===
24 Default is one.
25
26 When a triangle mesh has holes in it, the triangle mesh slicer switches over to a slow algorithm that spans gaps in the mesh.  The higher the 'Import Coarseness' setting, the wider the gaps in the mesh it will span.  An import coarseness of one means it will span gaps of the edge width.
27
28 ===Layer Height===
29 Default is 0.4 mm.
30
31 Defines the height of the layer, this is the most important chop setting.
32
33 ===Layers===
34 Chop slices from top to bottom.  To get only the bottom layer, set the "Layers From" to minus one.  The 'Layers From' until 'Layers To' range is a python slice.
35
36 ====Layers From====
37 Default is zero.
38
39 Defines the index of the top layer that will be chopped.  If the 'Layers From' is the default zero, the carving will start from the top layer.  If the 'Layers From' index is negative, then the carving will start from the 'Layers From' index above the bottom layer.
40
41 ====Layers To====
42 Default is a huge number, which will be limited to the highest index number.
43
44 Defines the index of the bottom layer that will be chopped.  If the 'Layers To' index is a huge number like the default, the carving will go to the bottom of the model.  If the 'Layers To' index is negative, then the carving will go to the 'Layers To' index above the bottom layer.
45
46 ===Mesh Type===
47 Default is 'Correct Mesh'.
48
49 ====Correct Mesh====
50 When selected, the mesh will be accurately chopped, and if a hole is found, chop will switch over to the algorithm that spans gaps.
51
52 ====Unproven Mesh====
53 When selected, chop will use the gap spanning algorithm from the start.  The problem with the gap spanning algothm is that it will span gaps, even if there is not actually a gap in the model.
54
55 ===Perimeter Width===
56 Default is 2 mm.
57
58 Defines the width of the edge.
59
60 ===SVG Viewer===
61 Default is webbrowser.
62
63 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.
64
65 ==Examples==
66 The following examples chop the file Screw Holder Bottom.stl.  The examples are run in a terminal in the folder which contains Screw Holder Bottom.stl and chop.py.
67
68 > python chop.py
69 This brings up the chop dialog.
70
71 > python chop.py Screw Holder Bottom.stl
72 The chop tool is parsing the file:
73 Screw Holder Bottom.stl
74 ..
75 The chop tool has created the file:
76 .. Screw Holder Bottom_chop.svg
77
78 """
79
80 from __future__ import absolute_import
81 try:
82         import psyco
83         psyco.full()
84 except:
85         pass
86 #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.
87 import __init__
88
89 from fabmetheus_utilities.fabmetheus_tools import fabmetheus_interpret
90 from fabmetheus_utilities import archive
91 from fabmetheus_utilities import euclidean
92 from fabmetheus_utilities import gcodec
93 from fabmetheus_utilities import settings
94 from fabmetheus_utilities import svg_writer
95 from skeinforge_application.skeinforge_utilities import skeinforge_polyfile
96 from skeinforge_application.skeinforge_utilities import skeinforge_profile
97 import math
98 import os
99 import sys
100 import time
101
102
103 __author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
104 __date__ = '$Date: 2008/02/05 $'
105 __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
106
107
108 def getCraftedText( fileName, gcodeText = '', repository=None):
109         "Get chopped text."
110         if fileName.endswith('.svg'):
111                 gcodeText = archive.getTextIfEmpty(fileName, gcodeText)
112                 if gcodec.isProcedureDoneOrFileIsEmpty( gcodeText, 'chop'):
113                         return gcodeText
114         carving = svg_writer.getCarving(fileName)
115         if carving == None:
116                 return ''
117         if repository == None:
118                 repository = ChopRepository()
119                 settings.getReadRepository(repository)
120         return ChopSkein().getCarvedSVG( carving, fileName, repository )
121
122 def getNewRepository():
123         'Get new repository.'
124         return ChopRepository()
125
126 def writeOutput(fileName, shouldAnalyze=True):
127         "Chop a GNU Triangulated Surface file.  If no fileName is specified, chop the first GNU Triangulated Surface file in this folder."
128         startTime = time.time()
129         print('File ' + archive.getSummarizedFileName(fileName) + ' is being chopped.')
130         repository = ChopRepository()
131         settings.getReadRepository(repository)
132         chopGcode = getCraftedText( fileName, '', repository )
133         if chopGcode == '':
134                 return
135         suffixFileName = fileName[ : fileName.rfind('.') ] + '_chop.svg'
136         suffixDirectoryName = os.path.dirname(suffixFileName)
137         suffixReplacedBaseName = os.path.basename(suffixFileName).replace(' ', '_')
138         suffixFileName = os.path.join( suffixDirectoryName, suffixReplacedBaseName )
139         archive.writeFileText( suffixFileName, chopGcode )
140         print('The chopped file is saved as ' + archive.getSummarizedFileName(suffixFileName) )
141         print('It took %s to chop the file.' % euclidean.getDurationString( time.time() - startTime ) )
142         if shouldAnalyze:
143                 settings.openSVGPage( suffixFileName, repository.svgViewer.value )
144
145
146 class ChopRepository:
147         "A class to handle the chop settings."
148         def __init__(self):
149                 "Set the default settings, execute title & settings fileName."
150                 skeinforge_profile.addListsToCraftTypeRepository('skeinforge_application.skeinforge_plugins.craft_plugins.chop.html', self )
151                 self.fileNameInput = settings.FileNameInput().getFromFileName( fabmetheus_interpret.getTranslatorFileTypeTuples(), 'Open File to be Chopped', self, '')
152                 self.addExtraTopLayerIfNecessary = settings.BooleanSetting().getFromValue('Add Extra Top Layer if Necessary', self, True )
153                 self.addLayerTemplateToSVG = settings.BooleanSetting().getFromValue('Add Layer Template to SVG', self, True)
154                 self.edgeWidth = settings.FloatSpin().getFromValue( 0.4, 'Edge Width (mm):', self, 4.0, 2.0 )
155                 self.extraDecimalPlaces = settings.FloatSpin().getFromValue(0.0, 'Extra Decimal Places (float):', self, 3.0, 2.0)
156                 self.importCoarseness = settings.FloatSpin().getFromValue( 0.5, 'Import Coarseness (ratio):', self, 2.0, 1.0 )
157                 self.layerHeight = settings.FloatSpin().getFromValue( 0.1, 'Layer Height (mm):', self, 1.0, 0.4 )
158                 self.layersFrom = settings.IntSpin().getFromValue( 0, 'Layers From (index):', self, 20, 0 )
159                 self.layersTo = settings.IntSpin().getSingleIncrementFromValue( 0, 'Layers To (index):', self, 912345678, 912345678 )
160                 self.meshTypeLabel = settings.LabelDisplay().getFromName('Mesh Type: ', self, )
161                 importLatentStringVar = settings.LatentStringVar()
162                 self.correctMesh = settings.Radio().getFromRadio( importLatentStringVar, 'Correct Mesh', self, True )
163                 self.unprovenMesh = settings.Radio().getFromRadio( importLatentStringVar, 'Unproven Mesh', self, False )
164                 self.svgViewer = settings.StringSetting().getFromValue('SVG Viewer:', self, 'webbrowser')
165                 settings.LabelSeparator().getFromRepository(self)
166                 self.executeTitle = 'Chop'
167
168         def execute(self):
169                 "Chop button has been clicked."
170                 fileNames = skeinforge_polyfile.getFileOrDirectoryTypes(self.fileNameInput.value, fabmetheus_interpret.getImportPluginFileNames(), self.fileNameInput.wasCancelled)
171                 for fileName in fileNames:
172                         writeOutput(fileName)
173
174
175 class ChopSkein:
176         "A class to chop a carving."
177         def addExtraTopLayerIfNecessary( self, carving, layerHeight, loopLayers ):
178                 "Add extra top layer if necessary."
179                 topRotatedBoundaryLayer = loopLayers[-1]
180                 cuttingSafeHeight = topRotatedBoundaryLayer.z + 0.5001 * layerHeight
181                 if cuttingSafeHeight > carving.getCarveCornerMaximum().z:
182                         return
183                 extraTopRotatedBoundaryLayer = topRotatedBoundaryLayer.getCopyAtZ( topRotatedBoundaryLayer.z + layerHeight )
184                 loopLayers.append( extraTopRotatedBoundaryLayer )
185
186         def getCarvedSVG( self, carving, fileName, repository ):
187                 "Parse gnu triangulated surface text and store the chopped gcode."
188                 layerHeight = repository.layerHeight.value
189                 edgeWidth = repository.edgeWidth.value
190                 carving.setCarveLayerHeight( layerHeight )
191                 importRadius = 0.5 * repository.importCoarseness.value * abs(edgeWidth)
192                 carving.setCarveImportRadius(max(importRadius, 0.001 * layerHeight))
193                 carving.setCarveIsCorrectMesh( repository.correctMesh.value )
194                 loopLayers = carving.getCarveBoundaryLayers()
195                 if len( loopLayers ) < 1:
196                         print('Warning, there are no slices for the model, this could be because the model is too small for the Layer Height.')
197                         return ''
198                 if repository.addExtraTopLayerIfNecessary.value:
199                         self.addExtraTopLayerIfNecessary( carving, layerHeight, loopLayers )
200                 loopLayers.reverse()
201                 layerHeight = carving.getCarveLayerHeight()
202                 decimalPlacesCarried = euclidean.getDecimalPlacesCarried(repository.extraDecimalPlaces.value, layerHeight)
203                 svgWriter = svg_writer.SVGWriter(
204                         repository.addLayerTemplateToSVG.value,
205                         carving.getCarveCornerMaximum(),
206                         carving.getCarveCornerMinimum(),
207                         decimalPlacesCarried,
208                         carving.getCarveLayerHeight(),
209                         edgeWidth)
210                 truncatedRotatedBoundaryLayers = svg_writer.getTruncatedRotatedBoundaryLayers(loopLayers, repository)
211                 return svgWriter.getReplacedSVGTemplate( fileName, truncatedRotatedBoundaryLayers, 'chop', carving.getFabmetheusXML())
212
213
214 def main():
215         "Display the chop dialog."
216         if len(sys.argv) > 1:
217                 writeOutput(' '.join(sys.argv[1 :]))
218         else:
219                 settings.startMainLoopFromConstructor(getNewRepository())
220
221 if __name__ == "__main__":
222         main()