Skip to content

Instantly share code, notes, and snippets.

@giobel
Last active December 29, 2022 15:26
Show Gist options
  • Save giobel/080894e6b850cd6c67176e3f3cd8f692 to your computer and use it in GitHub Desktop.
Save giobel/080894e6b850cd6c67176e3f3cd8f692 to your computer and use it in GitHub Desktop.
collection of rhino inside functions for Revit
#Rhino Inside Revit methods
using System;
using System.Collections;
using System.Collections.Generic;
using Rhino;
using Rhino.Geometry;
using Grasshopper;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Data;
using Grasshopper.Kernel.Types;
using RVT = Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using RhinoInside.Revit;
/// <summary>
/// This class will be instantiated on demand by the Script component.
/// </summary>
public class Script_Instance : GH_ScriptInstance
{
#region Utility functions
/// <summary>Print a String to the [Out] Parameter of the Script component.</summary>
/// <param name="text">String to print.</param>
private void Print(string text) { /* Implementation hidden. */ }
/// <summary>Print a formatted String to the [Out] Parameter of the Script component.</summary>
/// <param name="format">String format.</param>
/// <param name="args">Formatting parameters.</param>
private void Print(string format, params object[] args) { /* Implementation hidden. */ }
/// <summary>Print useful information about an object instance to the [Out] Parameter of the Script component. </summary>
/// <param name="obj">Object instance to parse.</param>
private void Reflect(object obj) { /* Implementation hidden. */ }
/// <summary>Print the signatures of all the overloads of a specific method to the [Out] Parameter of the Script component. </summary>
/// <param name="obj">Object instance to parse.</param>
private void Reflect(object obj, string method_name) { /* Implementation hidden. */ }
#endregion
#region Members
/// <summary>Gets the current Rhino document.</summary>
private readonly RhinoDoc RhinoDocument;
/// <summary>Gets the Grasshopper document that owns this script.</summary>
private readonly GH_Document GrasshopperDocument;
/// <summary>Gets the Grasshopper script component that owns this script.</summary>
private readonly IGH_Component Component;
/// <summary>
/// Gets the current iteration count. The first call to RunScript() is associated with Iteration==0.
/// Any subsequent call within the same solution will increment the Iteration count.
/// </summary>
private readonly int Iteration;
#endregion
/// <summary>
/// This procedure contains the user code. Input parameters are provided as regular arguments,
/// Output parameters as ref arguments. You don't have to assign output parameters,
/// they will have a default value.
/// </summary>
private void RunScript(object face, object y, ref object A)
{
//Face face = x as Face;
var doc = Revit.ActiveDBDocument;
RVT.Face refFace = (face as RVT.Face);
IList<RVT.CurveLoop> cl = refFace.GetEdgesAsCurveLoops();
/*
RVT.Face planeSurface = face as RVT.Face;
RVT.XYZ origin = planeSurface.ComputeNormal(new RVT.UV(0, 0));
RVT.Transform transf = planeSurface.ComputeDerivatives(new RVT.UV(0, 0));
RVT.XYZ XVec = transf.BasisX;
RVT.XYZ YVec = transf.BasisY;
RVT.XYZ ZVec = transf.BasisZ;
var plane = new Rhino.Geometry.Plane(ToRhino(ZVec), (Vector3d) ToRhino(XVec), (Vector3d) ToRhino(YVec));
*/
List<LineCurve> result = new List<LineCurve>();
foreach (var l in cl[0]){
RVT.Line la = l as RVT.Line;
result.Add(ToRhino(la));
}
A = result;
//A = face.ComputeNormal(new UV(0.5, 0.5));
}
// <Custom additional code>
static public Point3d ToRhino(RVT.XYZ p){
double scale = 304.8;
return new Point3d(p.X * scale, p.Y * scale, p.Z * scale);
}
static public Rhino.Geometry.LineCurve ToRhino (RVT.Line line){
double scale = 304.8;
return line.IsBound ? new Rhino.Geometry.LineCurve(line.GetEndPoint(0).ToRhino() * scale, line.GetEndPoint(1).ToRhino() * scale) : null;
}
// </Custom additional code>
}
import clr
clr.AddReference('System.Core')
from System.Linq import Enumerable
from System.IO import Path, File
clr.AddReference('RhinoInside.Revit')
from Rhino.Geometry import *
from RhinoInside.Revit import Revit, Convert
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Structure import *
clr.AddReference('System')
from System.Collections.Generic import List
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
import sys
sys.path.append(r'C:\Program Files (x86)\IronPython 2.7\Lib')
import os
doc = Revit.ActiveDBDocument
app = doc.Application
#a = "Walls" in x
RevitCategories = [c for c in doc.Settings.Categories if c.Name in x]
import clr
clr.AddReference('System.Core')
from System.Linq import Enumerable
from System.IO import Path, File
clr.AddReference('RhinoInside.Revit')
from Rhino.Geometry import *
from RhinoInside.Revit import Revit, Convert
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Structure import *
clr.AddReference('System')
from System.Collections.Generic import List
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
import sys
sys.path.append(r'C:\Program Files (x86)\IronPython 2.7\Lib')
import os
doc = Revit.ActiveDBDocument
app = doc.Application
cats = app.Create.NewCategorySet()
# Add Categories to Category Set.
for cat in RevitCategories:
cats.Insert(cat)
#cats.Insert(doc.Settings.Categories.get_Item(BuiltInCategory.OST_Walls))
#get the parameter file
sharedParameterFile = doc.Application.SharedParametersFilename;
tempSharedParameterFile = r"C:\Temp\tempSharedParam.txt";
if not os.path.isfile(tempSharedParameterFile):
open(tempSharedParameterFile, 'w').close()
app.SharedParametersFilename = tempSharedParameterFile;
createdReport = []
with Transaction(doc, "Create Parameters") as trans:
trans.Start()
try:
groupName = app.OpenSharedParameterFile().Groups.Create("Data")
for name in ParameterNames:
externalDefinition = groupName.Definitions.Create(ExternalDefinitionCreationOptions(name, ParameterType.Text))
# Create the new shared parameter
newInstanceBinding = app.Create.NewInstanceBinding(cats)
# insert the new parameter into your project.
doc.ParameterBindings.Insert(externalDefinition, newInstanceBinding, BuiltInParameterGroup.PG_DATA)
createdReport.append(name)
except:
import traceback
errors = traceback.format_exc()
finally:
app.SharedParametersFilename = sharedParameterFile;
trans.Commit()
# set back original shared paramter.
File.Delete(tempSharedParameterFile);
Created = createdReport
private void RunScript(object CurveLoop, Vector3d ExtrusionVector, int MaterialId, ref object A)
{
var doc = Revit.ActiveDBDocument;
int matId = MaterialId;
rvt.XYZ extrusionDirection = ExtrusionVector.ToHost();
Rhino.Geometry.Curve boundary = CurveLoop as Rhino.Geometry.Curve;
var boundaryLoop = boundary.ToHost().ToCurveLoop();
List<rvt.CurveLoop> loopList = new List<rvt.CurveLoop>();
loopList.Add(boundaryLoop);
double height = 20;
rvt.SolidOptions solidOptions = new rvt.SolidOptions(rvt.ElementId.InvalidElementId, rvt.ElementId.InvalidElementId);
solidOptions.MaterialId = new rvt.ElementId(matId);
rvt.Solid box = rvt.GeometryCreationUtilities
.CreateExtrusionGeometry(loopList, extrusionDirection,
height, solidOptions);
rvt.DirectShape ds = null;
using (rvt.Transaction t = new rvt.Transaction(doc, "Add direct shape"))
{
t.Start();
ds = rvt.DirectShape.CreateElement(doc, new rvt.ElementId(rvt.BuiltInCategory.OST_Walls));
ds.SetShape(new rvt.GeometryObject[] { box });
t.Commit();
}
A = ds;
}
import clr
clr.AddReference('System.Core')
from System.Linq import Enumerable
from System.IO import Path, File
clr.AddReference('RhinoInside.Revit')
from Rhino.Geometry import *
from RhinoInside.Revit import Revit, Convert
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Structure import *
clr.AddReference('System')
from System.Collections.Generic import List
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
import sys
sys.path.append(r'C:\Program Files (x86)\IronPython 2.7\Lib')
import os
doc = Revit.ActiveDBDocument
app = doc.Application
builtInCats = List[ElementId]()
for c in doc.Settings.Categories:
if c.Name in x:
builtInCats.Add(c.Id)
categoryFilter = ElementMulticategoryFilter(builtInCats);
ids = FilteredElementCollector(doc).WherePasses(categoryFilter).WhereElementIsNotElementType().ToElements();
#a = "Walls" in x
Elements = ids
import clr
clr.AddReference('System.Core')
from System.Linq import Enumerable
from System.IO import Path, File
clr.AddReference('RhinoInside.Revit')
from Rhino.Geometry import *
from RhinoInside.Revit import Revit, Convert
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Structure import *
clr.AddReference('System')
from System.Collections.Generic import List
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
import sys
sys.path.append(r'C:\Program Files (x86)\IronPython 2.7\Lib')
import os
doc = Revit.ActiveDBDocument
app = doc.Application
builtInCats = List[ElementId]()
indexes = []
for c in doc.Settings.Categories:
if c.Name in x:
builtInCats.Add(c.Id)
categoryFilter = ElementMulticategoryFilter(builtInCats);
ids = FilteredElementCollector(doc).WherePasses(categoryFilter).WhereElementIsNotElementType().ToElements();
for i in ids:
indexes.append(x.IndexOf(i.Category.Name))
#a = "Walls" in x
Elements = ids
Indexes = indexes
var doc = Revit.ActiveDBDocument;
Dictionary<Floor, List<ModelCurve>> dict_SketchLines = new Dictionary<Floor, List<ModelCurve>>();
Element floorElement = floorElementIn as Element;
Floor floor = floorElement as Floor;
List<ElementId> _deleted = null;
using (Transaction t = new Transaction(doc, "Get Outlines"))
{
t.Start();
_deleted = doc.Delete(floor.Id).ToList();
t.RollBack();
}
/*
List<ModelCurve> _sketchCurves = new List<ModelCurve>();
List<ModelCurve> sketch_geo = new List<ModelCurve>();
Sketch sketch = null;
List <Rhino.Geometry.Curve> rh_sketch_curves = new List<Rhino.Geometry.Curve>();
foreach (var id in _deleted)
{
Element ele = doc.GetElement(id);
Print(ele.ToString());
// find modelcurves. these are the lines in the bounderysketch
if (ele is Sketch)
{
sketch = ele as Sketch;
SketchPlane sketch_plane = sketch.SketchPlane;
CurveArrArray crv_arrarray = sketch.Profile as CurveArrArray;
foreach (var crvarr in crv_arrarray)
{
CurveArray crv_array = crvarr as CurveArray;
List <Rhino.Geometry.Curve> rh_sk_curves = new List<Rhino.Geometry.Curve>();
Rhino.Geometry.Curve[] poly = null;
foreach (Autodesk.Revit.DB.Curve crv in crv_array)
{
//Rhino.Geometry.Curve rh_sk_curve = RhinoInside.Revit.Convert.ToRhino(crv);
Rhino.Geometry.Curve rh_sk_curve = RhinoInside.Revit.Convert.Geometry.GeometryDecoder.ToCurve(crv);
//RhinoInside.Revit.Convert.Geometry.Raw.
rh_sk_curves.Add(rh_sk_curve);
}
poly = Rhino.Geometry.Curve.JoinCurves(rh_sk_curves);
foreach (var p in poly)
{
rh_sketch_curves.Add(p);
}
}
}
}
rhino_sketch_curves = rh_sketch_curves;
// TaskDialog.Show("Result", sb.ToString());
*/
"""Provides a scripting component.
Inputs:
x: The x script variable
y: The y script variable
Output:
a: The a output variable"""
__author__ = "Giovanni.Brogiolo"
__version__ = "2021.04.20"
import rhinoscriptsyntax as rs
import itertools
import Grasshopper as gh
import traceback
#https://discourse.mcneel.com/t/outputting-a-nested-python-list-as-tree/48188/2
def listToTree(nestedList):
""" Convert a nested python iterable to a datatree """
dt = gh.DataTree[object]()
for i,l in enumerate(nestedList):
dt.AddRange(l,gh.Kernel.Data.GH_Path(i))
return dt
elements = []
uniqueMaterials = []
materials = []
counter = 0
for item in allElements:
try:
param = item.LookupParameter(CarbonParameter)
if param != None:
value = param.AsString()
if value != None:
print(item.Id)
print(value)
if value in uniqueMaterials:
materials[uniqueMaterials.index(value)].append(value)
elements[uniqueMaterials.index(value)].append(item)
else:
uniqueMaterials.append(value)
materials.append([])
materials[counter].append(value)
elements.append([])
elements[counter].append(item)
counter += 1
except:
print(traceback.format_exc())
RevitElements = listToTree(elements)
CarbonMaterial = listToTree(materials)
print (uniqueMaterials)
print (counter)
print (materials)
import rhinoscriptsyntax as rs
from RhinoInside.Revit import Revit, Convert
from Autodesk.Revit import DB
doc = Revit.ActiveDBDocument
a = DB.FilteredElementCollector(doc, doc.ActiveView.Id).ToElements()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using Grasshopper.Kernel;
using Autodesk.Revit.DB;
namespace RhinoInside.Revit.GH.Components
{
public class LineByStartEndPoint : GH_TransactionalComponentItem
{
public override Guid ComponentGuid => new Guid("6ACFB3CC-BE34-4246-9A34-528B69825002");
public override GH_Exposure Exposure => GH_Exposure.primary;
protected override System.Drawing.Bitmap Icon => ImageBuilder.BuildIcon("L");
public LineByStartEndPoint() : base
(
"Line.ByEndPoints", "ByStartEndPoint",
"Create a Line by start and end point",
"Revit", "Build"
)
{ }
protected override void RegisterInputParams(GH_InputParamManager manager)
{
manager.AddCurveParameter("Line", "A", string.Empty, GH_ParamAccess.item);
manager.AddPlaneParameter("Plane", "P", string.Empty, GH_ParamAccess.item);
}
protected override void RegisterOutputParams(GH_OutputParamManager manager)
{
manager.AddParameter(new Parameters.Element(), "Line", "L", "New Line", GH_ParamAccess.item);
}
protected override void SolveInstance(IGH_DataAccess DA)
{
Rhino.Geometry.Curve axis = null;
DA.GetData("Line", ref axis);
Rhino.Geometry.Plane rhinoSketchPlane = new Rhino.Geometry.Plane();
DA.GetData("Plane", ref rhinoSketchPlane);
DA.DisableGapLogic();
int Iteration = DA.Iteration;
Revit.EnqueueAction((doc) => CommitInstance(doc, DA, Iteration, axis, rhinoSketchPlane));
}
void CommitInstance
(
Document doc, IGH_DataAccess DA, int Iteration, Rhino.Geometry.Curve curve, Rhino.Geometry.Plane rhinoPlane
)
{
var element = PreviousElement(doc, Iteration);
var revitCurve = curve;
try
{
var scaleFactor = 1.0 / Revit.ModelUnits;
if (scaleFactor != 1.0)
{
rhinoPlane = rhinoPlane.Scale(scaleFactor);
revitCurve?.Scale(scaleFactor);
}
var axisList = revitCurve.ToHost().ToList();
SketchPlane revitSketchPlane = SketchPlane.Create(doc, rhinoPlane.ToHost());
//SketchPlane revitSketchPlane = SketchPlane.Create(doc, rhinoPlane.ToHost());
element = doc.Create.NewModelCurve(axisList[0], revitSketchPlane);
}
catch (Exception e)
{
AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
}
finally
{
ReplaceElement(doc, DA, Iteration, element);
}
}
}
}
private void RunScript(object RevitElement, int MaterialId, ref object A)
{
var doc = Revit.ActiveDBDocument;
int matId = MaterialId;
rvt.ElementId materialId = new rvt.ElementId(matId);
rvt.Element selectedElement = RevitElement as rvt.Element;
Autodesk.Revit.DB.Options opt = new rvt.Options();
Autodesk.Revit.DB.GeometryElement geomElem = selectedElement.get_Geometry(opt);
rvt.Solid geomSolid = null;
foreach (rvt.GeometryObject geomObj in geomElem)
{
geomSolid = geomObj as rvt.Solid;
}
using (rvt.Transaction t = new rvt.Transaction(doc, "Change element color"))
{
t.Start();
foreach (rvt.Face geomFace in geomSolid.Faces)
{
doc.Paint(selectedElement.Id, geomFace, materialId);
}
t.Commit();
}
A = "Success";
}
import clr
clr.AddReference('System.Core')
from System.Linq import Enumerable
from System.IO import Path, File
clr.AddReference('RhinoInside.Revit')
from Rhino.Geometry import *
from RhinoInside.Revit import Revit, Convert
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Structure import *
clr.AddReference('System')
from System.Collections.Generic import List
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = Revit.ActiveDBDocument
app = doc.Application
done = 0
error = []
report = []
with Transaction(doc, "Set Parameters") as trans:
trans.Start()
for e in elements:
try:
for name,value in zip(paramNames, paramValues):
try:
param = e.LookupParameter(name)
param.Set(value)
except:
continue
done += 1
except:
import traceback
error.append(e.Id)
report.append(traceback.format_exc())
trans.Commit()
updated = done
errors = error
reports = report
using SpeckleCoreGeometryClasses;
using SpeckleCoreGeometryRevit;
using SpeckleElements;
using SpeckleElementsRevit;
using Autodesk.Revit.DB;
/// <summary>
/// This procedure contains the user code. Input parameters are provided as regular arguments,
/// Output parameters as ref arguments. You don't have to assign output parameters,
/// they will have a default value.
/// </summary>
private void RunScript(object x, object y, ref object A)
{
//var spkShaft = new SpeckleElements.Shaft();
XYZ revitPt = new XYZ(50, 32, 45);
XYZ revitEndPt = new XYZ(0, 0, 0);
//SpecklePoint spePt = SpeckleCoreGeometryRevit.Conversions.ToSpeckle(revitPt);
SpecklePoint spePta = MyToSpeckle(revitPt);
SpecklePoint endPt = MyToSpeckle(revitEndPt);
SpeckleLine sline = new SpeckleLine(){ Value = new List<double>() };
sline.Value.AddRange(spePta.Value);
sline.Value.AddRange(endPt.Value);
A = sline;
}
// <Custom additional code>
public static SpecklePoint MyToSpeckle(Autodesk.Revit.DB.XYZ pt)
{
double Scale = 1;
return new SpecklePoint(pt.X / Scale, pt.Y / Scale, pt.Z / Scale, null, null);
}
public static SpeckleLine ToSpeckle(Autodesk.Revit.DB.Line line)
{
SpeckleLine speckleLine = new SpeckleLine
{
Value = new List<double>()
};
speckleLine.Value.AddRange(line.GetEndPoint(0).ToSpeckle().Value);
speckleLine.Value.AddRange(line.GetEndPoint(1).ToSpeckle().Value);
speckleLine.GenerateHash();
return speckleLine;
}
// </Custom additional code>
}
using System;
using System.Collections;
using System.Collections.Generic;
using Rhino;
using Rhino.Geometry;
using Grasshopper;
using Grasshopper.Kernel;
using Grasshopper.Kernel.Data;
using Grasshopper.Kernel.Types;
using System.IO;
using System.Linq;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.Runtime.InteropServices;
using Rhino.DocObjects;
using Rhino.Collections;
using GH_IO;
using GH_IO.Serialization;
using SpeckleCore;
using SpeckleCoreGeometryRhino;
// No namespaces could be found for 'C:\Users\giovanni.brogiolo\source\repos\SpeckleCoreGeometry\SpeckleCoreGeometry\bin\Debug\SpeckleCoreGeometry.dll'
using SpeckleCoreGeometryClasses;
/// <summary>
/// This class will be instantiated on demand by the Script component.
/// </summary>
public class Script_Instance : GH_ScriptInstance
{
#region Utility functions
/// <summary>Print a String to the [Out] Parameter of the Script component.</summary>
/// <param name="text">String to print.</param>
private void Print(string text) { /* Implementation hidden. */ }
/// <summary>Print a formatted String to the [Out] Parameter of the Script component.</summary>
/// <param name="format">String format.</param>
/// <param name="args">Formatting parameters.</param>
private void Print(string format, params object[] args) { /* Implementation hidden. */ }
/// <summary>Print useful information about an object instance to the [Out] Parameter of the Script component. </summary>
/// <param name="obj">Object instance to parse.</param>
private void Reflect(object obj) { /* Implementation hidden. */ }
/// <summary>Print the signatures of all the overloads of a specific method to the [Out] Parameter of the Script component. </summary>
/// <param name="obj">Object instance to parse.</param>
private void Reflect(object obj, string method_name) { /* Implementation hidden. */ }
#endregion
#region Members
/// <summary>Gets the current Rhino document.</summary>
private readonly RhinoDoc RhinoDocument;
/// <summary>Gets the Grasshopper document that owns this script.</summary>
private readonly GH_Document GrasshopperDocument;
/// <summary>Gets the Grasshopper script component that owns this script.</summary>
private readonly IGH_Component Component;
/// <summary>
/// Gets the current iteration count. The first call to RunScript() is associated with Iteration==0.
/// Any subsequent call within the same solution will increment the Iteration count.
/// </summary>
private readonly int Iteration;
#endregion
/// <summary>
/// This procedure contains the user code. Input parameters are provided as regular arguments,
/// Output parameters as ref arguments. You don't have to assign output parameters,
/// they will have a default value.
/// </summary>
private void RunScript(List<object> x, object y, ref object A)
{
List<Mesh> lm = new List<Mesh>();
foreach (SpeckleMesh mesh in x){
lm.Add(MeshConverter(mesh));
}
A = lm;
}
// <Custom additional code>
static public Mesh MeshConverter(SpeckleMesh mesh){
Mesh m = new Mesh();
m.Vertices.AddVertices(mesh.Vertices.ToPoints());
int i = 0;
while ( i < mesh.Faces.Count )
{
if ( mesh.Faces[i] == 0 )
{ // triangle
m.Faces.AddFace(new MeshFace(mesh.Faces[i + 1], mesh.Faces[i + 2], mesh.Faces[i + 3]));
i += 4;
}
else
{ // quad
m.Faces.AddFace(new MeshFace(mesh.Faces[i + 1], mesh.Faces[i + 2], mesh.Faces[i + 3], mesh.Faces[i + 4]));
i += 5;
}
}
try
{
m.VertexColors.AppendColors(mesh.Colors.Select(c => System.Drawing.Color.FromArgb((int) c)).ToArray());
}
catch { }
if ( mesh.TextureCoordinates != null )
for ( int j = 0; j < mesh.TextureCoordinates.Count; j += 2 )
{
m.TextureCoordinates.Add(mesh.TextureCoordinates[j], mesh.TextureCoordinates[j + 1]);
}
m.UserDictionary.ReplaceContentsWith(mesh.Properties.ToNative());
return m;
}
// </Custom additional code>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment