Quantcast
Channel: All Revit API Forum posts
Viewing all 67020 articles
Browse latest View live

Re: Revit 2025 - Macro Manager and Visual Studio 2022


Re: Problem using Python script in Dynamo to change multiple family files

$
0
0

Dear Chris,

  

Welcome to the Revit API and congratulations on getting all your bits and pieces to work individually.

  

Your script looks fine to me.

  

However, unfortunately, it is hard for me to say anything about why it might not work, since I am not conversant in Python or Dynamo. This forum is dedicated to the pure .NET Revit API. Dynamo provides a wrapper around that. To discuss Dynamo-specific questions, you will probably be better of raising this in the Dynamo forum:

  

   

Constraint Error When Placing Couplers Between Rebars in Revit API

$
0
0

"I'm encountering a constraint error while using the Revit API to join rebars with couplers. I have three rebars of the same diameter, and they are lapped. I can successfully place a coupler between the first two rebars, but when trying to place a coupler between the second and third, I receive a constraint error.

The first two rebars are hosted by different elements, while the second and third share the same host. I’ve attempted to change the host to resolve the issue, but it hasn't worked. Could you please help me understand why this error occurs and how to fix it? I’ve attached a document and video for further details."

https://forums.autodesk.com/t5/revit-structure-forum/quot-constraint-error-when-placing-couplers-between-rebars-in/td-p/13083374 

We tried out with manual approach there we have to align the rebar twice as explained in above but still programmatically we are not able to do it .

Re: 4K DPI scaling for winforms support 2019

Re: Constraint Error When Placing Couplers Between Rebars in Revit API

$
0
0

In the answers to your post in the structural forum, some contributors point out that they need to add constraints, possibly several times over. Have you checked whether these constraints are observable in the Revit database, e.g., by checking the state before and after with RevitLookup or some other database exploration tool?

   

Re: How to execute BooleanOperations on Revit-Solid by AutoCAD?

$
0
0

UPD: 16.10.2024

Atthemoment, I have managedto union 100% of 1717solids(screenshotbelow)

ankofl_1-1729088387265.png
byuploadingtooff-filesandunion themusingCGAL.Theresultis an outputoff-file(it is in thescreenshotbelow)

ankofl_0-1729088225131.png
P.S: When trying to combine the Solids data through Revit, several dozens exceptions occurred about the inability to perform a Boolean operation on solid.

IcheckedinCGALthat the resultingmeshiscorrect,i.e. it does nothave self-intersections,limits the positivevolume, is correctlyoriented,andisalsoatriangular,not a polygonal mesh.

ThenIdecided to create a Solidbased on the offfileusing the followingmethods:

 

public static bool ReadOFF(string offFilePath, out List<XYZ> vertices, out List<int[]> triangles) { // 1. Чтение файла OFF vertices = []; triangles = []; if (!File.Exists(offFilePath)) { return false; } double k = UnitUtils.ConvertToInternalUnits(1, UnitTypeId.Meters); var strs = File.ReadAllLines(offFilePath); // Чтение количества вершин и треугольников string[] counts = strs[1].Split(); int vertexCount = int.Parse(counts[0]); int faceCount = int.Parse(counts[1]); // Чтение координат вершин for (int i = 3; i < 3 + vertexCount; i++) { string[] vertexData = strs[i].Split(' '); double x = double.Parse(vertexData[0]) * k; double y = double.Parse(vertexData[1]) * k; double z = double.Parse(vertexData[2]) * k; vertices.Add(new XYZ(x, y, z)); } // Чтение треугольников (граней) for (int i = 3 + vertexCount; i < 3 + vertexCount + faceCount; i++) { string[] faceData = strs[i].Split(" ")[1].Split(' '); if (faceData.Length == 3) // Треугольная грань { int v1 = int.Parse(faceData[0]); int v2 = int.Parse(faceData[1]); int v3 = int.Parse(faceData[2]); triangles.Add([v1, v3, v2]); } } return vertices.Count >= 3; }

 

And:

 

public static bool SolidFromMesh(List<XYZ> vertices, List<int[]> triangles, out Solid solid) { solid = null; try { // 2. Инициализация BRepBuilder для создания замкнутого объёма BRepBuilder brepBuilder = new(BRepType.OpenShell); brepBuilder.SetAllowShortEdges(); brepBuilder.AllowRemovalOfProblematicFaces(); // 3. Проход по треугольникам и создание граней foreach (int[] triangle in triangles) { XYZ v1 = vertices[triangle[0]]; XYZ v2 = vertices[triangle[1]]; XYZ v3 = vertices[triangle[2]]; if (v1.DistanceTo(v2) < 0.5 || v2.DistanceTo(v3) < 0.5 || v3.DistanceTo(v1) < 0.5) { continue; // Пропустить такие треугольники } // Создание плоскости для треугольной грани Plane trianglePlane = Plane.CreateByThreePoints(v1, v2, v3); // Добавление грани в BRepBuilder BRepBuilderGeometryId faceId = brepBuilder.AddFace( BRepBuilderSurfaceGeometry.Create(trianglePlane, null), false); // Создание рёбер треугольника BRepBuilderEdgeGeometry edge1 = BRepBuilderEdgeGeometry.Create(v1, v2); BRepBuilderEdgeGeometry edge2 = BRepBuilderEdgeGeometry.Create(v2, v3); BRepBuilderEdgeGeometry edge3 = BRepBuilderEdgeGeometry.Create(v3, v1); // Добавление рёбер в BRepBuilder BRepBuilderGeometryId edgeId1 = brepBuilder.AddEdge(edge1); BRepBuilderGeometryId edgeId2 = brepBuilder.AddEdge(edge2); BRepBuilderGeometryId edgeId3 = brepBuilder.AddEdge(edge3); if (!brepBuilder.IsValidEdgeId(edgeId1) || !brepBuilder.IsValidEdgeId(edgeId2) || !brepBuilder.IsValidEdgeId(edgeId3)) { } // Создание цикла для грани BRepBuilderGeometryId loopId = brepBuilder.AddLoop(faceId); var coEdgeId1 = brepBuilder.AddCoEdge(loopId, edgeId1, false); var coEdgeId2 = brepBuilder.AddCoEdge(loopId, edgeId2, false); var coEdgeId3 = brepBuilder.AddCoEdge(loopId, edgeId3, false); if (!brepBuilder.IsValidEdgeId(coEdgeId1) || !brepBuilder.IsValidEdgeId(coEdgeId2) || !brepBuilder.IsValidEdgeId(coEdgeId3)) { } if (!brepBuilder.IsValidLoopId(loopId)) { } if (!brepBuilder.IsValidFaceId(faceId)) { } brepBuilder.FinishLoop(loopId); brepBuilder.FinishFace(faceId); } // 4. Завершение создания BRep brepBuilder.Finish(); if (brepBuilder.IsResultAvailable()) { solid = brepBuilder.GetResult(); return true; } } catch (Exception e) { TaskDialog.Show("SolidHelper.SolidFromMesh()", e.Message); } return false; }

 

But I came acrossthefactthatwithanycombinationsandvariants of the

 

public static bool SolidFromMesh(List<XYZ> vertices, List<int[]> triangles, out Solid solid)

 

methodwhencheckingin

 

brepBuilder.IsResultAvailable()

 

at the end will be trueonlyin the caseof

 

BRepBuilder brepBuilder = new(BRepType.OpenShell)

 

In the case of

 

BRepBuilder brepBuilder = new(BRepType.Solid)brepBuilder.IsResultAvailable()

 

 -alwaysreturnsfalse
I decided that the data was too complex for Revit, and then I created an off-file containing a regular cube:

 

OFF 8 12 0 -50 -50 -50 50 -50 -50 50 50 -50 -50 50 -50 -50 -50 50 50 -50 50 50 50 50 -50 50 50 3 2 1 0 3 3 2 0 3 4 5 6 3 4 6 7 3 0 4 7 3 0 7 3 3 6 5 1 3 2 6 1 3 0 1 5 3 0 5 4 3 6 2 3 3 7 6 3

 

In this case, I received the correct filled Solid (despite the instruction to create OpenShell).

ankofl_3-1729091017864.png

Based on this, I believe that the main problem lies in the verification:

 

if (v1.DistanceTo(v2) < 0.5 || v2.DistanceTo(v3) < 0.5 || v3.DistanceTo(v1) < 0.5) { continue; // Пропустить такие треугольники }

 

With such a check, of course, instead of Solid, we will get an Open Shell, as can be seen in the screenshot below:

ankofl_2-1729090969172.png
If you make a check of at least0.1

 

if (v1.DistanceTo(v2) < 0.1 || v2.DistanceTo(v3) < 0.1 || v3.DistanceTo(v1) < 0.1) { continue; // Пропустить такие треугольники }

 

 

 

brepBuilder.IsResultAvailable()

 

 

 -alwaysreturnsfalse


Dear @jeremy_tammik can I ask you or someone from the development team to clarify in more detail what the introductory conditions are for the grid source data? Minimum edge lengths, minimum face area, etc? Because at the moment it seems to me that such an accurate geometry in Revit simply cannot be built from such constraints.

Thanks!

Changing the copied element

$
0
0

hi,mytask is to create a legend by copyinganother one anddeletingall the objects from there (since there are noways to create a legendin the revitapiyet).
Ialsoneed to findall the windowsin the legend;then,Ineed to copyanyelement of anylegend;pasteitinto the newlycreatedlegend;changeitstypeso that thiselementbecomes a windowfrom the list;andchangeitsothatitappears in front of us with a frontview.Andso you need to repeat as manytimesas there are windowsin the list. The resultshouldbe a newlegendwithall the windowsfrom the documentrepresented by the frontview.
Unfortunately,I'm stuckhalfwaythrough.Icopied the foundelementinto a newlegendand do notknowhowtochange it,I have been doing this for literallyseveralweeksnowand have not made anyprogress.I am asking for yourhelpinthisseeminglyeasytask.I will attachmycodebelow, I will begrateful for anyhintandhelp,thank you in advance.I am notanativeEnglishspeaker, so I canmakevarioustypes of mistakes,forwhich I apologize.

Re: Changing the copied element

$
0
0

Have you verified you can do this manually? I was not aware you could show modeled elements in a Legend, but then i don't use Legends very often. Second, is it a code failure, or is it just not changing the element type?


Re: Changing the copied element

$
0
0

Hi @will_smith3691215,

 

As the specific parameters (attached to elements) used to do internal Revits "Stuff" isn't well documented use RevitLookup to inspect the elements and which parameters it that that (might) does what you need.

 

Looking into a LegendComponent, it's not a specific class, so no direct properties on the Class to use. (see: https://www.revitapidocs.com )

So inspecting a placed LegendComponent reveals the following builtin parameters:

BuiltinParameter.LEGEND_COMPONENT, which is of the ElementId datatype and takes the Id of a Type (wall type etc..) to determine which family type to show

 

BuiltinParameter.LEGEND_COMPONENT_VIEW, seems to be the one to determine the viewdirection, it's a integer type so change some Legendcomponents and see which value belongs to which direction (seems -5 = Section)

 

BuiltinParameter.LEGEND_COMPONENT_LENGTH, looks like this one controls the length of the component and is a double (length type).

 

- Michel

 

 

Re: 4K DPI scaling for winforms support 2019

$
0
0

Without reading Jeremy's article (because i'm feeling rather lazy) rather than a programmatic solution, have you tried messing with the Compatibility settings within your Revit icon?

ctm_mka_0-1729105809205.png

 

Re: RevitID to Sheet

$
0
0

There is no direct correlation between element in a view and the sheet element. Rather you need to grab all sheets, filtering as necessary, grab all placed views, make each view active, then grab all elements in the view. Heres some Pseudo code to maybe help:

foreach(sheet in sheetcollection) list of viewsOnSheet = sheet.GetAllPlacedViews() foreach (view in viewsOnSheet) uidoc.activeview = view listOfElementIds = new filteredelementcollector(doc, view).wherelementisnotelementype().toelementids() //very generic element collector to grab just elements

'

Py Revit Json checkmark

$
0
0

I am creating a pop up where a user can save category, instance parameter, and type parameter. I save the selections with the values in a json. I then prompt the user to name their selection so that next time they can see what they saved and load it in if they like. The issue is that when a user selects the previous saved selections it does not check mark off the selections made, even though it reads in the json. The following is my code and I believe the issue is from function select_manual_check: 

# Function to load selection from JSON
def load_selection_from_json(selection_name)

 

    json_path = os.path.join(parameter_sets_dir"{}.json".format(selection_name))
    with open(json_path"r"as json_file:
        return json.load(json_file)

 

# Function to save selection to JSON
def save_selection_to_json(selection_namecategoriesinstance_parameterstype_parameters)

 

    json_path = os.path.join(parameter_sets_dir"{}.json".format(selection_name))
    with open(json_path"w"as json_file:
        json.dump({
            "categories"categories,
            "instance_parameters"instance_parameters,
            "type_parameters"type_parameters
        }, json_file)

 

# Function to collect model categories
def get_model_categories():
    return [cat.Name for cat in doc.Settings.Categories if cat.CategoryType == CategoryType.Model]

 

# Function to collect elements from selected categories
def collect_elements(categories)

 

    elements = []
    for category_name in categories:
        category = next((cat for cat in doc.Settings.Categories if cat.Name == category_name), None)
        if category:
            bic = System.Enum.Parse(BuiltInCategory, category.Id.IntegerValue.ToString())
            elements.extend(FilteredElementCollector(doc).OfCategory(bic).WhereElementIsNotElementType().ToElements())
    return elements

 

# Function to display selection dialog with manual check mark processing
def select_with_manual_check(optionschecked_optionstitle)

 

    options_with_checks = [(optopt in checked_optionsfor opt in sorted(options)]
    checked = forms.SelectFromList.show(
        [opt[0for opt in options_with_checks],
        #checked_options,
        title=title,
        multiselect=True,
        button_name="Select"
    )
    #checked = forms.BaseCheckBoxItem(checked_options)
    return checked

 

# Main function to run the selection
def main():
    # List saved selection sets
    saved_selections = [f.replace(".json"""for f in os.listdir(parameter_sets_dirif f.endswith(".json")]
   
    if saved_selections:
        selection_names = saved_selections + ["Create New Selection"]
        selected_name = forms.SelectFromList.show(
            sorted(selection_names),
            title="Select a Saved Selection or Create New",
            multiselect=False,
            button_name="Select"
        )
    else:
        forms.alert("No saved selections found. Creating a new selection..."exitscript=False)
        selected_name = "Create New Selection"

 

    # Initialize empty lists for selection if creating a new one
    model_categories_selected = []
    instance_parameter_to_select = []
    type_parameter_to_select = []

 

    # Load existing selection set if one is chosen
    if selected_name != "Create New Selection":
        loaded_selection = load_selection_from_json(selected_name)
        model_categories_selected = loaded_selection.get("categories", [])
        instance_parameter_to_select = loaded_selection.get("instance_parameters", [])
        type_parameter_to_select = loaded_selection.get("type_parameters", [])

 

    # Model Category Selection
    model_category_names = get_model_categories()
    selected_categories = select_with_manual_check(model_category_namesmodel_categories_selected"Select Model Categories")
   
    # Collect elements from the selected categories
    elements = collect_elements(selected_categories)

 

    # Instance Parameter Selection with Manual Check
    unique_instance_parameter_names = {p.Definition.Name for e in elements for p in e.Parameters}
    selected_instance_parameters = select_with_manual_check(unique_instance_parameter_namesinstance_parameter_to_select"Select Instance Parameters")

 

    # Type Parameter Selection with Manual Check
    unique_type_parameter_names = set()
    for element in elements:
        element_type = doc.GetElement(element.GetTypeId())
        if element_type:
            unique_type_parameter_names.update(p.Definition.Name for p in element_type.Parameters)
   
    selected_type_parameters = select_with_manual_check(unique_type_parameter_namestype_parameter_to_select"Select Type Parameters")

 

    # Save the selection if needed
    selection_name = forms.ask_for_string(prompt="Enter a name for this selection:"title="Save Selection")
    if selection_name:
        save_selection_to_json(selection_nameselected_categoriesselected_instance_parametersselected_type_parameters)

 

# Run main
main()

Revit 2025 and Visual Studio Code DocumentOpened event

$
0
0

I'm very green with C# and am testing some code but am encountering an error when building the solution, I have a variant of this code running under Revit 2022.
The error I'm getting is
C:\ProgramData\Autodesk\Revit\Macros\2025\Revit\AppHookup\Project_FilePath\Source\Project_FilePath\
ThisApplication.cs(36,5): error CS0127: Since 'ThisApplication.DocumentOpenedHandler(object?, Docum
entOpenedEventArgs)' returns void, a return keyword must not be followed by an object expression [C
:\ProgramData\Autodesk\Revit\Macros\2025\Revit\AppHookup\Project_FilePath\Source\Project_FilePath\P
roject_FilePath.csproj]

using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.DB.Events; using Autodesk.Revit.UI.Selection; namespace Project_FilePath { [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)] [Autodesk.Revit.DB.Macros.AddInId("2F4ED035-9D44-4043-B837-7844A9AA861E")] public partial class ThisApplication { private void Module_Startup(object? sender, EventArgs e) { // Subscribe to the DocumentOpened event Application.DocumentOpened += new EventHandler<DocumentOpenedEventArgs>(DocumentOpenedHandler); } private void Module_Shutdown(object? sender, EventArgs e) { // Unsubscribe to the DocumentOpened event Application.DocumentOpened -= new EventHandler<DocumentOpenedEventArgs>(DocumentOpenedHandler); } public void DocumentOpenedHandler(object? sender, DocumentOpenedEventArgs e) { if (e.Status == RevitAPIEventStatus.Succeeded) { try{ // Display a message box when a document is opened TaskDialog.Show("Test Macro","Revit File Opened"); } catch (Exception) { TaskDialog.Show("Error","There was a problem opening the document"); return Result.Succeeded; } } } } }

Seeking Advice

$
0
0

Problem statement:

We have developed a plugin for dimensioning and tagging. Please see the queries below.

1) We are having difficulty identifying the nearest elements based on their category.

2) In tagging, we need to obtain the extents of the tag text.

3) We need to identify any overlapping tags. Is there a solution to this?

4) In tagging, is it possible to have the tag leader or leader as a curve?

5) Is it possible to identify the connected elements of structural framing?

6) We are unable to obtain the center reference of the shaft opening. Is there a solution for this?

 

Autodesk Revit : 2022 version.

Re: Py Revit Json checkmark

$
0
0

So, your question has nothing to do with the Revit API, does it? Maybe it would be better to raise this in a forum discussing Python, or the UI functionality that you are using?

  

Also, I do not see any function in your code named select_manual_check...

  


Re: Revit 2025 and Visual Studio Code DocumentOpened event

$
0
0

Hi @Eduardo.SaezDRTV4 ,

 

It looks like the error you're seeing is due to a return statement in a method that is declared to return void.

public void DocumentOpenedHandler(object? sender, DocumentOpenedEventArgs e) { if (e.Status == RevitAPIEventStatus.Succeeded) { try { // Display a message box when a document is opened TaskDialog.Show("Test Macro", "Revit File Opened"); } catch (Exception) { TaskDialog.Show("Error", "There was a problem opening the document"); // No return is needed since the method is void } } }

Re: Revit 2025 and Visual Studio Code DocumentOpened event

$
0
0

Welcome to C# and the Revit API.

     

Actually, the error message says exactly what the problem is. If I pare it down and reformulate it a bit, it says, "your method DocumentOpenedHandler is a void function, so the return keyword must not be followed by an object expression". In other words, you cannot write return Result.Succeeded;; you have to leave out the Result.Succeeded and write just return;

  

However, I would also suggest that if you are running into issues like this, it might make sense to play around a bit more with just pure C# in tutorials or online courses before starting to address things in the Revit API, where you will be confronted and confused by the combination of Revit API quirks and C# issues.

  

This forum is (mostly) dedicated to discussing the Revit API, and not C# beginner issues.

  

Good luck and have fun!

   

Re: I would like to know the version of a rvt file before opening the file in revit

$
0
0

You can have simple solution by using  Revit Extractor : https://github.com/chuongmep/revit-extractor

Make sure you installed package and us right command :

from revit_extract import RevitExtractor rvt_path = r"D:\_WIP\Download\Sample Office Building Model V1.rvt" version = RevitExtractor.get_version(rvt_path) print(version)

 

Re: I would like to know the version of a rvt file before opening the file in revit

Re: Seeking Advice

$
0
0

Dear Timu, 

  

Congratulations for having already developed your add-in. Mos of the quesrtions you raise have been discussed here in the past, some of them quite often. I would suggest searching for existing answers one by one and adding to those threads if anything remains unclear. Here are some quick takes:

  

  1. Use a filtered element collector in combination with a category and a bounding box intersection filter.
  2. Discussed previously many times.
  3. Ditto.
  4. Can you achieve this manually in the UI? How? If not, the API will hardly add any functionality beyond the UI possibilities.
  5. Yes. Discussed previously.
  6. Yes, certainly. Well, the centre point, anyway. Does it necessarily have a reference?

     

Viewing all 67020 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>