Example #1
0
TESTED REVIT API: 2017

Author: Gui Talarico | github.com.gtalarico

This file is shared on www.revitapidocs.com
For more information visit http://github.com/gtalarico/revitapidocs
License: http://github.com/gtalarico/revitapidocs/blob/master/LICENSE.md
"""

import clr

clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')

from Autodesk.Revit import DB

uidoc = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document

pts = DB.FilteredElementCollector(doc).OfClass(
    DB.PointCloudInstance).WhereElementIsNotElementType().ToElements()
pt_cloud_settings = DB.PointClouds.PointCloudOverrideSettings()
pt_cloud_settings.ColorMode = DB.PointCloudColorMode.Normals
for pt in pts:
    view = uidoc.ActiveView
    pt_overrides = view.GetPointCloudOverrides()
    t = DB.Transaction(doc)
    t.Start('Set Pt Cloud Color Mode')
    pt_overrides.SetPointCloudOverrideSettings(pt.Id, pt_cloud_settings)
    t.Commit()
Example #2
0
def main():
    input_params = GUIgenerator('gaspipesize.xaml').ShowDialog()
    print("\nGUI INPUT DATA RECEIVED... ")
    target_elements = get_piping_system_type("GAS")
    target_elIds = []
    for element in target_elements:
        target_elIds.append(element.Id)

    selected_elIds = []
    selected_elements = [
        doc.GetElement(elId) for elId in uidoc.Selection.GetElementIds()
    ]

    for element in selected_elements:
        selected_elIds.append(element.Id)

    selected_pipes = set(target_elIds).intersection(selected_elIds)
    print("\nEvaluating  " + str(len(selected_pipes)) +
          "  Selected Gas Pipes...")
    changeCount = 0
    t = DB.Transaction(doc, "ChangePipeDiameters")

    t.Start()
    for pipeId in selected_pipes:
        pipe_params = collect_params(doc.GetElement(pipeId))
        pipe_section.elementId = pipeId
        pipe_section.pipeFlow = float(pipe_params['Flow'][2])
        pipe_section.diameterRead = round(float(pipe_params['Diameter'][2]),
                                          11)
        if inputData.pressureState:
            # High Pressure Pipe
            pipe_section.diameterCalc = size_HPPipe(float(pipe_section.pipeFlow), \
                                                float(inputData.sys_length), \
                                                int(inputData.inlet_press_sel[0]), \
                                                bool(inputData.natGas))
            print("Calculated Diameter:  " + str(pipe_section.diameterCalc) +
                  " in.")
        else:
            pipe_section.diameterCalc = size_LPPipe(float(pipe_section.pipeFlow), \
                                                float(inputData.sys_length), \
                                                float(inputData.press_drop_sel[:3]), \
                                                bool(inputData.natGas))
        pipe_section.diameterNew = round_PipeSize(pipe_section.diameterCalc)
        if pipe_section.diameterNew != None:
            if abs(pipe_section.diameterNew -
                   pipe_section.diameterRead) <= 0.0001:
                print("Pipe No. :  " + str(pipe_section.elementId) +
                      " did not need to be adjusted.")
            else:
                changeCount += 1
                if inputData.geometry == True:
                    # print("I made it this far!!")
                    parameters = doc.GetElement(
                        pipe_section.elementId).Parameters

                    for parameter in parameters:
                        if parameter.Definition.Name == "Diameter":
                            parameter.Set(float(pipe_section.diameterNew))
                        else:
                            continue
                print("Pipe No. : " + str(pipe_section.elementId) + \
                        " \n\t Was at : " + str(pipe_section.diameterRead * 12) + \
                        " \n\t Changed to : " + str(pipe_section.diameterNew * 12))
        else:
            continue
    t.Commit()

    print("Changed Size for " + str(changeCount) + " Elements!")
    if inputData.closeAfter:
        __window__.Close()
Example #3
0
collection = []

os.chdir('C:/Users/aberes/Desktop')
with open('sampleExcel.csv') as f:
	reader = csv.reader(f)
	for row in reader:
		collection.append(row)
		column_Num = len(row)



#Revit Schedule Creation__________________________________________________________________________________
doc = __revit__.ActiveUIDocument.Document
uidoc = __revit__.ActiveUIDocument

transaction = DB.Transaction(doc, 'import excel')
transaction.Start()

elemId = DB.ElementId(-1)
sched = DB.ViewSchedule.CreateSchedule(doc, elemId)
sched.Name = "TEST SCHEDULE"


definition = sched.Definition
definition.ShowHeaders = "false"

bodyData = sched.GetTableData().GetSectionData(DB.SectionType.Body)


headerData = sched.GetTableData().GetSectionData(DB.SectionType.Header)
Example #4
0
 def __init__(self, __doc=doc, name='', production=True):
     if not name:
         raise ValueError('Please provide a transaction name')
     self.transaction = DB.Transaction(__doc, name)
     self.production = production
Example #5
0
def main():
    """Main Script. """
    
    print("šŸ Running {fname} version {ver}...".format(fname=__name, ver=__version))

    # STEP 0: Setup
    doc = __revit__.ActiveUIDocument.Document
    view = doc.ActiveView

    # STEP 1: Get all available Pipe Tags in the project
    print("Getting all available pipe tags from the model...", end="")
    tag_types = db.FilteredElementCollector(doc)\
                  .OfCategory(db.BuiltInCategory.OST_PipeTags)\
                  .WhereElementIsElementType()\
                  .ToElements()
    print("āœ”")
    tags = {}  # tag_title: tag_type
    for tag_type in tag_types:
        tag_family_name = tag_type.get_Parameter(db.BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM).AsString()
        tag_type_name = tag_type.get_Parameter(db.BuiltInParameter.SYMBOL_NAME_PARAM).AsString()
        full_tag_name = "{f_name} - {t_name}".format(f_name=tag_family_name, t_name=tag_type_name)
        tags[full_tag_name] = tag_type

    # STEP 2: Check if setup tags actually exist in project
    print("Checking if expected tag family (and types) exist(s)... ", end="")
    all_tags_available = True
    for tag_name in TAG_TYPE_NAME_MAPPING.values():
        if not tag_name in tags:
            print("āœ˜ Error: {tag_name} not available!".format(tag_name=tag_name))
            all_tags_available = False
    if not all_tags_available:
        print("āœ˜ Error: Not all required tags are available in the project! See above.")
        return ui.Result.Failed
    print("āœ”")

    # STEP 3: Check if the current view a plan view
    print("šŸ›ˆ Current view is: '{v}' {t}".format(v=view.Name, t=type(view)))
    if type(view) is not db.ViewPlan:
        print("āœ˜ Error: Currently active view is not a plan view!")
        return ui.Result.Failed
            
    # STEP 4: Get all pipes in the view
    print("Getting all pipes from the currently active view... ", end="")
    pipes = db.FilteredElementCollector(doc, view.Id)\
                .OfCategory(db.BuiltInCategory.OST_PipeCurves)\
                .ToElements()
    print("āœ”")
    print("  āžœ Found {num} pipes in the currently active view.".format(num=len(pipes)))

    # STEP 5: Filter for vertical pipes
    print("Filtering vertical pipes... ", end="")
    vertical_pipes = [pipe for pipe in pipes if is_vertical(pipe)]
    print("āœ”")
    print("  āžœ Found {num} vertical pipes in the view.".format(num=len(vertical_pipes)))

    # STEP 6: Get the top and bottom view range elevations
    print("Finding views boundary elevations... ", end="")
    top, bottom = top_and_bottom_elevation(doc, view)
    print("āœ”")
    print("  āžœ Top boundary elevation is {0} ft (= {1} m)".format(top, top*FEET_TO_METER))
    print("  āžœ Bottom boundary elevation is {0} ft (= {1} m)".format(bottom, bottom*FEET_TO_METER))

    # STEP 7: Categorize pipes according to location and flow
    print("Categorizing vertical pipes... ", end="")
    categorized_pipes, _ = categorize_pipes(vertical_pipes, top, bottom)
    print("āœ”")
    for category, pipes in categorized_pipes.items():
        print("  āžœ Found {num} pipes in category '{cat}'".format(num=len(pipes), cat=category))

    # STEP 8: Place tags at the pipes TODO: avoid creating duplicate tags
    print("Creating tags... ", end="")
    transaction = db.Transaction(doc)
    transaction.Start("{name} - v{ver}".format(name=__name, ver=__version))
    try:
        for category, pipes in categorized_pipes.items():
            tag_type_id = tags[TAG_TYPE_NAME_MAPPING[category]].Id
            for pipe in pipes:
                point = pipe_location(pipe, top)
                new_tag = db.IndependentTag.Create(doc, view.Id, db.Reference(pipe), False, db.TagMode.TM_ADDBY_CATEGORY, db.TagOrientation.Horizontal, point)
                new_tag.ChangeTypeId(tag_type_id)
    except Exception as ex:
        print("\nāœ˜ Exception:\n {ex}".format(ex=ex))
        transaction.RollBack()
        return ui.Result.Failed
    else:
        transaction.Commit()
        print("āœ”\nDone. šŸ˜Š")
        return ui.Result.Succeeded
Example #6
0
def main():
    """Main Script."""

    print("Running {fname} version {ver}...".format(fname=__name,
                                                    ver=__version))

    # STEP 0: Setup
    app = __revit__.Application
    doc = __revit__.ActiveUIDocument.Document
    uidoc = __revit__.ActiveUIDocument
    view = doc.ActiveView

    # STEP 1: Get all links in the revit model
    links = {}
    for document in app.Documents:
        if document.IsLinked:
            links[document.Title] = document

    # STEP 2: Let user select the linked document to copy from
    print("Please select the link to copy rooms from...")
    select_form = LinkSelectionForm(links=links)
    result = select_form.ShowDialog()
    print(result)
    if result == swf.DialogResult.OK:
        selected_link_title = select_form.comboBoxLink.SelectedItem
        selected_link = links[selected_link_title]

        # STEP 3: Get all Rooms from the selected link
        rooms = db.FilteredElementCollector(selected_link)\
                .OfCategory(db.BuiltInCategory.OST_Rooms)\
                .ToElements()
        print("Found {0} rooms in the linked document".format(len(rooms)))

        # STEP 4: Get Levels from the current model:
        levels = db.FilteredElementCollector(doc)\
                .OfCategory(db.BuiltInCategory.OST_Levels)\
                .WhereElementIsNotElementType()\
                .ToElements()
        print("Found {0} levels in the model.".format(len(levels)))

        # STEP 5: Create spaces for all placed Rooms in the selected link
        print("Creating spaces for all placed rooms in the selected link...")
        transaction = db.Transaction(doc)
        transaction.Start("{name} - v{ver}".format(name=__name, ver=__version))
        try:
            created_spaces = []
            for room in rooms:
                space_level = find_closest_level(levels, room.Level.Elevation)
                if room.Location:  # room is actually placed
                    location_point = room.Location.Point
                    insert_point = db.UV(location_point.X, location_point.Y)
                    created_space = doc.Create.NewSpace(
                        space_level, insert_point)
                    created_spaces.append(created_space)
                    # Save unique ID of source room in space parameter "Comments"
                    comment_param = created_space.get_Parameter(
                        db.BuiltInParameter.ALL_MODEL_INSTANCE_COMMENTS)
                    comment_param.Set(room.UniqueId)
            print("Created {0} spaces.".format(len(created_spaces)))
        except Exception as ex:
            print("Exception: {0}".format(ex))
            transaction.RollBack()
        else:
            transaction.Commit()
            print("Done.")
    else:
        print("No link selected, nothing to do.")
if __shiftclick__:
    print("--- EXCEL-LEVEL-LIST -----------------------------------------")
    for i in ex_row: print(i)
    print("\n--- CREATED ------------------------------------------------")


import decimal
from decimal import Decimal 
decimal.getcontext().prec = 5

FECviewfamtype = DB.FilteredElementCollector(doc).OfClass(DB.ViewFamilyType)
floorplantype = [k for k in FECviewfamtype if k.FamilyName == "Floor Plan"][0]
ceilingplantype = [k for k in FECviewfamtype if k.FamilyName == "Ceiling Plan"][0]

t = DB.Transaction(doc, "Create Levels from Excel")
t.Start()

for i in ex_row:
    try:   
        elev = Decimal(i[1]).quantize(Decimal('0.01'),rounding="ROUND_HALF_UP")
        elev1 = elev / Decimal(0.3048)  
        #Create LEVEL  
        lev = DB.Level.Create(doc, elev1)  
        lev.Name = str(i[0])
        # Create FloorPlan, CeilingPlan
        if i[2]:
            floorplan = DB.ViewPlan.Create(doc, floorplantype.Id, lev.Id)
        if i[3]:
            ceilingplan = DB.ViewPlan.Create(doc, ceilingplantype.Id, lev.Id)
        if __shiftclick__:
def main():
    """Main Function."""

    print("Running {fname} version {ver}...".format(fname=__name,
                                                    ver=__version))

    # STEP 0: Setup
    doc = __revit__.ActiveUIDocument.Document
    view = doc.ActiveView

    # STEP 1: Ask user for clash report html file adn parse it
    print("Opening interference check report file...")
    open_dialog = swf.OpenFileDialog()
    open_dialog.Title = "Open Interference Check Report"
    open_dialog.Filter = "HMTL files (*.html)|*.html"
    if open_dialog.ShowDialog() == swf.DialogResult.OK:  # file selected
        file_path = open_dialog.FileName
        # STEP 2: Parse clash report file and summarize findings
        print("Reading {fname}...".format(fname=file_path))
        with open(file_path, mode="rb") as html_file:
            html = html_file.read()  # just read the plain bytes
            uhtml = unicode(
                html, "utf-16")  # Revit exports html in UTF-16(-LE) encoding
        print("Parsing file contents...")
        parser = InterferenceReportParser()
        parser.feed(uhtml)
        parser.close()
        clashes = parser.clashes
        clashing_ids = []
        for pair in parser.clashes.values():
            for elem_id in pair:
                clashing_ids.append(elem_id)
        clashing_ids = set(clashing_ids)
        # Get all element ids of the elements in the view
        all_ids = db.FilteredElementCollector(doc, view.Id)\
                    .WhereElementIsNotElementType()\
                    .ToElementIds()
        all_ids = set([elem_id.IntegerValue for elem_id in all_ids])
        # Get all element ids of non-clashing elements in the view
        non_clashing_ids = all_ids - clashing_ids
        # Create summary text for user input dialog
        summary_text = "Checked report {path}\n".format(path=file_path)
        summary_text += "Found {num} clashes in the report.\n".format(
            num=len(clashes))
        summary_text += "Found {num} clashing elements involved in those clashes.\n".format(
            num=len(clashing_ids))
        summary_text += "The total number of elements in the current view is {num}\n".format(
            num=len(all_ids))
        summary_text += "Found {num} non-clashing elements in the current view.".format(
            num=len(non_clashing_ids))
        print(summary_text)

        # STEP 3: Ask user for display option
        dialog = ui.TaskDialog(title="Mark All Clashes")
        dialog.MainInstruction = "Interference Report Summary"
        dialog.MainContent = summary_text
        dialog.AddCommandLink(ui.TaskDialogCommandLinkId.CommandLink1,
                              "Mark clashing elements and fade the rest")
        dialog.AddCommandLink(ui.TaskDialogCommandLinkId.CommandLink2,
                              "Hide all non-clashing elements temporarily")
        dialog.CommonButtons = ui.TaskDialogCommonButtons.Close
        dialog.DefaultButton = ui.TaskDialogResult.Close
        result = dialog.Show()

        # Step 4: Emphasize the clashes based on the user selection
        transaction = db.Transaction(doc)
        transaction.Start("{name} - v{ver}".format(name=__name, ver=__version))
        try:
            if result == ui.TaskDialogResult.CommandLink1:  # Mark clashes and fade the rest
                print("Marking all clashing elements and fading the rest...")
                for elem_id in all_ids:  # fade all visible elements in the view
                    view.SetElementOverrides(db.ElementId(elem_id),
                                             faded_overrides)
                for elem_id in clashing_ids:  # emphasize the clashing elements
                    view.SetElementOverrides(db.ElementId(elem_id),
                                             clashing_overrides)
            elif result == ui.TaskDialogResult.CommandLink2:  # Hide all non-clashing elements
                print(
                    "Hiding all non-clashing elements in the view temporarily..."
                )
                for elem_id in non_clashing_ids:  # hide alll non-clashing elements
                    view.HideElementTemporary(db.ElementId(elem_id))
            else:
                print("Nothing to do.")
        except Exception as ex:
            print("Exception: {ex}".format(ex=ex))
            transaction.RollBack()
        else:
            transaction.Commit()
            print("Done.")
    else:  # no file to parse
        print("Nothing to do.")
Example #9
0
from pyrevit import HOST_APP
from revitutils import doc, uidoc, selection, curview

# noinspection PyUnresolvedReferences
import Autodesk.Revit.DB as DB


__doc__ = 'Reorients the current 3D view camera, perpendicular to the' \
          'selected face. This tool will set a sketch plane over the ' \
          'selected face for 3d drawing.'

face = selection.utils.pick_face()

if face and isinstance(curview, DB.View3D):
    t = DB.Transaction(doc, 'Orient to Selected Face')
    t.Start()

    # calculate normal
    if HOST_APP.is_newer_than(2015):
        normal_vec = face.ComputeNormal(DB.UV(0, 0))
    else:
        normal_vec = face.Normal

    # create base plane for sketchplane
    if HOST_APP.is_newer_than(2016):
        base_plane = DB.Plane.CreateByNormalAndOrigin(normal_vec, face.Origin)
    else:
        base_plane = DB.Plane(normal_vec, face.Origin)

    # now that we have the base_plane and normal_vec
    # let's create the sketchplane
Example #10
0
def createBBox(geometry_curve, referenceArray):
    tx = DB.Transaction(doc, "test")
    tx.Start()
    railCurve = []
    x_val = []
    y_val = []
    z_val = []
    iter = 0
    refArray1 = DB.ReferenceArray()
    refArray2 = DB.ReferenceArray()
    # refArray2.Append(DB.Reference(geometry_curve))
    # refArray1.Append(geometry_curve.Reference)
    for curve in geometry_curve:
        print(str(curve.Length) + " Ft.")
        # print(curve.ToString())
        refArray1.Append(curve.Reference)
        # refArray2.Append(DB.Reference(curve))
        # c_line = DB.Line.CreateBound(curve.GetEndPoint(0), curve.GetEndPoint(1))
        # print("CLINE REF")
        # print(c_line.Reference)
        # railCurve.append(c_line)

        # print(curve.GetEndPoint(0))
        x_val.append(curve.GetEndPoint(0).X)
        # print("X-coordinate added : " + str(curve.GetEndPoint(0).X))
        x_val.append(curve.GetEndPoint(1).X)
        # print("X-coordinate added : " + str(curve.GetEndPoint(1).X))
        y_val.append(curve.GetEndPoint(0).Y)
        # print("Y-coordinate added : " + str(curve.GetEndPoint(0).Y))
        y_val.append(curve.GetEndPoint(1).Y)
        # print("Y-coordinate added : " + str(curve.GetEndPoint(1).Y))
        z_val.append(curve.GetEndPoint(0).Z)
        # print("Z-coordinate added : " + str(curve.GetEndPoint(0).Z))
        z_val.append(curve.GetEndPoint(1).Z)
        # print("Z-coordinate added : " + str(curve.GetEndPoint(1).Z))
        # newLine = None

        try:
            newLine = doc.Create.NewDetailCurve(view, curve)
            refArray2.Append(newLine.GeometryCurve.Reference)
            # doc.Create.NewDimension(view, newLine, referenceArray)
            # refArray.Append(curve)
            print("Detail Line Drawn")
            # doc.Create.NewDimension(view, curve, newRefArr)
        except:
            print("Rail Segment not visible in plane")
            next
        # refArray.Append(curve.Reference)
        # try:
        #     doc.Create.NewDimension(view, curve, referenceArray)
        #     print("New Dimension Created")
        # except:
        #     print("RefArrayItem Ignored")

    x_max = max(x_val)
    # print("X Max :" + str(x_max))
    # x_max_index = x_value.index(x_max)
    x_min = min(x_val)
    # print("X Min :" + str(x_min))
    y_max = max(y_val)
    # print("Y Max :" + str(y_max))
    y_min = min(y_val)
    # print("Y Min :" + str(y_min))
    z_max = max(z_val)
    # print("Z Max :" + str(z_max))
    z_min = min(z_val)
    print(str(refArray2.Size))
    iter = 0
    # for curve in geometry_curve:
    try:
        doc.Create.NewDimension(view, geometry_curve[2], refArray2)
    except:
        print("unable to generage dimension")

    # plane = doc.Create.NewReferencePlane(DB.XYZ(x_min, y_min, 0), DB.XYZ(x_max, y_max, 0), DB.XYZ(0,0,z_max), view)
    # for curve in geometry_curve:
    #     detCurv = doc.Create.NewDetailCurve(view, curve)
    # skplane = doc.FamilyCreate.NewSketchPlane(plane)

    # Create Line Vertices:
    # lnStart = DB.XYZ(0,0,0)
    # lnEnd = DB.XYZ(10,10,0)

    # curve = app.Create.NewLine(lnStart, lnEnd, True)
    # crv = doc.FamilyCreate.NewModelCurve(curve, skplane)

    # print("Z Min :" + str(z_min))
    # w = (x_max - x_min)
    # d = (y_max - y_min)
    # h = (z_max - z_min)
    # if d < 10:
    #     d = 10
    # if w < 10:
    #     w = 10

    # maxPt = (w,h,0)
    # minPt = (-w, -h, -d)
    # bbox = doc.GetElement(geometry_curve).BoundingBoxXYZ()
    # bbox.Enabled = True
    # bbox.Max = maxPt
    # bbox.Min = minPt

    # trans = Transform.Identity

    # midPt = .5 * (bbox.Max + bbox.Min)
    # trans.Origin = midPt
    # print(str(midPt))
    # dim = DB.Dimension(doc.ActiveView,)
    tx.Commit()
def main():
    """Main script - Correct the pipe riser tags tagging vent pipes."""

    print("šŸ Running {name} version {ver}:".format(name=__name, ver=__version))

    # STEP 0: Setup
    doc = __revit__.ActiveUIDocument.Document
    view = doc.ActiveView

    # STEP 1: Get all available Pipe Tags in the project
    print("Getting all available pipe tags from the model... ", end="")
    tag_types = db.FilteredElementCollector(doc)\
                  .OfCategory(db.BuiltInCategory.OST_PipeTags)\
                  .WhereElementIsElementType()\
                  .ToElements()
    tag_types_mapping = {}  # tag_title: tag_type
    for tag_type in tag_types:
        tag_family_name = tag_type.get_Parameter(
            db.BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM).AsString()
        tag_type_name = tag_type.get_Parameter(
            db.BuiltInParameter.SYMBOL_NAME_PARAM).AsString()
        full_tag_name = "{f_name} - {t_name}".format(f_name=tag_family_name,
                                                     t_name=tag_type_name)
        tag_types_mapping[full_tag_name] = tag_type
    print("āœ”")

    # STEP 2: Check if setup tags actually exist in project
    print("Checking if expected tag family (and types) exist(s)... ", end="")
    all_tags_available = True
    for tag_name in TAG_TYPE_NAME_MAPPING.values():
        if not tag_name in tag_types_mapping:
            print(
                "āœ˜ Error: {tag_name} not available!".format(tag_name=tag_name))
            all_tags_available = False
    if not all_tags_available:
        print(
            "āœ˜ Error: Not all required tags are available in the project! See above."
        )
        return ui.Result.Failed
    print("āœ”")

    # STEP 3: Get all the tags in the view
    tags_in_view = db.FilteredElementCollector(doc, view.Id)\
                     .OfCategory(db.BuiltInCategory.OST_PipeTags)\
                     .WhereElementIsNotElementType()\
                     .ToElements()

    # STEP 4: Change all tags on vent pipes to vent tags
    print("Changing all pipe riser tags tagging vent pipes.... ", end="")
    transaction = db.Transaction(doc)
    transaction.Start("{name} - v{ver}".format(name=__name, ver=__version))
    try:
        for tag in tags_in_view:
            host = tag.GetTaggedLocalElement()
            system = host.MEPSystem
            if system:
                system_type = doc.GetElement(system.GetTypeId())
                system_classification = system_type.SystemClassification
                if system_classification == db.MEPSystemClassification.Vent:
                    tag_type = doc.GetElement(tag.GetTypeId())
                    tag_family_name = tag_type.get_Parameter(
                        db.BuiltInParameter.SYMBOL_FAMILY_NAME_PARAM).AsString(
                        )
                    tag_type_name = tag_type.get_Parameter(
                        db.BuiltInParameter.SYMBOL_NAME_PARAM).AsString()
                    if not tag_family_name == TAG_FAMILY_NAME:  # other kind of tag, dont bother
                        continue
                    if tag_type_name not in REMAPPING:  # tag type already good or not in remapping
                        continue
                    target = REMAPPING[tag_type_name]
                    target_type_id = tag_types_mapping[
                        TAG_TYPE_NAME_MAPPING[target]].Id
                    tag.ChangeTypeId(target_type_id)
    except Exception as ex:
        print("\nāœ˜ Exception:\n {ex}".format(ex=ex))
        transaction.RollBack()
        return ui.Result.Failed
    else:
        transaction.Commit()
        print("āœ”\nDone. šŸ˜Š")
        return ui.Result.Succeeded
Example #12
0
print dumpedpa

so1 = [pick1.get_Parameter(eval("BuiltInParameter." + i)) for i in dumpedpa]

try:
    counter = 0
    while counter < 5:

        ref2 = uidoc.Selection.PickObject(ObjectType.Element)
        pick2 = doc.GetElement(ref2)

        if pick2.Category.Name.Equals(catname):
            #print "Equal"
            list = []

            t = DB.Transaction(doc, "Write Parameters")
            t.Start()

            for p in so1:
                if not p.IsReadOnly:
                    if p.StorageType.Equals(DB.StorageType.ElementId):
                        pval = p.AsElementId()
                    if p.StorageType.Equals(DB.StorageType.Integer):
                        pval = p.AsInteger()
                    if p.StorageType.Equals(DB.StorageType.String):
                        pval = p.AsString()
                    if p.StorageType.Equals(DB.StorageType.Double):
                        pval = p.AsDouble()

                    try:
                        print p.Definition.Name
Example #13
0
cShpMan = cActiveView.GetCropRegionShapeManager()
cBoundaryList = cShpMan.GetCropShape()

if (ptArray.Count> 4) and not(cShpMan.CanHaveShape):
	UI.TaskDialog.Show('pyRevitPlus-', 'Unable to set non=rectangular crop to the viewport.')
else:	
	newBoundaryList = DB.CurveLoop()
	#print('pyRevitPlus: Creating new boundary')
	for idx, value in enumerate(ptArray):
		pt0 = ptArray[idx-1]
		pt1 = ptArray[idx]
		#print("Curve {}: Start {}, curve end {}, distance {}".format(idx, pt0, pt1, math.sqrt( ((pt1[0]-pt0[0])**2)+((pt1[1]-pt0[1])**2) )))
		cLine = DB.Line.CreateBound(pt0, pt1)
		newBoundaryList.Append(cLine)
	#print('pyRevitPlus: Updating boundary')
	t = DB.Transaction(doc, 'Paste Viewport Clipping')
	t.Start()
	#	print('pyRevitPlus: In transaction')
	cActiveView.CropBoxVisible = True
	cActiveView.CropBoxActive =True
		
	if cShpMan.IsCropRegionShapeValid(newBoundaryList):
		try:
			cShpMan.RemoveCropRegionShape()
			cShpMan.SetCropShape(newBoundaryList)
		except InvalidOperationException:
			print('The crop of the associated view is not permitted to have a non-rectangular shape.')
		except ArgumentException :
			print('Boundary in boundary should represent one closed curve loop without self-intersections, consisting of non-zero length straight lines in a plane parallel to the view plane. ')
	doc.Regenerate()
	t.Commit()
Example #14
0
    viewlist.append(i) if i.Category.Name.Equals("Views") else
    sheetview.append(i) if i.Category.Name.Equals("Sheets") else False
    for i in secviewlist
]

if not viewlist:
    forms.alert("Select Views in the Project Browser to place on Sheet",
                ok=True)
    sys.exit()

if not sheetview:
    forms.alert("You have to select a Sheet also", ok=True)
    sys.exit()

try:
    t = DB.Transaction(doc, "test")
    t.Start()
    for i in viewlist:
        viewport = DB.Viewport.Create(doc, sheetview[0].Id, i.Id,
                                      DB.XYZ(0, 0, 0))
        #vplist.append(viewport)
    t.Commit()

except:
    t.RollBack()
    t.Dispose()
    import traceback
    print traceback.format_exc()

#ToDo: Get Parameter Values from Titleblock:
#- SheetIssueDate, DrawnBy
Example #15
0
def read_from_excel():
    """Option to write read sheet data from excel and create sheets"""
    _titleblock_id = _ask_for_titleblock()

    # res = forms.alert('Did you Save Excel file?',
    #                     ok=False, yes=True, no=True)
    res = True
    if res:
        # storage for excel data
        sheet_num = []
        sheet_name = []
        sheet_group = []
        sheet_approved = []
        sheet_designed = []
        sheet_checked = []
        sheet_drawn = []
        sheet_issue = []

        try:
            wb = xlrd.open_workbook(dest)
            sheet = wb.sheet_by_index(0)
            sheet_group_para = sheet.cell_value(0, 2)
            # target_range = str(forms.ask_for_string("2-11",prompt='Enter range of excel',title=loc))
            target_range = None
            if target_range:
                start = int(target_range.split("-")[0]) - 1
                if start <= 0:  # to avoid header being included in selection
                    start = 1
                end = int(target_range.split("-")[1])
            else:
                start = 1  # 1 in python is 2 in excel
                end = sheet.nrows

            for i in range(start, end):
                sheet_num.append(int_str(sheet.cell_value(i, 0)))
            for i in range(start, end):
                sheet_name.append(sheet.cell_value(i, 1))
            for i in range(start, end):
                sheet_group.append(sheet.cell_value(i, 2))
            for i in range(start, end):
                sheet_approved.append(sheet.cell_value(i, 3))
            for i in range(start, end):
                sheet_designed.append(sheet.cell_value(i, 4))
            for i in range(start, end):
                sheet_checked.append(sheet.cell_value(i, 5))
            for i in range(start, end):
                sheet_drawn.append(sheet.cell_value(i, 6))
            for i in range(start, end):
                date = sheet.cell_value(i, 7)
                if isinstance(
                        date, float
                ):  # if date is not stored as string we will have to convert it into string
                    datetime_date = xlrd.xldate_as_datetime(date, 0)
                    date_object = datetime_date.date()
                    string_date = date_object.isoformat()
                    date = string_date
                sheet_issue.append(int_str(
                    date))  # to filter out double quotes in date if any

            with DB.Transaction(doc, 'Create Sheet') as t:
                try:
                    t.Start()
                    for inpu in zip(sheet_num, sheet_name, sheet_group,
                                    sheet_approved, sheet_designed,
                                    sheet_checked, sheet_drawn, sheet_issue):
                        _create_sheet(inpu, t, sheet_group_para,
                                      _titleblock_id)
                    t.Commit()
                except:
                    t.RollBack()
                    print(traceback.format_exc())
        except:
            print(traceback.format_exc())
Example #16
0
def main():
    """Main Script."""

    print("šŸ Running {fname} version {ver}...".format(fname=__name,
                                                      ver=__version))

    # STEP 0: Setup
    doc = __revit__.ActiveUIDocument.Document

    # STEP 1: Inspect Model and summarize findings
    pipe_insulations = query_all_elements_of_category(
        doc=doc, cat=db.BuiltInCategory.OST_PipeInsulations)
    duct_insulations = query_all_elements_of_category(
        doc=doc, cat=db.BuiltInCategory.OST_DuctInsulations)
    rogue_pipe, unhosted_pipe = find_rogue_and_unhosted_elements(
        doc=doc, elems=pipe_insulations)
    rogue_duct, unhosted_duct = find_rogue_and_unhosted_elements(
        doc=doc, elems=duct_insulations)
    summary_list = write_summary(
        tpipe=pipe_insulations,
        tduct=duct_insulations,  # totals
        upipe=unhosted_pipe,
        uduct=unhosted_duct,  # unhosted
        rpipe=rogue_pipe,
        rduct=rogue_duct)  # rogue
    summary_text = "\n".join(summary_list)
    print(summary_text)

    # STEP 2: Receive User Input
    dialog = ui.TaskDialog(title="Insulation Cleanup")
    dialog.MainInstruction = "Insulation Cleanup Summary"
    dialog.MainContent = summary_text
    dialog.AddCommandLink(ui.TaskDialogCommandLinkId.CommandLink1,
                          "Write Report")
    dialog.AddCommandLink(ui.TaskDialogCommandLinkId.CommandLink2,
                          "Clean Insulation")
    dialog.CommonButtons = ui.TaskDialogCommonButtons.Close
    dialog.DefaultButton = ui.TaskDialogResult.Close
    result = dialog.Show()

    # STEP 3: Write report or clean up insulation
    if result == ui.TaskDialogResult.CommandLink1:  # Write report
        save_dialog = swf.SaveFileDialog()
        save_dialog.Title = "Save Insulation Cleanup Report"
        save_dialog.Filter = "Text files|*.txt"
        save_dialog.FileName = "report.txt"
        if save_dialog.ShowDialog() == swf.DialogResult.OK:  # Save report
            file_path = save_dialog.FileName
            print("Writing report to {0}".format(file_path))
            with open(file_path, mode="wb") as fh:
                report = write_report(doc, unhosted_pipe, rogue_pipe,
                                      unhosted_duct, rogue_duct)
                for line in report:
                    fh.write("{line}\r\n".format(line=line))
            print("āœ”\nDone. šŸ˜Š")
            return ui.Result.Succeeded
        else:  # Don't save report
            print("šŸ›ˆ File save dialog canceled.")
            return ui.Result.Cancelled
    elif result == ui.TaskDialogResult.CommandLink2:  # Clean Insulation
        transaction = db.Transaction(doc)
        transaction.Start("{name} - v{ver}".format(name=__name, ver=__version))
        try:
            print("Cleaning Insulation...")
            for pipe_element in unhosted_pipe:
                doc.Delete(pipe_element.Id)
            print("Deleted {num} unhosted pipe insulation elements".format(
                num=len(unhosted_pipe)))
            for pipe_pair in rogue_pipe:
                cleanup_insulation(pipe_pair)
            print("Moved {num} rogue pipe insulation elements.".format(
                num=len(rogue_pipe)))
            for duct_element in unhosted_duct:
                doc.Delete(duct_element.Id)
            print("Deleted {num} unhosted duct insulation elements.".format(
                num=len(unhosted_duct)))
            for duct_pair in rogue_duct:
                cleanup_insulation(duct_pair)
            print("Moved {num} rogue duct insulation elements.".format(
                num=len(rogue_duct)))
        except Exception as exception:
            print("Failed.\nException:\n{ex}".format(ex=exception))
            transaction.RollBack()
            return ui.Result.Failed
        else:
            print("āœ”\nDone. šŸ˜Š")
            transaction.Commit()
            return ui.Result.Succeeded
    else:
        print("Nothing to do.")
        return ui.Result.Cancelled