예제 #1
0
def print_metrics(mesh):
	"""Print metrics value of a mesh.
	
	Parameters
	----------
	mesh : Mesh
		A mesh.

	Returns
	-------
	results: dict
		Dictionary of metric values {metric: value}.

	Raises
	------
	-

	"""
	operators = {
			'edge_lengths': edge_lengths, 
			'face_curvatures': face_curvatures,
			'face_skewnesses': face_skewnesses,
			'minimum': minimum,
			'maximum': maximum,
			'mean': mean,
			'standard_deviation': standard_deviation,
			 }

	default_metrics_bool = [('minimum edge_lengths', False),
			   ('maximum edge_lengths', False),
			   ('mean edge_lengths', False),
			   ('standard_deviation edge_lengths', True),
			   ('minimum face_curvatures', False),
			   ('maximum face_curvatures', True),
			   ('mean face_curvatures', False),
			   ('standard_deviation face_curvatures', False),
			   ('minimum face_skewnesses', False),
			   ('maximum face_skewnesses', False),
			   ('mean face_skewnesses', True),
			   ('standard_deviation face_skewnesses', False),
	]
	
	metrics_bool = rs.CheckListBox(default_metrics_bool, message = 'which metrics do you want to print?', title = 'metrics')

	results = {}
	for item in metrics_bool:
		metrics, boolean = item
		if boolean:
			metrics_1, metrics_2 = metrics.split(' ')
			result = operators[metrics_1](operators[metrics_2](mesh).values())
			results[metrics] = result

	# TO DO: add units
	for key, value in results.items():
		print key, ': ', value

	return results
예제 #2
0
def RunCommand(is_interactive):
    # TODO: detect version
    ipylib_path = compas_rhino._get_ironpython_lib_path("6.0")
    print(ipylib_path)
    compas_packages = [
        (name, False) for name in os.listdir(ipylib_path)
        if name.split("_")[0] == "compas" and name != "compas_bootstrapper.py"
    ]
    results = rs.CheckListBox(compas_packages, "Select Packages to uninstall")

    if results:
        uninstall(results)
예제 #3
0
def BatchPrintLayouts():
    print "BatchPrintLayout is WIP. Use with caution."
    try:
        pages = sc.doc.Views.GetPageViews()
        if pages is None or len(pages) < 1:
            print "No layouts in file"
            return

        defaultPath = rs.DocumentPath()

        defaultName = utils.GetDatePrefix() + "_Rhino"

        filename = rs.SaveFileName("Save",
                                   "PDF (*.pdf)|*.pdf||",
                                   folder=defaultPath,
                                   filename=defaultName)
        if filename is None: return

        names = []
        for page in pages:
            names.append([page.PageName, False])
        selectedLayouts = rs.CheckListBox(names, "Select Layouts to print",
                                          "Batch Print")
        if selectedLayouts is None: return

        stop = False
        for layout in selectedLayouts:
            if layout[1] == True:
                stop = True
                break
        if stop == False:
            print "No layouts selected"
            return
        try:
            pdf = Rhino.FileIO.FilePdf.Create()
        except:
            print "Failed to load Rhino.FileIO.FilePdf.Create()"
            return
        dpi = 300
        for i, page in enumerate(pages):
            if selectedLayouts[i][1]:
                capture = Rhino.Display.ViewCaptureSettings(page, dpi)
                pdf.AddPage(capture)
        pdf.Write(filename)
        print "PDF saved to {}".format(filename)
    except IOError, e:
        print str(e)
        return
def viewCaptureToFile():
    namedViews = rs.NamedViews()
    items = []
    for view in namedViews:
        items.append([view, False])
    returnedVals = rs.CheckListBox(items, "Select Views to Export", "Extract Views")
    if returnedVals is None: return
    
    chosenViews = []
    for val in returnedVals:
        if val[1]:
            chosenViews.append(val[0])
    if len(chosenViews) < 1: return
    
    path = rs.BrowseForFolder(message = "Choose Folder to export to")
    
    if path is None: return
    
    width = rs.GetInteger("Image Width in Pixels", number = 1920, minimum = 600, maximum = 10000)
    if width is None: return
    height = .625 * width
    
    rs.AddNamedView("temp")
    
    now = datetime.date.today()
    dateList = []
    if len(str(now.month))>1:
        month = str(now.month)
    else:
        month = "0"+str(now.month)
    if len(str(now.day))>1:
        day = str(now.day)
    else:
        day = "0"+str(now.day)
    time = str(now.year)+month+day
    
    for x in chosenViews:
        rs.RestoreNamedView(x)
        fileName = "\\" + str(time) + "_" + x + ".jpg"
        filePath = path + fileName
        rs.Command("_-ViewCaptureToFile  " + str(filePath) + " w " + str(width) + " h " + str(height) + " _Enter")
    rs.RestoreNamedView("temp")
    rs.DeleteNamedView("temp")
예제 #5
0
def main():

    sourceObjects = rs.GetObjects(
        message="Select Objects to Move to Other Layers.",
        preselect=True,
        select=True)

    copy = rs.GetBoolean("Do you want to copy this layer?",
                         ("Copy", "No", "Yes"), False)
    includeList = None
    excludeList = [".3dm", "Make2D"]
    targetLayers = sorted(getLayerList.getLayers(includeList, excludeList))
    targetLayers = [(x, False) for x in targetLayers]

    destinationLayer = rs.CheckListBox(targetLayers)

    if not destinationLayer:
        return False

    rs.EnableRedraw(enable=False)

    sourceObjects = list(
        filter(lambda x: not rs.IsLayerReference(rs.ObjectLayer(x)),
               sourceObjects))

    for obj in sourceObjects:
        objLayer = rs.ObjectLayer(obj)

        parent, child = objLayer.split("::")[-2:]

        for dLayer in destinationLayer:
            if dLayer[1] == True:
                fullDLayer = dLayer[0] + "::" + child
                if not rs.IsLayer(fullDLayer):
                    print(dLayer[0] + "::" + child, objLayer)
                    fullDLayer = duplicateLayer(child, objLayer, dLayer[0])
                if copy[0] == True:
                    copyObj = rs.CopyObject(obj, translation=None)
                    rs.ObjectLayer(copyObj, layer=fullDLayer)
                else:
                    rs.ObjectLayer(obj, layer=fullDLayer)

    rs.EnableRedraw(enable=True)
def main():
    rs.EnableRedraw(enable=False)
    showList = sorted(getLayerList.getLayers(exclude=[".3dm", "Make2D"]))
    print(showList)
    showList.append("Select All")
    boxList = [(x, False) for x in showList]

    selectedLayer = rs.CheckListBox(boxList, message="Layer To Activate")

    if selectedLayer == "Select All":
        layers = sorted(list(set(topList)))
    elif selectedLayer:
        layers = [L[0] for L in selectedLayer if L[1] == True]
    else:
        return (None)
    print(layers)
    if isinstance(layers, str):
        changeColors(rs.LayerChildren(layers))
    else:
        for layer in layers:
            changeColors(rs.LayerChildren(layer))
    rs.EnableRedraw(enable=True)
예제 #7
0
def RunCommand(is_interactive):

    print('fetching conda envs....')

    envs = list_envs(show_packages=False)
    envs_dict = {}
    for env_path in envs:
        if env_path.find('envs') < 0:
            name = 'base'
        else:
            name = os.path.split(env_path)[-1]
        envs_dict[name] = env_path
    options = envs_dict.keys()

    if options:
        selected = rs.ListBox(options, "Select env to install")
        if selected:
            packages = list_package(selected)
            options = []
            for p in packages:
                if p['name'].find('compas') == 0:
                    entry = "%s   %s   %s" % (p['name'].replace('-', '_'), p['version'], p['channel'])
                    options.append((entry, False))

            if options:
                results = rs.CheckListBox(options, "Select compas packages to install from [%s]:" % selected)
                if results:
                    to_install = []
                    for package, yes in results:
                        if yes:
                            name = package.split("   ")[0]
                            to_install.append(name)
                    install_env_packages(selected, envs=envs, packages=to_install)

            else:
                print("no compas package found in env: %s" % selected)
예제 #8
0
def BatchCapture():
    try:
        namedViews = rs.NamedViews()
        if len(namedViews) < 1:
            print "There are no Named Views in this file."
            return None

        #Prepare checklis
        items = []
        for view in namedViews:
            items.append([view, False])

        #Checklist
        returnedVals = rs.CheckListBox(items, "Select Views to Export", "Batch Capture")
        if returnedVals is None: return

        chosenViews = []
        for val in returnedVals:
            if val[1]:
                chosenViews.append(val[0])
        if len(chosenViews) < 1: return

        defaultFilename = utils.GetDatePrefix() + '_FILENAME'
        #path = rs.SaveFileName('Batch Capture', "PNG (*.png)|*.png||", filename = date+'_FILENAME')
        path = rs.SaveFileName('Save view location', "PNG (*.png)|*.png|JPEG (*.jpeg)|*.jpeg||", filename = defaultFilename, extension = ".png")
        if path is None: return

        #Check if in stick
        if 'batchCapture-width' in sc.sticky:
            defaultWidth = sc.sticky['batchCapture-width']
        else:
            defaultWidth = 5100
        if 'batchCapture-height' in sc.sticky:
            defaultHeight = sc.sticky['batchCapture-height']
        else:
            defaultHeight = 3300

        #Get output width
        width =  rs.GetInteger('Width', defaultWidth, 200, 10000 )
        if width is None: return
        sc.sticky['batchCapture-width'] = width

        #Get output height
        height = rs.GetInteger('Height', defaultHeight, 200, 10000 )
        if height is None: return
        sc.sticky['batchCapture-height'] = height

        rs.AddNamedView("temp")

        baseName = os.path.splitext(path)[0]
        for eachView in chosenViews:
            rs.RestoreNamedView(eachView)

            splitPath = path.Split(".")
            if splitPath[-1] == "png":
                filePath = baseName + "_" + eachView + ".png"
                result = SafeCapture_PNG(filePath, width, height)
            else:
                filePath = baseName + "_" + eachView + ".jpg"
                result = SafeCapture_JPG(filePath, width, height)

        #return to original view
        rs.RestoreNamedView("temp")
        rs.DeleteNamedView("temp")


        result = True
    except:
        result = False
    utils.SaveFunctionData('IO-BatchCapture', [__version__] + chosenViews)
    return result
예제 #9
0
def CaptureDisplayModesToFile():
    try:
        displayModeNames = []
        displayModeBool = []
        displayModesChecked = []

        ########
        #Get current display mode
        originalDisplayMode = rc.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.DisplayMode.LocalName

        ########
        #Get default display mode selection
        if 'CaptureDisplayModes-DisplayModes' in sc.sticky:
            dict = sc.sticky['CaptureDisplayModes-DisplayModes']
            for each in rc.Display.DisplayModeDescription.GetDisplayModes():
                displayModeNames.append(each.EnglishName)
                if each.EnglishName in dict:
                    displayModeBool.append(dict[each.EnglishName])
                else:
                    displayModeBool.append(False)
        else:
            for each in rc.Display.DisplayModeDescription.GetDisplayModes():
                displayModeNames.append(each.EnglishName)
                displayModeBool.append(False)

        results = rs.CheckListBox(zip(displayModeNames, displayModeBool), 'Select Display Modes', 'Capture Display Modes To File')
        if results is None: return

        ########
        #Save display modes to sticky
        resultDict = {}
        for each in results:
            resultDict[each[0]] = each[1]
        sc.sticky['CaptureDisplayModes-DisplayModes'] = resultDict

        for each in results:
            if each[1]:
                displayModesChecked.append(each[0])

        ########
        #Get default filename
        date = utils.GetDatePrefix()
        activeView = sc.doc.Views.ActiveView.ActiveViewport.Name
        if activeView is None: activeView = 'VIEW'
        path = rs.SaveFileName('Export All Display Modes', "PNG (*.png)|*.png||", filename = date+'_'+activeView)
        if path is None: return

        ########
        #Get sizes from sticky
        if 'catpureDisplays-width' in sc.sticky:
            widthDefault = sc.sticky['catpureDisplays-width']
        else:
            widthDefault = 5100

        if 'catpureDisplays-height' in sc.sticky:
            heightDefault = sc.sticky['catpureDisplays-height']
        else:
            heightDefault = 3300

        width = rs.GetInteger('Image Width', number = widthDefault, minimum = 200, maximum = 20000)
        height = rs.GetInteger('Image Height', number = heightDefault, minimum = 200, maximum = 20000)

        ########
        #Save sizes to sticky
        sc.sticky['catpureDisplays-width'] = width
        sc.sticky['catpureDisplays-height'] = height

        #######################################################################
        #Export the images
        count = 0
        for name in displayModesChecked:
            try:
                rs.ViewDisplayMode(mode = name)
                exportImage(path, name, width, height)
                count += 1
            except:
                pass
        print "{} Images saved to {}".format(count , os.path.abspath(os.path.join(path, os.pardir)))
        result = True
    except:
        result = False
    ########
    #Restore original display mode
    if originalDisplayMode is not None:
        rs.ViewDisplayMode(mode = originalDisplayMode)

    ########
    #Save analytics
    try:
        utils.SaveFunctionData('IO-Capture Display Modes', [__version__, str(displayModesChecked), width, height, result])
    except: print "Failed to save function data"
    return result
예제 #10
0
def checkCurvePosition(objs):

    layers = []
    selection = []

    layers_low = []
    selection_low = []

    for i, obj in enumerate(objs):
        if rs.IsCurve(obj):
            if not isCurveOnCPlane(obj):
                # print "Curve {} not on Cplane".format(obj)
                selection.append(obj)
                appendLayer(layers, obj)
                if isCurveBelowCPlane(obj):
                    selection_low.append(obj)
                    appendLayer(layers_low, obj)

    # if any objects below cplane were found, abort
    if len(layers_low) > 0:
        rs.SelectObjects(selection_low)
        rs.ZoomSelected()
        redraw()

        rs.UnselectAllObjects()

        msg = "there were curves found below C-plane. Milling the router bed might damage the equipment.\n\nPlease check layers:\n"
        for layer in layers_low:
            msg = msg + "- " + layer + " \n"

        if rs.MessageBox(msg, 18, 'Warning') != 5:
            # not 5, button is not ignore
            # do not proceed with export
            return False

    # when an object is found on > 0 layers, prompt for proceed
    if len(layers) > 0:

        rs.SelectObjects(selection)
        rs.ZoomSelected()
        redraw()

        rs.UnselectAllObjects()

        list = []
        for layer in layers:
            list.append((layer, False))

        result = rs.CheckListBox(
            list,
            "there were non-planar or elevated curves found on layers below do you want to project them to XYplane",
            "ProjectToCplane")
        project = []
        if result:
            for item in result:
                if item[1]:
                    project.append(item[0])
            projectLayersToClpane(project)
        else:
            return False


#        msg = "there were non-planar or elevated curves found on layers:\n"
#        for layer in layers:
#            msg = msg + "- " + layer + " \n"
#
#        msg = msg + '\n Do you want to proceed?'
#
#
#        if rs.MessageBox(msg, 1) != 1:
#            # do not proceed with export
#            return False

    return True
예제 #11
0
steps = rs.GetInteger(message="Enter steps", number=20)
check_input(steps)
#base_height = rs.GetReal(message = "Enter base height", number = 0.5)

plinth = rs.GetBoolean("Plinth", ("plinth", "Disabled", "Enabled"), True)[0]
check_input(plinth)

plinth_lst = [plinth]
if plinth:
    plinth_height = rs.GetReal(message="Enter plinth height", number=1)
    check_input(plinth_height)
    plinth_thickness = rs.GetReal(message="Enter plinth thickness", number=0.3)
    check_input(plinth_thickness)
    if not type or not spiral:
        plinth_options = rs.CheckListBox(
            [["left side", False], ["right side", False], ["both sides", True]
             ], "which side(s)?")
        check_input(plinth_options)
    else:
        plinth_options = [("left", False), ("right", True), ("both", False)]
    plinth_lst += [plinth_height, plinth_thickness, plinth_options]

bannister = rs.GetBoolean("Bannister", ("bannister", "Disabled", "Enabled"),
                          True)[0]
check_input(bannister)
bannister_lst = [bannister]
if bannister:
    b_height = rs.GetReal(message="Enter bannister height", number=3)
    check_input(b_height)
    b_radius = rs.GetReal(message="Enter bannister radius", number=0.1)
    check_input(b_radius)
예제 #12
0
def Make2d():
    '''
    Rhinoceros Mac v5.4 WIP, 2D output improves when run with a smaller subset of objects.
    This macro generates 2D curves in three stages:
        1. Surface and intersections
        2. Surface U IsoCurves
        2. Surface V IsoCurves
    Due to form complexity, rounding issues/floating point mathematics,
    manual correction may be required.

    [1](https://gist.github.com/bengolder/3959792)
    [2](http://archiologics.com/2011-10-20-15-32-52/rhino-scripts/animation-tools/81-rvb-batch-render-make2d)
    [3](https://github.com/localcode/rhinopythonscripts/blob/master/Make2D.py)
    [4](http://docs.mcneel.com/rhino/5/help/en-us/commands/make2d.htm)
    '''
    def run():
        RunScript(
            '-Make2D  DrawingLayout=CurrentView ' + 'ShowTangentEdges=Yes ' +
            'CreateHiddenLines=No ' + 'MaintainSourceLayers=Yes ' + 'Enter ',
            True)

        rs.CurrentLayer('Default')

    baseLayers = [layer('PolySurfaces', 1), layer('Intersect', 'Curves')]

    # Allow user to select required views
    views = [(view, True) for i, view in enumerate(rs.NamedViews())]
    result = rs.CheckListBox(views, 'Select Views', 'Make2D')

    for view in [item[0] if item[1] else None for item in result]:
        if view is not None:  # and view != 'Base'
            rs.CurrentLayer('Default')
            rs.RestoreNamedView(view)

            # Hide all Layers
            for l in rs.LayerNames():
                if l != 'Default':
                    Visible(l, False)

            # 1. Generate Outlines
            # Generate 2D curves with relaxed tolerance(s) (decrease accuracy)
            # Curves are generated twice, once per tolerance,
            # to increase coverage and minimise fragmentation.
            for i, tolerance in enumerate((0.1, 0.001)):
                rs.UnitAbsoluteTolerance(tolerance, True)

                rs.UnselectAllObjects()

                # Select objects
                for l in baseLayers:
                    if rs.IsLayer(l):
                        Visible(l, True)  # rs.LayerVisible(l, True, True)
                        rs.ObjectsByLayer(l, True)

                run()

                # Transfer 2D curves to View layer
                for l in baseLayers:
                    for child in ('lines', 'tangents'):
                        a = layer('Make2D', 'visible', child, l)
                        b = layer(view, 'visible', child, str(i), l)

                        Transfer(a, b)
                        Visible(view, False)

                PurgeLayer('Make2D')

            # 2. Generate IsoCurves
            # Decrease tolerance (increase accuracy)
            rs.UnitAbsoluteTolerance(0.0000000001, True)

            # Run Make2D once per curve direction
            for dimension in 'UV':
                isoCurves = layer('Curves', 1, 0, dimension)
                layers = list(baseLayers)  # copy
                layers.append(isoCurves)

                rs.UnselectAllObjects()

                # Select objects
                for l in layers:
                    if rs.IsLayer(l):
                        Visible(l, True)  # rs.LayerVisible(l, True, True)
                        rs.ObjectsByLayer(l, True)

                run()

                a = layer('Make2D', 'visible', 'lines', isoCurves)
                b = layer(view, 'visible', 'lines', isoCurves)

                Transfer(a, b)

                Visible(view, False)
                Visible(isoCurves, False)
                PurgeLayer('Make2D')

            # 3. Compare and remove overlapping Curves
            args = {k: [] for k in 'ab'}

            for l in baseLayers:
                for child in ('lines', 'tangents'):
                    a = layer(view, 'visible', child, 0, l)
                    b = layer(view, 'visible', child, 1, l)

                    for var in 'ab':
                        l2 = eval(var)

                        if rs.IsLayer(l2):
                            Visible(l2, True)
                            args[var].extend(rs.ObjectsByLayer(l2))

            RemoveOverlappingCurves(*args.values())
    rs.LayerPrintWidth(name, width = rs.LayerPrintWidth(source))


sourceObjects = rs.GetObjects(message="Select Object to Move", preselect=True, select=False)

allLayers = rs.LayerNames()
topList = []
for layer in allLayers:
    if re.search("::", layer):
            layer = layer.split("::")[0]
    if rs.LayerChildCount(layer) > 0:
        topList.append(layer)

topList = sorted(list(set(topList)))
topList = [(x, False) for x in topList]
destinationLayer = rs.CheckListBox(topList)
rs.EnableRedraw(enable=False)
for obj in sourceObjects:
    objLayer = rs.ObjectLayer(obj)
    try:
        parent, child = objLayer.split("::")[-2:]
    except:
        pass
        
    for dLayer in destinationLayer:
        if dLayer[1] == True:
            fullDLayer = dLayer[0] + "::" + child
            if not rs.IsLayer(fullDLayer):
                print(dLayer[0]+"::"+child, objLayer)
                fullDLayer = duplicateLayer(child, objLayer, dLayer[0])   
            if copy[0] == True: