SHARE
TWEET

test.py

a guest Nov 21st, 2016 70 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # these commands get executed in the current scope
  2. from Autodesk.Revit.UI.Selection import ObjectType
  3. from Autodesk.Revit.UI import TaskDialog
  4. import clr
  5. import traceback
  6. import operator
  7. import math
  8. clr.AddReference('RevitAPI')
  9. clr.AddReference('RevitAPIUI')
  10. from Autodesk.Revit.DB import *
  11.  
  12. app = __revit__.Application
  13. doc = __revit__.ActiveUIDocument.Document
  14. uidoc = __revit__.ActiveUIDocument
  15. SHEET = doc.ActiveView
  16. LOGFILE =  "T:\Malcolm-Chris\REVIT\PYTHON REVIT SHELL\log.txt"
  17. RAW_WRITE = True
  18. def is_array(var):
  19.     return isinstance(var, (list, tuple))
  20.  
  21. def log(textArr,is_raw=False):
  22.     global LOGFILE
  23.     filename =  LOGFILE
  24.     if (not is_array(textArr)):
  25.         textArr = [textArr]
  26.     target = open(filename, 'a+')
  27.     target.write("\n")
  28.     for i in textArr:
  29.         if (not is_raw):
  30.             target.write(repr(i))
  31.         else:
  32.             target.write(i)
  33.     target.close()
  34.  
  35. def clearLog():
  36.     global LOGFILE
  37.     filename =  LOGFILE
  38.     target = open(filename, 'w+')
  39.     target.write("")
  40.     target.close()
  41.  
  42. def transpose(lis):
  43.     return map(list, zip(*lis))
  44.  
  45. def dicViewer(dic):
  46.     list = []
  47.     for key,val in dic.items():
  48.         list.append(["key:"+str(key),val])
  49.     return list
  50.  
  51. def getPtList(dic):
  52.     list = []
  53.     for key,val in dic.items():
  54.         list.append(map(lambda x: float(x), key.split(",")))
  55.     return list
  56.  
  57.  
  58. def seq(start, stop, step=1):
  59.     n = int(round((stop - start)/float(step)))
  60.     if n > 1:
  61.         return([start + step*i for i in range(n+1)])
  62.     else:
  63.         return([])
  64.  
  65.  
  66. def listToDic(list):
  67.     dic = {}
  68.     for i in list:
  69.         i[0] = i[0].replace("key:","")
  70.         dic[i[0]] = i[1]
  71.     return dic
  72.  
  73. def xyToPoint(xyPt):
  74.     return [xyPt[0],xyPt[1],0]
  75.     #return Point.ByCoordinates(xyPt[0],xyPt[1],0)
  76.    
  77. def getClosest(x,n):
  78.     return  math.floor(x / n) * n;
  79.  
  80. def closestNode(coord,points):
  81.     """Return closest point to coord from points"""
  82.     dists = [(pow(point[0] - coord[0], 2) + pow(point[1] - coord[1], 2), point) for point in points]            
  83.     # list of (dist, point) tuples
  84.     nearest = min(dists)
  85.     return nearest[1]  # return point only
  86.  
  87. def getNewDetailViewNumber(pts,offsetX, offsetY, stepX, stepY,gridPtsDic):
  88.     newPts = []
  89.     notClosestPts = []
  90.     newPtsPts = []
  91.     detailViewNumber = []
  92.     for pt in pts:
  93.         approxPt = ([round(getClosest(pt[0], stepX)+offsetX,2),round(getClosest(pt[1], stepY)+offsetY,2)])
  94.         log(["approxPt",approxPt])
  95.         notClosestPts.append(xyToPoint(approxPt))
  96.         closestPt = closestNode(approxPt, getPtList(gridPtsDic))
  97.  
  98.         newPtsPts.append(xyToPoint(closestPt))
  99.         newPts.append(closestPt)
  100.         detailViewNumber.append(gridPtsDic[",".join(map(lambda x: str(x), closestPt))])
  101.     #Assign your output to the OUT variable.
  102.     return {
  103.     "newPts":newPts,
  104.     "detailViewNumber":detailViewNumber,
  105.     "notClosestPts":notClosestPts,
  106.     "newPtsPts":newPtsPts
  107.     }
  108.  
  109.  
  110. def getPtGrid(startPt, endPt):
  111.            
  112.    
  113.     coords = {}
  114.  
  115.     # CHANGE THIS IF GRID IS DIFFERENT!
  116.     detailGrid = [
  117.         [30 ,25 ,20 ,15 ,10,5],
  118.         [29 ,24 ,19 ,14 ,9 ,4],
  119.         [28 ,23 ,18 ,13 ,8 ,3],
  120.         [27 ,22 ,17 ,12 ,7 ,2],
  121.         [26 ,21 ,16 ,11 ,6 ,1]]
  122.  
  123.     xDiv = len(detailGrid[0])
  124.     yDiv = len(detailGrid)
  125.  
  126.     detailGridFlat = reduce(operator.add, transpose(detailGrid))
  127.     count = 0
  128.     stepX = round((endPt.X-startPt.X)/(xDiv),2)
  129.     stepY = round((endPt.Y-startPt.Y)/(yDiv),2)
  130.     for i in seq(startPt.X, endPt.X-stepX, stepX):
  131.         for j in seq(startPt.Y, endPt.Y-stepY,  stepY):
  132.             coords[str(round(i,2))+","+str(round(j,2))]= detailGridFlat[count]
  133.             count=count+1
  134.  
  135.     #Assign your output to the OUT variable.
  136.     return { "coords": coords,
  137.         "offsetX": startPt.X,
  138.         "offsetY": endPt.Y,
  139.         "stepX": stepX,
  140.         "stepY": stepY
  141.         }
  142.    
  143.  
  144. def elementFromId(id):
  145.     log(["id:", id])
  146.     global doc
  147.     return doc.GetElement(id)
  148.  
  149. def setParam(el, paramName, value):
  150.     param = getParam(el, paramName, True)
  151.     if not param.IsReadOnly:
  152.         param.Set(value)
  153.     else:
  154.         log(["Coult not edit ",paramName," on ",el, ". It is either readonly or not user editable. // Read Only: ",param.IsReadOnly])
  155.  
  156. def getParam(el, paramName, asParamObject=False):
  157.     params = getParameters(el, asParamObject)
  158.     return params[paramName]
  159.  
  160. def getParameters(el,asParamObject=False):
  161.     parameters = el.Parameters
  162.     params = {}
  163.     for param in parameters:
  164.         if (asParamObject==False):
  165.             params[param.Definition.Name] = param.AsString()
  166.         else:
  167.             params[param.Definition.Name] = param
  168.     return params
  169.  
  170. def elementFromReference(ref):
  171.     global doc
  172.     id = ref.ElementId
  173.     return doc.GetElement(id)
  174.  
  175.  
  176. def getPointsFromViewports(viewport):
  177.     outline = viewport.GetLabelOutline()
  178.     return [outline.MaximumPoint.X,outline.MinimumPoint.Y,0]
  179.  
  180. def pickObject():
  181.    
  182.     __window__.Hide()
  183.     TaskDialog.Show ("Select Objects", "Select the line representing the grid bounds after closing this dialog.")
  184.     picked = uidoc.Selection.PickObject(ObjectType.Element)
  185.     #__window__.Topmost = True
  186.     #__window__.Show()
  187.     return picked
  188.  
  189.  
  190.  
  191. # clear log file
  192. clearLog()
  193. t = Transaction(doc, 'Rename Detail Numbers')
  194. t.Start()
  195.  #<------------- the stuff ------------>
  196. #lets get the guide curve
  197. try:
  198.    
  199.     bbCrvRef = pickObject()
  200.     #log(bbCrvRef)
  201.     bbCrv = elementFromReference(bbCrvRef).GeometryCurve
  202.     #log(bbCrv)
  203.     pts = [bbCrv.GetEndPoint(0),bbCrv.GetEndPoint(1)]
  204.     log(pts)
  205.     ptGridData = getPtGrid(pts[0],pts[1])
  206.     log(ptGridData)
  207.    
  208.     viewports = map(lambda x: elementFromId(x), SHEET.GetAllViewports())
  209.     titleBlockPts = map(lambda x: getPointsFromViewports(x) ,viewports)
  210.     log(titleBlockPts)
  211.     detailViewNumberData = getNewDetailViewNumber(titleBlockPts,ptGridData['offsetX'], ptGridData['offsetY'],ptGridData['stepX'], ptGridData['stepY'],ptGridData['coords'])
  212.     log(detailViewNumberData)
  213.     log(map(lambda x: getParameters(x) ,viewports))
  214.     log(map(lambda x: getParam(x,"Detail Number") ,viewports))
  215.     log("Hello")
  216.  
  217.  
  218.     # <---- Make unique numbers
  219.     for i, viewport in enumerate(viewports):
  220.         paramName = "Detail Number"
  221.         currentVal = getParam(viewport,"Detail Number")
  222.         setParam(viewport, paramName,currentVal+"x")
  223.     t.Commit()
  224.    
  225.     '''
  226.     # <---- Do the thang    
  227.     t2 = Transaction(doc, 'Rename Detail Numbers')
  228.     t2.Start()
  229.     for i, viewport in enumerate(viewports):
  230.         setParam(viewport, "Detail Number",detailViewNumberData[i])
  231.      t2.Commit()
  232.     '''
  233.    
  234. except SyntaxError, e:
  235.     log(["Error!\n---------\n", traceback.format_exc()],RAW_WRITE)
  236.  
  237. except Exception, e:
  238.     log(["Error!\n---------\n", traceback.format_exc()],RAW_WRITE)
  239.  
  240.  #<------------- end of the stuff ------------>
  241.  
  242.  
  243.  
  244. __window__.Close()
RAW Paste Data
Want to get better at Python?
Learn to code Python in 2017
Top