예제 #1
1
        static public void CreateTunnel()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor   ed  = doc.Editor;
            Database db  = doc.Database;

            //===========
            Matrix3d           curUCSMatrix = doc.Editor.CurrentUserCoordinateSystem;
            CoordinateSystem3d curUCS       = curUCSMatrix.CoordinateSystem3d;

            double             TunnelDia = 6.04;
            PromptEntityResult per       = ed.GetEntity("Select polylines");
            ObjectId           oid       = per.ObjectId;

            if (per.Status == PromptStatus.OK)
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    BlockTable       bt  = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                    BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);

                    DBObject objPick = tr.GetObject(oid, OpenMode.ForRead);
                    Entity   objEnt  = objPick as Entity;
                    string   sLayer  = objEnt.Layer.ToString();

                    ObjectIdCollection oDBO = CADops.SelectAllPolyline(sLayer);

                    List <string> data = new List <string>();
                    foreach (ObjectId id in oDBO)
                    {
                        //get 3d polyline
                        Polyline3d poly3d = tr.GetObject(id, OpenMode.ForRead) as Polyline3d;

                        //get points on 3d polyline
                        List <Point3d> pts0 = CADops.GetPointsFrom3dPolyline(poly3d, doc);
                        List <Point3d> pts  = pts0.Distinct(new PointComparer(3)).ToList();

                        //get vectors on points
                        List <Vector3d> vectorAlongPath = new List <Vector3d>();
                        List <Vector3d> vectors         = CADops.getVectors(pts, doc, ref vectorAlongPath);

                        List <LoftProfile> loftProfiles = new List <LoftProfile>();
                        for (int i = 0; i < pts.Count(); i = i + 4)
                        {
                            Point3d pt = pts[i];
                            //ed.WriteMessage($"TUN_CreateTBM => {pt.X}, {pt.Y}, {pt.Z}; ");

                            Vector3d v   = vectors[i].GetNormal() * TunnelDia / 2;
                            Matrix3d mat = Matrix3d.Displacement(v);
                            Point3d  npt = pt.TransformBy(mat);

                            //create a 2d line in XY plane
                            Line ln = new Line(npt, pt);

                            btr.AppendEntity(ln);
                            tr.AddNewlyCreatedDBObject(ln, true);

                            double ang = ln.Angle; //vectors[i].GetAngleTo(curUCS.Xaxis);
                                                   //ed.WriteMessage($"angle {ang}\n");

                            Region acRegion = new Region();
                            try
                            {
                                using (Circle acCirc = new Circle())
                                {
                                    acCirc.Center = new Point3d(pt.X, pt.Y, pt.Z);
                                    acCirc.Radius = TunnelDia / 2;

                                    acCirc.TransformBy(Matrix3d.Rotation(Angle.angToRad(90), curUCS.Xaxis, acCirc.Center));
                                    acCirc.TransformBy(Matrix3d.Rotation(ang, curUCS.Zaxis, acCirc.Center));

                                    // Add the new object to the block table record and the transaction
                                    btr.AppendEntity(acCirc);
                                    tr.AddNewlyCreatedDBObject(acCirc, true);

                                    DBObjectCollection acDBObjColl = new DBObjectCollection();
                                    acDBObjColl.Add(acCirc);
                                    DBObjectCollection myRegionColl = new DBObjectCollection();
                                    myRegionColl = Region.CreateFromCurves(acDBObjColl);
                                    Region acRegion1 = myRegionColl[0] as Region;
                                    // Add the new object to the block table record and the transaction
                                    btr.AppendEntity(acRegion1);
                                    tr.AddNewlyCreatedDBObject(acRegion1, true);
                                    LoftProfile lp1 = new LoftProfile(acRegion1);
                                    loftProfiles.Add(lp1);
                                }
                            }
                            catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage(ex.ToString()); }
                        }

                        LoftProfile[] lps = new LoftProfile[loftProfiles.Count()];
                        for (int i = 0; i < loftProfiles.Count(); i++)
                        {
                            lps[i] = loftProfiles[i];
                        }

                        try
                        {
                            // =========== create loft solid
                            Solid3d sol = new Solid3d();
                            sol.SetDatabaseDefaults();
                            LoftOptions lpOptions = new LoftOptions();
                            //LoftProfile lpGuide = new LoftProfile(acLine);//create loft profile
                            //LoftProfile[] guideToLoft = new LoftProfile[1] { lpGuide };
                            //sol.CreateLoftedSolid(lps, guideToLoft, null, lpOptions);//guide to loft can not be null, this parameter is not optional
                            sol.CreateLoftedSolid(lps, null, null, lpOptions);
                            sol.Layer = sLayer;//assign layer

                            //=============save it into database
                            Autodesk.AutoCAD.DatabaseServices.Entity ent = sol;//this is created for using hyperlink
                            btr.AppendEntity(ent);
                            tr.AddNewlyCreatedDBObject(ent, true);
                        }
                        catch (Autodesk.AutoCAD.Runtime.Exception ex) { ed.WriteMessage(ex.ToString()); }
                    }

                    tr.Commit();
                }
            }
        }
예제 #2
0
        public void DrawAndSaveAs2(Product product, IWorkbookSet bookSet)
        {
            if (File.Exists(filePath))
            { throw new Exception("已经存在temp.dwg,请保证已经删除"); }

            //TODO:Not here
            product.Parts.ForEach(it => it.CalculateLocationInfo(Point3d.Origin, 0));

            using (Database db = new Database())
            using (Transaction acTrans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)acTrans.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)acTrans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                foreach (var part in product.Parts)
                {
                    Solid3d panel = new Solid3d();
                    panel.CreateBox(part.Length, part.Width, part.Thickness);

                    panel.TransformBy(Matrix3d.Rotation(part.XRotation * Math.PI / 180, Vector3d.XAxis, Point3d.Origin));
                    panel.TransformBy(Matrix3d.Rotation(part.YRotation * Math.PI / 180, Vector3d.YAxis, Point3d.Origin));
                    panel.TransformBy(Matrix3d.Rotation(part.ZRotation * Math.PI / 180, Vector3d.ZAxis, Point3d.Origin));

                    var moveVector = new Vector3d();
                    panel.TransformBy(Matrix3d.Displacement(part.CenterVector));

                    btr.AppendEntity(panel);
                    acTrans.AddNewlyCreatedDBObject(panel, true);
                }

                acTrans.Commit();

                db.SaveAs(filePath, DwgVersion.Newest);
            }
        }
예제 #3
0
        public void DrawAndSaveAs()
        {
            if (File.Exists(filePath))
            { throw new Exception("已经存在temp.dwg,请保证已经删除"); }

            using (Database db = new Database())
            using (Transaction acTrans = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = (BlockTable)acTrans.GetObject(db.BlockTableId, OpenMode.ForRead);
                BlockTableRecord btr = (BlockTableRecord)acTrans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                Solid3d solid = new Solid3d();
                solid.CreateBox(width, depth, height);

                //Move the block to the left-behind origin
                solid.TransformBy(Matrix3d.Displacement(new Vector3d(width / 2, -depth / 2, height / 2)));

                btr.AppendEntity(solid);
                acTrans.AddNewlyCreatedDBObject(solid, true);

                acTrans.Commit();

                db.SaveAs(filePath, DwgVersion.Newest);
            }
        }
예제 #4
0
 /// <summary>
 /// Gets the centroid of the region.
 /// </summary>
 /// <param name="reg">The instance to which the method applies.</param>
 /// <returns>The centroid of the region (WCS coordinates).</returns>
 public static Point3d Centroid(this Region reg)
 {
     using (Solid3d sol = new Solid3d())
     {
         sol.Extrude(reg, 2.0, 0.0);
         return sol.MassProperties.Centroid - reg.Normal;
     }
 }
예제 #5
0
        public void ExtrudedSolidCommand()
        {
            var document = Application.DocumentManager.MdiActiveDocument;

            if (document == null) // don't bother doing anything else
                return;

            using (var polyline = new Polyline())
            {
                var extrudedSquareInputResult = GetExtrusionInputFromUser();

                // convenience variables
                var width = extrudedSquareInputResult.Width;
                var height = extrudedSquareInputResult.Height;
                var depth = extrudedSquareInputResult.Depth;

                // Using the polyline, we add vertices based on the user's input
                polyline.AddVertexAt(0, Point2d.Origin, 0.0, 0.0, 0.0);
                polyline.AddVertexAt(1, new Point2d(width, 0.0), 0.0, 0.0, 0.0);
                polyline.AddVertexAt(2, new Point2d(width, height), 0.0, 0.0, 0.0);
                polyline.AddVertexAt(3, new Point2d(0.0, height), 0.0, 0.0, 0.0);
                polyline.Closed = true;

                // add polyline to DBObjectCollection for us in creating region from curves
                using (var dbObjectCollection = new DBObjectCollection { polyline })
                {
                    using (var regionCollection = Region.CreateFromCurves(dbObjectCollection))
                    {
                        using (var region = (Region)regionCollection[0])
                        {
                            using (var solid = new Solid3d())
                            {
                                // extrude the region to the depth the user specified
                                solid.Extrude(region, depth, 0.0);
                                using (document.LockDocument())
                                {
                                    using (var database = document.Database)
                                    {
                                        using (var transaction = database.TransactionManager.StartTransaction())
                                        {
                                            // get the current space for appending our extruded solid
                                            using (var currentSpace = (BlockTableRecord)transaction.GetObject(database.CurrentSpaceId, OpenMode.ForWrite))
                                            {
                                                currentSpace.AppendEntity(solid);
                                            }

                                            transaction.AddNewlyCreatedDBObject(solid, true);
                                            transaction.Commit();
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
            }
        }
    private bool _drawing;     // Drawing mode active

    public KinectSolidsJig(
      Document doc, Transaction tr, double profRad
    )
    {
      // Initialise the various members

      _doc = doc;
      _tr = tr;
      _vertices = new Point3dCollection();
      _cursor = null;
      _drawing = false;
      _profile = null;
      _sweepOpts = null;
      _path = null;
      _tube = null;
      _profRad = profRad;
      _sweepBroken = false;
    }
        /// <summary>
        ///     Построить основную часть
        /// </summary>
        private void BuildMainPart()
        {
            using (var transaction =
                       _database.TransactionManager.StartTransaction())
            {
                var blockTableRecord = GetBlockTableRecord(transaction);
                using (var mainPartSolid3d = new Solid3d())
                {
                    mainPartSolid3d.CreateBox(
                        _parameters.ModelParameters[ParameterType.MainPartLength].Value,
                        _parameters.ModelParameters[ParameterType.MainPartWidth].Value,
                        _parameters.ModelParameters[ParameterType.MainPartHeight].Value);

                    blockTableRecord.AppendEntity(mainPartSolid3d);
                    transaction.AddNewlyCreatedDBObject(mainPartSolid3d, true);
                }

                transaction.Commit();
            }
        }
예제 #8
0
        public static Matrix3d GetStairRotation(Solid3d stair3d)
        {
            GripDataCollection grips    = new GripDataCollection();
            GetGripPointsFlags bitFlags = GetGripPointsFlags.GripPointsOnly;

            stair3d.GetGripPoints(grips, 0, 0, Application.DocumentManager.MdiActiveDocument.Editor.GetCurrentView().ViewDirection, bitFlags);

            // Grip point [0] is the start point of the polyline defining the stair
            // Grip point [0,1,2] are the points defining the vertical line and grip point [2,3,4] defining the horizontal line of the first step

            Point2d start   = new Point2d(grips[2].GripPoint.X, grips[2].GripPoint.Y);
            Point2d end     = new Point2d(grips[4].GripPoint.X, grips[4].GripPoint.Y);
            Point3d pInsert = grips[0].GripPoint;

            double angle = start.GetVectorTo(end).Angle;

            grips.Dispose();

            return(Matrix3d.Rotation(angle, Vector3d.ZAxis, pInsert));
        }
예제 #9
0
        /// <summary>
        /// Построить 3д солид-модель
        /// </summary>
        /// <param name="WatchData">Параметры часов</param>
        /// <returns>3Д - солид модель</returns>
        public Solid3d BuildCrown(WatchData WatchData)
        {
            //заводная головка
            Solid3d CrownPart = new Solid3d();

            CrownPart.CreateFrustum(Height, Diameter, Diameter, Diameter);

            //низ заводной головки
            Solid3d CrownBottom = new Solid3d();

            CrownBottom.CreateFrustum(1, Diameter, Diameter, Diameter - _pararameters[ParNames.CrownBottomHeight]);
            CrownBottom.TransformBy(Matrix3d.Displacement(new Point3d(0, 0, Height / _pararameters[ParNames.CrownTransformByZ] + _pararameters[ParNames.CrownTopHeight]) - Point3d.Origin));
            CrownPart.BooleanOperation(BooleanOperationType.BoolUnite, CrownBottom.Clone() as Solid3d);

            //вверх зав.головки
            Solid3d CrownTop = new Solid3d();

            CrownBottom.CreateFrustum(_pararameters[ParNames.CrownTopHeight], Diameter - _pararameters[ParNames.CrownTopHeight], Diameter - _pararameters[ParNames.CrownTopHeight], Diameter);
            CrownBottom.TransformBy(Matrix3d.Displacement(new Point3d(0, 0, -Height / _pararameters[ParNames.CrownTransformByZ] - 0.25) - Point3d.Origin));
            CrownPart.BooleanOperation(BooleanOperationType.BoolUnite, CrownBottom.Clone() as Solid3d);

            CrownBottom.CreateFrustum(_pararameters[ParNames.CrownTopHeight], Diameter - _pararameters[ParNames.CrownTopHeight], Diameter - _pararameters[ParNames.CrownTopHeight], Diameter - 1);
            CrownBottom.TransformBy(Matrix3d.Displacement(new Point3d(0, 0, -Height / _pararameters[ParNames.CrownTransformByZ] - _pararameters[ParNames.CrownTopHeight]) - Point3d.Origin));
            CrownPart.BooleanOperation(BooleanOperationType.BoolSubtract, CrownBottom.Clone() as Solid3d);

            //вырезаем цилиндры по радиусу зав. головки
            Solid3d CrownCutter = new Solid3d();

            CrownCutter.CreateFrustum(Height + _pararameters[ParNames.CrownBottomHeight], Diameter / _pararameters[ParNames.CrownCutterCount], Diameter / _pararameters[ParNames.CrownCutterCount], Diameter / _pararameters[ParNames.CrownCutterCount]);

            for (int i = 0; i < _pararameters[ParNames.CrownCutterCylinder]; i++)
            {
                CrownCutter.TransformBy(Matrix3d.Displacement(new Vector3d(Diameter * Math.Cos(Math.PI / 12 * i), Diameter * Math.Sin(Math.PI / 12 * i), 0)));
                CrownPart.BooleanOperation(BooleanOperationType.BoolSubtract, CrownCutter.Clone() as Solid3d);
                CrownCutter.TransformBy(Matrix3d.Displacement(new Vector3d(-Diameter * Math.Cos(Math.PI / 12 * i), -Diameter * Math.Sin(Math.PI / 12 * i), 0)));
            }

            CrownPart.TransformBy(Matrix3d.Rotation(Math.PI / 2, new Vector3d(1, 0, 0), Point3d.Origin));
            CrownPart.TransformBy(Matrix3d.Displacement(new Vector3d(0, WatchData.BodyDiameter + Height / _pararameters[ParNames.CrownTransformByZ] + _pararameters[ParNames.CrownBottomHeight], 0)));
            return(CrownPart);
        }
예제 #10
0
파일: Body.cs 프로젝트: 15831944/WatchCAD
        /// <summary>
        /// Строим стрелки
        /// </summary>
        /// <param name="WatchData">Информация о часах</param>
        /// <returns>модель стрелок</returns>
        private Solid3d BuildArrows(WatchData WatchData)
        {
            //стрелки
            Solid3d Arrows = new Solid3d();
            //база
            Solid3d Base = new Solid3d();

            //первая часть базы
            Base.CreateFrustum(_params[ParNames.BodyTransformByX] / 2, _params[ParNames.BodyTransformByZ], _params[ParNames.BodyTransformByZ], _params[ParNames.BodyTransformByZ]);
            Base.TransformBy(Matrix3d.Displacement(new Vector3d(0, 0, Height / 2 + _params[ParNames.BodyTransformByX] / 4)));
            Arrows.BooleanOperation(BooleanOperationType.BoolUnite, Base.Clone() as Solid3d);

            //вторая часть бызы
            Base.CreateFrustum(_params[ParNames.BodyTransformByX] / 2, _params[ParNames.BodyTransformByY], _params[ParNames.BodyTransformByY], _params[ParNames.BodyTransformByY]);
            Base.TransformBy(Matrix3d.Displacement(new Vector3d(0, 0, Height / 2 + _params[ParNames.BodyTransformByX] / 4 * 3)));
            Arrows.BooleanOperation(BooleanOperationType.BoolUnite, Base.Clone() as Solid3d);

            //часовая стрелка
            Solid3d Arrow = new Solid3d();

            Arrow.CreateBox(Diameter / 2, _params[ParNames.BodyTransformByY], _params[ParNames.BodyTransformByX] / 4);
            Arrow.TransformBy(Matrix3d.Displacement(new Vector3d(-(Diameter / 4), 0, Height / 2 + _params[ParNames.BodyTransformByX] / 4)));
            double TrueHour = System.DateTime.Now.Hour + ((double)System.DateTime.Now.Minute / 60);

            Arrow.TransformBy(Matrix3d.Rotation(-(Math.PI / 6 * TrueHour), new Vector3d(0, 0, 1), Point3d.Origin));
            Arrows.BooleanOperation(BooleanOperationType.BoolUnite, Arrow.Clone() as Solid3d);

            //минутная стрелка
            Arrow.CreateBox(Diameter / 2 + _params[ParNames.BodyTopTransformByY], _params[ParNames.BodyTransformByX] + _params[ParNames.BodyTransformByX] / 5, _params[ParNames.BodyTransformByX] / 5);
            Arrow.TransformBy(Matrix3d.Displacement(new Vector3d(-(Diameter / 4), 0, Height / 2 + _params[ParNames.BodyTransformByX] / 4 * 3)));
            Arrow.TransformBy(Matrix3d.Rotation(-(Math.PI / 30 * System.DateTime.Now.Minute), new Vector3d(0, 0, 1), Point3d.Origin));
            Arrows.BooleanOperation(BooleanOperationType.BoolUnite, Arrow.Clone() as Solid3d);
            //секундная стрелка
            Arrow.CreateBox(Diameter / 2 + _params[ParNames.BodyBottomHeight], _params[ParNames.BodyTransformByX] / 2, _params[ParNames.BodyTransformByX] / 5);
            Arrow.TransformBy(Matrix3d.Displacement(new Vector3d(-(Diameter / _params[ParNames.BodyTopTransformByX]), 0, Height / 2 + _params[ParNames.BodyTransformByX] + _params[ParNames.BodyTransformByX] / 10)));
            Arrow.TransformBy(Matrix3d.Rotation(-(Math.PI / 30 * System.DateTime.Now.Second), new Vector3d(0, 0, 1), Point3d.Origin));
            Arrows.BooleanOperation(BooleanOperationType.BoolUnite, Arrow.Clone() as Solid3d);

            return(Arrows);
        }
예제 #11
0
파일: Class2.cs 프로젝트: daqi5258/CKX2014
        public static void SolidJig()
        {
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;
            Database db = ed.Document.Database;

            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    JigPline          jig = new JigPline();
                    Point3dCollection pts;
                    PromptResult      res = jig.DragMe(out pts);
                    if (res.Status == PromptStatus.OK)
                    {
                        BlockTableRecord   btr   = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                        Polyline3d         pLine = new Polyline3d(Poly3dType.SimplePoly, pts, true);
                        DBObjectCollection dbObj = new DBObjectCollection();
                        dbObj.Add(pLine);
                        Region region = Region.CreateFromCurves(dbObj)[0] as Region;
                        btr.AppendEntity(region);
                        tr.AddNewlyCreatedDBObject(region, true);
                        Solid3d solid = new Solid3d();
                        btr.AppendEntity(solid);
                        tr.AddNewlyCreatedDBObject(solid, true);
                        JigSolid solJig = new JigSolid(solid, ed.CurrentUserCoordinateSystem, region, pts[0]);
                        btr.AppendEntity(pLine);
                        tr.AddNewlyCreatedDBObject(pLine, true);
                        res = ed.Drag(solJig);
                        switch (res.Status)
                        {
                        case PromptStatus.OK:

                            break;
                        }
                    }
                    tr.Commit();
                }
            }
            catch { }
        }
예제 #12
0
        public static void UpdateSolid3D(ObjectId objectId, dynamic xb)
        {
            Editor   ed      = acApp.DocumentManager.MdiActiveDocument.Editor;
            Document acDoc   = acApp.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;

            Point3d p1 = new Point3d(Convert.ToDouble(xb.x1), Convert.ToDouble(xb.y1), Convert.ToDouble(xb.z1));
            Point3d p2 = new Point3d(Convert.ToDouble(xb.x2), Convert.ToDouble(xb.y2), Convert.ToDouble(xb.z2));

            //acCurDb.TryGetObjectId();
            // Start a transaction
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                Solid3d acSol3DBox = (Solid3d)acTrans.GetObject(objectId, OpenMode.ForWrite);
                acSol3DBox.CreateBox(Math.Abs(p2.X - p1.X), Math.Abs(p2.Y - p1.Y), Math.Abs(p2.Z - p1.Z));
                Point3d center = new Point3d(p1.X + ((p2.X - p1.X) / 2), p1.Y + ((p2.Y - p1.Y) / 2), p1.Z + ((p2.Z - p1.Z) / 2));
                acSol3DBox.TransformBy(Matrix3d.Displacement(center.GetAsVector()));
                acSol3DBox.Draw();
                acTrans.Commit();
                ed.UpdateScreen();
            }
        }
예제 #13
0
 /// <summary>
 ///     TODO
 /// </summary>
 /// <param name="acSol"></param>
 public EntInfo(Solid3d acSol, Database acCurDb, Transaction acTrans)
 {
     ObjId           = acSol.ObjectId;
     Hndl            = acSol.Handle;
     EntLayer        = acSol.Layer;
     EntColor        = acSol.Color;
     EntMaterial     = acSol.Material;
     TxDirection     = TextureDirection.Unknown;
     RcName          = string.Empty;
     IsSweep         = false;
     IsMirror        = false;
     IsChild         = false;
     RcInfo          = string.Empty;
     RcQtyOf         = 0;
     RcQtyTotal      = 0;
     LayMatrix       = Matrix3d.Identity;
     AsymmetryVector = new Vector3d();
     NumberOfChanges = acSol.NumChanges;
     ParentHandle    = acSol.Handle;
     ChildHandles    = new List <Handle>();
     ReadEntity(acSol, acCurDb, acTrans);
 }
        public void AddSolidOrPath()
        {
            if (_tube != null || _path != null)
            {
                // We'll add the swept solid, if we have one, otherwise
                // we'll add the path

                Entity ent;

                if (_tube == null)
                {
                    ent   = _path;
                    _path = null;
                }
                else
                {
                    ent   = _tube;
                    _tube = null;
                }

                var btr =
                    (BlockTableRecord)_tr.GetObject(
                        _doc.Database.CurrentSpaceId,
                        OpenMode.ForWrite
                        );

                ent.ColorIndex = finalSolColor;

                btr.AppendEntity(ent);
                _tr.AddNewlyCreatedDBObject(ent, true);
            }

            Cleanup();

            _vertices.Clear();

            _sweepBroken = false;
        }
예제 #15
0
        public static bool IsStairPropertySetOnSolid(Solid3d sol)
        {
            bool result = false;

            using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
            {
                ObjectIdCollection setIds = PropertyDataServices.GetPropertySets(sol);
                if (setIds.Count > 0)
                {
                    foreach (ObjectId id in setIds)
                    {
                        PropertySet pset = (PropertySet)id.GetObject(OpenMode.ForRead);
                        if (pset.PropertySetDefinitionName == MyPlugin.psdName)
                        {
                            result = true;
                            break;
                        }
                    }
                }
                tr.Commit();
            }
            return(result);
        }
예제 #16
0
        public void cmdCreateBox()
        {
            var doc = AcApp.DocumentManager.MdiActiveDocument;
            var ed  = doc.Editor;
            var db  = doc.Database;

            using (var tr = db.TransactionManager.StartTransaction())
            {
                var bt  = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                var btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                var box = new Solid3d();
                box.CreateBox(100, 200, 300);

                var matrix = ed.CurrentUserCoordinateSystem;
                matrix = matrix * Matrix3d.Displacement(new Vector3d(111, 222, 333));
                box.TransformBy(matrix);

                btr.AppendEntity(box);
                tr.AddNewlyCreatedDBObject(box, true);

                tr.Commit();
            }
        }
예제 #17
0
        public static bool SetStairPropertiesToSolid(Solid3d sol, BaseStairObject bso)
        {
            bool result = false;

            if (!IsStairPropertySetOnSolid(sol))
            {
                AddStairPropertySetToSolid(sol);
            }

            using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
            {
                ObjectIdCollection setIds = PropertyDataServices.GetPropertySets(sol);
                if (setIds.Count > 0)
                {
                    foreach (ObjectId id in setIds)
                    {
                        PropertySet pset = (PropertySet)id.GetObject(OpenMode.ForWrite);
                        if (pset.PropertySetDefinitionName == MyPlugin.psdName && pset.IsWriteEnabled)
                        {
                            // Get the ObjectID of the property set definition by name
                            // Get the value of the property definition
                            pset.SetAt(pset.PropertyNameToId("name"), bso.Name);
                            pset.SetAt(pset.PropertyNameToId("_tread"), bso.Tread);
                            pset.SetAt(pset.PropertyNameToId("_riser"), bso.Riser);
                            pset.SetAt(pset.PropertyNameToId("_landing"), bso.Landing);
                            pset.SetAt(pset.PropertyNameToId("_width"), bso.Width);
                            pset.SetAt(pset.PropertyNameToId("_slope"), bso.Slope);
                            pset.SetAt(pset.PropertyNameToId("_steps"), bso.Steps);
                            result = true;
                            break;
                        }
                    }
                }
                tr.Commit();
            }
            return(result);
        }
예제 #18
0
        public void DrawAndSaveAs2(Product product, IWorkbookSet bookSet)
        {
            if (File.Exists(filePath))
            {
                throw new Exception("已经存在temp.dwg,请保证已经删除");
            }

            //TODO:Not here
            product.Parts.ForEach(it => it.CalculateLocationInfo(Point3d.Origin, 0));

            using (Database db = new Database())
                using (Transaction acTrans = db.TransactionManager.StartTransaction())
                {
                    BlockTable       bt  = (BlockTable)acTrans.GetObject(db.BlockTableId, OpenMode.ForRead);
                    BlockTableRecord btr = (BlockTableRecord)acTrans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                    foreach (var part in product.Parts)
                    {
                        Solid3d panel = new Solid3d();
                        panel.CreateBox(part.Length, part.Width, part.Thickness);

                        panel.TransformBy(Matrix3d.Rotation(part.XRotation * Math.PI / 180, Vector3d.XAxis, Point3d.Origin));
                        panel.TransformBy(Matrix3d.Rotation(part.YRotation * Math.PI / 180, Vector3d.YAxis, Point3d.Origin));
                        panel.TransformBy(Matrix3d.Rotation(part.ZRotation * Math.PI / 180, Vector3d.ZAxis, Point3d.Origin));

                        var moveVector = new Vector3d();
                        panel.TransformBy(Matrix3d.Displacement(part.CenterVector));

                        btr.AppendEntity(panel);
                        acTrans.AddNewlyCreatedDBObject(panel, true);
                    }

                    acTrans.Commit();

                    db.SaveAs(filePath, DwgVersion.Newest);
                }
        }
예제 #19
0
        /// <summary>
        /// 由中心点、圆环半径和圆管半径在UCS中创建圆环体
        /// </summary>
        /// <param name="cenPt">中心点</param>
        /// <param name="majorRadius">圆环半径</param>
        /// <param name="minorRadius">圆管半径</param>
        /// <returns>返回创建的圆环体的Id</returns>
        public static ObjectId AddTorus(Point3d cenPt, double majorRadius, double minorRadius)
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = Application.DocumentManager.MdiActiveDocument.Editor;

            if (Math.Abs(majorRadius) < 0.00001 || minorRadius < 0.00001)
            {
                ed.WriteMessage("\n参数不当,创建圆锥体失败!");
                return(ObjectId.Null);
            }

            try
            {
                // 创建
                Solid3d ent = new Solid3d();
                ent.RecordHistory = true;
                ent.CreateTorus(majorRadius, minorRadius);

                // 位置调整
                Matrix3d mt = ed.CurrentUserCoordinateSystem;
                mt = mt * Matrix3d.Displacement(cenPt - Point3d.Origin);
                ent.TransformBy(mt);

                ObjectId entId = ObjectId.Null;
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    entId = db.AddToModelSpace(ent);
                    tr.Commit();
                }
                return(entId);
            }
            catch
            {
                ed.WriteMessage("\n参数不当,创建圆锥体失败!");
                return(ObjectId.Null);
            }
        }
예제 #20
0
        public static BaseStairObject GetStairPropertiesFromSolid(Solid3d sol)
        {
            BaseStairObject retBso = null;

            using (Transaction tr = HostApplicationServices.WorkingDatabase.TransactionManager.StartTransaction())
            {
                ObjectIdCollection setIds = PropertyDataServices.GetPropertySets(sol);
                if (setIds.Count > 0)
                {
                    foreach (ObjectId id in setIds)
                    {
                        PropertySet pset = (PropertySet)id.GetObject(OpenMode.ForRead);

                        if (pset.PropertySetDefinitionName == MyPlugin.psdName)
                        {
                            // Get the ObjectID of the property set definition by name
                            // Get the value of the property definition
                            BaseStairObject bso = new BaseStairObject
                            {
                                Id      = sol.Id,
                                Name    = Convert.ToString(pset.GetAt(pset.PropertyNameToId("name"))),
                                Steps   = Convert.ToInt32(pset.GetAt(pset.PropertyNameToId("_steps"))),
                                Tread   = Convert.ToDouble(pset.GetAt(pset.PropertyNameToId("_tread"))),
                                Riser   = Convert.ToDouble(pset.GetAt(pset.PropertyNameToId("_riser"))),
                                Landing = Convert.ToDouble(pset.GetAt(pset.PropertyNameToId("_landing"))),
                                Width   = Convert.ToDouble(pset.GetAt(pset.PropertyNameToId("_width"))),
                                Slope   = Convert.ToDouble(pset.GetAt(pset.PropertyNameToId("_slope")))
                            };
                            retBso = bso;
                        }
                    }
                }
                tr.Commit();
            }
            return(retBso);
        }
        public void Cleanup()
        {
            if (_path != null)
            {
                _path.Dispose();
                _path = null;
            }
            ;
            if (_profile != null)
            {
                _profile.Dispose();
                _profile = null;
            }
            ;
            if (_tube != null)
            {
                _tube.Dispose();
                _tube = null;
            }
            ;

            _sweepOpts = null;
            _vertices.Clear();
        }
예제 #22
0
        /// <summary>
        ///     TODO
        /// </summary>
        /// <param name="acSol"></param>
        private void GetLayMatrix(Solid3d acSol)
        {
            try
            {
                var bestVerts = GetBestVerts(acSol);

                if (bestVerts == null)
                {
                    LayMatrix = GetAbstractMatrix(acSol);
                }
                else if (bestVerts.Count == 0)
                {
                    LayMatrix = new Matrix3d();
                }
                else
                {
                    LayMatrix = RefineLayMatrix(bestVerts);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
예제 #23
0
        public static Solid3d GetBoundingBox(this Transaction acTrans, ObjectId[] ids, Database acCurDb)
        {
            var extents = acTrans.GetExtents(ids, acCurDb);

            //Get geom extents of all selected
            var minX = extents.MinPoint.X;
            var maxX = extents.MaxPoint.X;
            var minY = extents.MinPoint.Y;
            var maxY = extents.MaxPoint.Y;
            var minZ = extents.MinPoint.Z;
            var maxZ = extents.MaxPoint.Z;

            var sol = new Solid3d();

            var width  = Math.Abs(maxX - minX);
            var length = Math.Abs(maxY - minY);
            var height = Math.Abs(maxZ - minZ);

            sol.CreateBox(width, length, height);
            sol.TransformBy(
                Matrix3d.Displacement(sol.GeometricExtents.MinPoint.GetVectorTo(new Point3d(minX, minY, minZ))));

            return(sol);
        }
예제 #24
0
        public KinectrotateCylinderJig(
            Document doc, Transaction tr, double profSide, double factor
            )
        {
            // Initialise the various members

            _doc             = doc;
            _tr              = tr;
            _vertices        = new Point3dCollection();
            _lastDrawnVertex = -1;
            _resizing        = false;
            _resizebool      = 0;
            _drawing         = false;
            leftHand         = new Point3d();
            rightHand        = new Point3d();
            leftHip          = new Point3d();
            _isRotate        = false;
            vRot             = new Vector3d();
            _changeaxis      = false;
            _firstdraw       = 0;
            ct         = 0;
            _created   = new DBObjectCollection();
            _profSide  = profSide;
            _segFactor = factor;

            cube = new Solid3d();
            cube.CreateFrustum(0.5, 0.5, 0.8, 0.5);

            Words.Add("red");
            Words.Add("green");
            Words.Add("blue");
            Words.Add("yellow");
            Words.Add("pink");
            Words.Add("magenta");
            Words.Add("cyan");
        }
예제 #25
0
파일: Findings.cs 프로젝트: sanjaysy/ORSAPR
        /// <summary>
        /// Функция отрисовки портов вывода
        /// </summary>
        /// <param name="database">База данныйх</param>
        /// <param name="Trans">Транцакция</param>
        /// <param name="parameters">Класс с параметрами построения мотора</param>
        /// <param name="positionPort">Позиция отверстия</param>
        /// <param name="Figure">Обьект класса</param>
        /// <param name="x">Позиция центра по координате Х</param>
        /// <param name="y">Позиция центра по координате Y</param>
        /// <param name="z">Позиция центра по координате Z</param>
        private void Ports(Database database, Transaction trans, MotorParameters parameters, int positionPort, Solid3d figure, double x, double y, double z)
        {
            // Открываем таблицу блоков для чтения
            BlockTable blockTable = trans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable;

            // Открываем таблицу блоков модели для записи
            BlockTableRecord blockTableRecord = trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

            // Создаем 3D обьект - прямоугольник
            Solid3d port = new Solid3d();

            port.SetDatabaseDefaults();
            port.CreateFrustum(_widthFindings * (parameters.CountPorts - positionPort), _diameretPorts / 2, _diameretPorts / 2, _diameretPorts / 2);
            port.ColorIndex = 4;

            // Перемещение и и поворот
            port.TransformBy(Matrix3d.Displacement(new Point3d(x, y, z) - Point3d.Origin));
            Vector3d vRotPort = new Point3d(0, 0, 0).GetVectorTo(new Point3d(0, 1, 0));

            port.TransformBy(Matrix3d.Rotation(Math.PI / 2, vRotPort, new Point3d(x, y, z)));
            blockTableRecord.AppendEntity(port);
            trans.AddNewlyCreatedDBObject(port, true);
            figure.BooleanOperation(BooleanOperationType.BoolSubtract, port);
        }
예제 #26
0
        /// <summary>
        ///     TODO
        /// </summary>
        /// <param name="acSol"></param>
        /// <returns></returns>
        private Matrix3d GetAbstractMatrix(Solid3d acSol)
        {
            var bestMatrix = new Matrix3d();

            using (var acBrep = acSol.GetBrep())
            {
                try
                {
                    if (acBrep.Faces.Any())
                    {
                        double largest = 0;

                        foreach (var acFace in acBrep.Faces)
                        {
                            var fArea = acFace.GetArea();

                            if (fArea.IsEqualArea(largest) || fArea < largest)
                            {
                                continue;
                            }

                            largest    = fArea;
                            bestMatrix = acFace.GetLayMatrix();
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    MailAgent.Report(e.Message);
                    return(bestMatrix);
                }
            }

            return(bestMatrix);
        }
예제 #27
0
        public KinectrotateCylinderJig(
          Document doc, Transaction tr, double profSide, double factor
        )
        {
            // Initialise the various members

            _doc = doc;
            _tr = tr;
            _vertices = new Point3dCollection();
            _lastDrawnVertex = -1;
            _resizing = false;
            _resizebool = 0;
            _drawing = false;
            leftHand = new Point3d();
            rightHand = new Point3d();
            leftHip = new Point3d();
            _isRotate = false;
            vRot = new Vector3d();
            _changeaxis = false;
            _firstdraw = 0;
            ct = 0;
            _created = new DBObjectCollection();
            _profSide = profSide;
            _segFactor = factor;

            cube = new Solid3d();
            cube.CreateFrustum(0.5, 0.5, 0.8,0.5);

            Words.Add("red");
            Words.Add("green");
            Words.Add("blue");
            Words.Add("yellow");
            Words.Add("pink");
            Words.Add("magenta");
            Words.Add("cyan");
        }
    protected override bool WorldDrawData(WorldDraw draw)
    {
      if (!base.WorldDrawData(draw))
        return false;

      TransientManager ctm =
        TransientManager.CurrentTransientManager;
      IntegerCollection ints = new IntegerCollection();

      // Draw any outstanding segments (and do so only once)

      bool wasCalibrating = _calibrating;

      while (_lineSegs.Count > 0)
      {
        // Get the line segment and remove it from the list

        LineSegment3d ls = _lineSegs[0];
        _lineSegs.RemoveAt(0);

        // Create an equivalent, red, database line
        // (or yellow, if calibrating)

        Line ln = new Line(ls.StartPoint, ls.EndPoint);
        ln.ColorIndex = (wasCalibrating ? 2 : 1);
        _lines.Add(ln);

        // Draw it as transient graphics

        ctm.AddTransient(
          ln, TransientDrawingMode.DirectShortTerm,
          128, ints
        );

        _calibrating = false;
      }

      if (_drawing)
      {
        if (_cursor == null)
        {
          if (_vertices.Count > 0)
          {
            // Clear our skeleton

            ClearTransients();

            _curPt = _vertices[_vertices.Count - 1];

            // Make our sphere 10cm in diameter (5cm radius)

            Solid3d sol = new Solid3d();
            sol.CreateSphere(0.05);
            _cursor = sol;
            _cursor.TransformBy(
              Matrix3d.Displacement(_curPt - Point3d.Origin)
            );

            _cursor.ColorIndex = 2;

            ctm.AddTransient(
              _cursor, TransientDrawingMode.DirectShortTerm,
              128, ints
            );
          }
        }
        else
        {
          if (_vertices.Count > 0)
          {
            Point3d newPt = _vertices[_vertices.Count - 1];
            _cursor.TransformBy(
              Matrix3d.Displacement(newPt - _curPt)
            );
            _curPt = newPt;

            ctm.UpdateTransient(_cursor, ints);
          }
        }
      }
      else // !_drawing
      {
        if (_cursor != null)
        {
          ctm.EraseTransient(_cursor, ints);
          _cursor.Dispose();
          _cursor = null;
        }
      }

      return true;
    }
예제 #29
0
        protected override bool WorldDrawData(WorldDraw draw)
        {
            if (!base.WorldDrawData(draw))
                return false;

            short origCol = draw.SubEntityTraits.Color;

            if (_resizing)
            {
                using (Solid3d cylinder = new Solid3d())
                {
                    try
                    {
                        cylinder.CreateFrustum(_profSide, _profSide, _profSide,_profSide);

                        if (cylinder != null)
                        {
                            cylinder.TransformBy(
                              Matrix3d.Displacement(
                                _resizeLocation - Point3d.Origin
                              )
                            );

                            // Draw the cursor

                            draw.SubEntityTraits.Color = ColorIndex;
                            cylinder.WorldDraw(draw);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _doc.Editor.WriteMessage(
                          "\nException: {0} - {1}", ex.Message, ex.InnerException
                        );
                    }
                    finally
                    {
                        draw.SubEntityTraits.Color = origCol;
                    }
                }
                return true;
            }

            // If we're currently drawing...

            if (_drawing)
            {
                Solid3d sol = null;
                try
                {
                    // If we have vertices that haven't yet been drawn...

                    if (_vertices.Count > 1 //&&
                        //_vertices.Count - 1 > _lastDrawnVertex
                      )
                    {
                        // ... generate a tube

                        if (GenerateTube(_profSide, _vertices, out sol))
                        {
                            // We now need to break the pipe...

                            // If it was created, add it to our list to draw

                            _created.Add(sol);
                            sol = null;

                            // Clear all but the last vertex to draw from
                            // next time

                            ClearAllButLast(_vertices, 1);
                        }
                    }
                }
                catch
                {
                    // If the tube generation failed...

                    if (sol != null)
                    {
                        sol.Dispose();
                    }

                    // Loop, creating the most recent successful tube we can

                    bool succeeded = false;
                    int n = 1;

                    do
                    {
                        try
                        {
                            // Generate the previous, working tube using all
                            // but the last points (if it fails, one more is
                            // excluded per iteration, until we get a working
                            // tube)

                            GenerateTube(
                              _profSide, GetAllButLast(_vertices, n++), out sol
                            );

                            _created.Add(sol);
                            sol = null;
                            succeeded = true;
                        }
                        catch { }
                    }
                    while (!succeeded && n < _vertices.Count);

                    if (succeeded)
                    {
                        ClearAllButLast(_vertices, n - 1);

                        if (_vertices.Count > 1)
                        {
                            try
                            {
                                // And generate a tube for the remaining vertices

                                GenerateTube(_profSide, _vertices, out sol);
                            }
                            catch
                            {
                                succeeded = false;
                            }
                        }
                    }

                    if (!succeeded && sol != null)
                    {
                        sol.Dispose();
                        sol = null;
                    }
                }

                // Draw our solid(s)

                draw.SubEntityTraits.Color = ColorIndex;

                foreach (DBObject obj in _created)
                {
                    Entity ent = obj as Entity;
                    if (ent != null)
                    {
                        try
                        {
                            ent.WorldDraw(draw);
                        }
                        catch
                        { }
                    }
                }

                if (sol != null)
                {
                    try
                    {
                        sol.WorldDraw(draw);
                    }
                    catch
                    { }
                }

                if (_vertices.Count > 0)
                {
                    Point3d lastPt = _vertices[_vertices.Count - 1];

                    // Create a cursor sphere

                    using (Solid3d cursor = new Solid3d())
                    {
                        try
                        {
                            cursor.CreateFrustum(_profSide, _profSide, _profSide, _profSide );

                            if (cursor != null)
                            {
                                cursor.TransformBy(
                                  Matrix3d.Displacement(lastPt - Point3d.Origin)
                                );

                                // Draw the cursor

                                draw.SubEntityTraits.Color = 5; //ColorIndex;

                                cursor.WorldDraw(draw);
                            }
                        }
                        catch { }
                    }
                }

                if (sol != null)
                {
                    sol.Dispose();
                }
            }

            draw.SubEntityTraits.Color = origCol;

            return true;
        }
    public void AddSolidOrPath()
    {
      if (_tube != null || _path != null)
      {
        // We'll add the swept solid, if we have one, otherwise
        // we'll add the path

        Entity ent;

        if (_tube == null)
        {
          ent = _path;
          _path = null;
        }
        else
        {
          ent = _tube;
          _tube = null;
        }

        BlockTableRecord btr =
          (BlockTableRecord)_tr.GetObject(
            _doc.Database.CurrentSpaceId,
            OpenMode.ForWrite
          );

        ent.ColorIndex = finalSolColor;

        btr.AppendEntity(ent);
        _tr.AddNewlyCreatedDBObject(ent, true);

      }

      Cleanup();

      _vertices.Clear();

      _sweepBroken = false;
    }
예제 #31
0
 /// <summary>
 /// 三维实体布尔运算
 /// </summary>
 /// <param name="solid1"></param>
 /// <param name="solid2"></param>
 /// <param name="type"></param>
 public static Solid3d BooleanOper(Solid3d solid1, Solid3d solid2, BooleanOperationType type)
 {
     solid1.BooleanOperation(type, solid2);
     return(solid1);
 }
예제 #32
0
        protected override bool WorldDrawData(WorldDraw draw)
        {
            if (!base.WorldDrawData(draw))
                return false;

            short origCol = draw.SubEntityTraits.Color;

            if (_resizing)
            {
                //  using (Solid3d cube = new Solid3d())
                //{
                try
                {


                    //cube.CreateBox(0.5, 0.5, 0.5);
                    _firstdraw = _firstdraw + 1;


                    if (cube != null)
                    {
                        //int i = 20000;
                        bool chk = false;
                        //cube.TransformBy(
                        //  Matrix3d.Displacement(
                        //     _resizeLocation - Point3d.Origin
                        //  )
                        //  );

                        // Draw the cursor

                        draw.SubEntityTraits.Color = ColorIndex;
                        cube.WorldDraw(draw);
                        vRot = leftHand.GetVectorTo(rightHand); ;// new Point3d(-3, 4, 0).GetVectorTo(new Point3d(-3, -4, 0)); //rightHand.GetVectorTo(leftHand);

                        System.Threading.Thread.Sleep((int)System.TimeSpan.FromSeconds(0.2).TotalMilliseconds);

                        //chk = (leftHand.Z < leftHip.Z);

                        //while (true)
                        //{
                        //  if (chk)
                        //    break;
                        //Point3d pt1 = rightHand - leftHand;
                        cube.TransformBy(Matrix3d.Rotation(0.1, vRot, Point3d.Origin));
                        //}

                        /*if (chk)
                        {
                            cube.TransformBy(Matrix3d.Rotation(1.046, vRot, leftHand));
                            System.Threading.Thread.Sleep((int)System.TimeSpan.FromSeconds(2).TotalMilliseconds);
                        }  */

                        //cube.TransformBy(Matrix3d.Rotation(0.5236, vRot, leftHand));
                    }

                    // if(_changeaxis)

                    //            vRot = rightHand.GetVectorTo(leftHand);
                    //          cube.TransformBy(Matrix3d.Rotation(0.5236,vRot,leftHand));

                    //   if (leftHand.Z > leftHip.Z)
                    //     _isRotate = false;

                }
                catch (System.Exception ex)
                {

                    _doc.Editor.WriteMessage(
                      "\nException: {0} - {1}", ex.Message, ex.InnerException
                    );
                }
                finally
                {
                    draw.SubEntityTraits.Color = origCol;
                }
                // }
                return true;
            }

            if (_isRotate)
            {
                cube.WorldDraw(draw);
            }

            // If we're currently drawing...

            if (_drawing)
            {
                Solid3d sol = null;
                try
                {
                    // If we have vertices that haven't yet been drawn...

                    if (_vertices.Count > 1 //&&
                        //_vertices.Count - 1 > _lastDrawnVertex
                      )
                    {
                        // ... generate a tube

                        if (GenerateTube(_profSide, _vertices, out sol))
                        {
                            // We now need to break the pipe...

                            // If it was created, add it to our list to draw

                            _created.Add(sol);
                            sol = null;

                            // Clear all but the last vertex to draw from
                            // next time

                            ClearAllButLast(_vertices, 1);
                        }
                    }
                }
                catch
                {
                    // If the tube generation failed...

                    if (sol != null)
                    {
                        sol.Dispose();
                    }

                    // Loop, creating the most recent successful tube we can

                    bool succeeded = false;
                    int n = 1;

                    do
                    {
                        try
                        {
                            // Generate the previous, working tube using all
                            // but the last points (if it fails, one more is
                            // excluded per iteration, until we get a working
                            // tube)

                            GenerateTube(
                              _profSide, GetAllButLast(_vertices, n++), out sol
                            );

                            _created.Add(sol);
                            sol = null;
                            succeeded = true;
                        }
                        catch { }
                    }
                    while (!succeeded && n < _vertices.Count);

                    if (succeeded)
                    {
                        ClearAllButLast(_vertices, n - 1);

                        if (_vertices.Count > 1)
                        {
                            try
                            {
                                // And generate a tube for the remaining vertices

                                GenerateTube(_profSide, _vertices, out sol);
                            }
                            catch
                            {
                                succeeded = false;
                            }
                        }
                    }

                    if (!succeeded && sol != null)
                    {
                        sol.Dispose();
                        sol = null;
                    }
                }

                // Draw our solid(s)

                draw.SubEntityTraits.Color = ColorIndex;

                foreach (DBObject obj in _created)
                {
                    Entity ent = obj as Entity;
                    if (ent != null)
                    {
                        try
                        {
                            ent.WorldDraw(draw);
                        }
                        catch
                        { }
                    }
                }

                if (sol != null)
                {
                    try
                    {
                        sol.WorldDraw(draw);
                    }
                    catch
                    { }
                }

                if (_vertices.Count > 0)
                {
                    Point3d lastPt = _vertices[_vertices.Count - 1];

                    // Create a cursor sphere

                    using (Solid3d cursor = new Solid3d())
                    {
                        try
                        {
                            cursor.CreateBox(_profSide, _profSide, _profSide);

                            if (cursor != null)
                            {
                                cursor.TransformBy(
                                  Matrix3d.Displacement(lastPt - Point3d.Origin)
                                );

                                // Draw the cursor

                                draw.SubEntityTraits.Color = 4; // ColorIndex;

                                cursor.WorldDraw(draw);
                            }
                        }
                        catch { }
                    }
                }

                if (sol != null)
                {
                    sol.Dispose();
                }
            }

            draw.SubEntityTraits.Color = origCol;

            return true;
        }
예제 #33
0
        /// <summary>
        ///     TODO
        /// </summary>
        /// <param name="acSol"></param>
        /// <returns></returns>
        private List <VertExt> GetBestVerts(Solid3d acSol)
        {
            var vList = new List <VertExt>();

            using (var acBrep = new Brep(acSol))
            {
                if (acBrep.IsNull)
                {
                    return(vList);
                }

                if (!acBrep.IsNull)
                {
                    var y = 0.0;

                    try
                    {
                        foreach (var face in acBrep.Faces)
                        {
                            FaceCount++;
                            var fArea = 0.0;

                            if (SubId.Type == SubentityType.Face && SubId == face.SubentityPath.SubentId)
                            {
                                fArea        = face.GetArea();
                                SubArea      = fArea.RoundArea();
                                SubPerimeter = face.GetPerimeterLength().RoundToTolerance();
                            }

                            using (var surface = face.Surface as ExternalBoundedSurface)
                            {
                                if (!surface.IsPlane)
                                {
                                    if (!surface.IsCylinder)
                                    {
                                        Has3DFaces = true;
                                    }
                                    HasNonFlatFaces = true;
                                    continue;
                                }
                            }

                            if (fArea == 0.0)
                            {
                                fArea = face.GetArea();
                            }

                            var x = fArea;

                            try
                            {
                                foreach (var acLoop in face.Loops)
                                {
                                    var lType = acLoop.GetLoopType();

                                    if (lType == LoopKit.Interior)
                                    {
                                        HasHoles = true;
                                        continue;
                                    }

                                    if (lType != LoopKit.Error)
                                    {
                                        if (lType == LoopKit.RightAngle)
                                        {
                                            x *= 1.5;
                                        }

                                        if (!x.IsEqualArea(y))
                                        {
                                            if (x < y)
                                            {
                                                continue;
                                            }

                                            vList.Clear();
                                            y            = x;
                                            MaxArea      = x.RoundArea();
                                            MaxPerimeter = face.GetPerimeterLength().RoundToTolerance();
                                        }

                                        try
                                        {
                                            foreach (var vtx in acLoop.Vertices)
                                            {
                                                vList.Add(new VertExt(vtx, acLoop));
                                                if (vList.Count > 1000)
                                                {
                                                    break;
                                                }
                                            }
                                        }
                                        catch (Exception e)
                                        {
                                            Console.WriteLine(e);
                                            MailAgent.Report(e.Message);
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e);
                                MailAgent.Report(e.Message);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        MailAgent.Report(e.Message);
                    }
                }
                else
                {
                    if (SubId.Type == SubentityType.Edge)
                    {
                        try
                        {
                            foreach (var acEdge in acBrep.Edges)
                            {
                                var subentityPath = acEdge.SubentityPath;
                                if (subentityPath.SubentId == SubId)
                                {
                                    SubPerimeter = acEdge.GetLength().RoundToTolerance();
                                    break;
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                            MailAgent.Report(e.Message);
                        }
                    }
                }

                return(MaxArea != 0.0 ? vList : null);
            }
        }
예제 #34
0
        /// <summary>
        ///     TODO
        /// </summary>
        /// <param name="acSol"></param>
        private void ReadEntity(Solid3d acSol, Database acCurDb, Transaction acTrans)
        {
            RcName       = acSol.GetPartName();
            ParentHandle = acSol.GetParent();
            ChildHandles = acSol.GetChildren();
            IsSweep      = acSol.GetIsSweep();
            IsMirror     = acSol.GetIsMirror();
            RcInfo       = acSol.GetPartInfo();
            RcQtyOf      = acSol.GetQtyOf();
            RcQtyTotal   = acSol.GetQtyTotal();
            TxDirection  = acSol.GetTextureDirection();

            GetRotationMatrices(acSol);
            GetLayMatrix(acSol);

            if (LayMatrix == new Matrix3d())
            {
                LayMatrix = GetAbstractMatrix(acSol);
            }

            using (var solCopy = acSol.Clone() as Solid3d)
            {
                if (solCopy != null)
                {
                    if (LayMatrix != Matrix3d.Identity)
                    {
                        solCopy.TransformBy(LayMatrix);
                    }

                    //Get Volume & Extents
                    Extents  = solCopy.GetBounds();
                    MinExt   = Extents.MinPoint;
                    MaxExt   = Extents.MaxPoint;
                    Centroid = solCopy.MassProperties.Centroid;
                    Box      = Extents.Volume();
                    Volume   = acSol.Volume();
                }
            }

            var identity = Matrix3d.Identity;

            if ((MaxExt.Z + MinExt.Z) / 2 < 0)
            {
                var vector3D = new Vector3d(0, 1, 0);
                identity   = Matrix3d.Rotation(3.14159265358979, vector3D, new Point3d());
                LayMatrix *= identity;
            }

            if (IsBox)
            {
                Asymmetry = 0;
            }
            else
            {
                var boxCen = GetBoxCenter(MinExt, MaxExt).RoundToTolerance();

                AsymmetryVector = boxCen.GetVectorTo(Centroid.RoundToTolerance());
                AsymmetryVector = AsymmetryVector.TransformBy(identity);
                Asymmetry       = AsymmetryVector.Length;

                if (!Asymmetry.IsLessThanTol())
                {
                    Asymmetry = Asymmetry.RoundToTolerance();
                }
                else
                {
                    Asymmetry = 0;
                }

                AsymmetryVector = AsymmetryVector.RoundToTolerance();

                if (Asymmetry > 0)
                {
                    FixMatrix(boxCen);
                }

                AsymString = AsymVStr(AsymmetryVector);
            }

            //Get length, width, thickness

            if (IsSweep)
            {
                //TODO
            }
            else
            {
                var measures = new List <double>(3)
                {
                    MaxExt.X - MinExt.X,
                    MaxExt.Y - MinExt.Y,
                    MaxExt.Z - MinExt.Z
                };

                measures.Sort();

                if (TxDirection == TextureDirection.Across)
                {
                    Width  = measures[2].RoundToTolerance();
                    Length = measures[1].RoundToTolerance();
                }
                else
                {
                    Length = measures[2].RoundToTolerance();
                    Width  = measures[1].RoundToTolerance();
                }

                Thickness = measures[0].RoundToTolerance();
            }

            //Add the XData
            acSol.AddXData(this, acCurDb, acTrans);
        }
    protected override bool WorldDrawData(WorldDraw draw)
    {
      if (!base.WorldDrawData(draw))
        return false;

      short origCol = draw.SubEntityTraits.Color;

      // If we're currently drawing...

      if (_drawing)
      {
        try
        {
          // Let's start by creating our spline path

          if ((_path == null && _vertices.Count > 1) ||
              (_path != null &&
                _vertices.Count > _path.NumFitPoints))
          {
            if (_path != null)
              _path.Dispose();

            _path = new Spline(_vertices, 0, 0.0);

            // And our sweep profile, if we don't have one

            if (_profile != null)
              _profile.Dispose();

            _profile =
              new Circle(
                _vertices[0],
                _vertices[1] - _vertices[0],
                _profRad
              );

            // And our sweep options, if we don't have one

            if (_sweepOpts == null)
            {
              SweepOptionsBuilder sob =
                new SweepOptionsBuilder();

              // Align the entity to sweep to the path

              sob.Align =
                SweepOptionsAlignOption.AlignSweepEntityToPath;

              // The base point is the start of the path

              sob.BasePoint = _path.StartPoint;

              // The profile will rotate to follow the path

              sob.Bank = true;
              _sweepOpts = sob.ToSweepOptions();
            }

            // Finally create a blank solid, if it's null

            if (_tube == null)
              _tube = new Solid3d();

            // And sweep our profile along our path

            _tube.CreateSweptSolid(_profile, _path, _sweepOpts);
          }
        }
        catch (Autodesk.AutoCAD.Runtime.Exception ex)
        {
          _sweepBroken = true;
          _tube.Dispose();
          _tube = null;
          _doc.Editor.WriteMessage(
            "\nException: {0}", ex.Message
          );
        }

        // Draw our path, if we have one

        if (_path != null)
        {
          draw.SubEntityTraits.Color = transPathColor;
          _path.WorldDraw(draw);
        }

        // And our solid

        if (_tube != null)
        {
          draw.SubEntityTraits.Color = transSolColor;
          _tube.WorldDraw(draw);
        }

        if (_vertices.Count > 0)
        {
          // Get the last point (at which our cursor should
          // be located, if it exists)

          Point3d lastPt = _vertices[_vertices.Count - 1];

          if (_cursor == null)
          {
            // Create a cursor sphere

            _cursor = new Solid3d();
            ((Solid3d)_cursor).CreateSphere(_profRad);
            _curPt = Point3d.Origin;
          }

          // Move it to the current point

          _cursor.TransformBy(
            Matrix3d.Displacement(lastPt - _curPt)
          );
          _curPt = lastPt;

          // Draw the cursor

          draw.SubEntityTraits.Color =
            (_sweepBroken ? transPathColor : transSolColor);

          _cursor.WorldDraw(draw);
        }
      }

      draw.SubEntityTraits.Color = origCol;

      return true;
    }
예제 #36
0
        // draw the 3-D drawing
        // nFlag: dimension control
        private void DrawSolidProfile(Plate pl, Point3d p0, int nFlag)
        {
            // Create Container for the curve, the region (face)
            DBObjectCollection curves = new DBObjectCollection();
            // - Collection for the regions
            DBObjectCollection regions = new DBObjectCollection();

            // Solid3d objects
            Solid3d plateSolid = new Solid3d();
            Solid3d rectHole   = new Solid3d();            // Rectangular Hole in the Center

            Point3d[] pt = new Point3d[26];                // geometry helpers
            Line[]    ln = new Line[26];                   // database objects

            // create points
            pt[0]  = p0;
            pt[1]  = new Point3d(p0.X + (pl.dW - pl.R1), p0.Y, p0.Z);
            pt[2]  = new Point3d(p0.X + pl.dW, pl.R1, p0.Z);
            pt[3]  = new Point3d(pt[1].X, pt[2].Y, p0.Z);
            pt[4]  = new Point3d(pt[3].X, pt[3].Y + pl.L9, p0.Z);
            pt[5]  = new Point3d(pt[4].X + pl.L2, pt[4].Y + pl.L8, p0.Z);
            pt[6]  = new Point3d(pt[5].X, pt[5].Y + pl.L7, p0.Z);
            pt[7]  = new Point3d(pt[4].X, pt[6].Y + pl.L6, p0.Z);
            pt[8]  = new Point3d(pt[7].X, pt[7].Y + pl.L5, p0.Z);
            pt[9]  = new Point3d(p0.X + pl.L3, pt[8].Y + pl.L4, p0.Z);
            pt[10] = new Point3d(p0.X, pt[9].Y, p0.Z);

            // symmetry - create points on negative x-axis
            int k = 9;

            for (int i = 11; i < 20; i++)
            {
                pt[i] = new Point3d(-pt[k].X, pt[k].Y, pt[k].Z);
                k--;
            }

            // create lines and store them into the database
            for (int i = 0; i < 20; i++)
            {
                if (i != 1 & i != 18)
                {
                    ln[i]            = new Line(pt[i], pt[(i + 1)]);
                    ln[i].ColorIndex = pl.nColor[CONTOUR];      // 0:index
                    curves.Add(ln[i]);
                }
                else if (i == 1)
                {
                    double st_angle0  = 270 * (Math.PI / 180);
                    double end_angle0 = 0;

                    Arc a0 = new Arc(pt[3], pl.R1, st_angle0, end_angle0);
                    a0.ColorIndex = pl.nColor[CONTOUR];      // 0:index
                    curves.Add(a0);
                }
                else if (i == 18)
                {
                    double st_angle1  = 180 * (Math.PI / 180);
                    double end_angle1 = 270 * (Math.PI / 180);

                    Arc a1 = new Arc(pt[17], pl.R1, st_angle1, end_angle1);
                    a1.ColorIndex = pl.nColor[CONTOUR];      // 0:index
                    curves.Add(a1);
                }
                else
                {
                    continue;
                }
            }

            // Create the Region from the curves
            regions = Region.CreateFromCurves(curves);
            plateSolid.ColorIndex = pl.nColor[CONTOUR];

            // Create the plate without the hole
            plateSolid.Extrude((Region)regions[0], pl.dT, 0.0);

            // draw points for centre hole
            curves.Clear();

            pt[20] = new Point3d(p0.X + pl.R2, pt[3].Y + pl.R2, 0.0);
            pt[21] = new Point3d(pt[20].X, pt[7].Y - pl.R2, 0.0);
            pt[22] = new Point3d(-pt[20].X, pt[7].Y - pl.R2, 0.0);
            pt[23] = new Point3d(-(p0.X + pl.R2), pt[3].Y + pl.R2, 0.0);
            pt[24] = new Point3d(p0.X, pt[20].Y, 0.0);
            pt[25] = new Point3d(p0.X, pt[21].Y, 0.0);

            // draw lines for centre hole
            for (int i = 20; i < 24; i++)
            {
                if (i != 21 & i != 23)
                {
                    ln[i]            = new Line(pt[i], pt[(i + 1)]);
                    ln[i].ColorIndex = pl.nColor[CONTOUR];      // 0:index
                    curves.Add(ln[i]);
                }
                else if (i == 21)
                {
                    double st_angle2  = 0;
                    double end_angle2 = 180 * (Math.PI / 180);

                    Arc a2 = new Arc(pt[25], pl.R2, st_angle2, end_angle2);
                    a2.ColorIndex = pl.nColor[CONTOUR];      // 0:index
                    curves.Add(a2);
                }
                else if (i == 23)
                {
                    double st_angle3  = 180 * (Math.PI / 180);
                    double end_angle3 = 0;

                    Arc a3 = new Arc(pt[24], pl.R2, st_angle3, end_angle3);
                    a3.ColorIndex = pl.nColor[CONTOUR];      // 0:index
                    curves.Add(a3);
                }
                else
                {
                    continue;
                }
            }

            // Create the Region from the curves (Rectangular Hole)
            regions = Region.CreateFromCurves(curves);
            rectHole.Extrude((Region)regions[0], pl.dT, 0.0);
            rectHole.ColorIndex = pl.nColor[HIDDEN];

            // Substract the Hole Solid from the Rectangle
            plateSolid.BooleanOperation(BooleanOperationType.BoolSubtract, rectHole);

            // Add Solids into the Database
            AcTrans.Add(plateSolid);
        }
        public static ObjectId CreateExtrusion(Point2d[] pts, Point3d destPt, Vector3d normal, WoodGrainAlignment grain)
        {
            ObjectId entId = ObjectId.Null;

            Document activeDoc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database db = activeDoc.Database;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

                BlockTableRecord btr = null;
                if (String.IsNullOrEmpty(blockName))
                    btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;
                else
                {
                    if (bt.Has(blockName))
                        btr = tr.GetObject(bt[blockName], OpenMode.ForWrite) as BlockTableRecord;
                    else
                    {
                        btr = new BlockTableRecord();
                        btr.Name = blockName;
                        bt.UpgradeOpen();
                        bt.Add(btr);
                        tr.AddNewlyCreatedDBObject(btr, true);
                    }
                }

                Solid3d extrudedSolid = new Solid3d();
                using (Autodesk.AutoCAD.DatabaseServices.Polyline outline = new Autodesk.AutoCAD.DatabaseServices.Polyline())
                {
                    outline.SetDatabaseDefaults();
                    outline.Normal = normal;

                    int cnt = 0;
                    foreach (Point2d pt in pts)
                    {
                        outline.AddVertexAt(cnt, pt, 0, 0, 0);
                        cnt++;
                    }
                    outline.Closed = true;

                    Extents3d exts = outline.GeometricExtents;
                    Point3d minPt = exts.MinPoint;
                    Point3d maxPt = exts.MaxPoint;

                    double p1 = maxPt.X - minPt.X;
                    double p2 = maxPt.Y - minPt.Y;
                    double p3 = maxPt.Z - minPt.Z;

                    double pmin = 0.0;
                    if (p1 == 0)
                    {
                        pmin = Math.Min(p2, p3);
                    }
                    if (p2 == 0)
                    {
                        pmin = Math.Min(p1, p3);
                    }
                    if (p3 == 0)
                    {
                        pmin = Math.Min(p1, p2);
                    }
                    double pmax = Math.Max(Math.Max(p1, p2), p3);

                    extrudedSolid.RecordHistory = true;

                    plyIndex++;

                    Vector3d heightVector = outline.Normal * t;

                    SweepOptions sweepOptions = new SweepOptions();

                    SweepOptionsBuilder builder = new SweepOptionsBuilder(sweepOptions);

                    extrudedSolid.CreateExtrudedSolid(outline, heightVector, sweepOptions);
                }

                entId = btr.AppendEntity(extrudedSolid);
                tr.AddNewlyCreatedDBObject(extrudedSolid, true);

                extrudedSolid.TransformBy(Matrix3d.Displacement(destPt.GetAsVector()));

                tr.Commit();
            }

            return entId;
        }
예제 #38
0
파일: Findings.cs 프로젝트: sanjaysy/ORSAPR
        /// <summary>
        /// Функция построения коробки выводов
        /// </summary>
        /// <param name="database">База данный объектов </param>
        /// <param name="Trans">Транзакции</param>
        /// <param name="parameters">Класс с параметрами построения мотора</param>
        public void Build(Database database, Transaction trans, MotorParameters parameters)
        {
            int widthFindings  = _widthFindings;
            int lenFindings    = _lenFindings;
            int heightFindings = _heightFindings;

            int countPorts    = _countPorts;
            int diameretPorts = _diameretPorts;

            int lenBox      = parameters.LenBox;
            int diameretBox = parameters.DiameretBox;

            // Коэффициенты трансформации
            double transformationFactorLen    = 1.2;
            double transformationFactorHeight = 0.1;

            // Открываем таблицу блоков для чтения
            BlockTable blockTable = trans.GetObject(database.BlockTableId, OpenMode.ForRead) as BlockTable;

            // Открываем таблицу блоков модели для записи
            BlockTableRecord blockTableRecord = trans.GetObject(blockTable[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

            // Создаем 3D обьект - прямоугольник
            Solid3d findings = new Solid3d();

            findings.SetDatabaseDefaults();
            findings.CreateBox(widthFindings, lenFindings, heightFindings);
            findings.ColorIndex = 7;

            // Задаем позицию центра 3D обьекта
            findings.TransformBy(Matrix3d.Displacement(new Point3d(0, -lenBox / 2 + transformationFactorLen * lenFindings / 2, diameretBox / 2 + heightFindings / 2 - transformationFactorHeight * heightFindings) - Point3d.Origin));

            // Добавляем новый обьект в таблицу блоков и отправляем на транзакцию
            blockTableRecord.AppendEntity(findings);
            trans.AddNewlyCreatedDBObject(findings, true);

            // Параметры
            double cavityWidth  = widthFindings * 0.8;
            double cavityLen    = lenFindings * 0.9;
            double cavityHeight = heightFindings * 0.8;

            // Создать новую фигуру
            Solid3d cavity = new Solid3d();

            cavity.SetDatabaseDefaults();
            cavity.CreateBox(cavityWidth, cavityLen, cavityHeight);
            cavity.TransformBy(Matrix3d.Displacement(new Point3d(0, -lenBox / 2 + transformationFactorLen * lenFindings / 2, diameretBox / 2 + heightFindings / 2 - transformationFactorHeight * heightFindings) - Point3d.Origin));

            // Добавляем новый обьект в таблицу блоков и отправляем на транзакцию
            blockTableRecord.AppendEntity(cavity);
            trans.AddNewlyCreatedDBObject(cavity, true);

            findings.BooleanOperation(BooleanOperationType.BoolSubtract, cavity);


            double coordZ = diameretBox / 2 + heightFindings / 2 - transformationFactorHeight * heightFindings;
            double coordX = widthFindings / 3;


            if (countPorts >= 1)
            {
                double y1 = -lenBox / 2 + (transformationFactorLen * lenFindings / 2 + lenFindings / 3);
                Ports(database, trans, parameters, 0, findings, coordX, y1, coordZ);
            }
            if (countPorts > 2)
            {
                double y2 = -lenBox / 2 + (transformationFactorLen * lenFindings / 2);
                Ports(database, trans, parameters, 2, findings, coordX, y2, coordZ);
            }
            if (countPorts > 4)
            {
                double y3 = -lenBox / 2 + (transformationFactorLen * lenFindings / 2 - lenFindings / 3);
                Ports(database, trans, parameters, 4, findings, -coordX, y3, coordZ);
            }
        }
        public static void CreateHandleBlock()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = null;

                if (bt.Has("Handle"))
                    btr = tr.GetObject(bt["Handle"], OpenMode.ForWrite) as BlockTableRecord;
                else
                {
                    btr = new BlockTableRecord();
                    btr.Name = "Handle";
                    bt.UpgradeOpen();
                    bt.Add(btr);
                    tr.AddNewlyCreatedDBObject(btr, true);
                }

                using (Autodesk.AutoCAD.DatabaseServices.Polyline outline = new Autodesk.AutoCAD.DatabaseServices.Polyline())
                {
                    outline.SetDatabaseDefaults();
                    outline.Normal = Vector3d.XAxis;

                    outline.AddVertexAt(0, new Point2d(0.0, 0.0), 0, 0, 0);
                    outline.AddVertexAt(1, new Point2d(0.0, 0.5 * t), 0, 0, 0);
                    outline.AddVertexAt(2, new Point2d(-t, 0.5 * t), 0, 0, 0);
                    outline.AddVertexAt(3, new Point2d(-t, 0.75 * t), 0, 0, 0);
                    outline.AddVertexAt(4, new Point2d(-1.25 * t, t), 0, 0, 0);
                    outline.AddVertexAt(5, new Point2d(-1.75 * t, t), 0, 0, 0);
                    outline.AddVertexAt(6, new Point2d(-2.0 * t, 0.75 * t), 0, 0, 0);
                    outline.AddVertexAt(7, new Point2d(-2.0 * t, 0.0), 0, 0, 0);
                    outline.Closed = true;

                    RevolveOptions opts = new RevolveOptions();
                    RevolveOptionsBuilder rob = new RevolveOptionsBuilder(opts);
                    rob.CloseToAxis = true;
                    rob.DraftAngle = 0;
                    rob.TwistAngle = 0;

                    Solid3d handle = new Solid3d(); ;
                    handle.CreateRevolvedSolid(outline, new Point3d(0, 0, 0), Vector3d.YAxis, 2.0 * Math.PI, 0, rob.ToRevolveOptions());
                    handle.ColorIndex = 0;

                    btr.AppendEntity(handle);
                    tr.AddNewlyCreatedDBObject(handle, true);

                    tr.Commit();
                }
            }
        }
예제 #40
0
        public void PickFace()
        {
            try
            {
                Document doc = Application.DocumentManager.MdiActiveDocument;
                Database db  = doc.Database;
                Editor   ed  = doc.Editor;

                Utils.Init();
                Utils.ChangeViewStyle("Hidden");

                while (true)
                {
                    //ClearDrawnGraphics();
                    PromptEntityOptions peo = new PromptEntityOptions("\nSelect face of solid:");
                    peo.SetRejectMessage("\nMust be a 3D solid.");
                    peo.AddAllowedClass(typeof(Solid3d), false);
                    PromptEntityResult per = ed.GetEntity(peo);
                    if (per.Status != PromptStatus.OK || per.Status == PromptStatus.Cancel)
                    {
                        Utils.End();
                        break;
                    }

                    Transaction tr = db.TransactionManager.StartTransaction();
                    using (tr)
                    {
                        Solid3d sol = tr.GetObject(per.ObjectId, OpenMode.ForRead) as Solid3d;
                        if (sol != null)
                        {
                            Brep brp = new Brep(sol);
                            using (brp)
                            {
                                // We're going to check interference between our
                                // solid and a line we're creating between the
                                // picked point and the user (we use the view
                                // direction to decide in which direction to
                                // draw the line)

                                Point3d dir = (Point3d)Application.GetSystemVariable("VIEWDIR");
                                Point3d picked = per.PickedPoint, nearerUser = per.PickedPoint - (dir - Point3d.Origin);

                                // Two hits should be enough (in and out)
                                const int numHits = 1;

                                // Create out line
                                Line3d ln   = new Line3d(picked, nearerUser);
                                Hit[]  hits = brp.GetLineContainment(ln, numHits);
                                ln.Dispose();

                                if (hits == null || hits.Length < numHits)
                                {
                                    Utils.End();
                                    return;
                                }

                                // Set the shortest distance to something large
                                // and the index to the first item in the list
                                double shortest = (picked - nearerUser).Length;
                                int    found    = 0;

                                // Loop through and check the distance to the
                                // user (the depth of field).
                                for (int idx = 0; idx < numHits; idx++)
                                {
                                    Hit    hit  = hits[idx];
                                    double dist = (hit.Point - nearerUser).Length;
                                    if (dist < shortest)
                                    {
                                        shortest = dist;
                                        found    = idx;
                                    }
                                }

                                // Once we have the nearest point to the screen,
                                // use that one to get the containing curves
                                //List<Curve3d> curves = new List<Curve3d>();
                                List <Point3d> faceBoundary = new List <Point3d>();

                                if (CheckContainment(ed, brp, hits[found].Point, ref faceBoundary))
                                {
                                    Utils.SetLayer("!FDS_MESH[open]");


                                    //Utils.CreateSurfaceinDB(faceBoundary[0], faceBoundary[1], faceBoundary[0].X, "X");
                                    if (faceBoundary[0].X == faceBoundary[1].X)
                                    {
                                        if (faceBoundary[0].X == sol.GeometricExtents.MinPoint.X)
                                        {
                                            Utils.CreateBox(faceBoundary[0], new Point3d(faceBoundary[1].X - 0.01, faceBoundary[1].Y, faceBoundary[1].Z));
                                        }
                                        else if (faceBoundary[0].X == sol.GeometricExtents.MaxPoint.X)
                                        {
                                            Utils.CreateBox(faceBoundary[0], new Point3d(faceBoundary[1].X + 0.01, faceBoundary[1].Y, faceBoundary[1].Z));
                                        }
                                    }
                                    //Utils.CreateSurfaceinDB(faceBoundary[0], faceBoundary[1], faceBoundary[0].Y, "Y");
                                    else if (faceBoundary[0].Y == faceBoundary[1].Y)
                                    {
                                        if (faceBoundary[0].Y == sol.GeometricExtents.MinPoint.Y)
                                        {
                                            Utils.CreateBox(faceBoundary[0], new Point3d(faceBoundary[1].X, faceBoundary[1].Y - 0.01, faceBoundary[1].Z));
                                        }
                                        else if (faceBoundary[0].Y == sol.GeometricExtents.MaxPoint.Y)
                                        {
                                            Utils.CreateBox(faceBoundary[0], new Point3d(faceBoundary[1].X, faceBoundary[1].Y + 0.01, faceBoundary[1].Z));
                                        }
                                    }
                                    if (faceBoundary[0].Z == faceBoundary[1].Z)
                                    {
                                        if (faceBoundary[0].Z == sol.GeometricExtents.MinPoint.Z)
                                        {
                                            Utils.CreateBox(faceBoundary[0], new Point3d(faceBoundary[1].X, faceBoundary[1].Y, faceBoundary[1].Z - 0.01));
                                        }
                                        else if (faceBoundary[0].Z == sol.GeometricExtents.MaxPoint.Z)
                                        {
                                            Utils.CreateBox(faceBoundary[0], new Point3d(faceBoundary[1].X, faceBoundary[1].Y, faceBoundary[1].Z + 0.01));
                                        }
                                    }
                                    //    Utils.CreateSurfaceinDB(faceBoundary[0], faceBoundary[1], faceBoundary[0].Z, "Z");
                                    // If we get some back, get drawables for them and
                                    // pass them through to the transient graphics API


                                    //TransientManager tm = TransientManager.CurrentTransientManager;
                                    //IntegerCollection ic = new IntegerCollection();


                                    //foreach (Curve3d curve in curves)
                                    //{
                                    //    ed.WriteMessage("\nCurve start: " + curve.StartPoint.ToString());
                                    //    ed.WriteMessage("\nCurve end: " + curve.EndPoint.ToString());
                                    //    Drawable d = GetDrawable(curve);
                                    //    tm.AddTransient(d, TransientDrawingMode.DirectTopmost, 0, ic);
                                    //    _drawn.Add(d);
                                    //}
                                }
                            }
                        }
                        tr.Commit();
                    }
                }
                Utils.End();
                return;
            }
            catch (System.Exception e)
            {
                ed.WriteMessage("Program error: " + e.ToString());
                Utils.End();
                return;
            }
        }
예제 #41
0
        protected override bool WorldDrawData(WorldDraw draw)
        {
            if (!base.WorldDrawData(draw))
            {
                return(false);
            }

            short origCol = draw.SubEntityTraits.Color;

            if (_resizing)
            {
                //  using (Solid3d cube = new Solid3d())
                //{
                try
                {
                    //cube.CreateBox(0.5, 0.5, 0.5);
                    _firstdraw = _firstdraw + 1;


                    if (cube != null)
                    {
                        //int i = 20000;
                        bool chk = false;
                        //cube.TransformBy(
                        //  Matrix3d.Displacement(
                        //     _resizeLocation - Point3d.Origin
                        //  )
                        //  );

                        // Draw the cursor

                        draw.SubEntityTraits.Color = ColorIndex;
                        cube.WorldDraw(draw);
                        vRot = leftHand.GetVectorTo(rightHand);; // new Point3d(-3, 4, 0).GetVectorTo(new Point3d(-3, -4, 0)); //rightHand.GetVectorTo(leftHand);

                        System.Threading.Thread.Sleep((int)System.TimeSpan.FromSeconds(0.2).TotalMilliseconds);

                        //chk = (leftHand.Z < leftHip.Z);

                        //while (true)
                        //{
                        //  if (chk)
                        //    break;
                        //Point3d pt1 = rightHand - leftHand;
                        cube.TransformBy(Matrix3d.Rotation(0.1, vRot, Point3d.Origin));
                        //}

                        /*if (chk)
                         * {
                         *  cube.TransformBy(Matrix3d.Rotation(1.046, vRot, leftHand));
                         *  System.Threading.Thread.Sleep((int)System.TimeSpan.FromSeconds(2).TotalMilliseconds);
                         * }  */

                        //cube.TransformBy(Matrix3d.Rotation(0.5236, vRot, leftHand));
                    }

                    // if(_changeaxis)

                    //            vRot = rightHand.GetVectorTo(leftHand);
                    //          cube.TransformBy(Matrix3d.Rotation(0.5236,vRot,leftHand));

                    //   if (leftHand.Z > leftHip.Z)
                    //     _isRotate = false;
                }
                catch (System.Exception ex)
                {
                    _doc.Editor.WriteMessage(
                        "\nException: {0} - {1}", ex.Message, ex.InnerException
                        );
                }
                finally
                {
                    draw.SubEntityTraits.Color = origCol;
                }
                // }
                return(true);
            }

            if (_isRotate)
            {
                cube.WorldDraw(draw);
            }

            // If we're currently drawing...

            if (_drawing)
            {
                Solid3d sol = null;
                try
                {
                    // If we have vertices that haven't yet been drawn...

                    if (_vertices.Count > 1 //&&
                        //_vertices.Count - 1 > _lastDrawnVertex
                        )
                    {
                        // ... generate a tube

                        if (GenerateTube(_profSide, _vertices, out sol))
                        {
                            // We now need to break the pipe...

                            // If it was created, add it to our list to draw

                            _created.Add(sol);
                            sol = null;

                            // Clear all but the last vertex to draw from
                            // next time

                            ClearAllButLast(_vertices, 1);
                        }
                    }
                }
                catch
                {
                    // If the tube generation failed...

                    if (sol != null)
                    {
                        sol.Dispose();
                    }

                    // Loop, creating the most recent successful tube we can

                    bool succeeded = false;
                    int  n         = 1;

                    do
                    {
                        try
                        {
                            // Generate the previous, working tube using all
                            // but the last points (if it fails, one more is
                            // excluded per iteration, until we get a working
                            // tube)

                            GenerateTube(
                                _profSide, GetAllButLast(_vertices, n++), out sol
                                );

                            _created.Add(sol);
                            sol       = null;
                            succeeded = true;
                        }
                        catch { }
                    }while (!succeeded && n < _vertices.Count);

                    if (succeeded)
                    {
                        ClearAllButLast(_vertices, n - 1);

                        if (_vertices.Count > 1)
                        {
                            try
                            {
                                // And generate a tube for the remaining vertices

                                GenerateTube(_profSide, _vertices, out sol);
                            }
                            catch
                            {
                                succeeded = false;
                            }
                        }
                    }

                    if (!succeeded && sol != null)
                    {
                        sol.Dispose();
                        sol = null;
                    }
                }

                // Draw our solid(s)

                draw.SubEntityTraits.Color = ColorIndex;

                foreach (DBObject obj in _created)
                {
                    Entity ent = obj as Entity;
                    if (ent != null)
                    {
                        try
                        {
                            ent.WorldDraw(draw);
                        }
                        catch
                        { }
                    }
                }

                if (sol != null)
                {
                    try
                    {
                        sol.WorldDraw(draw);
                    }
                    catch
                    { }
                }

                if (_vertices.Count > 0)
                {
                    Point3d lastPt = _vertices[_vertices.Count - 1];

                    // Create a cursor sphere

                    using (Solid3d cursor = new Solid3d())
                    {
                        try
                        {
                            cursor.CreateBox(_profSide, _profSide, _profSide);

                            if (cursor != null)
                            {
                                cursor.TransformBy(
                                    Matrix3d.Displacement(lastPt - Point3d.Origin)
                                    );

                                // Draw the cursor

                                draw.SubEntityTraits.Color = 4; // ColorIndex;

                                cursor.WorldDraw(draw);
                            }
                        }
                        catch { }
                    }
                }

                if (sol != null)
                {
                    sol.Dispose();
                }
            }

            draw.SubEntityTraits.Color = origCol;

            return(true);
        }
    public void Cleanup()
    {
      if (_path != null)
      {
        _path.Dispose();
        _path = null;
      };
      if (_profile != null)
      {
        _profile.Dispose();
        _profile = null;
      };
      if (_tube != null)
      {
        _tube.Dispose();
        _tube = null;
      };

      _sweepOpts = null;
      _vertices.Clear();
    }
예제 #43
0
        protected override bool WorldDrawData(WorldDraw draw)
        {
            if (!base.WorldDrawData(draw))
            {
                return(false);
            }

            short origCol = draw.SubEntityTraits.Color;

            if (_resizing)
            {
                using (Solid3d cube = new Solid3d())
                {
                    try
                    {
                        if (switchm == 1)
                        {
                            cube.CreateFrustum(_profSide, _profSide, _profSide, 0.0);
                        }
                        else if (switchm == 0)
                        {
                            cube.CreateBox(_profSide, _profSide, _profSide);
                        }


                        if (cube != null)
                        {
                            cube.TransformBy(
                                Matrix3d.Displacement(
                                    _resizeLocation - Point3d.Origin
                                    )
                                );

                            // Draw the cursor

                            draw.SubEntityTraits.Color = ColorIndex;
                            cube.WorldDraw(draw);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _doc.Editor.WriteMessage(
                            "\nException: {0} - {1}", ex.Message, ex.InnerException
                            );
                    }
                    finally
                    {
                        draw.SubEntityTraits.Color = origCol;
                    }
                }



                return(true);
            }

            // If we're currently drawing...

            if (_drawing)
            {
                Solid3d sol = null;
                try
                {
                    // If we have vertices that haven't yet been drawn...

                    if (_vertices.Count > 1 //&&
                        //_vertices.Count - 1 > _lastDrawnVertex
                        )
                    {
                        // ... generate a tube

                        if (GenerateTube(_profSide, _vertices, out sol))
                        {
                            // We now need to break the pipe...

                            // If it was created, add it to our list to draw

                            _created.Add(sol);
                            sol = null;

                            // Clear all but the last vertex to draw from
                            // next time

                            ClearAllButLast(_vertices, 1);
                        }
                    }
                }
                catch
                {
                    // If the tube generation failed...

                    if (sol != null)
                    {
                        sol.Dispose();
                    }

                    // Loop, creating the most recent successful tube we can

                    bool succeeded = false;
                    int  n         = 1;

                    do
                    {
                        try
                        {
                            // Generate the previous, working tube using all
                            // but the last points (if it fails, one more is
                            // excluded per iteration, until we get a working
                            // tube)

                            GenerateTube(
                                _profSide, GetAllButLast(_vertices, n++), out sol
                                );

                            _created.Add(sol);
                            sol       = null;
                            succeeded = true;
                        }
                        catch { }
                    }while (!succeeded && n < _vertices.Count);

                    if (succeeded)
                    {
                        ClearAllButLast(_vertices, n - 1);

                        if (_vertices.Count > 1)
                        {
                            try
                            {
                                // And generate a tube for the remaining vertices

                                GenerateTube(_profSide, _vertices, out sol);
                            }
                            catch
                            {
                                succeeded = false;
                            }
                        }
                    }

                    if (!succeeded && sol != null)
                    {
                        sol.Dispose();
                        sol = null;
                    }
                }

                // Draw our solid(s)

                draw.SubEntityTraits.Color = ColorIndex;

                foreach (DBObject obj in _created)
                {
                    Entity ent = obj as Entity;
                    if (ent != null)
                    {
                        try
                        {
                            ent.WorldDraw(draw);
                        }
                        catch
                        { }
                    }
                }

                if (sol != null)
                {
                    try
                    {
                        sol.WorldDraw(draw);
                    }
                    catch
                    { }
                }

                if (_vertices.Count > 0)
                {
                    Point3d lastPt = _vertices[_vertices.Count - 1];

                    // Create a cursor sphere

                    using (Solid3d cursor = new Solid3d())
                    {
                        try
                        {
                            if (switchm == 1)
                            {
                                cursor.CreateFrustum(_profSide, _profSide, _profSide, 0.0);
                            }
                            else if (switchm == 0)
                            {
                                cursor.CreateBox(_profSide, _profSide, _profSide);
                            }
                            if (cursor != null)
                            {
                                cursor.TransformBy(
                                    Matrix3d.Displacement(lastPt - Point3d.Origin)
                                    );

                                // Draw the cursor

                                draw.SubEntityTraits.Color = 4;     // ColorIndex;

                                cursor.WorldDraw(draw);
                            }
                        }
                        catch { }
                    }
                }

                if (sol != null)
                {
                    sol.Dispose();
                }
            }

            draw.SubEntityTraits.Color = origCol;

            return(true);
        }
예제 #44
0
        private bool GenerateTube(
          double profRad, Point3dCollection pts, out Solid3d sol
        )
        {
            bool readyToBreak;

            // Let's start by creating our spline path

            using (Spline path = new Spline(pts, 0, 0.0))
            {
                double pathLen = path.GetDistanceAtParameter(path.EndParam);
                readyToBreak = (pathLen > _profSide * _segFactor);

                // And our sweep profile

                Circle profile =
                  new Circle(pts[0], pts[1] - pts[0], profRad);
                using (profile)
                {
                    // Then our sweep options

                    SweepOptionsBuilder sob = new SweepOptionsBuilder();

                    // Align the entity to sweep to the path

                    sob.Align =
                      SweepOptionsAlignOption.AlignSweepEntityToPath;

                    // The base point is the start of the path

                    sob.BasePoint = path.StartPoint;

                    // The profile will rotate to follow the path

                    sob.Bank = true;
                    using (SweepOptions sweepOpts = sob.ToSweepOptions())
                    {
                        sol = new Solid3d();
                        sol.ColorIndex = ColorIndex;

                        // Sweep our profile along our path

                        sol.CreateSweptSolid(profile, path, sweepOpts);
                    }
                }
            }
            _lastDrawnVertex = pts.Count - 1;

            return readyToBreak;
        }
예제 #45
0
        public void Cmd_EdgeBand()
        {
            if (!LicensingAgent.Check())
            {
                return;
            }
            var acCurDoc = Application.DocumentManager.MdiActiveDocument;
            var acCurDb  = acCurDoc.Database;
            var acCurEd  = acCurDoc.Editor;

            //Call user to select a face
            var userSel = acCurEd.SelectSubentity(SubentityType.Face, "\nSelect a FACE to use as cutting criteria: ");

            if (userSel == null)
            {
                return;
            }
            if (userSel.Item1 == ObjectId.Null)
            {
                return;
            }
            if (userSel.Item2 == SubentityId.Null)
            {
                return;
            }

            var insetOpts = new PromptDistanceOptions("\nEnter edge banding thickness: ")
            {
                AllowNone     = false,
                AllowZero     = false,
                AllowNegative = false,
                DefaultValue  = SettingsUser.EdgeBandThickness
            };

            //Get the offset distance
            var insetRes = acCurEd.GetDistance(insetOpts);

            if (insetRes.Status != PromptStatus.OK)
            {
                return;
            }

            SettingsUser.EdgeBandThickness = insetRes.Value;


            // ReSharper disable once CompareOfFloatsByEqualityOperator
            if (SettingsUser.EdgeBandThickness <= 0)
            {
                return;
            }

            Entity  faceEnt  = null;
            Surface tempSurf = null;
            Solid3d tempSol  = null;

            try
            {
                //Open a transaction
                using (var acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    var acSol = acTrans.GetObject(userSel.Item1, OpenMode.ForWrite) as Solid3d;

                    if (acSol == null)
                    {
                        acTrans.Abort();
                        return;
                    }

                    var innerSol = acSol.Clone() as Solid3d;

                    if (innerSol == null)
                    {
                        acTrans.Abort();
                        return;
                    }

                    acSol.Layer = acCurDb.GetCLayer(acTrans);
                    acCurDb.AppendEntity(innerSol);

                    faceEnt = acSol.GetSubentity(userSel.Item2);

                    var eInfo    = new EntInfo(acSol, acCurDb, acTrans);
                    var largestM = eInfo.GetLargestMeasurement();

                    using (tempSurf = faceEnt.CreateSurfaceFromFace(acCurDb, acTrans, false))
                    {
                        var thickness = largestM + SettingsUser.EdgeBandThickness;

                        using (tempSol = tempSurf.Thicken(-(thickness * 2), true))
                        {
                            tempSol.OffsetBody(-SettingsUser.EdgeBandThickness);

                            var cutSol = tempSol.Slice(tempSurf, true);
                            cutSol.Dispose();

                            acSol.BooleanOperation(BooleanOperationType.BoolSubtract, tempSol);
                        }
                    }

                    var acBool1 = new[] { innerSol.ObjectId };
                    var acBool2 = new[] { acSol.ObjectId };

                    acBool1.SolidSubtrahend(acBool2, acCurDb, acTrans, false);

                    acTrans.Commit();
                }
            }
            catch (Exception e)
            {
                acCurEd.WriteMessage(e.Message);
                MailAgent.Report(e.Message);
            }
            finally
            {
                if (faceEnt != null)
                {
                    faceEnt.Dispose();
                }
                if (tempSurf != null)
                {
                    tempSurf.Dispose();
                }
                if (tempSol != null)
                {
                    tempSol.Dispose();
                }
            }
        }
예제 #46
0
        public static DBObject Create(this Grevit.Types.Slab s, Transaction tr)
        {
            try
            {
                BlockTable bt = (BlockTable)tr.GetObject(Command.Database.BlockTableId, OpenMode.ForRead);
                BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                // Polyline acPoly = new Polyline();
                //acPoly.SetDatabaseDefaults();

                //int i = 0;

                DBObjectCollection objColl = new DBObjectCollection();
                Point3dCollection ptcol = new Point3dCollection();
                foreach (Grevit.Types.Loop loop in s.surface.profile)
                {
                    foreach (Grevit.Types.Component p in loop.outline)
                        ptcol = p.To3dPointCollection();


                    //Curve3dCollection collt = parse3dCurve(p);
                    //acPoly.AppendVertex(new PolylineVertex3d(new Point3d(p.x, p.y, p.z)));
                    //acPoly.AddVertexAt(i, new Point2d(p.x, p.y), 0, 0, 0);
                    //i++;

                    //foreach (Curve3d curve in collt)
                    //{ 
                    //    objColl.Add(Autodesk.AutoCAD.DatabaseServices.Curve.CreateFromGeCurve(curve));
                    //}
                }

                Polyline3d face = new Polyline3d(Poly3dType.SimplePoly, ptcol, true);
                objColl.Add(face);
                //Polyline3d face = new Polyline3d();
                //ETC...
                // or from your settings
                // Polyline3d face = new Polyline3d(Poly3dType.SimplePoly, vertices, true);





                DBObjectCollection myRegionColl = new DBObjectCollection();
                // create a single region
                Autodesk.AutoCAD.DatabaseServices.Region objreg = new Autodesk.AutoCAD.DatabaseServices.Region();
                DBObjectCollection objRegions = new DBObjectCollection();
                try
                {
                    objRegions = Autodesk.AutoCAD.DatabaseServices.Region.CreateFromCurves(objColl);
                    objreg = objRegions[0] as Autodesk.AutoCAD.DatabaseServices.Region;

                }
                catch (Autodesk.AutoCAD.Runtime.Exception ex)
                {
                    // eInvalidInput exception
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Error: unable to create region collection:\n" + ex.Message);

                }






                //acPoly.Closed = true;
                //ms.AppendEntity(acPoly);
                //tr.AddNewlyCreatedDBObject(acPoly, true);

                //atrix3d mm = Matrix3d.Displacement(new Vector3d(0, 0, r.outline[0].z));
                //acPoly.TransformBy(mm);


                //Autodesk.Aec.Geometry.Profile myProfile = Autodesk.Aec.Geometry.Profile.CreateFromEntity(acPoly, ed.CurrentUserCoordinateSystem);

                //Slab slab = new Slab();
                //slab.SetDatabaseDefaults(db);
                //slab.SetToStandard(db);         
                //slab.Location = new Point3d(0, 0, 0);

                //slab.SetBaseProfile(myProfile, Matrix3d.Identity);

                //DBObjectCollection col = acPoly.GetOffsetCurves(0);


                //DBObjectCollection res = Region.CreateFromCurves(coll);

                //Region reg = res[0] as Region;

                Solid3d solid = new Solid3d();
                solid.Extrude(objreg, s.height, s.slope);


                LayerTable lt = (LayerTable)tr.GetObject(Command.Database.LayerTableId, OpenMode.ForRead);
                if (s.TypeOrLayer != "") { if (lt.Has(s.TypeOrLayer)) solid.LayerId = lt[s.TypeOrLayer]; }
                //if (ss.Has(r.family, tr)) slab.StyleId = ss.GetAt(r.family);


                ms.AppendEntity(solid);
                tr.AddNewlyCreatedDBObject(solid, true);
                return solid;
            }

            catch (Autodesk.AutoCAD.Runtime.Exception e)
            {
            }

            return null;
        }