public static DirectShape CreateRoomDirectShape(Room room) { DirectShape roomShape = null; try { List <GeometryObject> geoList = new List <GeometryObject>(); var solidGeometries = from geoObj in room.ClosedShell where geoObj.GetType() == typeof(Solid) && (geoObj as Solid).Volume != 0 select geoObj; if (solidGeometries.Any()) { geoList = solidGeometries.ToList(); } ElementId categoryId = new ElementId((int)BuiltInCategory.OST_Mass); if (DirectShape.IsValidCategoryId(categoryId, room.Document)) { #if RELEASE2015 || RELEASE2016 roomShape = DirectShape.CreateElement(room.Document, categoryId, "Measure", room.UniqueId); #else roomShape = DirectShape.CreateElement(room.Document, categoryId); #endif } roomShape.SetShape(geoList); } catch (Exception ex) { string message = ex.Message; } return(roomShape); }
/// <summary> /// Creates a new DirectShape. /// </summary> /// <param name="doc"></param> /// <param name="parm"></param> /// <param name="opt"></param> /// <returns></returns> public static DirectShape CreateDirectShape(this Document doc, DirectShapeParameter parm, SolidOptions opt = null) { if (doc is null) { throw new ArgumentNullException(nameof(doc)); } if (parm is null) { throw new ArgumentNullException(nameof(parm)); } var solid = CreateExtrusionGeometry(parm.Profile.ToList(), parm.Direction, parm.Distance); if (opt != null) { solid = CreateExtrusionGeometry(parm.Profile.ToList(), parm.Direction, parm.Distance, opt); } var result = DirectShape.CreateElement(doc, new ElementId(parm.Category)); result?.AppendShape(new List <GeometryObject> { solid }); return(result); }
public Result Execute(ExternalCommandData data, ref string message, ElementSet elements) { // RhinoCommon code var sphere = new Sphere(Point3d.Origin, 12 * Revit.ModelUnits); var brep = sphere.ToBrep(); var mp = MeshingParameters.Default; mp.MinimumEdgeLength = Revit.VertexTolerance; var meshes = Rhino.Geometry.Mesh.CreateFromBrep(brep, mp); // Revit code var uiApp = data.Application; var doc = uiApp.ActiveUIDocument.Document; using (var trans = new Transaction(doc)) { if (trans.Start(MethodBase.GetCurrentMethod().DeclaringType.Name) == TransactionStatus.Started) { var categoryId = new ElementId(BuiltInCategory.OST_GenericModel); var ds = DirectShape.CreateElement(doc, categoryId); ds.Name = "Sphere"; foreach (var geometryList in meshes.ToHost().ToList()) { ds.AppendShape(geometryList); } trans.Commit(); } } return(Result.Succeeded); }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { var uiapp = commandData.Application; var uidoc = uiapp.ActiveUIDocument; var doc = uidoc.Document; const double scale = 0.2; const double length = 4.0 * Math.PI; const int steps = 8; var profile = CreateProfile(scale); var profiles = Enumerable .Range(0, steps + 1) .Select(x => x * length / steps) .Select(CreateSinusTransform) .Select(x => profile.CreateTransformed(x)) .ToList(); using (var transaction = new Transaction(doc, "create loft form with sinus path")) { transaction.Start(); var solid = GeometryCreationUtilities.CreateLoftGeometry(profiles, new SolidOptions(ElementId.InvalidElementId, ElementId.InvalidElementId)); var directShape = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)); directShape.AppendShape(new GeometryObject[] { solid }); transaction.Commit(); } return(Result.Succeeded); }
/// <summary> /// Implement this method as an external command for Revit. /// </summary> /// <param name="commandData">An object that is passed to the external application /// which contains data related to the command, /// such as the application object and active view.</param> /// <param name="message">A message that can be set by the external application /// which will be displayed if a failure or cancellation is returned by /// the external command.</param> /// <param name="elements">A set of elements to which the external application /// can add elements that are to be highlighted in case of failure or cancellation.</param> /// <returns>Return the status of the external command. /// A result of Succeeded means that the API external method functioned as expected. /// Cancelled can be used to signify that the user canceled the external operation /// at some point. Failure should be returned if the application is unable to proceed with /// the operation.</returns> public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { _dbdocument = commandData.Application.ActiveUIDocument.Document; try { using (Autodesk.Revit.DB.Transaction tr = new Autodesk.Revit.DB.Transaction(_dbdocument, "CreateNURBS")) { tr.Start(); DirectShape myDirectShape = DirectShape.CreateElement(_dbdocument, new ElementId(BuiltInCategory.OST_GenericModel)); myDirectShape.ApplicationId = "TestCreateNURBS"; myDirectShape.ApplicationDataId = "NURBS"; if (null != myDirectShape) { myDirectShape.SetShape(CreateNurbsSurface()); } tr.Commit(); } } catch (Exception ex) { message = ex.Message; return(Result.Failed); } return(Result.Succeeded); }
//https://thebuildingcoder.typepad.com/blog/2012/09/sphere-creation-for-avf-and-filtering.html public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; Solid s1 = Command.CreateSphereAt(new XYZ(0, 0, 15), 15); Solid s2 = Command.CreateSphereAt(new XYZ(0, 0, 32.5), 10); Solid s3 = Command.CreateSphereAt(new XYZ(0, 0, 47.5), 5); Transaction buildASnowman = new Transaction(doc, "Build a Snowman"); buildASnowman.Start(); var ds1 = DirectShape.CreateElement(doc, new ElementId(-2000151)); ds1.SetShape(new GeometryObject[] { s1, s2, s3 }); buildASnowman.Commit(); return(Result.Succeeded); }
public static void CreateSphereDirectShape(Document doc, XYZ center, float radius, string name) { List <Curve> profile = new List <Curve>(); // first create sphere with 2' radius XYZ profile00 = center; XYZ profilePlus = center + new XYZ(0, radius, 0); XYZ profileMinus = center - new XYZ(0, radius, 0); profile.Add(Line.CreateBound(profilePlus, profileMinus)); profile.Add(Arc.Create(profileMinus, profilePlus, center + new XYZ(radius, 0, 0))); CurveLoop curveLoop = CurveLoop.Create(profile); SolidOptions options = new SolidOptions(ElementId.InvalidElementId, ElementId.InvalidElementId); Frame frame = new Frame(center, XYZ.BasisX, -XYZ.BasisZ, XYZ.BasisY); Solid sphere = GeometryCreationUtilities.CreateRevolvedGeometry(frame, new CurveLoop[] { curveLoop }, 0, 2 * Math.PI, options); using (Transaction t = new Transaction(doc, "Create sphere direct shape")) { t.Start(); DirectShape ds = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)); ds.SetShape(new GeometryObject[] { sphere }); ds.Name = name; t.Commit(); } }
// Create a DirectShape Sphere static public void CreateSphereDirectShape(Document doc) { List <Curve> profile = new List <Curve>(); // first create sphere with 2' radius XYZ center = XYZ.Zero; double radius = 2.0; //XYZ profile00 = center; XYZ profilePlus = center + new XYZ(0, radius, 0); XYZ profileMinus = center - new XYZ(0, radius, 0); profile.Add(Line.CreateBound(profilePlus, profileMinus)); profile.Add(Arc.Create(profileMinus, profilePlus, center + new XYZ(radius, 0, 0))); CurveLoop curveLoop = CurveLoop.Create(profile); SolidOptions options = new SolidOptions(ElementId.InvalidElementId, ElementId.InvalidElementId); Frame frame = new Frame(center, XYZ.BasisX, -XYZ.BasisZ, XYZ.BasisY); if (Frame.CanDefineRevitGeometry(frame) == true) { Solid sphere = GeometryCreationUtilities.CreateRevolvedGeometry(frame, new CurveLoop[] { curveLoop }, 0, 2 * Math.PI, options); using (Transaction t = new Transaction(doc, "Create sphere direct shape")) { t.Start(); // create direct shape and assign the sphere shape DirectShape ds = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)); ds.ApplicationId = "Application id"; ds.ApplicationDataId = "Geometry object id"; ds.SetShape(new GeometryObject[] { sphere }); t.Commit(); } } }
public override Result Execute(ExternalCommandData data, ref string message, ElementSet elements) { // RhinoCommon code var sphere = new Sphere(Point3d.Origin, 12 * Revit.ModelUnits); var brep = sphere.ToBrep(); var meshes = Rhino.Geometry.Mesh.CreateFromBrep(brep, MeshingParameters.Default); // Revit code var uiApp = data.Application; var doc = uiApp.ActiveUIDocument.Document; using (var trans = new Transaction(doc, MethodBase.GetCurrentMethod().DeclaringType.FullName)) { if (trans.Start() == TransactionStatus.Started) { var categoryId = new ElementId(BuiltInCategory.OST_GenericModel); var ds = DirectShape.CreateElement(doc, categoryId); ds.Name = "Sphere"; foreach (var shape in meshes.ConvertAll(ShapeEncoder.ToShape)) { if (shape?.Length > 0) { ds.AppendShape(shape); } } trans.Commit(); } } return(Result.Succeeded); }
public static DirectShape CreateDirectShape( Document doc, Solid transientSolid, string dsName) { ElementId catId = new ElementId( BuiltInCategory.OST_GenericModel); AddInId addInId = doc.Application.ActiveAddInId; DirectShape ds = DirectShape.CreateElement(doc, catId, addInId.GetGUID().ToString(), ""); if (ds.IsValidGeometry(transientSolid)) { ds.SetShape(new GeometryObject[] { transientSolid }); } else { TessellatedShapeBuilderResult result = GetTessellatedSolid(doc, transientSolid); ds.SetShape(result.GetGeometricalObjects()); } ds.Name = dsName; return(ds); }
/// <summary> /// Create a DirectShape, and set its options accordingly. /// </summary> /// <param name="doc">The document.</param> /// <param name="categoryId">The category of the DirectShape.</param> /// <param name="dataGUID">The GUID of the data creating the DirectShape.</param> /// <param name="geomObjs">The list of geometries to add to the DirectShape.</param> /// <param name="id">The id of the IFCEntity object creating the DirectShape.</param> /// <returns>The DirectShape.</returns> static public DirectShape CreateElement(Document doc, ElementId categoryId, string dataGUID, IList <GeometryObject> geomObjs, int id) { string appGUID = Importer.ImportAppGUID(); DirectShape directShape = DirectShape.CreateElement(doc, GetDSValidCategoryId(doc, categoryId, id)); directShape.ApplicationId = appGUID; directShape.ApplicationDataId = dataGUID; // Note: we use the standard options for the DirectShape that is created. This includes but is not limited to: // Referenceable: true. // Room Bounding: if applicable, user settable. if (IFCImportFile.TheFile.Options.UseStreamlinedOptions) { // Disable referencing for performance purposes. DirectShapeOptions options = directShape.GetOptions(); options.ReferencingOption = DirectShapeReferencingOption.NotReferenceable; directShape.SetOptions(options); } if (directShape != null && geomObjs != null) { directShape.SetShape(geomObjs); } return(directShape); }
/// <summary> /// need open transaction. /// </summary> public static void CreateDirectShape(this Document _doc, IEnumerable <GeometryObject> _geometry, XYZ _translation) { DirectShape ds = DirectShape.CreateElement(_doc, new ElementId(BuiltInCategory.OST_GenericModel)); ds.SetShape(_geometry.ToList()); ElementTransformUtils.MoveElement(ds.Document, ds.Id, _translation); }
void ReconstructDirectShapeByPoint ( Document doc, ref Autodesk.Revit.DB.Element element, Rhino.Geometry.Point3d point ) { var scaleFactor = 1.0 / Revit.ModelUnits; ThrowIfNotValid(nameof(point), point); if (element is DirectShape ds) { } else { ds = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)); } ds.SetShape(new List <GeometryObject> { Point.Create((point * scaleFactor).ToHost()) }); ReplaceElement(ref element, ds); }
private bool CreateRoomMass(SpatialElement room) { if (!SpatialElementGeometryCalculator.CanCalculateGeometry(room)) { return(false); } try { SpatialElementGeometryResults results; using (var calculator = new SpatialElementGeometryCalculator(doc)) { results = calculator.CalculateSpatialElementGeometry(room); } using (Solid roomSolid = results.GetGeometry()) { var eid = new ElementId(BuiltInCategory.OST_Mass); DirectShape roomShape = DirectShape.CreateElement(doc, eid); if (roomShape != null && roomSolid.Volume > 0 && roomSolid.Faces.Size > 0) { var geomObj = new GeometryObject[] { roomSolid }; if (geomObj.Length > 0) { roomShape.SetShape(geomObj); CopyAllRoomParametersToMasses(room, roomShape); return(true); } } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } return(false); }
void CommitInstance ( Document doc, IGH_DataAccess DA, int Iteration, Rhino.Geometry.Mesh mesh ) { var element = PreviousElement(doc, Iteration); try { if (mesh == null) { throw new NullReferenceException($"Parameter '{Params.Input[0].Name}' not set to an instance of a Mesh."); } if (!mesh.IsValidWithLog(out var log)) { foreach (var line in log.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries)) { AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, line); } throw new Exception($"Parameter '{Params.Input[0].Name}' not set to a valid Mesh."); } var scaleFactor = 1.0 / Revit.ModelUnits; if (scaleFactor != 1.0) { mesh.Scale(scaleFactor); } var shape = new List <GeometryObject>(); foreach (var geometry in mesh.ToHost().SelectMany(x => x.ToDirectShapeGeometry())) { // DirectShape only accepts those types and no nulls switch (geometry) { case Point p: shape.Add(p); break; case Curve c: shape.Add(c); break; case Solid s: shape.Add(s); break; case Mesh m: shape.Add(m); break; } } var ds = element as DirectShape ?? CopyParametersFrom(DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)), element); ds.SetShape(shape); element = ds; ReplaceElement(doc, DA, Iteration, element); } catch (Exception e) { AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message); ReplaceElement(doc, DA, Iteration, null); } }
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { Document doc = commandData.Application.ActiveUIDocument.Document; Solid box = Box(); Solid sphere = Sphere(); Solid unionSolid = BooleanOperationsUtils.ExecuteBooleanOperation(box, sphere, BooleanOperationsType.Union); Solid intersectSolid = BooleanOperationsUtils.ExecuteBooleanOperation(box, sphere, BooleanOperationsType.Intersect); Solid diffSolid = BooleanOperationsUtils.ExecuteBooleanOperation(box, sphere, BooleanOperationsType.Difference); //Use DirectShape to visualise geometries using (Transaction t = new Transaction(doc, "Transaction")) { t.Start(); GeometryObject[] unionGeomObj = new GeometryObject[] { unionSolid }; GeometryObject[] interGeomObj = new GeometryObject[] { intersectSolid }; GeometryObject[] diffGeomObj = new GeometryObject[] { diffSolid }; DirectShape ds1 = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)); ds1.SetShape(unionGeomObj); DirectShape ds2 = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)); ds2.SetShape(interGeomObj); DirectShape ds3 = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)); ds3.SetShape(diffGeomObj); t.Commit(); } return(Result.Succeeded); }
/// <summary> /// 生成常规模型,记得开启事务!!! /// </summary> /// <param name="doc"></param> /// <param name="transientSolid"></param> /// <param name="isOpenTrans">是否在方法内部开启事务,如果为false,请手动在方法外部开启事务</param> /// <param name="dsName"></param> /// <returns></returns> /// <remarks>生成Solid不需要开启事务,但是DirectShape一定要开启事务</remarks> public static ElementId CreateDirectShape(Document doc, Solid transientSolid, bool isOpenTrans = false, String dsName = "") { ElementId catId = new ElementId(BuiltInCategory.OST_GenericModel); //常规模型 Transaction tr = null; if (isOpenTrans) { tr = new Transaction(doc, "DirectShape"); tr.Start(); //DirectShape ds = DirectShape.CreateElement(doc, catId); //SetShape(ds, transientSolid); //if (!String.IsNullOrEmpty(dsName)) // ds.Name = dsName; } // 需要开启事务 DirectShape ds = DirectShape.CreateElement(doc, catId); SetShape(ds, transientSolid); if (!String.IsNullOrEmpty(dsName)) { ds.Name = dsName; } tr?.Commit(); tr?.Dispose(); return(ds.Id); }
/// <summary> /// creates a DirectShape instance of which shape is Sphere. /// Sphere is defined by its center and radius. /// </summary> /// <param name="document">The Revit document where the instance to be drawn</param> /// <param name="name">The name of this instance</param> /// <param name="center">Position of the center</param> /// <param name="radius">Radius of the circle</param> /// <param name="line_color">Outline color of Circle</param> /// <param name="surface_transparency">Surface transparency; ranged from 0 (transparent) to 100 (opaque)</param> public DirectSphere(Document document, string name, XYZ center, double radius, Color line_color, int surface_transparency) : base(document, name) { m_shape_type = ShapeTypes.Sphere; Center = center; Radius = radius; XYZ top = center + radius * XYZ.BasisZ; XYZ bottom = center - radius * XYZ.BasisZ; XYZ right = center + radius * XYZ.BasisX; Frame frame = new Frame(center, XYZ.BasisX, XYZ.BasisY, XYZ.BasisZ); List <Curve> profile = new List <Curve>(); profile.Add(Line.CreateBound(top, bottom)); profile.Add(Arc.Create(bottom, top, right)); CurveLoop curve_loop = CurveLoop.Create(profile); SolidOptions options = new SolidOptions(ElementId.InvalidElementId, ElementId.InvalidElementId); if (Frame.CanDefineRevitGeometry(frame) == true) { Solid sphere = GeometryCreationUtilities.CreateRevolvedGeometry(frame, new CurveLoop[] { curve_loop }, 0, 2 * Math.PI, options); using (Transaction t = new Transaction(document, "Create sphere direct shape.")) { t.Start(); DirectShape shape = DirectShape.CreateElement(document, new ElementId(BuiltInCategory.OST_GenericModel)); shape.SetShape(new GeometryObject[] { sphere }); shape.SetName(name); m_element_id = shape.Id; document.ActiveView.SetElementOverrides(shape.Id, new OverrideGraphicSettings().SetProjectionLineColor(line_color).SetSurfaceTransparency(surface_transparency)); t.Commit(); } } }
void ReconstructDirectShapeByCurve ( Document doc, ref Autodesk.Revit.DB.Element element, Rhino.Geometry.Curve curve ) { var scaleFactor = 1.0 / Revit.ModelUnits; ThrowIfNotValid(nameof(curve), curve); if (element is DirectShape ds) { } else { ds = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)); } var shape = curve. ToHostMultiple(scaleFactor). SelectMany(x => x.ToDirectShapeGeometry()); ds.SetShape(shape.ToList()); ReplaceElement(ref element, ds); }
/// <summary> /// Create a DirectShape, and set its options accordingly. /// </summary> /// <param name="doc">The document.</param> /// <param name="categoryId">The category of the DirectShape.</param> /// <param name="dataGUID">The GUID of the data creating the DirectShape.</param> /// <param name="geomObjs">The list of geometries to add to the DirectShape.</param> /// <param name="id">The id of the IFCEntity object creating the DirectShape.</param> /// <returns>The DirectShape.</returns> static public DirectShape CreateElement(Document doc, ElementId categoryId, string dataGUID, IList <GeometryObject> geomObjs, int id, IFCEntityType entityType) { string appGUID = Importer.ImportAppGUID(); DirectShape directShape = DirectShape.CreateElement(doc, GetDSValidCategoryId(doc, categoryId, id)); directShape.ApplicationId = appGUID; directShape.ApplicationDataId = dataGUID; // Note: we use the standard options for the DirectShape that is created. This includes but is not limited to: // Referenceable: true. // Room Bounding: if applicable, user settable. if (IFCImportFile.TheFile.Options.UseStreamlinedOptions) { // Disable referencing for performance purposes. DirectShapeOptions options = directShape.GetOptions(); options.ReferencingOption = DirectShapeReferencingOption.NotReferenceable; directShape.SetOptions(options); } // This is used in some places to create something not related to an IFCEntity if (!Importer.TheProcessor.CreateOrUpdateElement(id, dataGUID, entityType.ToString(), categoryId.IntegerValue, geomObjs)) { if (geomObjs != null) { directShape?.SetShape(geomObjs); } } return(directShape); }
public void ProcessMultipleSAT() { List <ElementId> importIds = new List <ElementId>(); // create and set new SAT options SATImportOptions satOptions = new SATImportOptions(); satOptions.Placement = ImportPlacement.Origin; satOptions.ColorMode = ImportColorMode.BlackAndWhite; satOptions.Unit = ImportUnit.Millimeter; using (Transaction trans = new Transaction(m_doc, "UpdateSAT")) { trans.Start(); List <GeometryObject> geoObjList = new List <GeometryObject>(); DirectShape ds = null; ElementId currentId; try { currentId = m_doc.Import(@"B:\Rhino\OpenNURBS\v5_example_file.sat", satOptions, m_doc.ActiveView); importIds.Add(currentId); } catch (Exception) { currentId = ElementId.InvalidElementId; } // extract geometry from import instance ImportInstance ii = m_doc.GetElement(currentId) as ImportInstance; Options gOptions = new Options(); gOptions.ComputeReferences = true; GeometryElement geoElement = ii.get_Geometry(gOptions); // get solids from geometry element List <GeometryObject> tempGeoList = FindElementGeometry(geoElement); foreach (GeometryObject go in tempGeoList) { geoObjList.Add(go); } ds = DirectShape.CreateElement(m_doc, new ElementId((int)BuiltInCategory.OST_GenericModel)); ds.SetShape(geoObjList); // set the Direct Shape options DirectShapeOptions dsOptions = ds.GetOptions(); dsOptions.ReferencingOption = DirectShapeReferencingOption.Referenceable; ds.SetOptions(dsOptions); trans.Commit(); trans.Start("Delete Elements"); // clean up imported solids m_doc.Delete(importIds); trans.Commit(); } }
/***************************************************/ /**** Public Methods ****/ /***************************************************/ public static Element ToRevitElement(this ModelInstance modelInstance, Document document, RevitSettings settings = null, Dictionary <Guid, List <int> > refObjects = null) { if (modelInstance == null || document == null) { return(null); } Element element = refObjects.GetValue <Element>(document, modelInstance.BHoM_Guid); if (element != null) { return(element); } if (modelInstance.Properties == null) { Compute.NullObjectPropertiesWarning(modelInstance); return(null); } settings = settings.DefaultIfNull(); BuiltInCategory builtInCategory = modelInstance.BuiltInCategory(document); if (modelInstance.Location is ISurface || modelInstance.Location is ISolid) { Solid brep = ToRevit(modelInstance.Location as dynamic); if (brep == null) { Compute.GeometryConvertFailed(modelInstance); return(null); } DirectShape directShape = DirectShape.CreateElement(document, new ElementId((int)builtInCategory)); directShape.AppendShape(new List <GeometryObject> { brep }); element = directShape; } else { ElementType elementType = modelInstance.Properties.ElementType(document, new List <BuiltInCategory> { builtInCategory }, settings); element = modelInstance.IToRevitElement(elementType, settings); } if (element == null) { return(null); } // Copy parameters from BHoM object to Revit element element.CopyParameters(modelInstance, settings); refObjects.AddOrReplace(modelInstance, element); return(element); }
/// <summary> /// creates a DirectShape instance of which shape is a part of a torus (like elbow joint pipe). /// Torus is defined by center, axis, tube radius, and mean radius (the distance between center and tube center). /// The tube_begin and tube_end defines the angle between the two edges of the piece. /// </summary> /// <param name="document">The Revit document where the instance to be drawn</param> /// <param name="name">The name of this instance</param> /// <param name="center">Position of center of the torus' hole</param> /// <param name="axis">Vector passing through the center</param> /// <param name="mean_radius">The distance between torus center and its tube center</param> /// <param name="tube_radius">Radius of tube</param> /// <param name="tube_begin">The vector pointing to one of the torus' edge from its center</param> /// <param name="torus_angle">The angle between the tube begin and end</param> /// <param name="line_color">Outline color of the torus</param> /// <param name="surface_transparency">Surface transparency; ranged from 0 (transparent) to 100 (opaque)</param> public DirectTorus(Document document, string name, XYZ center, XYZ axis, double mean_radius, double tube_radius, XYZ tube_begin, double torus_angle, Color line_color, int surface_transparency) : base(document, name) { m_shape_type = ShapeTypes.Torus; Center = center; Axis = axis; MeanRadius = mean_radius; TubeRadius = tube_radius; HasAnElbow = true; TubeBegin = tube_begin; TubeAngle = torus_angle; XYZ tilting_axis = XYZ.BasisZ.CrossProduct(axis); double tilting_angle = FindSurfaceRevitPluginUtils.GetPositiveAngleBetween(XYZ.BasisZ, axis, tilting_axis); bool no_need_to_tilt = tilting_axis.IsAlmostEqualTo(XYZ.Zero); Transform tilting_torus = no_need_to_tilt ? Transform.Identity : Transform.CreateRotation(tilting_axis, tilting_angle); XYZ tilted_basis_x = tilting_torus.OfVector(XYZ.BasisX); // model space coordinates Frame frame = new Frame(XYZ.Zero, XYZ.BasisX, XYZ.BasisY, XYZ.BasisZ); XYZ model_tube_center = XYZ.BasisX * mean_radius; XYZ model_tube_top = model_tube_center + tube_radius * XYZ.BasisZ; XYZ model_tube_bottom = model_tube_center - tube_radius * XYZ.BasisZ; XYZ model_tube_outer = model_tube_center + tube_radius * XYZ.BasisX; XYZ model_tube_inner = model_tube_center - tube_radius * XYZ.BasisX; List <Curve> tube_circle = new List <Curve>(); tube_circle.Add(Arc.Create(model_tube_top, model_tube_bottom, model_tube_inner)); tube_circle.Add(Arc.Create(model_tube_bottom, model_tube_top, model_tube_outer)); CurveLoop curve_loop = CurveLoop.Create(tube_circle); SolidOptions options = new SolidOptions(ElementId.InvalidElementId, ElementId.InvalidElementId); if (Frame.CanDefineRevitGeometry(frame)) { Solid torus = GeometryCreationUtilities.CreateRevolvedGeometry(frame, new CurveLoop[] { curve_loop }, 0, torus_angle, options); using (Transaction t = new Transaction(document, "Create torus direct shape.")) { t.Start(); DirectShape shape = DirectShape.CreateElement(document, new ElementId(BuiltInCategory.OST_GenericModel)); shape.SetShape(new GeometryObject[] { torus }); shape.SetName(name); m_element_id = shape.Id; if (no_need_to_tilt == false) { shape.Location.Rotate(Line.CreateUnbound(XYZ.Zero, tilting_axis), tilting_angle); } shape.Location.Rotate(Line.CreateUnbound(XYZ.Zero, axis), FindSurfaceRevitPluginUtils.GetPositiveAngleBetween(tilted_basis_x, tube_begin, axis)); shape.Location.Move(center); document.ActiveView.SetElementOverrides(shape.Id, new OverrideGraphicSettings().SetProjectionLineColor(line_color).SetSurfaceTransparency(surface_transparency)); t.Commit(); } } }
public DirectShape GetTurningRadiusWithKneeAndToeClearanceDirectShape(XYZ centerPoint) { // The measurements are mentioned in the drawing in inches but we want it to be in internal units (feet) double inch9 = UnitUtils.ConvertToInternalUnits(9, DisplayUnitType.DUT_DECIMAL_INCHES); double inch13 = UnitUtils.ConvertToInternalUnits(13, DisplayUnitType.DUT_DECIMAL_INCHES); double inch21 = UnitUtils.ConvertToInternalUnits(21, DisplayUnitType.DUT_DECIMAL_INCHES); double inch24 = UnitUtils.ConvertToInternalUnits(24, DisplayUnitType.DUT_DECIMAL_INCHES); double inch27 = UnitUtils.ConvertToInternalUnits(27, DisplayUnitType.DUT_DECIMAL_INCHES); double inch30 = UnitUtils.ConvertToInternalUnits(30, DisplayUnitType.DUT_DECIMAL_INCHES); double inch54 = UnitUtils.ConvertToInternalUnits(54, DisplayUnitType.DUT_DECIMAL_INCHES); // First Create a profile to rotate // Let's take center point as the center of the turning circle. XYZ pt1 = new XYZ(0, 0, 0); XYZ pt2 = new XYZ(inch30, 0, 0); XYZ pt3 = new XYZ(inch30, 0, inch9); XYZ pt4 = new XYZ(inch24, 0, inch9); XYZ pt5 = new XYZ(inch21, 0, inch27); XYZ pt6 = new XYZ(inch13, 0, inch27); XYZ pt7 = new XYZ(inch13, 0, inch54); XYZ pt8 = new XYZ(0, 0, inch54); // Document doc = DocumentInterface.getInstance().GetDoc(); Document doc = this.ActiveUIDocument.Document; // Create the profile to rotate List <Curve> profile = new List <Curve>(); profile.Add(Line.CreateBound(pt1, pt2)); profile.Add(Line.CreateBound(pt2, pt3)); profile.Add(Line.CreateBound(pt3, pt4)); profile.Add(Line.CreateBound(pt4, pt5)); profile.Add(Line.CreateBound(pt5, pt6)); profile.Add(Line.CreateBound(pt6, pt7)); profile.Add(Line.CreateBound(pt7, pt8)); profile.Add(Line.CreateBound(pt8, pt1)); DirectShape ds = null; CurveLoop curveLoop = CurveLoop.Create(profile); Solid rotatedSolid = GeometryCreationUtilities.CreateRevolvedGeometry(new Frame(), new CurveLoop[] { curveLoop }, 0, Math.PI * 2.0); using (Transaction transaction = new Transaction(doc, "Create the clearance space solid")) { transaction.Start(); // create direct shape and assign the sphere shape ds = DirectShape.CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)); ds.ApplicationId = "Application id"; ds.ApplicationDataId = "Geometry object id"; ds.SetShape(new GeometryObject[] { rotatedSolid }); ds.Location.Move(centerPoint); // since we have added the solid on origin, the centerPoint - origin (zero) is the direction vector. transaction.Commit(); } return(ds); }
public static bool CreateAreaSolid(Document doc, AreaProperties ap, out MassProperties createdMass) { bool created = false; createdMass = null; try { string appGuid = doc.Application.ActiveAddInId.GetGUID().ToString(); if (null != ap.Linked3dMass) { //delete existing mass first MassProperties existingMass = ap.Linked3dMass; doc.Delete(new ElementId(existingMass.MassId)); } IList <GeometryObject> areaGeometries = new List <GeometryObject>(); if (ap.AreaProfile.Count > 0) { XYZ extrusionDir = new XYZ(0, 0, 1); Solid areaSolid = GeometryCreationUtilities.CreateExtrusionGeometry(ap.AreaProfile, extrusionDir, ap.UserHeight); if (null != areaSolid) { areaGeometries.Add(areaSolid); } } #if RELEASE2015 || RELEASE2016 DirectShape createdShape = DirectShape.CreateElement(doc, new ElementId(massCategory), appGuid, ap.AreaId.ToString()); #else DirectShape createdShape = DirectShape.CreateElement(doc, new ElementId(massCategory)); createdShape.ApplicationId = appGuid; createdShape.ApplicationDataId = ap.AreaId.ToString(); #endif #if RELEASE2016 DirectShapeOptions options = createdShape.GetOptions(); options.ReferencingOption = DirectShapeReferencingOption.Referenceable; createdShape.SetOptions(options); #endif createdShape.SetShape(areaGeometries); createdShape.SetName(ap.AreaName); Element massElement = doc.GetElement(createdShape.Id); if (null != massElement) { createdMass = new MassProperties(massElement); createdMass.SetHostInfo(ap.AreaUniqueId, SourceType.Areas, ap.AreaCenterPoint, ap.UserHeight); bool stored = MassDataStorageUtil.SetLinkedHostInfo(massElement, SourceType.Areas.ToString(), ap.AreaUniqueId, ap.AreaCenterPoint, ap.UserHeight); created = true; } } catch (Exception ex) { MessageBox.Show("Failed to create area solid.\n" + ex.Message, "Create Area Solid", MessageBoxButtons.OK, MessageBoxIcon.Warning); } return(created); }
internal static ElementId AddMeshToDocument(ref Document doc, Mesh mesh) { ElementId elemId = new ElementId(BuiltInCategory.OST_GenericModel); DirectShape ds = DirectShape.CreateElement(doc, elemId); ds.SetShape(new List <GeometryObject> { mesh }); return(elemId); }
static void GetDirectShape(Document doc, Solid solid) { using (Transaction t = new Transaction(doc, "Create DirectShape object")) { t.Start(); DirectShape ds = DirectShape .CreateElement(doc, new ElementId(BuiltInCategory.OST_GenericModel)); ds.SetShape(new GeometryObject[] { solid }); t.Commit(); } }
/// <summary> /// creates a DirectShape instance of which shape is Plane. /// Plane is defined by four vertices (top-left, top-right, bottom-left, bottom-right) on the plane. /// (Actually, it is a rectangle as you already know.) /// </summary> /// <remarks>The Plane has very small thickness (0.0039) since there is no way to create a plane with no thickness using DirectShape.</remarks> /// <param name="document">The Revit document where the instance to be drawn</param> /// <param name="name">The name of this instance</param> /// <param name="top_left">Position of the top-left vertex</param> /// <param name="top_right">Position of the top-right vertex</param> /// <param name="bottom_left">Position of the bottom-left vertex</param> /// <param name="bottom_right">Position of the bottom-right vertex</param> /// <param name="line_color">Outline color of Plane</param> /// <param name="surface_transparency">Surface transparency; ranged from 0 (transparent) to 100 (opaque)</param> public DirectPlane(Document document, string name, XYZ top_left, XYZ top_right, XYZ bottom_left, XYZ bottom_right, Color line_color, int surface_transparency) : base(document, name) { m_shape_type = ShapeTypes.Plane; TopLeft = top_left; TopRight = top_right; BottomLeft = bottom_left; BottomRight = bottom_right; XYZ rotation_axis, translation_offset; double rotation_angle; XYZ tl, tr; XYZ bl, br; // We'll rotates and translates the plane transformed to be axis-aligned, because GeometryCreationUtilities.CreateSweptGeometry may fail to define a plane due to the precision issue. GetAxisAlignedPlane( top_left, top_right, bottom_left, bottom_right, out tl, out tr, out bl, out br, out rotation_axis, out rotation_angle, out translation_offset); Frame frame = new Frame(XYZ.Zero, XYZ.BasisX, XYZ.BasisY, XYZ.BasisZ); List <Curve> profile = new List <Curve>(); profile.Add(Line.CreateBound(tl, bl)); profile.Add(Line.CreateBound(bl, br)); profile.Add(Line.CreateBound(br, tr)); profile.Add(Line.CreateBound(tr, tl)); List <Curve> swept_profile = new List <Curve>(); swept_profile.Add(Line.CreateBound(XYZ.Zero, 0.0039 * XYZ.BasisZ)); CurveLoop curve_loop = CurveLoop.Create(profile); CurveLoop sweep_path = CurveLoop.Create(swept_profile); SolidOptions options = new SolidOptions(ElementId.InvalidElementId, ElementId.InvalidElementId); if (Frame.CanDefineRevitGeometry(frame) == true) { Solid thin_box = GeometryCreationUtilities.CreateSweptGeometry(sweep_path, 0, 0, new CurveLoop[] { curve_loop }, options); using (Transaction t = new Transaction(document, "Create plane direct shape")) { t.Start(); DirectShape shape = DirectShape.CreateElement(document, new ElementId(BuiltInCategory.OST_GenericModel)); shape.SetShape(new GeometryObject[] { thin_box }); shape.SetName(name); m_element_id = shape.Id; shape.Location.Rotate(Line.CreateUnbound(XYZ.Zero, rotation_axis), -rotation_angle); shape.Location.Move(-translation_offset); document.ActiveView.SetElementOverrides(shape.Id, new OverrideGraphicSettings().SetProjectionLineColor(line_color).SetSurfaceTransparency(surface_transparency)); t.Commit(); } } }
/// <summary> /// Create a DirectShape. /// </summary> /// <param name="doc">The document.</param> /// <param name="categoryId">The category of the DirectShape.</param> /// <param name="dataGUID">The GUID of the data creating the DirectShape.</param> /// <returns>The DirectShape.</returns> static public DirectShape CreateElement(Document doc, ElementId categoryId, string dataGUID, IList <GeometryObject> geomObjs) { string appGUID = Importer.ImportAppGUID(); DirectShape directShape = DirectShape.CreateElement(doc, categoryId, appGUID, dataGUID); if (directShape != null && geomObjs != null) { directShape.SetShape(geomObjs); } return(directShape); }
public static Result Import3DMFile(string filePath, Document doc, BuiltInCategory builtInCategory) { using (var model = File3dm.Read(filePath)) { var scaleFactor = RhinoMath.UnitScale(model.Settings.ModelUnitSystem, Revit.ModelUnitSystem); using (var trans = new Transaction(doc, "Import 3D Model")) { if (trans.Start() == TransactionStatus.Started) { var categoryId = new ElementId(builtInCategory); var ds = DirectShape.CreateElement(doc, categoryId); ds.Name = Path.GetFileName(filePath); foreach (var obj in model.Objects) { if (!obj.Attributes.Visible) { continue; } var layer = model.AllLayers.FindIndex(obj.Attributes.LayerIndex); if (layer?.IsVisible != true) { continue; } var geometryList = ImportObject(obj.Geometry, obj.Attributes, scaleFactor); if (geometryList == null) { continue; } try { ds.AppendShape(geometryList); } catch (Autodesk.Revit.Exceptions.ArgumentException) { } } if (trans.Commit() == TransactionStatus.Committed) { var elements = new ElementId[] { ds.Id }; Revit.ActiveUIDocument.Selection.SetElementIds(elements); Revit.ActiveUIDocument.ShowElements(elements); return(Result.Succeeded); } } } } return(Result.Failed); }