Exemplo n.º 1
0
        public Extrusion GetOffsetExtrusion()
        {
            var offsetCrv = SITE.Offset(
                CENTROID,
                Vector3d.ZAxis,
                SETBACKDIST,
                Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance,
                CurveOffsetCornerStyle.Sharp
                );

            try
            {
                double ar = AreaMassProperties.Compute(offsetCrv[0]).Area;
                HEIGHT = GFA / ar;
                SOLID  = Extrusion.Create(offsetCrv[0], -HEIGHT, true);
            }
            catch (Exception) { }
            return(SOLID);
        }
Exemplo n.º 2
0
        public static List <Brep> SplitByCurve(Brep brepToSplit, Curve splitter)
        {
            if (splitter == null)
            {
                List <Brep> unmodified = new List <Brep>();
                unmodified.Add(brepToSplit);
                return(unmodified);
            }

            Brep splitterBrep = Extrusion.CreateExtrusion(splitter, Vector3d.ZAxis).ToBrep();

            Brep[] splitBreps = brepToSplit.Split(splitterBrep, 0.1);

            List <Brep> result = new List <Brep>(splitBreps);

            //MessageBox.Show(result.Count.ToString());

            return(result);
        }
Exemplo n.º 3
0
        // =============================================================
        //  helper function: find a planar face with the given normal
        // =============================================================
        PlanarFace findFace(Extrusion pBox, XYZ normal)
        {
            // get the geometry object of the given element
            //
            Options op = new Options();

            op.ComputeReferences = true;
            GeometryElement geomElem = pBox.get_Geometry(op);

            // loop through the array and find a face with the given normal
            //
            foreach (GeometryObject geomObj in geomElem)
            {
                if (geomObj is Solid)  // solid is what we are interested in.
                {
                    Solid     pSolid = (Solid)geomObj;
                    FaceArray faces  = pSolid.Faces;
                    foreach (Face pFace in faces)
                    {
                        PlanarFace pPlanarFace = (PlanarFace)pFace;
                        if ((pPlanarFace != null) && pPlanarFace.FaceNormal.IsAlmostEqualTo(normal)) // we found the face
                        {
                            return(pPlanarFace);
                        }
                    }
                }

                // will come back later as needed.
                //
                //else if (geomObj is Instance)
                //{
                //}
                //else if (geomObj is Curve)
                //{
                //}
                //else if (geomObj is Mesh)
                //{
                //}
            }

            // if we come here, we did not find any.
            return(null);
        }
        // command main
        //
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            // objects for the top level access
            //
            _app = commandData.Application.Application;
            _doc = commandData.Application.ActiveUIDocument.Document;

            // (0) This command works in the context of family editor only.
            //     We also check if the template is for an appropriate category if needed.
            //     Here we use a Column(i.e., Metric Column.rft) template.
            //     Although there is no specific checking about metric or imperial, our lab only works in metric for now.
            //
            if (!isRightTemplate(BuiltInCategory.OST_Columns))
            {
                Util.ErrorMsg("Please open Metric Column.rft");
                return(Result.Failed);
            }

            // (1) create a simple extrusion. just a simple box for now.
            Extrusion pSolid = createSolid();

            // We need to regenerate so that we can build on this new geometry
            _doc.Regenerate();

            // try this:
            // if you comment addAlignment and addTypes calls below and execute only up to here,
            // you will see the column's top will not follow the upper level.

            // (2) add alignment
            addAlignments(pSolid);

            // try this: at each stage of adding a function here, you should be able to see the result in UI.

            // (3) add types
            addTypes();

            // finally, return
            return(Result.Succeeded);
        }
Exemplo n.º 5
0
        private Extrusion CreateExtrusion(Document familyDoc)
        {
            try
            {
                Plane plane = familyDoc.Application.Create.NewPlane(new XYZ(0.0, 0.0, 1.0),
                                                                    new XYZ(0.0, 0.0, 0.0)
                                                                    );

                SketchPlane    s_plane = familyDoc.FamilyCreate.NewSketchPlane(plane);
                ReferenceArray ra      = new ReferenceArray();
                CurveArray     profile = new CurveArray();
                CurveArrArray  caa     = new CurveArrArray();

                int i = 0;
                while (i < 3)
                {
                    profile.Append(familyDoc.Application.Create.NewLineBound(_vert[i], _vert[i + 1]));
                    ++i;
                }
                profile.Append(familyDoc.Application.Create.NewLineBound(_vert[i], _vert[i - i]));
                caa.Append(profile);

                Extrusion extrusion = familyDoc.FamilyCreate.NewExtrusion(true, caa, s_plane, 10.0);

                AssignSubCategory(familyDoc, extrusion);

                Line line = familyDoc.Application.Create.NewLine(_vert[0], _vert[1], true);
                ConstructParam(familyDoc, _width, line, "Width");
                line = familyDoc.Application.Create.NewLine(_vert[1], _vert[2], true);
                ConstructParam(familyDoc, _height, line, "Height");

                SetFormula(familyDoc);

                return(extrusion);
            }

            catch (Exception ex)
            {
                TaskDialog.Show("Extrusion Error", ex.Message);
                return(null);
            }
        }
Exemplo n.º 6
0
        public CupBoard GetCupBoard(MySqlConnection connection, int FkOrder)
        {
            List <Locker> lockerList = GetLockerList(connection, FkOrder);
            List <int>    idLockers  = GetLockersID(connection, FkOrder);
            int           idLocker   = idLockers[0];

            Dictionary <string, string> lockerAttribute = GetLockerAttribute(connection, FkOrder, idLocker);

            string color = lockerAttribute["color"];
            double width = Convert.ToDouble(lockerAttribute["width"]);
            double depth = Convert.ToDouble(lockerAttribute["depth"]);

            Extrusion extrusion       = GetExtrusion(FkOrder, idLocker);
            CupBoard  cupBoard        = new CupBoard(width, depth, lockerList, extrusion);
            double    extrusionHeight = cupBoard.GetTotalHeight();

            cupBoard.GetExtrusion().SetHeight(extrusionHeight);

            return(cupBoard);
        }
Exemplo n.º 7
0
        /// <summary>
        /// The method is used to create extrusion using FamilyItemFactory.NewExtrusion()
        /// </summary>
        /// <param name="curveArrArray">the CurveArrArray parameter</param>
        /// <param name="workPlane">the reference plane is used to create SketchPlane</param>
        /// <param name="startOffset">the extrusion's StartOffset property</param>
        /// <param name="endOffset">the extrusion's EndOffset property</param>
        /// <returns>the new extrusion</returns>
        public Extrusion NewExtrusion(CurveArrArray curveArrArray, ReferencePlane workPlane, double startOffset, double endOffset)
        {
            Extrusion rectExtrusion = null;

            try
            {
                SubTransaction subTransaction = new SubTransaction(m_document);
                subTransaction.Start();
                SketchPlane sketch = SketchPlane.Create(m_document, workPlane.GetPlane());
                rectExtrusion             = m_familyCreator.NewExtrusion(true, curveArrArray, sketch, Math.Abs(endOffset - startOffset));
                rectExtrusion.StartOffset = startOffset;
                rectExtrusion.EndOffset   = endOffset;
                subTransaction.Commit();
                return(rectExtrusion);
            }
            catch
            {
                return(null);
            }
        }
Exemplo n.º 8
0
        public override void Invalidate()
        {
            gfa       = 0;
            height    = -1;
            footPrint = 0;
            foreach (Grammar grammar in grammars)
            {
                int lastIndex = grammar.stagedOutputs.Count - 1;
                if (grammar.stagedOutputs == null || lastIndex < 0)
                {
                    continue;
                }
                foreach (ShapeObject s in grammar.stagedOutputs[lastIndex].shapes)
                {
                    try
                    {
                        Extrusion ext = (Extrusion)s.meshable;
                        //find highest height
                        float top = ext.polygon.vertices[0].y + ext.height;
                        if (top > height)
                        {
                            height = top;
                        }
                        //local floor for gfa calculation, add local gfa to global gfa
                        float baseArea = ext.polygon.Area();
                        float flrs     = Mathf.Round(ext.height / floorHeight);
                        gfa += (baseArea * flrs);

                        //footprint
                        if (ext.polygon.vertices[0].y == ground)
                        {
                            footPrint += baseArea;
                        }
                    }
                    catch (Exception e)
                    { Debug.Log("Exception e=:" + e.ToString()); }
                }
                //once we have the buiding height, we can have number of floors
            }
            floors = (int)(height / floorHeight);
        }
Exemplo n.º 9
0
        private Brep ExtrudeCurveBothSide(Curve Crv, Vector3d Direction, bool BothSide, bool IsCape)
        {
            double Tolerance = Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance;

            if (Direction.Length == 0)
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "拉伸向量的长度不能为0");
                return(null);
            }
            if (BothSide)
            {
                Crv.Transform(Transform.Translation(Direction));
                Direction.Reverse();
                Direction = Direction * 2;
            }
            if (Crv.IsPlanar())
            {
                try
                {
                    Brep Temp = Extrusion.CreateExtrusion(Crv, Direction).ToBrep();
                    if (IsCape)
                    {
                        return(Temp.CapPlanarHoles(Tolerance));
                    }
                    else
                    {
                        return(Temp);
                    }
                }
                catch (Exception e)
                {
                    this.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, string.Format("内部错误:{0}", e.Message));
                    return(null);
                }
            }
            else
            {
                this.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "输入的几何体不符合条件");
                return(null);
            }
        }
Exemplo n.º 10
0
    // Use this for initialization
    void Start()
    {
        Vector3[] pts = new Vector3[]
        {
            new Vector3(),
            new Vector3(30, 0, -5),
            new Vector3(50, 0, 0),
            new Vector3(50, 0, 20),
            new Vector3(0, 0, 20),
        };

        Polygon pg = new Polygon(pts);

        ShapeObject.CreateMeshable(pg);
        Extrusion ext = pg.Extrude(new Vector3(0, 20, 0));

        ShapeObject refo = ShapeObject.CreateMeshable(ext);

        refo.transform.Translate(new Vector3(0, 20, 0));

        ext.bbox = BoundingBox.CreateFromPoints(ext.vertices, new Vector3(1, 0, 0));

        //ShapeObject.CreateMeshable(ext);
        //Meshable[] mbs = SGUtility.DivideFormByCount(ext, 3, 0);
        Meshable[] mbs     = SGUtility.DivideFormToLength(ext, 10, 0);
        int        counter = 0;

        foreach (Meshable mb in mbs)
        {
            if (mb.bbox == null)
            {
                throw new System.Exception("null bbox");
            }
            SGUtility.ScaleForm(mb, new Vector3(0.9f, 0.3f, 0.9f), Alignment.Center3D);
            ShapeObject so = ShapeObject.CreateMeshable(mb);

            //so.transform.Translate(new Vector3(counter*1, 10, 0));

            counter += 1;
        }
    }
Exemplo n.º 11
0
        private void SetConstraints(Document familyDoc, Extrusion extrusion)
        {
            try
            {
                CurveArrArray curvesArr = new CurveArrArray();
                curvesArr = extrusion.Sketch.Profile;

                foreach (CurveArray ca in curvesArr)
                {
                    CurveArrayIterator itor = ca.ForwardIterator();
                    itor.Reset();
                    itor.MoveNext();
                    Line l = itor.Current as Line;
                    _rightCon.Append(l.Reference);
                    itor.MoveNext();
                    l = itor.Current as Line;
                    _topCon.Append(l.Reference);
                    itor.MoveNext();
                    l = itor.Current as Line;
                    _leftCon.Append(l.Reference);
                    l = itor.Current as Line;
                    _botCon.Append(l.Reference);
                }
                ReferenceArrayArray conArray = new ReferenceArrayArray();

                conArray.Append(_rightCon);
                conArray.Append(_topCon);
                conArray.Append(_leftCon);
                conArray.Append(_botCon);

                ConstructConstraint(familyDoc, _rightCon);
                ConstructConstraint(familyDoc, _topCon);
                ConstructConstraint(familyDoc, _leftCon);
            }

            catch (Exception ex)
            {
                TaskDialog.Show("Constraint Error", ex.Message);
            }
        }
Exemplo n.º 12
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //【通过APP打开族文件】
            Application app     = commandData.Application.Application;
            string      rftPath = @"C:\ProgramData\Autodesk\RVT 2020\Family Templates\Chinese\公制柱.rft";
            Document    docRfa  = app.NewFamilyDocument(rftPath);
            //【创建几何】
            double     width      = 2.5 / 0.3048;
            double     height     = 10 / 0.3048;
            XYZ        point1     = new XYZ(width, width, 0);
            XYZ        point2     = new XYZ(-width, width, 0);
            XYZ        point3     = new XYZ(-width, -width, 0);
            XYZ        point4     = new XYZ(width, -width, 0);
            CurveArray curveArray = new CurveArray();

            curveArray.Append(Line.CreateBound(point1, point2));
            curveArray.Append(Line.CreateBound(point2, point3));
            curveArray.Append(Line.CreateBound(point3, point4));
            curveArray.Append(Line.CreateBound(point4, point1));
            CurveArrArray curveArrArray = new CurveArrArray();

            curveArrArray.Append(curveArray);
            //【创建草图平面】
            SketchPlane sketchPlane = new FilteredElementCollector(docRfa).OfClass(typeof(SketchPlane)).First(x => x.Name == "低于参照标高") as SketchPlane;
            //【开始创建】
            Transaction trans = new Transaction(docRfa, "创建柱族");

            trans.Start();
            Extrusion extrusion = docRfa.FamilyCreate.NewExtrusion(true, curveArrArray, sketchPlane, height);

            trans.Commit();
            //【保存出来】
            SaveAsOptions saveAsOptions = new SaveAsOptions();

            saveAsOptions.MaximumBackups        = 1;
            saveAsOptions.OverwriteExistingFile = true;
            docRfa.SaveAs(@"E:\编程创建的柱子.rfa", saveAsOptions);
            docRfa.Close(false);
            return(Result.Succeeded);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Create one rectangular extrusion
        /// </summary>
        private void CreateExtrusion()
        {
            try
            {
                #region Create rectangle profile
                CurveArrArray curveArrArray = new CurveArrArray();
                CurveArray    curveArray1   = new CurveArray();

                Autodesk.Revit.DB.XYZ normal      = Autodesk.Revit.DB.XYZ.BasisZ;
                SketchPlane           sketchPlane = CreateSketchPlane(normal, Autodesk.Revit.DB.XYZ.Zero);

                // create one rectangular extrusion
                Autodesk.Revit.DB.XYZ p0 = Autodesk.Revit.DB.XYZ.Zero;
                Autodesk.Revit.DB.XYZ p1 = new Autodesk.Revit.DB.XYZ(10, 0, 0);
                Autodesk.Revit.DB.XYZ p2 = new Autodesk.Revit.DB.XYZ(10, 10, 0);
                Autodesk.Revit.DB.XYZ p3 = new Autodesk.Revit.DB.XYZ(0, 10, 0);
                Line line1 = Line.CreateBound(p0, p1);
                Line line2 = Line.CreateBound(p1, p2);
                Line line3 = Line.CreateBound(p2, p3);
                Line line4 = Line.CreateBound(p3, p0);
                curveArray1.Append(line1);
                curveArray1.Append(line2);
                curveArray1.Append(line3);
                curveArray1.Append(line4);

                curveArrArray.Append(curveArray1);
                #endregion
                // here create rectangular extrusion
                Extrusion rectExtrusion = m_creationFamily.NewExtrusion(true, curveArrArray, sketchPlane, 10);
                // move to proper place
                Autodesk.Revit.DB.XYZ transPoint1 = new Autodesk.Revit.DB.XYZ(-16, 0, 0);
                ElementTransformUtils.MoveElement(m_familyDocument, rectExtrusion.Id, transPoint1);
            }
            catch (Exception e)
            {
                m_errCount++;
                m_errorInfo += "Unexpected exceptions occur in CreateExtrusion: " + e.ToString() + "\r\n";
            }
        }
Exemplo n.º 14
0
            public CockpitFuselage(Nose nose, float length, float baseScale, float bend)
            {
                Fuselage = Extrusion.Extrude <V, P> (false, false, nose.XSection,
                                                     nose.XSection.Transform(Mat.Translation <Mat4> (0f, 0, -length) *
                                                                             Mat.Scaling <Mat4> (1f, baseScale, baseScale)));

                Fuselage = Composite.Create(Stacking.StackBackward(nose.Cone, Fuselage));
                XSection = Path <P, Vec3> .FromVecs(
                    from v in Fuselage.Vertices.Furthest (Dir3D.Back)
                    where v.position.Y >= -0.2f
                    select v.position).Close();

                var pivotPoint = XSection.Vertices.Furthest(Dir3D.Up).First().position;

                Fuselage = Fuselage.ManipulateVertices(
                    Manipulators.Transform <V> (Mat.RotationX <Mat4> (bend.Radians()).RelativeTo(pivotPoint))
                    .Where(v => v.position.Z > pivotPoint.Z), true)
                           .Color(_color);

                XSectionStart = XSection.Vertices.Furthest(Dir3D.Down + Dir3D.Left).Single();
                XSection      = XSection.RenumberNodes(XSection.Vertices.IndexOf(XSectionStart)).Open();
            }
Exemplo n.º 15
0
 private void BuildFamily(Document familyDoc)
 {
     try
     {
         Transaction tR = new Transaction(familyDoc, "Set References");
         if (tR.Start() == TransactionStatus.Started)
         {
             SetReferences(familyDoc);
             tR.Commit();
         }
         Extrusion   extrusion = null;
         Transaction tE        = new Transaction(familyDoc, "Create Extrusion");
         if (tE.Start() == TransactionStatus.Started)
         {
             extrusion = CreateExtrusion(familyDoc);
             tE.Commit();
         }
         if (null != extrusion)
         {
             Transaction tC = new Transaction(familyDoc, "Set Constraints");
             if (tC.Start() == TransactionStatus.Started)
             {
                 SetConstraints(familyDoc, extrusion);
                 tC.Commit();
             }
             //Transaction tF = new Transaction(familyDoc, "Set Formula");
             //if (tF.Start() == TransactionStatus.Started)
             //{
             //    SetFormula(familyDoc);
             //    tF.Commit();
             //}
         }
     }
     catch (Exception ex)
     {
         TaskDialog.Show("Build Error", ex.Message);
     }
 }
Exemplo n.º 16
0
        private void SetConstraints(Document familyDoc, Extrusion extrusion)
        {
            CurveArrArray curvesArr = new CurveArrArray();

            curvesArr = extrusion.Sketch.Profile;

            foreach (CurveArray ca in curvesArr)
            {
                CurveArrayIterator itor = ca.ForwardIterator();
                itor.Reset();
                itor.MoveNext();
                Line l = itor.Current as Line;
                _rightCon.Append(l.Reference);
                itor.MoveNext();
                l = itor.Current as Line;
                _topCon.Append(l.Reference);
                itor.MoveNext();
                l = itor.Current as Line;
                _leftCon.Append(l.Reference);
                l = itor.Current as Line;
                _botCon.Append(l.Reference);
            }
            ReferenceArrayArray conArray = new ReferenceArrayArray();

            conArray.Append(_rightCon);
            conArray.Append(_topCon);
            conArray.Append(_leftCon);
            conArray.Append(_botCon);

            //Line line = familyDoc.Application.Create.NewLine(_vert[0], _vert[1], true);
            ConstructConstraint(familyDoc, _rightCon);
            //line = familyDoc.Application.Create.NewLine(_vert[1], _vert[2], true);
            ConstructConstraint(familyDoc, _topCon);
            //line = familyDoc.Application.Create.NewLine(_vert[2], _vert[3], true);
            ConstructConstraint(familyDoc, _leftCon);
            //line = familyDoc.Application.Create.NewLine(_vert[3], _vert[0], true);
            //ConstructConstraint(familyDoc, _botCon, line);
        }
Exemplo n.º 17
0
        public static IGeometry Geometry3D(this Bar bar, bool onlyOuterExtrusion = true)
        {
            if (bar.IsNull())
            {
                return(null);
            }

            // . If the profile is made of two curves (e.g. I section), selects only the outermost.
            IEnumerable <IGeometry> extrusions = bar.Extrude(false);
            Extrusion barOutermostExtrusion    = extrusions.OfType <Extrusion>().OrderBy(extr => Engine.Geometry.Query.IArea(extr.Curve)).First();

            if (onlyOuterExtrusion)
            {
                return(barOutermostExtrusion);
            }
            else
            {
                return new CompositeGeometry()
                       {
                           Elements = extrusions.ToList()
                       }
            };
        }
Exemplo n.º 18
0
        public static IGeometry GeometricalRepresentation(this Bar bar, RepresentationOptions reprOptions = null)
        {
            if (bar == null)
            {
                BH.Engine.Base.Compute.RecordError("Cannot compute the geometrical representation of a null bar.");
                return(null);
            }

            reprOptions = reprOptions ?? new RepresentationOptions();

            if (!reprOptions.Detailed1DElements)
            {
                return(bar.Centreline()); //returns the piped centreline.
            }
            else
            {
                // Gets the BH.oM.Geometry.Extrusion out of the Bar. If the profile is made of two curves (e.g. I section), selects only the outermost.
                Extrusion barOutermostExtrusion = bar.Extrude(false).Cast <Extrusion>().OrderBy(extr => extr.Curve.IArea()).First();
                barOutermostExtrusion.Capped = reprOptions.Cap1DElements;

                return(barOutermostExtrusion);
            }
        }
Exemplo n.º 19
0
        public static Reaction <Camera> Renderer(SceneGraph sceneGraph, Vec3 skyColor)
        {
            _skyboxShader = new GLProgram(VertexShader(), FragmentShader());
            _skybox       = new Skybox(_skyboxShader);
            _skyColor     = skyColor;
            var cube = Extrusion.Cube <PositionalVertex> (_cubeSize, _cubeSize, _cubeSize).Center();

            _vertices = new VBO <PositionalVertex> (cube.Vertices, BufferTarget.ArrayBuffer);
            _indices  = new VBO <int> (cube.Indices, BufferTarget.ElementArrayBuffer);
            var environmentMap = Texture.CubeMapFromFiles(
                _paths.Map(s => string.Format(@"Textures/{0}.bmp", s)), 0)
                                 .LinearFiltering().ClampToEdges(Axes.All);

            sceneGraph.GlobalLighting.DiffuseMap = environmentMap;

            return(React.By <Camera> (_skybox.Render)
                   .BindSamplers(new Dictionary <Sampler, Texture> ()
            {
                { !_skybox.cubeMap, environmentMap }
            })
                   .Culling(CullFaceMode.Front)
                   .Program(_skyboxShader));
        }
Exemplo n.º 20
0
    public void SetRatio(List <ShapeObject> sos)
    {
        Dictionary <string, float> namedArea   = new Dictionary <string, float>();
        Dictionary <string, Color> namedColors = new Dictionary <string, Color>();
        List <string> names  = new List <string>();
        List <float>  areas  = new List <float>();
        List <Color>  colors = new List <Color>();

        foreach (ShapeObject so in sos)
        {
            if (so.meshable.GetType() == typeof(Extrusion))
            {
                Extrusion ext  = (Extrusion)so.meshable;
                float     area = ext.polygon.Area();
                if (!namedArea.ContainsKey(so.name))
                {
                    namedArea[so.name]   = area;
                    namedColors[so.name] = so.GetComponent <MeshRenderer>().material.color;
                }
                else
                {
                    namedArea[so.name] += area;
                }
            }
        }
        foreach (KeyValuePair <string, float> kv in namedArea)
        {
            names.Add(kv.Key);
            areas.Add(kv.Value);
        }
        foreach (KeyValuePair <string, Color> kv in namedColors)
        {
            colors.Add(kv.Value);
        }

        SetRatio(areas.ToArray(), names.ToArray(), colors.ToArray());
    }
Exemplo n.º 21
0
        public void genBaseMass()
        {
            PolylineCurve outerCrv    = new PolylineCurve(outerPtLi);
            double        outerAr     = AreaMassProperties.Compute(outerCrv).Area;
            PolylineCurve innerCrv    = new PolylineCurve(innerPtLi);
            double        innerAr     = AreaMassProperties.Compute(innerCrv).Area;
            double        diffAr      = outerAr - innerAr;
            int           numBaseFlrs = (int)(SITE_AR * baseFsr / diffAr) + 1;
            double        baseHt      = numBaseFlrs * flrHt;
            Extrusion     outerExtr   = Extrusion.Create(outerCrv, baseHt, true);
            Extrusion     innerExtr   = Extrusion.Create(innerCrv, baseHt, true);

            Brep[] outerBrep = { outerExtr.ToBrep() };
            Brep[] innerBrep = { innerExtr.ToBrep() };
            Brep[] diffBrep  = Brep.CreateBooleanDifference(outerBrep, innerBrep, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance);
            for (int i = 0; i < diffBrep.Length; i++)
            {
                globalBrepLi.Add(diffBrep[i]);
            }

            globalBaseCrvLi = new List <Curve>();
            double spineHt = 0.0;

            for (int i = 0; i < numBaseFlrs; i++)
            {
                Curve outerCrvDup = outerCrv.DuplicateCurve();
                Rhino.Geometry.Transform xform = Rhino.Geometry.Transform.Translation(0, 0, spineHt);
                outerCrvDup.Transform(xform);
                Curve innerCrvDup = innerCrv.DuplicateCurve();
                innerCrvDup.Transform(xform);
                globalBaseCrvLi.Add(innerCrvDup);
                globalBaseCrvLi.Add(outerCrvDup);
                spineHt += flrHt;
            }
            BaseMassHt = baseHt;
        }
        // ======================================
        //   (2.1) add alignments
        // ======================================
        void addAlignments(Extrusion pBox)
        {
            //
              // (1) we want to constrain the upper face of the column to the "Upper Ref Level"
              //

              // which direction are we looking at?
              //
              View pView = findElement(typeof(View), "Front") as View;

              // find the upper ref level
              // findElement() is a helper function. see below.
              //
              Level upperLevel = findElement(typeof(Level), "Upper Ref Level") as Level;
              Reference ref1 = upperLevel.GetPlaneReference();

              // find the face of the box
              // findFace() is a helper function. see below.
              //
              PlanarFace upperFace = findFace(pBox, new XYZ(0.0, 0.0, 1.0)); // find a face whose normal is z-up.
              Reference ref2 = upperFace.Reference;

              // create alignments
              //
              _doc.FamilyCreate.NewAlignment(pView, ref1, ref2);

              //
              // (2) do the same for the lower level
              //

              // find the lower ref level
              // findElement() is a helper function. see below.
              //
              Level lowerLevel = findElement(typeof(Level), "Lower Ref. Level") as Level;
              Reference ref3 = lowerLevel.GetPlaneReference();

              // find the face of the box
              // findFace() is a helper function. see below.
              PlanarFace lowerFace = findFace(pBox, new XYZ(0.0, 0.0, -1.0)); // find a face whose normal is z-down.
              Reference ref4 = lowerFace.Reference;

              // create alignments
              //
              _doc.FamilyCreate.NewAlignment(pView, ref3, ref4);

              //
              // (3)  same idea for the Right/Left/Front/Back
              //
              // get the plan view
              // note: same name maybe used for different view types. either one should work.
              View pViewPlan = findElement(typeof(ViewPlan), "Lower Ref. Level") as View;

              // find reference planes
              ReferencePlane refRight = findElement(typeof(ReferencePlane), "Right") as ReferencePlane;
              ReferencePlane refLeft = findElement(typeof(ReferencePlane), "Left") as ReferencePlane;
              ReferencePlane refFront = findElement(typeof(ReferencePlane), "Front") as ReferencePlane;
              ReferencePlane refBack = findElement(typeof(ReferencePlane), "Back") as ReferencePlane;
              ReferencePlane refOffsetV = findElement(typeof(ReferencePlane), "OffsetV") as ReferencePlane;  // added for L-shape
              ReferencePlane refOffsetH = findElement(typeof(ReferencePlane), "OffsetH") as ReferencePlane;  // added for L-shape

              // find the face of the box
              // Note: findFace need to be enhanced for this as face normal is not enough to determine the face.
              //
              PlanarFace faceRight = findFace(pBox, new XYZ(1.0, 0.0, 0.0), refRight); // modified for L-shape
              PlanarFace faceLeft = findFace(pBox, new XYZ(-1.0, 0.0, 0.0));
              PlanarFace faceFront = findFace(pBox, new XYZ(0.0, -1.0, 0.0));
              PlanarFace faceBack = findFace(pBox, new XYZ(0.0, 1.0, 0.0), refBack); // modified for L-shape
              PlanarFace faceOffsetV = findFace(pBox, new XYZ(1.0, 0.0, 0.0), refOffsetV); // added for L-shape
              PlanarFace faceOffsetH = findFace(pBox, new XYZ(0.0, 1.0, 0.0), refOffsetH);  // added for L-shape

              // create alignments
              //
              _doc.FamilyCreate.NewAlignment(pViewPlan, refRight.GetReference(), faceRight.Reference);
              _doc.FamilyCreate.NewAlignment(pViewPlan, refLeft.GetReference(), faceLeft.Reference);
              _doc.FamilyCreate.NewAlignment(pViewPlan, refFront.GetReference(), faceFront.Reference);
              _doc.FamilyCreate.NewAlignment(pViewPlan, refBack.GetReference(), faceBack.Reference);
              _doc.FamilyCreate.NewAlignment(pViewPlan, refOffsetV.GetReference(), faceOffsetV.Reference);  // added for L-shape
              _doc.FamilyCreate.NewAlignment(pViewPlan, refOffsetH.GetReference(), faceOffsetH.Reference);  // added for L-shape
        }
        // command main
        //
        public Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            // objects for the top level access
              //
              _app = commandData.Application.Application;
              _doc = commandData.Application.ActiveUIDocument.Document;

              // (0) This command works in the context of family editor only.
              //     We also check if the template is for an appropriate category if needed.
              //     Here we use a Column(i.e., Metric Column.rft) template.
              //     Although there is no specific checking about metric or imperial, our lab only works in metric for now.
              //
              if (!isRightTemplate(BuiltInCategory.OST_Columns))
              {
            Util.ErrorMsg("Please open Metric Column.rft");
            return Result.Failed;
              }

              using (Transaction transaction = new Transaction(_doc))
              {
              try
              {
              if (transaction.Start("CreateFamily") == TransactionStatus.Started)
              {
                  // (1.1) add reference planes
                  addReferencePlanes();

                  // (1.2) create a simple extrusion. we create a L-shape extrusion.
                  Extrusion pSolid = createSolid();
                  _doc.Regenerate();

                  // (2) add alignment
                  addAlignments(pSolid);

                  // (3.1) add parameters
                  addParameters();

                  // (3.2) add dimensions
                  addDimensions();

                  // (3.3) add types
                  addTypes();

                  // (4.1) add formula
                  addFormulas();

                  // (4.2) add materials
                  addMaterials(pSolid);
                  transaction.Commit();
              }
              else
              {
                  TaskDialog.Show("ERROR", "Start transaction failed!");
                  return Result.Failed;
              }
              }
              catch (Exception ex)
              {
              TaskDialog.Show("ERROR", ex.ToString());
              if (transaction.GetStatus() == TransactionStatus.Started)
                  transaction.RollBack();
              return Result.Failed;
              }
              }

              // finally return
              return Result.Succeeded;
        }
Exemplo n.º 24
0
        private void SetConstraints(Document familyDoc, Extrusion extrusion)
        {
            CurveArrArray curvesArr = new CurveArrArray();
            curvesArr = extrusion.Sketch.Profile;

            foreach (CurveArray ca in curvesArr)
            {
                CurveArrayIterator itor = ca.ForwardIterator();
                itor.Reset();
                itor.MoveNext();
                Line l = itor.Current as Line;
                _rightCon.Append(l.Reference);
                itor.MoveNext();
                l = itor.Current as Line;
                _topCon.Append(l.Reference);
                itor.MoveNext();
                l = itor.Current as Line;
                _leftCon.Append(l.Reference);
                l = itor.Current as Line;
                _botCon.Append(l.Reference);
            }
            ReferenceArrayArray conArray = new ReferenceArrayArray();

            conArray.Append(_rightCon);
            conArray.Append(_topCon);
            conArray.Append(_leftCon);
            conArray.Append(_botCon);

            //Line line = familyDoc.Application.Create.NewLine(_vert[0], _vert[1], true);
            ConstructConstraint(familyDoc, _rightCon);
            //line = familyDoc.Application.Create.NewLine(_vert[1], _vert[2], true);
            ConstructConstraint(familyDoc, _topCon);
            //line = familyDoc.Application.Create.NewLine(_vert[2], _vert[3], true);
            ConstructConstraint(familyDoc, _leftCon);
            //line = familyDoc.Application.Create.NewLine(_vert[3], _vert[0], true);
            //ConstructConstraint(familyDoc, _botCon, line);
        }
Exemplo n.º 25
0
        public void createBuliding(int inpPlotType)
        {
            Random bldHeights = new Random();

            if (this.plotSrf.GetArea() < 50)
            {
                return(false);
            }


            if (inpPlotType > 0)
            {
                int minBldHeight = 0;
                int maxBldHeight = 3;


                if (inpPlotType == 1)
                {
                    minBldHeight = 3;
                    maxBldHeight = 9;
                }

                if (inpPlotType == 2)
                {
                    minBldHeight = 18;
                    maxBldHeight = 30;
                }

                if (inpPlotType == 3)
                {
                    minBldHeight = 60;
                    maxBldHeight = 150;
                }

                double actualBulidingHeight = this.bldHeights.Next(minBldHeight, maxBldHeight);

                System.Drawing.Color bldCol = System.Drawing.Color.White;

                if (actualBulidingHeight < 6)
                {
                    ;
                }
                bldCol = System.Drawing.Color.FromArgb(168, 126, 198);
                else if (actualBulidingHeight < 12)
                {
                    bldCol = System.Drawing.Color.FromArgb(255, 173, 194);
                }
                else if (actualBulidingHeight < 36)
                {
                    bldCol = System.Drawing.Color.FromArgb(243, 104, 75);
                }
                else if (actualBulidingHeight < 92)
                {
                    bldCol = System.Drawing.Color.FromArgb(225, 164, 24);
                }
                else if (actualBulidingHeight < 120)
                {
                    bldCol = System.Drawing.Color.FromArgb(254, 255, 51);
                }


                ObjectAttributes oa = new ObjectAttributes
                                      oa.ColorSource = ObjectColorSource.ColorFromObjects;
                oa.ObjectColor = System.Drawing.Color.FromArgb()


                                 Curve border = Curve.JoinCurves(this.plotSrf.DuplicateNakedEdgeCurves(true, false))[0];
                this.bulidingOutlines         = Curve.JoinCurves(border.Offset(Plane.WorldXY, -5, RhinoDoc.ActiveDoc.ModelAbsoluteTolerance, CurveOffsetCornerStyle.None))[0];



                this.buliding = Extrusion.Create(this.bulidingOutlines, actualBulidingHeight, true);
                RhinoDoc.ActiveDoc.Objects.AddExtrusion(this.buliding, oa);
                RhinoDoc.ActiveDoc.Objects.AddCurve(bulidingOutlines);
            }
Exemplo n.º 26
0
        /// <since>5.0</since>
        public Extrusion DuplicateExtrusionGeometry()
        {
            Extrusion rc = DuplicateGeometry() as Extrusion;

            return(rc);
        }
Exemplo n.º 27
0
        /// <summary>
        /// get all planar faces of an extrusion
        /// </summary>
        /// <param name="extrusion">the extrusion to read</param>
        /// <returns>a list of all planar faces of the extrusion</returns>
        public List<PlanarFace> GetPlanarFaces(Extrusion extrusion)
        {
            // the option to get geometry elements
            Options m_geoOptions = m_application.Create.NewGeometryOptions();
            m_geoOptions.View = m_document.ActiveView;
            m_geoOptions.ComputeReferences = true;

            // get the planar faces
            List<PlanarFace> m_planarFaces = new List<PlanarFace>();
            Autodesk.Revit.DB.GeometryElement geoElement = extrusion.get_Geometry(m_geoOptions);
            foreach (GeometryObject geoObject in geoElement.Objects)
            {
                Solid geoSolid = geoObject as Solid;
                if (null == geoSolid)
                {
                    continue;
                }
                foreach (Face geoFace in geoSolid.Faces)
                {
                    if (geoFace is PlanarFace)
                    {
                        m_planarFaces.Add(geoFace as PlanarFace);
                    }
                }
            }
            return m_planarFaces;
        }
Exemplo n.º 28
0
 /// <summary>
 /// The method is used to get extrusion's face along to the specified parameters
 /// </summary>
 /// <param name="extrusion">the extrusion</param>
 /// <param name="view">options view</param>
 /// <param name="ExtOrInt">If true indicate getting exterior extrusion face, else getting interior extrusion face</param>
 /// <returns>the face</returns>
 public static Face GetExtrusionFace(Extrusion extrusion, View view, bool ExtOrInt)
 {
     Face face = null;
     FaceArray faces = null;
     if (extrusion.IsSolid)
     {
         Options options = new Options();
         options.ComputeReferences = true;
         options.View = view;
         GeometryObjectArray geoArr = extrusion.get_Geometry(options).Objects;
         foreach (GeometryObject geoObj in geoArr)
         {
             if (geoObj is Solid)
             {
                 Solid s = geoObj as Solid;
                 faces = s.Faces;
             }
         }
         if (ExtOrInt)
             face = GetExteriorFace(faces);
         else
             face = GetInteriorFace(faces);
     }
     return face;
 }
Exemplo n.º 29
0
        private void Stream( ArrayList data, Extrusion ext )
        {
            data.Add( new Snoop.Data.ClassSeparator( typeof( Extrusion ) ) );

              data.Add( new Snoop.Data.Double( "End offset", ext.EndOffset ) );
              data.Add( new Snoop.Data.Double( "Start offset", ext.StartOffset ) );
              data.Add( new Snoop.Data.Object( "Sketch", ext.Sketch ) );
        }
    // ======================================
    //   (4.2) add materials
    // ======================================
    //
    // in Revit 2010, you cannot modify asset.
    // SPR# 155053 - WishList: Ability to access\modify properties in Render Appearance of Materials using API.
    // To Do in future: you can extend this functionality to create a new one in future.
    //
    // This function is only for reference.  this is not used. If use this way, it is fixed at solid level. You cannot change it.
    //
    public void addMaterialsToSolid(Extrusion pSolid)
    {
      // We assume Material type "Glass" exists. Template "Metric Column.rft" include "Glass",
      // which in fact is the only interesting one to see the effect.
      // In practice, you will want to include in your template.
      //
      // To Do: For the exersize, create it with more appropriate ones in UI, then use the name here.
      //
      Material pMat = findElement(typeof(Material), "Glass") as Material;
      if (pMat != null)
      {
        // no material with the given name.
        ElementId idMat = pMat.Id;

        // 'Autodesk.Revit.DB.Element.get_Parameter(string)' is obsolete: 
        // 'This property is obsolete in Revit 2015, 
        // as more than one parameter can have the same name on a given element. 
        // Use Element.Parameters to obtain a complete list of parameters on this Element, 
        // or Element.GetParameters(String) to get a list of all parameters by name, 
        // or Element.LookupParameter(String) to return the first available parameter with the given name

        //pSolid.get_Parameter("Material").Set(idMat);       

        /// Updated for Revit 2015
        /// 
        pSolid.LookupParameter("Material").Set(idMat);


      }
    }
Exemplo n.º 31
0
        /***************************************************/
        /**** public Computation - Surfaces            ****/
        /***************************************************/

        public static BoundingBox Bounds(this Extrusion surface)
        {
            BoundingBox box = surface.Curve.IBounds();

            return(box + (box + surface.Direction));
        }
Exemplo n.º 32
0
        // ===============================================================
        // helper function: given a solid, find a planar 
        // face with the given normal (version 2)
        // this is a slightly enhaced version of the previous 
        // version and checks if the face is on the given reference plane.
        // ===============================================================
        PlanarFace findFace(Extrusion pBox, XYZ normal, ReferencePlane refPlane)
        {
            // get the geometry object of the given element
            //
            Options op = new Options();
            op.ComputeReferences = true;
            GeometryElement geomElem = pBox.get_Geometry(op);

            // loop through the array and find a face with the given normal
            //
            foreach (GeometryObject geomObj in geomElem)
            {
                if (geomObj is Solid)  // solid is what we are interested in.
                {
                    Solid pSolid = geomObj as Solid;
                    FaceArray faces = pSolid.Faces;
                    foreach (Face pFace in faces)
                    {
                        PlanarFace pPlanarFace = (PlanarFace)pFace;
                        // check to see if they have same normal
                        if ((pPlanarFace != null) && pPlanarFace.FaceNormal.IsAlmostEqualTo(normal))
                        {
                            // additionally, we want to check if the face is on the reference plane
                            //
                            XYZ p0 = refPlane.BubbleEnd;
                            XYZ p1 = refPlane.FreeEnd;
                            //Line pCurve = _app.Create.NewLineBound(p0, p1);  // Revit 2013
                            Line pCurve = Line.CreateBound(p0, p1);  // Revit 2014
                            if (pPlanarFace.Intersect(pCurve) == SetComparisonResult.Subset)
                            {
                                return pPlanarFace; // we found the face
                            }
                        }
                    }
                }

                // will come back later as needed.
                //
                //else if (geomObj is Instance)
                //{
                //}
                //else if (geomObj is Curve)
                //{
                //}
                //else if (geomObj is Mesh)
                //{
                //}
            }

            // if we come here, we did not find any.
            return null;
        }
Exemplo n.º 33
0
        public static List <Brep> DrawHouse(Household hhp)
        {
            double   height  = Consts.FloorHeight;
            Curve    outline = hhp.GetOutline();
            Polyline outPoly = CurveTools.ToPolyline(outline);

            Brep x = Extrusion.Create(outline, height, true).ToBrep();

            x.CapPlanarHoles(1);

            double windowSide   = 300;
            double windowLow    = 300;
            double windowHeight = 2100;
            double windowDepth  = 200;

            List <Brep> wins = new List <Brep>();

            for (int i = 0; i < hhp.LightingEdge.Count; i++)
            {
                //Rhino.RhinoDoc.ActiveDoc.Objects.Add(hhp.LightingEdge[i].ToNurbsCurve());
                //var c = hhp.LightingEdge[i].ToNurbsCurve().Trim(CurveEnd.Both, 300);
                //var p1 = c.PointAtStart + Vector3d.ZAxis * 300;
                //var p2 = c.PointAtStart + Vector3d.ZAxis * 2400;
                //var p3 = c.PointAtEnd + Vector3d.ZAxis * 2400;
                //var p4 = c.PointAtEnd + Vector3d.ZAxis * 300;
                //Brep[] open = Brep.CreatePlanarBreps(new PolylineCurve(new Point3d[] { p1, p2, p3, p4, p1 }));
                Line tempLine = hhp.LightingEdge[i];

                Point3d  midPoint  = tempLine.PointAt(0.5);
                Vector3d windowVec = tempLine.UnitTangent;
                windowVec.Rotate(Math.PI / 2, Vector3d.ZAxis);
                midPoint.Transform(Transform.Translation(Vector3d.Multiply(windowVec, 10)));

                if (hhp.GetOutline().Contains(midPoint) == Rhino.Geometry.PointContainment.Inside)
                {
                    tempLine.Flip();
                }

                tempLine.Extend(-windowSide, -windowSide);

                Curve tempCurve = tempLine.ToNurbsCurve();
                tempCurve.Translate(Vector3d.Multiply(Vector3d.ZAxis, windowLow));
                Point3d pt1 = tempCurve.PointAtStart;
                Point3d pt2 = tempCurve.PointAtEnd;
                Point3d pt3 = tempCurve.PointAtEnd;
                pt3.Transform(Transform.Translation(Vector3d.Multiply(Vector3d.ZAxis, windowHeight)));
                Point3d pt4 = tempCurve.PointAtStart;
                pt4.Transform(Transform.Translation(Vector3d.Multiply(Vector3d.ZAxis, windowHeight)));
                Point3d        pt5          = tempCurve.PointAtStart;
                List <Point3d> windowPoints = new List <Point3d>();
                windowPoints.Add(pt1);
                windowPoints.Add(pt2);
                windowPoints.Add(pt3);
                windowPoints.Add(pt4);
                windowPoints.Add(pt5);
                Polyline windowPolyline = new Polyline(windowPoints);
                Curve    win            = windowPolyline.ToNurbsCurve();


                Plane windowPlane;
                win.TryGetPlane(out windowPlane);
                Vector3d windowNormal = windowPlane.Normal;
                Curve    windowCurve  = win.Duplicate() as Curve;
                windowCurve.Translate(Vector3d.Multiply(windowNormal, windowDepth));
                Surface windowSurface = Surface.CreateExtrusion(windowCurve, Vector3d.Multiply(windowNormal, -windowDepth * 2));
                Brep    windowBrep    = windowSurface.ToBrep();
                Brep[]  withHolesTemp = x.Split(windowBrep, 1);

                if (withHolesTemp.Length != 0)
                {
                    x = withHolesTemp[0];
                }

                Curve duplicatedWindowCurve = (win.Duplicate() as Curve);
                duplicatedWindowCurve.Transform(Transform.Translation(windowNormal * (windowDepth - 100)));

                Curve windowCurveBottom = duplicatedWindowCurve.DuplicateSegments()[0];
                Curve heightCurve       = duplicatedWindowCurve.DuplicateSegments()[1];

                wins.AddRange(DrawWindowAll(windowCurveBottom, heightCurve.GetLength(), false));

                Curve[] tempLoftBase = { win, duplicatedWindowCurve };

                Curve pathCurve = new LineCurve(Point3d.Origin, new Point3d(windowNormal * (-windowDepth + 100)));
                wins.Add(Brep.JoinBreps(Brep.CreateFromLoft(tempLoftBase, Point3d.Unset, Point3d.Unset, LoftType.Normal, false), 0)[0]);
            }


            //1. 양쪽에서 300씩 , 위400 아래300 사각형.빵꾸. 안쪽으로 200
            //->창틀
            //2. 사방 30씩, 안쪽으로 100
            //->창문와꾸
            //3. 창 안쪽에서 20, 창문와꾸 30, 바깥쪽50 ,길이 1200 * 2
            //4. ㅊ



            //Brep w1 = Brep.create  hhp.LightingEdge[0]
            wins.Add(x);
            return(wins);
        }
Exemplo n.º 34
0
        private static void CollectGeometryInfo(RhinoObjectInfo objInfo, ref RhinoGeometryContainer container)
        {
            try
            {
                ObjectType geoType = objInfo.Geometry.ObjectType;
                switch (geoType)
                {
                case ObjectType.Point:
                    Point point = objInfo.Geometry as Point;
                    if (null != point)
                    {
                        container.Points.Add(objInfo);
                    }
                    break;

                case ObjectType.Curve:
                    Curve curve = objInfo.Geometry as Curve;
                    if (null != curve)
                    {
                        container.Curves.Add(objInfo);
                    }
                    break;

                case ObjectType.Surface:
                    Surface surface = objInfo.Geometry as Surface;
                    if (null != surface)
                    {
                        container.Surfaces.Add(objInfo);
                    }
                    break;

                case ObjectType.Brep:
                    Brep brep = objInfo.Geometry as Brep;
                    if (null != brep)
                    {
                        container.Breps.Add(objInfo);
                    }
                    break;

                case ObjectType.Extrusion:
                    Extrusion extrusion = objInfo.Geometry as Extrusion;
                    if (null != extrusion)
                    {
                        container.Extrusions.Add(objInfo);
                    }
                    break;

                case ObjectType.Mesh:
                    Mesh mesh = objInfo.Geometry as Mesh;
                    if (null != mesh)
                    {
                        container.Meshes.Add(objInfo);
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
            }
        }
Exemplo n.º 35
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            //Hello World
            //TaskDialog.Show("VL title", "VL says Hello Revit");

            var uiApp = commandData.Application;
            var app   = commandData.Application.Application;
            var uiDoc = commandData.Application.ActiveUIDocument;
            var doc   = commandData.Application.ActiveUIDocument.Document;


            #region 放置类型为"0762*2032 mm"的门
            //首先通过类型过滤出 类型为门的族类型,找到名称相同的
            string       doorTypeName = "0762*2032 mm";
            FamilySymbol doorType     = null;
            var          filter       = new LogicalAndFilter(
                new ElementCategoryFilter(BuiltInCategory.OST_Doors),
                new ElementClassFilter(typeof(FamilySymbol))
                );
            var  collector   = new FilteredElementCollector(doc).WherePasses(filter);
            bool symbolFound = collector.FirstOrDefault(c => c.Name == doorTypeName) != null;
            //如果没有则通过文件加载族
            if (symbolFound)
            {
                doorType = collector.FirstOrDefault(c => c.Name == doorTypeName) as FamilySymbol;
            }
            else
            {
                string file = @"familyFilePath";
                Family family;
                if (doc.LoadFamily(file, out family))
                {
                    var validType = family.GetValidTypes().FirstOrDefault(c =>
                    {
                        var symbol = (doc.GetElement(c) as FamilySymbol);
                        if (symbol != null && symbol.Name == doorTypeName)
                        {
                            return(true);
                        }
                        return(false);
                    });
                    if (validType != null)
                    {
                        doorType    = doc.GetElement(validType) as FamilySymbol;
                        symbolFound = true;
                    }
                }
            }
            //使用族类型创建门 线性的门是有着LocationCurve的且LocationCurve.Curve为Line的元素
            Wall wall = null;
            if (doorType != null)
            {
                Element element = new FilteredElementCollector(doc)
                                  .WherePasses(new ElementClassFilter(typeof(Wall)))
                                  .FirstOrDefault(c =>
                {
                    var locationCurve = c.Location as LocationCurve;
                    if (locationCurve != null)
                    {
                        var line = locationCurve.Curve as Line;
                        if (line != null)
                        {
                            return(true);
                        }
                        return(false);
                    }
                    return(false);
                });
                if (element != null)
                {
                    wall = element as Wall;
                }
            }
            //在墙的中心创建一个门
            if (wall != null)
            {
                var            line          = (wall.Location as LocationCurve).Curve as Line;
                var            wallLevel     = doc.GetElement(wall.LevelId) as Level;
                XYZ            midPoint      = (line.GetEndPoint(0) + line.GetEndPoint(1)) / 2;
                var            structureType = Autodesk.Revit.DB.Structure.StructuralType.NonStructural;
                FamilyInstance door          = doc.Create.NewFamilyInstance(midPoint, doorType, wall, wallLevel, structureType);
            }
            #endregion

            #region  制墙类型
            var wallElementId = 1111;
            wall = doc.GetElement(new ElementId(wallElementId)) as Wall;
            if (wall != null)
            {
                var         wallType       = wall.WallType;
                ElementType duplicatedType = wallType.Duplicate(wall.Name + "duplicated");
            }
            #endregion

            #region 元素移动
            VLTransactionHelper.DelegateTransaction(doc, "创建一根柱子", () =>
            {
                //Revit文档的创建句柄
                Autodesk.Revit.Creation.Document creator = doc.Create;
                XYZ origin              = new XYZ(0, 0, 0);
                Level level             = doc.GetElement(new ElementId(12122)) as Level;
                FamilySymbol columnType = doc.GetElement(new ElementId(12123)) as FamilySymbol;
                var structureType       = Autodesk.Revit.DB.Structure.StructuralType.Column;
                FamilyInstance column   = creator.NewFamilyInstance(origin, columnType, level, structureType);
                XYZ newPlace            = new XYZ(10, 20, 30);
                ElementTransformUtils.MoveElement(doc, column.Id, newPlace);
                return(true);
            });
            #endregion

            #region ElementTransformUtils
            //ElementTransformUtils.CopyElement();
            //ElementTransformUtils.CopyElements();
            //ElementTransformUtils.MirrorElement();
            //ElementTransformUtils.MirrorElements();
            //ElementTransformUtils.MoveElement();
            //ElementTransformUtils.MoveElements();
            //ElementTransformUtils.RotateElement();
            //ElementTransformUtils.RotateElements();
            #endregion

            #region 元素旋转
            VLTransactionHelper.DelegateTransaction(doc, "ElementTransformUtils旋转方法", () =>
            {
                LocationCurve wallLine = wall.Location as LocationCurve;
                XYZ p1    = wallLine.Curve.GetEndPoint(0);
                XYZ p2    = new XYZ(p1.X, p1.Y, 30);
                Line axis = Line.CreateBound(p1, p2);
                ElementTransformUtils.RotateElement(doc, wall.Id, axis, Math.PI / 3);//逆时针60°
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "LocationCurve,LocationPoint,自带的旋转方法", () =>
            {
                LocationCurve locationCurve = wall.Location as LocationCurve;//线性坐标自带线
                if (locationCurve != null)
                {
                    Curve curve = locationCurve.Curve;
                    var start   = curve.GetEndPoint(0);
                    Line axis   = Line.CreateBound(start, start.Add(new XYZ(0, 0, 10)));
                    locationCurve.Rotate(axis, Math.PI);//PI=180°
                }
                LocationPoint locationPoint = wall.Location as LocationPoint;
                if (locationPoint != null)
                {
                    var start = locationPoint.Point;
                    Line axis = Line.CreateBound(start, start.Add(new XYZ(0, 0, 10)));
                    locationPoint.Rotate(axis, Math.PI);
                }
                return(true);
            });
            #endregion

            #region 元素镜像
            VLTransactionHelper.DelegateTransaction(doc, "元素镜像", () =>
            {
                Plane plane = new Plane(XYZ.BasisX, XYZ.Zero);
                if (ElementTransformUtils.CanMirrorElement(doc, wall.Id))
                {
                    ElementTransformUtils.MirrorElement(doc, wall.Id, plane);
                }
                return(true);
            });
            #endregion

            #region 元素删除
            //var deleteElements = Document.Delete(@ElementIds);
            #endregion

            #region 元素组合
            VLTransactionHelper.DelegateTransaction(doc, "元素组合", () =>
            {
                List <ElementId> elementIds = new List <ElementId>()
                {
                    new ElementId(1000),
                    new ElementId(1001),
                    new ElementId(1002),
                };
                Group group = doc.Create.NewGroup(elementIds);
                return(true);
            });
            #endregion

            #region 元素编辑
            VLTransactionHelper.DelegateTransaction(doc, "创建参照平面", () =>
            {
                XYZ bubbleEnd = new XYZ(0, 5, 5);
                XYZ freeEnd   = new XYZ(5, 5, 5);
                XYZ cutVector = XYZ.BasisY;
                View view     = doc.ActiveView;
                ReferencePlane referencePlane = doc.FamilyCreate.NewReferencePlane(bubbleEnd, freeEnd, cutVector, view);
                referencePlane.Name           = "MyReferencePlane";
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "创建参照线,由模型线-转>参照线", () =>
            {
                ModelCurve modelCurve = doc.GetElement(new ElementId(1000)) as ModelCurve;//ModelCurve模型线
                modelCurve.ChangeToReferenceLine();
                //modelCurve.IsReferenceLine;
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "通过标高创建草图平面,然后在草图平面创建模型线", () =>
            {
                Level level             = new FilteredElementCollector(doc).OfCategory(BuiltInCategory.OST_Levels).FirstOrDefault() as Level;
                Line line               = Line.CreateBound(XYZ.Zero, new XYZ(10, 10, 0));
                SketchPlane sketchPlane = SketchPlane.Create(doc, level.Id);
                ModelCurve modelLine    = doc.FamilyCreate.NewModelCurve(line, sketchPlane);
                return(true);
            });
            VLTransactionHelper.DelegateTransaction(doc, "使用拉身体获取相应的草图平面", () =>
            {
                Extrusion extrusion         = doc.GetElement(new ElementId(11212)) as Extrusion;
                SketchPlane sketchPlane     = extrusion.Sketch.SketchPlane;
                CurveArrArray sketchProfile = extrusion.Sketch.Profile;
                return(true);
            });
            #endregion

            #region 族
            string       tagName   = "梁平法_集中标_左对齐";
            FamilySymbol tagSymbol = null;
            //查找族类型
            var symbols = new FilteredElementCollector(doc)
                          .WherePasses(new ElementClassFilter(typeof(FamilySymbol)))
                          .WherePasses(new ElementCategoryFilter(BuiltInCategory.OST_StructuralFramingTags));
            var targetSymbol = symbols.FirstOrDefault(c => c.Name == tagName);
            if (targetSymbol != null)
            {
                tagSymbol = targetSymbol as FamilySymbol;
            }
            //空时加载族类型
            if (tagSymbol == null)
            {
                var    symbolFile = @"E:\WorkingSpace\Tasks\0526标注\梁平法_集中标_左对齐.rfa";
                Family family;
                if (doc.LoadFamily(symbolFile, out family))
                {
                    foreach (ElementId typeId in family.GetValidTypes())
                    {
                        var validType = doc.GetElement(typeId) as FamilySymbol;
                        if (validType != null && validType.Name == tagName)
                        {
                            tagSymbol = validType;
                            break;
                        }
                    }
                }
                else
                {
                    TaskDialogShow("加载族文件失败");
                }
            }
            //如果上述两者获取到了对应的族
            if (tagSymbol != null)
            {
                //doc.Create.NewFamilyInstance(, tagSymbol);
            }
            #endregion

            #region 建筑建模

            VLTransactionHelper.DelegateTransaction(doc, "修改标高的基面", () =>
            {
                var levelId         = 111;
                Level level         = doc.GetElement(new ElementId(levelId)) as Level;
                LevelType levelType = doc.GetElement(level.GetTypeId()) as LevelType;


                return(true);
            });


            #endregion

            return(Result.Succeeded);
        }
        // ======================================
        //  (4.2) add materials
        // ======================================
        //
        // in Revit 2010, you cannot modify asset.
        // SPR# 155053 - WishList: Ability to access\modify properties in Render Appearance of Materials using API.
        // To Do in future: you can extend this functionality to create a new one in future.
        //
        // This function is only for reference.  this is not used. If use this way, it is fixed at solid level. You cannot change it.
        //
        public void addMaterialsToSolid(Extrusion pSolid)
        {
            // We assume Material type "Glass" exists. Template "Metric Column.rft" include "Glass",
            // which in fact is the only interesting one to see the effect.
            // In practice, you will want to include in your template.
            //
            // To Do: For the exersize, create it with more appropriate ones in UI, then use the name here.
            //
            Material pMat = findElement(typeof(Material), "Glass") as Material;
            if (pMat != null)
            {
                // no material with the given name.
                ElementId idMat = pMat.Id;

                // 'Autodesk.Revit.DB.Element.get_Parameter(string)' is obsolete 
                // 'This property is obsolete in Revit 2015, 
                //Parameter paramMat = pSolid.get_Parameter("Material");

                //pSolid.get_Parameter("Material").Set(idMat);

                /// Updated for Revit 2015

                pSolid.LookupParameter("Material").Set(idMat);
            }
        }
Exemplo n.º 37
0
        public static _Extrusion_GetSizes[] _GetSizes(this Extrusion e)
        {
            var pointAtStart = e.PathStart;
            var brep         = e.ToBrep();

            // Get edges contacted with start point of Extrusion
            var trims = new List <_Extrusion_TrimsSort>();

            foreach (var f in brep.Faces)
            {
                foreach (var l in f._Loops_ThreadSafe())
                {
                    foreach (var t in l._Trims_ThreadSafe())
                    {
                        if (t.Edge != null)
                        {
                            if (t.Edge.PointAtStart._DistanceTo(pointAtStart)._IsZero())
                            {
                                trims.Add(new _Extrusion_TrimsSort()
                                {
                                    trim = t
                                });
                            }
                            else if (t.Edge.PointAtEnd._DistanceTo(pointAtStart)._IsZero())
                            {
                                trims.Add(new _Extrusion_TrimsSort()
                                {
                                    trim = t, IsReversed = true
                                });
                            }
                        }
                    }
                }
            }

            // Set lengths for every edge
            foreach (var trim in trims)
            {
                trim.length = trim.trim.Edge._GetLength_ThreadSafe();
            }

            // Sort
            trims.Sort((a, b) =>
            {
                if (a.length._IsSame(b.length))
                {
                    return(0);
                }
                return(a.length - b.length < 0 ? 1 : -1);
            });

            // Remove duplicated edges
            for (int i = trims.Count - 1; i >= 1; i--) // loop exluding first
            {
                var trim                = trims[i];
                var trimPrev            = trims[i - 1];
                var trim_StartPoint     = !trim.IsReversed ? trim.trim.Edge.PointAtStart : trim.trim.Edge.PointAtEnd;
                var trim_EndPoint       = !trim.IsReversed ? trim.trim.Edge.PointAtEnd : trim.trim.Edge.PointAtStart;
                var trimPrev_StartPoint = !trimPrev.IsReversed ? trimPrev.trim.Edge.PointAtStart : trimPrev.trim.Edge.PointAtEnd;
                var trimPrev_EndPoint   = !trimPrev.IsReversed ? trimPrev.trim.Edge.PointAtEnd : trimPrev.trim.Edge.PointAtStart;
                if (trim_StartPoint.DistanceTo(trimPrev_StartPoint)._IsZero() &&
                    trim_EndPoint.DistanceTo(trimPrev_EndPoint)._IsZero())
                {
                    trims.RemoveAt(i);
                }
            }


            // Reverse if needed and return results
            var res = trims.Select(o =>
            {
                var crv = o.trim.Edge.DuplicateCurve();
                if (o.IsReversed)
                {
                    crv.Reverse();
                }
                return(new _Extrusion_GetSizes
                {
                    Crv = crv,
                    Length = o.length
                });
            }).ToArray();


            // Set names and values
            foreach (var s in res)
            {
                s.Size = s.Length;
            }
            if (res.Length == 3)
            {
                res[0].Name = "Width";
                res[1].Name = "Height";
                res[2].Name = "Thickness";
            }
            else if (res.Length == 2)
            {
                res[0].Name = "Width";
                res[1].Name = "Radius";
                res[1].Size = res[1].Length / (2 * Math.PI);
            }

            return(res);
        }
        public void addMaterials(Extrusion pSolid)
        {
            // We assume Material type "Glass" exists. Template "Metric Column.rft" include "Glass",
            // which in fact is the only interesting one to see the effect.
            // In practice, you will want to include in your template.
            //
            // To Do: For the exersize, create it with more appropriate ones in UI, then use the name here.
            //

            // (1)  get the materials id that we are intersted in (e.g., "Glass")
            //
            Material pMat = findElement(typeof(Material), "Glass") as Material;
            if (pMat != null)
            {
                ElementId idMat = pMat.Id;
                // (2a) this add a material to the solid base.  but then, we cannot change it for each column.
                //
                //pSolid.Parameter("Material").Set(idMat)

                // (2b) add a parameter for material finish
                //
                // this time we use instance parameter so that we can change it at instance level.
                //
                FamilyManager pFamilyMgr = _doc.FamilyManager;
                FamilyParameter famParamFinish = pFamilyMgr.AddParameter("ColumnFinish", BuiltInParameterGroup.PG_MATERIALS, ParameterType.Material, true);

                // (2b.1) associate material parameter to the family parameter we just added
                //

                // 'Autodesk.Revit.DB.Element.get_Parameter(string)' is obsolete 
                // 'This property is obsolete in Revit 2015, 
                //Parameter paramMat = pSolid.get_Parameter("Material");

                /// Updated for Revit 2015

                Parameter paramMat = pSolid.LookupParameter("Material");
                pFamilyMgr.AssociateElementParameterToFamilyParameter(paramMat, famParamFinish);

                // (2b.2) for our convenience, let's add another type with Glass finish
                //
                addType("Glass", 600.0, 600.0);
                pFamilyMgr.Set(famParamFinish, idMat);
            }
        }
Exemplo n.º 39
0
        // ======================================
        //   (2.1) add alignments
        // ======================================
        void addAlignments(Extrusion pBox)
        {
            //
            // (1) we want to constrain the upper face of the column to the "Upper Ref Level"
            //

            // which direction are we looking at?
            //
            View pView = findElement(typeof(View), "Front") as View;

            // find the upper ref level
            // findElement() is a helper function. see below.
            //
            Level upperLevel = findElement(typeof(Level), "Upper Ref Level") as Level;
            Reference ref1 = upperLevel.GetPlaneReference();

            // find the face of the box
            // findFace() is a helper function. see below.
            //
            PlanarFace upperFace = findFace(pBox, new XYZ(0.0, 0.0, 1.0)); // find a face whose normal is z-up.
            Reference ref2 = upperFace.Reference;

            // create alignments
            //
            _doc.FamilyCreate.NewAlignment(pView, ref1, ref2);

            //
            // (2) do the same for the lower level
            //

            // find the lower ref level
            // findElement() is a helper function. see below.
            //
            Level lowerLevel = findElement(typeof(Level), "Lower Ref. Level") as Level;
            Reference ref3 = lowerLevel.GetPlaneReference();

            // find the face of the box
            // findFace() is a helper function. see below.
            PlanarFace lowerFace = findFace(pBox, new XYZ(0.0, 0.0, -1.0)); // find a face whose normal is z-down.
            Reference ref4 = lowerFace.Reference;

            // create alignments
            //
            _doc.FamilyCreate.NewAlignment(pView, ref3, ref4);

            //
            // (3)  same idea for the Right/Left/Front/Back
            //
            // get the plan view
            // note: same name maybe used for different view types. either one should work.
            View pViewPlan = findElement(typeof(ViewPlan), "Lower Ref. Level") as View;

            // find reference planes
            ReferencePlane refRight = findElement(typeof(ReferencePlane), "Right") as ReferencePlane;
            ReferencePlane refLeft = findElement(typeof(ReferencePlane), "Left") as ReferencePlane;
            ReferencePlane refFront = findElement(typeof(ReferencePlane), "Front") as ReferencePlane;
            ReferencePlane refBack = findElement(typeof(ReferencePlane), "Back") as ReferencePlane;
            ReferencePlane refOffsetV = findElement(typeof(ReferencePlane), "OffsetV") as ReferencePlane; // added for L-shape
            ReferencePlane refOffsetH = findElement(typeof(ReferencePlane), "OffsetH") as ReferencePlane; // added for L-shape

            // find the face of the box
            // Note: findFace need to be enhanced for this as face normal is not enough to determine the face.
            //
            PlanarFace faceRight = findFace(pBox, new XYZ(1.0, 0.0, 0.0), refRight); // modified for L-shape
            PlanarFace faceLeft = findFace(pBox, new XYZ(-1.0, 0.0, 0.0));
            PlanarFace faceFront = findFace(pBox, new XYZ(0.0, -1.0, 0.0));
            PlanarFace faceBack = findFace(pBox, new XYZ(0.0, 1.0, 0.0), refBack); // modified for L-shape
            PlanarFace faceOffsetV = findFace(pBox, new XYZ(1.0, 0.0, 0.0), refOffsetV); // added for L-shape
            PlanarFace faceOffsetH = findFace(pBox, new XYZ(0.0, 1.0, 0.0), refOffsetH); // added for L-shape

            // create alignments
            //
            _doc.FamilyCreate.NewAlignment(pViewPlan, refRight.GetReference(), faceRight.Reference);
            _doc.FamilyCreate.NewAlignment(pViewPlan, refLeft.GetReference(), faceLeft.Reference);
            _doc.FamilyCreate.NewAlignment(pViewPlan, refFront.GetReference(), faceFront.Reference);
            _doc.FamilyCreate.NewAlignment(pViewPlan, refBack.GetReference(), faceBack.Reference);
            _doc.FamilyCreate.NewAlignment(pViewPlan, refOffsetV.GetReference(), faceOffsetV.Reference); // added for L-shape
            _doc.FamilyCreate.NewAlignment(pViewPlan, refOffsetH.GetReference(), faceOffsetH.Reference); // added for L-shape
        }
        // =================================================================
        //  (5.1.2) set the visibility of the solid not to show in coarse
        // =================================================================
        public void changeVisibility(Extrusion pSolid)
        {
            // set the visibility of the model not to shown in coarse.
            //
            FamilyElementVisibility pVis = new FamilyElementVisibility(FamilyElementVisibilityType.Model);
            pVis.IsShownInCoarse = false;

            pSolid.SetVisibility(pVis);
        }
Exemplo n.º 41
0
        // =============================================================
        //   helper function: find a planar face with the given normal
        // =============================================================
        PlanarFace findFace(Extrusion pBox, XYZ normal)
        {
            // get the geometry object of the given element
            //
            Options op = new Options();
            op.ComputeReferences = true;
            GeometryElement geomElem = pBox.get_Geometry(op);

            // loop through the array and find a face with the given normal
            //
            foreach (GeometryObject geomObj in geomElem)
            {
                if (geomObj is Solid)  // solid is what we are interested in.
                {
                    Solid pSolid = geomObj as Solid;
                    FaceArray faces = pSolid.Faces;
                    foreach (Face pFace in faces)
                    {
                        PlanarFace pPlanarFace = (PlanarFace)pFace;
                        if ((pPlanarFace != null) && pPlanarFace.FaceNormal.IsAlmostEqualTo(normal)) // we found the face
                        {
                            return pPlanarFace;
                        }
                    }
                }
                // will come back later as needed.
                //
                //else if (geomObj is Instance)
                //{
                //}
                //else if (geomObj is Curve)
                //{
                //}
                //else if (geomObj is Mesh)
                //{
                //}
            }

            // if we come here, we did not find any.
            return null;
        }
Exemplo n.º 42
0
        private void SetConstraints(Document familyDoc, Extrusion extrusion)
        {
            try
            {
                CurveArrArray curvesArr = new CurveArrArray();
                curvesArr = extrusion.Sketch.Profile;

                foreach (CurveArray ca in curvesArr)
                {
                    CurveArrayIterator itor = ca.ForwardIterator();
                    itor.Reset();
                    itor.MoveNext();
                    Line l = itor.Current as Line;
                    _rightCon.Append(l.Reference);
                    itor.MoveNext();
                    l = itor.Current as Line;
                    _topCon.Append(l.Reference);
                    itor.MoveNext();
                    l = itor.Current as Line;
                    _leftCon.Append(l.Reference);
                    l = itor.Current as Line;
                    _botCon.Append(l.Reference);
                }
                ReferenceArrayArray conArray = new ReferenceArrayArray();

                conArray.Append(_rightCon);
                conArray.Append(_topCon);
                conArray.Append(_leftCon);
                conArray.Append(_botCon);

                ConstructConstraint(familyDoc, _rightCon);
                ConstructConstraint(familyDoc, _topCon);
                ConstructConstraint(familyDoc, _leftCon);
            }

            catch (Exception ex)
            {
                TaskDialog.Show("Constraint Error", ex.Message);
            }
        }