Help with Python---Creating Voxels

Hello, I’m trying to re-work a script that somebody else created and is currently not working. I have attached the problematic problem of the graph and pasted the python script below. It is supposed to (and does) create .png slices through the height of the model. What it is not doing, however, is giving me any output in dynamo—which I am expecting. Can somebody please look at the end of the python script and give me advice as to why the outputs are not working? This worked years ago, so I wonder if it has to do with dynamo and/or python being updated and a command not working anytmore.

Thanks so much. I’m familiar with Dynamo but have a hard time with Python at the moment, though I’m actively learning.

import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

# Import Element wrapper extension methods
clr.AddReference('RevitNodes')
import Revit
clr.ImportExtensions(Revit.Elements)

# Import geometry conversion extension methods
clr.ImportExtensions(Revit.GeometryConversion)

# Import DocumentManager and TransactionManager
clr.AddReference('RevitServices')
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

# Import RevitAPI
clr.AddReference('RevitAPI')
import Autodesk
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB import FilteredElementCollector as _FilteredElementCollector
from Autodesk.Revit.DB import ViewFamilyType as _ViewFamilyType

import System
from System import Array
from System.Collections.Generic import *
import sys
sys.path.append("C:\Program Files (x86)\IronPython 2.7\Lib")
import os
import math
import shutil


def clean_up(folder_name):
	for file_name in os.listdir(folder_name): # delete all content
		file_path = os.path.join(folder_name, file_name)
		
		if os.path.isfile(file_path):
			os.remove(file_path)
		else:
			shutil.rmtree(file_path)
	os.makedirs(os.path.join(folder_name, "origin")) # add origin folder


def get_ViewFamilyTypeId(viewFamilyTypeName):	
	names = []
	ids = []
	viewFamilyTypeId = -1
	collector = _FilteredElementCollector(doc).OfClass(_ViewFamilyType) #collecting all elements of type ViewFamilyType
	for t in collector:
		names.append(t.FamilyName)
		ids.append(t.Id)
		if t.FamilyName == viewFamilyTypeName:
			viewFamilyTypeId = t.Id
			break # get the first
	return viewFamilyTypeId
			
			
def create_view(doc, viewFamilyTypeId, boundingBox, voxel_size):		
	if viewFamilyTypeId != -1:
		TransactionManager.Instance.EnsureInTransaction(doc)
		
		boundingBoxSlice = boundingBox
		boundingBoxSlice.Max = XYZ(boundingBox.Max.X, boundingBox.Max.Y, boundingBox.Min.Z + voxel_size)  # adjust boundingbox for far clip offset		
		sectionView = ViewSection.CreateDetail(doc, viewFamilyTypeId, boundingBoxSlice) 					
		
		viewId = Autodesk.Revit.DB.ElementId(int(str(sectionView.Id)) - 1)
		minY = boundingBoxSlice.Min.Y
		maxY = boundingBoxSlice.Max.Y
		midY = (maxY + minY) / 2
		minX = boundingBoxSlice.Min.X
		maxX = boundingBoxSlice.Max.X
		minZ = boundingBoxSlice.Min.Z
		axis = Line.CreateBound(XYZ(minX, midY, minZ), XYZ(maxX, midY, minZ))  # flip DetailView direction
		ElementTransformUtils.RotateElement(doc, viewId, axis, math.pi)	
		
		TransactionManager.Instance.TransactionTaskDone()
		return sectionView


def update_view(doc, view, voxel_size):
	TransactionManager.Instance.EnsureInTransaction(doc)	
	translationVec = XYZ(0, 0, voxel_size)
	viewId = Autodesk.Revit.DB.ElementId(int(str(view.Id)) - 1)
	ElementTransformUtils.MoveElement(doc, viewId, translationVec)	
	TransactionManager.Instance.TransactionTaskDone()
	return sectionView, height
	
	
def export_view_image(view, path, image_width, doc):
	TransactionManager.Instance.EnsureInTransaction(doc)
	ieo = ImageExportOptions()
	ieo.ExportRange = ExportRange.SetOfViews
	ieo.SetViewsAndSheets([view.Id])
	ieo.FilePath = path	
	ieo.HLRandWFViewsFileType = ImageFileType.PNG
	ieo.ShadowViewsFileType = ImageFileType.PNG
	ieo.PixelSize = image_width
	doc.ExportImage(ieo)
	TransactionManager.Instance.TransactionTaskDone()
	return ieo.IsValidFileName(path)
	
	
def delete_views(doc, views):
	TransactionManager.Instance.EnsureInTransaction(doc)	
	for view in views:
		doc.Delete(view.Id)
	TransactionManager.Instance.TransactionTaskDone()


def apply_viewTemplate(doc, view, viewTemplateName):
	viewTemplate = None
	collector = FilteredElementCollector(doc).OfClass(View)
	for i in collector:
		if i.IsTemplate == True and i.Name == viewTemplateName:
			viewTemplate = i
	
	TransactionManager.Instance.EnsureInTransaction(doc)
	if viewTemplate is not None:
		view.ViewTemplateId = viewTemplate.Id
	TransactionManager.Instance.TransactionTaskDone()


def get_scopeBox(name):
	collector = FilteredElementCollector(doc)
	elements = collector.OfCategory(BuiltInCategory.OST_VolumeOfInterest).ToElements()
	for element in elements:
		if element.Name == name:
			return element


def rename_images(digit, folder_name):
	path = os.path.join(folder_name, "origin")
	new_filenames = []
	
	for f_name in os.listdir(path):
	    new_f_name = f_name[0:digit] +'.png'  # 3 digits worth
	    os.rename(os.path.join(path, f_name), os.path.join(path, new_f_name))
	    new_filenames.append(new_f_name)
	    

filePath = IN[0]
slices = IN[1] * 12
scopeBox_name = IN[2]
viewTemplateName = IN[3]
is_delete = IN[4]

clean_up(filePath)

doc = DocumentManager.Instance.CurrentDBDocument
scopeBox = get_scopeBox(scopeBox_name)

filenames = []

try:
	count = 1
	heights = []
	
	viewFamilyTypeId = get_ViewFamilyTypeId("Detail View")
	boundingBox = scopeBox.get_BoundingBox(None) # https://github.com/DynamoDS/DynamoRevit/blob/Revit2015/src/Libraries/RevitNodes/Elements/Element.cs
	
	voxel_size = (boundingBox.Max.Z - boundingBox.Min.Z) / slices * 12 # feet to inch
	image_width = (boundingBox.Max.X - boundingBox.Min.X) / voxel_size
		
	if image_width <= 15000:
		bottom = boundingBox.Min.Z
		top = boundingBox.Max.Z
		height = bottom
		digit = len(str(int((top - bottom) / voxel_size))) 	
		
		sectionView = create_view(doc, viewFamilyTypeId, boundingBox, voxel_size)
		apply_viewTemplate(doc, sectionView, viewTemplateName)
		
		while height < top:
		#	if count > 10:  # TEMP for test
				#break
		
			heights.append(height)
		
			height += voxel_size	
			update_view(doc, sectionView, voxel_size)
			
			imageName = filePath + "\\origin\\" + str(count).rjust(digit, '0') # filename format: "tempFileName - view type - view name"; craete origin folder
			isValid = export_view_image(sectionView, imageName, image_width, doc)
			
			filenames.append(imageName)
			filenames.append(isValid)
			
			count += 1
			
		if is_delete:
			delete_views(doc, [sectionView])
			
		TransactionManager.Instance.ForceCloseTransaction()  # Dynamo transaction force close order
			
		rename_images(digit, filePath)
			
		OUT = "success", digit, sectionView, image_width, str(voxel_size * 12) + " in" # other outputs:  boundingBox.Min, boundingBox.Max, heights
	else:
		OUT = "failed: image_width out of range > 15000, please set larger # of slices", image_width
except Exception as e:
	OUT =  "failed", e

test dynamo script.dyn (16.6 KB)

Hi @anordstrom

Could you show us what’s the error message?

Could you share the link to the old post?

Which Revit and Dynamo Version you’re currently using?

1 Like

Thanks.

This is my error. I don’t have an old post—it was a conference/talk. Currently in dynamo 2.3 and the newest version of Python.

image