def _insert_zigzag(self, p, t): """Receives: p Point3d t int: {0 | 1 | 2 | 3}. A transformation, where 0: identity 1: (vertical) reflection 2: (90 degree) rotation 3: reflection and rotation as above Inserts a zigzag block at point p under transformation t """ insertion_point = p reflect_no = [1, 1, 1] reflect_yes = [-1, 1, 1] rotate_no = 0 rotate_yes = 90 if t == 0: scale = reflect_no angle = rotate_no elif t == 1: scale = reflect_yes angle = rotate_no elif t == 2: scale = reflect_no angle = rotate_yes elif t == 3: scale = reflect_yes angle = rotate_yes else: pass rs.InsertBlock(self.zigzag, insertion_point, scale, angle)
def addLevelMarks(func): rs.EnableRedraw(False) leftAlign = True geometry = [] currentLevels = setLevels.getFloorLevels() for level in currentLevels: if level is None: print "Levels have not been set." return levelNames = rs.GetDocumentData("Levels") size = 10 i = 0 stPts = [] for level in currentLevels: vec1 = [size*.2,size*.1,0] ptA = [0, level, 0] ptB = [size*.5, level, 0] stPts.append(ptA) geometry.append(rs.AddLine(ptA, ptB)) geometry.append(rs.AddText(levelNames[i] + ": +" + str(level), rs.VectorAdd(ptA, vec1), size*.1)) #Triangle Marking triPts = [[0,0,0], [size*.05, size*.07,0], [-size*.05, size*.07,0], [0,0,0]] newPts = [] triPt = rs.VectorAdd(ptA, [size*.1, 0,0]) for j in range(0, 4): newPts.append(rs.VectorAdd(triPt, triPts[j])) tri = rs.AddPolyline(newPts) geometry.append(rs.CloseCurve(tri)) i=i+1 #Dimensions for i in range(0, len(currentLevels)-1): pt1 = [0,currentLevels[i], 0] pt2 = [0,currentLevels[i+1], 0] pt3 = [size*-.15,currentLevels[i+1], 0] geometry.append(rs.AddAlignedDimension(pt1, pt2, pt3)) firstPt = [0,currentLevels[0], 0] lastPt = [0,currentLevels[-1], 0] dimOffset = [size*-.3,currentLevels[-1], 0] geometry.append(rs.AddAlignedDimension(firstPt, lastPt, dimOffset)) rs.AddLayer("80_LAYOUT", visible = True) annoLayer = rs.AddLayer("ANNO", parent = "80_LAYOUT") for geo in geometry: rs.ObjectLayer(geo, annoLayer) rs.AddBlock(geometry, [0,0,0], "Level Marks", True) if (func == 0): block = rs.InsertBlock("Level Marks", [0,0,0]) rs.ObjectLayer(block, "ANNO") rs.EnableRedraw(True) return
def main(): for name in rs.BlockNames(): block = rs.InsertBlock(name, (0,0,0)) rs.UnselectAllObjects() # explodblock uids = rs.ExplodeBlockInstance(block) rs.SelectObjects(uids) rs.Command('! _-Export _Pause "E:\\TNM\\template\\tools\\' + name + '.3dm" _Enter')
def CreateDesignOption(): objs = rs.GetObjects("Select objects to create design option with", preselect=True) if objs is None: return None try: date = utils.GetDatePrefix() origName = date + '_OPTION_00' defaultName = origName for i in range(100): defaultName = utils.UpdateString(defaultName) if origName == defaultName: break if rs.IsBlock(defaultName) == False: break looping = True while looping: designOptionName = rs.StringBox("Design Option Name", defaultName, "Create Design Option") if designOptionName is None: return None if rs.IsBlock(designOptionName): print "Block name already exists" elif len(designOptionName) == 0: print "Must specify a name" else: looping = False block = rs.AddBlock(objs, (0, 0, 0), designOptionName, True) blockInstance = rs.InsertBlock(designOptionName, (0, 0, 0)) #Add user text rs.SetUserText(blockInstance, 'Design Option History', designOptionName) #Ensure 3_DESIGN OPTIONS already exists layers.AddLayerByNumber(3000, False) #Create new layer parentLayer = layers.GetLayerNameByNumber(3000) designOptionLayer = rs.AddLayer(parentLayer + "::" + designOptionName, color=utils.GetRandomColor()) rs.ObjectLayer(blockInstance, designOptionLayer) utils.SaveFunctionData('Blocks-Create Design Option', [__version__, designOptionName]) return True except: print "Failed to create design option" utils.SaveFunctionData('Blocks-Create Design Option', [__version__, '', 'Failed']) return None
def main(): for name in rs.BlockNames(): block = rs.InsertBlock(name, (0, 0, 0)) rs.UnselectAllObjects() # explodblock uids = rs.ExplodeBlockInstance(block) rs.SelectObjects(uids) rs.Command( "_-Insert File=Yes LinkMode=Link E:\\TNM\\template\\tools\\" + name + ".3dm Block 0,0,0 1.0 0.0")
def new_instance(cls, position): """Receives: position Point3d or (num, num, num). The center point of the arrow Creates a double arrow definition, if there is not one already. Inserts an instance at the specified location on the specified layer. Returns: return_value guid. The guid of the new instance if successful. None otherwise """ if not cls._definition_exists(): cls._new_definition() arrow_name = s.Settings.double_arrow_name return_value = rs.InsertBlock(arrow_name, position) return return_value
def new_instance(cls, layer_name, position): """Receives: layer_name str. The name of an existing layer position Point3d or (num, num, num). The center point of the arrow Creates an arrow definition, if there is not already one. Inserts an arrow instance at the specified position on the specified layer. Returns: arrow_instance guid. The guid of the new arrow instance """ if not cls._definition_exists(): cls._new_definition() rs.CurrentLayer(layer_name) arrow_name = s.Settings.arrow_name return_value = rs.InsertBlock(arrow_name, position) default_layer_name = s.Settings.default_layer_name rs.CurrentLayer(default_layer_name) return return_value
def organizedBlock(): """ create a block from selection and add it to a layer with the block's name nested under layer Block_Definitions tested in Rhino 6.14 www.studiogijs.nl """ #get objects to create block from objs = rs.GetObjects("select objects to creat block from") if not objs: return base_point = rs.GetPoint("block base point") if not base_point: return def checkName(): block_name = rs.GetString("enter block name") if block_name == '' or block_name == None: print "block name can't be empty" return checkName() #check if layer Block_Definitions exist, else create it if not rs.IsLayer("Block_Definitions"): rs.AddLayer("Block_Definitions") #check if layer with block name exists, else create it if not rs.IsLayer("Block_Definitions::" + block_name): block_layer = rs.AddLayer(block_name, parent="Block_Definitions") else: print "block definition with this name already exists" return checkName() return block_layer, block_name block_layer, block_name = checkName() #create the block block = rs.AddBlock(objs, base_point, block_name, True) if not block: return temp_layer = rs.CurrentLayer() rs.CurrentLayer(block_layer) rs.InsertBlock(block, base_point) #restore to previous layer rs.CurrentLayer(temp_layer)
def assignBlockToPanel(obj): """ Assigns block containing a base surface to a surface with the matching name. Block, base surface, and target surface must all have the same name. input: target surface (with name) returns: None """ allBlockNames = rs.BlockNames() for eachBlockName in allBlockNames: if rs.ObjectName(obj) == eachBlockName: blockName = eachBlockName print "Matching Block Found" objBasePt = rs.SurfaceEditPoints(obj)[0] objYPt = rs.SurfaceEditPoints(obj)[1] objXPt = rs.SurfaceEditPoints(obj)[2] objXVec = rs.VectorCreate(objXPt, objBasePt) objXLength = rs.VectorLength(objXVec) objYLength = rs.Distance(objBasePt, objYPt) blockObjs = rs.BlockObjects(blockName) for blockObj in blockObjs: if rs.ObjectName(blockObj) == blockName: print "Contains base plane" if rs.IsSurface(blockObj): blockBasePt = rs.SurfaceEditPoints(blockObj)[0] blockYPt = rs.SurfaceEditPoints(blockObj)[1] blockXPt = rs.SurfaceEditPoints(blockObj)[2] blockXVec = rs.VectorCreate(blockXPt, blockBasePt) rotAngle = rs.VectorAngle(objXVec, blockXVec) blockXLength = rs.VectorLength(blockXVec) blockYLength = rs.VectorLength( rs.VectorCreate(blockYPt, blockBasePt)) xScale = objXLength / blockXLength yScale = objYLength / blockYLength newScale = [yScale, xScale, 1] rs.InsertBlock(blockName, objBasePt, scale=newScale, angle_degrees=rotAngle) break else: print "Error: Base plane was not a surface"
def makeBlockUnique(obj): oldBase = rs.BlockInstanceInsertPoint(obj) if oldBase is None: return newName = rs.GetString("New Block Name") if newName is None: return newOrigin = rs.GetPoint("Select New Block Base point", base_point=oldBase) if newOrigin is None: return blockObjs = rs.ExplodeBlockInstance(obj) if blockObjs is None: return origObjs = [] for a in blockObjs: origObjs.append(a) rs.AddBlock(origObjs, newOrigin, newName, True) rs.InsertBlock(newName, newOrigin) return
def new_instance(cls, layer_name, position): """Receives: layer_name str. The name of an existing layer position Point3d. The position of the frame block Creates a frame block definition, if there is not already one. Inserts a frame block instance at the specified position on the specified layer. Returns: frame_instance guid. The guid of the new frame block instance """ ( frame_name, default_layer_name ) = ( s.Settings.frame_name, s.Settings.default_layer_name) if not cls._definition_exists(): cls._new_definition() rs.CurrentLayer(layer_name) frame_instance = rs.InsertBlock(frame_name, position) rs.CurrentLayer(default_layer_name) return frame_instance
def draw_model_paperspace(): #go to paperspace, then go to view and enter its modelspace view = rs.CurrentView() #rs.CurrentDetail() detail = rs.CurrentDetail(view) type = Rhino.RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.ViewportType if type != Rhino.Display.ViewportType.DetailViewport: print "Please enter detail modelspace" return print type #get model objs = rs.GetObjects("Select objects to draw", rs.filter.polysurface) rs.SelectObjects(objs) #make 2d, as current view rs.Command("!-_Make2D DrawingLayout=CurrentView _enter _enter") dwg_crvs = rs.LastCreatedObjects() #cut and paste into view window (paperspace) origin = [0, 0, 0] rs.AddBlock(dwg_crvs, origin, name=view, delete_input=True) #leave detail view and insert block rs.CurrentDetail(view, detail=view) insert_pt = [17, 11, 0] obj = rs.InsertBlock(view, insert_pt) #orient 2pt with 3d scaling enabled r1 = rs.GetPoint("Pick reference corner 1") r2 = rs.GetPoint("Pick reference corner 2") t1 = rs.GetPoint("Pick target corner 1") t2 = rs.GetPoint("Pick target corner 2") ref_pts = [r1, r2] target_pts = [t1, t2] rs.OrientObject(obj, ref_pts, target_pts, flags=2) print "Script Finished" return
def _insert_other_block(other_block_name, layer_name, position): if not rs.IsBlock(other_block_name): _define_other_block() rs.CurrentLayer(layer_name) rs.InsertBlock(other_block_name, position) rs.CurrentLayer(s.Settings.default_layer_name)
import rhinoscriptsyntax as rs theObjs = rs.SelectedObjects() rs.EnableRedraw(enable=False) for i in range(len(theObjs)): obj = [theObjs[i]] objName = str(rs.ObjectLayer(obj[0])) + str(i) block = rs.AddBlock(obj, (0, 0, 0), objName, True) rs.InsertBlock(block, (0, 0, 0)) rs.EnableRedraw(enable=True)
import trkRhinoPy as trp import rhinoscriptsyntax as rs obj = rs.GetObject('select block to insert', rs.filter.instance, preselect=True) if obj: blkname = rs.BlockInstanceName(obj) pt = rs.GetPoint('insertion point') if pt: rs.InsertBlock(blkname, pt)
def ExportSelected(scale, path, name): #ShowStep("Scene or block export") # Include lights, exclude grips in selected selected = SelectedObjects() rs.UnselectAllObjects() export_exists = False # Export lights # NOTE: Lights must be exported separately so that # placeholder meshes can be imported without modification. placeholders = [] for object in selected: if rs.ObjectType(object) & lights_export: rs.SelectObject(object) lightLocation = LightLocation(object, scale) placeholders.append(lightLocation) rs.SelectObject(lightLocation) if len(SelectedObjects()) > 0: #ShowStep("Light export") ExportModel(path, name + ".lights") rs.DeleteObjects(placeholders) export_exists = True rs.UnselectAllObjects() # Export meshes for object in selected: if rs.ObjectType(object) & meshes_export: rs.SelectObject(object) if len(SelectedObjects()) > 0: #ShowStep("Mesh objects export") ExportModel(path, name + ".meshes") export_exists = True rs.UnselectAllObjects() # Export detail for object in selected: if rs.ObjectType(object) & detail_export: rs.SelectObject(object) if len(SelectedObjects()) > 0: #ShowStep("Parametric objects export") ExportModel(path, name + ".meshes0", 0) ExportModel(path, name + ".meshes1", 1) ExportModel(path, name + ".meshes2", 2) export_exists = True rs.UnselectAllObjects() # Export blocks # NOTE: Block placeholders must be exported separately # so that meshes can be imported with modification. placeholders = [] for object in selected: if rs.ObjectType(object) & blocks_export: # Export block constituents into subdirectory # On import contents of block will be merged, # and will then replace placeholders in scene and other blocks block = rs.BlockInstanceName(object) block_name = SafeObjectName(block) block_path = os.path.join(path, block_name) block_done = False try: os.mkdir(block_path) except OSError: # Directory exists so block has already been exported block_done = True if not block_done: # Export block instantiation instance = rs.InsertBlock(block, [0, 0, 0]) # IMPORTANT: Nested instances are not exploded, # so that constituent blocks will be exported. instance_parts = rs.ExplodeBlockInstance(instance) rs.SelectObjects(instance_parts) block_name_map = {} UniqueRename(block_name_map) #ShowStep("Block " + block + " export") # IMPORTANT: block subdirectory is prepended to name # so that constituent blocks will be discovered or exported # in adjacent directories. # This prevents repeated exporting in nested directories. block_pathname = os.path.join(block_name, block_name) block_done = ExportSelected(scale, path, block_pathname) rs.DeleteObjects(instance_parts) if block_done: # Create a placeholder placeholders.append(BlockLocation(object, scale)) else: # Remove empty directory os.rmdir(block_path) if len(placeholders) > 0: rs.SelectObjects(placeholders) #ShowStep("Block placeholder export") ExportModel(path, name + ".places") rs.DeleteObjects(placeholders) export_exists = True # Restore selection rs.SelectObjects(selected) return export_exists
def drawOpening(self, distance, length, side=0, block=0, direct=0): """ side=0 start from startPoint , side=1 start from endPoint direct: 0 | 1 ------- 2 | 3 block 0=empty 1=window 2=door """ localDirect = direct if side == 1: self.flip() if direct == 0: localDirect = 3 if direct == 1: localDirect = 2 if direct == 2: localDirect = 1 if direct == 3: localDirect = 0 startParameter = self.line1.ClosestParameter(self.line0.From) startPoint = self.line1.ClosestPoint(self.line0.From, False) if startParameter >= 0: distance00 = distance distance10 = distance + startPoint.DistanceTo(self.line1.From) else: distance00 = distance + startPoint.DistanceTo(self.line1.From) distance10 = distance distance01 = distance00 + length distance11 = distance10 + length """ p10 p11 ------ ------>line1 | | ------ ------>line0 p00 p01 """ point00 = self.line0.PointAtLength(distance00) point10 = self.line1.PointAtLength(distance10) point01 = self.line0.PointAtLength(distance01) point11 = self.line1.PointAtLength(distance11) parameter00 = self.line0.ClosestParameter(point00) parameter10 = self.line1.ClosestParameter(point10) parameter01 = self.line0.ClosestParameter(point01) parameter11 = self.line1.ClosestParameter(point11) if parameter00 < 0 or parameter00 > 1 or parameter10 < 0 or parameter10 > 1 or parameter01 < 0 or parameter01 > 1 or parameter11 < 0 or parameter11 > 1: print("error: wrong opening length") return 0 # drawing sc.doc.Objects.AddLine(point00, point10) sc.doc.Objects.AddLine(point01, point11) sc.doc.Objects.AddLine(self.line0.From, self.line0.PointAt(parameter00)) sc.doc.Objects.AddLine(self.line0.PointAt(parameter01), self.line0.To) sc.doc.Objects.AddLine(self.line1.From, self.line1.PointAt(parameter10)) sc.doc.Objects.AddLine(self.line1.PointAt(parameter11), self.line1.To) # empty if block == 0: pass # window elif block == 1: scaleX = point00.DistanceTo(point01) / 1000 scaleY = point00.DistanceTo(point10) / 100 origin = (point00 + point10 + point01 + point11) / 4 block_id = rs.InsertBlock("window", origin, (scaleX, scaleY, 1), 0, (0, 0, 1)) angle_degrees = rs.Angle(point00, point01)[0] rs.RotateObject(block_id, origin, angle_degrees) # door elif block == 2: scaleX = point00.DistanceTo(point01) / 1000 scaleY = scaleX origin = (point00 + point10 + point01 + point11) / 4 block_id = rs.InsertBlock("door", origin, (scaleX, scaleY, 1), 0, (0, 0, 1)) angle_degrees = rs.Angle(point00, point01)[0] rs.RotateObject(block_id, origin, angle_degrees) if localDirect == 0: pass elif localDirect == 1: rs.MirrorObject(block_id, (point10 + point11) / 2, (point00 + point01) / 2) elif localDirect == 2: rs.MirrorObject(block_id, (point00 + point10) / 2, (point01 + point11) / 2) elif localDirect == 3: rs.MirrorObject(block_id, (point10 + point11) / 2, (point00 + point01) / 2) rs.MirrorObject(block_id, (point00 + point10) / 2, (point01 + point11) / 2)
def Populate_Surfaces(): #try: ########################################################################### #GET FUNCTIONS #GET INPUT SURFACE #srfs = rs.GetObjects('Select surface to populate', rs.filter.surface, True, True) #if srfs is None: return msg = "Select a surface or polysurface face to populate" srf_filter = rc.DocObjects.ObjectType.Surface res, srfObjs = rc.Input.RhinoGet.GetMultipleObjects(msg, False, srf_filter) if res != rc.Commands.Result.Success: return #Cleanup obj ref srfs = [] for srf in srfObjs: if srf.GeometryComponentIndex < 0: face = srf.Surface() else: face = srf.Face() subSrf = face.ToNurbsSurface() srfs.append(subSrf) #GET POPULATION TYPE type = GetPopulationType(False) if type is None: return None #GET BLOCK NAMES if type == 'Custom Block': blockNames, blockIDs = GetCustomBlockNames() else: blockNames = GetBlockNames(type) if blockNames is None: return #GET NUMBER OF OBJECTS numObjects = GetNumObjects() if numObjects is None: return None ########################################################################### #Spacing if type == '2D People' or type == '3D People': spacing = 42 elif type == '2D Trees': spacing = 100 elif type == '3D Trees': spacing = 200 else: spacing = GetCustomSpacing(blockNames[0]) ########################################################################### #DRAW FUNCTIONS rs.EnableRedraw(False) #RANDOM PTS ON SURFACE pts = [] for srf in srfs: pts.append(RandomPtsOnSrf(srf, numObjects)) #RANDOM ANGLES angles = [] for srf in srfs: angles.append(RandomAngles(numObjects)) #ORIENT ANGLES AWAY FROM EDGES if type == '2D People' or type == '3D People': for i, srf in enumerate(srfs): angles[i] = OrientAwayFromEdges(pts[i], angles[i], srf, spacing) for i in range(0, 5): #CONGREGATE THE POINTS for j, srf in enumerate(srfs): pts[j] = Congregate(pts[j], spacing, 3) #MOVE AWAY FROM SURFACE EDGES pts[j] = MoveAwayFromEdges(pts[j], srf, spacing) #ORIENT ANGLES TOGETHER if type == '2D People' or type == '3D People': for i, srf in enumerate(srfs): angles[i] = AlignAngles(pts[i], angles[i], srf, spacing) upVec = rc.Geometry.Vector3d(0, 0, 1) scaleVariation = .1 for i, srf in enumerate(srfs): for j, pt in enumerate(pts[i]): #Choose random angle angle = angles[i][j] thisIndex = random.randint(0, len(blockNames) - 1) thisBlockName = blockNames[thisIndex] if TryLoadBlock(type, thisBlockName): #xform = rs.BlockInstanceXform(blockIDs[thisIndex]) eachBlock = rs.InsertBlock(thisBlockName, pt, angle_degrees=angle) #eachBlock = rs.InsertBlock2(thisBlockName, newXform) try: if type == '2D People' or type == '3D People': layerName = '2_ENTOURAGE::' + 'People' elif type == '2D Trees': layerName = '2_ENTOURAGE::' + 'Vegetation' elif type == '3D Trees': layerName = '2_ENTOURAGE::' + 'Vegetation' elif type == '3D Vehicles': layerName = '2_ENTOURAGE::' + 'Vehicles' elif type == 'Custom Block': layerName = rs.ObjectLayer(blockIDs[0]) else: layerName = '2_ENTOURAGE' rs.ObjectLayer(eachBlock, layerName) xyScale = random.uniform(1 - scaleVariation, 1 + scaleVariation) zScale = random.uniform(1 - scaleVariation, 1 + scaleVariation) rs.ScaleObject(eachBlock, pt, (xyScale, xyScale, zScale)) except: pass rs.EnableRedraw(True)
def sweepVolume(crv, tool_id, z_pos): tangent = rs.CurveTangent(crv, rs.CurveParameter(crv, 0)) origin = rs.CurveStartPoint(crv) block = rs.InsertBlock( tool_id, (0,0,0), scale=(1,1,1) ) # rs.DeleteObjects(objs) # pt2 = [origin.X, origin.Y + perp.XAxis[1], origin.Z] pt2 = [origin.X, origin.Y , origin.Z + 1] pt3 = [origin.X + tangent.X, origin.Y + tangent.Y , origin.Z + tangent.Z] ref = [(0,0,0),(0,1,0),(0,0,1)] target = [origin, pt2 ,pt3] block = rs.OrientObject(block, ref, target) objs = rs.ExplodeBlockInstance(block) profile = None for item in objs: if rs.ObjectLayer(item) == 'HULP::C_Toolcontours' or rs.ObjectLayer(item) == 'Hulp::C_Toolcontours': profile = rs.CopyObject(item) rs.DeleteObjects(objs) if not profile: rs.MessageBox('there is no layer named "C_Toolcontours" in block %s' % rs.BlockInstanceName(block)) return False profile = rs.OffsetCurve(profile, rs.CurveAreaCentroid(profile)[0], 0.001, style=1) # rs.MoveObject(profile, (0,0,z_pos)) # rail = obj # rail_crv = rs.coercecurve(rail) # if not rail_crv: return # # cross_sections = [profile] # if not cross_sections: return # cross_sections = [rs.coercecurve(crv) for crv in cross_sections] # # sweep = Rhino.Geometry.SweepOneRail() # sweep.AngleToleranceRadians = scriptcontext.doc.ModelAngleToleranceRadians # sweep.ClosedSweep = True # # sweep.MiterType = 2 # sweep.SweepTolerance = scriptcontext.doc.ModelAbsoluteTolerance # sweep.SetToRoadlikeTop() # breps = sweep.PerformSweep(rail_crv, cross_sections) # for brep in breps: scriptcontext.doc.Objects.AddBrep(brep) # scriptcontext.doc.Views.Redraw() # # # surface_id = rs.LastCreatedObjects() # METHOD1 surface_id = rs.AddSweep1( crv, profile, True ) rs.CapPlanarHoles(surface_id) pt = rs.CurveAreaCentroid(profile)[0] pt2 = (pt.X, pt.Y, pt.Z+1) rev = rs.AddRevSrf( profile, (pt, pt2) ) rs.MoveObject(surface_id, (0,0,z_pos)) rs.MoveObject(rev, (0,0,z_pos)) return [surface_id, rev] rs.UnselectAllObjects() rs.SelectObjects([crv, profile]) result = rs.Command("_-Sweep1 _Enter Style=RoadlikeTop _Enter", False) if result: rs.DeleteObject(profile) surface_id = rs.LastCreatedObjects() rs.CapPlanarHoles(surface_id) rs.DeleteObjects(objs) rs.MoveObject(surface_id, (0,0,z_pos)) return surface_id
def draw_rule_frame(self): """Draws a rule frame at the origin """ rs.InsertBlock('shape frame', [0, 0, 0]) rs.InsertBlock('shape frame', [50, 0, 0])
def TreeMassing(): try: litre = rs.GetReal("Enter the root ball litres, max 2000 Litres", 400) soilDepth = rs.GetReal('Enter the soil depth available in m', 0.8) matureHeight = rs.GetReal('Enter the mature tree height in m', 5) dbh = rs.GetReal( 'Enter the DBH at maturity in m, if unknown hit Enter', 0) userPt = rs.GetPoint('Pick a point to place rootball') rs.EnableRedraw(False) # Dictionery for litre size to pot Rootball Diameter [0] / Rootball Height [1] / Calliper [2] / Height [3] / Spread [4] # Figures obtained from https://winterhill.com.au/tree-sizes/ PotDict = { 25: [0.300, 0.250, 0.020, 1.000, 0.500], 45: [0.420, 0.350, 0.025, 2.000, 1.000], 75: [0.465, 0.500, 0.035, 2.500, 2.000], 100: [0.520, 0.560, 0.050, 3.500, 2.000], 200: [0.700, 0.625, 0.070, 4.500, 3.000], 400: [0.980, 0.715, 0.090, 6.000, 4.000], 600: [1.200, 0.600, 0.100, 6.000, 5.000], 800: [1.300, 0.600, 0.120, 7.000, 5.000], 1000: [1.500, 0.600, 0.150, 8.000, 5.000], 2000: [2.000, 0.800, 0.200, 9.000, 5.000], } def closest(lst, K): return lst[min(range(len(lst)), key=lambda i: abs(lst[i]-K))] def scale(): system = rs.UnitSystem() if system == 2 or system == 3 or system == 4: scaleFactorDict = {2: 1000, 3: 100, 4: 1} scaleFactor = scaleFactorDict[system] return scaleFactor if system != 2 or system != 3 or system != 4: return None s = scale() if s == None: rs.MessageBox( "This tool is can only be used in mm, cm or m model units") return None # Calc for standard soil requirements as per Australian Standards if dbh == 0: dbh = ((matureHeight / 100) * 4) * 1000 # Gives a DBH in mm # Gives a required soil volume in M3 reqSoil = (matureHeight * dbh) / 100 reqSoilRadius = math.sqrt(reqSoil / ((math.pi)*soilDepth)) # Add soil puck to doc reqSoilRadiusCyl = rs.AddCylinder( userPt, (soilDepth*s), (reqSoilRadius*s), cap=True) rs.ObjectColor(reqSoilRadiusCyl, (150, 75, 0)) # Calc for size of rootball as per standard pot sizes litreMatch = closest(list(PotDict.keys()), litre) dia = (PotDict[litreMatch])[0] height = (PotDict[litreMatch])[1] # Add Rootball to doc rootballCyl = rs.AddCylinder(userPt, (height*s), ((dia/2)*s)) rs.ObjectColor(rootballCyl, (0, 128, 0)) vec = (0, 0, ((soilDepth*s) - (height*s))) rs.MoveObject(rootballCyl, vec) # Add Tree model based on Dict calliper = (PotDict[litreMatch])[2] treeHeight = (PotDict[litreMatch])[3] spread = (PotDict[litreMatch])[4] vec02 = (0, 0, (((soilDepth*s) - (height*s))) + (height*s)) treeTrunk = rs.AddCylinder(userPt, (treeHeight*s), (calliper*s)) rs.ObjectColor(treeTrunk, (101, 67, 33)) rs.MoveObject(treeTrunk, vec02) canopy = rs.AddSphere(userPt, ((spread/2)*s)) rs.ObjectColor(canopy, (33, 101, 67)) vec03 = (0, 0, (((soilDepth*s) - (height*s))) + (height*s) + (treeHeight*s) - ((spread/2)*s)) rs.MoveObject(canopy, vec03) # Various Text Annotation txt1 = rs.AddText('Rootball ' + 'Height = ' + str(height*s) + ', Diameter = ' + str(dia*s), userPt, height=(.1*s), font="Arial", font_style=0, justification=2) txt2 = rs.AddText('Soil Volume Requirement = ' + str(reqSoil) + ' m3', (userPt.X, (userPt.Y - (.2*s)), userPt.Z), height=(.1*s), font="Arial", font_style=0, justification=2) block = rs.AddBlock((reqSoilRadiusCyl, rootballCyl, treeTrunk, canopy, txt1, txt2), userPt, ("Rootball and Soil " + (str(random.random()))), delete_input=True) rs.BlockDescription(block, 'Rootball ' + 'Height = ' + str(height*s) + ', Diameter = ' + str(dia*s) + ', Soil Volume Requirement = ' + str(reqSoil) + ' m3') guid = rs.InsertBlock(block, userPt) rs.ObjectName(guid, 'Rootball ' + 'Height = ' + str(height*s) + ', Diameter = ' + str(dia*s) + ', Soil Volume Requirement = ' + str(reqSoil) + ' m3') rs.EnableRedraw(True) except: print("Failed to execute") rs.EnableRedraw(True) return
def RunCommand(is_interactive): if sc.escape_test(False): print "script cancelled" #do something print "Making unique..." #******* Get blocks ***************** #************************************ objectIds = rs.GetObjects("Pick some blocks", 4096, preselect=True) if not objectIds: print "No objects" return False #pause viewport redraw rs.EnableRedraw(False) #******* Sort blocks by type ******** #************************************ blockTypes = {} for id in objectIds: blockName = rs.BlockInstanceName(id) if blockName not in blockTypes: blockTypes[blockName] = [] blockTypes[blockName].append(id) #***** Define new block and add ***** #************************************ #Get block names blockNames = rs.BlockNames() #gather all new objects when done finalObjs = [] for blockType in blockTypes: for id in blockTypes[blockType]: #Get the block transformation matrix and name blockXForm = rs.BlockInstanceXform(id) blockName = rs.BlockInstanceName(id) #Insert new block in 0,0,0 newBlock = rs.InsertBlock(blockName, [0, 0, 0]) #Explode the block exObjs = rs.ExplodeBlockInstance(newBlock) #create new block name # if the string ends in digits m will be a Match object, or None otherwise. strippedName = re.sub(r'#[0-9]+$', '', blockName) #test if block name exist and add to the end number if true. x = 0 tryAgain = True while tryAgain: x += 1 newerBlockName = strippedName + "#" + str(x) if newerBlockName not in blockNames: tryAgain = False break #insert exObjs as new block rs.AddBlock(exObjs, [0, 0, 0], newerBlockName, delete_input=True) newerBlock = rs.InsertBlock(newerBlockName, [0, 0, 0]) #match properties from original rs.MatchObjectAttributes(newerBlock, id) #transform new block rs.TransformObject(newerBlock, blockXForm) #append for final selection finalObjs.append(newerBlock) #add name to list of used blocknames. blockNames.append(newerBlockName) #Delete original block rs.DeleteObjects(objectIds) #Select all new objects rs.SelectObjects(finalObjs) rs.EnableRedraw(True) print "...aaand its done." #End RunCommand() #end sane return 0
def insert_block(self): insert_pt = [17, 11, 0] obj = rs.InsertBlock(self.block_name, insert_pt) self.paper_dwg = obj return
def insert_rule_frames(): rs.CurrentLayer('infrastructure') rs.InsertBlock('shape frame', [0, 0, 0]) rs.InsertBlock('shape frame', [50, 0, 0]) rs.CurrentLayer('Default')