Esempio n. 1
0
def setLayerMat(layer, color):
    index = scriptcontext.doc.Materials.Add()
    mat = scriptcontext.doc.Materials[index]
    mat.DiffuseColor = color
    mat.Name = layer
    print((mat.MaterialIndex))
    exist_mat = rs.LayerMaterialIndex(layer)
    if exist_mat == -1:

        mat.CommitChanges()
        rs.LayerMaterialIndex(layer, mat.MaterialIndex)
Esempio n. 2
0
def unifyColor(layer):
    layer_c = rs.LayerColor(layer)
    layer_m = rs.LayerMaterialIndex(layer)
    if layer_m == -1:
        layer_m = rs.AddMaterialToLayer(layer)
    rs.MaterialColor(layer_m, layer_c)
    rs.LayerPrintColor(layer, layer_c)
def SampleSynchronizeRenderColors():

    objects = rs.AllObjects()
    if objects is None: return

    for obj in objects:

        color = rs.ObjectColor(obj)
        source = rs.ObjectColorSource(obj)
        material = -1

        if source == 0:
            layer = rs.ObjectLayer(obj)
            material = rs.LayerMaterialIndex(layer)
            if material < 0:
                material = rs.AddMaterialToLayer(layer)

        elif source == 1:
            material = rs.ObjectMaterialIndex(obj)
            if material < 0:
                material = rs.AddMaterialToObject(obj)

        if material >= 0:
            if color != rs.MaterialColor(material):
                rs.MaterialColor(material, color)

    rs.Redraw()
def objMatNameToLayer(guids):
    for guid in guids:
        obj = rs.coercerhinoobject(guid)

        #This gets the layers material index
        objLay = rs.ObjectLayer(obj)
        a = rs.LayerMaterialIndex(objLay)

        #This gets the 'By Object' Material Index
        material_index = obj.Attributes.MaterialIndex

        #Get material name from index
        rhino_material = sc.doc.Materials[
            a]  #<This is where you change the material to look up
        material_color = rhino_material.DiffuseColor
        material_name = rhino_material.Name

        print rhino_material.Name
        layer_index = sc.doc.Layers.Find(material_name, True)
        if layer_index >= 0:
            obj.Attributes.LayerIndex = layer_index
            obj.CommitChanges()
        else:
            new_layer_index = sc.doc.Layers.Add(material_name, material_color)
            obj.Attributes.LayerIndex = new_layer_index
            obj.CommitChanges()
def iterate():
    colDelta = 20
    origLayer = rs.GetLayer("Select Layer to Iterate")
    if origLayer is None:
        return

    shortName = origLayer.split("::")[-1]
    parentLay = rs.ParentLayer(origLayer)
    nameParts = shortName.split("_")
    if len(nameParts) > 1:
        num = int(nameParts[1]) + 1
    else:
        num = 1
    if len(str(num)) == 1:
        newNum = "0" + str(num)
    else:
        newNum = str(num)
    newName = nameParts[0] + "_" + newNum
    lay1 = rs.CurrentLayer(origLayer)

    #MAterials
    matIndex = rs.LayerMaterialIndex(lay1)

    #New Color
    oldCol = rs.LayerColor(lay1)
    oldRed = rs.ColorRedValue(oldCol)
    oldGreen = rs.ColorGreenValue(oldCol)
    oldBlue = rs.ColorBlueValue(oldCol)

    newRed = oldRed + randCol(colDelta)
    if newRed > 255:
        newRed = 255 - (newRed - 255)
    if newRed < 0:
        newRed = abs(newRed)

    newGreen = oldGreen + randCol(colDelta)
    if newGreen > 255:
        newGreen = 255 - (newGreen - 255)
    if newGreen < 0:
        newGreen = abs(newGreen)

    newBlue = oldBlue + randCol(colDelta)
    if newBlue > 255:
        newBlue = 255 - (newBlue - 255)
    if newBlue < 0:
        newBlue = abs(newBlue)
    newCol = (newBlue, newGreen, newBlue)
    newLay = rs.AddLayer(newName, color=newCol, parent=parentLay)
    #print nameParts
    #print newName
    finalLayer = rs.CurrentLayer(newLay)
    #sc.doc.Layers.CurrentLayer.RenderMaterialIndex = 3
    #c = sc.doc.Layers.CurrentLayer.RenderMaterialIndex
    #sc.doc.Layers.Modify(
    #Rhino.DocObjects.Tables.LayerTable.CurrentLayer.r
    #sc.doc.Views.Redraw()
    #b = sc.doc.Layers.CurrentLayer
    #print ""
    return
Esempio n. 6
0
def set_layer_properties(layer, properties):
    """Set Rhino layer properties."""

    rs.LayerVisible(layer, properties.get("LayerVisible"))
    rs.LayerLocked(layer, properties.get("LayerLocked"))
    rs.LayerColor(layer, hex_to_rbg(properties.get("LayerColor")))
    rs.LayerMaterialIndex(layer, properties.get("LayerMaterialIndex"))
    rs.LayerLinetype(layer, properties.get("LayerLinetype"))
    rs.LayerPrintColor(layer, hex_to_rbg(properties.get("LayerPrintColor")))
    rs.LayerPrintWidth(layer, properties.get("LayerPrintWidth"))
def ExportAsSKP(objs, newFolder, newFolderName):
    tempLayers = []
    
    copiedObjs = []
    
    rs.StatusBarProgressMeterShow('Exporting to SKP', 0, len(objs))
    
    for i, obj in enumerate(objs):
        tempCopy = rs.CopyObject(obj)
        rs.ObjectLayer(tempCopy, rs.ObjectLayer(obj))
        copiedObjs.append(tempCopy)
        rs.StatusBarProgressMeterUpdate(i)
    
    for obj in copiedObjs:
        shortName = rs.LayerName(rs.ObjectLayer(obj), False)
        layerName = newFolderName + '_' + shortName
        if rs.IsLayer(layerName):
            rs.ObjectLayer(obj, layerName)
        else:
            matIndex = rs.LayerMaterialIndex(rs.ObjectLayer(obj))
            newLayer = rs.AddLayer(layerName, rs.LayerColor(rs.ObjectLayer(obj)))
            rs.LayerMaterialIndex(newLayer, matIndex)
            tempLayers.append(newLayer)
            rs.ObjectLayer(obj, newLayer)
    rs.StatusBarProgressMeterHide()
    
    try:
        filepath = os.path.join(newFolder,newFolderName + '.skp')
        rs.SelectObjects(copiedObjs)
        rs.Command('-_Export ' + '"' + filepath + '"' + ' s SketchUp2015 Enter ', False)
        
        #CLEANUP
        rs.UnselectAllObjects() 
        try:
            rs.DeleteObjects(copiedObjs)
        except:
            rs.DeleteObject(copiedObjs)
        for layer in tempLayers:
            rs.DeleteLayer(layer)
    except:
        print "export failed"
def get_layer_properties(layer):
    """Get Rhino layer properties."""

    return {
        "LayerVisible": rs.LayerVisible(layer),
        "LayerLocked": rs.LayerLocked(layer),
        "LayerColor": rgb_to_hex(rs.LayerColor(layer)),
        "LayerMaterialIndex": rs.LayerMaterialIndex(layer),
        "LayerLinetype": rs.LayerLinetype(layer),
        "LayerPrintColor": rgb_to_hex(rs.LayerPrintColor(layer)),
        "LayerPrintWidth": rs.LayerPrintWidth(layer)
    }
def applyVrayMatToLayer(layer, matName):
    """
    applies vray mat to a layer
    input: layer, single layer name - matName: Vray mat string e.g. /glass_architectural
    returns: None
    """
    srf = rs.AddSphere([0,0,0], 1)
    rs.SelectObject(srf)
    rs.Command("-_visApplyMaterial "+matName)
    matIndex = rs.ObjectMaterialIndex(srf)
    rs.LayerMaterialIndex(layer, matIndex)
    rs.DeleteObject(srf)
    return None
def changeColors(childLayers):
    print(childLayers)
    for childLayer in childLayers:
        for name, color in colorDict.items():
            color = rs.coercecolor(color)
            if re.search('HATCH-' + name + '$', childLayer):
                print(childLayer)
                rs.LayerPrintColor(childLayer, color)
                rs.LayerColor(childLayer, color)
                layer_c = rs.LayerColor(childLayer)
                layer_m = rs.LayerMaterialIndex(childLayer)
                if layer_m == -1:
                    layer_m = rs.AddMaterialToLayer(childLayer)
                rs.MaterialColor(layer_m, layer_c)
Esempio n. 11
0
def processObject(object, parentInstances):
    global g_instances
    global g_instancesByName
    global g_parts
    global g_materials

    name = rs.ObjectName(object)
    if not name:
        name = "Unnamed"
    type = rs.ObjectType(object)
    layer = rs.ObjectLayer(object)

    if type == rs.filter.instance:
        type = rs.BlockInstanceName(object)

        xform = rs.BlockInstanceXform(object)

        # Seems like transforms are in global frame already
        # --> Probably due to exploding the block hierarchies...
        #for parent in reversed(parentInstances[1:]) :
        #    xform = parent["xform"] * xform

        subObjects = rs.ExplodeBlockInstance(object)

        fullName = name
        if len(parentInstances) > 1:
            for parent in parentInstances[1:]:
                fullName = parent["name"] + "." + fullName
        originalFullName = fullName

        appendixCtr = 1
        while fullName in g_instancesByName:
            fullName = format("%s+%d" % (originalFullName, appendixCtr))
            appendixCtr += 1
        if fullName != originalFullName:
            print("WARNING: Renamed %s => %s" % (originalFullName, fullName))

        instance = \
        {
               "name" : name,
           "fullName" : fullName,
               "type" : type,
              "xform" : xform,
            "parents" : list(parentInstances),
              "parts" : [],
            "touched" : False,
        }
        g_instances.append(instance)
        g_instancesByName[fullName] = instance

        for subObject in subObjects:
            processObject(subObject, parentInstances + [instance])
        return

    skipReason = None
    if rs.LayerLocked(layer):
        skipReason = "layer locked"
    elif not rs.LayerVisible(layer):
        skipReason = "layer hidden"
    elif type != rs.filter.polysurface and type != rs.filter.surface:
        skipReason = "bad type - " + typeStr[type]

    if skipReason:
        # make sure we can delete object by moving to current layer
        rs.ObjectLayer(object, rs.CurrentLayer())
        print("Skipping %s (%s)" % (str(object), skipReason))
    else:
        brep = rs.coercebrep(object)
        meshes = rc.Geometry.Mesh.CreateFromBrep(brep, g_meshParams)
        joinedMesh = rc.Geometry.Mesh()
        for mesh in meshes:
            joinedMesh.Append(mesh)
        joinedMesh.Reduce(0, False, 10, False)
        if not joinedMesh.Faces.ConvertQuadsToTriangles():
            print("WARNING: Failed to convert quads to tris for %s" %
                  (str(object)))
        if not joinedMesh.Compact():
            print("WARNING: Failed to compact %s" % (str(object)))

        materialSrc = rs.ObjectMaterialSource(object)
        if materialSrc == 0:
            materialIdx = rs.LayerMaterialIndex(rs.ObjectLayer(object))
        else:
            materialIdx = rs.ObjectMaterialIndex(object)

        material = rs.MaterialName(materialIdx)
        if not material:
            material = "None"
        g_materials[material] = materialIdx

        joinedMeshGuid = sc.doc.Objects.AddMesh(joinedMesh)
        rs.ObjectName(joinedMeshGuid, name)
        rs.ObjectMaterialSource(joinedMeshGuid, 1)
        rs.ObjectMaterialIndex(joinedMeshGuid, materialIdx)

        part = \
        {
                "name" : name,
                "mesh" : joinedMesh,
            "instance" : parentInstances[-1],
            "material" : material,
        }
        parentInstances[-1]["parts"].append(part)
        if not parentInstances[-1]["touched"]:
            for parentInstance in parentInstances:
                parentInstance["touched"] = True
        g_parts.append(part)

    rs.DeleteObject(object)
import rhinoscriptsyntax as rs

layer = rs.CurrentLayer()
layer_c = rs.LayerColor(layer)
layer_m = rs.LayerMaterialIndex(layer)
if layer_m == -1:
    layer_m = rs.AddMaterialToLayer(layer)
rs.MaterialColor(layer_m, layer_c)
rs.LayerPrintColor(layer, layer_c)
"""
For use with the Feasibility Study Workflow. 
See "F:\Resource\Strategic Initiatives\0702013.20 Research Initiative\Rhino Workflow"

For use with Feasibility Study Assistant Grasshopper Script.
See "F:\Resource\Strategic Initiatives\0702013.20 Research Initiative\Grasshopper\Grasshopper Toolset\Feasibility Drafting and modeling Assistant"

This script is to create a subfolder to a hatch layer that specifies it as an 
open area, as you might label as "OPEN TO BELOW" in floor plans.

Make sure the layer you want to add an OPEN layer to is the currently selected layer
before running.

"""

import rhinoscriptsyntax as rs

currentLayer = rs.CurrentLayer()
layerName = rs.LayerName(currentLayer, fullpath=False)
newLayer = rs.AddLayer(name=layerName+"_OPEN")
rs.ParentLayer(newLayer, currentLayer)


layer_c = rs.LayerColor(currentLayer)
layer_m = rs.LayerMaterialIndex(currentLayer)
if layer_m == -1:
    layer_m = rs.AddMaterialToLayer(newLayer)
rs.MaterialColor(layer_m, layer_c)
rs.LayerPrintColor(newLayer, layer_c)
rs.LayerColor(newLayer, layer_c)
Esempio n. 14
0
def exportToRenderSKP():
    #try:
    #Get Objects
    objs = rs.GetObjects("Select objects to export", preselect = True)
    if objs is None: return
    
    #Default Name
    if 'exportToRenderSKP-prevName' in sc.sticky:
        prevName = sc.sticky['exportToRenderSKP-prevName']
        defaultFilename = utils.UpdateString(prevName)
    else:
        defaultFilename = utils.GetDatePrefix() + '_OPTION_01'
    
    #Default Folder
    if 'exportToRenderSKP-path' in sc.sticky:
        defaultFolder = sc.sticky['exportToRenderSKP-path']
    elif utils.IsSavedInProjectFolder():
        origPath = rs.DocumentPath()
        path = os.path.normpath(origPath)
        pathParts = path.split(os.sep)
        projectFolder = os.path.join(pathParts[0],'\\' ,pathParts[1])
        referenceFolder = os.path.join(projectFolder, r'03 DRAWINGS\02 RENDERING\0_copy 3d  folder structure\Reference')
        if os.path.isdir(referenceFolder):
            print "Reference folder exists"
            defaultFolder = referenceFolder
        else:
            print "Reference folder not found"
            defaultFolder = rs.DocumentPath()
    else:
        defaultFolder = rs.DocumentPath()
    fileName = rs.SaveFileName("Export to render", "Sketchup 2015 (*.skp)|*.skp||", folder = defaultFolder, filename = defaultFilename)
    if fileName is None: return
    sc.sticky['exportToRenderSKP-prevName'] = os.path.splitext(fileName)[0]
    sc.sticky['exportToRenderSKP-path'] = os.path.dirname(fileName)
    
    tempLayers = []
    copiedObjs = []
    seperator = ' > '
    baseName = os.path.splitext(os.path.basename(fileName))[0]

    #Copy all objects to export
    rs.StatusBarProgressMeterShow('Exporting to SKP', 0, len(objs))
    for i, obj in enumerate(objs):
        tempCopy = rs.CopyObject(obj)
        if rs.IsBlockInstance(tempCopy):
            explodedObjs = list(rs.ExplodeBlockInstance(obj, True))
            copiedObjs += explodedObjs
        else:
            copiedObjs.append(tempCopy)
        rs.StatusBarProgressMeterUpdate(i)

    #Move all copies to a different layer
    for i, obj in enumerate(copiedObjs):
        layerFullName = rs.ObjectLayer(obj)
        shortName = layerFullName.replace('::', seperator)
        layerName = baseName + seperator + shortName
        if rs.IsLayer(layerName):
            rs.ObjectLayer(obj, layerName)
        else:
            matIndex = rs.LayerMaterialIndex(rs.ObjectLayer(obj))
            newLayer = rs.AddLayer(layerName, rs.LayerColor(rs.ObjectLayer(obj)))
            rs.LayerMaterialIndex(newLayer, matIndex)
            tempLayers.append(newLayer)
            rs.ObjectLayer(obj, newLayer)
    rs.StatusBarProgressMeterHide()

    try:
        rs.SelectObjects(copiedObjs)
        rs.Command('-_Export ' + '"' + fileName + '"' + ' s SketchUp2015 Enter ', False)

        #CLEANUP
        rs.UnselectAllObjects()
        try:
            rs.DeleteObjects(copiedObjs)
        except:
            rs.DeleteObject(copiedObjs)
        for layer in tempLayers:
            rs.DeleteLayer(layer)
    except:
        print "export failed"
    result = True
    #except:
    #    result = False
    try:
        pass
        #utils.SaveFunctionData('IO-Export to Render[SKP]', [fileName, baseName, os.path.getsize(fileName),len(objs), result])
    except:
        print "Failed to save function data"
    return result
Esempio n. 15
0
currentLayer = rs.CurrentLayer()

for entry in layerDict:

    cLayerName = currentLayer + "::" + entry

    if cLayerName not in rs.LayerNames():
        rs.AddLayer(entry,
                    rs.coercecolor(layerDict[entry]['LayerColor']),
                    parent=currentLayer)
    elif rs.LayerLinetype(cLayerName) is not (
            layerDict[entry]['LayerLinetype']):
        rs.LayerLinetype(cLayerName, layerDict[entry]['LayerLinetype'])

    rs.LayerColor(cLayerName, rs.coercecolor(layerDict[entry]['LayerColor']))
    rs.LayerLinetype(cLayerName, layerDict[entry]['LayerLinetype'])
    rs.LayerPrintWidth(cLayerName, layerDict[entry]['LayerPrintWidth'])
    rs.LayerPrintColor(cLayerName,
                       rs.coercecolor(layerDict[entry]['LayerPrintColor']))

    if re.search("-HATCH-", cLayerName):
        layer_c = rs.coercecolor(rs.LayerColor(cLayerName))
        layer_m = rs.LayerMaterialIndex(cLayerName)
        if layer_m == -1:
            layer_m = rs.AddMaterialToLayer(cLayerName)
        rs.MaterialColor(layer_m, layer_c)
        rs.LayerPrintColor(cLayerName, layer_c)

rs.EnableRedraw(enable=True)