Beispiel #1
0
        public IExternalCommand.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Application revit = commandData.Application;
            Document curDoc = revit.ActiveDocument;
            FamilySymbol symbol = null;
            ElementSetIterator selIt = curDoc.Selection.Elements.ForwardIterator();
            if (selIt.MoveNext())
            {
                FamilyInstance fi = selIt.Current as FamilyInstance;
                symbol = fi.Symbol;
            }
            if (symbol == null)
            {
                message = "Please select a family instance!";
                return IExternalCommand.Result.Cancelled;
            }

            XYZ startPoint = new XYZ(0, 30, 0);
            FamilyInstance createdFamily = curDoc.Create.NewFamilyInstance(ref startPoint, symbol, Autodesk.Revit.Structural.Enums.StructuralType.UnknownFraming);
            if (null == createdFamily)
            {
                message = "Create the family failed.";
                return IExternalCommand.Result.Failed;
            }

            return IExternalCommand.Result.Succeeded;
        }
        /// <summary>
        /// Create a new dimension element using the given
        /// references and dimension line end points.
        /// This method opens and commits its own transaction,
        /// assuming that no transaction is open yet and manual
        /// transaction mode is being used.
        /// Note that this has only been tested so far using
        /// references to surfaces on planar walls in a plan
        /// view.
        /// </summary>
        public static void CreateDimensionElement(
            View view,
            XYZ p1,
            Reference r1,
            XYZ p2,
            Reference r2)
        {
            Document doc = view.Document;

              ReferenceArray ra = new ReferenceArray();

              ra.Append( r1 );
              ra.Append( r2 );

              Line line = Line.CreateBound( p1, p2 );

              using( Transaction t = new Transaction( doc ) )
              {
            t.Start( "Create New Dimension" );

            Dimension dim = doc.Create.NewDimension(
              view, line, ra );

            t.Commit();
              }
        }
 /// <summary>
 /// Возвращает строку для трехмерной точки XYZ
 /// или вектора с координатами этой точки
 /// преобразованную из футов в миллиметры
 /// и отформатированную до двух знаков после запятой
 /// </summary>
 public static string PointStringMm( XYZ p )
 {
     return string.Format( "({0};{1};{2})",
       RealString( p.X * _foot_to_mm ),
       RealString( p.Y * _foot_to_mm ),
       RealString( p.Z * _foot_to_mm ) );
 }
Beispiel #4
0
        private static XYZ haversine(XYZ start, XYZ end)
        {
            XYZ ret = start - end;
            if (ret.GetLength() < 0.0000000001 && ret.GetLength() > -0.0000000001)
                return new XYZ(0, 0, 0);

            var earthRadius = 6371000; // metres
            var degreesToRadians = Math.PI / 180;

            var lat1 = start.Y * degreesToRadians;
            var lat2 = end.Y * degreesToRadians;
            var long1 = start.X * degreesToRadians;
            var long2 = end.X * degreesToRadians;

            var Δlat = lat2 - lat1;
            var Δlong = long2 - long1;

            var a = Math.Sin(Δlat / 2) * Math.Sin(Δlat / 2) +
                    Math.Cos(lat1) * Math.Cos(lat2) *
                    Math.Sin(Δlong / 2) * Math.Sin(Δlong / 2);
            var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

            ret = ret.Normalize();
            ret = ret.Multiply(earthRadius * c);

            return ret;
        }
 private static XYZ NewMaxBound(XYZ oldMaxBound, IList<XYZ> vertices)
 {
     XYZ maxBound = oldMaxBound;
     foreach (XYZ vertex in vertices)
         maxBound = new XYZ(Math.Max(maxBound.X, vertex.X), Math.Max(maxBound.Y, vertex.Y), Math.Max(maxBound.Z, vertex.Z));
     return maxBound;
 }
Beispiel #6
0
        public void CreateHelix()
        {
            double increment = 0.1;
            double current = 0;
            XYZ startPt;
            XYZ endPt;
            XYZ zAxis = GeomUtils.kZAxis;
            XYZ origin = GeomUtils.kOrigin;
            Line line;
            Plane plane = m_revitApp.Application.Create.NewPlane(zAxis, origin);
            SketchPlane sketchPlane = SketchPlane.Create(m_revitApp.ActiveUIDocument.Document, plane);
            CurveArray curveArray = new CurveArray();

            startPt = new XYZ(Math.Cos(current), Math.Sin(current), current);
            current += increment;

            while (current <= GeomUtils.kTwoPi) {
                endPt = new XYZ(Math.Cos(current), Math.Sin(current), current);

                line = Line.CreateBound(startPt, endPt);
                curveArray.Append(line);

                startPt = endPt;
                current += increment;
            }

            m_revitApp.ActiveUIDocument.Document.Create.NewModelCurveArray(curveArray, sketchPlane);
        }
        /// <summary>
        /// Creates IfcAxis2Placement3D object.
        /// </summary>
        /// <param name="file">
        /// The IFC file.
        /// </param>
        /// <param name="origin">
        /// The origin.
        /// </param>
        /// <param name="zDirection">
        /// The Z direction.
        /// </param>
        /// <param name="xDirection">
        /// The X direction.
        /// </param>
        /// <returns>
        /// The handle.
        /// </returns>
        public static IFCAnyHandle CreateAxis(IFCFile file, XYZ origin, XYZ zDirection, XYZ xDirection)
        {
            IFCAnyHandle directionOpt = IFCAnyHandle.Create();
            IFCAnyHandle refOpt = IFCAnyHandle.Create();
            IFCAnyHandle location = IFCAnyHandle.Create();

            if (origin != null)
            {
                IList<double> measure = new List<double>();
                measure.Add(origin.X); measure.Add(origin.Y); measure.Add(origin.Z);
                location = CreateCartesianPoint(file, measure);
            }
            else
            {
                location = ExporterIFCUtils.GetGlobal3DOriginHandle();
            }

            bool exportzDirectionAndxDirection = (zDirection != null && xDirection != null && (!MathUtil.IsAlmostEqual(zDirection[2], 1.0) || !MathUtil.IsAlmostEqual(xDirection[0], 1.0)));

            if (exportzDirectionAndxDirection)
            {
                IList<double> axisPts = new List<double>();
                axisPts.Add(zDirection.X); axisPts.Add(zDirection.Y); axisPts.Add(zDirection.Z);
                directionOpt = CreateDirection(file, axisPts);
            }

            if (exportzDirectionAndxDirection)
            {
                IList<double> axisPts = new List<double>();
                axisPts.Add(xDirection.X); axisPts.Add(xDirection.Y); axisPts.Add(xDirection.Z);
                refOpt = CreateDirection(file, axisPts);
            }

            return file.CreateAxis2Placement3D(location, directionOpt, refOpt);
        }
Beispiel #8
0
 public Map(Minecraft minecraft)
 {
     this.minecraft = minecraft;
     chunks = new Chunk[21, 21];
     center = this.chunks.GetLength (0) / 2;
     playerChunk = null;
 }
 //class constructor
 public Revit_View_ThreeD(View3D view)
 {
     vView3D = view;
     vCameraPosition=vView3D.EyePosition;
     vCameraViewDirection = vView3D.ViewDirection;
     vCameraUp = vView3D.UpDirection;
 }
Beispiel #10
0
        public override FScheme.Value Evaluate(FSharpList<FScheme.Value> args)
        {
            var t = (Transform)((FScheme.Value.Container)args[0]).Item;
            double width = ((FScheme.Value.Number)args[1]).Item;
            double height = ((FScheme.Value.Number)args[2]).Item;

            //ccw from upper right
            var p0 = new XYZ(width / 2, height / 2, 0);
            var p3 = new XYZ(-width / 2, height / 2, 0);
            var p2 = new XYZ(-width / 2, -height / 2, 0);
            var p1 = new XYZ(width / 2, -height / 2, 0);

            p0 = t.OfPoint(p0);
            p1 = t.OfPoint(p1);
            p2 = t.OfPoint(p2);
            p3 = t.OfPoint(p3);

            var l1 = dynRevitSettings.Doc.Application.Application.Create.NewLineBound(p0, p1);
            var l2 = dynRevitSettings.Doc.Application.Application.Create.NewLineBound(p1, p2);
            var l3 = dynRevitSettings.Doc.Application.Application.Create.NewLineBound(p2, p3);
            var l4 = dynRevitSettings.Doc.Application.Application.Create.NewLineBound(p3, p0);

            var cl = new Autodesk.Revit.DB.CurveLoop();
            cl.Append(l1);
            cl.Append(l2);
            cl.Append(l3);
            cl.Append(l4);

            return FScheme.Value.NewContainer(cl);
        }
Beispiel #11
0
        internal ImportInstance(string satPath, XYZ translation = null)
        {
            translation = translation ?? XYZ.Zero;

            TransactionManager.Instance.EnsureInTransaction(Document);

            var options = new SATImportOptions()
            {
                Unit = ImportUnit.Foot
            };

            var id = Document.Import(satPath, options, Document.ActiveView);
            var element = Document.GetElement(id);
            var importInstance = element as Autodesk.Revit.DB.ImportInstance;

            if (importInstance == null)
            {
                throw new Exception("Could not obtain ImportInstance from imported Element");
            }

            InternalSetImportInstance(importInstance);
            InternalUnpinAndTranslateImportInstance(translation);

            this.Path = satPath;

            TransactionManager.Instance.TransactionTaskDone();
        }
        private XYZ GetValidXVectorFromLoop(CurveLoop curveLoop, XYZ zVec, XYZ origin)
        {
            foreach (Curve curve in curveLoop)
            {
                IList<XYZ> pointsToCheck = new List<XYZ>();

                // If unbound, must be cyclic.
                if (!curve.IsBound)
                {
                    pointsToCheck.Add(curve.Evaluate(0, false));
                    pointsToCheck.Add(curve.Evaluate(Math.PI / 2.0, false));
                    pointsToCheck.Add(curve.Evaluate(Math.PI, false));
                }
                else
                {
                    pointsToCheck.Add(curve.Evaluate(0, true));
                    pointsToCheck.Add(curve.Evaluate(1.0, true));
                    if (curve.IsCyclic)
                        pointsToCheck.Add(curve.Evaluate(0.5, true));
                }

                foreach (XYZ pointToCheck in pointsToCheck)
                {
                    XYZ possibleVec = (pointToCheck - origin);
                    XYZ yVec = zVec.CrossProduct(possibleVec).Normalize();
                    if (yVec.IsZeroLength())
                        continue;
                    return yVec.CrossProduct(zVec);
                }
            }

            return null;
        }
Beispiel #13
0
 private void nextMove()
 {
     lock (this) {
         if (this.endPosition != null && !this.position.Equals (this.endPosition)) {
             double realSpeed = this.speed / 1000.0 * moving.Interval;
             double distance = getDistance (endPosition, position);
             double u = realSpeed / (distance - realSpeed);
             XYZ<double> nextPosition = new XYZ<double> (0, 0, 0);
             nextPosition.x = (position.x + u * endPosition.x) / (1 + u);
             nextPosition.y = (position.y + u * endPosition.y) / (1 + u);
             nextPosition.z = (position.z + u * endPosition.z) / (1 + u);
             this.position = nextPosition;
             if (realSpeed >= distance)
                 this.position = this.endPosition;
             this.minecraft.SendPacket (new object[] {
                 (byte)PacketID.PlayerPosition,
                 this.position.x,
                 this.position.y,
                 this.position.y + this.height,
                 this.position.z,
                 this.onGround
             }
             );
             this.minecraft.map.updateMap ();
         }
     }
 }
Beispiel #14
0
        /// <summary>
        //MOVES THE CAMERA ACCORDING TO THE PROJECT BASE LOCATION 
        //function that changes the coordinates accordingly to the project base location to an absolute location (for BCF export)
        //if the value negative is set to true, does the opposite (for opening BCF views)
        /// </summary>
        /// <param name="c">center</param>
        /// <param name="view">view direction</param>
        /// <param name="up">up direction</param>
        /// <param name="negative">convert to/from</param>
        /// <returns></returns>
        public static ViewOrientation3D ConvertBasePoint(Document doc, XYZ c, XYZ view, XYZ up, bool negative)
        {
            //UIDocument uidoc = uiapp.ActiveUIDocument;
            //Document doc = uidoc.Document;

            //ElementCategoryFilter filter = new ElementCategoryFilter(BuiltInCategory.OST_ProjectBasePoint);
            //FilteredElementCollector collector = new FilteredElementCollector(doc);
            //System.Collections.Generic.IEnumerable<Element> elements = collector.WherePasses(filter).ToElements();

            double angle = 0;
            double x = 0;
            double y = 0;
            double z = 0;

            //VERY IMPORTANT
            //BuiltInParameter.BASEPOINT_EASTWEST_PARAM is the value of the BASE POINT LOCATION
            //position is the location of the BPL related to Revit's absolute origini!
            //if BPL is set to 0,0,0 not always it corresponds to Revit's origin

            ProjectLocation projectLocation = doc.ActiveProjectLocation;
            XYZ origin = new XYZ(0, 0, 0);
            ProjectPosition position = projectLocation.get_ProjectPosition(origin);

            int i = (negative) ? -1 : 1;
            //foreach (Element element in elements)
            //{
            //    MessageBox.Show(UnitUtils.ConvertFromInternalUnits(position.EastWest, DisplayUnitType.DUT_METERS).ToString() + "  " + element.get_Parameter(BuiltInParameter.BASEPOINT_EASTWEST_PARAM).AsValueString() + "\n" +
            //        UnitUtils.ConvertFromInternalUnits(position.NorthSouth, DisplayUnitType.DUT_METERS).ToString() + "  " + element.get_Parameter(BuiltInParameter.BASEPOINT_NORTHSOUTH_PARAM).AsValueString() + "\n" +
            //        UnitUtils.ConvertFromInternalUnits(position.Elevation, DisplayUnitType.DUT_METERS).ToString() + "  " + element.get_Parameter(BuiltInParameter.BASEPOINT_ELEVATION_PARAM).AsValueString() + "\n" +
            //        position.Angle.ToString() + "  " + element.get_Parameter(BuiltInParameter.BASEPOINT_ANGLETON_PARAM).AsDouble().ToString());
            //}
            x = i * position.EastWest;
            y = i * position.NorthSouth;
            z = i * position.Elevation;
            angle = i * position.Angle;

            if (negative) // I do the addition BEFORE
                c = new XYZ(c.X + x, c.Y + y, c.Z + z);

            //rotation
            double centX = (c.X * Math.Cos(angle)) - (c.Y * Math.Sin(angle));
            double centY = (c.X * Math.Sin(angle)) + (c.Y * Math.Cos(angle));

            XYZ newC = new XYZ();
            if (negative)
                newC = new XYZ(centX, centY, c.Z);
            else // I do the addition AFTERWARDS
                newC = new XYZ(centX + x, centY + y, c.Z + z);


            double viewX = (view.X * Math.Cos(angle)) - (view.Y * Math.Sin(angle));
            double viewY = (view.X * Math.Sin(angle)) + (view.Y * Math.Cos(angle));
            XYZ newView = new XYZ(viewX, viewY, view.Z);

            double upX = (up.X * Math.Cos(angle)) - (up.Y * Math.Sin(angle));
            double upY = (up.X * Math.Sin(angle)) + (up.Y * Math.Cos(angle));

            XYZ newUp = new XYZ(upX, upY, up.Z);
            return new ViewOrientation3D(newC, newUp, newView);
        }
Beispiel #15
0
        public void apply()
        {
            if (m_particleA.isFree() || m_particleB.isFree())
            {

                XYZ a2b = m_particleA.getPosition().Subtract(m_particleB.getPosition());

                double a2bDistance = Math.Abs(Math.Sqrt(a2b.X * a2b.X + a2b.Y * a2b.Y + a2b.Z * a2b.Z)); // MDJ vector norm http://mathworld.wolfram.com/VectorNorm.html != a2b.Normalize();

                if (a2bDistance == 0)
                {
                    a2b = new XYZ(0, 0, 0);
                }
                else
                {
                    a2b = a2b / a2bDistance;
                }

                double springForce = -(a2bDistance - m_restLength) * m_springConstant;

                XYZ Va2b = m_particleA.getVelocity() - m_particleB.getVelocity();

                double dampingForce = -m_Damping * (a2b.DotProduct(Va2b));

                // forceB is same as forceA in opposite direction
                double r = springForce + dampingForce;

                a2b = a2b * r;

                if (m_particleA.isFree())
                    m_particleA.addForce(a2b);
                if (m_particleB.isFree())
                    m_particleB.addForce(-a2b);
            }
        }
Beispiel #16
0
        public IExternalCommand.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Application revit = commandData.Application;
            Document curDoc = revit.ActiveDocument;

            //配置几何曲线
            CurveArray curves = new CurveArray();
            if (null == curves)
            {
                message = "Create the curves failed.";
                return IExternalCommand.Result.Failed;
            }
            XYZ first = new XYZ(0, 0, 0);
            XYZ second = new XYZ(10, 0, 0);
            XYZ third = new XYZ(10, 10, 0);
            XYZ fourth = new XYZ(0, 10, 0);
            curves.Append(revit.Create.NewLine(ref first, ref second, true));
            curves.Append(revit.Create.NewLine(ref second, ref third, true));
            curves.Append(revit.Create.NewLine(ref third, ref fourth, true));
            curves.Append(revit.Create.NewLine(ref fourth, ref first, true));
            // 利用几何曲线,类型,标高等创建地板对象
            Floor createdFloor = curDoc.Create.NewFloor(curves, true);
            if (null == createdFloor)
            {
                message = "Create floor failed.!";
                return IExternalCommand.Result.Failed;
            }

            return IExternalCommand.Result.Succeeded;
        }
Beispiel #17
0
 /// <summary>
 /// Return a string for an XYZ point
 /// or vector with its coordinates
 /// formatted to two decimal places.
 /// </summary>
 public static string PointString( XYZ p )
 {
     return string.Format( "({0},{1},{2})",
     RealString( p.X ),
     RealString( p.Y ),
     RealString( p.Z ) );
 }
        public static Tuple<Face, Reference> GetClosestFace(Document document, XYZ p)
        {
            Face resultFace = null;
            Reference resultReference = null;

            double min_distance = double.MaxValue;
            FilteredElementCollector collector = new FilteredElementCollector(document);
            var walls = collector.OfClass(typeof (Wall));
            foreach (Wall wall in walls)
            {
                IList<Reference> sideFaces =
                    HostObjectUtils.GetSideFaces(wall, ShellLayerType.Interior);
                // access the side face
                Face face = document.GetElement(sideFaces[0]).GetGeometryObjectFromReference(sideFaces[0]) as Face;
                var intersection = face.Project(p);

                if (intersection != null)
                {
                    if (intersection.Distance < min_distance)
                    {
                        resultFace = face;
                        resultReference = sideFaces[0];
                        min_distance = intersection.Distance;
                    }
                }
            }
            //resultFace.
            return new Tuple<Face,Reference>( resultFace, resultReference);
        }
Beispiel #19
0
        public IExternalCommand.Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Application revit = commandData.Application;
            Document curDoc = revit.ActiveDocument;
            XYZ startPoint = new XYZ(0, 0, 0);
            XYZ endPoint = new XYZ(10, 0, 0);
            WallType wallType = null;
            WallTypeSetIterator it = curDoc.WallTypes.ForwardIterator();
            if (it.MoveNext())
            {
                wallType = it.Current as WallType;
            }
            if (wallType == null)
            {
                message = "No any wall type in current document!";
                return IExternalCommand.Result.Failed;
            }
            Level createlevel = curDoc.ActiveView.GenLevel;
            //创建几何曲线
            Line geometryLine = revit.Create.NewLine(ref startPoint, ref endPoint, true);
            if (null == geometryLine)
            {
                message = "Create the geometry line failed.";
                return IExternalCommand.Result.Failed;
            }
            // 利用几何曲线,墙类型,标高创建墙对象
            Wall createdWall = curDoc.Create.NewWall(geometryLine, wallType, createlevel, 10, startPoint.Z + createlevel.Elevation, true, true);
            if (null == createdWall)
            {
                message = "Create the wall failed.";
                return IExternalCommand.Result.Failed;
            }

            return IExternalCommand.Result.Succeeded;
        }
Beispiel #20
0
 /// <summary>
 /// Build Orientation3D object for eye point and a target point 
 /// </summary>
 /// <param name="eyePoint"></param>
 /// <param name="target"></param>
 /// <returns></returns>
 protected static ViewOrientation3D BuildOrientation3D(XYZ eyePoint, XYZ target)
 {
     var globalUp = XYZ.BasisZ;
     var direction = target.Subtract(eyePoint);
     var up = direction.CrossProduct(globalUp).CrossProduct(direction);
     return new ViewOrientation3D(eyePoint, up, direction);
 }
Beispiel #21
0
        /// <summary>
        /// de-serialize vector passed from UI trough options 
        /// </summary>
        private static XYZ ParseXYZ(string value)
        {
            XYZ retVal = null;

            //split string to components by removing seprator characters
            string[] separator = new string[] { ",", "(", ")", " " };
            string[] sList = new string[3] { "", "", "" };
            sList = value.Split(separator, StringSplitOptions.RemoveEmptyEntries);
            //should remain only 3 values if everything is OK

            try
            {
                double valX = double.Parse(sList[0]); //parsing values
                double valY = double.Parse(sList[1]);
                double valZ = double.Parse(sList[2]);
                //if no exception then put it in return value
                retVal = new XYZ(valX, valY, valZ);
            }
            catch (FormatException)
            {

            }
            //return null if there is a problem or a value 
            return retVal;
        }
Beispiel #22
0
        Midpoint(XYZ pt1, XYZ pt2)
        {
            XYZ newPt = new XYZ(((pt1.X + pt2.X) / 2.0),
                                        ((pt1.Y + pt2.Y) / 2.0),
                                        ((pt1.Z + pt2.Z) / 2.0));

            return newPt;
        }
Beispiel #23
0
        public ViewPortInfo(ElementId id, XYZ location, View v, Viewport vp)
        {
            this.id = id;

            this.location = location;
            this.view = v;
            this.vport = vp;
        }
        /// <summary>
        /// Determines if curve loop is counterclockwise.
        /// </summary>
        /// <param name="curveLoop">
        /// The curveLoop.
        /// </param>
        /// <param name="normal">
        /// The normal.
        /// </param>
        /// <returns>
        /// Returns true only if the loop is counterclockwise, false otherwise.
        /// </returns>
        public static bool IsIFCLoopCCW(CurveLoop curveLoop, XYZ normal)
        {
            if (curveLoop == null)
                throw new Exception("CurveLoop is null.");

            // If loop is not suitable for ccw evaluation an exception is thrown
            return curveLoop.IsCounterclockwise(normal);
        }
 private static XYZ GetConvertedCoords(ExportedInstance instanse)
 {
     var convertedCoords = new XYZ(
         Utils.MillimetersToFeet(instanse.X),
         Utils.MillimetersToFeet(instanse.Y),
         Utils.MillimetersToFeet(instanse.Z));
     return convertedCoords;
 }
Beispiel #26
0
 public static XYZ GetXYZ(double x, double y, double z)
 {
     XYZ myXYZ = new XYZ(
     UnitUtils.ConvertToInternalUnits(x, DisplayUnitType.DUT_METERS),
     UnitUtils.ConvertToInternalUnits(y, DisplayUnitType.DUT_METERS),
     UnitUtils.ConvertToInternalUnits(z, DisplayUnitType.DUT_METERS));
       return myXYZ;
 }
        protected override void Process(IFCAnyHandle ifcVertexPoint)
        {
            base.Process(ifcVertexPoint);

            IFCAnyHandle vertexGeometry = IFCImportHandleUtil.GetRequiredInstanceAttribute(ifcVertexPoint, "VertexGeometry", true);
            XYZ unScaledVertexGeometry = IFCPoint.ProcessIFCPoint(vertexGeometry);
            VertexGeometry = IFCUnitUtil.ScaleLength(unScaledVertexGeometry);
        }
Beispiel #28
0
 Move()
 {
    XYZ vec = new XYZ(10.0, 10.0, 0.0);
    ElementTransformUtils.MoveElements(
       m_revitApp.ActiveUIDocument.Document,
       m_revitApp.ActiveUIDocument.Selection.GetElementIds(),
       vec
       );
 }
		public static Double GetLongitude(XYZ projCoordXYZ, Document dbDoc)
		{
			Double longitude;
			Double baseLongitude = DroneUtils.RadToDegrees(dbDoc.SiteLocation.Longitude);
			XYZ baseCoordsXYZ = TransformToBasePointCoords(projCoordXYZ, dbDoc);
			longitude = baseLongitude + DroneUtils.FeetToLongitude(baseCoordsXYZ.X, baseLongitude);

			return longitude;
		}
Beispiel #30
0
 // added to handle maintaining/updating chains non-destructively
 public Particle(int ID, double mass, XYZ position, bool fix)
 {
     m_ID = ID;
        m_Position = position;
        m_oldPosition = position;
        m_Velocity = new XYZ(0, 0, 0);
        m_Force = new XYZ(0, 0, 0);
        m_Mass = mass;
        m_Fixed = fix;
 }
Beispiel #31
0
 /// <summary>
 /// Elements that passes the referenceFilter-Predicate will pass
 /// </summary>
 /// <param name="reference"> </param>
 /// <param name="position"> </param>
 /// <returns></returns>
 public bool AllowReference(Reference reference, XYZ position)
 {
     return(m_referenceFilter(reference, position));
 }
        /// <summary>
        /// Calculates the size of a bounding box, which expands to include the given points.
        /// </summary>
        /// <param name="points">The points in a container of which size is to be calculated</param>
        /// <param name="lower_left">Lower-left boundary that is calculated</param>
        /// <param name="upper_right">Upper-right boundary that is calculated</param>
        public static void CalculateBoundingBox(CloudPoint[] points, out XYZ lower_left, out XYZ upper_right)
        {
            const double Revit_eps = 1.0e-9;
            double       mx, my, mz; mx = my = mz = double.MaxValue;
            double       Mx, My, Mz; Mx = My = Mz = -double.MaxValue;

            foreach (CloudPoint cp in points)
            {
                mx = Math.Min(cp.X, mx); Mx = Math.Max(cp.X, Mx);
                my = Math.Min(cp.Y, my); My = Math.Max(cp.Y, My);
                mz = Math.Min(cp.Z, mz); Mz = Math.Max(cp.Z, Mz);
            }

            double m = Math.Min(mx, Math.Min(my, mz)) - Revit_eps;
            double M = Math.Max(Mx, Math.Max(My, Mz)) + Revit_eps;

            lower_left  = new XYZ(m, m, m);
            upper_right = new XYZ(M, M, M);
        }
Beispiel #33
0
        /// <summary>
        /// Create Beam(s) Between The Selected Structural Columns
        /// </summary>
        /// <param name="doc">Active Revit Document</param>
        /// <param name="refList">Selected Elements Id list</param>
        /// <param name="symbolSelectionForm">Symbol Selection Form</param>
        /// <param name="view">Active Revit View</param>
        private void CreateBeamMethod(Document doc, View view, ICollection <ElementId> refList, SymbolSelectionForm symbolSelectionForm)
        {
            // Collect column location point with offset as point list
            List <XYZ> points = new List <XYZ>();

            // Need at least two columns
            if (refList.Count < 2)
            {
                TaskDialog.Show("ERROR", "Please select at least two columns");
            }

            // Iterate through the list
            foreach (ElementId r in refList)
            {
                Element column = doc.GetElement(r);

                // Get element as family instance
                FamilyInstance familyInstance = column as FamilyInstance;
                FamilySymbol   columnSymbol   = familyInstance.Symbol;

                // If selected elements aren't structural column cancel the operation
                if (familyInstance.StructuralType == StructuralType.Column)
                {
                    // Get the bounding box of element
                    BoundingBoxXYZ boxXYZ = familyInstance.get_BoundingBox(view);

                    // Column bounding box reference height
                    double column_height = boxXYZ.Max.Z - boxXYZ.Min.Z;

                    // Offset point
                    XYZ offset = new XYZ(0, 0, column_height);

                    //// Get the column location point
                    Location      loc           = familyInstance.Location;
                    LocationPoint locationPoint = loc as LocationPoint;

                    // Add offset to the column location point to get the height of column
                    points.Add(locationPoint.Point.Add(offset));
                }

                else
                {
                    TaskDialog.Show("ERROR", "Please select at least two columns");
                }
            }

            // Create beam location line from column location points
            List <Line> lines = CreateLine(refList.Count, points);

            // get the active level from document
            Level level = doc.GetElement(doc.ActiveView.LevelId) as Level;

            if (App.beamTypeSelection != null)
            {
                FamilySymbol beamSymbol = App.beamTypeSelection as FamilySymbol;

                // For using in the document, symbol has to be activate.
                if (!beamSymbol.IsActive)
                {
                    beamSymbol.Activate();
                }

                if (lines != null)
                {
                    foreach (Line line in lines)
                    {
                        FamilyInstance beam = doc.Create.NewFamilyInstance(line, beamSymbol, level, StructuralType.Beam);
                    }
                }
            }
            else
            {
                TaskDialog.Show("INFO", "Combo box selection is null");
            }
        }
        /// <summary>
        /// Return a closed loop of integer-based points
        /// scaled to millimetres from a given Revit model
        /// face in feet.
        /// </summary>
        internal static JtLoop GetLoop(
            Autodesk.Revit.Creation.Application creapp,
            Face face)
        {
            JtLoop loop = null;

            foreach (EdgeArray a in face.EdgeLoops)
            {
                int nEdges = a.Size;

                List <Curve> curves
                    = new List <Curve>(nEdges);

                XYZ p0 = null; // loop start point
                XYZ p;         // edge start point
                XYZ q = null;  // edge end point

                // Test ValidateCurveLoops

                //CurveLoop loopIfc = new CurveLoop();

                foreach (Edge e in a)
                {
                    // This requires post-processing using
                    // SortCurvesContiguous:

                    Curve curve = e.AsCurve();

                    if (_debug_output)
                    {
                        p = curve.GetEndPoint(0);
                        q = curve.GetEndPoint(1);
                        Debug.Print("{0} --> {1}",
                                    Util.PointString(p),
                                    Util.PointString(q));
                    }

                    // This returns the curves already
                    // correctly oriented:

                    curve = e.AsCurveFollowingFace(
                        face);

                    if (_debug_output)
                    {
                        p = curve.GetEndPoint(0);
                        q = curve.GetEndPoint(1);
                        Debug.Print("{0} --> {1} following face",
                                    Util.PointString(p),
                                    Util.PointString(q));
                    }

                    curves.Add(curve);

                    // Throws an exception saying "This curve
                    // will make the loop not contiguous.
                    // Parameter name: pCurve"

                    //loopIfc.Append( curve );
                }

                // We never reach this point:

                //List<CurveLoop> loopsIfc
                //  = new List<CurveLoop>( 1 );

                //loopsIfc.Add( loopIfc );

                //IList<CurveLoop> loopsIfcOut = ExporterIFCUtils
                //  .ValidateCurveLoops( loopsIfc, XYZ.BasisZ );

                // This is no longer needed if we use
                // AsCurveFollowingFace instead of AsCurve:

                CurveUtils.SortCurvesContiguous(
                    creapp, curves, _debug_output);

                q = null;

                loop = new JtLoop(nEdges);

                foreach (Curve curve in curves)
                {
                    // Todo: handle non-linear curve.
                    // Especially: if two long lines have a
                    // short arc in between them, skip the arc
                    // and extend both lines.

                    p = curve.GetEndPoint(0);

                    Debug.Assert(null == q ||
                                 q.IsAlmostEqualTo(p, 1e-04),
                                 string.Format(
                                     "expected last endpoint to equal current start point, not distance {0}",
                                     (null == q ? 0 : p.DistanceTo(q))));

                    q = curve.GetEndPoint(1);

                    if (_debug_output)
                    {
                        Debug.Print("{0} --> {1}",
                                    Util.PointString(p),
                                    Util.PointString(q));
                    }

                    if (null == p0)
                    {
                        p0 = p; // save loop start point
                    }

                    int n = -1;

                    if (_tessellate_curves &&
                        _min_tessellation_curve_length_in_feet
                        < q.DistanceTo(p))
                    {
                        IList <XYZ> pts = curve.Tessellate();
                        n = pts.Count;

                        Debug.Assert(1 < n, "expected at least two points");
                        Debug.Assert(p.IsAlmostEqualTo(pts[0]), "expected tessellation start equal curve start point");
                        Debug.Assert(q.IsAlmostEqualTo(pts[n - 1]), "expected tessellation end equal curve end point");

                        if (2 == n)
                        {
                            n = -1; // this is a straight line
                        }
                        else
                        {
                            --n; // skip last point

                            for (int i = 0; i < n; ++i)
                            {
                                loop.Add(new Point2dInt(pts[i]));
                            }
                        }
                    }

                    // If tessellation is disabled,
                    // or curve is too short to tessellate,
                    // or has only two tessellation points,
                    // just add the start point:

                    if (-1 == n)
                    {
                        loop.Add(new Point2dInt(p));
                    }
                }
                Debug.Assert(q.IsAlmostEqualTo(p0, 1e-05),
                             string.Format(
                                 "expected last endpoint to equal current start point, not distance {0}",
                                 p0.DistanceTo(q)));
            }
            return(loop);
        }
 /// <summary>
 /// Allow Selection of References
 /// </summary>
 /// <param name="reference">Selected Reference</param>
 /// <param name="position">Selected Point</param>
 /// <returns></returns>
 public bool AllowReference(Reference reference, XYZ position) => false;
Beispiel #36
0
            private void RenderUpcomingEvents()
            {
                string vessel_guid           = vessel_.id.ToString();
                double current_time          = plugin_.CurrentTime();
                bool   should_clear_guidance = true;

                for (int i = 0; i < burn_editors_.Count; ++i)
                {
                    NavigationManoeuvre manoeuvre =
                        plugin_.FlightPlanGetManoeuvre(vessel_guid, i);
                    if (manoeuvre.final_time > current_time)
                    {
                        if (manoeuvre.burn.initial_time > current_time)
                        {
                            UnityEngine.GUILayout.TextArea("Upcoming manœuvre: #" + (i + 1));
                            UnityEngine.GUILayout.Label(
                                "Ignition " + FormatTimeSpan(TimeSpan.FromSeconds(
                                                                 current_time - manoeuvre.burn.initial_time)));
                        }
                        else
                        {
                            UnityEngine.GUILayout.TextArea("Ongoing manœuvre: #" + (i + 1));
                            UnityEngine.GUILayout.Label(
                                "Cutoff " + FormatTimeSpan(TimeSpan.FromSeconds(
                                                               current_time - manoeuvre.final_time)));
                        }
                        // In career mode, the patched conic solver may be null.  In that case
                        // we do not offer the option of showing the manœuvre on the navball,
                        // even though the flight planner is still available to plan it.
                        // TODO(egg): We may want to consider setting the burn vector directly
                        // rather than going through the solver.
                        if (vessel_.patchedConicSolver != null)
                        {
                            using (new HorizontalLayout()) {
                                show_guidance_ =
                                    UnityEngine.GUILayout.Toggle(show_guidance_, "Show on navball");
                                if (UnityEngine.GUILayout.Button("Warp to manœuvre"))
                                {
                                    TimeWarp.fetch.WarpTo(manoeuvre.burn.initial_time - 60);
                                }
                            }
                            XYZ guidance = plugin_.FlightPlanGetGuidance(vessel_guid, i);
                            if (show_guidance_ &&
                                !double.IsNaN(guidance.x + guidance.y + guidance.z))
                            {
                                if (guidance_node_ == null ||
                                    !vessel_.patchedConicSolver.maneuverNodes.Contains(
                                        guidance_node_))
                                {
                                    while (vessel_.patchedConicSolver.maneuverNodes.Count > 0)
                                    {
                                        vessel_.patchedConicSolver.maneuverNodes.Last().RemoveSelf();
                                    }
                                    guidance_node_ = vessel_.patchedConicSolver.AddManeuverNode(
                                        manoeuvre.burn.initial_time);
                                }
                                else if (vessel_.patchedConicSolver.maneuverNodes.Count > 1)
                                {
                                    while (vessel_.patchedConicSolver.maneuverNodes.Count > 1)
                                    {
                                        if (vessel_.patchedConicSolver.maneuverNodes.First() ==
                                            guidance_node_)
                                        {
                                            vessel_.patchedConicSolver.maneuverNodes.Last().RemoveSelf();
                                        }
                                        else
                                        {
                                            vessel_.patchedConicSolver.maneuverNodes.First().RemoveSelf();
                                        }
                                    }
                                }
                                Vector3d stock_velocity_at_node_time =
                                    vessel_.orbit.getOrbitalVelocityAtUT(
                                        manoeuvre.burn.initial_time).xzy;
                                Vector3d stock_displacement_from_parent_at_node_time =
                                    vessel_.orbit.getRelativePositionAtUT(
                                        manoeuvre.burn.initial_time).xzy;
                                UnityEngine.Quaternion stock_frenet_frame_to_world =
                                    UnityEngine.Quaternion.LookRotation(
                                        stock_velocity_at_node_time,
                                        Vector3d.Cross(
                                            stock_velocity_at_node_time,
                                            stock_displacement_from_parent_at_node_time));
                                guidance_node_.DeltaV =
                                    ((Vector3d)manoeuvre.burn.delta_v).magnitude *
                                    (Vector3d)(UnityEngine.Quaternion.Inverse(
                                                   stock_frenet_frame_to_world) *
                                               (Vector3d)guidance);
                                guidance_node_.UT = manoeuvre.burn.initial_time;
                                vessel_.patchedConicSolver.UpdateFlightPlan();
                                should_clear_guidance = false;
                            }
                            break;
                        }
                    }
                }
                if (should_clear_guidance && guidance_node_ != null)
                {
                    guidance_node_.RemoveSelf();
                    guidance_node_ = null;
                }
            }
Beispiel #37
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            //Solid argument
            bool isSolid = ((Value.Number)args[0]).Item == 1;

            //Surface argument
            bool isSurface = ((Value.Number)args[2]).Item == 1;

            //Build up our list of list of references for the form by...
            var curvesListList = (Value.List)args[1];
            //Now we add all of those references into ReferenceArrays
            ReferenceArrayArray refArrArr = new ReferenceArrayArray();

            FSharpList <Value> vals = ((Value.List)curvesListList).Item;

            if (vals.Any() && (vals[0] is Value.Container) && ((Value.Container)vals[0]).Item is ModelCurveArray)
            {
                //Build a sequence that unwraps the input list from it's Value form.
                IEnumerable <ModelCurveArray> modelCurveArrays = ((Value.List)args[1]).Item.Select(
                    x => (ModelCurveArray)((Value.Container)x).Item
                    );

                foreach (var modelCurveArray in modelCurveArrays)
                {
                    var refArr = new ReferenceArray();
                    foreach (Autodesk.Revit.DB.ModelCurve modelCurve in modelCurveArray)
                    {
                        refArr.Append(modelCurve.GeometryCurve.Reference);
                    }
                    refArrArr.Append(refArr);
                }
            }
            else
            {
                IEnumerable <IEnumerable <Reference> > refArrays = (curvesListList).Item.Select(
                    //...first selecting everything in the topmost list...
                    delegate(Value x)
                {
                    //If the element in the topmost list is a sub-list...
                    if (x.IsList)
                    {
                        //...then we return a new IEnumerable of References by converting the sub list.
                        return((x as Value.List).Item.Select(
                                   delegate(Value y)
                        {
                            //Since we're in a sub-list, we can assume it's a container.
                            var item = ((Value.Container)y).Item;
                            if (item is CurveElement)
                            {
                                return (item as CurveElement).GeometryCurve.Reference;
                            }
                            else
                            {
                                return (Reference)item;
                            }
                        }
                                   ));
                    }
                    //If the element is not a sub-list, then just assume it's a container.
                    else
                    {
                        var obj = ((Value.Container)x).Item;
                        Reference r;
                        if (obj is CurveElement)
                        {
                            r = (obj as CurveElement).GeometryCurve.Reference;
                        }
                        else
                        {
                            r = (Reference)obj;
                        }
                        //We return a list here since it's expecting an IEnumerable<Reference>. In reality,
                        //just passing the element by itself instead of a sub-list is a shortcut for having
                        //a list with one element, so this is just performing that for the user.
                        return(new List <Reference>()
                        {
                            r
                        });
                    }
                }
                    );

                //Now we add all of those references into ReferenceArrays

                foreach (IEnumerable <Reference> refs in refArrays.Where(x => x.Any()))
                {
                    var refArr = new ReferenceArray();
                    foreach (Reference r in refs)
                    {
                        refArr.Append(r);
                    }
                    refArrArr.Append(refArr);
                }
            }
            //If we already have a form stored...
            if (this.Elements.Any())
            {
                Form oldF;
                //is this same element?
                if (dynUtils.TryGetElement(this.Elements[0], out oldF))
                {
                    if (oldF.IsSolid == isSolid &&
                        _preferSurfaceForOneLoop == isSurface &&
                        matchOrAddFormCurveToReferenceCurveMap(oldF, refArrArr, true))
                    {
                        return(Value.NewContainer(oldF));
                    }
                }

                //Dissolve it, we will re-make it later.
                if (FormUtils.CanBeDissolved(this.UIDocument.Document, this.Elements.Take(1).ToList()))
                {
                    FormUtils.DissolveForms(this.UIDocument.Document, this.Elements.Take(1).ToList());
                }
                //And register the form for deletion. Since we've already deleted it here manually, we can
                //pass "true" as the second argument.
                this.DeleteElement(this.Elements[0], true);
            }
            else if (this._formId != ElementId.InvalidElementId)
            {
                Form oldF;
                if (dynUtils.TryGetElement(this._formId, out oldF))
                {
                    if (oldF.IsSolid == isSolid &&
                        _preferSurfaceForOneLoop == isSurface &&
                        matchOrAddFormCurveToReferenceCurveMap(oldF, refArrArr, true))
                    {
                        return(Value.NewContainer(oldF));
                    }
                }
            }

            _preferSurfaceForOneLoop = isSurface;

            //We use the ReferenceArrayArray to make the form, and we store it for later runs.

            Form f;

            //if we only have a single refArr, we can make a capping surface or an extrusion
            if (refArrArr.Size == 1)
            {
                ReferenceArray refArr = refArrArr.get_Item(0);

                if (isSurface) // make a capping surface
                {
                    f = this.UIDocument.Document.FamilyCreate.NewFormByCap(true, refArr);
                }
                else  // make an extruded surface
                {
                    // The extrusion form direction
                    XYZ direction = new XYZ(0, 0, 50);
                    f = this.UIDocument.Document.FamilyCreate.NewExtrusionForm(true, refArr, direction);
                }
            }
            else // make a lofted surface
            {
                f = this.UIDocument.Document.FamilyCreate.NewLoftForm(isSolid, refArrArr);
            }

            matchOrAddFormCurveToReferenceCurveMap(f, refArrArr, false);
            this.Elements.Add(f.Id);

            return(Value.NewContainer(f));
        }
Beispiel #38
0
 public bool AllowReference(Reference r, XYZ p)
 {
     return(false);
 }
Beispiel #39
0
 /// <summary>
 /// This class does not filter for references
 /// </summary>
 /// <param name="reference"></param>
 /// <param name="position"></param>
 /// <returns>true</returns>
 public bool AllowReference(Reference reference, XYZ position)
 {
     return(true);
 }
Beispiel #40
0
        public void MoveElement(Document doc, FamilyInstance familyInstance, XYZ point1, XYZ point2)
        {
            Line line  = Line.CreateBound(point1, point2);
            XYZ  direc = line.Direction * 0.010417;

            using (Transaction tr = new Transaction(doc, "Move element"))
            {
                tr.Start();
                ElementTransformUtils.MoveElement(doc, familyInstance.Id, direc);
                tr.Commit();
            }
        }
Beispiel #41
0
        protected override void CreateShapeInternal(IFCImportShapeEditScope shapeEditScope, Transform lcs, Transform scaledLcs, string guid)
        {
            using (BuilderScope bs = shapeEditScope.InitializeBuilder(IFCShapeBuilderType.TessellatedShapeBuilder))
            {
                base.CreateShapeInternal(shapeEditScope, lcs, scaledLcs, guid);

                TessellatedShapeBuilderScope tsBuilderScope = bs as TessellatedShapeBuilderScope;

                tsBuilderScope.StartCollectingFaceSet();

                // Create the face set from IFCIndexedPolygonalFace
                foreach (IFCIndexedPolygonalFace face in Faces)
                {
                    tsBuilderScope.StartCollectingFace(GetMaterialElementId(shapeEditScope));

                    IList <XYZ> loopVertices = new List <XYZ>();
                    foreach (int vertInd in face.CoordIndex)
                    {
                        int actualVIdx = vertInd - 1; // IFC starts the list position at 1
                        if (PnIndex != null)
                        {
                            actualVIdx = PnIndex[actualVIdx] - 1;
                        }
                        IList <double> vert   = Coordinates.CoordList[actualVIdx];
                        XYZ            vertex = applyProjectUnitScaleVertex(new XYZ(vert[0], vert[1], vert[2]));
                        loopVertices.Add(scaledLcs.OfPoint(vertex));
                    }
                    IList <XYZ> validVertices;
                    IFCGeometryUtil.CheckAnyDistanceVerticesWithinTolerance(Id, shapeEditScope, loopVertices, out validVertices);

                    bool bPotentiallyAbortFace = false;
                    if (!tsBuilderScope.AddLoopVertices(Id, validVertices))
                    {
                        bPotentiallyAbortFace = true;
                    }

                    // Handle holes
                    if (face.InnerCoordIndices != null)
                    {
                        foreach (IList <int> innerLoop in face.InnerCoordIndices)
                        {
                            IList <XYZ> innerLoopVertices = new List <XYZ>();
                            foreach (int innerVerIdx in innerLoop)
                            {
                                int actualVIdx = innerVerIdx - 1;
                                if (PnIndex != null)
                                {
                                    actualVIdx = PnIndex[actualVIdx] - 1;
                                }
                                IList <double> vert   = Coordinates.CoordList[actualVIdx];
                                XYZ            vertex = applyProjectUnitScaleVertex(new XYZ(vert[0], vert[1], vert[2]));
                                // add vertex to the loop
                                innerLoopVertices.Add(scaledLcs.OfPoint(vertex));
                            }
                            IList <XYZ> validInnerV;
                            IFCGeometryUtil.CheckAnyDistanceVerticesWithinTolerance(Id, shapeEditScope, innerLoopVertices, out validInnerV);

                            if (!tsBuilderScope.AddLoopVertices(Id, validInnerV))
                            {
                                bPotentiallyAbortFace = true;
                            }
                        }
                    }

                    if (bPotentiallyAbortFace)
                    {
                        tsBuilderScope.AbortCurrentFace();
                    }
                    else
                    {
                        tsBuilderScope.StopCollectingFace();
                    }
                }

                IList <GeometryObject> createdGeometries = tsBuilderScope.CreateGeometry(guid);
                if (createdGeometries != null)
                {
                    foreach (GeometryObject createdGeometry in createdGeometries)
                    {
                        shapeEditScope.AddGeometry(IFCSolidInfo.Create(Id, createdGeometry));
                    }
                }
            }
        }
Beispiel #42
0
        //updates all controls
        private void UpdateUI()
        {
            if (edit.Gradient == null)
            {
                grpStops.Enabled = false;
            }
            else
            {
                grpStops.Enabled = true;
                //ColorPoint cpt = edit.Selection as ColorPoint;
                if (edit.Selection.Count > 0)
                {
                    vColorLoc.Enabled      = true;
                    lblColorSelect.Enabled = btnDeleteColor.Enabled = !edit.FocusSelection;
                    //
                    vColorLoc.Value =
                        (int)((edit.FocusSelection ? edit.Selection.First().Focus : edit.Selection.First().Position) * 100.0);

                    if (edit.Selection.Count == 0)
                    {
                        lblColorSelect.Color = Color.DimGray;
                    }
                    else
                    {
                        ColorPoint cpt = edit.Selection.First() as ColorPoint;
                        lblColorSelect.Color = edit.FocusSelection
                                                                        ? Color.DimGray
                                                                        : lblColorSelect.OldColor = (_xyz = cpt.Color).ToRGB().ToArgb();
                    }
                }
                else
                {
                    lblColorSelect.Enabled = vColorLoc.Enabled = btnDeleteColor.Enabled = false;
                    lblColorSelect.Color   = lblColorSelect.OldColor = Color.DimGray;
                    vColorLoc.Value        = 0;
                }
            }
        }
Beispiel #43
0
        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;

            // obtain the current selection and pick
            // out all walls from it:

            //Selection sel = uidoc.Selection; // 2014

            ICollection <ElementId> ids = uidoc.Selection
                                          .GetElementIds(); // 2015

            List <Wall> walls = new List <Wall>(2);

            //foreach( Element e in sel.Elements ) // 2014

            foreach (ElementId id in ids) // 2015
            {
                Element e = doc.GetElement(id);

                if (e is Wall)
                {
                    walls.Add(e as Wall);
                }
            }

            if (2 != walls.Count)
            {
                message = _prompt;
                return(Result.Failed);
            }

            // ensure the two selected walls are straight and
            // parallel; determine their mutual normal vector
            // and a point on each wall for distance
            // calculations:

            List <Line> lines     = new List <Line>(2);
            List <XYZ>  midpoints = new List <XYZ>(2);
            XYZ         normal    = null;

            foreach (Wall wall in walls)
            {
                LocationCurve lc    = wall.Location as LocationCurve;
                Curve         curve = lc.Curve;

                if (!(curve is Line))
                {
                    message = _prompt;
                    return(Result.Failed);
                }

                Line l = curve as Line;
                lines.Add(l);
                midpoints.Add(Util.Midpoint(l));

                if (null == normal)
                {
                    normal = Util.Normal(l);
                }
                else
                {
                    if (!Util.IsParallel(normal, Util.Normal(l)))
                    {
                        message = _prompt;
                        return(Result.Failed);
                    }
                }
            }

            // find the two closest facing faces on the walls;
            // they are vertical faces that are parallel to the
            // wall curve and closest to the other wall.

            Options opt = app.Create.NewGeometryOptions();

            opt.ComputeReferences = true;

            List <Face> faces = new List <Face>(2);

            faces.Add(GetClosestFace(walls[0], midpoints[1], normal, opt));
            faces.Add(GetClosestFace(walls[1], midpoints[0], normal, opt));

            // create the dimensioning:

            CreateDimensionElement(doc.ActiveView,
                                   midpoints[0], faces[0].Reference,
                                   midpoints[1], faces[1].Reference);

            return(Result.Succeeded);
        }
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            Result rc = Result.Failed;

            UIApplication app = commandData.Application;
            Document      doc = app.ActiveUIDocument.Document;

            // Check whether the family we are
            // interested in is loaded:

#if _2010
            List <Element> symbols = new List <Element>();

            Filter filter = app.Create.Filter.NewFamilyFilter(
                _family_name);

            doc.get_Elements(filter, symbols);

            // the family filter returns both the
            // symbols and the family itself:

            Family f = null;
            foreach (Element e in symbols)
            {
                if (e is Family)
                {
                    f = e as Family;
                }
                else if (e is FamilySymbol)
                {
                    FamilySymbol s = e as FamilySymbol;
                    Debug.Print(
                        "Family name={0}, symbol name={1}",
                        s.Family.Name, s.Name);
                }
            }
#endif

            Family f = Util.GetFirstElementOfTypeNamed(
                doc, typeof(Family), _family_name) as Family;

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Create New Column Type and Instance");

                // If the family was not already loaded, then do so:

                if (null == f)
                {
                    if (!doc.LoadFamily(_path, out f))
                    {
                        message = "Unable to load '" + _path + "'.";
                    }
                }

                if (null != f)
                {
                    Debug.Print("Family name={0}", f.Name);

                    // Pick a symbol for duplication, any one
                    // will do, we select the first:

                    FamilySymbol s = null;

                    //foreach( FamilySymbol s2 in f.Symbols ) // 2014

                    foreach (ElementId id in f.GetFamilySymbolIds()) // 2015
                    {
                        s = doc.GetElement(id) as FamilySymbol;
                        break;
                    }

                    Debug.Assert(null != s,
                                 "expected at least one symbol"
                                 + " to be defined in family");

                    // Duplicate the existing symbol:

                    ElementType s1 = s.Duplicate("Nuovo simbolo");
                    s = s1 as FamilySymbol;

                    // Analyse the symbol parameters:

                    foreach (Parameter param in s.Parameters)
                    {
                        Debug.Print(
                            "Parameter name={0}, value={1}",
                            param.Definition.Name,
                            param.AsValueString());
                    }

                    // Define new dimensions for our new type;
                    // the specified parameter name is case sensitive:

                    //s.get_Parameter( "Width" ).Set( Util.MmToFoot( 500 ) ); // 2014
                    //s.get_Parameter( "Depth" ).Set( Util.MmToFoot( 1000 ) ); // 2014

                    s.LookupParameter("Width").Set(Util.MmToFoot(500));  // 2015
                    s.LookupParameter("Depth").Set(Util.MmToFoot(1000)); // 2015

                    // We can change the symbol name at any time:

                    s.Name = "Nuovo simbolo due";

                    // Insert an instance of our new symbol:

                    XYZ p = XYZ.Zero;
                    doc.Create.NewFamilyInstance(
                        p, s, nonStructural);

                    // For a column, the reference direction is ignored:

                    //XYZ normal = new XYZ( 1, 2, 3 );
                    //doc.Create.NewFamilyInstance(
                    //  p, s, normal, null, nonStructural );

                    rc = Result.Succeeded;
                }
                t.Commit();
            }
            return(rc);
        }
Beispiel #45
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            var doc          = dynRevitSettings.Doc;
            var refCurveList = ((Value.List)args[0]).Item.Select(
                x => (((Value.Container)x).Item is Autodesk.Revit.DB.ModelCurve ?
                      ((Autodesk.Revit.DB.ModelCurve)((Value.Container)x).Item)
                   : (Autodesk.Revit.DB.ModelCurve)(
                          doc.Document.GetElement(
                              ((Reference)((Value.Container)x).Item).ElementId)
                          )
                      )
                ).ToList();

            ModelCurveArray myModelCurves = new ModelCurveArray();

            //Plane thisPlane = null;
            //Line oneLine = null;

            List <ElementId> refIds = new List <ElementId>();
            XYZ    loopStart        = new XYZ();
            XYZ    otherEnd         = new XYZ();
            int    index            = 0;
            double tolerance        = 0.000000001;

            foreach (var refCurve in refCurveList)
            {
                if (index == 0)
                {
                    loopStart = refCurve.GeometryCurve.Evaluate(0.0, true);
                    otherEnd  = refCurve.GeometryCurve.Evaluate(1.0, true);
                }
                else //if (index > 0)
                {
                    XYZ startXYZ = refCurve.GeometryCurve.Evaluate(0.0, true);
                    XYZ endXYZ   = refCurve.GeometryCurve.Evaluate(1.0, true);
                    if (index == 1)
                    {
                        if (startXYZ.DistanceTo(otherEnd) > tolerance && endXYZ.DistanceTo(otherEnd) > tolerance &&
                            (startXYZ.DistanceTo(loopStart) > tolerance || endXYZ.DistanceTo(loopStart) > tolerance))
                        {
                            XYZ temp = loopStart;
                            loopStart = otherEnd;
                            otherEnd  = temp;
                        }
                        if (startXYZ.DistanceTo(otherEnd) > tolerance && endXYZ.DistanceTo(otherEnd) < tolerance)
                        {
                            otherEnd = startXYZ;
                        }
                        else if (startXYZ.DistanceTo(otherEnd) < tolerance && endXYZ.DistanceTo(otherEnd) > tolerance)
                        {
                            otherEnd = endXYZ;
                        }
                        else
                        {
                            throw new Exception("Gap between curves in chain of reference curves.");
                        }
                    }
                }

                /* not needed check
                 * if (refCurve.GeometryCurve is Line)
                 * {
                 *  Line thisLine = refCurve.GeometryCurve as Line;
                 *  if (thisPlane != null)
                 *  {
                 *      if (Math.Abs(thisPlane.Normal.DotProduct(thisLine.Direction)) > tolerance)
                 *          throw new Exception(" Planar Ref Curve Chain fails: not planar");
                 *      if (Math.Abs(thisPlane.Normal.DotProduct(thisLine.Origin - thisPlane.Origin)) > tolerance)
                 *          throw new Exception(" Planar Ref Curve Chain fails: not planar");
                 *  }
                 *  else if (oneLine == null)
                 *      oneLine = thisLine;
                 *  else
                 *  {
                 *      if (Math.Abs(oneLine.Direction.DotProduct(thisLine.Direction)) > 1.0 - tolerance)
                 *      {
                 *          double projAdjust = oneLine.Direction.DotProduct(oneLine.Origin - thisLine.Origin);
                 *          XYZ adjustedOrigin = thisLine.Origin + projAdjust * oneLine.Direction;
                 *          if (adjustedOrigin.DistanceTo(oneLine.Origin) > tolerance)
                 *              throw new Exception(" Planar Ref Curve Chain fails: not planar");
                 *      }
                 *      else
                 *      {
                 *          XYZ norm = oneLine.Direction.CrossProduct(thisLine.Direction);
                 *          norm = norm.Normalize();
                 *          thisPlane = new Plane(norm, oneLine.Origin);
                 *          if (Math.Abs(thisPlane.Normal.DotProduct(thisLine.Origin - thisPlane.Origin)) > tolerance)
                 *              throw new Exception(" Planar Ref Curve Chain fails: not planar");
                 *      }
                 *
                 *  }
                 * }
                 * else
                 * {
                 *  CurveLoop curveLoop = new CurveLoop();
                 *  curveLoop.Append(refCurve.GeometryCurve);
                 *  if (!curveLoop.HasPlane())
                 *      throw new Exception(" Planar Ref Curve Chain fails: curve is not planar.");
                 *  Plane curvePlane = curveLoop.GetPlane();
                 *  if (thisPlane == null && oneLine == null)
                 *      thisPlane = curveLoop.GetPlane();
                 *  else if (thisPlane != null)
                 *  {
                 *      if (Math.Abs(thisPlane.Normal.DotProduct(curvePlane.Normal)) < 1.0 - tolerance)
                 *          throw new Exception(" Planar Ref Curve Chain fails: not planar");
                 *      if (Math.Abs(thisPlane.Normal.DotProduct(curvePlane.Origin - thisPlane.Origin)) > tolerance)
                 *          throw new Exception(" Planar Ref Curve Chain fails: not planar");
                 *  }
                 *  else if (oneLine != null)
                 *  {
                 *      thisPlane = curvePlane;
                 *      if (Math.Abs(thisPlane.Normal.DotProduct(oneLine.Direction)) > tolerance)
                 *          throw new Exception(" Planar Ref Curve Chain fails: not planar");
                 *      if (Math.Abs(thisPlane.Normal.DotProduct(oneLine.Origin - thisPlane.Origin)) > tolerance)
                 *          throw new Exception(" Planar Ref Curve Chain fails: not planar");
                 *  }
                 * }
                 */

                refIds.Add(refCurve.Id);
                myModelCurves.Append(refCurve);
                index++;
            }

            List <ElementId> removeIds = new List <ElementId>();

            foreach (ElementId oldId in this.Elements)
            {
                if (!refIds.Contains(oldId))
                {
                    removeIds.Add(oldId);
                }
            }

            foreach (ElementId removeId in removeIds)
            {
                this.Elements.Remove(removeId);
            }
            foreach (ElementId newId in refIds)
            {
                if (!this.Elements.Contains(newId))
                {
                    this.Elements.Add(newId);
                }
            }
            //if (!curveLoop.HasPlane())
            //    throw new Exception(" Planar Ref Curve Chain fails: not planar");
            return(Value.NewContainer(myModelCurves));
        }
Beispiel #46
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiApp = commandData.Application;

            Autodesk.Revit.ApplicationServices.Application app = uiApp.Application;
            UIDocument uiDoc = uiApp.ActiveUIDocument;
            Document   doc   = uiDoc.Document;
            SortableBindingList <SearchHit> results          = new SortableBindingList <SearchHit>();
            ElementClassFilter       FamilyInstanceFilter    = new ElementClassFilter(typeof(FamilyInstance));
            FilteredElementCollector FamilyInstanceCollector = new FilteredElementCollector(doc);
            ICollection <Element>    AllFamilyInstances      = FamilyInstanceCollector.WherePasses(FamilyInstanceFilter).ToElements();
            List <ElementId>         liIds    = new List <ElementId>();
            List <string>            ParamLst = new List <string>();

            Autodesk.Revit.DB.View  view = doc.ActiveView;
            SelectionChangedWatcher _selectionChangedWatcher = new SelectionChangedWatcher(uiDoc, false);
            FamilySymbol            FmlySmbl;
            Family Fmly;
            string s = string.Empty;

            Global.Instance.OurForm2 = new Form2(_selectionChangedWatcher);



            double cvolume = 0.00, svolume = 0.00;

            foreach (FamilyInstance f in AllFamilyInstances)
            {
                FmlySmbl = f.Symbol;
                Fmly     = FmlySmbl.Family;
                // Add Instance Parameter names to list
                s += "\n" + f.Name + "\n";
                s += f.Category.Name + "\n";
                s += FmlySmbl.Name + "\n";
                s += Fmly.Name + "\n";
                ElementId elemId = f.Id;
                ICollection <ElementId> materials = f.GetMaterialIds(false);

                foreach (ElementId matId in materials)
                {
                    Material material = doc.GetElement(matId) as Material;
                    s += "Materials = " + material.Name + "\n";

                    s += "Material Volume =" + f.GetMaterialVolume(matId) + "\n";
                    s += "Material Area = " + f.GetMaterialArea(matId, false) + "\n";
                    double volume = f.GetMaterialVolume(matId);
                    volume = Math.Round(volume, 2);
                    double         cost         = Math.Round(volume * 100, 2);
                    BoundingBoxXYZ bounding     = f.get_BoundingBox(null);
                    XYZ            center       = (bounding.Max + bounding.Min) * 0.5;
                    string         sCoordinates = Math.Round(center.X, 5) + ", " + Math.Round(center.Y, 5) + ", " + Math.Round(center.Z, 5);
                    XYZ            size         = bounding.Max - bounding.Min;
                    string         sLength      = " " + Math.Round(Math.Max(size.X, Math.Max(size.Y, size.Z)), 2);

                    int nbeams = 0, ncolumns = 0;
                    if (material.Name.Contains("Concrete") || material.Name.Contains("Steel"))
                    {
                        if (material.Name.Contains("Concrete"))
                        {
                            cvolume += f.GetMaterialVolume(matId);
                        }
                        if (material.Name.Contains("Steel"))
                        {
                            svolume += f.GetMaterialVolume(matId);
                        }


                        liIds.Add(f.Id);
                        Global.Instance.OurForm2.appendVolume(Math.Round(svolume, 2), Math.Round(cvolume, 2), nbeams, ncolumns);
                    }
                }
                // Get FamilyInstance AnalyticalModel type
                if (null != f.GetAnalyticalModel())
                {
                    //  s += "FamilyInstance AnalyticalModel is : " + f.GetAnalyticalModel() + "\n";
                }
                // Get FamilyInstance host name
                if (f.Host != null)
                {
                    s += "FamilyInstance host name is : " + f.Host.Name + "\n";
                }
            }
            // string path ="C:\\Users\\Tarun Sahu\\Desktop\\info.txt";

            //File.WriteAllText(path,s);

            Transaction tx = new Transaction(doc);

            tx.Start("Isolate search selection");
            // Requires transaction



            tx.Commit();

            Global.Instance.OurForm2.Show(NativeWindow.FromHandle(Global.Instance.RevitWindowHandle));
            // Global.Instance.OurForm.button3_Click_1();
            return(Result.Succeeded);
        }
 public bool AllowReference(Reference r, XYZ p)
 {
     return(true);
 }
Beispiel #48
0
        public override void Evaluate(FSharpList <Value> args, Dictionary <PortData, Value> outPuts)
        {
            var  crv  = (Curve)((Value.Container)args[0]).Item;
            Face face = null;

            Autodesk.Revit.DB.Plane thisPlane = null;

            var geo = ((Value.Container)args[1]).Item;

            if (geo is Face)
            {
                face = geo as Face;
            }
            else if (geo is Autodesk.Revit.DB.Plane)
            {
                #region plane processing

                thisPlane = geo as Autodesk.Revit.DB.Plane;
                // tesselate curve and find uv envelope in projection to the plane
                IList <XYZ> tessCurve      = crv.Tessellate();
                var         curvePointEnum = tessCurve.GetEnumerator();
                var         corner1        = new XYZ();
                var         corner2        = new XYZ();
                bool        cornersSet     = false;
                for (; curvePointEnum.MoveNext();)
                {
                    if (!cornersSet)
                    {
                        corner1    = curvePointEnum.Current;
                        corner2    = curvePointEnum.Current;
                        cornersSet = true;
                    }
                    else
                    {
                        for (int coord = 0; coord < 3; coord++)
                        {
                            if (corner1[coord] > curvePointEnum.Current[coord])
                            {
                                corner1 = new XYZ(coord == 0 ? curvePointEnum.Current[coord] : corner1[coord],
                                                  coord == 1 ? curvePointEnum.Current[coord] : corner1[coord],
                                                  coord == 2 ? curvePointEnum.Current[coord] : corner1[coord]);
                            }
                            if (corner2[coord] < curvePointEnum.Current[coord])
                            {
                                corner2 = new XYZ(coord == 0 ? curvePointEnum.Current[coord] : corner2[coord],
                                                  coord == 1 ? curvePointEnum.Current[coord] : corner2[coord],
                                                  coord == 2 ? curvePointEnum.Current[coord] : corner2[coord]);
                            }
                        }
                    }
                }

                double dist1    = thisPlane.Origin.DistanceTo(corner1);
                double dist2    = thisPlane.Origin.DistanceTo(corner2);
                double sizeRect = 2.0 * (dist1 + dist2) + 100.0;

                var cLoop = new Autodesk.Revit.DB.CurveLoop();
                for (int index = 0; index < 4; index++)
                {
                    double coord0 = (index == 0 || index == 3) ? -sizeRect : sizeRect;
                    double coord1 = (index < 2) ? -sizeRect : sizeRect;
                    XYZ    pnt0   = thisPlane.Origin + coord0 * thisPlane.XVec + coord1 * thisPlane.YVec;

                    double coord3 = (index < 2) ? sizeRect : -sizeRect;
                    double coord4 = (index == 0 || index == 3) ? -sizeRect : sizeRect;
                    XYZ    pnt1   = thisPlane.Origin + coord3 * thisPlane.XVec + coord4 * thisPlane.YVec;
                    Line   cLine  = dynRevitSettings.Revit.Application.Create.NewLineBound(pnt0, pnt1);
                    cLoop.Append(cLine);
                }
                var listCLoops = new List <Autodesk.Revit.DB.CurveLoop> {
                    cLoop
                };

                Solid tempSolid = GeometryCreationUtilities.CreateExtrusionGeometry(listCLoops, thisPlane.Normal, 100.0);

                //find right face

                FaceArray facesOfExtrusion = tempSolid.Faces;
                for (int indexFace = 0; indexFace < facesOfExtrusion.Size; indexFace++)
                {
                    Face faceAtIndex = facesOfExtrusion.get_Item(indexFace);
                    if (faceAtIndex is PlanarFace)
                    {
                        var pFace = faceAtIndex as PlanarFace;
                        if (Math.Abs(thisPlane.Normal.DotProduct(pFace.Normal)) < 0.99)
                        {
                            continue;
                        }
                        if (Math.Abs(thisPlane.Normal.DotProduct(thisPlane.Origin - pFace.Origin)) > 0.1)
                        {
                            continue;
                        }
                        face = faceAtIndex;
                        break;
                    }
                }
                if (face == null)
                {
                    throw new Exception("Curve Face Intersection could not process supplied Plane.");
                }

                #endregion
            }

            IntersectionResultArray xsects;
            var result = face.Intersect(crv, out xsects);

            //var xsect_results = FSharpList<Value>.Empty;
            var xsect_xyzs        = FSharpList <Value> .Empty;
            var xsect_face_uvs    = FSharpList <Value> .Empty;
            var xsect_params      = FSharpList <Value> .Empty;
            var xsect_edges       = FSharpList <Value> .Empty;
            var xsect_edge_params = FSharpList <Value> .Empty;

            var results = FSharpList <Value> .Empty;
            if (xsects != null)
            {
                foreach (IntersectionResult ir in xsects)
                {
                    var xsect = FSharpList <Value> .Empty;
                    try
                    {
                        xsect_edge_params = FSharpList <Value> .Cons(Value.NewNumber(ir.EdgeParameter), xsect_edge_params);
                    }
                    catch
                    {
                        xsect_edge_params = FSharpList <Value> .Cons(Value.NewNumber(0), xsect_edge_params);
                    }
                    xsect_edges = FSharpList <Value> .Cons(Value.NewContainer(ir.EdgeObject), xsect_edges);

                    xsect_params = FSharpList <Value> .Cons(Value.NewNumber(ir.Parameter), xsect_params);

                    if (thisPlane != null)
                    {
                        UV planeUV = new UV(thisPlane.XVec.DotProduct(ir.XYZPoint - thisPlane.Origin),
                                            thisPlane.YVec.DotProduct(ir.XYZPoint - thisPlane.Origin));
                        xsect_face_uvs = FSharpList <Value> .Cons(Value.NewContainer(planeUV), xsect_face_uvs);
                    }
                    else
                    {
                        xsect_face_uvs = FSharpList <Value> .Cons(Value.NewContainer(ir.UVPoint), xsect_face_uvs);
                    }

                    xsect_xyzs = FSharpList <Value> .Cons(Value.NewContainer(ir.XYZPoint), xsect_xyzs);

                    //xsect_results = FSharpList<Value>.Cons(Value.NewList(xsect), xsect_results);
                }
            }

            outPuts[_edgeTPort]  = Value.NewList(xsect_edge_params);
            outPuts[_edgePort]   = Value.NewList(xsect_edges);
            outPuts[_tPort]      = Value.NewList(xsect_params);
            outPuts[_uvPort]     = Value.NewList(xsect_face_uvs);
            outPuts[_xyzPort]    = Value.NewList(xsect_xyzs);
            outPuts[_resultPort] = Value.NewString(result.ToString());
        }
Beispiel #49
0
        private static XYZ getVertVec(XYZ vec)
        {
            XYZ ret = new XYZ(-vec.Y + vec.Z, vec.X + vec.Z, -vec.Y - vec.X);

            return(ret);
        }
Beispiel #50
0
        public List <Curve> createIsovist(XYZ curPoint, int numRays, double radius, double startAngle, double endAngle, View curView, Document curDoc, SketchPlane eyeSketchPlane, List <Face> wallFaces, ElementId defaultFRId)
        {
            XYZ xAxis = new XYZ(1, 0, 0);
            XYZ yAxis = new XYZ(0, 1, 0);


            Arc arc = Arc.Create(curPoint, radius, startAngle, endAngle, xAxis, yAxis);
            //ModelCurve newArc = curDoc.Create.NewModelCurve(arc, eyeSketchPlane);

            int    counter = 0;
            double meter   = 0;
            double step    = endAngle / numRays;

            List <Line> lineList = new List <Line>();

            for (int i = 0; i < numRays; i++)
            {
                XYZ  arcParam = arc.Evaluate(meter, false);
                Line lineOut  = Line.CreateBound(curPoint, arcParam);
                lineList.Add(lineOut);
                //ModelCurve newModelCurve = curDoc.Create.NewModelCurve(lineOut, eyeSketchPlane);

                meter = meter + step;
            }

            List <Line>   interList   = new List <Line>();
            List <Line>   outerList   = new List <Line>();
            List <double> lineLengths = new List <double>();


            foreach (Line curLine in lineList)
            {
                outerList.Clear();

                foreach (Face curFace in wallFaces)
                {
                    XYZ interPoint     = intersectFaceCurve(curLine, curFace);
                    UV  parms          = new UV(.5, .5);
                    XYZ curFaceLocator = curFace.Evaluate(parms);

                    double curDistance = curPoint.DistanceTo(curFaceLocator);

                    if (curDistance <= radius - (radius * .1))
                    {
                        XYZ interPoints = intersectFaceCurve(curLine, curFace);

                        if (interPoints != null)
                        {
                            if (interPoints.DistanceTo(curPoint) >= .3)
                            {
                                Line interLine = Line.CreateBound(curPoint, interPoint);

                                outerList.Add(interLine);
                            }
                        }

                        counter++;
                    }
                }

                outerList.Add(curLine);


                lineLengths.Clear();

                foreach (Line outerLine in outerList)
                {
                    double lineLength = outerLine.Length;

                    lineLengths.Add(lineLength);
                }


                int indexMin = lineLengths.IndexOf(lineLengths.Min());
                interList.Add(outerList[indexMin]);
            }



            List <XYZ> endPoints = new List <XYZ>();

            foreach (Line line in interList)
            {
                if (line.Length != radius)
                {
                    endPoints.Add(line.GetEndPoint(1));
                }
            }



            List <Curve> outLineList = new List <Curve>();

            for (int i = 1; i <= endPoints.Count - 1; i++)
            {
                outLineList.Add(Line.CreateBound(endPoints[i - 1], endPoints[i]));
            }
            outLineList.Add(Line.CreateBound(endPoints[endPoints.Count - 1], endPoints[0]));

            CurveLoop regionLoop = CurveLoop.Create(outLineList);


            foreach (Line line in outLineList)
            {
                //ModelCurve newModelCurve = curDoc.Create.NewModelCurve(line, eyeSketchPlane);
            }

            List <CurveLoop> regionLoops = new List <CurveLoop>();

            regionLoops.Add(regionLoop);

            //FilledRegion region = FilledRegion.Create(curDoc, defaultFRId, curView.Id, regionLoops);



            return(outLineList);
        }
 public XyzInMetres(XYZ p_in_feet)
 {
     X = FeetToMetre(p_in_feet.X);
     Y = FeetToMetre(p_in_feet.Y);
     Z = FeetToMetre(p_in_feet.Z);
 }
Beispiel #52
0
 /// <summary>
 /// Return a clipper integer point
 /// from a Revit model space one.
 /// Do so by dropping the Z coordinate
 /// and converting from imperial feet
 /// to millimetres.
 /// </summary>
 IntPoint GetIntPoint(XYZ p)
 {
     return(new IntPoint(
                ConvertFeetToMillimetres(p.X),
                ConvertFeetToMillimetres(p.Y)));
 }
Beispiel #53
0
        private void WriteElementGeometry(int elementId)
        {
            FilteredElementCollector viewCollector = new FilteredElementCollector(m_doc);

            viewCollector.OfClass(typeof(ViewPlan));
            Func <ViewPlan, bool> isLevel1FloorPlan = v => !v.IsTemplate && v.Name == "Level 1" && v.ViewType == ViewType.FloorPlan;

            m_targetView = viewCollector.Cast <ViewPlan>().First <ViewPlan>(isLevel1FloorPlan);

            Transaction createCurve = new Transaction(m_doc, "Create reference curves");

            createCurve.Start();
            const double xReferenceLocation = 30;
            Line         vLine = Line.CreateBound(new XYZ(xReferenceLocation, 0, 0), new XYZ(xReferenceLocation, 20, 0));

            m_vLine = m_doc.Create.NewDetailCurve(m_targetView, vLine);

            const double yReferenceLocation = -10;
            Line         hLine = Line.CreateBound(new XYZ(0, yReferenceLocation, 0), new XYZ(20, yReferenceLocation, 0));

            m_hLine = m_doc.Create.NewDetailCurve(m_targetView, hLine);
            createCurve.Commit();

            Element e = m_doc.GetElement(new ElementId(elementId));

            Options options = new Options();

            options.ComputeReferences        = true;
            options.IncludeNonVisibleObjects = true;
            options.View = m_targetView;

            GeometryElement geomElem = e.get_Geometry(options);

            foreach (GeometryObject geomObj in geomElem)
            {
                if (geomObj is Solid)
                {
                    WriteSolid((Solid)geomObj);
                }
                else if (geomObj is GeometryInstance)
                {
                    TraverseGeometryInstance((GeometryInstance)geomObj);
                }
                else
                {
                    m_writer.WriteLine("Something else - " + geomObj.GetType().Name);
                }
            }

            foreach (Curve curve in m_referencePlaneReferences)
            {
                // Try to get the geometry object from reference
                Reference      curveReference = curve.Reference;
                GeometryObject geomObj        = e.GetGeometryObjectFromReference(curveReference);

                if (geomObj != null)
                {
                    m_writer.WriteLine("Curve reference leads to: " + geomObj.GetType().Name);
                }
            }

            // Dimension to reference curves
            foreach (Curve curve in m_referencePlaneReferences)
            {
                DetailCurve targetLine = m_vLine;

                Line line           = (Line)curve;
                XYZ  lineStartPoint = line.GetEndPoint(0);
                XYZ  lineEndPoint   = line.GetEndPoint(1);
                XYZ  direction      = lineEndPoint - lineStartPoint;
                Line dimensionLine  = null;
                if (Math.Abs(direction.Y) < 0.0001)
                {
                    targetLine = m_hLine;
                    XYZ dimensionLineStart = new XYZ(lineStartPoint.X + 5, lineStartPoint.Y, 0);
                    XYZ dimensionLineEnd   = new XYZ(dimensionLineStart.X, dimensionLineStart.Y + 10, 0);

                    dimensionLine = Line.CreateBound(dimensionLineStart, dimensionLineEnd);
                }
                else
                {
                    targetLine = m_vLine;
                    XYZ dimensionLineStart = new XYZ(lineStartPoint.X, lineStartPoint.Y + 5, 0);
                    XYZ dimensionLineEnd   = new XYZ(dimensionLineStart.X + 10, dimensionLineStart.Y, 0);
                    dimensionLine = Line.CreateBound(dimensionLineStart, dimensionLineEnd);
                }

                ReferenceArray references = new ReferenceArray();
                references.Append(curve.Reference);
                references.Append(targetLine.GeometryCurve.Reference);

                Transaction t = new Transaction(m_doc, "Create dimension");
                t.Start();
                m_doc.Create.NewDimension(m_targetView, dimensionLine, references);
                t.Commit();
            }
        }
Beispiel #54
0
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            UIApplication uiapp = commandData.Application;
            UIDocument    uidoc = uiapp.ActiveUIDocument;
            Application   app   = uiapp.Application;

            // Get the current Document
            Document curDoc = uiapp.ActiveUIDocument.Document;

            //Get the current View
            View curView = uidoc.Document.ActiveView;

            BoundingBoxXYZ curViewBoundary = curView.CropBox;


            FilteredElementCollector viewCollector = new FilteredElementCollector(curDoc);

            viewCollector.OfClass(typeof(View3D));
            List <View3D> view3dList = viewCollector.ToElements().Cast <View3D>().Where(x => x.IsTemplate == false).ToList();

            //TaskDialog.Show("test", view3dList.First().ViewName.ToString());


            //Build eyeLevel and eyeLevel sketchplane
            double eyeLevel  = 5;
            XYZ    eyeNormal = new XYZ(0, 0, 1);
            XYZ    xAxis     = new XYZ(1, 0, 0);
            XYZ    yAxis     = new XYZ(0, 1, 0);

            //Isovist variables
            int    numRays       = 600;
            double isoRadius     = 300;
            double isoStartAngle = 0;
            double isoEndAngle   = 360;

            //Convert to radians
            double radIsoStartAngle = (Math.PI / 180) * isoStartAngle;
            double radIsoEndAngle   = (Math.PI / 180) * isoEndAngle;


            //Get all walls
            FilteredElementCollector wallCollector = new FilteredElementCollector(curDoc, curView.Id);

            wallCollector.OfCategory(BuiltInCategory.OST_Walls);


            //Get all stacked walls
            FilteredElementCollector stackedWallCollector = new FilteredElementCollector(curDoc, curView.Id);

            stackedWallCollector.OfCategory(BuiltInCategory.OST_StackedWalls);

            stackedWallCollector.UnionWith(wallCollector).WhereElementIsNotElementType();


            //TaskDialog.Show("Test", stackedWallCollector.Count().ToString() + " Walls");


            List <Face>  wallFaces  = new List <Face>();
            double       totalArea  = 0;
            List <Solid> wallSolids = new List <Solid>();

            foreach (Element curWall in stackedWallCollector)
            {
                Options         opt      = new Options();
                GeometryElement geomElem = curWall.get_Geometry(opt);


                foreach (GeometryObject geomObj in geomElem)
                {
                    Solid geomSolid = geomObj as Solid;
                    wallSolids.Add(geomSolid);


                    if (null != geomSolid)
                    {
                        foreach (Face geomFace in geomSolid.Faces)
                        {
                            totalArea += geomFace.Area;
                            wallFaces.Add(geomFace);
                        }
                    }
                }
            }

            //TaskDialog.Show("test", wallFaces.Count().ToString() + "  Faces");



            //Determine All Defaults for stuff later
            ElementId defaultView3d = curDoc.GetDefaultElementTypeId(ElementTypeGroup.ViewType3D);

            ElementId defaultTxtId = curDoc.GetDefaultElementTypeId(ElementTypeGroup.TextNoteType);
            ElementId defaultFRId  = curDoc.GetDefaultElementTypeId(ElementTypeGroup.FilledRegionType);



            //Create View Boundary filter for roomCollector

            Outline outline = new Outline(new XYZ(curViewBoundary.Min.X, curViewBoundary.Min.Y, -100), new XYZ(curViewBoundary.Max.X, curViewBoundary.Max.Y, 100));
            BoundingBoxIsInsideFilter bbFilter = new BoundingBoxIsInsideFilter(outline);

            //FilteredElementCollector roomList = roomCollector.WherePasses(bbFilter);


            // Get all rooms; Divide into point grid; Return points in curPointList
            RoomFilter filter = new RoomFilter();

            FilteredElementCollector roomCollector = new FilteredElementCollector(curDoc, curView.Id);

            roomCollector.WherePasses(filter).WherePasses(bbFilter);

            TaskDialog.Show("Magic View Region Drawing Machine", "Be sure to set the crop region around the rooms you would like to test, encompassing at least one exterior wall and all bounding elements." +
                            "Only rooms located fully within the bounds of the view range will be calculated.");
            TaskDialog.Show("Magic View Region Drawing Machine", roomCollector.Count().ToString() + " rooms fully visible in current view. The more rooms you run, the longer this will take!");

            Transaction t = new Transaction(curDoc, "Draw Some Lines");

            t.Start();

            View3D curView3d = View3D.CreateIsometric(curDoc, defaultView3d);

            IEnumerable <Element> extWalls = GetExteriorWalls(curDoc, curView);

            //TaskDialog.Show("test", extWalls.Count().ToString() +"  Exterior Walls");

            List <XYZ> somePoints = new List <XYZ>();

            foreach (Element wall in extWalls)
            {
                List <XYZ> pointsList = new List <XYZ>();


                pointsList = GetWallOpenings(wall, eyeLevel, curView3d);

                somePoints.AddRange(pointsList);
            }

            //TaskDialog.Show("test", somePoints.Count.ToString()+" points");


            List <List <Curve> > viewCones = new List <List <Curve> >();



            foreach (XYZ curPoint in somePoints)
            {
                Plane       eyePlane       = Plane.CreateByNormalAndOrigin(eyeNormal, curPoint);
                SketchPlane eyeSketchPlane = SketchPlane.Create(curDoc, eyePlane);

                //Arc arc = Arc.Create(curPoint, 2, 0, 360, xAxis, yAxis);
                //ModelCurve newArc = curDoc.Create.NewModelCurve(arc, eyeSketchPlane);



                List <Curve> outLineList = createIsovist(curPoint, numRays, isoRadius, radIsoStartAngle, radIsoEndAngle, curView, curDoc, eyeSketchPlane, wallFaces, defaultFRId);


                viewCones.Add(outLineList);
            }

            //Convert to polygons in int values
            Polygons polys = GetBoundaryLoops(viewCones);
            //TaskDialog.Show("test", polys.Count.ToString()+ " Polygons");


            //Calculate Intersection
            Polygons union = new Polygons();

            Clipper c = new Clipper();

            c.AddPath(polys[0], PolyType.ptSubject, true);

            for (int i = 1; i < polys.Count - 1; i++)
            {
                c.AddPath(polys[i], PolyType.ptClip, true);
            }

            c.Execute(ClipType.ctUnion, union, PolyFillType.pftPositive);

            /*
             *
             *          TaskDialog.Show("test", union.Count.ToString()+ " Polygons");
             *
             *          if (0 < union.Count)
             *          {
             *                  List<CurveLoop>regionLoops = new List<CurveLoop>();
             *
             *                  for (int p = 0; p < union.Count -1; p++)
             *                  {
             *                          List<Curve> unionLineList = new List<Curve>();
             *                          Polygon poly = union[p];
             *
             *                          for (int i = 1; i <= poly.Count-1; i++)
             *                          {
             *                                  unionLineList.Add(Line.CreateBound(GetXyzPoint(poly[i-1]), GetXyzPoint(poly[i])));
             *
             *                          }
             *                          unionLineList.Add(Line.CreateBound(GetXyzPoint(poly[poly.Count-1]), GetXyzPoint(poly[0])));
             *
             *                          CurveLoop regionLoop = CurveLoop.Create(unionLineList);
             *
             *                          regionLoops.Add(regionLoop);
             *
             *                  }
             *
             *                  FilledRegion region = FilledRegion.Create(curDoc, defaultFRId, curView.Id, regionLoops);
             *
             *
             *          }
             */


            foreach (Room curRoom in roomCollector)
            {
                SpatialElementBoundaryOptions bo = new SpatialElementBoundaryOptions();

                List <Curve> roomCurves = new List <Curve>();
                foreach (List <BoundarySegment> lstBs in curRoom.GetBoundarySegments(bo))
                {
                    foreach (BoundarySegment bs in lstBs)
                    {
                        roomCurves.Add(bs.GetCurve());
                    }
                }

                XYZ sketchPoint = new XYZ(0, 0, 0);

                Plane       eyePlane       = Plane.CreateByNormalAndOrigin(eyeNormal, sketchPoint);
                SketchPlane eyeSketchPlane = SketchPlane.Create(curDoc, eyePlane);


                List <List <Curve> > roomLoops = new List <List <Curve> >();

                roomLoops.Add(roomCurves);

                //Convert to polygon in int values
                Polygon roomPoly = GetBoundaryLoop(roomCurves);


                //Calculate Intersection
                Polygons intersection = new Polygons();

                Clipper c2 = new Clipper();

                c2.AddPath(roomPoly, PolyType.ptClip, true);
                c2.AddPaths(union, PolyType.ptSubject, true);

                c2.Execute(ClipType.ctIntersection, intersection, PolyFillType.pftPositive);

                //TaskDialog.Show("test", intersection.Count.ToString());


                if (0 < intersection.Count)
                {
                    List <CurveLoop> regionLoops          = new List <CurveLoop>();
                    List <Curve>     intersectionLineList = new List <Curve>();
                    Polygon          poly = intersection[0];

                    IntPoint?p0 = null;
                    IntPoint?p  = null;

                    foreach (IntPoint q in poly)
                    {
                        if (null == p0)
                        {
                            p0 = q;
                        }
                        if (null != p)
                        {
                            intersectionLineList.Add(Line.CreateBound(GetXyzPoint(p.Value), GetXyzPoint(q)));
                        }
                        p = q;
                    }

                    intersectionLineList.Add(Line.CreateBound(GetXyzPoint(poly[poly.Count - 1]), GetXyzPoint(poly[0])));

                    foreach (Curve cur in intersectionLineList)
                    {
                        //ModelCurve newArc = curDoc.Create.NewModelCurve(cur, eyeSketchPlane);
                    }


                    CurveLoop regionLoop = CurveLoop.Create(intersectionLineList);

                    regionLoops.Add(regionLoop);


                    //TaskDialog.Show("test", intersectionLineList.Count.ToString());



                    FilledRegion region = FilledRegion.Create(curDoc, defaultFRId, curView.Id, regionLoops);
                }
            }

            t.Commit();



            TaskDialog.Show("Magic View Region Drawing Machine", "Always double check the results, sometimes walls are missed. Tip: Curtain wall is prone to gliches and watch your door openings... Enjoy!");

            return(Result.Succeeded);
        }
Beispiel #55
0
 /// <summary>
 /// Internal constructor for the ReferencePoint
 /// </summary>
 /// <param name="xyz"></param>
 private ReferencePoint(XYZ xyz)
 {
     SafeInit(() => InitReferencePoint(xyz));
 }
        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;

            // Get a lighting fixture family symbol:

            FilteredElementCollector symbols
                = Util.GetElementsOfType(doc,
                                         typeof(FamilySymbol),
                                         BuiltInCategory.OST_LightingFixtures);

            FamilySymbol sym = symbols.FirstElement()
                               as FamilySymbol;

            if (null == sym)
            {
                message = "No lighting fixture symbol found.";
                return(Result.Failed);
            }

            // Pick the ceiling:

#if _2010
            uidoc.Selection.StatusbarTip
                = "Please select ceiling to host lighting fixture";

            uidoc.Selection.PickOne();

            Element ceiling = null;

            foreach (Element e in uidoc.Selection.Elements)
            {
                ceiling = e as Element;
                break;
            }
#endif // _2010

            Reference r = uidoc.Selection.PickObject(
                ObjectType.Element,
                "Please select ceiling to host lighting fixture");

            if (null == r)
            {
                message = "Nothing selected.";
                return(Result.Failed);
            }

            // 'Autodesk.Revit.DB.Reference.Element' is
            // obsolete: Property will be removed. Use
            // Document.GetElement(Reference) instead.
            //Element ceiling = r.Element; // 2011

            Element ceiling = doc.GetElement(r) as Wall; // 2012

            // Get the level 1:

            Level level = Util.GetFirstElementOfTypeNamed(
                doc, typeof(Level), "Level 1") as Level;

            if (null == level)
            {
                message = "Level 1 not found.";
                return(Result.Failed);
            }

            // Create the family instance:

            XYZ p = app.Create.NewXYZ(-43, 28, 0);

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Place New Lighting Fixture Instance");

                FamilyInstance instLight
                    = doc.Create.NewFamilyInstance(
                          p, sym, ceiling, level,
                          StructuralType.NonStructural);

                t.Commit();
            }
            return(Result.Succeeded);
        }
Beispiel #57
0
        // edits the selected color in the 'edit' control
        private void editSelectedPoints()
        {
            if (edit.Gradient == null || edit.FocusSelection)
            {
                return;
            }

            if (DiscreteColors)
            {
                List <Color> selectedColors = new List <Color>();
                foreach (ColorGradient.Point point in edit.Selection)
                {
                    ColorPoint pt = point as ColorPoint;
                    if (pt == null)
                    {
                        continue;
                    }
                    selectedColors.Add(pt.Color.ToRGB().ToArgb());
                }

                using (DiscreteColorPicker picker = new DiscreteColorPicker()) {
                    picker.ValidColors    = ValidDiscreteColors;
                    picker.SelectedColors = selectedColors;
                    if (picker.ShowDialog() == DialogResult.OK)
                    {
                        if (picker.SelectedColors.Count() == 0)
                        {
                            DeleteColor();
                        }
                        //else if (picker.SelectedColors.Count() == selectedColors.Count) {
                        //	int i = 0;
                        //	foreach (Color selectedColor in picker.SelectedColors) {
                        //		ColorPoint pt = edit.Selection[i] as ColorPoint;
                        //		pt.Color = XYZ.FromRGB(selectedColor);
                        //	}
                        //}
                        else
                        {
                            double position = edit.Selection.First().Position;

                            foreach (ColorGradient.Point point in edit.Selection)
                            {
                                edit.Gradient.Colors.Remove(point as ColorPoint);
                            }

                            foreach (Color selectedColor in picker.SelectedColors)
                            {
                                ColorPoint newPoint = new ColorPoint(selectedColor, position);
                                edit.Gradient.Colors.Add(newPoint);
                            }
                        }
                    }
                }
            }
            else
            {
                if (edit.Selection.Count > 1)
                {
                    //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible)
                    MessageBoxForm.msgIcon = SystemIcons.Error;                     //this is used if you want to add a system icon to the message form.
                    var messageBox = new MessageBoxForm("Non-discrete color gradient, >1 selected point. oops! please report it.", "Delete library gradient?", false, false);
                    messageBox.ShowDialog();
                }
                ColorPoint pt = edit.Selection.FirstOrDefault() as ColorPoint;
                if (pt == null)
                {
                    return;
                }
                using (ColorPicker frm = new ColorPicker(_mode, _fader)) {
                    frm.LockValue_V = LockColorEditorHSV_Value;
                    frm.Color       = _xyz;
                    if (frm.ShowDialog(this.FindForm()) == DialogResult.OK)
                    {
                        pt.Color             = _xyz = frm.Color;
                        lblColorSelect.Color = _xyz.ToRGB().ToArgb();
                        _mode  = frm.SecondaryMode;
                        _fader = frm.PrimaryFader;
                    }
                }
            }
        }
Beispiel #58
0
 public abstract bool AllowReference(Reference reference, XYZ position);
Beispiel #59
0
 /// <summary>
 /// References will pass, if they don't pass the original filter
 /// </summary>
 /// <param name="reference"></param>
 /// <param name="position"></param>
 /// <returns></returns>
 public bool AllowReference(Reference reference, XYZ position)
 {
     return(!m_filter.AllowReference(reference, position));
 }
Beispiel #60
0
            public void Duct_from_AutoCad()
            {
                UIDocument uidoc = this.ActiveUIDocument;
                Document   doc   = uidoc.Document;

                Autodesk.Revit.DB.View currentview = doc.ActiveView;
                if (currentview.ViewType != ViewType.FloorPlan)
                {
                    return;
                }                                                   //Only works in floorplans
                try
                {
                    puntoref_revit = uidoc.Selection.PickPoint("Pick origin point in REVIT");
                }
                catch { return; }
                OpenFileDialog archivofile = new OpenFileDialog();

                archivofile.Title           = "Open CAD data file";
                archivofile.CheckFileExists = true;
                archivofile.CheckPathExists = true;
                archivofile.Filter          = "Txt|*.txt";
                if (archivofile.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                string nombrefile = archivofile.FileName;

                string[] lineasarchivo = File.ReadAllLines(nombrefile);
                string   lineadata     = String.Empty;

                //get Rectangular Duct Type
                FilteredElementCollector collectorductos = new FilteredElementCollector(doc);

                collectorductos.OfClass(typeof(Autodesk.Revit.DB.Mechanical.DuctType)).ToElements();

                Autodesk.Revit.DB.Mechanical.DuctType ducttypefinal = null;
                foreach (Element elemw in collectorductos)
                {
                    Autodesk.Revit.DB.Mechanical.DuctType duct_type = elemw as Autodesk.Revit.DB.Mechanical.DuctType;
                    System.Diagnostics.Debug.Print(duct_type.Name);
                    Parameter ovaltoround     = duct_type.get_Parameter(BuiltInParameter.RBS_CURVETYPE_MULTISHAPE_TRANSITION_OVALROUND_PARAM);
                    Parameter recttooval      = duct_type.get_Parameter(BuiltInParameter.RBS_CURVETYPE_MULTISHAPE_TRANSITION_RECTOVAL_PARAM);
                    Parameter recttoround     = duct_type.get_Parameter(BuiltInParameter.RBS_CURVETYPE_MULTISHAPE_TRANSITION_PARAM);
                    int       val_ovaltoround = ovaltoround.AsElementId().IntegerValue;
                    int       val_recttooval  = recttooval.AsElementId().IntegerValue;
                    int       val_recttoround = recttoround.AsElementId().IntegerValue;
                    System.Diagnostics.Debug.Print("Oval to round:" + val_ovaltoround.ToString());
                    System.Diagnostics.Debug.Print("Rect to oval:" + val_recttooval.ToString());
                    System.Diagnostics.Debug.Print("Rect to round:" + val_recttoround.ToString());
                    //if val_recttoround is -1 the ducttype is OVAL
                    //if val_ovaltoround is -1 the ducttype is RECTANGULAR
                    // if val_recttooval is -1 the ducttyoe is ROUND
                    if (val_ovaltoround == -1)
                    {
                        ducttypefinal = duct_type; break;
                    }
                }
                //
                lineadata = lineasarchivo[0];
                string[] datos = lineadata.Split(';');
                double   x1    = Math.Round(Convert.ToDouble(datos[0]), 6) / 0.3048;
                double   y1    = Math.Round(Convert.ToDouble(datos[1]), 6) / 0.3048;
                double   z1    = Math.Round(Convert.ToDouble(datos[2]), 6) / 0.3048;

                puntoref_cad      = new XYZ(x1, y1, z1);
                vector_correccion = puntoref_revit - puntoref_cad;
                XYZ puntoCR    = new XYZ();
                int Countducts = 0;

                using (Transaction tr = new Transaction(doc, "DuctFromCAD"))
                {
                    tr.Start();
                    for (int ii = 1; ii < lineasarchivo.Length; ii++)
                    {
                        lineadata = lineasarchivo[ii];
                        datos     = lineadata.Split(';');
                        x1        = Math.Round(Convert.ToDouble(datos[0]), 6) / 0.3048;
                        y1        = Math.Round(Convert.ToDouble(datos[1]), 6) / 0.3048;
                        z1        = Math.Round(Convert.ToDouble(datos[2]), 6) / 0.3048;
                        double x2        = Math.Round(Convert.ToDouble(datos[3]), 6) / 0.3048;
                        double y2        = Math.Round(Convert.ToDouble(datos[4]), 6) / 0.3048;
                        double z2        = Math.Round(Convert.ToDouble(datos[5]), 6) / 0.3048;
                        double ancho     = Math.Round(Convert.ToDouble(datos[6]), 3);
                        string dim_ducto = datos[7];
                        if (dim_ducto != null && dim_ducto != "")
                        {
                            string[] blanksplit = dim_ducto.Split(' ');
                            string[] sizeplit   = blanksplit[0].Split('x');
                            double   widthduct  = Convert.ToDouble(sizeplit[0]) / 12; //from inches to feet
                            double   heightduct = Convert.ToDouble(sizeplit[1]) / 12; //from inches to feet
                            System.Diagnostics.Debug.Print(widthduct.ToString() + "x" + heightduct.ToString());
                            XYZ p1 = new XYZ(x1, y1, z1) + vector_correccion;
                            XYZ p2 = new XYZ(x2, y2, z2) + vector_correccion;
                            if (p1.DistanceTo(p2) < 1)
                            {
                                continue;
                            }                            //Not less than a feet
                            try
                            {
                                Autodesk.Revit.DB.Mechanical.Duct new_duct = doc.Create.NewDuct(p1, p2, ducttypefinal);
                                new_duct.get_Parameter(BuiltInParameter.RBS_CURVE_WIDTH_PARAM).Set(widthduct);
                                new_duct.get_Parameter(BuiltInParameter.RBS_CURVE_HEIGHT_PARAM).Set(heightduct);
                                doc.Create.NewTag(currentview, new_duct, false, TagMode.TM_ADDBY_CATEGORY, TagOrientation.TAG_HORIZONTAL, p1.Add(p2).Divide(2));
                                //doc.Create.NewTextNote(currentview, p1.Add(p2).Divide(2.001), XYZ.BasisX, XYZ.BasisZ, 1, TextAlignFlags.TEF_ALIGN_CENTER, sizeplit[0] + "x" + sizeplit[1]);
                                Countducts++;
                            }
                            catch { }
                        }
                    }
                    tr.Commit();
                }
                MessageBox.Show("Imported " + Countducts.ToString() + " Ducts");
            }