コード例 #1
0
def TestIntersection(obj, tester):
    # there are a few possible intersection methods in rhinoscriptsyntax
    # as an initial setup only a few intersections are handled
    # to make this script faster and more robuste best would be to intersect not with rhinoscriptsyntax
    # But use RhinoCommon methods instead.
    #
    #for now only rhinoscriptsyntax methods are used as an example below:

    # if both are breps ( (poly)surface or extrusion
    if rs.IsBrep(obj) and rs.IsBrep(tester):
        intersections = rs.IntersectBreps(obj, tester)
        if intersections:
            #Delete intersections if they were made
            rs.DeleteObjects(intersections)
            return True

    if rs.IsMesh(obj) and rs.IsMesh(tester):
        intersections = rs.MeshMeshIntersection(obj, tester)
        if intersections:
            #This method does not create a curve but returns a list of points
            #so nothing to delete
            return True

    #Mixed input needs to be handled different as is with curves.
    #if either is a mesh the other needs to be converted to a mesh as well

    #catchall return False
    return False
コード例 #2
0
 def slice_plane(self, target, plane):
     
     ### Slice
     p = rs.coerceplane(plane)
     
     ### Geomrtry Type
     if rs.IsMesh(target):
         # print("Mesh!!")
         m = rs.coercemesh(target)
         # print(m)
         polylines = rg.Intersect.Intersection.MeshPlane(m, p)
     
     elif rs.IsBrep(target):
         # print("Brep!")
         b = rs.coercebrep(target)
         mp = rg.MeshingParameters.QualityRenderMesh
         m = rg.Mesh.CreateFromBrep(b, mp)
         # print(m[0])
         polylines = rg.Intersect.Intersection.MeshPlane(m[0], p)
     
     else:
         # print("N/A")
         polylines = None
     
     return polylines
コード例 #3
0
def cutAtPlan(level):
    planPlane = rs.AddPlaneSurface([-1000,-1000,level], 3000, 3000)
    baseLayer = rs.AddLayer("60_PLANS")
    newParent = rs.AddLayer("PLAN_"+str(level), parent = baseLayer)
    origLayer = rs.CurrentLayer()
    shortName = rs.LayerName(origLayer, fullpath = False)
    
    #newChildsParent = rs.AddLayer( , parent = newParent)
    newChild = rs.AddLayer(shortName, parent = newParent, color = rs.LayerColor(origLayer))
    rs.CurrentLayer(newChild)
    
    objs = rs.ObjectsByLayer(origLayer)
    #if len(objs)<1:
    #    skip = True
    intersectCrvs = []
    tempCrv = None
    for obj in objs:
        if rs.IsBrep(obj):
            
            tempCrv = rs.IntersectBreps(obj, planPlane)
        if tempCrv != None:
            intersectCrvs.append(tempCrv)
    
    for crv in intersectCrvs:
        if not None:
            rs.ObjectLayer(crv, newChild)
    
    rs.DeleteObject(planPlane)
    rs.CurrentLayer(origLayer)
コード例 #4
0
def splitModel(objs, cutLevel):
    point = Rhino.Geometry.Point3d(0,0,cutLevel)
    
    belowDir = rs.AddLine(point, [0,0,-9999])
    aboveDir = rs.AddLine(point, [0,0,9999])
    circle = rs.AddCircle(point, 9999)
    circleSrf = rs.AddPlanarSrf(circle)
    
    aboveGroup = rs.AddGroup("Above")
    belowGroup = rs.AddGroup("Below")
    
    
    for obj in objs:
        ptBtm = rs.BoundingBox(obj)[0]
        ptTop = rs.BoundingBox(obj)[6]
        if ptBtm[2]>cutLevel:
            intersecting = False
            rs.AddObjectToGroup(obj, "Above")
            #print "Object Above"
        elif ptTop[2]<cutLevel:
            intersecting = False
            rs.AddObjectToGroup(obj, "Below")
            #print "Object Below"
        else:
            intersecting = True
        
        if intersecting:
            if rs.IsBrep(obj):
                closed = False
                if rs.IsPolysurfaceClosed(obj):
                    closed = True
                try:
                    copy = rs.CopyObject(obj)
                    splitSrfs = rs.SplitBrep(obj, circleSrf, True)
                    for splitSrf in splitSrfs:
                        #print "looping"
                        if closed:
                            rs.CapPlanarHoles(splitSrf)
                        rs.MatchObjectAttributes(splitSrf, copy)
                        ptBtm = rs.BoundingBox(splitSrf)[0]
                        ptTop = rs.BoundingBox(splitSrf)[6]
                        mdPtZ = (ptBtm[2] + ptTop[2]) / 2
                        if mdPtZ>cutLevel:
                            rs.AddObjectToGroup(splitSrf, "Above")
                        else:
                            rs.AddObjectToGroup(splitSrf, "Below")
                    rs.DeleteObject(copy)
                    rs.DeleteObject(obj)
                except:
                    None
            if rs.IsBlockInstance(obj):
                contents = rs.ExplodeBlockInstance(obj)
                for content in contents:
                    objs.append(content)
    rs.DeleteObject(belowDir)
    rs.DeleteObject(aboveDir)
    rs.DeleteObject(circle)
    rs.DeleteObject(circleSrf)
コード例 #5
0
def importComponent(path):
    imported=rs.Command("-Insert "+path+' Objects Enter 0,0,0 1 0')
    if imported:
        components=rs.LastCreatedObjects()
        polys=[]
        breps=[]
        for comp in components:
            if rs.IsCurve(comp):polys.append(comp)
            if rs.IsBrep(comp):breps.append(comp)
        print ('polys \n',polys)
        print ('breps \n',breps)
        return [breps,polys]
コード例 #6
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
コード例 #7
0
def importComponent(path):
    if path is None: return None
    imported = rs.Command("-Insert " + path + ' Objects Enter 0,0,0 1 0')
    outComponent = AttrDict()

    if imported:
        components = rs.LastCreatedObjects()
        outComponent.polys = []
        outComponent.breps = []
        for comp in components:
            if rs.IsCurve(comp): outComponent.polys.append(comp)
            if rs.IsBrep(comp): outComponent.breps.append(comp)
        return outComponent
コード例 #8
0
def IntersectGeo(obj, level):
    tolerance = rs.UnitAbsoluteTolerance()
    plane = rc.Geometry.Plane(rs.coerce3dpoint((0, 0, level)),
                              rs.coerce3dvector((0, 0, 1)))
    finalCurves = []
    #BLOCKS
    if rs.IsBlockInstance(obj):
        matrix = rs.BlockInstanceXform(obj)
        blockObjs = rs.BlockObjects(rs.BlockInstanceName(obj))
        for eachBlockObj in blockObjs:
            newCopy = rs.CopyObject(eachBlockObj)
            xformedObj = rs.TransformObject(newCopy, matrix)

            #EXTRUSIONS
            if isinstance(xformedObj, rc.Geometry.Extrusion):
                temp = sc.doc.Objects.AddBrep(xformedObj.ToBrep(False))
                xformedObj = rs.coercebrep(temp)
                rs.DeleteObject(temp)

            #BREPS IN BLOCK
            result = IntersectBrepPlane(xformedObj, plane)
            if result is None: continue
            for each in result:
                if each is not None:
                    finalCurves.append(each)
            rs.DeleteObject(xformedObj)

            #MESHES IN BLOCK <---This code might not be necessary
            result = IntersectMeshPlane(xformedObj, plane)
            if result is None: continue
            for each in result:
                if each is not None:
                    finalCurves.append(each)
            rs.DeleteObject(xformedObj)

    #BREPS
    elif rs.IsBrep(obj):
        result = IntersectBrepPlane(obj, plane)
        if result is None: return None
        for each in result:
            if each is not None:
                finalCurves.append(each)

    #MESHES
    elif rs.IsMesh(obj):
        result = IntersectMeshPlane(obj, plane)
        if result is None: return None
        for each in result:
            if each is not None:
                finalCurves.append(each)
    return finalCurves
コード例 #9
0
ファイル: rsTools.py プロジェクト: vctcn93/rhinoscript
    def split(srfs,cutter,stop=False):
        ##print('iter:{},num srfs:{}'.format(iteration,len(srfs)))
        outbin=[]
        for s in srfs:
            if not rs.IsBrep(s):
                continue
            result=rs.SplitBrep(s,cutter,True)
            #print('$result is ',result)

            if result is None:
                # pass
                outbin.append(s)
            else:
                outbin+=split(result,cutter)
        return outbin
コード例 #10
0
def cutAtPlan(level, join):
    cutPlane = rs.AddPlaneSurface([-1000,-1000,level], 3000, 3000)
    plane = rs.PlaneFromNormal([-1000,-1000,0], [0,0,1])
    planPlane = rs.AddPlaneSurface(plane, 3000, 3000)
    
    objs = rs.VisibleObjects()
    intersectCrvs = []
    tempCrv = None
    for obj in objs:
        if rs.IsBrep(obj):
            tempCrv = rs.IntersectBreps(obj, cutPlane)
        if tempCrv:
            rs.MatchObjectAttributes(tempCrv, obj)
            newCrvs = flatten(tempCrv)
    rs.DeleteObject(cutPlane)
    rs.DeleteObject(planPlane)
コード例 #11
0
def contourPt(obj, pt):
    """
    creates a contour according to xy plane at specified height
    obj: single object to contour
    pt: a point to contour at
    """
    planPlane = rs.AddPlaneSurface([-10000, -10000, pt[2]], 30000, 30000)
    intersectCrvs = []
    tempCrv = None

    if rs.IsBrep(obj):
        tempCrv = rs.IntersectBreps(obj, planPlane)
    if tempCrv != None:
        objName = rs.ObjectName(obj)
        rs.ObjectName(tempCrv, objName)
        intersectCrvs.append(tempCrv)
        rs.MatchObjectAttributes(tempCrv, obj)
    rs.DeleteObject(planPlane)
    return intersectCrvs
コード例 #12
0
 def on_click_add_hb_object(self, sender, e):
     
     objects = sc.doc.Objects.GetSelectedObjects(False, False)
     
     for obj in objects:
         if not rs.IsBrep(obj.Id) and not rs.IsMesh(obj.Id):
             return
         #check object on list
         if obj.Id in self.m_hb_object_ids:
             return 
         #create grid item row
         itemText = obj.ShortDescription(False)
         if obj.Name:
             itemText += " - " + obj.Name
         self.m_hb_object_ids += [obj.Id]
         datarow = [itemText, self.m_hb_type_items, self.m_hb_material_items]
         #update grid values
         self.m_hb_objects_gridview.DataStore += \
             [RowValues(datarow, self.m_hb_column_cell_type)]
コード例 #13
0
ファイル: drawing.py プロジェクト: tmwarchitecture/PCPA_TOOLS
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
コード例 #14
0
def SplitGeometry(objs, plane, dir=1):
    global diffRadius
    circle = Rhino.Geometry.Circle(plane, diffRadius)
    negShape = Rhino.Geometry.Cylinder(circle, diffRadius * dir)
    negShapeBrep = negShape.ToBrep(True, True)
    negShapeGeo = sc.doc.Objects.AddBrep(negShapeBrep)

    visibleGeometry = []

    for obj in objs:
        if rs.IsBrep(obj):
            if rs.IsPolysurfaceClosed(obj):
                resultObjs = rs.BooleanDifference(obj, negShapeGeo, False)
                if resultObjs is None:
                    visibleGeometry.append(obj)
                elif len(resultObjs) < 1:
                    visibleGeometry.append(obj)
                else:
                    for each in resultObjs:
                        visibleGeometry.append(each)
            else:
                resultObjs = rs.SplitBrep(obj, negShapeGeo)
                if resultObjs is None:
                    visibleGeometry.append(obj)
                elif len(resultObjs) < 1:
                    visibleGeometry.append(obj)
                else:
                    for each in resultObjs:
                        if IsAbovePlane(each, plane.OriginZ):
                            if dir == -1:
                                visibleGeometry.append(each)
                            else:
                                rs.DeleteObject(each)
                        else:
                            if dir == 1:
                                visibleGeometry.append(each)
                            else:
                                rs.DeleteObject(each)

    rs.DeleteObject(negShapeGeo)
    return visibleGeometry
コード例 #15
0
    def lb_generate_test_points(self):
        
        
        try:
            #load breps/meshes from analysis grid object list
            brep_list = []
            mesh_list = []            
            for item in  self.m_gridsurfs_list_box.Items:
                    if rs.IsBrep(item.Tag):
                        brep_list += [Rhino.DocObjects.ObjRef(item.Tag).Brep()]
                    elif rs.IsMesh(item.Tag):
                        mesh_list += [Rhino.DocObjects.ObjRef(item.Tag).Mesh()]
                    else:
                        continue
                      
            #prepare grid paramers
            grid_size = self.m_numeric_gridsize_updown.Value   
            dist_base_surf = self.m_numeric_distsurf_updown.Value
            move_test_mesh = False
            
            #create meshes from breps, add to mesh list
            
            input_mesh = mesh_list + LadybugEto.createMesh(brep_list, grid_size)
            self.m_output_mesh = []
            self.m_test_points = []
            self.m_pts_vectors = []
            for index, mesh in enumerate(input_mesh):
                test_points, pts_vectors, faces_area, output_mesh = \
                                        LadybugEto.getTestPts(
                                                                [mesh], 
                                                                dist_base_surf, 
                                                                move_test_mesh)
                self.m_test_points += [test_points]
                self.m_pts_vectors += [pts_vectors]
                self.m_output_mesh += output_mesh
                
            #update meshes in scene
            LadybugEto.bakeGeo(self.m_output_mesh, 'lb_sunlighthours')

        except Exception as e:
            print e   
コード例 #16
0
 def on_click_add_grid_object(self, sender, e):
     
     objects = sc.doc.Objects.GetSelectedObjects(False, False)
     item_list = [item.Tag for item in self.m_gridsurfs_list_box.Items]
     
     for obj in objects:
         #invalid selection type?
         if not rs.IsBrep(obj.Id) and not rs.IsMesh(obj.Id):
             return            
         #already in list?
         if obj.Id in item_list:
             return   
         #create list item
         item = forms.ListItem()
         item.Text = obj.ShortDescription(False)
         if obj.Name:
             item.Text += " - " + obj.Name
         item.Tag = obj.Id
         self.m_gridsurfs_list_box.Items.Add(item)
         
     self.lb_generate_test_points()
コード例 #17
0
def main(north, boundary, timeperiod, monthRange, location):
    if sc.sticky.has_key('ladybug_release'):
        try:
            if not sc.sticky['ladybug_release'].isCompatible(ghenv.Component):
                return -1
            if sc.sticky['ladybug_release'].isInputMissing(ghenv.Component):
                return -1
        except:
            warning = "You need a newer version of Ladybug to use this component." + \
            "Use updateLadybug component to update userObjects.\n" + \
            "If you have already updated userObjects drag Ladybug_Ladybug component " + \
            "into canvas and try again."
            w = gh.GH_RuntimeMessageLevel.Warning
            ghenv.Component.AddRuntimeMessage(w, warning)
            return -1
        lb_sp = sc.sticky["ladybug_SunPath"]()
        lb_prep = sc.sticky["ladybug_Preparation"]()

        # setting solar noon variables
        latitude, longitude, timeZone, elevation = readLocation(_location)
        year = datetime.datetime.now().year
        day = 21
        """
        MONTH_DICT = {0:range(3,7), 1:range(3,10), 2:range(3,13),\
              3:range(6,10), 4:range(6,13),\
              5:range(9,13)}
        """

        mth_lst = MONTH_DICT[monthRange]

        t = timeperiod / 2.0
        centerPt = rs.CurveAreaCentroid(boundary)[0]
        # do geometry operations
        boundary = clean_curve(boundary)
        brep_lst = []
        for mth in mth_lst:
            solar_noon = get_solar_noon(mth, year, timeZone, day, latitude,
                                        longitude)
            hourlst = [solar_noon - t, solar_noon + t]
            #print mth
            #print 'month: ',mth,'th;', 'hours: ', hourlst
            sun_pts = get_sunpt(lb_sp,
                                lb_prep,
                                latitude,
                                centerPt,
                                mth,
                                day,
                                hourlst,
                                north_=north,
                                lon=longitude,
                                tZ=timeZone,
                                scale_=100)
            brep = rs.coercebrep(make_zone(sun_pts, boundary))
            brep_lst.append(brep)

        SE = None
        TOL = sc.doc.ModelAbsoluteTolerance
        for i in range(len(brep_lst) - 1):
            brep = brep_lst[i]
            brep_ = brep_lst[i + 1]
            if not SE and rs.IsBrep(brep):
                SE_ = brep
            else:
                SE_ = SE
            if rs.IsBrep(brep_):
                SE = rc.Brep.CreateBooleanIntersection(SE_, brep_, TOL)[0]
            else:
                SE = SE_
        return SE

    else:
        print "You should first let the Ladybug fly..."
        ghenv.Component.AddRuntimeMessage(
            ERROR_W, "You should first let the Ladybug fly...")
コード例 #18
0
ファイル: finger.py プロジェクト: alexbjorkc/rhinotools
def make_fingers(positive, negative, subdivisions):
  """
  intersect two collections of planes
  subdivide the intersections
  assign each subdivision to a guid from which it will be subtracted
  """

  # this vector is used to indicate axis of the intersection.
  # it needs to be parallel to the intersection
  # (there are other ways of doing this!)
  p0 = rs.GetPoint("select start of intersection")
  p1 = rs.GetPoint("select end of intersection")

  edge = rs.AddLine(p0, p1)
  vector = rs.VectorCreate(p0, p1)

  rs.EnableRedraw(False)

  # this dict maps a pair of planes (ps, ns) to their booleanintersection
  intersections = {}

  for ps in positive:
    for ns in negative:
      intersection = rs.BooleanIntersection(ps, ns, False)
      if intersection is not None:
        intersections[(ps, ns)] = intersection

  # here we construct some very large cylinders aligned with the axis you drew
  origins = []
  cylinders = []
  for i in range(subdivisions+1):
    origin = rs.EvaluateCurve(edge, rs.CurveParameter(edge, i * 1.0/(subdivisions)))
    origins.append(origin)

  rs.DeleteObject(edge)

  for i in range(subdivisions):
    plane = rs.PlaneFromNormal(origins[i], vector)
    circle = rs.AddCircle(plane, 100)
    planar_circle = rs.AddPlanarSrf(circle)

    extrusion_curve = rs.AddLine(origins[i], origins[i+1])
    cylinders.append(rs.ExtrudeSurface(planar_circle, extrusion_curve))

    rs.DeleteObject(circle)
    rs.DeleteObject(planar_circle)
    rs.DeleteObject(extrusion_curve)


  # we perform a boolean intersection between each intersection and
  # the cylinders to construct the fingers
  for key, intersection in intersections.items():
    ps, ns = key

    for i, cylinder in enumerate(cylinders):
      print "intersection", intersection
      print "cylinder", cylinder
      objs = [brep for brep in rs.BooleanIntersection(intersection, cylinder, False) if rs.IsBrep(brep)]
      # assign the resulting fingers to either the positive or negative
      if i % 2 == 0:
        guid_to_difference[ps].extend(objs)
      else:
        guid_to_difference[ns].extend(objs)

  DeleteItemOrList(cylinders)
  DeleteItemOrList(intersections.values())

  rs.EnableRedraw(True)
コード例 #19
0
    def generateAnalysis(test_points, pts_vectors, name, window_groups,
                         sun_vectors, hoys, timestep, hb_object_ids,
                         hb_object_types, hb_object_mats, folder, filename,
                         save_file_only, grid_mesh):

        try:
            analysis_grids = AnalysisGrid.from_points_and_vectors(
                test_points, pts_vectors, name, window_groups)

            #get analysis recipe
            analysis_recipe = None
            if sun_vectors and sun_vectors[0] != None and \
                hoys and hoys[0] != None and analysis_grids:
                # set a sunlight hours analysis recipe together if there are points
                analysis_recipe = SolarAccessGridBased(sun_vectors, hoys,
                                                       [analysis_grids],
                                                       timestep)
            else:
                print "missing sun vector data"
                return

            #HB surfaces

            #convert scene hb objects into rhino common
            geo_list = []
            for id in hb_object_ids:
                if rs.IsBrep(id):
                    geo_list += [rc.DocObjects.ObjRef(id).Brep()]
                elif rs.IsMesh(id):
                    geo_list += [rc.DocObjects.ObjRef(id).Mesh()]
                else:
                    continue

            #preapre paramters
            if len(geo_list) != 0 and geo_list[0] != None:
                names = None  #not included yet in eto interface (could use scene object name)
                hb_objects = []
                for index, geo in enumerate(geo_list):
                    type = hb_object_types[index]
                    radMat = hb_object_mats[index]

                    isNameSetByUser = False
                    if names:
                        isNameSetByUser = True

                    isTypeSetByUser = True
                    if not type:
                        isTypeSetByUser = False

                    rad_prop = RadianceProperties(
                        radMat) if radMat else RadianceProperties()
                    ep_prop = None

                    if radMat and radMat.__class__.__name__ == 'Plastic':
                        hb_objects += HBSurface.from_geometry(
                            names, geo, type, isNameSetByUser, isTypeSetByUser,
                            rad_prop, ep_prop)
                    elif radMat and radMat.__class__.__name__ == 'Glass':
                        hb_objects += HBFenSurface.from_geometry(
                            names, geo, isNameSetByUser, rad_prop, ep_prop)

            else:
                print "No valid HB surfaces selected"
                return

            # Run analysis
            rad_scene = None
            if not hb_objects or not analysis_recipe:
                print "Missing HB objects or analysis recipe"
                return

            try:
                for obj in hb_objects:
                    assert hasattr(obj, 'isHBObject')
            except AssertionError:
                raise ValueError(
                    "\n{} is not a valid Honeybee object.".format(obj))

            assert hasattr(analysis_recipe, 'isAnalysisRecipe'), \
                ValueError("\n{} is not a Honeybee recipe.".format(analysis_recipe))

            legend_par = analysis_recipe.legend_parameters

            #write to file

            # Add Honeybee objects to the recipe
            analysis_recipe.hb_objects = hb_objects
            analysis_recipe.scene = rad_scene

            batch_file = analysis_recipe.write(folder, filename)

            #run if 'save file only' is not checked
            outputs = None
            if not save_file_only:
                if analysis_recipe.run(batch_file, False):
                    try:
                        outputs = analysis_recipe.results()
                    except StopIteration:
                        raise ValueError(
                            'Length of the results is smaller than the analysis grids '
                            'point count [{}]. In case you have changed the analysis'
                            ' Grid you must re-calculate daylight/view matrix!'
                            .format(analysis_recipe.total_point_count))
            if outputs:
                LadybugEto.displayAnalysis(grid_mesh, outputs, legend_par,
                                           filename)

        except Exception as e:
            print e
コード例 #20
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)
コード例 #21
0
ファイル: ArrayBetween.py プロジェクト: syl1130/pythonscripts
def ArrayBetween():
    def OnDynamicDraw(sender, e):
        i = optBasePoint[0]
        pts = []
        count = optInt.CurrentValue
        if i == 0:  #center
            basept.X = center.X
            basept.Y = center.Y
        if i == 1:  #lowerleft
            basept.X = center.X - width / 2
            basept.Y = center.Y - depth / 2
        if i == 2:  #upperleft
            basept.X = center.X - width / 2
            basept.Y = center.Y + depth / 2
        if i == 3:  #lowerright
            basept.X = center.X + width / 2
            basept.Y = center.Y - depth / 2
        if i == 4:  #upperright
            basept.X = center.X + width / 2
            basept.Y = center.Y + depth / 2
        vec = e.CurrentPoint - basept

        gp.SetBasePoint(basept, False)
        line = Rhino.Geometry.Line(basept, e.CurrentPoint)
        curve = line.ToNurbsCurve()
        params = curve.DivideByCount(count - 1, True)
        for param in params:
            pts.append(line.PointAt(param))

        length = vec.Length
        dist = length / (count - 1)
        vec.Unitize()

        for i in range(1, count):
            translate = vec * i * dist
            xf = Rhino.Geometry.Transform.Translation(translate)
            newobj = obj.Duplicate()
            newobj.Transform(xf)
            if obj.ObjectType == Rhino.DocObjects.ObjectType.Curve:
                e.Display.DrawCurve(newobj, Color.LightCyan, 2)
            if obj.ObjectType == Rhino.DocObjects.ObjectType.Brep:
                e.Display.DrawBrepWires(newobj, Color.LightCyan)
        e.Display.DrawLine(line, Color.Blue, 2)

    def getPoint():
        while True:
            result = gp.Get()
            if result == Rhino.Input.GetResult.Point:
                count = optInt.CurrentValue
                line = Rhino.Geometry.Line(center, gp.Point())
                curve = line.ToNurbsCurve()
                params = curve.DivideByCount(count - 1, True)
                pts = []
                for param in params:
                    pts.append(line.PointAt(param))
                vec = gp.Point() - basept
                length = vec.Length
                dist = length / (count - 1)
                vec.Unitize()

                for i in range(1, count):
                    translate = vec * i * dist
                    xf = Rhino.Geometry.Transform.Translation(translate)
                    newobj = obj.Duplicate()
                    newobj.Transform(xf)
                    if obj.ObjectType == Rhino.DocObjects.ObjectType.Curve:
                        sc.doc.Objects.AddCurve(newobj)
                    if obj.ObjectType == Rhino.DocObjects.ObjectType.Brep:
                        sc.doc.Objects.AddBrep(newobj)
                sc.doc.Views.Redraw()
            elif result == Rhino.Input.GetResult.Option:
                optionindex = gp.Option().CurrentListOptionIndex
                optBasePoint[0] = optionindex

                getPoint()
            break

    docobj = rs.GetObject("select object to array", 28)
    if rs.IsCurve(docobj):
        obj = rs.coercecurve(docobj)
    if rs.IsBrep(docobj):
        obj = rs.coercebrep(docobj)
    if not obj: return

    plane = Rhino.Geometry.Plane.WorldXY
    bb = obj.GetBoundingBox(plane)
    if bb == None:
        print "can't calculate boundingbox"
        return
    center = bb.Center

    basept = bb.Center

    minimum = bb.Min
    maximum = bb.Max

    center.Z = minimum.Z
    width = maximum.X - minimum.X
    depth = maximum.Y - minimum.Y

    gp = Rhino.Input.Custom.GetPoint()
    gp.SetCommandPrompt("point to array to / distance")
    optInt = Rhino.Input.Custom.OptionInteger(3, 3, 999)
    gp.AddOptionInteger("Count", optInt)
    basepoints = [
        "center", "lower_left", "upper_left", "lower_right", "upper_right"
    ]
    gp.AddOptionList("basepoint", basepoints, 0)
    optBasePoint = [0]  #equal to index 0 of basepoints option

    gp.DynamicDraw += OnDynamicDraw
    getPoint()
コード例 #22
0
ファイル: Deploy_Engine.py プロジェクト: vctcn93/rhinoscript
 def onAddRhinoObject(self, sender, e):
     obj = rs.FirstObject()
     isBrep = rs.IsBrep(obj)
     if self.interaction_mode.auto_block and isBrep:
         self.addObject(obj, 'BLOCK', 0, None)