Example #1
0
import rhinoscriptsyntax as rs

from compas.geometry import discrete_coons_patch

from compas.utilities import geometric_key

from compas.datastructures import Mesh

from compas_rhino.artists.meshartist import MeshArtist

if __name__ == '__main__':

    div = 15

    crvs = rs.GetObjects("Select four curves (in order)", 4)

    sets_pts = [rs.DivideCurve(crv, div) for crv in crvs]

    ab, bc, dc, ad = sets_pts
    points, faces = discrete_coons_patch(ab, bc, dc, ad)

    mesh = Mesh.from_vertices_and_faces(points, faces)

    artist = MeshArtist(mesh, layer='coons_mesh')
    artist.draw()
Example #2
0
        x, y, z = rs.BrepClosestPoint(srf, mesh.vertex_coordinates(key))[0]
        attr['x'] = x
        attr['y'] = y
        attr['z'] = z

    conduit.redraw()


if __name__ == '__main__':

    # set the remeshing parameters
    trg_l = 0.65
    kmax = 300

    crvs = rs.GetObjects("Select boundary curves", 4)
    srf = rs.GetObject("Select nurbs srf", 8)

    sets_pts = [
        rs.DivideCurve(crv, round(rs.CurveLength(crv) / trg_l, 0))
        for crv in crvs
    ]

    sets_pts = sort_pts(sets_pts)

    # cull duplicate points
    points = []
    for pts in sets_pts:
        points += pts[1:]

    # construct delaunay mesh
Example #3
0
import math
import random

#functions
#to draw points if necessary
def drawPts(PTLIST):
    rs.EnableRedraw(False)
    for i in range(len(PTLIST)):
        for j in range(len(PTLIST[i])):
            rs.AddPoint(PTLIST[i][j])
    rs.EnableRedraw(True)

#identify surface
srf = rs.GetObject("Select surface", 8+16) #specify surface GUID
#identify crvs
crvs = rs.GetObjects("Select polylines", 4) #specify curves GUID

proj_crvs = rs.ProjectCurveToSurface(crvs, srf, (0,0,1))

crvPts = []
for i in range(len(proj_crvs)):
    nowCrv = proj_crvs[i]
    nowCrvPts = rs.CurvePoints(nowCrv)
    crvPts.append(nowCrvPts)


#generate text file
DEM_file = open("170131_PATHtest.txt", "w")

for i in range(len(crvPts)):
    newLine = ""
Example #4
0
import compas_rhino as rhino
from compas_rhino.geometry import RhinoGeometry

from compas.datastructures.mesh import Mesh
from compas_pattern.datastructures.pseudo_quad_mesh import PseudoQuadMesh
from compas_pattern.datastructures.pseudo_quad_mesh import pqm_from_mesh
from compas_pattern.cad.rhino.utilities import draw_mesh

from compas_pattern.algorithms.editing import editing

# mesh selection
guid = rs.GetObject('get mesh')
mesh = RhinoGeometry.from_guid(guid)
vertices, faces = mesh.get_vertices_and_faces()
mesh = PseudoQuadMesh.from_vertices_and_faces(vertices, faces)

poles = rs.GetObjects('pole points', filter=1)
if poles is None:
    poles = []
poles = [rs.PointCoordinates(pole) for pole in poles]

vertices, face_vertices = pqm_from_mesh(mesh, poles)

mesh = PseudoQuadMesh.from_vertices_and_faces(vertices, face_vertices)

editing(mesh)

mesh = mesh.to_mesh()

mesh_guid = draw_mesh(mesh)
Example #5
0
def objsSetQuickTag():
    objs = rs.GetObjects('select objects to tag', preselect=True)
    tagVal = rs.GetString('Tag Value')
    map(lambda x: setQuickTag(x, tagVal), objs)
def MultiNestedBoundaryTrimCurves():
    msg = "Select closed boundary curves for trimming"
    TCrvs = rs.GetObjects(msg, 4, preselect=False)
    if not TCrvs: return

    cCrvs = [crv for crv in TCrvs if rs.IsCurveClosed(crv)]
    if len(cCrvs) == 0:
        print "No closed trim curves found"
        return
    rs.LockObjects(cCrvs)

    origCrvs = rs.GetObjects("Select curves to trim", 4)
    rs.UnlockObjects(cCrvs)
    if not origCrvs: return

    #plane which is active when trim curve is chosen
    refPlane = rs.ViewCPlane()

    if sc.sticky.has_key("TrimSideChoice"):
        oldTSChoice = sc.sticky["TrimSideChoice"]
    else:
        oldTSChoice = True

    choice = [["Trim", "Outside", "Inside"]]
    res = rs.GetBoolean("Side to trim away?", choice, [oldTSChoice])
    if not res: return
    trimIns = res[0]  #False=Outside

    tol = sc.doc.ModelAbsoluteTolerance
    bb = rs.BoundingBox(origCrvs, refPlane)  #CPlane box, world coords
    if not bb: return
    zVec = refPlane.ZAxis

    rs.EnableRedraw(False)
    botPlane = Rhino.Geometry.Plane(bb[0] - zVec, zVec)  #check
    xform = rs.XformPlanarProjection(botPlane)
    cutCrvs = rs.TransformObjects(cCrvs, xform, True)
    ccc = CheckPlanarCurvesForCollision(cutCrvs)
    if ccc:
        msg = "Boundary curves overlap, results may be unpredictable, continue?"
        res = rs.MessageBox(msg, 1 + 32)
        if res != 1: return
    bSrfs = rs.AddPlanarSrf(cutCrvs)
    rs.DeleteObjects(cutCrvs)
    if bSrfs == None: return

    line = rs.AddLine(bb[0] - zVec, bb[4] + zVec)
    vols = []
    for srf in bSrfs:
        ext = rs.ExtrudeSurface(srf, line, True)
        if ext != None: vols.append(ext)
    rs.DeleteObjects(bSrfs)
    rs.DeleteObject(line)
    if len(vols) == 0: return
    exGroup = rs.AddGroup()
    rs.AddObjectsToGroup(vols, exGroup)

    rs.Prompt("Splitting curves...")
    rs.SelectObjects(origCrvs)
    rs.Command("_Split _-SelGroup " + exGroup + " _Enter", False)
    splitRes = rs.LastCreatedObjects()
    rs.DeleteGroup(exGroup)

    rs.Prompt("Classifying trims...")
    noSplit = []
    for crv in origCrvs:
        #add curve to list if it has not been split (still exists in doc)
        id = sc.doc.Objects.Find(crv)
        if id != None: noSplit.append(crv)

    errors = 0
    if splitRes:
        if len(noSplit) > 0: splitRes.extend(noSplit)
        for crv in splitRes:
            inside = MultiTestInOrOut(crv, vols)
            if inside != None:
                if (inside and trimIns) or (not inside and not trimIns):
                    rs.DeleteObject(crv)
            else:
                errors += 1
    rs.DeleteObjects(vols)
    if errors > 0: print "Problems with {} curves".format(errors)
    sc.sticky["TrimSideChoice"] = trimIns
Example #7
0
import rhinoscriptsyntax as rs
import trkRhinoPy as trp

objs = rs.GetObjects("Select surfaces", rs.filter.surface, preselect=True)
rs.EnableRedraw(False)


def calcArea(srfs):
    areas = []
    for srf in srfs:
        areas.append(rs.SurfaceArea(srf)[0])
    totalArea = sum(areas)
    # totalAreaPy = totalArea/3.3058
    # print(area, areapy)
    # txt = rs.ClipboardText(area)
    return totalArea


siteKeys = ("site area", "legal scr", "legal far")


def getSiteCoverage(objs):
    designCoverageArea = calcArea(objs)
    return designCoverageArea


def runTest():
    areas = (createCoverage(objs), createFloors(objs))
    sitearea = float(rs.GetDocumentUserText("site area"))
    legalscr = float(rs.GetDocumentUserText("legal scr"))
    legalfar = float(rs.GetDocumentUserText("legal far"))
Example #8
0
import rhinoscriptsyntax as rs
import math
import codecs

crvs = rs.GetObjects("Select curves", 4)
distance_x = rs.GetReal("Vertical Distance", 0.4)
filament = rs.GetReal("Filament Diameter", 1.75)
Layerheight = rs.GetReal("Layer Height", 0.2)
extrude_temp = rs.GetReal("Extrude temperture", 205)
bed_temp = rs.GetReal("Bed temperture", 60)
printspeed = rs.GetReal("Print speed", 2500)
multi = rs.GetReal("Extrude multiply", 1.0)
line_number = (len(crvs))
filename = rs.SaveFileName("Save", "G-code (*.gcode)|*.gcode||")
f = codecs.open(filename, 'w', 'utf-8')

f.write('G90\n')
f.write('M83\n')
f.write('M106 S0\n')
f.write('M140 S{0}\n'.format(bed_temp))
f.write('M104 S{0} T0\n'.format(extrude_temp))
f.write('M109 S{0} T0\n'.format(extrude_temp))
f.write('G28\n')
f.write('G92 E0\n')
f.write('G1 E-1.0000 F1800\n')
f.write("G1 Z6.475 F1000\n")
f.write(";first z = 0.18\n")

for l in range(line_number):
    startPoint = rs.CurveStartPoint(crvs[l])
    endPoint = rs.CurveEndPoint(crvs[l])
Example #9
0
import rhinoscriptsyntax as rs
import os


def AutoExport(objs):
    appData = os.getenv('APPDATA')
    targetFolder = appData + r"\PCPA\temp.dwg"
    rs.SelectObjects(objs)
    rs.Command(
        '-_Export ' + '"' + targetFolder + '"' + ' s "2007 Natural" Enter ',
        True)


objs = rs.GetObjects()
AutoExport(objs)
from compas_3gs.rhino import rhino_vertex_modify_fixity
from compas_3gs.rhino import rhino_volmesh_vertex_lift

from compas_3gs.rhino import draw_vertex_fixities

try:
    import rhinoscriptsyntax as rs
except ImportError:
    compas.raise_if_ironpython()

# ------------------------------------------------------------------------------
# 1. make vomesh from rhino polysurfaces
# ------------------------------------------------------------------------------
layer_force = 'force_volmesh'

guids = rs.GetObjects("select polysurfaces", filter=rs.filter.polysurface)
rs.HideObjects(guids)

forcediagram = ForceVolMesh()
forcediagram = volmesh_from_polysurfaces(forcediagram, guids)
forcediagram.layer = layer_force
forcediagram.attributes['name'] = layer_force

forcediagram.draw_faces()
forcediagram.draw_edges()
forcediagram.draw_vertices()

# ------------------------------------------------------------------------------
# 2. modify volmesh vertices
# ------------------------------------------------------------------------------
Example #11
0
        vkeys.append(vkey)

    for i, key in enumerate(face_vkeys):
        try:
            index = keys.index(key)
            face_vkeys[i] = vkeys[index]
        except:
            pass
    mesh.add_face(face_vkeys)
    del mesh.face[fkey]

    mesh_unify_cycle_directions(mesh)


#create mesh from polylines
polylines = rs.GetObjects("Select Polylines", 4)
polys = get_polyline_points(polylines)
points = get_points_from_polylines(polys)
polys = get_faces_from_polylines(polys, points)
mesh_faces = [polys[key]['indices'] for key in polys]
mesh_vertices = points

mesh_obj = RhinoMesh.from_vertices_and_faces(mesh_vertices, mesh_faces)
mesh_unify_cycle_directions(mesh_obj)

#get fixed nodes
fixed = []
fixed_objs = rs.ObjectsByLayer("SD_fixed")
fixed_coords = [rs.PointCoordinates(obj) for obj in fixed_objs]
if fixed_objs:
    for i, vertex in enumerate(mesh_vertices):
Example #12
0
import rhinoscriptsyntax as rs

objs = rs.GetObjects('select objs',
                     rs.filter.surface | rs.filter.curve | rs.filter.point,
                     preselect=True)
grade = rs.GetString("toggle grade")


def boolToggle(grade):
    if len(grade) == 0:
        return False
    else:
        return True


def srfPtZPair(srf):
    domainU = rs.SurfaceDomain(srf, 0)
    domainV = rs.SurfaceDomain(srf, 1)
    u = domainU[1] / 2.0
    v = domainV[1] / 2.0
    point = rs.EvaluateSurface(srf, u, v)
    el = round(point.Z, 3)
    return [srf, el]


def crvPtZpair(crv):
    domain = rs.CurveDomain(crv)
    t = domain[1] / 2.0
    point = rs.EvaluateCurve(crv, t)
    el = round(point.Z, 3)
    return [crv, el]
Example #13
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
Example #14
0
def exportToRenderDWG():
    try:
        fileLocations = config.GetDict()

        print "Exporting to 3ds max"
        objs = rs.GetObjects("Select objects to export", preselect=True)
        if objs is None: return

        #SAVE FILE NAME
        defaultFolder = rs.DocumentPath()
        defaultFilename = utils.GetDatePrefix() + '_OPTION_01'
        fileName = rs.SaveFileName("Export to render", "Autocad (*.dwg)|*.dwg||", defaultFolder, defaultFilename)
        if fileName is None: return
        base=os.path.basename(fileName)
        cadName = os.path.splitext(base)[0]

        #SUPER EXPLODE
        #EXPLODE SELECTED BLOCKS (CHECKLIST)
            #blockNames = rs.BlockNames(True)
            #print blockNames

            #results = rs.CheckListBox(blockNames, "Select blocks to explode", "Explode for render")
        #CHECK BACKFACES
        #CHECK GEOMETRY
        #EXPORT EACH LAYER AS SAT FILE.
        #CHECK ORIGIN
        #INSERT ORIGIN

        #CHECK SCALE (Units)
        if rs.UnitSystem() == 8:
            print "Units checked"
        else:
            print "This model is in {}, it should be in Inches".format(rs.UnitSystemName(singular=False))

        #UNIFY MESH NORMALS
        #MERGE ALL EDGES
        #MERGE ALL FACES

        #DELETE DUPS
        #rs.UnselectAllObjects()
        #rs.Command('-_Seldup ', echo=False)
        #dupObjs = rs.SelectedObjects()
        #if len(dupObjs) > 0:
        #    rs.DeleteObjects(dupObjs)
        #    print "{} duplicate objects deleted".format(len(dupObjs))

        #JOIN BY LAYER

        #PLACE UNDER A PARENT LAYER W/ DATESTAMP
        AddMasterRootLayer(cadName)

        #CHANGE LAYER NAMES?

        #IMPORT ACAD SCHEME
        standards.LoadAcadSchemes(fileLocations['ACAD Scheme Folder'])

        #SET DEFAULT FOLDER TO REFERENCE FOLDER UNDER RENDERING

        #EXPORT TO DWG
        rs.SelectObjects(objs)
        exportScheme = 'PCPA_MaxSolids'
        rs.Command('-_Export ' + '"' + fileName + '" S ' + '"' + exportScheme + '"' + ' Enter P 100 Enter', False)

        #REMOVE MASTER ROOT LAYER
        RemoveMasterRootLayer(cadName)
        return True
    except:
        return False
Example #15
0
def FilamentCalculator():
    """3D Printing filament length, weight, volume calculator."""

    input_obj = rs.SelectedObjects()
    if not input_obj:
        input_obj = rs.GetObjects("Select objects")
    if not input_obj: return

    volume = 0.0
    for o in input_obj:
        if rs.IsMesh(o):
            a, b, c = rs.MeshVolume(o)
            volume += b
        elif rs.IsObjectSolid(o):
            a, b = rs.SurfaceVolume(o)
            volume += a
    if volume == 0.0: return

    filaments = {
        "PLA": 1.24,
        "ABS": 1.05,
        "ASA": 1.07,
        "PETG": 1.27,
        "PETT": 1.45,
        "HIPS": 1.07,
        "TPU": 1.30,
        "PMMA": 1.18,
        "Nylon": 1.08,
        "Polycarbonate": 1.20,
        "Copperfill": 3.90
    }

    filament = rs.GetString("Material:", "PLA", [a for a in filaments])

    density = filaments[filament]
    volume = volume / rs.UnitScale(rs.UnitSystem(), 3)**3
    weight = volume * filaments[filament]

    l1 = volume / (math.pi * (0.175 / 2)**2) / 100
    l2 = volume / (math.pi * (0.285 / 2)**2) / 100
    l3 = volume / (math.pi * (0.3 / 2)**2) / 100

    volume = round(volume, 3)
    weight = round(weight, 3)

    l1 = round(l1, 2)
    l2 = round(l2, 2)
    l3 = round(l3, 2)

    message = """{f}:
    Density = {d} grams / cubic centimeter
    Volume = {v} cubic centimeters
    Weight ~ {w} grams
    1.75 mm filament length ~ {l1} meters
    2.85 mm filament length ~ {l2} meters
    3.00 mm filament length ~ {l3} meters"""
    message = message.format(f=filament,
                             d=density,
                             v=volume,
                             w=weight,
                             l1=l1,
                             l2=l2,
                             l3=l3)
    rs.MessageBox(message, buttons=0, title="FilamentCalculator:")
    print(message)
Example #16
0
import rhinoscriptsyntax as rs
import trkRhinoPy as trp
import scriptcontext as sc
import Rhino

objs = rs.GetObjects('select objects', preselect=True)

reverse = rs.GetString("reverse")

isreverse = trp.boolToggle(reverse)

lvlpts = sc.sticky["lvlptdict"]
planpts = sc.sticky['planptdict']

levelkeys = lvlpts.keys()

vecs = dict([(key, lvlpts[key] - planpts[key]) for key in levelkeys])


def lvlxform(obj):
    lvlkey = rs.GetUserText(obj, 'level')
    vec = vecs[lvlkey]
    if isreverse:
        vec = rs.VectorReverse(vec)
    rs.MoveObject(obj, vec)


if lvlpts and planpts and objs:
    map(lvlxform, objs)

# sc.doc = Rhino.RhinoDoc.ActiveDoc
Example #17
0
rs.AddLayer("_t")
rs.CurrentLayer("_t")

Layers = []
CurObjLayNames=[]
CurObjLayParentNames=[]

for layer in rs.LayerNames():
    if rs.IsLayerVisible(layer):
        Layers.extend([layer])
        
Layers = list(dict.fromkeys(Layers))



CurObjs = rs.GetObjects("select object to keep layers on")

for CurObj in CurObjs:
  CurObjLayId = rs.ObjectLayer(CurObj)
  CurObjLayName = rs.LayerName(CurObjLayId, fullpath=True)
  CurObjLayNames.extend([CurObjLayName])
  CurObjLayNames = list(dict.fromkeys(CurObjLayNames))
  

for name in CurObjLayNames:
    for layer in Layers:
        if rs.IsLayerParentOf(name,layer):
            CurObjLayParentNames.extend([layer])
            
    CurObjLayParentNames = list(dict.fromkeys(CurObjLayParentNames))
Example #18
0
import rhinoscriptsyntax as rs

objs = rs.GetObjects("Select Objects")
if objs:
    names = []
for obj in objs:
    name = rs.ObjectName(obj)
    if name is None: name = ""

    names.append(name)
    results = rs.PropertyListBox(objs, names, "Modify object name(s)")

    if results:
        rs.ObjectName(objs[i], results[i])
Example #19
0
    basic_2 = cen_a - rs.SurfaceAreaCentroid(exp_a[4])[0]
    basic_2 /= sqrt_length(basic_2[0], basic_2[1], basic_2[2])

    # create tranformation matrix
    M = create_matrix(basic_0, basic_1, basic_2, [0, 0, 0])

    # scale
    rs.ScaleObjects([block_a] + model_inside, cen_a,
                    [200 / L, 200 / L, 200 / L])

    # move to [0,0,0]
    rs.MoveObjects([block_a] + model_inside, -cen_a)

    # rotate
    rs.TransformObjects([block_a] + model_inside, M)

    # move to object
    rs.MoveObjects([block_a] + model_inside, cen_b)

    rs.DeleteObjects(exp_a)
    rs.DeleteObjects(exp_b)

    rs.DeleteObjects(c)


if __name__ == "__main__":
    box_a = rs.GetObject("Pick box a")
    model_inside = rs.GetObjects("Align box a")
    box_b = rs.GetObject("Pick box to align to")
    alingBlock(box_a, box_b, model_inside)
Example #20
0
import rhinoscriptsyntax as rs
from compas_pattern.algorithms.decomposition.algorithm import surface_decomposition
from compas_pattern.algorithms.decomposition.algorithm import decomposition_curves
from compas_pattern.algorithms.decomposition.algorithm import decomposition_mesh

from compas_rhino.artists import MeshArtist

guids = rs.GetObjects('get surfaces', filter=8)
crv_guids = rs.GetObjects('get curves', filter=4) or []
pt_guids = rs.GetObjects('get points', filter=1) or []
discretisation = rs.GetReal('discretisation value', 1, 0)
box = rs.BoundingBox(guids)
scale = rs.Distance(box[0], box[2])
#discretisation = 0.005 * scale
rs.EnableRedraw(False)
for srf_guid in guids:
    decomposition, outer_boundary, inner_boundaries, polyline_features, point_features = surface_decomposition(
        srf_guid, discretisation, crv_guids=crv_guids, pt_guids=pt_guids)
    mesh = decomposition_mesh(srf_guid, decomposition, point_features)
    rs.EnableRedraw(False)
    MeshArtist(mesh).draw_mesh()
    #for u, v in mesh.edges():
    #    rs.AddLine(mesh.vertex_coordinates(u), mesh.vertex_coordinates(v))
Example #21
0
import rhinoscriptsyntax as rs
import trkRhinoPy as trp

objs = rs.GetObjects('select objects', rs.filter.surface|rs.filter.polysurface, preselect=True)

rs.EnableRedraw(False)

if objs:
    map(trp.setObjAreaValue, objs)

rs.EnableRedraw(True)
Example #22
0
import rhinoscriptsyntax as rs

from compas.datastructures import Mesh
from compas_rhino.artists.meshartist import MeshArtist

from compas_rhino.utilities import get_line_coordinates
from compas.geometry import mesh_smooth_centroid

if __name__ == '__main__':

    edge_crvs = rs.GetObjects("Select edges", 4)
    lines = get_line_coordinates(edge_crvs)

    mesh = Mesh.from_lines(lines, delete_boundary_face=True)

    fixed = set(mesh.vertices_on_boundary())
    mesh_smooth_centroid(mesh, fixed=fixed, kmax=1, damping=0.5)

    # draw edges for selection
    artist = MeshArtist(mesh, layer='edges_hex')
    artist.draw_edges()
    artist.redraw()
Example #23
0
from groupMove import GroupMove

rectOutlineList = [] # Outline list of bounding box for nesting
objects = [] # objects selected manually for nesting
rotatedAngle = [] # rotated angle for each object to fit in bounding box
objCenter = [] # object center for later group rotation and transformation
count = 0 # Count for number of objects include in nesting operation
movingCenter = [] # center of movement from object's original position
val = True # dummy for for-loop termination
nestingComplete = True

# create boards needed for nesting (default: 1220 (mm)*2440 (mm) boards with 20 (mm) safety (x50))
boards = CreateBoard(1220, 2440, 50, 20)
while val:
    count += 1
    temp = rs.GetObjects("Select objects needed to nest (Current obj count: %d)" % count, 0, True)
    if temp:
        objects.append(temp)
    else:
        break
# Ask user for safety distance between objects (I put 22 here not 20 for a reason)
objectSpacing = rs.GetReal("Please enter safety distance between objects (default 22 (mm)): ", 22, 0, 200)
objectSpacing /= 2
# find external contour for nesting operations
listOfObjOutlines = ReturnObjectOutline(objects)
# get min bounding box list (returned) and rotated angle for fitting
rectOutlineList = GetAllRectOutline(listOfObjOutlines,rotatedAngle,objCenter,movingCenter,objectSpacing)
# Nesting operation (core heuristic) (return true if objects to nest is more then boards)
nestingComplete = RectNestingOperation(boards, rectOutlineList)
# nesting completion validation
if (not nestingComplete):
Example #24
0
def custom_constraints(mesh, surface):
    from compas_pattern.cad.rhino.utilities import surface_borders

    #surface_boundaries = surface_borders(surface, border_type = 0)

    rs.EnableRedraw(True)
    surface_boundaries = rs.GetObjects('surface boundaries', filter=4)
    rs.EnableRedraw(False)

    constraints = {}

    artist = rhino_artist.MeshArtist(mesh, layer='mesh_artist')
    artist.clear_layer()

    vertex_points = {
        rs.AddPoint(mesh.vertex_coordinates(vkey)): vkey
        for vkey in mesh.vertices()
    }
    rs.EnableRedraw(True)
    fixed_vertices = rs.GetObjects('fixed vertices', filter=1)
    if fixed_vertices is None:
        fixed_vertices = []
    vkeys = [vertex_points[vkey] for vkey in fixed_vertices]
    rs.DeleteObjects(vertex_points)
    rs.EnableRedraw(False)
    #artist.draw_vertexlabels()
    #artist.redraw()
    #vkeys = rhino.mesh_select_vertices(mesh, message = 'fixed vertices')
    #artist.clear_layer()
    #artist.redraw()

    for vkey in vkeys:
        if vkey not in constraints:
            constraints[vkey] = ('fixed', mesh.vertex_coordinates(vkey))

    # collect boundayr polylines with splits
    from compas_pattern.topology.polyline_extraction import mesh_boundaries
    mesh_boundaries = mesh_boundaries(mesh)
    split_vertices = [
        vkey for vkey, constraint in constraints.items()
        if constraint[0] == 'fixed'
    ]

    # add one vertex per mesh boundary element that has no split vertices yet, i.e. that has no corner vertices (2-valency)
    for boundary in mesh_boundaries:
        to_add = True
        for vkey in boundary:
            if vkey in split_vertices:
                to_add = False
                break
        if to_add:
            split_vertices.append(boundary[0])

    split_mesh_boundaries = []
    while len(split_vertices) > 0:
        start = split_vertices.pop()
        # exception if split vertex corresponds to a non-boundary point feature
        if not mesh.is_vertex_on_boundary(start):
            continue
        polyline = [start]

        while 1:
            for nbr, fkey in iter(mesh.halfedge[polyline[-1]].items()):
                if fkey is None:
                    polyline.append(nbr)
                    break

            # end of boundary element
            if start == polyline[-1]:
                split_mesh_boundaries.append(polyline)
                break
            # end of boundary subelement
            elif polyline[-1] in split_vertices:
                split_mesh_boundaries.append(polyline)
                split_vertices.remove(polyline[-1])
                polyline = polyline[-1:]

    srf_dots = {
        rs.AddTextDot('srf_boundary', rs.CurveMidPoint(srf_bdry)): srf_bdry
        for srf_bdry in surface_boundaries
    }

    for mesh_bdry in split_mesh_boundaries:
        if len(mesh_bdry) == 2:
            xyz = mesh.edge_midpoint(mesh_bdry[0], mesh_bdry[1])
        else:
            idx = int(math.floor(len(mesh_bdry) / 2))
            xyz = mesh.vertex_coordinates(mesh_bdry[idx])
        mesh_dot = rs.AddTextDot('?', xyz)

        rs.EnableRedraw(True)
        crv_cstr = srf_dots[rs.GetObject('boundary constraint', filter=8192)]
        rs.EnableRedraw(False)

        for vkey in mesh_bdry:
            if vkey not in constraints:
                constraints[vkey] = ('curve', crv_cstr)

        rs.DeleteObject(mesh_dot)

    rs.EnableRedraw(True)
    rs.DeleteObjects(srf_dots)
    rs.EnableRedraw(False)

    for vkey in mesh.vertices():
        if vkey not in constraints:
            constraints[vkey] = ('surface', surface)

    return constraints, surface_boundaries
Example #25
0
def main():
    pts = rs.GetObjects("select points you want to add sphere to: ", 1,True,True);
    rad = rs.GetReal("radius of spheres");
    for pt in pts:
        rs.AddSphere(pt,rad);
Example #26
0
import Rhino
import rhinoscriptsyntax as rs
import scriptcontext as sc

txt = rs.GetObject(message='select text', filter=512, preselect=True)

if rs.IsText(txt):
    text = rs.TextObjectText(txt)
    color = rs.ObjectColor(txt)

objs = rs.GetObjects(message='select objs', preselect=True)

def AddTag(obj, text, color):
    box = rs.BoundingBox(obj)
    mid = (box[0] + box[-2])/2
    tag = rs.AddTextDot(text, mid)
    rs.SetUserText(obj, 'tag', text)
    rs.ObjectColor(obj, color)
    group = rs.AddGroup()
    rs.AddObjectsToGroup([obj, tag], group)

if objs:
    map(lambda x: AddTag(x, text, color), objs)
def main():
    crvs = rs.GetObjects("Select curves to connect:", 4, True)
    connectEndpoints(crvs)
    print("Script is incomplete.  Please selDup and delete extra curves")
Example #28
0
import rhinoscriptsyntax as rs
import random

pickedCurves = rs.GetObjects("pick some curves", 4)
desiredArea = 1000.0

for curve in pickedCurves:
    length = rs.CurveLength(curve)
    extrudeAmt = desiredArea / length
    direcitonalVector = (random.uniform(-10, 10), random.uniform(-10, 10),
                         random.uniform(-10, 10))
    #how we have a vector with random x, y and z components
    #to give it the precise amplitude we want, we will normalize it, meaning it will keep the direction, but have a length of one unit
    #then, we'll scale the vector to the desired amplitude

    unitVect = rs.VectorUnitize(direcitonalVector)

    scaledVect = rs.VectorScale(unitVect, extrudeAmt)

    startPoint = rs.CurveMidPoint(curve)
    endPoint = rs.VectorAdd(startPoint, scaledVect)

    pathCurve = rs.AddLine(startPoint, endPoint)

    rs.ExtrudeCurve(curve, pathCurve)
    rs.DeleteObject(pathCurve)
    #further example: how to put the surface on a new layer
Example #29
0
import rhinoscriptsyntax as rs

#pick an object
objects = rs.GetObjects("Select components")

#Loop between my objects
for id in objects:
    name = rs.ObjectName(id)
    print "component:", name
    rc = rs.OffsetCurve(id, [0, 0, 0],  10, normal=None, style=1)
Example #30
0
__author__ = "dfmd"
__version__ = "2019.07.12"

import rhinoscriptsyntax as rs

base_curve = rs.GetObject("Reference curve", rs.filter.curve, True, True)
curves = rs.GetObjects("Curves")
tol = rs.GetReal("Tolerance", .005)

if base_curve and curves:
    try:
        base_lenght = rs.CurveLength(base_curve)
        lenght_curves = []
        for curve in curves:
            if abs(rs.CurveLength(curve) - base_lenght) < tol:
                lenght_curves.append(curve)
        rs.SelectObjects(lenght_curves)
        print "%s equal length objects found." % len(lenght_curves)

    except Exception as e:
        print('Error: %s' % e)