def get_layers_to_string(structure_element, element_param_name, material_param_name, base=''): element_type = doc.GetElement(structure_element.GetTypeId()) element_param = element_type.LookupParameter(element_param_name) if element_param: structure = element_type.GetCompoundStructure() variable_layer_index = structure.VariableLayerIndex max_point = get_max_slab_shape_vertex(structure_element) layers = structure.GetLayers() data = '' for i in range(0, len(layers)): width = to_int(UnitUtils.ConvertFromInternalUnits(layers[i].Width, DisplayUnitType.DUT_MILLIMETERS)) name = get_material_name(layers[i].MaterialId, material_param_name).capitalize() if not name: name = 'Value_is_missing' is_variable_layer = layers[i].LayerId == variable_layer_index if width != 0 and not is_variable_layer or isinstance(max_point, str): data += '\r\n{}. {} - {} мм'.format(i + 1, name, width) elif is_variable_layer and not isinstance(max_point, str): total_width = to_int(width + max_point) data += '\r\n{}. {} - от {}-{} мм'.format(i + 1, name, width, total_width) else: data += '\r\n{}. {}'.format(i + 1, name) if base: data += '\r\n{}. {}'.format(len(layers) + 1, base) if element_param.StorageType == StorageType.String: element_param.Set(data.strip()) return data.strip()
def unit_conversion(): """Convert Revit units to Dynamo Units.""" doc = DocumentManager.Instance.CurrentDBDocument doc_units = doc.GetUnits() length_unit = doc_units.GetFormatOptions(UnitType.UT_Length).DisplayUnits return UnitUtils.ConvertFromInternalUnits(1.0, length_unit)
def set_value_by_param_name(elem, parameter_name, value): param = elem.LookupParameter(parameter_name) if param: if param.StorageType == StorageType.String: val = UnitUtils.ConvertFromInternalUnits(value, DisplayUnitType.DUT_SQUARE_METERS) param.Set(str(val)) elif param.StorageType == StorageType.Double: param.Set(value)
def get_max_slab_shape_vertex(structure_element): if structure_element.Category.Id.IntegerValue == -2000032: slab_shape_editor = structure_element.SlabShapeEditor if slab_shape_editor: slab_shape_vertices = slab_shape_editor.SlabShapeVertices point_z = [vertice.Position.Z for vertice in slab_shape_vertices] return UnitUtils.ConvertFromInternalUnits(max(point_z), DisplayUnitType.DUT_MILLIMETERS) else: return 'no shape editor'
def cutElements(col, paramName, value): # Получение список плиток меньше значения value из paramName result = [] for i in col: para = i.LookupParameter(paramName) if para: param_value = round(UnitUtils.ConvertFromInternalUnits(para.AsDouble(), para.DisplayUnitType)) if param_value < value: result.append(i) return result
def Convert_From_Internal_Display_Length(length): """ convert length To Internal Units \n Converts a value from a given display unit to Revit's internal units. """ # retrieve unit display current in revit unit_format_options = doc.GetUnits().GetFormatOptions(UnitType.UT_Length) display_unit = unit_format_options.DisplayUnits return UnitUtils.ConvertFromInternalUnits (float(length), display_unit)
def set_parameter_by_name(value, param_name, document): f_manager = document.FamilyManager if len(list(f_manager.Types)) == 0: f_manager.NewType('Тип 1') param = f_manager.get_Parameter(param_name) if param: if param.CanAssignFormula: val = UnitUtils.ConvertFromInternalUnits(value, param.DisplayUnitType) f_manager.SetFormula(param, str(val)) return '{} - {}'.format(param_name, val) else: return 'Not OK'
def convert_internal_to_m(length): """Function to convert cm to feet.""" rvt_year = int(app.VersionNumber) # RVT >= 2022 if rvt_year < 2022: from Autodesk.Revit.DB import DisplayUnitType return UnitUtils.Convert(length, DisplayUnitType.DUT_DECIMAL_FEET, DisplayUnitType.DUT_METERS) # RVT >= 2022 else: from Autodesk.Revit.DB import UnitTypeId return UnitUtils.ConvertFromInternalUnits(length, UnitTypeId.Meters)
def renameLevel(levels, sign=True): count = 1 TransactionManager.Instance.EnsureInTransaction(doc) for ld in levels: elev_mm = UnitUtils.ConvertFromInternalUnits( ld.Elevation, DisplayUnitType.DUT_METERS) param = ld.get_Parameter(BuiltInParameter.DATUM_TEXT) if param: if sign: name_level = "L{}(+{:.3f})".format(count, elev_mm) else: name_level = "B{}({:.3f})".format(count, elev_mm) param.Set(name_level) count += 1 TransactionManager.Instance.TransactionTaskDone()
def get_square_from_runs_and_landings(stair): if stair.Category.Id.IntegerValue == -2000120: document = stair.Document runs_square = get_square_from_part(stair.GetStairsRuns(), document) landings_square = get_square_from_part(stair.GetStairsLandings(), document) if runs_square: set_value(stair, IN[1], runs_square) # noqa value_runs = UnitUtils.ConvertFromInternalUnits( runs_square, DisplayUnitType.DUT_SQUARE_METERS) else: set_value(stair, IN[1], 0) # noqa value_runs = 'нет маршей' if landings_square: set_value(stair, IN[2], landings_square) # noqa value_landings = UnitUtils.ConvertFromInternalUnits( landings_square, DisplayUnitType.DUT_SQUARE_METERS) else: set_value(stair, IN[2], 0) # noqa value_landings = 'нет площадок' return 'Площадь ступенек: {}'.format( value_runs), 'Площадь площадок: {}'.format(value_landings) else: return 'Select stair'
def GetBalisterCount(items, document): types = [] info = [] for item in items: param_length = item.get_Parameter(BuiltInParameter.CURVE_ELEM_LENGTH) railingType = document.GetElement(item.GetTypeId()) bp = railingType.BalusterPlacement.BalusterPattern cornerPost = railingType.BalusterPlacement.PostPattern cornerPost_el = doc.GetElement(cornerPost.CornerPost.BalusterFamilyId) info.append( UnitUtils.ConvertFromInternalUnits( bp.PatternAngle, DisplayUnitType.DUT_DEGREES_AND_MINUTES)) if bp.DistributionJustification == PatternJustification.Beginning or \ bp.DistributionJustification == PatternJustification.End: count = int(param_length.AsDouble() / bp.Length) elif bp.DistributionJustification == PatternJustification.Center: count = int(param_length.AsDouble() / bp.Length) + 2 elif bp.DistributionJustification == PatternJustification.SpreadPatternToFit: count = int(param_length.AsDouble() / bp.Length) - 2 if cornerPost_el: count += 1 types.append(count) return types, info
def import_config_length(length): return str(UnitUtils.ConvertFromInternalUnits(float(length), display_unit))
from RevitServices.Transactions import TransactionManager doc = DocumentManager.Instance.CurrentDBDocument el_fam = FilteredElementCollector(doc).OfClass(Family).ToElements() el_inst = FilteredElementCollector(doc).OfClass(FamilyInstance).ToElements() schemaGuid = System.Guid('3cd61681-a611-4a2f-b49c-ea8f0030807b') sch = Schema.Lookup(schemaGuid) fam_name = [f.Name for f in el_fam if f.GetEntity(sch).SchemaGUID == schemaGuid] el = [] param_offset_guid = System.Guid('e4793a44-6050-45b3-843e-cfb49d9191c5') param_guid = System.Guid('6ec2f9e9-3d50-4d75-a453-26ef4e6d1625') TransactionManager.Instance.EnsureInTransaction(doc) for e in el_inst: if e.Symbol.Family.Name in fam_name and e.get_Parameter(param_offset_guid): lev = UnitUtils.ConvertFromInternalUnits(e.Location.Point.Z, DisplayUnitType.DUT_MILLIMETERS) param = e.get_Parameter(param_offset_guid) param_value = UnitUtils.ConvertFromInternalUnits(param.AsDouble(), param.DisplayUnitType) if e.get_Parameter(param_guid): param_set = e.get_Parameter(param_guid) value = UnitUtils.ConvertToInternalUnits(lev + param_value, param_set.DisplayUnitType) param_set.Set(value) el.append(e) TransactionManager.Instance.TransactionTaskDone() OUT = el
lnkdoc = linkdoc[0] transform = rvtlinks[0].GetTotalTransform() rooms = FilteredElementCollector(lnkdoc).OfCategory( BuiltInCategory.OST_Rooms).ToElements() fam_col = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Furniture). \ WhereElementIsNotElementType().ToElements() mlist = [] for room in rooms: llist = [] room_box = room.get_BoundingBox(None) boxMin = transform.OfPoint(room_box.Min) boxMax = transform.OfPoint(room_box.Max) outline = Outline(boxMin, boxMax) bbfilter = BoundingBoxIntersectsFilter(outline) fam_ins = FilteredElementCollector(doc).OfCategory( BuiltInCategory.OST_Furniture).WherePasses(bbfilter).ToElements() llist.append(fam_ins) param = room.get_Parameter(BuiltInParameter.ROOM_AREA).AsDouble() llist.append( UnitUtils.ConvertFromInternalUnits(param, DisplayUnitType.DUT_SQUARE_METERS)) mlist.append(llist) flist = [] for f in fam_col: flist.append(lnkdoc.GetRoomAtPoint(f.Location.Point)) OUT = flist, fam_col
# Revit and Dynamo module from Autodesk.Revit.DB import Material, DisplayUnitType, UnitUtils from RevitServices.Persistence import DocumentManager doc = DocumentManager.Instance.CurrentDBDocument # argument assigned the IN port elements = list(UnwrapElement(IN[0])) # wrap input inside a list (if not a list) if not isinstance(elements, list): elements = [elements] # core data processing unit = DisplayUnitType.DUT_KILOGRAMS_PER_CUBIC_METER structural_asset, thermal_asset, element = [], [], [] for elem in elements: try: t1 = doc.GetElement( elem.StructuralAssetId).GetStructuralAsset().Density structural_asset.append(UnitUtils.ConvertFromInternalUnits(t1, unit)) t2 = doc.GetElement(elem.ThermalAssetId).GetThermalAsset().Density thermal_asset.append(UnitUtils.ConvertFromInternalUnits(t2, unit)) element.append(elem) except BaseException: pass # return assigned the OUT port OUT = structural_asset, thermal_asset, element
from RevitServices.Persistence import DocumentManager from RevitServices.Transactions import TransactionManager doc = DocumentManager.Instance.CurrentDBDocument # argument assigned the IN port elements = list(UnwrapElement(IN[0])) load_value = IN[1] load_type = list(UnwrapElement(IN[2])) # wrap input inside a list (if not a list) if not isinstance(load_value, list): load_value = [load_value] # output unit dut = DisplayUnitType.DUT_METERS # core data processing loads = [] TransactionManager.Instance.EnsureInTransaction(doc) for ids, (element, outer) in enumerate(zip(elements, load_value)): for inner in outer: Zaxis = UnitUtils.ConvertFromInternalUnits(inner, dut) areaload = AreaLoad.Create(doc, element, XYZ(0, 0, Zaxis), load_type[0]) loads.append(areaload) TransactionManager.Instance.ForceCloseTransaction() # return assigned the OUT port OUT = loads
import clr clr.AddReference("RevitAPI") from Autodesk.Revit.DB import FilteredElementCollector, UnitUtils from Autodesk.Revit.DB.Plumbing import PipingSystem clr.AddReference("RevitServices") from RevitServices.Persistence import DocumentManager doc = DocumentManager.Instance.CurrentDBDocument sys = FilteredElementCollector(doc).OfClass(PipingSystem) paramValue = [] for s in sys: sysType = doc.GetElement(s.GetTypeId()) param = sysType.LookupParameter('Температура вещества') if param: value = param.AsDouble() paramValue.append(round(UnitUtils.ConvertFromInternalUnits(value, param.DisplayUnitType))) OUT = paramValue
import clr clr.AddReference("RevitAPI") from Autodesk.Revit.DB import FilteredElementCollector, UnitUtils, DisplayUnitType, BuiltInCategory clr.AddReference("RevitServices") from RevitServices.Persistence import DocumentManager doc = DocumentManager.Instance.CurrentDBDocument def filterBasePoint(items): for i in items: return i el = FilteredElementCollector(doc).OfCategory( BuiltInCategory.OST_SharedBasePoint).ToElements() bp = filterBasePoint(el) x = UnitUtils.ConvertFromInternalUnits(bp.Position.X, DisplayUnitType.DUT_MILLIMETERS) y = UnitUtils.ConvertFromInternalUnits(bp.Position.Y, DisplayUnitType.DUT_MILLIMETERS) OUT = x, y, bp
def meter(double): return UnitUtils.ConvertFromInternalUnits(double, DisplayUnitType.DUT_METERS)
def Convert_length(length): Int_Length = (UnitUtils.ConvertFromInternalUnits(float(length), display_unit)) return int(round(Int_Length))
def __write_to_excel(self, params_to_write): """ Writing parameters to an Excel workbook (private method) """ units = { UnitType.UT_Length: DisplayUnitType.DUT_METERS, UnitType.UT_Area: DisplayUnitType.DUT_SQUARE_METERS, UnitType.UT_Volume: DisplayUnitType.DUT_CUBIC_METERS, UnitType.UT_Number: DisplayUnitType.DUT_PERCENTAGE, UnitType.UT_HVAC_Heating_Load: DisplayUnitType.DUT_KILOWATTS, UnitType.UT_HVAC_Cooling_Load: DisplayUnitType.DUT_KILOWATTS, UnitType.UT_HVAC_Airflow_Density: DisplayUnitType.DUT_CUBIC_FEET_PER_MINUTE_SQUARE_FOOT, UnitType.UT_HVAC_Airflow: DisplayUnitType.DUT_CUBIC_METERS_PER_HOUR } columns = list(string.ascii_uppercase) + [ "".join(i) for i in product(string.ascii_uppercase, repeat=2) ] params = dict(izip(params_to_write, columns)) try: workBook = self.excel.Workbooks.Open(r'{}'.format( self._xl_file_path)) workSheet = workBook.Worksheets(1) except Exception as e: logger.error(e, exc_info=True) pass for par, col in params.items(): workSheet.Cells[1, col] = par row = 2 MEPSpaces = self.merge_two_dicts(self.New_MEPSpaces, self.Exist_MEPSpaces) for space_id, space in MEPSpaces.items(): try: workSheet.Cells[row, "A"] = space_id for par in space.Parameters: par_name = par.Definition.Name if par_name in params.keys(): if par.StorageType == StorageType.String: workSheet.Cells[row, params[par_name]] = par.AsString() elif par.StorageType == StorageType.Integer: workSheet.Cells[ row, params[par_name]] = par.AsInteger() else: conv_val = UnitUtils.ConvertFromInternalUnits( par.AsDouble(), units.get(par.Definition.UnitType, DisplayUnitType.DUT_GENERAL)) workSheet.Cells[row, params[par_name]] = conv_val self.counter += 1 self.ReportProgress.emit(self.counter) row += 1 except Exception as e: logger.error(e, exc_info=True) pass # makes the Excel application visible to the user self.excel.Visible = True
doc = DocumentManager.Instance.CurrentDBDocument el = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_GenericModel) \ .WhereElementIsNotElementType().ToElements() el_filter = [] point_z = [] TransactionManager.Instance.EnsureInTransaction(doc) for i in el: param_group_model = i.Symbol.LookupParameter('Группа модели') param_otmetka = i.LookupParameter(IN[1]) # noqa if param_group_model: if param_group_model.AsString() == IN[0]: # noqa el_filter.append(i) pointXYZ = i.Location.Point point_z.append( round( UnitUtils.ConvertFromInternalUnits( pointXYZ.Z, DisplayUnitType.DUT_MILLIMETERS))) else: OUT = "Нет совпадающих критериев" if param_otmetka: for p in point_z: param_otmetka.Set( UnitUtils.ConvertToInternalUnits( p, param_otmetka.DisplayUnitType)) else: OUT = 'Нет такого параметра для записи значения' TransactionManager.Instance.TransactionTaskDone()
def Convert_toMM(value): return UnitUtils.ConvertFromInternalUnits(value, DisplayUnitType.DUT_MILLIMETERS)
full_wall_square = room_height * perimenter elements_in_room = get_segments_length(room_segments)[0] inserts = get_inserts_in_room(elements_in_room, room) inserts_square = 0 for ins in inserts: inserts_square += get_square(ins) if get_square(ins) == 0: report = 0 total_square = full_wall_square - inserts_square value = total_square * report set_value_by_param_name(room, param_name, value) # noqa return value room_col = FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Rooms).ToElements() TransactionManager.Instance.EnsureInTransaction(doc) report = [] report.append('{:>5}{:-^25}{:^5}'.format('Номер'.upper(), 'Имя помещения'.upper(), 'Площадь'.upper())) for room in room_col: name = room.get_Parameter(BuiltInParameter.ROOM_NAME).AsString() number = room.Number total = UnitUtils.ConvertFromInternalUnits(get_full_square_wall_from_room(room,IN[1]), # noqa DisplayUnitType.DUT_SQUARE_METERS) report.append('{:>5}{:-^25}{:.2f}'.format(number, name, total)) TransactionManager.Instance.TransactionTaskDone() OUT = report
def valueParameter(param, paramName): para = param.LookupParameter(paramName) return round(UnitUtils.ConvertFromInternalUnits(para.AsDouble(), para.DisplayUnitType))
sel = IN[1] # noqa if isinstance(sel, list): painted_face = [] for s in sel: pf = RemovePaintFromElement(s) if pf: painted_face.append(pf) all_faces = [] for items in painted_face: for item in items: all_faces.append(item) list_elems = group_by_key(all_faces, lambda e: e.MaterialElementId)[0] faces_area = [] for items in list_elems: fa = [] for item in items: fa.append( UnitUtils.ConvertFromInternalUnits( item.Area, DisplayUnitType.DUT_SQUARE_METERS)) faces_area.append(fa) list_name = group_by_key( all_faces, lambda e: doc.GetElement(e.MaterialElementId).Name)[1] OUT = faces_area, list_name else: OUT = RemovePaintFromElement(sel)
def ConvertFromInteralUnitToMM(Parameter): Parameter = UnitUtils.ConvertFromInternalUnits( float(Parameter), DisplayUnitType.DUT_MILLIMETERS) return Parameter
import clr clr.AddReference("RevitAPI") from Autodesk.Revit.DB import UnitUtils, DisplayUnitType, Transaction clr.AddReference('RevitAPIUI') from Autodesk.Revit.UI.Selection import ObjectType, Selection clr.AddReference("RevitServices") from RevitServices.Persistence import DocumentManager doc = DocumentManager.Instance.CurrentDBDocument uidoc = DocumentManager.Instance.CurrentUIDocument uiapp = DocumentManager.Instance.CurrentUIApplication app = uiapp.Application t = Transaction(doc, 'Получаение бокса') t.Start() el_p = uidoc.Selection.PickObject(ObjectType.Element, 'Выбрать элемент') el = doc.GetElement(el_p) e = el.get_BoundingBox(doc.ActiveView) e_min = e.Min.X e_max = e.Max.X dis = UnitUtils.ConvertFromInternalUnits(e_max - e_min, DisplayUnitType.DUT_MILLIMETERS) t.Commit() OUT = el, dis
scale = v.Scale elems = FilteredElementCollector(doc, v.Id).OfClass(CurveElement) for e in elems: graphics_style_cat = e.LineStyle.GraphicsStyleCategory id_cat = graphics_style_cat.Id if BuiltInCategory(id_cat.IntegerValue) == BuiltInCategory.OST_ProfileFamilies: cat = graphics_style_cat line_length += e.GeometryCurve.Length gs = cat.GetGraphicsStyle(GraphicsStyleType.Projection) gsCat = gs.GraphicsStyleCategory gsCat.LineColor = Color(IN[1].Red, IN[1].Green, IN[1].Blue) # noqa v.Scale = 1 v.Scale = scale line_length = UnitUtils.ConvertFromInternalUnits(line_length, DisplayUnitType.DUT_MILLIMETERS) f_manager = doc.FamilyManager param_name = "_Профиль.Длина" length_param = f_manager.get_Parameter(param_name) if len(list(f_manager.Types)) == 0: f_manager.NewType('Тип 1') if length_param: if length_param.CanAssignFormula: f_manager.SetFormula(length_param, str(line_length)) OUT = "Длина профиля {}".format(round(line_length)) else: fparameter = f_manager.AddParameter( param_name, BuiltInParameterGroup.PG_DATA, ParameterType.Length, False)
def jt_FromIntUnits(lengthValue): return UnitUtils.ConvertFromInternalUnits( lengthValue, Document.GetUnits(doc).GetFormatOptions( UnitType.UT_Length).DisplayUnits)