예제 #1
0
def offsetext():
    def RepresentsInt(s):
        try: 
            int(s)
            return True
        except ValueError:
            return False
    
    
    viste = rs.ViewNames()
    for viewport in viste:
        rs.ViewDisplayMode(viewport,"Shaded")
    diametro = rs.StringBox("dimensione della punta","10","scontornatura")
    if RepresentsInt(diametro):
        diametro = int(diametro)
    else:
        diametro = 10
    brep =  rs.GetObjects("dammi un solido",16)
    brepexp = rs.ExplodePolysurfaces(brep)
    get_val = rs.GetEdgeCurves("dammi le curve")
    surf_edge = []
    
    for i in get_val:
        surf_edge.append(i[0])
    surf_edge = rs.coerceguidlist(surf_edge)
    if len(surf_edge)>1:
        surf_edge = rs.JoinCurves(surf_edge,True)
    surface = rs.GetObjects("conferma la selezione",8,False,True,1,1)

    print surf_edge
    uv= []
    temp_edge = rs.ExplodeCurves(surf_edge,False)
    new_surface = rs.CopyObject(surface,(0,0,0))
    list_evpt =[]
    for i in temp_edge:
        evpt =rs.CurveMidPoint(i)
        print evpt
        list_evpt.append(evpt)
    for i in list_evpt:
        bord= rs.SurfaceClosestPoint(new_surface,i)
        uv.append(bord)
    for i in uv:
        rs.ExtendSurface(new_surface,i,diametro*10)
    edge = rs.OffsetCurveOnSurface(surf_edge,new_surface,-diametro)
    print edge
    if rs.CurveLength(edge)<rs.CurveLength(surf_edge):
        rs.DeleteObject(edge)
        edge =  rs.OffsetCurveOnSurface(surf_edge,new_surface,diametro)
    surf_edge = rs.ExplodeCurves(surf_edge,True)
    print edge
    
    rs.ObjectColor(edge,(0,0,255))
    for i in brepexp:
        rs.DeleteObject(i)
    for i in temp_edge:
        rs.DeleteObject(i)
    for i in surf_edge:
        rs.DeleteObject(i)
    
    rs.DeleteObjects([new_surface,surface])
예제 #2
0
def wallProfile(polySrf):

    if polySrf:
        offsets = []

        border = rs.DuplicateSurfaceBorder(polySrf)
        rs.SimplifyCurve(border)
        offsets.append(rs.OffsetCurve(border, [0, 0, 0], width / 2))

        faces = rs.ExplodePolysurfaces(polySrf, False)
        faceborders = [rs.DuplicateSurfaceBorder(face) for face in faces]
        rs.DeleteObjects(faces)

        for faceborder in faceborders:
            rs.SimplifyCurve(faceborder)
            centroid = rs.CurveAreaCentroid(faceborder)
            offsets.append(rs.OffsetCurve(faceborder, centroid[0], width / 2))

        rs.DeleteObjects(faceborders)

        srf = rs.AddPlanarSrf(offsets)

        rs.DeleteObjects(border)
        rs.DeleteObjects(offsets)
        return srf
def innerPanel():
    objs = rs.GetObjects("Select objects to add frame to", filter = 24, group = True,preselect = True)
    if objs is None:
        return
    dist = rs.GetReal("Offset Distance")
    if dist is None:
        return
    rs.EnableRedraw(False)
    
    srfs = []
    
    for obj in objs:
        if rs.IsPolysurface(obj):
            srfs = srfs + rs.ExplodePolysurfaces(obj)
        else:
            srfs.append(rs.CopyObject(obj))
    
    for srf in srfs:
        if rs.IsSurfacePlanar(srf):
            edgeCrvs = rs.DuplicateEdgeCurves(srf)
            border = rs.JoinCurves(edgeCrvs, True)
            innerEdge = rs.OffsetCurveOnSurface(border, srf, dist)
            #rs.SplitBrep(srf, innerEdge)
            rs.AddPlanarSrf(innerEdge)
            rs.DeleteObject(innerEdge)
            rs.DeleteObject(border)
        else:
            print "A surface was not planar"
    rs.DeleteObjects(srfs)
    rs.EnableRedraw(True)
예제 #4
0
def getBottomFace(obj):
    faces = rs.ExplodePolysurfaces(obj)
    output = []
    [
        output.append(face)
        if getSrfNormal(face).Z == -1 else rs.DeleteObject(face)
        for face in faces
    ]
    return output
예제 #5
0
    def setPlanarBaseSurface(self):
        '''
        set surface that is planar surface
        this surface will be made from additiveObj
        this surface will be used in offsetNonPlanarSurface()
        '''

        explodedSurfaces = rs.ExplodePolysurfaces(self.additiveObj)
        editPoint = []

        if len(explodedSurfaces) is 0:

            meshed = rhino.Geometry.Mesh.CreateFromBrep(
                rs.coercebrep(self.additiveObj))
            editPoint = rs.MeshVertices(meshed[0])
        else:

            for i in explodedSurfaces:
                meshed = rhino.Geometry.Mesh.CreateFromBrep(rs.coercebrep(i))
                vertices = rs.MeshVertices(meshed[0])
                editPoint.extend(vertices)

        rs.DeleteObjects(explodedSurfaces)

        xValues = [i[0] for i in editPoint]
        yValues = [i[1] for i in editPoint]

        xValues.sort()
        yValues.sort()

        xMin = xValues[0]
        xMax = xValues[-1]
        yMin = yValues[0]
        yMax = yValues[-1]

        lineForSur = []
        lineForSur.append(rs.AddLine((xMin, yMin, 0), (xMax, yMin, 0)))
        lineForSur.append(rs.AddLine((xMax, yMin, 0), (xMax, yMax, 0)))
        lineForSur.append(rs.AddLine((xMax, yMax, 0), (xMin, yMax, 0)))
        lineForSur.append(rs.AddLine((xMin, yMax, 0), (xMin, yMin, 0)))

        joinedCurve = rs.JoinCurves(lineForSur)
        rs.DeleteObjects(lineForSur)

        curveForSur = rs.OffsetCurve(joinedCurve, (0, 0, 1), 20)

        if len(curveForSur) > 1:
            curveForSur = rs.OffsetCurve(joinedCurve, (0, 0, 1), -20)

        self.basePlanarSurface = rs.AddPlanarSrf(curveForSur)
        rs.DeleteObjects(curveForSur)

        if self.basePlanarSurface is None:
            return False

        return True
예제 #6
0
def createSectionBox(obj):
    box = rs.BoundingBox(obj)
    bb = rs.AddBox(box)
    faces = rs.ExplodePolysurfaces(bb)
    faces = [rs.FlipSurface(x) for x in faces]
    planes = [getSrfFrame(x) for x in faces]
    clips = [rs.AddClippingPlane(x, 1000, 1000) for x in planes]
    group = rs.AddGroup()
    rs.AddObjectsToGroup(clips, group)
    return clips
예제 #7
0
def get_ref_pts(ref_obj, srf_num, indexes):
    obj_copy = rs.CopyObject(ref_obj)
    all_srf = rs.ExplodePolysurfaces(obj_copy)
    ref_srf = rs.DuplicateSurfaceBorder(all_srf[srf_num])
    ref_lines = rs.ExplodeCurves(ref_srf)
    ref_points = [
        rs.CurveEndPoint(ref_lines[indexes[0]]),
        rs.CurveEndPoint(ref_lines[indexes[1]]),
        rs.CurveEndPoint(ref_lines[indexes[2]])
    ]
    return ref_points
예제 #8
0
    def heightfield(self, density=10, over_space=True):
        """"""
        try:
            du, dv = density
        except TypeError:
            du = density
            dv = density

        du = int(du)
        dv = int(dv)

        xyz = []

        rs.EnableRedraw(False)

        if rs.IsPolysurface(self.guid):
            faces = rs.ExplodePolysurfaces(self.guid)
        elif rs.IsSurface(self.guid):
            faces = [self.guid]
        else:
            raise RhinoSurfaceError('object is not a surface')

        if over_space:
            for guid in faces:
                face = RhinoSurface(guid)
                uv = face.space(density)
                for u, v in uv:
                    xyz.append(list(rs.EvaluateSurface(face.guid, u, v)))
        else:
            for guid in faces:
                bbox = rs.BoundingBox(guid)
                xmin = bbox[0][0]
                xmax = bbox[1][0]
                ymin = bbox[0][1]
                ymax = bbox[3][1]
                xstep = 1.0 * (xmax - xmin) / (du - 1)
                ystep = 1.0 * (ymax - ymin) / (dv - 1)
                seeds = []
                for i in xrange(du):
                    for j in xrange(dv):
                        seed = xmin + i * xstep, ymin + j * ystep, 0
                        seeds.append(seed)
                points = map(list,
                             rs.ProjectPointToSurface(seeds, guid, [0, 0, 1]))
                xyz += points

        if len(faces) > 1:
            rs.DeleteObjects(faces)

        rs.EnableRedraw(True)

        return xyz
예제 #9
0
def clean_and_coerce_list(brep_list):
    #""" Ladybug - This definition cleans the list and adds them to RhinoCommon"""

    outputMesh = []
    outputBrep = []

    for id in brep_list:
        if rs.IsMesh(id):
            geo = rs.coercemesh(id)
            if geo is not None:
                outputMesh.append(geo)
                try:
                    rs.DeleteObject(id)
                except:
                    pass

        elif rs.IsBrep(id):
            geo = rs.coercebrep(id)
            if geo is not None:
                outputBrep.append(geo)
                try:
                    rs.DeleteObject(id)
                except:
                    pass

            else:
                # the idea was to remove the problematice surfaces
                # not all the geometry which is not possible since
                # badGeometries won't pass rs.IsBrep()
                tempBrep = []
                surfaces = rs.ExplodePolysurfaces(id)

                for surface in surfaces:
                    geo = rs.coercesurface(surface)
                    if geo is not None:
                        tempBrep.append(geo)
                        try:
                            rs.DeleteObject(surface)
                        except:
                            pass

                geo = JoinBreps(tempBrep, 0.01)

                for Brep in tempBrep:
                    Brep.Dispose()
                    try:
                        rs.DeleteObject(id)
                    except:
                        pass
                outputBrep.append(geo)

    return outputMesh, outputBrep
예제 #10
0
def wallBaseSrf(crv, width):
    rs.SimplifyCurve(crv)
    if rs.IsCurveClosed(crv):
        domain = rs.CurveDomain(crv)
        parameter = (domain[0] + domain[1]) / 2.0
        rs.CurveSeam(crv, parameter)
    offsets = map(lambda x: rs.OffsetCurve(crv, [0, 0, 0], x),
                  [width / 2, -width / 2])
    section = rs.AddLoftSrf(offsets, loft_type=2)

    if offsets: rs.DeleteObjects(offsets)
    if rs.IsPolysurface(section):
        return rs.ExplodePolysurfaces(section, delete_input=True)
    return section
예제 #11
0
def rebuildBrep(obj):
    srfs = rs.ExplodePolysurfaces(obj)
    crvs = map(rebuildSrfCrv, srfs)
    rs.DeleteObjects(srfs)
    newSrfs = map(rs.AddPlanarSrf, crvs)
    # newSrfs = rs.AddPlanarSrf(crvs)
    rs.DeleteObjects(crvs)
    newbrep = rs.JoinSurfaces(newSrfs, delete_input=True)
    try:
        copySourceLayer(newbrep, obj)
        copySourceData(newbrep, obj)
    except:
        pass
    rs.DeleteObject(obj)
예제 #12
0
    def splitSrfwCrvs(srfGuid, crvGuids, delOrigSrf, skipBadCrvs=True):
        """Split a Surface with a Set of Curves
        Parameters:
          srfGuid: the input surface ID
          crvsGuid: the input trimming curves ID
          skipBadCrvs: flag to omit bad curves or fail the script if bad curves encountered
          delOrigSrf: flag to Delete the Original Surface
        Returns:
          True if successful
          False if not successful
        """

        retSrf = []

        srf = rs.coercesurface(srfGuid)
        if srf == None:
            print("SSC001_Not a Valid Surface")
            return False

        crvs = []
        for crv in crvGuids:
            validCrv = rs.coercecurve(crv)
            if validCrv == None:
                print("SSC002_Not a Valid Curve")
                if skipBadCrvs == False:
                    return False
            crvs.append(validCrv)

        #Have a Valid Surface and Valid Curves

        splitSrf = rg.BrepFace.Split(srf, crvs, 0.1)
        polySrf = sc.doc.Objects.AddBrep(splitSrf)
        splitSrfs = rs.ExplodePolysurfaces(polySrf)
        retSrf = splitSrfs

        #Change Isocurve Density to 0 for Individual Split Surfaces
        for srf in splitSrfs:
            theSrf = sc.doc.Objects.Find(srf)
            theSrf.Attributes.WireDensity = 0
            theSrf.CommitChanges()

        if delOrigSrf:
            sc.doc.Objects.Delete(srfGuid, True)

        sc.doc.Objects.Delete(polySrf, True)

        return retSrf
예제 #13
0
    def detectParalellSurface(self):
        #fix layer height

        #self.paralellIntersectedCurve
        #self.indexParalellSurfaces

        explodedSurfaces = rs.ExplodePolysurfaces(self.addtiveObj)

        for surface in explodedSurfaces:
            #normals.append(rs.SurfaceNormal(surface))
            tmpNormal = rs.SurfaceNormal(surface, [0, 0])

            gotAngle = rs.VectorAngle(tmpNormal, self.normalVec)
            if gotAngle == 0 or gotAngle == 180:

                tmpPoints = rs.SurfaceEditPoints(surface)
                tmpPlane = rs.PlaneFromNormal(tmpPoints[0], self.normalVec)

                distance = rs.DistanceToPlane(tmpPlane, self.basePointForPlane)

                distance *= (1.0 / math.cos(math.radians(self.angleOfSurface)))
                print("distance")
                print(distance)

                paralellLayer = int(distance / self.fixedLayerHeight)
                if paralellLayer < 0:
                    paralellLayer *= -1

                if paralellLayer == int(
                        self.distancePrinting /
                        self.fixedLayerHeight) or int(distance) == 0:
                    continue

                self.indexParalellSurfaces.append(int(paralellLayer))
                print("paralellLayer")
                print(paralellLayer)
                print("layer num")
                print(self.distancePrinting / self.fixedLayerHeight)
                #there is object to delete
                self.paralellIntersectedCurves.append(
                    rs.JoinCurves(rs.DuplicateEdgeCurves(surface)))

        rs.DeleteObjects(explodedSurfaces)
        """
예제 #14
0
def AddCoordinateTag(obj):
    dots = []
    if rs.IsCurve(obj):
        pts = rs.CurveEditPoints(obj)
    elif rs.IsSurface(obj):
        pts = rs.SurfaceEditPoints(obj)
    elif rs.IsBrep(obj):
        srfs = rs.ExplodePolysurfaces(obj)
        pts = []
        for srf in srfs:
            pts+=rs.SurfaceEditPoints(srf)
        rs.DeleteObjects(srfs)
    try:
        pts
    except:
        return
    for pt in pts:
        dots.append(rs.AddTextDot('X: '+str(pt.X)+'\nY: '+str(pt.Y)+'\nZ: ' +str( pt.Z), pt))
    return dots
예제 #15
0
def RecursiveBox(polysurface, generation):
    surfaces = rs.ExplodePolysurfaces(polysurface, True)
    for surface in surfaces:

        if generation > 0:
            rs.RebuildSurface(surface, pointcount=(5, 5))
            domainU = rs.SurfaceDomain(surface, 0)
            domainV = rs.SurfaceDomain(surface, 1)
            randomU = random.uniform(domainU[0], domainU[1])
            randomV = random.uniform(domainV[0], domainV[1])
            point = rs.EvaluateSurface(surface, randomU, randomV)
            hulls = drawBoxByCenter(point[0], point[1], point[2],
                                    generation * 3, generation * 3,
                                    generation * 6)
            RecursiveBox(hulls, generation - 1)


#            ExplodeBox(hulls)
        SplitRecursive(surface, 0.5, 0, 3, generation)
    def ConvertPolysurfaceToSurface(self, polysurface):
        """
        converts polysurfaces to surface and returns False and surface
        if the argument is a polysurface. Returns True and the argument
        type if it is not a polysurface. Polysurfaces are made by SplitBrep
        We can't use normal functions on them. So, we have to turn them
        into seperate surfaces with ExplodePolysurfaces. SplitBrep function is
        used in RemoveSurfacesOutsideOfBox().
        An auxilliary method to trim extruding fractures.

        Parameters
        ----------
        ploysurface: GUID
            guid of a Rhino surface
        """
        # Confirm this is a polysurface
        if rs.ObjectType(polysurface) != 16:
            return [False, [polysurface]]  # false, not a ploysurface
        # unjoins the polysurface and get identifiers of he separate surfaces
        surfaces = rs.ExplodePolysurfaces(polysurface)

        # Sometimes, the function ExplodePolysurfaces makes polysurfaces.
        # If it did, call this function again on those surfaces!
        non_poly_surfaces = []
        for surf in surfaces:
            # check if polysurface was created instead of surface
            if rs.ObjectType(surf) == 16:
                # convert the object to surface using its GUID once more,
                # incase polysurface was created
                # NB: RECURSIVE
                additional_split_surfaces = ConvertPolysurfaceToSurface(
                    surf)[1]
                for new_surf in additional_split_surfaces:
                    non_poly_surfaces.append(new_surf)
                    # self.new_fractures.append(new_surf)
            else:
                non_poly_surfaces.append(surf)
                # self.new_fractures.append(surf)

        # Delete the old polysurface
        rs.DeleteObject(polysurface)

        return [True, non_poly_surfaces]
예제 #17
0
def makeSliceSurface(surface, maxAngle):

    explodedSurfaces = rs.ExplodePolysurfaces(surface)

    newSurfaces = []
    rs.DeleteObject(surface)

    baseVec = (0, 0, 1)

    for i in explodedSurfaces:
        vec = rs.SurfaceNormal(i, [0, 0])
        angle = rs.VectorAngle(baseVec, vec)

        if angle > maxAngle:
            rs.DeleteObject(i)
        else:
            newSurfaces.append(i)

    joinedSurface = rs.JoinSurfaces(newSurfaces)

    return joinedSurface
예제 #18
0
    def space(self, density=10):
        """"""
        try:
            du, dv = density
        except TypeError:
            du = density
            dv = density

        density_u = int(du)
        density_v = int(dv)

        uv = []

        rs.EnableRedraw(False)

        if rs.IsPolysurface(self.guid):
            faces = rs.ExplodePolysurfaces(self.guid)
        elif rs.IsSurface(self.guid):
            faces = [self.guid]
        else:
            raise Exception('Object is not a surface.')

        for face in faces:
            domain_u = rs.SurfaceDomain(face, 0)
            domain_v = rs.SurfaceDomain(face, 1)
            du = (domain_u[1] - domain_u[0]) / (density_u - 1)
            dv = (domain_v[1] - domain_v[0]) / (density_v - 1)

            for i in range(density_u):
                for j in range(density_v):
                    uv.append((domain_u[0] + i * du, domain_v[0] + j * dv))

        if len(faces) > 1:
            rs.DeleteObjects(faces)

        rs.EnableRedraw(True)

        return uv
예제 #19
0
def makeWall(crvs, width):
    rs.EnableRedraw(False)
    breps = []
    shapes = []

    for crv in crvs:
        rs.SimplifyCurve(crv)
        shape = offsetBothCrvs(crv, width)
        if rs.IsPolysurface(shape):
            surfs = rs.ExplodePolysurfaces(shape)
            for surf in surfs:
                shapes.append(surf)
            if shape: rs.DeleteObjects(shape)
        else:
            shapes.append(shape)

    for shape in shapes:
        railCurve = addRail(shape)
        breps.append(rs.ExtrudeSurface(shape, railCurve))
        if railCurve: rs.DeleteObjects(railCurve)

    if shapes: rs.DeleteObjects(shapes)
    rs.EnableRedraw(False)
    return breps
예제 #20
0
import rhinoscriptsyntax as rs
import scriptcontext as sc
import Rhino as rh

viste = rs.ViewNames()
for viewport in viste:
    rs.ViewDisplayMode(viewport, "Shaded")
diametro = 1
brep = rs.GetObjects("dammi un solido", 16)
brepexp = rs.ExplodePolysurfaces(brep)
surface = rs.GetObject("dammi la superficie", 8)
surf_edge = rs.DuplicateSurfaceBorder(surface, 1)

new_surface = rs.CopyObject(surface, (0, 0, 0))
uv = []
temp_edge = rs.ExplodeCurves(surf_edge, False)

list_evpt = []
for i in temp_edge:
    evpt = rs.CurveMidPoint(i)
    print evpt
    list_evpt.append(evpt)
for i in list_evpt:
    bord = rs.SurfaceClosestPoint(new_surface, i)
    uv.append(bord)
for i in uv:
    rs.ExtendSurface(new_surface, i, diametro * 10)
edge = rs.OffsetCurveOnSurface(surf_edge, new_surface, -diametro)
print edge
if rs.CurveLength(edge) < rs.CurveLength(surf_edge):
    rs.DeleteObject(edge)
예제 #21
0
    faceString = "f"
    for index in indexes:
        faceString = faceString + " " + str(index)
    return faceString + "\n"


polysurfaces = rs.GetObjects('select polysurfaces', 16)
nU = rs.GetInteger("u", 1)
nV = rs.GetInteger("v", 1)
filename = rs.SaveFileName()
vertices = {}
vI = 1
# file = open("testPythonexport.obj", "w")
file = open(filename, "w")
for polysurface in polysurfaces:
    surfaces = rs.ExplodePolysurfaces(polysurface)
    for surface in surfaces:
        domainU = rs.SurfaceDomain(surface, 0)
        dU = (domainU[1] - domainU[0]) / nU
        domainV = rs.SurfaceDomain(surface, 1)
        dV = (domainV[1] - domainV[0]) / nV
        for i in range(nU):
            for j in range(nV):
                cU1 = i * dU + domainU[0]
                cV1 = j * dV + domainV[0]
                cU2 = (i + 1) * dU + domainU[0]
                cV2 = (j + 1) * dV + domainV[0]
                pt1 = rs.SurfaceEvaluate(surface, [cU1, cV1], 1)[0]
                pt2 = rs.SurfaceEvaluate(surface, [cU2, cV1], 1)[0]
                pt3 = rs.SurfaceEvaluate(surface, [cU2, cV2], 1)[0]
                pt4 = rs.SurfaceEvaluate(surface, [cU1, cV2], 1)[0]
예제 #22
0
def rc_collapse_box():

    go = Rhino.Input.Custom.GetObject()
    go.GeometryFilter = Rhino.DocObjects.ObjectType.Brep

    default_KeepLayer = sc.sticky["KeepLayer"] if sc.sticky.has_key(
        "KeepLayer") else False
    default_IgnoreOpen = sc.sticky["IgnoreOpen"] if sc.sticky.has_key(
        "IgnoreOpen") else False
    opt_KeepLayer = Rhino.Input.Custom.OptionToggle(default_KeepLayer, "No",
                                                    "Yes")
    opt_IgnoreOpen = Rhino.Input.Custom.OptionToggle(default_IgnoreOpen, "No",
                                                     "Yes")

    go.SetCommandPrompt("Select Breps")
    go.AddOptionToggle("KeepLayer", opt_KeepLayer)
    go.AddOptionToggle("IgnoreOpenBreps", opt_IgnoreOpen)

    go.GroupSelect = True
    go.SubObjectSelect = False
    go.AcceptEnterWhenDone(True)
    go.AcceptNothing(True)
    go.EnableClearObjectsOnEntry(False)
    go.EnableUnselectObjectsOnExit(False)
    go.GroupSelect = True
    go.SubObjectSelect = False
    go.DeselectAllBeforePostSelect = False

    res = None
    bHavePreselectedObjects = True

    while True:
        res = go.GetMultiple(1, 0)
        if res == Rhino.Input.GetResult.Option:
            go.EnablePreSelect(False, True)
            continue
        #If not correct
        elif res != Rhino.Input.GetResult.Object:
            rs.Redraw()
            print "No breps were selected!"
            return Rhino.Commands.Result.Cancel
        if go.ObjectsWerePreselected:
            rs.Redraw()
            bHavePreselectedObjects = True
            go.EnablePreSelect(False, True)
            continue
        break

    OPT_IGNORE_OPEN = opt_IgnoreOpen.CurrentValue
    OPT_KEEP_LAYER = opt_KeepLayer.CurrentValue
    sticky["IgnoreOpen"] = OPT_IGNORE_OPEN
    sticky["KeepLayer"] = OPT_KEEP_LAYER

    rs.EnableRedraw(False)

    input_breps = []
    for i in xrange(go.ObjectCount):
        b_obj = go.Object(i).Object()
        input_breps.append(b_obj.Id)

    current_cplane = sc.doc.Views.ActiveView.ActiveViewport.GetConstructionPlane(
    )
    temp_cplane = current_cplane.Plane
    current_cplane.Plane = rs.WorldXYPlane()

    solid_brep_count = 0
    for brep in input_breps:

        if not rs.IsObjectSolid(brep):
            solid_brep_count += 1
            if OPT_IGNORE_OPEN: continue

        if OPT_KEEP_LAYER: brep_layer = rs.ObjectLayer(rs.coerceguid(brep))

        exploded = rs.ExplodePolysurfaces(brep, True)
        remaining_srfs = []
        for srf in exploded:
            norm = rs.SurfaceNormal(srf, [0.5, 0.5])
            if 10 > rs.VectorAngle(norm, [0, 0, 1]) or 10 > rs.VectorAngle(
                    norm, [0, 0, -1]):
                rs.DeleteObject(srf)
            else:
                remaining_srfs.append(srf)
        areas = [rs.SurfaceArea(s) for s in remaining_srfs]
        areas = [x[0] for x in areas]
        srfs, areas = zip(
            *sorted(zip(remaining_srfs, areas), key=lambda x: x[1]))
        pt1, _ = rs.SurfaceAreaCentroid(srfs[-1])
        pt2, _ = rs.SurfaceAreaCentroid(srfs[-2])
        vect = rs.VectorCreate(pt2, pt1)
        vect = rs.VectorDivide(vect, 2)
        rs.MoveObject(srfs[-1], vect)

        if OPT_KEEP_LAYER: rs.ObjectLayer(srfs[-1], brep_layer)
        rs.SelectObjects(srfs[-1])
        rs.DeleteObjects(srfs[:-1])

    rs.EnableRedraw(True)
    rs.Redraw()

    current_cplane.Plane = temp_cplane
    if solid_brep_count > 0:
        outcome = " and were not collapsed." if OPT_IGNORE_OPEN else " and may have been flattened incorrectly. Check input geometry."
        report = str(solid_brep_count) + " brep(s) were not closed" + outcome
        print report
예제 #23
0
print "Yes"

from objects_to_mesh import nurbs_to_mesh_ani

import rhinoscriptsyntax as rs

if __name__ == '__main__':

    poly_srf = rs.GetObjects("Select Objects", 8 + 16)

    if poly_srf:
        srfs_explo = rs.ExplodePolysurfaces(poly_srf)

    if srfs_explo:
        srfs = srfs_explo
    else:
        srfs = poly_srf

    trg_len_min = 1
    trg_len_max = 2.8
    dummy = rs.GetReal("Maximum distance to surface", 0.05)
    rhino_meshes = []
    for i, srf in enumerate(srfs):
        print("Computing Surface {0} of {1}".format(i + 1, len(srfs) + 1))
        rs.EnableRedraw(False)
        rs.HideObject(srf)
        rhino_meshes.append(
            nurbs_to_mesh_ani(srf, trg_len_min, trg_len_max, vis=1))
        if srfs_explo:
            rs.DeleteObject(srf)
예제 #24
0
                 [minX + x * stepX, minY + (y + 1) * stepY, minZ + z * stepZ],
                 [minX + x * stepX, minY + y * stepY,
                  minZ + (z + 1) * stepZ], [
                      minX + (x + 1) * stepX, minY + y * stepY,
                      minZ + (z + 1) * stepZ
                  ], [
                      minX + (x + 1) * stepX, minY + (y + 1) * stepY,
                      minZ + (z + 1) * stepZ
                  ], [
                      minX + x * stepX, minY + (y + 1) * stepY,
                      minZ + (z + 1) * stepZ
                  ]))

            # Group boxes
            #            boxes = rs.AddObjectsToGroup(box, "Boxes")
            boxFaces = rs.ExplodePolysurfaces(box)

            # Calculate density
            density = 0
            for curveId in objectIds:
                for faceId in boxFaces:
                    intersection_list = rs.CurveSurfaceIntersection(
                        curveId, faceId)
                    if intersection_list:
                        density += len(intersection_list)
            # Map density to radius
            topBound = min(stepX, stepY, stepZ) / 4
            dRad = topBound * (density / numCurves)

            # Density at a point
            print x, " ", y, " ", z, " >> ", density
예제 #25
0
import rhinoscriptsyntax as rs
# !-RunPythonScript "objectBottomFaceArea.py"

# rs.EnableRedraw(False)
faces = []
bndry = []
obj = rs.GetObject("Select polysurface to explode",
                   rs.filter.polysurface,
                   preselect=True)
if rs.IsPolysurface(obj):
    faces = rs.ExplodePolysurfaces(obj)

for face in faces:
    if rs.IsSurface(face):
        domainU = rs.SurfaceDomain(face, 0)
        domainV = rs.SurfaceDomain(face, 1)
        u = domainU[1] / 2.0
        v = domainV[1] / 2.0
        point = rs.EvaluateSurface(face, u, v)
        param = rs.SurfaceClosestPoint(face, point)
        normal = rs.SurfaceNormal(face, param)
        # print normal
        if normal.Z == -1:
            bndry.append(face)

for bnd in bndry:
    area = rs.SurfaceArea(bnd)[0]
    areapy = area / 3.3058
    print area, areapy
    txt = rs.ClipboardText(area)
예제 #26
0
def ExplodeBox(hulls, index):
    if rs.IsBrep(hulls):
        faces = rs.ExplodePolysurfaces(hulls, True)
        for face in faces:
            SplitRecursive(face, 0.5, 0, 3, index)
예제 #27
0
def alingBlock(block_a, block_b, model_inside):
    """
    Scale box to the correct dimentions
    Align box a and what is inside to box b
    The dimention of the box is expected to be equal lenght
    :param block_a:
    :param block_b: block to align block_a to
    :param model_inside: models inside block_a
    """

    # Find center of box_a
    exp_a = rs.ExplodePolysurfaces(block_a)
    cen_a = Vector3d(0, 0, 0)
    for exp in exp_a:
        cen_a += rs.SurfaceAreaCentroid(exp)[0]
    cen_a /= 6.0

    # Find center of box_b
    exp_b = rs.ExplodePolysurfaces(block_b)
    cen_b = Vector3d(0, 0, 0)
    for exp in exp_b:
        cen_b += rs.SurfaceAreaCentroid(exp)[0]
    cen_b /= 6.0

    # Find side Lenght
    c = rs.DuplicateEdgeCurves(exp_a[0])
    L = float(rs.CurveLength(c[0]))

    def sqrt_length(a, b, c):
        return math.sqrt(a * a + b * b + c * c)

    def create_matrix(a, b, c, d):
        M = [[a[0], a[1], a[2], d[0]], [b[0], b[1], b[2], d[1]],
             [c[0], c[1], c[2], d[2]], [0, 0, 0, 1]]
        return M

    # find basic function of box_a
    basic_0 = cen_a - rs.SurfaceAreaCentroid(exp_a[0])[0]
    basic_0 /= sqrt_length(basic_0[0], basic_0[1], basic_0[2])

    basic_1 = rs.SurfaceAreaCentroid(exp_a[1])[0] - cen_a
    basic_1 /= sqrt_length(basic_1[0], basic_1[1], basic_1[2])

    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)
예제 #28
0
 def rev(Ge, Lis, Src, div):
     udiv = div
     vdiv = div
     Pt_L = Lis[0][0]
     srf = []
     FirstRay = []
     SecondRay = []
     First_RefPoint = []
     drawray = []
     Reverb = []
     for i in Ge:
         srf.append(i[0])
     sph = (rs.AddSphere(Src[1], Src[2]))
     Src_pt = (Src[1])
     u = rs.SurfaceDomain(sph, 0)
     v = rs.SurfaceDomain(sph, 1)
     pts = []
     for i in range(0, udiv + 1, 1):
         for j in range(0, vdiv + 1, 1):
             pt = (i / udiv, j / vdiv, 0)
             sphP = rs.SurfaceParameter(sph, pt)
             newpt = rs.EvaluateSurface(sph, sphP[0], sphP[1])
             pts.append(rs.AddPoint(newpt))
     Dir = []
     for p in pts:
         Dir.append(rs.VectorCreate(p, Src_pt))
     Reflexion = []
     for d in Dir:
         Reflexion.append(rs.ShootRay(srf, Src_pt, d, reflections=4))
     Project = []
     for v in Reflexion:
         Cl_Pt = []
         Ray_v = []
         try:
             Project.append(v[1])
             Ray_v.append(rs.AddPolyline(v))
         except:
             pass
         for u in Ray_v:
             pt_on = rs.CurveClosestPoint(u, Pt_L)
             cl = rs.EvaluateCurve(u, pt_on)
             Dicl = (rs.Distance(Pt_L, cl))
             if Dicl <= ((Lis[0])[3]):
                 try:
                     First_RefPoint = rs.CurveClosestPoint(u, v[1])
                     Second_RefPoint = rs.CurveClosestPoint(u, v[2])
                     endc = ((rs.CurveClosestPoint(
                         u, (rs.CurveEndPoint(u)))))
                     if pt_on > Second_RefPoint:
                         SecondRay.append(pt_on / endc *
                                          (rs.CurveLength(u)))
                         drawray.append(u)
                     elif pt_on > First_RefPoint:
                         FirstRay.append(pt_on / endc *
                                         (rs.CurveLength(u)))
                 except:
                     pass
     box = rs.AddBox(rs.BoundingBox(Project))
     boxarea = round((rs.SurfaceArea(box)[0]), 2)
     Cube = []
     Cube.append(box)
     surfacetorev = []
     for s in srf:
         ptons = []
         for p in Project:
             if rs.Distance((rs.BrepClosestPoint(s, p)[0]), p) < 0.1:
                 ptons.append(p)
         if len(ptons) > 0:
             surfacetorev.append(s)
     surfaceab = []
     for x in Ge:
         if x[0] in surfacetorev:
             surfaceab.append(x[2])
     SrfandAb = [(surfacetorev[i], surfaceab[i])
                 for i in range(0, len(surfacetorev))]
     bbox = box
     box = round(((rs.SurfaceVolume(box))[0]), 1)
     srfvol = []
     srfvolex = []
     absvol = []
     srfarea = []
     srfrev = []
     areaabs = []
     surfacecenter = []
     absidx = []
     absvoltot = []
     for i in SrfandAb:
         if rs.SurfaceVolume(i[0]) > 0:
             srfvol.append(i[0])
             absvol.append(i[1])
         else:
             srfarea.append((rs.SurfaceArea(i[0]))[0])
             absvoltot.append(i[1])
     srfvolex = rs.ExplodePolysurfaces(srfvol)
     for i in srfvolex:
         ptonsrf = []
         usefulsrf = []
         for p in Project:
             if rs.Distance((rs.BrepClosestPoint(i, p)[0]), p) < 0.01:
                 ptonsrf.append(p)
                 usefulsrf.append(i)
         if len(ptonsrf) > 0:
             srfarea.append(rs.SurfaceArea(i)[0])
             srfrev.append(i)
     for i in srfrev:
         surfacecenter.append(rs.SurfaceAreaCentroid(i)[0])
     for b in srfvol:
         for i in surfacecenter:
             if rs.Distance((rs.BrepClosestPoint(b, i)[0]), i) < 0.01:
                 absidx.append(srfvol.index(b))
     for i in absidx:
         absvoltot.append(absvol[i])
     try:
         areaabs = [
             srfarea[i] * (absvoltot[i])
             for i in range(0, len(absvoltot))
         ]
     except:
         raise Exception(
             'One source must be too deep inside a geometry, try to get it out or to move it a little bit !'
         )
     Builtareaabs = 0
     for i in areaabs:
         Builtareaabs += i
     BuiltArea = 0
     for i in srfarea:
         BuiltArea += i
     BuiltArea = round(BuiltArea, 2)
     EmptyArea = 2 * (round(boxarea - BuiltArea, 2))
     if EmptyArea < 0:
         EmptyArea = 0
     TR = 1000 * (0.16 * box) / (Builtareaabs + (EmptyArea * 1))
     FRValue = 0
     for f in FirstRay:
         FV = ((((Lis[0])[3]) * 15) / f)
         FRValue += FV
     if FRValue >= 125:
         FRValue = 125
     SRValue = 0
     for s in SecondRay:
         SV = ((((Lis[0])[3]) * 20) / s)
         SRValue += SV
     if SRValue > 125:
         SRValue = 125
     Reverb.append(round(FRValue))
     Reverb.append(round(SRValue))
     Reverb.append(round(TR, 2))
     return Reverb
예제 #29
0
         for row in range(N_blocks)]  # line id, each contour has 4 lines
face_center = [[[0 for col in range(3)] for col in range(Nfaces)]
               for row in range(N_blocks)
               ]  # x-, y-, z-coordinates of face center
Dimensions = [[[-1 for col in range(3)] for col in range(Nfaces)]
              for row in range(N_blocks)
              ]  # face size in x-, y- and z-direction
Block_center = [0 for row in range(N_blocks)
                ]  # x-, y-, z-coordinates of block center
Volume = [-1 for row in range(N_blocks)]  # block volume
maxLength = 0  # max block length (used for defining tolerance)

# Extract block face dimensions, block face center, max block length
for ii in range(N_blocks):
    faces[ii] = rs.ExplodePolysurfaces(
        ALL_BLOCKS[ii]
    )  # explode blocks into surfaces represeting the block faces
    for jj in range(Nfaces):
        lines[ii][jj] = rs.DuplicateEdgeCurves(
            faces[ii][jj]
        )  # sketch lines along face edges (!) dev. hint: this is time consuming and can be improved
        curves[ii][jj] = rs.JoinCurves(
            lines[ii]
            [jj])  # join the lines to create polyline along face adges
        for kk in range(3):
            face_center[ii][jj][kk] = round(
                rs.CurveAreaCentroid(curves[ii][jj])[0][kk],
                RoundUnit)  # read coordinates of face center
        if jj == 1 or jj == 3:  # faces belonging to yz-plane
            Dimensions[ii][jj][0] = face_center[ii][jj][
                0]  # x-coordinate of face center
예제 #30
0
    def setSurfaceForSlicing(self):

        explodedSurfaces = rs.ExplodePolysurfaces(self.addtiveObj)
        editPoint = []

        #get editPoint from polysurfaces
        if len(explodedSurfaces) == 0:
            #use obj
            meshed = rhino.Geometry.Mesh.CreateFromBrep(
                rs.coercebrep(self.addtiveObj))
            editPoint = rs.MeshVertices(meshed[0])

        else:
            for i in explodedSurfaces:
                meshed = rhino.Geometry.Mesh.CreateFromBrep(rs.coercebrep(i))
                vertices = rs.MeshVertices(meshed[0])
                editPoint.extend(vertices)

        rs.DeleteObjects(explodedSurfaces)

        minValue = []
        maxValue = []
        basePointForPlane = None
        basePointForDistance = None

        for i in range(len(editPoint)):
            if i == 0:
                basePointForPlane = editPoint[0]
                basePointForDistance = editPoint[0]

                for j in range(3):
                    minValue.append(editPoint[0][j])
                    maxValue.append(editPoint[0][j])
                continue

            else:
                if basePointForPlane[2] > editPoint[i][2]:
                    basePointForPlane = editPoint[i]
                if basePointForDistance[2] < editPoint[i][2]:
                    basePointForDistance = editPoint[i]

                for j in range(3):
                    if minValue[j] > editPoint[i][j]:
                        minValue[j] = editPoint[i][j]
                    elif maxValue[j] < editPoint[i][j]:
                        maxValue[j] = editPoint[i][j]

        #why?
        self.basePointForPlane = basePointForPlane

        plane = rs.PlaneFromNormal(basePointForPlane, self.normalVec)

        #calculating distance printing
        self.calcDistance(plane, editPoint)

        #make base surface
        pntForSur = []
        line = (minValue[0], minValue[1],
                minValue[2]), (minValue[0], minValue[1], maxValue[2])
        pntForSur.append(rs.LinePlaneIntersection(line, plane))
        line = (minValue[0], maxValue[1],
                minValue[2]), (minValue[0], maxValue[1], maxValue[2])
        pntForSur.append(rs.LinePlaneIntersection(line, plane))
        line = (maxValue[0], maxValue[1],
                minValue[2]), (maxValue[0], maxValue[1], maxValue[2])
        pntForSur.append(rs.LinePlaneIntersection(line, plane))
        line = (maxValue[0], minValue[1],
                minValue[2]), (maxValue[0], minValue[1], maxValue[2])
        pntForSur.append(rs.LinePlaneIntersection(line, plane))

        lineForSur = []

        for i in range(4):
            lineForSur.append(rs.AddLine(pntForSur[i], pntForSur[(i + 1) % 4]))

        joinedCurve = rs.JoinCurves(lineForSur)
        rs.DeleteObjects(lineForSur)

        curveForSur = rs.OffsetCurve(joinedCurve, rs.CurveNormal(joinedCurve),
                                     30)

        self.sliceSurface = rs.AddPlanarSrf(curveForSur)

        if len(curveForSur) > 1 or rs.IsPointOnSurface(
                self.sliceSurface, rs.CurveStartPoint(joinedCurve)) is False:

            rs.DeleteObjects(curveForSur)
            if self.sliceSurface is not None:
                rs.DeleteObject(self.sliceSurface)

            curveForSur = rs.OffsetCurve(joinedCurve,
                                         rs.CurveNormal(joinedCurve), -30)
            self.sliceSurface = rs.AddPlanarSrf(curveForSur)
        rs.DeleteObjects(joinedCurve)
        rs.DeleteObjects(curveForSur)

        self.fixedLayerHeight = float(
            self.gcoder.getLayerHeight() *
            (1.0 / math.cos(math.radians(self.angleOfSurface))))

        self.addtiveObj = rs.CopyObject(self.addtiveObj,
                                        (0, 0, self.fixedLayerHeight * 0.9))
        self.sliceSurface = rs.MoveObject(self.sliceSurface,
                                          (0, 0, self.fixedLayerHeight * 0.9))