Option Explicit
 
Call Main()
Sub Main()
	'Iniatialize variables to use
	Dim objFSO, objFile, solid, objSnSPlugIn, resolution
	Dim disp, vm, Point, resFactor, maxRes
	
	'Initialize SnS plugin
	Set objSnSPlugIn = Rhino.GetPluginObject("SnSScript")

	
	'Prompt to select location to save solution data as a CSV 
	Dim FileLocation : FileLocation = Rhino.SaveFileName("Save location for convergence data", , , , "csv")

     
	'Open a file to receive the computed values and write the header
	Set objFSO = CreateObject("Scripting.FileSystemObject")
	Set objFile = objFSO.OpenTextFile(FileLocation, 2, True)
	Call objFile.Write("Resolution,Displacement,vonMises" & vbCrLf)
     
	'Have user select the solid to analyze
	solid = Rhino.GetObject("Select a solid", 48)
	
	'SnSScript only works with closed polysurfaces.  Check to see if solid is an extrusion.
	If ( Rhino.IsExtrusion(solid) )  Then
		Rhino.MessageBox("Convert the extrusion to a closed polysurface by running the ConvertExtrusion command.  You will have to redefine the loads and restraints by running SnS.")
		Exit Sub
	End If
	
	'Select point in the solid to check for convergence
	Point = Rhino.GetPointOnSurface(solid, "Select point to query stress.")

	
	'Set initial resolution, maximum resolution, and increment factor
	resolution = 1000
	maxRes = 100000
	resFactor = 5 / 4
     
	'Iterate through resolutions, solve at each resolution and
	'write solution values to the file.
	While (resolution < maxRes)
		'Solve the simulation in SnS
		objSnSPlugIn.Solve solid, resolution
		
		'Query displacement and von Mises solution values
		disp = objSnSPlugIn.QuerySolutionValue(solid, "DSPT", Point)
		vm = objSnSPlugIn.QuerySolutionValue(solid, "VONM", Point)
		
		'Write a new line to the file with these values separated by comma's
		Call objFile.Write(resolution & "," & disp & "," & vm & vbCrLf)
		
		'Increase the resolution by the defined factor
		resolution = Rhino.Ceil(resolution * resFactor)
	Wend
	
	'Close the file object.
	Call objFile.Close()
     
End Sub