예제 #1
0
        private PromptDoubleResult GetScaleNumber()
        {
            PromptDoubleOptions scaleRatioOptions = new PromptDoubleOptions("Skala: ");
            scaleRatioOptions.AllowNegative = false;
            scaleRatioOptions.AllowZero = false;

            PromptDoubleResult scaleRatio = editor.GetDouble(scaleRatioOptions);
            return scaleRatio;
        }
예제 #2
0
파일: AKoty.cs 프로젝트: anielii/Acommands
        private PromptDoubleResult GetDrawingScale()
        {
            PromptDoubleOptions drawingScaleOptions = new PromptDoubleOptions("Skala jednostek: ");
            drawingScaleOptions.DefaultValue = 1;
            drawingScaleOptions.UseDefaultValue = true;
            drawingScaleOptions.AllowNegative = false;
            drawingScaleOptions.AllowZero = false;

            PromptDoubleResult drawingScale = editor.GetDouble(drawingScaleOptions);
            return drawingScale;
        }
예제 #3
0
        public void AngleTest()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptAngleOptions opt1 = new PromptAngleOptions("Enter start angle of the arc");

            opt1.AllowNone = false;
            opt1.UseDashedLine = true;

            //USAGE OF INPUT CONTEXT REACTORS
            ed.PromptingForAngle += new PromptAngleOptionsEventHandler(handle_promptangleOptions);
            ed.PromptedForAngle += new PromptDoubleResultEventHandler(handle_promptAngleResult);

            PromptDoubleResult startAngle = ed.GetAngle(opt1);

            ed.PromptingForAngle -= new PromptAngleOptionsEventHandler(handle_promptangleOptions);
            ed.PromptedForAngle -= new PromptDoubleResultEventHandler(handle_promptAngleResult);

            opt1.Message = "Enter end angle of the arc";
            PromptDoubleResult endAngle = ed.GetAngle(opt1);

            PromptDoubleOptions opt2 = new PromptDoubleOptions("Enter the radius of the arc(double)");
            opt2.Message = "Enter the radius of the arc(double)";
            PromptDoubleResult radius = ed.GetDouble(opt2);

            if(startAngle.Status == PromptStatus.OK && endAngle.Status == PromptStatus.OK && radius.Status == PromptStatus.OK)
            {
                Point3d center = new Point3d(30.0, 19.0, 0.0);
                Database db = Application.DocumentManager.MdiActiveDocument.Database;
                Autodesk.AutoCAD.DatabaseServices.TransactionManager tm = db.TransactionManager;

                using (Transaction myT = tm.StartTransaction())
                {
                    BlockTable bt = (BlockTable)tm.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                    BlockTableRecord btr = (BlockTableRecord)tm.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                    using (Arc arc1 = new Arc(center, radius.Value, startAngle.Value, endAngle.Value))
                    {
                        btr.AppendEntity(arc1);
                        tm.AddNewlyCreatedDBObject(arc1, true);
                    }
                    myT.Commit();
                }

            }
            else
            {
                ed.WriteMessage("Arc cannot be constructed");
            }
        }
예제 #4
0
        public void DoubleTest()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptDoubleOptions opt1 = new PromptDoubleOptions("Enter a number or Pi/Two-pi");
            opt1.Keywords.Add("Pi");
            opt1.Keywords.Add("Two-pi");
            opt1.AllowNone = false;
            opt1.AllowZero = false;
            opt1.DefaultValue = 1.0;

            PromptDoubleResult doubleRes = ed.GetDouble(opt1);
            if(doubleRes.Status == PromptStatus.Keyword)
            {
                switch (doubleRes.StringResult)
                {
                    case "Pi":
                        ed.WriteMessage("Value is 3.14");
                        break;
                    case "Two-pi":
                        ed.WriteMessage("\nValue is 6.28");
                        break;
                    default:
                        ed.WriteMessage("\nKeyword unknown");
                        break;
                }
            }
            if(doubleRes.Status != PromptStatus.OK)
            {
                ed.WriteMessage("\nUser entered: " + doubleRes.Status.ToString());
            }
        }
예제 #5
0
        public static void AutoNums()
        {
            Document acDoc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database acDb  = acDoc.Database;
            Editor   acEd  = acDoc.Editor;

            string currentFormat = "0";

            bool continuePick = true;

            Point3d basePoint;
            bool    isFirstPick = true;

            while (continuePick)
            {
                string s = (AutoType == AutoType.Number) ? start.ToString("F" + precision, CultureInfo.InvariantCulture)
                    : startChar.ToString();
                string             incrementString = (AutoType == AutoType.Number) ? ", Increment: " + step + ", Current Format: " + currentFormat : "";
                PromptPointOptions po2             = new PromptPointOptions("\nPick a point to insert text (Next: " + prefix
                                                                            + s
                                                                            + surfix
                                                                            + incrementString + ", Text height: " + textHeight + ")" + " or ");

                if (!isFirstPick)
                {
                    po2.UseBasePoint = true;
                    po2.BasePoint    = basePoint;
                }

                po2.Keywords.Add("Start");
                if (AutoType == AutoType.Number)
                {
                    po2.Keywords.Add("Increment");
                }
                po2.Keywords.Add("Options");
                PromptPointResult pr;
                pr = acEd.GetPoint(po2);

                if (pr.Status == PromptStatus.OK)
                {
                    Point3d thisPoint = pr.Value;
                    if (isFirstPick)
                    {
                        basePoint   = thisPoint;
                        isFirstPick = false;
                    }

                    using (Transaction tr = acDoc.TransactionManager.StartTransaction())
                    {
                        DBText thisText = new DBText();
                        if (AutoType == AutoType.Number)
                        {
                            thisText.TextString = prefix + start.ToString("F" + precision, CultureInfo.InvariantCulture) + surfix;
                        }
                        else
                        {
                            thisText.TextString = prefix + startChar + surfix;
                        }

                        thisText.Position = pr.Value;
                        thisText.Height   = textHeight;

                        BlockTable acBlkTbl;
                        acBlkTbl = tr.GetObject(acDb.BlockTableId, OpenMode.ForRead) as BlockTable;

                        BlockTableRecord acBlkTblRec;
                        acBlkTblRec = tr.GetObject(acDb.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

                        acBlkTblRec.AppendEntity(thisText);
                        tr.AddNewlyCreatedDBObject(thisText, true);
                        t = thisText;

                        TextBounds.CreateTextBound(thisText, boundType);
                        tr.Commit();
                        if (AutoType == AutoType.Number)
                        {
                            start += step;
                        }
                        else
                        {
                            startChar++;
                        }
                    }
                }
                else if (pr.Status == PromptStatus.Keyword)
                {
                    switch (pr.StringResult)
                    {
                    case "Start":
                        if (AutoType == AutoType.Number)
                        {
                            PromptDoubleOptions pdo = new PromptDoubleOptions("\nSpecify starting number [" + start + "]");
                            PromptDoubleResult  pdr = acEd.GetDouble(pdo);
                            if (pdr.Status == PromptStatus.OK)
                            {
                                start = pdr.Value;
                            }
                        }
                        else
                        {
                            PromptStringOptions pso = new PromptStringOptions("\nSpecify Start Letter (" + startChar + ")");
                            pso.AllowSpaces = false;
                            PromptResult psrs = acEd.GetString(pso);
                            if (psrs.Status == PromptStatus.OK)
                            {
                                startChar = psrs.StringResult[0];
                            }
                        }
                        break;

                    case "Increment":
                        PromptDoubleOptions pdo2 = new PromptDoubleOptions("\nSpecify increment number [" + step + "]");
                        PromptDoubleResult  pdr2 = acEd.GetDouble(pdo2);
                        if (pdr2.Status == PromptStatus.OK)
                        {
                            step = pdr2.Value;
                        }
                        break;

                    case "Options":
                        PromptKeywordOptions pko = new PromptKeywordOptions("\nSelect Options: ");
                        pko.Keywords.Add("Prefix");
                        pko.Keywords.Add("Surfix");
                        pko.Keywords.Add("Format");
                        pko.Keywords.Add("Bounds");
                        pko.Keywords.Add("TextHeight");
                        pko.Keywords.Add("NumberOrLetter");
                        pko.Keywords.Default = "Format";
                        PromptResult pkr = acEd.GetKeywords(pko);

                        if (pkr.Status == PromptStatus.OK)
                        {
                            string resultKeyword = pkr.StringResult;
                            switch (resultKeyword)
                            {
                            case "Prefix":
                                PromptStringOptions pso = new PromptStringOptions("\nSpecify prefix (" + prefix + ")");
                                pso.AllowSpaces = true;
                                PromptResult psrs = acEd.GetString(pso);
                                if (psrs.Status == PromptStatus.OK)
                                {
                                    prefix = psrs.StringResult;
                                }
                                break;

                            case "Surfix":
                                PromptStringOptions pso2 = new PromptStringOptions("\nSpecify Surfix (" + surfix + ")");
                                pso2.AllowSpaces = true;
                                PromptResult psrs2 = acEd.GetString(pso2);
                                if (psrs2.Status == PromptStatus.OK)
                                {
                                    surfix = psrs2.StringResult;
                                }
                                break;

                            case "Format":
                                PromptIntegerOptions piio = new PromptIntegerOptions("\nSpecify NUMBER symbol after decimal symbol [" + " | Current Format:" + currentFormat + "]");
                                piio.AllowNone     = true;
                                piio.AllowZero     = true;
                                piio.AllowNegative = false;

                                PromptIntegerResult piir = acEd.GetInteger(piio);
                                if (piir.Status == PromptStatus.OK)
                                {
                                    precision = piir.Value;
                                }
                                if (precision > 0)
                                {
                                    currentFormat  = "0";
                                    currentFormat += ".";
                                    for (int i = 1; i <= precision; i++)
                                    {
                                        currentFormat += "0";
                                    }
                                }
                                break;

                            case "Bounds":
                                PromptKeywordOptions pkob = new PromptKeywordOptions("\nSpecify Text bound type (" + boundType.ToString() + ")");
                                pkob.AllowNone = true;

                                pkob.Keywords.Add("None");
                                pkob.Keywords.Add("Rectangle");
                                pkob.Keywords.Add("Circle");
                                pkob.Keywords.Add("Triangle");
                                pkob.Keywords.Default = "None";
                                PromptResult pkrb = acEd.GetKeywords(pkob);

                                if (pkrb.Status == PromptStatus.OK)
                                {
                                    string result = pkrb.StringResult;
                                    switch (result)
                                    {
                                    case "None":
                                        boundType = TextBounds.BoundType.None;
                                        break;

                                    case "Rectangle":
                                        boundType = TextBounds.BoundType.Rectangle;
                                        break;

                                    case "Circle":
                                        boundType = TextBounds.BoundType.Circle;
                                        break;

                                    case "Triangle":
                                        boundType = TextBounds.BoundType.Triangle;
                                        break;

                                    default: break;
                                    }
                                }

                                break;

                            case "TextHeight":
                                PromptDoubleOptions pdo3 = new PromptDoubleOptions("\nSpecify height for new text (" + textHeight + ")");

                                PromptDoubleResult pdr3 = acEd.GetDouble(pdo3);
                                if (pdr3.Status == PromptStatus.OK)
                                {
                                    textHeight = pdr3.Value;
                                }
                                break;

                            case "NumberOrLetter":
                                PromptKeywordOptions pkob2 = new PromptKeywordOptions("\nUsing Number or Letter? (" + AutoType.ToString() + ")");
                                pkob2.AllowNone = true;

                                pkob2.Keywords.Add("Number");
                                pkob2.Keywords.Add("Letter");

                                PromptResult pkrb2 = acEd.GetKeywords(pkob2);

                                if (pkrb2.Status == PromptStatus.OK)
                                {
                                    string result = pkrb2.StringResult;
                                    switch (result)
                                    {
                                    case "Number":
                                        AutoType = AutoType.Number;
                                        break;

                                    case "Letter":
                                        AutoType = AutoType.Letter;
                                        break;

                                    default: break;
                                    }
                                }

                                break;

                            default: break;
                            }
                        }

                        break;

                    default: break;
                    }
                }
                else
                {
                    continuePick = false;
                }
            }
        }
예제 #6
0
파일: CivApp.cs 프로젝트: Lufan/Genplan2012
 public static Double PromptEnterDouble(String message, Double defaultValue = 0.0d)
 {
     Double result = -1.0d;
     try
     {
         using (var tr = AcadApp.StartTransaction())
         {
             var optDist = new PromptDoubleOptions(message);
             optDist.UseDefaultValue = true;
             optDist.DefaultValue = defaultValue;
             optDist.AllowNone = false;
             optDist.AllowNegative = false;
             var valDist = AcadApp.AcaEd.GetDouble(optDist);
             if (valDist.Status == PromptStatus.OK)
             {
                 result = valDist.Value;
                 return result;
             }
         } // using
     }
     catch (Autodesk.AutoCAD.Runtime.Exception ex)
     {
         AcadApp.AcaEd.WriteMessage("ERROR: CivApp.PromptEnterDouble()\n" + ex + "\n");
     }
     return -1.0d; //There have been some errors
 }
예제 #7
0
        public void Figura1()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.GetDocument(db);
            Editor ed = doc.Editor;

            PromptDoubleOptions GetIlgis = new PromptDoubleOptions("\nĮveskite mikroskemos ilgį");
            double Ilgis;
            GetIlgis.AllowNegative = false;
            GetIlgis.AllowZero = false;
            GetIlgis.AllowNone = false;
            PromptDoubleResult GetIlgisRezultatas = ed.GetDouble(GetIlgis);
            Ilgis = GetIlgisRezultatas.Value;

            PromptDoubleOptions GetPlotis = new PromptDoubleOptions("\nĮveskite mikroskemos plotį");
            double Plotis;
            GetPlotis.AllowNegative = false;
            GetPlotis.AllowZero = false;
            GetPlotis.AllowNone = false;
            PromptDoubleResult GetPlotisRezultatas = ed.GetDouble(GetPlotis);
            Plotis = GetPlotisRezultatas.Value;

            PromptPointOptions GetTaskas = new PromptPointOptions("\nPasirinkite tašką");
            Point3d Taskas;
            GetTaskas.AllowNone = false;
            PromptPointResult GetTaskasRezultatas = ed.GetPoint(GetTaskas);
            Taskas = GetTaskasRezultatas.Value;

            Transaction tr = db.TransactionManager.StartTransaction();
            using (tr)
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite,false);
                Polyline3d polyline = new Polyline3d();
                btr.AppendEntity(polyline);
                tr.AddNewlyCreatedDBObject(polyline, true);
                PolylineVertex3d vex3d = new PolylineVertex3d();

                //Pradinis taskas
                vex3d = new PolylineVertex3d(Taskas);
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                //Atsakos tarp pradinio ir pirmo kampo
                double betaIlgis = Ilgis / 8;
                double AtsakosIlgis = Math.Min(Ilgis / 4, Plotis / 4);
                for (int i = 1; i < 8; i++)
                {
                    // Linija iki atsakos
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X, Taskas.Y + betaIlgis * i, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos linija
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X - AtsakosIlgis, Taskas.Y + betaIlgis * i, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos grizimas atgal i kontura
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X, Taskas.Y + betaIlgis * i, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);
                }

                // Pirmas kampas
                vex3d = new PolylineVertex3d(new Point3d(Taskas.X, Taskas.Y + Ilgis, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                //Atsakos tarp pirmo ir angtro kampo
                double betaPlotis = Plotis / 2;
                for (int i = 1; i < 2; i++)
                {
                    // Linija iki atsakos
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + betaPlotis * i, Taskas.Y + Ilgis, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos linija
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + betaPlotis * i, Taskas.Y + Ilgis + AtsakosIlgis, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos grizimas atgal i kontura
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + betaPlotis * i, Taskas.Y + Ilgis, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);
                }

                //Antras kampas
                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis, Taskas.Y + Ilgis, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                //Atsakos tarp antro ir trecio kampo
                for (int i = 1; i < 8; i++)
                {
                    // Linija iki atsakos
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis, Taskas.Y + Ilgis - betaIlgis * i, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos linija
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis + AtsakosIlgis, Taskas.Y + Ilgis - betaIlgis * i, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos grizimas atgal i kontura
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis, Taskas.Y + Ilgis - betaIlgis * i, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);
                }

                //Trecias kampas
                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis, Taskas.Y, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                //Atsakos tarp trecio ir pradinio kampo
                for (int i = 1; i < 2; i++)
                {
                    // Linija iki atsakos
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis - betaPlotis * i, Taskas.Y, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos linija
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis - betaPlotis * i, Taskas.Y - AtsakosIlgis, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos grizimas atgal i kontura
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis - betaPlotis * i, Taskas.Y, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);
                }

                //Ketvirtas kampas / Pradinis taskas
                vex3d = new PolylineVertex3d(Taskas);
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);
                tr.Commit();
            }
        }
예제 #8
0
        public static void getPointsDelta()
        {
            // Получение текущего документа и базы данных
            Document acDoc = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            TypeViewerForm tvf = new TypeViewerForm();

            // Старт транзакции
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                PromptPointResult pPtRes;
                PromptPointOptions pPtOpts = new PromptPointOptions("");

                // Prompt for the start point
                pPtOpts.Message = "\nВведи точку перехода: ";
                pPtRes = acDoc.Editor.GetPoint(pPtOpts);

                int indX = Data.pathPoints.FindIndex(item => item == pPtRes.Value);

                //PromptStringOptions psoOpt = new PromptStringOptions("nВведите имя блока: ");
                PromptDoubleResult psoRes;
                PromptDoubleOptions psoOpt = new PromptDoubleOptions("");

                psoOpt.Message = "\nВведите длину перехода: ";
                psoRes = acDoc.Editor.GetDouble(psoOpt);
                Data.deltaPoints[indX] = psoRes.Value;

                // Сохранение нового объекта в базе данных
                acTrans.Commit();
            }
        }
예제 #9
0
        public void Create()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;

            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                //Get employee name
                PromptStringOptions prName = new PromptStringOptions("Enter Employee Name");
                prName.AllowSpaces = true;
                PromptResult prNameRes = ed.GetString(prName);
                if (prNameRes.Status != PromptStatus.OK)
                {
                    trans.Abort();
                    return;
                }

                //Get employee division
                PromptStringOptions prDiv = new PromptStringOptions("Enter Employee Division");
                prDiv.AllowSpaces = true;
                PromptResult prDivRes = ed.GetString(prDiv);
                if (prDivRes.Status != PromptStatus.OK)
                {
                    trans.Abort();
                    return;
                }

                //Get employee salary
                PromptDoubleOptions prSal = new PromptDoubleOptions("Enter Employee Salary");
                prSal.AllowNegative = false;
                prSal.AllowNone     = false;
                prSal.AllowZero     = false;
                PromptDoubleResult prSalRes = ed.GetDouble(prSal);
                if (prSalRes.Status != PromptStatus.OK)
                {
                    trans.Abort();
                    return;
                }

                //Get employee//s coordinates in the drawing
                PromptPointOptions prPos = new PromptPointOptions("Enter Employee Position");
                prPos.AllowNone = false;
                PromptPointResult prPosRes = ed.GetPoint(prPos);
                if (prPosRes.Status != PromptStatus.OK)
                {
                    trans.Abort();
                    return;
                }

                //Create the employee block reference
                CreateEmployee(prNameRes.StringResult, prDivRes.StringResult, prSalRes.Value, prPosRes.Value);

                String manager = null;

                //Now create the division
                //Pass an empty string for manager to check if it already exists
                Xrecord  depMgrXRec;
                ObjectId xRecId;
                xRecId = CreateDivision(prDivRes.StringResult, manager);

                //Open the department manager XRecord
                depMgrXRec = (Xrecord)trans.GetObject(xRecId, OpenMode.ForRead);

                foreach (TypedValue val in depMgrXRec.Data.AsArray())
                {
                    string str;
                    str = (string)val.Value;
                    if (str.Equals(""))
                    {
                        // Manager was not set, now set it
                        // Prompt for  manager name first
                        PromptStringOptions prManagerName = new PromptStringOptions("\n" + "No Manager Set. Enter Manager Name");
                        prManagerName.AllowSpaces = true;
                        PromptResult prManagerNameRes = ed.GetString(prManagerName);
                        if (prManagerNameRes.Status != PromptStatus.OK)
                        {
                            trans.Abort();
                            return;
                        }

                        //Set a manager name
                        depMgrXRec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Text, prManagerName.Message));
                    }
                }

                trans.Commit();
            }
        }
        public void AdjustTabs()
        {
            var doc = Application.DocumentManager.MdiActiveDocument;

            if (null == doc)
            {
                return;
            }
            var db = doc.Database;
            var ed = doc.Editor;

            // Here we're going to get a selection set, but only care
            // about splines

            var pso = new PromptSelectionOptions();
            var psr = ed.GetSelection();

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

            var pdo = new PromptDoubleOptions("\nEnter wiggle factor");

            pdo.DefaultValue    = 0.8;
            pdo.UseDefaultValue = true;
            pdo.AllowNegative   = false;
            pdo.AllowZero       = false;

            var pdr = ed.GetDouble(pdo);

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

            using (var tr = doc.TransactionManager.StartTransaction())
            {
                foreach (var id in psr.Value.GetObjectIds())
                {
                    // We only care about splines

                    var sp = tr.GetObject(id, OpenMode.ForRead) as Spline;
                    if (sp != null && sp.NumFitPoints == 6)
                    {
                        // Collect the fit points

                        var pts = sp.FitData.GetFitPoints();

                        // Adjust them

                        AddWiggle(pts, pdr.Value);

                        // Set back the top points to the spline
                        // (we know these are the ones that have changed)

                        sp.UpgradeOpen();

                        sp.SetFitPointAt(2, pts[2]);
                        sp.SetFitPointAt(3, pts[3]);
                    }
                }
                tr.Commit();
            }
        }
예제 #11
0
        private double? TryGetDensitySpan(string promptMessage)
        {
            PromptDoubleOptions options = new PromptDoubleOptions(promptMessage);
            options.AllowNegative = false;
            options.AllowZero = false;
            options.DefaultValue = 0.20;

            PromptDoubleResult result = editor.GetDouble(options);
            if (result.Status == PromptStatus.OK)
            {
                return result.Value;
            }
            else
            {
                acMark.RemoveMarks();
                return null;
            }
        }
예제 #12
0
        private double? TryGetBaDiameter(string message)
        {
            PromptDoubleOptions options = new PromptDoubleOptions(message);
            options.AllowZero = false;
            options.AllowNegative = false;
            options.AllowNone = false;
            options.DefaultValue = 8;
            options.UseDefaultValue = true;

            PromptDoubleResult result = editor.GetDouble(options);
            if (result.Status == PromptStatus.OK)
            {
                return result.Value / 1000;
            }
            else
            {
                return null;
            }

        }
예제 #13
0
        private double? TryGetSpanStep(string promptMessage)
        {
            PromptDoubleOptions options = new PromptDoubleOptions(promptMessage);
            options.AllowNegative = false;
            options.AllowZero = false;
            options.DefaultValue = 20;

            PromptDoubleResult result = editor.GetDouble(options);
            if (result.Status == PromptStatus.OK)
            {
                return result.Value / 100;
            }
            else
            {
                return null;
            }
        }
    public void NavigateWithKinect()
    {
      Document doc =
        Autodesk.AutoCAD.ApplicationServices.
          Application.DocumentManager.MdiActiveDocument;
      Database db = doc.Database;
      Editor ed = doc.Editor;

      // As the user to select the camera and target locations

      PromptPointResult camRes =
        ed.GetPoint("\nPick camera location");
      if (camRes.Status != PromptStatus.OK)
        return;

      PromptPointResult tgtRes =
        ed.GetPoint("\nPick target location");
      if (tgtRes.Status != PromptStatus.OK)
        return;

      // And also the height from ground level

      PromptDoubleOptions pdo =
        new PromptDoubleOptions("\nEnter height from ground");
      pdo.UseDefaultValue = true;

      // Default height of 6' or 2m

      pdo.DefaultValue = (db.Lunits > 2 ? 6 : 2);

      PromptDoubleResult hgtRes = ed.GetDouble(pdo);
      if (hgtRes.Status != PromptStatus.OK)
        return;

      _zoomDist = hgtRes.Value / 10.0;

      // We need a Kinect object

      KinectSensor kinect = null;

      // Make sure we dispose of our Camera (which will
      // commit the transaction)

      Camera camera = new Camera(doc);
      using (camera)
      {
        // Set the height from the ground as a vector

        Vector3d height = new Vector3d(0, 0, hgtRes.Value);
        camera.Location = camRes.Value + height;
        camera.Target = tgtRes.Value + height;

        camera.ApplyToCurrentView();

        // Unset the loop termination flag

        _finished = false;
        _reset = true;

        if (KinectSensor.KinectSensors.Count <= 0)
        {
          ed.WriteMessage(
            "\nUnable to start Kinect sensor - " +
            "are you sure it's plugged in?"
          );
          return;
        }
                      
        // We need our Kinect sensor

        kinect = KinectSensor.KinectSensors[0];

        // We only care about skeleton information

        kinect.SkeletonFrameReady +=
          new EventHandler<SkeletonFrameReadyEventArgs>(
            OnSkeletonFrameReady
          );

        kinect.SkeletonStream.Enable();

        kinect.Start();

        // Loop until user terminates or cancels

        while (
          !_finished &&
          !HostApplicationServices.Current.UserBreak()
        )
        {
          // Direction from Kinect is:
          //
          // 0, 0, 1  - arm pointing directly at the center
          // 1, 0, 0  - arm pointing directly left
          // -1, 0, 0 - arm pointing directly right
          // 0, 1, 0  - arm pointing directly down
          // 0, -1, 0 - arm pointing directly up

          const double distFac = 0.001;
          const double angFac = 0.003;

          if (_reset)
          {
            // Reset to the initial view parameters

            camera.Location = camRes.Value + height;
            camera.Target = tgtRes.Value + height;

            camera.ApplyToCurrentView();

            _reset = false;
          }
          else if (_orbiting || _navigating)
          {
            Matrix3d locMat = Matrix3d.Identity;

            // We only orbit if not too close to the centre

            if (Math.Abs(_direction.X) > 0.2)
            {
              locMat =
                Matrix3d.Rotation(
                  -_direction.X * angFac,
                  Vector3d.ZAxis, camera.Target
                ) * locMat;
            }
            
            // And the same for upwards/downwards tilt

            if (Math.Abs(_direction.Y) > 0.2)
            {
              // To tilt upwards/downwards, we need the right axis
              // of rotation. Use a coordinate system object taking
              // the view direction as the Y axis and the Z axis of
              // WCS as the X axis, leaving the Z axis of the
              // coordinate system as our axis of rotation

              Vector3d newYaxis =
                camera.Location - camera.Target;
              newYaxis = newYaxis / newYaxis.Length;

              CoordinateSystem3d cs =
                new CoordinateSystem3d(
                  camera.Target,
                  Vector3d.ZAxis,
                  newYaxis
                );

              locMat =
                Matrix3d.Rotation(
                  -_direction.Y * angFac,
                  cs.Zaxis, camera.Target
                ) * locMat;
            }

            // If we're zooming, we adjust the camera and target
            // locations by a displacement along the viewing
            // direction

            if (_navigating)
            {
              Matrix3d trgMat =
                Matrix3d.Displacement(
                  (camera.Target - camera.Location) * distFac
                );
              locMat = trgMat * locMat;
              camera.TargTransform = trgMat;
            }
            camera.LocTransform = locMat;

            camera.ApplyToCurrentView();
          }

          // Reset the transformation values

          camera.LocTransform = Matrix3d.Identity;
          camera.TargTransform = Matrix3d.Identity;

          System.Windows.Forms.Application.DoEvents();
        }
      }

      kinect.Stop();

      kinect.SkeletonFrameReady -=
        new EventHandler<SkeletonFrameReadyEventArgs>(
          OnSkeletonFrameReady
        );
    }
예제 #15
0
        public void Figura4()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.GetDocument(db);
            Editor ed = doc.Editor;

            PromptDoubleOptions GetSpindulys = new PromptDoubleOptions("\nĮveskite didžiausio apskritimo spindulį");
            double Spindulys;
            GetSpindulys.AllowNegative = false;
            GetSpindulys.AllowZero = false;
            GetSpindulys.AllowZero = false;
            PromptDoubleResult GetSpindulysRezultatas = ed.GetDouble(GetSpindulys);
            Spindulys = GetSpindulysRezultatas.Value;

            PromptDoubleOptions GetPlotis = new PromptDoubleOptions("\nĮveskite apskirtimo spindulio mažėjimą");
            double Plotis;
            GetPlotis.AllowNegative = false;
            GetPlotis.AllowZero = false;
            GetPlotis.AllowZero = false;
            PromptDoubleResult GetPlotisRezultatas = ed.GetDouble(GetPlotis);
            Plotis = GetPlotisRezultatas.Value;

            PromptPointOptions GetTaskas = new PromptPointOptions("\nPasirinkite centro tašką");
            Point3d Taskas;
            GetTaskas.AllowNone = false;
            PromptPointResult GetTaskasRezultatas = ed.GetPoint(GetTaskas);
            Taskas = GetTaskasRezultatas.Value;

            Transaction tr = db.TransactionManager.StartTransaction();
            using (tr)
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                int i = 1;
                while(Spindulys > 0)
                {
                    Circle Apskritimas = new Circle(Taskas, new Vector3d(0, 0, 1), Spindulys);
                    btr.AppendEntity(Apskritimas);
                    tr.AddNewlyCreatedDBObject(Apskritimas, true);

                    Hatch hatch = new Hatch();
                    btr.AppendEntity(hatch);
                    tr.AddNewlyCreatedDBObject(hatch, true);

                    ObjectIdCollection ID = new ObjectIdCollection();
                    ID.Add(Apskritimas.ObjectId);
                    hatch.HatchStyle = HatchStyle.Ignore;
                    hatch.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                    hatch.Associative = true;
                    hatch.AppendLoop(HatchLoopTypes.Outermost, ID);
                    hatch.EvaluateHatch(true);
                    hatch.ColorIndex = i++;

                    Spindulys -= Plotis;
                }
                tr.Commit();
            }
        }
예제 #16
0
        public void Figura3()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.GetDocument(db);
            Editor ed = doc.Editor;

            PromptDoubleOptions GetSpindulys = new PromptDoubleOptions("\nĮveskite apskritimų spindulį");
            double Spindulys;
            GetSpindulys.AllowNegative = false;
            GetSpindulys.AllowZero = false;
            GetSpindulys.AllowNone = false;
            PromptDoubleResult GetSpindulysRezultatas = ed.GetDouble(GetSpindulys);
            Spindulys = GetSpindulysRezultatas.Value;

            PromptIntegerOptions GetKiekis = new PromptIntegerOptions("\nĮveskite apskritimų skaičių");
            int Kiekis;
            GetKiekis.AllowNegative = false;
            GetKiekis.AllowZero = false;
            GetSpindulys.AllowNone = false;
            PromptIntegerResult GetKiekisRezultatas = ed.GetInteger(GetKiekis);
            Kiekis = GetKiekisRezultatas.Value;

            PromptPointOptions GetTaskas = new PromptPointOptions("\nPasirinkite pradžios tašką");
            Point3d Taskas;
            GetTaskas.AllowNone = false;
            PromptPointResult GetTaskasRezultatas = ed.GetPoint(GetTaskas);
            Taskas = GetTaskasRezultatas.Value;
            Transaction tr = db.TransactionManager.StartTransaction();

            double kampas = 360 / Kiekis;
            double dabartiniskampas = 0;
            using (tr)
            {
                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                for (int j = 0; j < Kiekis; j++)
                {
                    dabartiniskampas += kampas;
                    Point3d beta = new Point3d(Taskas.X + Math.Sin(dabartiniskampas) * Spindulys, Taskas.Y + Math.Cos(dabartiniskampas) * Spindulys, 0);
                    Taskas = beta;
                    Circle Apskritimas = new Circle(Taskas , new Vector3d(0, 0, 1), Spindulys);
                    btr.AppendEntity(Apskritimas);
                    tr.AddNewlyCreatedDBObject(Apskritimas, true);
                }
                tr.Commit();
            }
        }
예제 #17
0
        public void TZWuCha()
        {
            int length = 100;


            TypedValue[] tv = new TypedValue[2] {
                new TypedValue((int)DxfCode.Start, "POLYLINE"), new TypedValue((int)DxfCode.Start, "DIMENSION")
            };

            SelectionFilter sf = new SelectionFilter(tv);

            //var selRes = Ed.GetSelection(sf);
            var selRes = Ed.GetSelection();

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

            var listIds = selRes.Value.GetObjectIds().ToList();


            List <Polyline>  listPl  = new List <Polyline>();
            List <Dimension> listDim = new List <Dimension>();

            using (var trans = Db.TransactionManager.StartTransaction())
            {
                foreach (ObjectId oId in listIds)
                {
                    var ent = trans.GetObject(oId, OpenMode.ForRead) as Entity;

                    if ((ent as Polyline) != null)
                    {
                        listPl.Add((Polyline)ent);
                    }
                    else if ((ent as Dimension) != null)
                    {
                        listDim.Add((Dimension)ent);
                    }
                }
                trans.Commit();
            }

            var propDbOpts = new PromptDoubleOptions("请输入误差范围:");

            var dbRes = Ed.GetDouble(propDbOpts);

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

            double lMin = length - dbRes.Value;
            double lMax = length + dbRes.Value;

            //Dictionary<Vector3d, double> dicVecDb = new Dictionary<Vector3d, double>();

            List <Vector3d> listVec3d = new List <Vector3d>();
            List <double>   listDis   = new List <double>();


            List <Point3d> ptArr = new List <Point3d>();

            Polyline plSF = null;
            Polyline plST = null;
            Polyline plSW = null;


            int indexSF = 0;
            int indexST = 0;
            int indexSW = 0;

            List <Polyline> listJoinPL = new List <Polyline>();

            //找到相连的pl组成一组加入到集合中
            foreach (var pl in listPl)
            {
                ptArr = Get4Pt(pl);
                if (ptArr.Count == 3)
                {
                    plST    = pl;
                    indexST = listPl.IndexOf(plST);
                    listJoinPL.Add(plST);
                    continue;
                }
                else if (ptArr.Count == 2)
                {
                    plSW    = pl;
                    indexSW = listPl.IndexOf(plSW);
                    listJoinPL.Add(plSW);
                    continue;
                }
                else if (ptArr.Count == 4)
                {
                    var listVec = new List <Vector3d>();
                    var listDb  = new List <double>();
                    for (int i = 0; i < ptArr.Count - 1; i++)
                    {
                        var ptF1 = ptArr[i];
                        var ptF2 = ptArr[i + 1];

                        var vecF = ptF2 - ptF1;

                        listVec.Add(vecF);
                        listDb.Add(Math.Round(vecF.Length, 3));
                    }


                    var v1 = listVec[0];
                    var v2 = listVec[1];
                    var v3 = listVec[2];


                    if (Math.Abs(listDb[listVec.IndexOf(v1)] - listDb[listVec.IndexOf(v3)]) > 2 * dbRes.Value)
                    {
                        plSF    = pl;
                        indexSF = listPl.IndexOf(plSF);
                        listJoinPL.Add(plSF);

                        continue;
                    }
                }
            }

            bool flag = false;


            List <int>      listInt    = new List <int>();
            List <Polyline> listMerged = new List <Polyline>();

            //if (plSW != null) listJoinPL.Add(plSW);
            //if (plST != null) listJoinPL.Add(plST);
            //if (plSF != null) listJoinPL.Add(plSF);


            if (listJoinPL.Count > 1)
            {
                using (var trans = Db.TransactionManager.StartTransaction())
                {
                    for (int j = 0; j < listJoinPL.Count; j++)
                    {
                        if (listInt.Contains(listPl.IndexOf(listJoinPL[j])))
                        {
                            continue;
                        }


                        var plJoin = trans.GetObject(listJoinPL[j].ObjectId, OpenMode.ForWrite) as Polyline;
                        listInt.Add(listPl.IndexOf(plJoin));
                        for (int i = j + 1; i < listJoinPL.Count; i++)
                        {
                            if (listInt.Contains(listPl.IndexOf(listJoinPL[i])))
                            {
                                continue;
                            }

                            var plJoin2 = trans.GetObject(listJoinPL[i].ObjectId, OpenMode.ForWrite) as Polyline;

                            try
                            {
                                plJoin.JoinEntity(plJoin2);
                                flag = true;
                                listInt.Add(listPl.IndexOf(plJoin2));
                            }
                            catch (System.Exception ex)
                            {
                                plJoin2.DowngradeOpen();

                                Ed.WriteMessage(ex.ToString());

                                continue;
                            }
                        }

                        if (flag)
                        {
                            listMerged.Add(plJoin);
                            flag = false;
                            plJoin.DowngradeOpen();
                        }
                    }
                    trans.Commit();
                }
            }
            listInt = listInt.Distinct().ToList();

            if (listInt.Count > 1)
            {
                for (int i = 0; i < listInt.Count; i++)
                {
                    listPl[listInt[i]] = null;
                }

                listPl = listPl.Where(p => p != null).ToList();
            }

            listPl.AddRange(listMerged);

            //listInt.Clear();
            listJoinPL.Clear();
            listMerged.Clear();



            /*if (plSF != null && plST != null)
             * {
             *
             *  using (var trans = Db.TransactionManager.StartTransaction())
             *  {
             *
             *      plST = trans.GetObject(plST.ObjectId, OpenMode.ForWrite) as Polyline;
             *      plSF = trans.GetObject(plSF.ObjectId, OpenMode.ForWrite) as Polyline;
             *
             *      try
             *      {
             *          plST.JoinEntity(plSF);
             *          flag = true;
             *
             *      }
             *      catch (System.Exception ex)
             *      {
             *
             *          flag = false;
             *          Ed.WriteMessage(ex.ToString());
             *      }
             *
             *      plST.DowngradeOpen();
             *      plSF.DowngradeOpen();
             *
             *      trans.Commit();
             *  }
             * }
             *
             * if (flag)
             * {
             *  listPl[indexST] = plST;
             *  listPl.RemoveAt(indexSF);
             *  flag = false;
             *  indexST = 0;
             *  indexSF = 0;
             * }*/



            //分点的个数分别处理
            foreach (Polyline pl in listPl)
            {
                //dicVecDb.Clear();
                listVec3d.Clear();
                listDis.Clear();
                ptArr.Clear();


                ptArr = Get4Pt(pl);

                if (ptArr.Count == 5 && !pl.Closed && ptArr[0] != ptArr[4])
                {
                    ptArr = ptArr.Distinct(new PointCompare()).ToList();
                }

                if (ptArr.Count == 5)
                {
                    Vector3d v1 = ptArr[1] - ptArr[0];
                    Vector3d v2 = ptArr[2] - ptArr[1];
                    Vector3d v3 = ptArr[3] - ptArr[2];
                    Vector3d v4 = ptArr[4] - ptArr[3];

                    //dicVecDb.Add(v1, Math.Round(v1.Length, 3));
                    //dicVecDb.Add(v2, Math.Round(v2.Length, 3));
                    //dicVecDb.Add(v3, Math.Round(v3.Length, 3));
                    //dicVecDb.Add(v4, Math.Round(v4.Length, 3));

                    listVec3d.Add(v1);
                    listVec3d.Add(v2);
                    listVec3d.Add(v3);
                    listVec3d.Add(v4);

                    listDis.Add(Math.Round(v1.Length, 3));
                    listDis.Add(Math.Round(v2.Length, 3));
                    listDis.Add(Math.Round(v3.Length, 3));
                    listDis.Add(Math.Round(v4.Length, 3));


                    double v1agl = Math.Abs(v1.GetAngleTo(v2) - Math.PI / 2);
                    double v3agl = Math.Abs(v2.GetAngleTo(v3) - Math.PI / 2);
                    double v4agl = Math.Abs(v1.GetAngleTo(v4) - Math.PI / 2);

                    int indexPt1 = 0;
                    int indexPt2 = 0;
                    //求有问题得点
                    //v1不是需要计算的误差
                    if (listDis[listVec3d.IndexOf(v1)] > lMax || listDis[listVec3d.IndexOf(v1)] < lMin)
                    //if (dicVecDb[v1] > lMax || dicVecDb[v1] < lMin)
                    {
                        var v2Db = Math.Abs(length - listDis[listVec3d.IndexOf(v2)]);
                        var v4Db = Math.Abs(length - listDis[listVec3d.IndexOf(v4)]);
                        if (listDis[listVec3d.IndexOf(v1)] < listDis[listVec3d.IndexOf(v3)] || v1agl < v3agl)
                        //if (dicVecDb[v1] < dicVecDb[v3] || v1agl < v3agl)
                        {
                            if (v2Db > v4Db)
                            {
                                indexPt1 = 1;
                                indexPt2 = 2;
                            }
                            else
                            {
                                indexPt1 = 4;
                                indexPt2 = 3;
                            }
                        }
                        else
                        {
                            if (v2Db > v4Db)
                            {
                                indexPt1 = 2;
                                indexPt2 = 1;
                            }
                            else
                            {
                                indexPt1 = 3;
                                indexPt2 = 4;
                            }
                        }
                    }
                    else
                    {
                        var v1Db = Math.Abs(length - listDis[listVec3d.IndexOf(v1)]);
                        var v3Db = Math.Abs(length - listDis[listVec3d.IndexOf(v3)]);

                        //if (dicVecDb[v2] < dicVecDb[v4] || v1agl < v4agl)
                        if (listDis[listVec3d.IndexOf(v2)] < listDis[listVec3d.IndexOf(v4)] || v1agl < v4agl)
                        {
                            if (v1Db > v3Db)
                            {
                                indexPt1 = 1;
                                indexPt2 = 0;
                            }
                            else
                            {
                                indexPt1 = 2;
                                indexPt2 = 3;
                            }
                        }
                        else
                        {
                            if (v1Db > v3Db)
                            {
                                indexPt1 = 0;
                                indexPt2 = 1;
                            }
                            else
                            {
                                indexPt1 = 3;
                                indexPt2 = 2;
                            }
                        }
                    }

                    var pt1     = ptArr[indexPt1];
                    var wrongPt = ptArr[indexPt2];

                    var vec = (wrongPt - pt1).GetNormal();

                    var jzPt = pt1 + vec * length;

                    ptArr[indexPt2] = jzPt;

                    if (indexPt2 == 4)
                    {
                        ptArr[0] = jzPt;
                    }

                    DimToSpace(ptArr, listDim, pt1, wrongPt, indexPt2);

                    //Ed.WriteMessage($"{v1.Length}\n,{v2.Length}\n{v3.Length}\n{v4.Length}\n");
                    //Ed.WriteMessage($"{v1.GetAngleTo(v2) * 180 / Math.PI}\n");
                    //Ed.WriteMessage($"{v2.GetAngleTo(v3) * 180 / Math.PI}\n");
                    //Ed.WriteMessage($"{v3.GetAngleTo(v4) * 180 / Math.PI}\n");
                    //Ed.WriteMessage($"{v4.GetAngleTo(v1) * 180 / Math.PI}\n");
                }
                else if (ptArr.Count == 4 && !pl.Closed)
                {
                    for (int i = 0; i < ptArr.Count - 1; i++)
                    {
                        var ptF1 = ptArr[i];
                        var ptF2 = ptArr[i + 1];

                        var vecF = ptF2 - ptF1;

                        //dicVecDb.Add(vecF, Math.Round(vecF.Length, 3));

                        listVec3d.Add(vecF);
                        listDis.Add(Math.Round(vecF.Length, 3));
                    }

                    var v1 = listVec3d[0];
                    var v2 = listVec3d[1];
                    var v3 = listVec3d[2];
                    var v4 = ptArr[0] - ptArr[3];

                    double v1agl = Math.Abs(v1.GetAngleTo(v2) - Math.PI / 2);
                    double v4agl = Math.Abs(v1.GetAngleTo(v4) - Math.PI / 2);

                    int indexPt1 = 0;
                    int indexPt2 = 0;

                    double diffV1 = Math.Abs(dbRes.Value - Math.Abs(length - listDis[listVec3d.IndexOf(v1)]));
                    double diffV3 = Math.Abs(dbRes.Value - Math.Abs(length - listDis[listVec3d.IndexOf(v3)]));
                    if (diffV1 < diffV3)
                    {
                        if (v1.X > 0)
                        {
                            indexPt1 = 0;
                            indexPt2 = 1;
                        }
                        else
                        {
                            indexPt1 = 1;
                            indexPt2 = 0;
                        }
                    }
                    else if (diffV1 >= diffV3)
                    {
                        if (v3.X > 0)
                        {
                            indexPt1 = 2;
                            indexPt2 = 3;
                        }
                        else
                        {
                            indexPt1 = 3;
                            indexPt2 = 2;
                        }
                    }
                    var pt1     = ptArr[indexPt1];
                    var wrongPt = ptArr[indexPt2];

                    var vec = (wrongPt - pt1).GetNormal();

                    var jzPt = pt1 + vec * length;

                    ptArr[indexPt2] = jzPt;



                    //这里单独弄个方法
                    DimToSpace(ptArr, listDim, pt1, wrongPt, indexPt2);
                }
                else if (ptArr.Count == 6 && !pl.Closed)
                {
                    Vector3d v1 = ptArr[2] - ptArr[1];
                    Vector3d v2 = ptArr[3] - ptArr[2];
                    Vector3d v3 = ptArr[4] - ptArr[3];
                    Vector3d v4 = ptArr[4] - ptArr[1];
                    Vector3d v5 = ptArr[0] - ptArr[1];
                    Vector3d v6 = ptArr[4] - ptArr[5];
                    //dicVecDb.Add(v1, Math.Round(v1.Length, 3));
                    //dicVecDb.Add(v2, Math.Round(v2.Length, 3));
                    //dicVecDb.Add(v3, Math.Round(v3.Length, 3));
                    //dicVecDb.Add(v4, Math.Round(v4.Length, 3));
                    //dicVecDb.Add(v5, Math.Round(v5.Length, 3));
                    //dicVecDb.Add(v6, Math.Round(v6.Length, 3));

                    listVec3d.Add(v1);
                    listVec3d.Add(v2);
                    listVec3d.Add(v3);
                    listVec3d.Add(v4);
                    listVec3d.Add(v5);
                    listVec3d.Add(v6);

                    listDis.Add(Math.Round(v1.Length, 3));
                    listDis.Add(Math.Round(v2.Length, 3));
                    listDis.Add(Math.Round(v3.Length, 3));
                    listDis.Add(Math.Round(v4.Length, 3));
                    listDis.Add(Math.Round(v5.Length, 3));
                    listDis.Add(Math.Round(v6.Length, 3));



                    double v1agl    = Math.Abs(v1.GetAngleTo(v2) - Math.PI / 2);
                    double v3agl    = Math.Abs(v2.GetAngleTo(v3) - Math.PI / 2);
                    double v4agl    = Math.Abs(v1.GetAngleTo(v4) - Math.PI / 2);
                    int    indexPt1 = 0;
                    int    indexPt2 = 0;


                    for (int m = 0; m <= 3; m++)
                    {
                        //求有问题得点
                        //v1 不是要求误差的边
                        if (listDis[m] >= lMax || listDis[m] <= lMin)
                        {
                            var v2Db = Math.Abs(length - listDis[(m + 1) % 2]);
                            var v4Db = Math.Abs(length - listDis[(m + 3) % 2 + 2]);
                            if (listDis[m] < listDis[(m + 2) % 2] || v1agl < v3agl)
                            {
                                if (v2Db > v4Db)
                                {
                                    indexPt1 = 2;
                                    indexPt2 = 3;
                                }
                                else
                                {
                                    indexPt1 = 1;
                                    indexPt2 = 4;
                                }
                            }
                            else
                            {
                                if (v2Db > v4Db)
                                {
                                    indexPt1 = 3;
                                    indexPt2 = 2;
                                }
                                else
                                {
                                    indexPt1 = 4;
                                    indexPt2 = 1;
                                }
                            }
                        }
                        else
                        {
                            var v1Db = Math.Abs(length - listDis[m]);
                            var v3Db = Math.Abs(length - listDis[m + 2]);
                            if (listDis[(m + 1) % 2] < listDis[(m + 3) % 2 + 2] || v1agl < v4agl)
                            {
                                if (v1Db > v3Db)
                                {
                                    indexPt1 = 2;
                                    indexPt2 = 1;
                                }
                                else
                                {
                                    indexPt1 = 3;
                                    indexPt2 = 4;
                                }
                            }
                            else
                            {
                                if (v1Db > v3Db)
                                {
                                    indexPt1 = 1;
                                    indexPt2 = 2;
                                }
                                else
                                {
                                    indexPt1 = 4;
                                    indexPt2 = 3;
                                }
                            }
                        }
                        var wrongPt = Point3d.Origin;
                        var pt1     = Point3d.Origin;
                        if (!((indexPt1 == 1 && indexPt2 == 4) && (indexPt1 == 4 && indexPt2 == 1)))
                        {
                            pt1     = ptArr[indexPt1];
                            wrongPt = ptArr[indexPt2];

                            var vec1 = wrongPt - pt1;
                            var vec2 = pt1 - wrongPt;

                            int index = -1;

                            if (listVec3d.IndexOf(vec1) != -1)
                            {
                                index = listVec3d.IndexOf(vec1);
                            }
                            else if (listVec3d.IndexOf(vec2) != -1)
                            {
                                index = listVec3d.IndexOf(vec2);
                            }


                            var vec = (wrongPt - pt1).GetNormal();

                            var jzPt = pt1 + vec * length;

                            ptArr[indexPt2] = jzPt;

                            if (index != -1)
                            {
                                listVec3d[index] = pt1 - jzPt;
                                listDis[index]   = (pt1 - jzPt).Length;
                            }
                        }
                        else
                        {
                            if (indexPt1 == 1 && indexPt2 == 4)
                            {
                                wrongPt = ptArr[indexPt2];
                                var ptSpecial = ptArr[indexPt1];
                                var vec1      = wrongPt - ptSpecial;
                                var vec2      = ptSpecial - wrongPt;

                                if (ptArr[0].Y < ptArr[5].Y || ptArr[0].X < ptArr[5].X)
                                {
                                    pt1 = ptArr[0];
                                }
                                else
                                {
                                    pt1 = ptArr[5];
                                }



                                var vec = wrongPt - pt1;


                                int index = -1;

                                if (listVec3d.IndexOf(vec1) != -1)
                                {
                                    index = listVec3d.IndexOf(vec1);
                                }
                                else if (listVec3d.IndexOf(vec2) != -1)
                                {
                                    index = listVec3d.IndexOf(vec2);
                                }

                                var jzPt = pt1 + vec.GetNormal() * (vec.Length + dbRes.Value);

                                ptArr[indexPt2] = jzPt;

                                if (index != -1)
                                {
                                    listVec3d[index] = ptSpecial - jzPt;
                                    listDis[index]   = (ptSpecial - jzPt).Length;
                                }
                            }
                            if (indexPt1 == 4 && indexPt2 == 1)
                            {
                                wrongPt = ptArr[indexPt2];
                                var ptSpecial = ptArr[indexPt1];
                                var vec1      = wrongPt - ptSpecial;
                                var vec2      = ptSpecial - wrongPt;

                                if (ptArr[0].Y < ptArr[5].Y || ptArr[0].X < ptArr[5].X)
                                {
                                    pt1 = ptArr[5];
                                }
                                else
                                {
                                    pt1 = ptArr[0];
                                }

                                int index = -1;

                                if (listVec3d.IndexOf(vec1) != -1)
                                {
                                    index = listVec3d.IndexOf(vec1);
                                }
                                else if (listVec3d.IndexOf(vec2) != -1)
                                {
                                    index = listVec3d.IndexOf(vec2);
                                }

                                var vec = wrongPt - pt1;

                                var jzPt = pt1 + vec.GetNormal() * (vec.Length + dbRes.Value);

                                ptArr[indexPt2] = jzPt;

                                if (index != -1)
                                {
                                    listVec3d[index] = ptSpecial - jzPt;
                                    listDis[index]   = (ptSpecial - jzPt).Length;
                                }
                            }
                        }

                        if (!((indexPt1 == 1 && indexPt2 == 4) && (indexPt1 == 4 && indexPt2 == 1)))
                        {
                            DimToSpace(ptArr, listDim, pt1, wrongPt, indexPt2);
                        }
                        else
                        {
                            if (indexPt1 == 1 && indexPt2 == 4)
                            {
                                DimToSpace2(ptArr, listDim, ptArr[1], wrongPt, indexPt2);
                            }
                            if (indexPt1 == 4 && indexPt2 == 1)
                            {
                                DimToSpace2(ptArr, listDim, ptArr[4], wrongPt, indexPt2);
                            }
                        }
                    }
                }

                Polyline plJz2 = new Polyline();

                foreach (var point in ptArr)
                {
                    plJz2.AddVertexAt(plJz2.NumberOfVertices, new Point2d(point.X, point.Y), 0, 0, 0);
                }

                //plJz.TransformBy(Matrix3d.Displacement(Vector3d.ZAxis * 100));
                plJz2.ColorIndex = 6;

                Pl2Pl(plJz2, pl);

                plJz2.ToSpace();

                using (var trans = Db.TransactionManager.StartTransaction())
                {
                    var ent2 = trans.GetObject(pl.ObjectId, OpenMode.ForWrite) as Entity;

                    ent2.Erase(true);

                    trans.Commit();
                }
            }


            /* if (plSF != null && plST != null)
             * {
             *
             *   using (var trans = Db.TransactionManager.StartTransaction())
             *   {
             *
             *       plST = trans.GetObject(plST.ObjectId, OpenMode.ForWrite) as Polyline;
             *       plSF = trans.GetObject(plSF.ObjectId, OpenMode.ForWrite) as Polyline;
             *
             *       plST.JoinEntity(plSF);
             *
             *       plST.DowngradeOpen();
             *       plSF.DowngradeOpen();
             *
             *       trans.Commit();
             *   }
             * }
             */
        }
예제 #18
0
        public static void LArrow()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor   ed  = doc.Editor;

            PromptDoubleOptions optDouble = new PromptDoubleOptions("\n请输入箭头长度:");

            optDouble.AllowNone       = true;
            optDouble.AllowZero       = false;
            optDouble.DefaultValue    = ArrowLength;
            optDouble.UseDefaultValue = true;

            PromptDoubleResult resDouble = ed.GetDouble(optDouble);

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

            ArrowLength = resDouble.Value;

            PromptPointResult res1 = ed.GetPoint("\n请输入起点:");

            if (res1.Status == PromptStatus.OK)
            {
                PromptPointOptions opts = new PromptPointOptions("\n请输入终点:");
                //实现类似jig的操作
                opts.BasePoint    = res1.Value;
                opts.UseBasePoint = true;

                PromptPointResult res2 = ed.GetPoint(opts);
                if (res2.Status == PromptStatus.OK)
                {
                    Database db = doc.Database;
                    using (Transaction tr = db.TransactionManager.StartTransaction())
                    {
                        BlockTableRecord btr =
                            (BlockTableRecord)tr.GetObject(
                                db.CurrentSpaceId,
                                OpenMode.ForWrite,
                                false);
                        Line line = new Line(res1.Value, res2.Value);
                        btr.AppendEntity(line);
                        tr.AddNewlyCreatedDBObject(line, true);
                        RegAppTable rat =
                            (RegAppTable)tr.GetObject(
                                db.RegAppTableId,
                                OpenMode.ForRead,
                                false);
                        if (!rat.Has(RegAppName))
                        {
                            rat.UpgradeOpen();
                            RegAppTableRecord regapp = new RegAppTableRecord();
                            regapp.Name = RegAppName;
                            rat.Add(regapp);
                            tr.AddNewlyCreatedDBObject(regapp, true);
                        }
                        SetTo(line);
                        tr.Commit();
                    }
                }
            }
        }
예제 #19
0
        public void fJETFAN()
        {
            Editor ed = acApp.DocumentManager.MdiActiveDocument.Editor;

            try
            {
                Utils.Utils.Init();

                // Get zMin & zMax | height level
                PromptDoubleOptions zMinO = new PromptDoubleOptions("\nEnter Z-min level:");
                zMinO.DefaultValue = zMinOld;
                PromptDoubleResult zMin = ed.GetDouble(zMinO);
                if (zMin.Status != PromptStatus.OK)
                {
                    Utils.Utils.End(); return;
                }
                zMinOld = zMin.Value;
                Utils.Utils.SetUCS(zMin.Value);

                double             height;
                PromptDoubleResult zMax;
                PromptDoubleResult heightResult;
                // Enter Z-max (and check if > Z-min) or Height
                while (true)
                {
                    PromptDoubleOptions zMaxO = new PromptDoubleOptions("\nEnter Z-max level or ");
                    zMaxO.Keywords.Add("Height");
                    zMaxO.DefaultValue = zMaxOld;
                    zMax = ed.GetDouble(zMaxO);
                    if (zMax.Status == PromptStatus.Keyword && zMax.StringResult == "Height")
                    {
                        PromptDoubleOptions heightO = new PromptDoubleOptions("\nEnter height:");
                        heightO.DefaultValue  = heightOld;
                        heightO.AllowNone     = false;
                        heightO.AllowZero     = false;
                        heightO.AllowNegative = false;
                        heightResult          = ed.GetDouble(heightO);
                        if (heightResult.Status == PromptStatus.OK)
                        {
                            height    = heightResult.Value;
                            heightOld = heightResult.Value;
                            break;
                        }
                    }
                    else if (zMax.Status != PromptStatus.OK)
                    {
                        Utils.Utils.End(); return;
                    }
                    else if (zMax.Value <= zMin.Value)
                    {
                        ed.WriteMessage("\nZ-max level should be greater than Z-min level");
                    }
                    else
                    {
                        zMaxOld = zMax.Value;
                        height  = zMax.Value - zMin.Value;
                        break;
                    }
                }

                while (true)
                {
                    if (!Utils.Layers.CurrentLayer().Contains("!FDS_JETF"))
                    {
                        Utils.Layers.SetLayer("!FDS_JETF[jetfan]");
                    }

                    PromptPointOptions p1Option = new PromptPointOptions("\nSpecify jet-fan first corner:");
                    p1Option.AllowNone = false;
                    PromptPointResult p1 = ed.GetPoint(p1Option);
                    if (p1.Status != PromptStatus.OK || p1.Status == PromptStatus.Cancel)
                    {
                        break;
                    }

                    var p2 = ed.GetUcsCorner("Pick jet-fan opposite corner:", p1.Value);
                    if (p2.Status != PromptStatus.OK || p2.Status == PromptStatus.Cancel)
                    {
                        break;
                    }

                    ObjectId jetObstId = Utils.Utils.CreateBox(p1.Value, p2.Value, height, zMin.Value, true);

                    Document  acDoc   = acApp.DocumentManager.MdiActiveDocument;
                    Database  acCurDb = acDoc.Database;
                    Extents3d jetExt;
                    using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                    {
                        Entity acEnt = acTrans.GetObject(jetObstId, OpenMode.ForRead) as Entity;
                        jetExt = acEnt.GeometricExtents;
                    }

                    PromptPointOptions p1DirO = new PromptPointOptions("\nSpecify jet-fan direction");
                    p1DirO.AllowNone = false;
                    PromptPointResult p1Dir = ed.GetPoint(p1DirO);
                    if (p1Dir.Status != PromptStatus.OK || p1Dir.Status == PromptStatus.Cancel)
                    {
                        break;
                    }

                    Point3d center = new Point3d(jetExt.MinPoint.X + (jetExt.MaxPoint.X - jetExt.MinPoint.X) / 2, jetExt.MinPoint.Y + (jetExt.MaxPoint.Y - jetExt.MinPoint.Y) / 2, jetExt.MinPoint.Z);
                    ed.WriteMessage(center.ToString());
                    // Tutaj tworzenie polilinii + xdata kierunek ...
                    // Po X jet-fan
                    if (Math.Abs(jetExt.MaxPoint.X - jetExt.MinPoint.X) > Math.Abs(jetExt.MaxPoint.Y - jetExt.MinPoint.Y))
                    {
                        if (p1Dir.Value.X < jetExt.MinPoint.X)
                        {
                            Utils.Xdata.SaveXdata(AddJetfanDirection(center, "-x").ToString(), jetObstId);
                        }
                        else
                        {
                            Utils.Xdata.SaveXdata(AddJetfanDirection(center, "+x").ToString(), jetObstId);
                        }
                    }
                    // Po Y jet-fan
                    else
                    {
                        if (p1Dir.Value.Y < jetExt.MinPoint.Y)
                        {
                            Utils.Xdata.SaveXdata(AddJetfanDirection(center, "-y").ToString(), jetObstId);
                        }
                        else
                        {
                            Utils.Xdata.SaveXdata(AddJetfanDirection(center, "+y").ToString(), jetObstId);
                        }
                    }
                }
                Utils.Utils.End();
            }
            catch (System.Exception e)
            {
                ed.WriteMessage("\nProgram exception: " + e.ToString());
                Utils.Utils.End();
            }
        }
        public void GetIntersectionsRiver()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Autodesk.AutoCAD.ApplicationServices.Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Transaction tr = db.TransactionManager.StartTransaction();

            #region For Word
            string filepath = "D:\\intersections_rivers.docx";

            using (WordprocessingDocument docX = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                try
                {
                    // Add a main document part.
                    MainDocumentPart mainPart = docX.AddMainDocumentPart();
                    StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>();
                    Styles styles1 = new Styles();
                    DocDefaults docDefaults =
                        new DocDefaults(
                            new RunPropertiesDefault(new RunPropertiesBaseStyle(new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            }, new FontSize() { Val = "24" },
                                new FontSizeComplexScript() { Val = "24" })),
                                new ParagraphPropertiesDefault(new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto }));
                    styles1.AppendChild(docDefaults);
                    styleDefinitionsPart.Styles = styles1;

                    mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                    DocumentFormat.OpenXml.Wordprocessing.Body body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body());
                    ParagraphProperties paragraphProperties1 = new ParagraphProperties(
                        new Justification() { Val = JustificationValues.Center },
                        new ParagraphMarkRunProperties(
                            new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            },
                            new FontSize() { Val = "24" },
                            new FontSizeComplexScript() { Val = "24" }
                            ));

                    Paragraph para = body.AppendChild(new Paragraph());
                    para.AppendChild(paragraphProperties1);

                    Run run = para.AppendChild(new Run());

                    RunProperties runProperties1 = new RunProperties(
                        new Bold());

                    // String msg contains the text, "Hello, Word!"
                    run.AppendChild(runProperties1);
                    run.AppendChild(new Text("ПРИЛОЖЕНИЕ"));
                    run.AppendChild(new Break());
                    run.AppendChild(new Text("Ведомость пересечений"));
                    run.AppendChild(new Break());

                    var table = new DocumentFormat.OpenXml.Wordprocessing.Table();
                    // Create a TableProperties object and specify its border information.
                    TableProperties tblProp = new TableProperties(
                        new TableWidth() { Width = "9782", Type = TableWidthUnitValues.Dxa },
                        new TableIndentation() { Width = -318, Type = TableWidthUnitValues.Dxa },
                        new TableBorders(
                            new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }),
                        new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" }
                        );

                    // Append the TableProperties object to the empty table.
                    table.AppendChild<TableProperties>(tblProp);

                    // Add 3 columns to the table.
                    TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(),
                         new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn());
                    table.AppendChild(tg);

                    TableRow tr1 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 430 }),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1709" },
                                new VerticalMerge() { Val = MergedCellValues.Restart },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Наимен. водотока")))),
                        //new TableCellProperties(new TableCellWidth() {Type = TableWidthUnitValues.Pct, Width = "500"})
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 2 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "3922" }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Пикетное положение пересечения")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Ширина водотока в межень")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1358" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new VerticalMerge() { Val = MergedCellValues.Restart }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Глуб. водотока")))),
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 3 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2368" }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Горизонт воды")))),
                        new TableCell(new TableCellProperties(
                            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "425" },
                            new VerticalMerge() { Val = MergedCellValues.Restart },
                            new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Прим."))))
                        );
                    table.AppendChild(tr1);
                    TableRow tr2 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 419 }),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("От")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("До")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("половодье")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1260" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Дата съемки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("На день съемки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Макс.")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())));
                    table.AppendChild(tr2);

                    TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = 9 });
            #endregion

                    while (true)
                    {

                        //using (tr)
                        //{
                        try
                        {
                            #region Поиск пересечений
                            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                            PromptEntityOptions peo = new PromptEntityOptions("\nВыбери polyline  >>");
                            peo.SetRejectMessage("\nМожно только polyline >>");
                            peo.AddAllowedClass(typeof(Polyline), false);
                            PromptEntityResult res;
                            res = ed.GetEntity(peo);
                            if (res.Status != PromptStatus.OK)
                            {
                                break;
                            }
                            DBObject ent = (DBObject)tr.GetObject(res.ObjectId, OpenMode.ForRead);
                            if (ent == null) return;

                            PromptPointResult pPtRes;
                            PromptPointOptions pPtOpts = new PromptPointOptions("");
                            // Prompt for the start point
                            pPtOpts.Message = "\nВведи начало: ";
                            pPtRes = doc.Editor.GetPoint(pPtOpts);

                            PromptDoubleOptions getpik = new PromptDoubleOptions("\nВведи пикетаж (в формате числа, а не 0+00): ");
                            PromptDoubleResult getpikRes = doc.Editor.GetDouble(getpik);

                            //zoom
                            /*PromptEntityResult per = ed.GetEntity(peo);

                            if (per.Status != PromptStatus.OK)
                                return;*/

                            // Extract its extents

                            Extents3d ext;

                            Transaction trans = db.TransactionManager.StartTransaction();
                            using (trans)
                            {
                                Entity enti = (Entity)trans.GetObject(res.ObjectId, OpenMode.ForRead);
                                ext = enti.GeometricExtents;
                                trans.Commit();
                            }

                            ext.TransformBy(ed.CurrentUserCoordinateSystem.Inverse());

                            ZoomWin(ed, ext.MinPoint, ext.MaxPoint);
                            //

                            //Polyline poly = (Polyline)ent as Polyline;
                            Curve curv = ent as Curve;

                            DBObjectCollection pcurves = new DBObjectCollection();

                            curv.Explode(pcurves);
                            TypedValue[] values = new TypedValue[]
                     {
                        new TypedValue(0, "lwpolyline")
                        //might be added layer name to select curve:
                        //, new TypedValue(8, "mylayer")
                     };
                            SelectionFilter filter = new SelectionFilter(values);

                            Point3dCollection fence = new Point3dCollection();

                            double leng = curv.GetDistanceAtParameter(curv.EndParam) - curv.GetDistanceAtParameter(curv.StartParam);
                            // number of divisions along polyline to create fence selection
                            double step = leng / 256;// set number of steps to your suit

                            int num = Convert.ToInt32(leng / step);

                            for (int i = 0; i < num; i++)
                            {
                                Point3d pp = curv.GetPointAtDist(step * i);

                                fence.Add(curv.GetClosestPointTo(pp, false));
                            }

                            PromptSelectionResult selres = ed.SelectFence(fence, filter);

                            if (selres.Status != PromptStatus.OK) return;
                            Point3dCollection intpts = new Point3dCollection();

                            DBObjectCollection qcurves = new DBObjectCollection();
                            //ed.WriteMessage("\nCheck");
                            foreach (SelectedObject selobj in selres.Value)
                            {
                                DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForRead, false) as DBObject;
                                if (selobj.ObjectId != curv.ObjectId)
                                {
                                    DBObjectCollection icurves = new DBObjectCollection();
                                    Curve icurv = obj as Curve;
                                    icurv.Explode(icurves);
                                    foreach (DBObject dbo in icurves)
                                    {
                                        if (!qcurves.Contains(dbo))
                                            qcurves.Add(dbo);
                                    }
                                }

                            }
                            //ed.WriteMessage("\n{0}", qcurves.Count);

                            int j = 0;
                            Point3dCollection polypts = new Point3dCollection();

                            for (int i = 0; i < pcurves.Count; ++i)
                            {
                                for (j = 0; j < qcurves.Count; ++j)
                                {
                                    Curve curve1 = pcurves[i] as Curve;

                                    Curve curve2 = qcurves[j] as Curve;

                                    Point3dCollection pts = new Point3dCollection();

                                    curve1.IntersectWith(curve2, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero);

                                    foreach (Point3d pt in pts)
                                    {
                                        if (!polypts.Contains(pt))
                                            polypts.Add(pt);
                                    }
                                }
                            }
                            #endregion

                            try
                            {
                                using (Transaction tran = db.TransactionManager.StartTransaction())
                                {
                                    Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                    table.AppendChild(new TableRow(
                                        new TableCell(
                                            new TableCellProperties(
                                                new GridSpan() { Val = 9 }),
                                                new Paragraph(
                                                    new ParagraphProperties(
                                                        new ParagraphMarkRunProperties(new Bold()),
                                                        new Justification() { Val = JustificationValues.Center }),
                                                        new Run(new RunProperties(
                                                            new Bold()),
                                                            new Text("ПК" + ((int)(getpikRes.Value)).ToString("F0") + "-ПК" +
                                                                ((int)(100 * getpikRes.Value + pline.Length) / 100).ToString("F0") + "+" +
                                                                ((100 * getpikRes.Value + pline.Length) % 100).ToString("F")))))));
                                }
                            }
                            catch { ed.WriteMessage("\nError."); }

                            Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("osmode", 0);// optional
                            // for debug only
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format("\nНайдено пересечений: {0}", polypts.Count));

                            if (polypts.Count == 0)
                            {
                                try
                                {
                                    using (Transaction tran = db.TransactionManager.StartTransaction())
                                    {
                                        Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                        table.AppendChild(new TableRow(
                                            new TableCell(
                                                new TableCellProperties(
                                                    new GridSpan() { Val = 9 }),
                                                    new Paragraph(
                                                        new ParagraphProperties(
                                                            new Justification() { Val = JustificationValues.Center }),
                                                            new Run(new Text("На данном участке трассы пересечения отсутствуют"))))));
                                    }
                                }
                                catch { ed.WriteMessage("\nError."); }
                            }
                            else
                            {
                                //List<double> pik = new List<double>(polypts.Count);
                                double[] pik = new double[polypts.Count];
                                int numInter = 0;

                                foreach (Point3d inspt in polypts)
                                {
                                    double dist = 0;
                                    dist = 100 * getpikRes.Value;

                                    // test for visulization only
                                    /*Circle circ = new Circle(inspt, Vector3d.ZAxis, 10 * db.Dimtxt);
                                    circ.ColorIndex = 1;
                                    btr.AppendEntity(circ);
                                    tr.AddNewlyCreatedDBObject(circ, true);*/

                                    Point3d curr = pPtRes.Value, next = pPtRes.Value;
                                    try
                                    {
                                        using (Transaction tran = db.TransactionManager.StartTransaction())
                                        {
                                            Polyline pline = (Polyline)tran.GetObject(res.ObjectId, OpenMode.ForRead);
                                            if ((pPtRes.Value == pline.GetLineSegmentAt(0).StartPoint) || (pPtRes.Value == pline.GetLineSegmentAt(0).EndPoint))
                                                for (int i = 0; i < pline.NumberOfVertices - 2; i++)
                                                {
                                                    LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                                    LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                                    double angle = GetPolylineShape(l1, l2, pline.Normal);
                                                    if (angle > Math.PI)
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }
                                                    else
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }

                                                    if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1)
                                                    {
                                                        dist += inspt.DistanceTo(curr);
                                                        ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n");
                                                        break;
                                                    }
                                                    else
                                                        dist += curr.DistanceTo(next);

                                                    curr = next;
                                                }
                                            else
                                                for (int i = pline.NumberOfVertices - 3; i >= 0; i--)
                                                {
                                                    LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                                    LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                                    double angle = GetPolylineShape(l1, l2, pline.Normal);
                                                    if (angle > Math.PI)
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }
                                                    else
                                                    {
                                                        if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                                            next = l1.StartPoint;
                                                        else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                                            next = l1.EndPoint;
                                                    }

                                                    if (Math.Abs(inspt.DistanceTo(curr) + inspt.DistanceTo(next) - curr.DistanceTo(next)) < 1)
                                                    {
                                                        dist += inspt.DistanceTo(curr);
                                                        ed.WriteMessage(((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F") + "\n");
                                                        break;
                                                    }
                                                    else
                                                        dist += curr.DistanceTo(next);

                                                    curr = next;
                                                }
                                        }
                                    }
                                    catch
                                    {
                                        ed.WriteMessage("\nInvalid polyline.");
                                    }
                                    pik[numInter] = dist;
                                    numInter++;
                                    //ed.WriteMessage(" {0:0.00}\n", dist);
                                }

                                //pik.Sort();

                                Array.Sort(pik);

                                for (int i = 0; i < polypts.Count; i++)
                                {
                                    tr1 = new TableRow(
                                        new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(
                                                new TableCellProperties(
                                                    new GridSpan() { Val = 2 }),
                                                    new Paragraph(
                                                        new ParagraphProperties(
                                                            new Justification() { Val = JustificationValues.Center }),
                                                            new Run(new Text(((int)pik[i] / 100).ToString("F0") + "+" + (pik[i] % 100).ToString("F"))))),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run())),
                                        new TableCell(new Paragraph(new Run()))
                                        );
                                    table.AppendChild(tr1);
                                }
                            }

                        }
                        catch
                        {
                            ed.WriteMessage("\nError");
                        }
                        //}
                    }

                    tr.Commit();

                    body.AppendChild(table);
                    body.AppendChild(
                        new SectionProperties(
                            new PageMargin()
                            {
                                Top = 1134,
                                Right = (UInt32Value)850U,
                                Bottom = 1134,
                                Left = (UInt32Value)1418U,
                                Header = (UInt32Value)708U,
                                Footer = (UInt32Value)708U,
                                Gutter = (UInt32Value)0U
                            }));
                    ed.WriteMessage("\nДокумент сохранен в D:\\intersections_rivers.docx");
                }
                catch
                {
                    ed.WriteMessage("\nError.");
                }
            }
        }
예제 #21
0
        public void fVENT()
        {
            Editor ed = acApp.DocumentManager.MdiActiveDocument.Editor;

            try
            {
                Utils.Utils.Init();
                if (!Utils.Layers.CurrentLayer().Contains("!FDS_VENT"))
                {
                    Utils.Layers.SetLayerType("!FDS_VENT");
                }

                while (true)
                {
                    PromptKeywordOptions orientationOptions = new PromptKeywordOptions("\nChoose vent orientation");
                    orientationOptions.Keywords.Add("Horizontal");
                    orientationOptions.Keywords.Add("Vertical");
                    orientationOptions.AllowNone = false;
                    PromptResult orientation = ed.GetKeywords(orientationOptions);

                    if (orientation.Status != PromptStatus.OK || orientation.Status == PromptStatus.Cancel)
                    {
                        Utils.Utils.End(); break;
                    }
                    if (orientation.Status == PromptStatus.OK)
                    {
                        if (orientation.StringResult == "Vertical")
                        {
                            while (true)
                            {
                                PromptDoubleOptions zMinOption = new PromptDoubleOptions("Enter vent Z-min level");
                                zMinOption.AllowNone    = false;
                                zMinOption.DefaultValue = zMinOld;
                                PromptDoubleResult zMin = ed.GetDouble(zMinOption);
                                if (zMin.Status != PromptStatus.OK || zMin.Status == PromptStatus.Cancel)
                                {
                                    goto End;
                                }
                                zMinOld = zMin.Value;
                                Utils.Utils.SetUCS(zMin.Value);

                                double             height;
                                PromptDoubleResult zMax;
                                PromptDoubleResult heightResult;
                                // Enter Z-max (and check if > Z-min) or Height
                                while (true)
                                {
                                    PromptDoubleOptions zMaxO = new PromptDoubleOptions("\nEnter vent Z-max level or ");
                                    zMaxO.DefaultValue = zMaxOld;
                                    zMaxO.Keywords.Add("Height");
                                    zMax = ed.GetDouble(zMaxO);
                                    if (zMax.Status == PromptStatus.Keyword && zMax.StringResult == "Height")
                                    {
                                        PromptDoubleOptions heightO = new PromptDoubleOptions("\nEnter vent height:");
                                        heightO.DefaultValue  = heightOld;
                                        heightO.AllowNone     = false;
                                        heightO.AllowZero     = false;
                                        heightO.AllowNegative = false;
                                        heightResult          = ed.GetDouble(heightO);
                                        if (heightResult.Status == PromptStatus.OK)
                                        {
                                            height    = heightResult.Value;
                                            heightOld = heightResult.Value;
                                            break;
                                        }
                                    }
                                    else if (zMax.Status != PromptStatus.OK)
                                    {
                                        goto End;
                                    }
                                    else if (zMax.Value <= zMin.Value)
                                    {
                                        ed.WriteMessage("\nZ-max level should be greater than Z-min level");
                                    }
                                    else
                                    {
                                        zMaxOld = zMax.Value;
                                        height  = zMax.Value - zMin.Value;
                                        break;
                                    }
                                }

                                Utils.Utils.SetOrtho(true);

                                while (true)
                                {
                                    PromptPointOptions p1Option = new PromptPointOptions("\nSpecify vent first corner:");
                                    p1Option.AllowNone = false;
                                    PromptPointResult p1 = ed.GetPoint(p1Option);
                                    if (p1.Status != PromptStatus.OK || p1.Status == PromptStatus.Cancel)
                                    {
                                        goto End;
                                    }

                                    PromptPointOptions p2Option = new PromptPointOptions("\nSpecify vent second corner:");
                                    p2Option.AllowNone    = false;
                                    p2Option.UseBasePoint = true;
                                    p2Option.BasePoint    = p1.Value;
                                    PromptPointResult p2 = ed.GetPoint(p2Option);
                                    if (p2.Status != PromptStatus.OK || p2.Status == PromptStatus.Cancel)
                                    {
                                        goto End;
                                    }
                                    Utils.Utils.CreateExtrudedSurface(new Point3d(p1.Value.X, p1.Value.Y, zMin.Value), new Point3d(p2.Value.X, p2.Value.Y, zMax.Value));
                                }
                            }
                        }
                        else if (orientation.StringResult == "Horizontal")
                        {
                            while (true)
                            {
                                PromptDoubleOptions zlevelOption = new PromptDoubleOptions("Enter vent Z level");
                                zlevelOption.AllowNone    = false;
                                zlevelOption.DefaultValue = zMinOld;
                                PromptDoubleResult zlevel = ed.GetDouble(zlevelOption);
                                if (zlevel.Status != PromptStatus.OK || zlevel.Status == PromptStatus.Cancel)
                                {
                                    goto End;
                                }
                                zMinOld = zlevel.Value;
                                Utils.Utils.SetUCS(zlevel.Value);

                                Utils.Utils.SetOrtho(false);

                                while (true)
                                {
                                    PromptPointOptions p1Option = new PromptPointOptions("\nSpecify vent first corner:");
                                    p1Option.AllowNone = false;
                                    PromptPointResult p1 = ed.GetPoint(p1Option);
                                    if (p1.Status != PromptStatus.OK || p1.Status == PromptStatus.Cancel)
                                    {
                                        goto End;
                                    }

                                    var p2 = ed.GetUcsCorner("Pick vent opposite corner:", p1.Value);
                                    if (p2.Status != PromptStatus.OK || p2.Status == PromptStatus.Cancel)
                                    {
                                        goto End;
                                    }
                                    Utils.Utils.CreateExtrudedSurface(new Point3d(p1.Value.X, p1.Value.Y, zlevel.Value), new Point3d(p2.Value.X, p2.Value.Y, zlevel.Value));
                                }
                            }
                        }
                    }
                    End :;
                }
                Utils.Utils.End();
            }
            catch (System.Exception e)
            {
                ed.WriteMessage("\nProgram exception: " + e.ToString());
                Utils.Utils.End();
            }
        }
예제 #22
0
        public void StretchPolylineVertex()
        {
            Document doc = AcAp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;

            ed = doc.Editor;
            double requiredArea = 0;

            try
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    PromptDoubleOptions pdo = new PromptDoubleOptions(
                        "\nSpecify the required area: ")
                    {
                        AllowNegative   = false,
                        AllowNone       = false,
                        AllowZero       = false,
                        DefaultValue    = defaultArea,
                        UseDefaultValue = defaultArea == 0 ? false : true
                    };
                    PromptDoubleResult pdr = ed.GetDouble(pdo);
                    if (pdr.Status != PromptStatus.OK)
                    {
                        return;
                    }

                    requiredArea = defaultArea = pdr.Value;



                    PromptEntityOptions peo = new PromptEntityOptions("\nSelect a polyline: ")
                    {
                        AllowNone = false
                    };
                    peo.SetRejectMessage("\n>>>this is not a polyline, Select a polyline: ");
                    peo.AddAllowedClass(typeof(Polyline), true);

                    ed.TurnForcedPickOn();
                    ed.PointMonitor += Ed_PointMonitor;

                    PromptEntityResult per = ed.GetEntity(peo);
                    if (per.Status != PromptStatus.OK)
                    {
                        return;
                    }
                    var pline = trans.GetObject(per.ObjectId, OpenMode.ForRead) as Polyline;
                    if (!pline.Closed)
                    {
                        ed.WriteMessage("\nThe selected polyline is not closed");
                        return;
                    }
                    var area     = pline.GetArea();
                    var pickedPt = pline.GetClosestPointTo(per.PickedPoint, true);

                    double param = pline.GetParameterAtPoint(pickedPt);
                    int    mIndex, fIndex, eIndex;
                    int    endParam = (int)pline.EndParam - 1;
                    if (param - Math.Truncate(param) < 0.5)
                    {
                        mIndex = (int)param;
                        fIndex = mIndex == endParam ? 0 : mIndex + 1;
                        eIndex = mIndex == 0 ? endParam : mIndex - 1;
                    }
                    else
                    {
                        mIndex = (int)param == endParam ? 0 : (int)param + 1;
                        fIndex = mIndex == 0 ? endParam : mIndex - 1;
                        eIndex = mIndex == endParam ? 0 : mIndex + 1;
                    }

                    var movablePoint = pline.GetPointAtParameter(mIndex).GetPoint2d();
                    var fixedPoint   = pline.GetPointAtParameter(fIndex).GetPoint2d();
                    var extPoint     = pline.GetPointAtParameter(eIndex).GetPoint2d();

                    var l1   = movablePoint.GetDistanceTo(fixedPoint);
                    var dA   = requiredArea - Math.Abs(area);
                    var ang1 = fixedPoint.GetVectorTo(movablePoint).Angle;
                    var ang2 = extPoint.GetVectorTo(movablePoint).Angle;

                    var ang         = ang1 - ang2;
                    var dl          = 2 * dA / (l1 * Math.Abs(Math.Sin(ang)));
                    var finaltPoint = movablePoint.Polar(ang2, dl);

                    pline.UpgradeOpen();
                    pline.SetPointAt(mIndex, finaltPoint);
                    trans.Commit();
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage(ex.Message);
            }
        }
예제 #23
0
        public static void fWall()
        {
            Utils.Utils.Init();
            Document doc = acApp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = acApp.DocumentManager.MdiActiveDocument.Editor;

            BulgePolyJig jig = new BulgePolyJig(ed.CurrentUserCoordinateSystem);

            // Get zMin & zMax | height level
            PromptDoubleOptions zMinO = new PromptDoubleOptions("\nEnter Z-min level:");

            zMinO.DefaultValue = zMinOld;
            PromptDoubleResult zMin = ed.GetDouble(zMinO);

            if (zMin.Status != PromptStatus.OK)
            {
                Utils.Utils.End(); return;
            }
            zMinOld = zMin.Value;
            Utils.Utils.SetUCS(zMin.Value);

            if (!Utils.Layers.CurrentLayer().Contains("OBST"))
            {
                Utils.Layers.SetLayerForCurrentFloor("!FDS_OBST[gypsum_board]");
            }

            double             height;
            PromptDoubleResult zMax;
            PromptDoubleResult heightResult;

            // Enter Z-max (and check if > Z-min) or Height
            while (true)
            {
                PromptDoubleOptions zMaxO = new PromptDoubleOptions("\nEnter Z-max level or ");
                zMaxO.DefaultValue = zMaxOld;
                zMaxO.Keywords.Add("Height");
                zMax = ed.GetDouble(zMaxO);
                if (zMax.Status == PromptStatus.Keyword && zMax.StringResult == "Height")
                {
                    PromptDoubleOptions heightO = new PromptDoubleOptions("\nEnter height:");
                    heightO.DefaultValue  = heightOld;
                    heightO.AllowNone     = false;
                    heightO.AllowZero     = false;
                    heightO.AllowNegative = false;
                    heightResult          = ed.GetDouble(heightO);
                    if (heightResult.Status == PromptStatus.OK)
                    {
                        height    = heightResult.Value;
                        heightOld = heightResult.Value;
                        break;
                    }
                }
                else if (zMax.Status != PromptStatus.OK)
                {
                    Utils.Utils.End(); return;
                }
                else if (zMax.Value <= zMin.Value)
                {
                    ed.WriteMessage("\nZ-max level should be greater than Z-min level");
                }
                else
                {
                    zMaxOld = zMax.Value;
                    height  = zMax.Value - zMin.Value;
                    break;
                }
            }


            while (true)
            {
                PromptResult res = ed.Drag(jig);
                switch (res.Status)
                {
                // New point was added, keep going
                case PromptStatus.OK:
                    jig.AddDummyVertex();
                    break;

                // Keyword was entered
                case PromptStatus.Keyword:
                    if (jig.IsUndoing)
                    {
                        jig.RemoveLastVertex();
                    }
                    break;

                // If the jig completed successfully, add the polyline
                case PromptStatus.None:
                    jig.RemoveLastVertex();
                    jig.Append();
                    // Wyciagniecie geometrii
                    jig.ExtrudeWall(zMin.Value, zMax.Value, height);
                    Utils.Utils.End();
                    return;

                // User cancelled the command, get out of here
                // and don't forget to dispose the jigged entity
                default:
                    jig.Entity.Dispose();
                    Utils.Utils.End();
                    return;
                }
            }
        }
예제 #24
0
        public static void getYourPath()
        {
            // Получение текущего документа и базы данных
            Document acDoc = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            TypeViewerForm tvf = new TypeViewerForm();
            double delta = 0;
            int indStart, indEnd = 0;
            List<int> colorPath = new List<int>();
            List<int> path = new List<int>();

            using (DocumentLock doclock = acDoc.LockDocument())
            {

                // Старт транзакции
                using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
                {
                    PromptPointResult pPtRes;
                    PromptPointOptions pPtOpts = new PromptPointOptions("");

                    PromptDoubleResult psoRes;
                    PromptDoubleOptions psoOpt = new PromptDoubleOptions("");

                    // Prompt for the start point
                    pPtOpts.Message = "\nВведи начало пути: ";
                    pPtRes = acDoc.Editor.GetPoint(pPtOpts);
                    indStart = Data.pathPoints.FindIndex(item => item == pPtRes.Value);

                    psoOpt.Message = "\nВведите длину спуска: ";
                    if (Data.descentPoints[indStart] == 0)
                        psoOpt.DefaultValue = Data.descent;
                    else
                        psoOpt.DefaultValue = Data.descentPoints[indStart];

                    psoRes = acDoc.Editor.GetDouble(psoOpt);
                    if (Data.descentPoints[indStart] == 0)
                    {
                        Data.descentPoints[indStart] = psoRes.Value;
                        Data.descent = psoRes.Value;
                    }
                    delta = delta + psoRes.Value;
                    path.Add(indStart);

                    while (true)
                    {
                        pPtOpts.Message = "\nВведи следующую точку пути: ";
                        pPtRes = acDoc.Editor.GetPoint(pPtOpts);

                        indEnd = Data.pathPoints.FindIndex(item => item == pPtRes.Value);
                        if (indEnd == -1) break;
                        path.Add(indEnd);

                        //Application.ShowAlertDialog("Тут все хорошо 1");

                        colorPath = Class4.setPath(Data.arrayFloidS, path, indStart, indEnd, Data.arrayFloidS[indStart, indEnd]);
                        //Application.ShowAlertDialog("Тут все хорошо 2");

                        Data.dlina = Data.arrayFloidD[indStart, indEnd] + delta;

                        indStart = indEnd;

                    }

                    psoOpt.Message = "\nВведите длину спуска: ";
                    if (Data.descentPoints[indStart] == 0)
                        psoOpt.DefaultValue = Data.descent;
                    else
                        psoOpt.DefaultValue = Data.descentPoints[indStart];

                    psoRes = acDoc.Editor.GetDouble(psoOpt);
                    if (Data.descentPoints[indStart] == 0)
                    {
                        Data.descentPoints[indStart] = psoRes.Value;
                        Data.descent = psoRes.Value;
                    }
                    delta = delta + psoRes.Value;
                    Data.dlina = Data.dlina + delta;

                    PromptSelectionResult acSSPrompt1 = acDoc.Editor.GetSelection();
                    // Если статус запроса равен OK, объекты выбраны
                    if (acSSPrompt1.Status == PromptStatus.OK)
                    {
                        SelectionSet acSSet1 = acSSPrompt1.Value;

                        for (int i = 0; i < colorPath.Count - 1; i++)
                        {
                            //Application.ShowAlertDialog("Путь: " + colorPath[i].ToString());
                            foreach (SelectedObject acSSObj in acSSet1)
                            {
                                // Проверка, нужно убедиться в правильности полученного объекта
                                if (acSSObj != null)
                                {
                                    // Открытие объекта для чтения
                                    Line acEnt = acTrans.GetObject(acSSObj.ObjectId, OpenMode.ForWrite) as Line;
                                    //Application.ShowAlertDialog("Тут все хорошо 3");
                                    if (acEnt != null)
                                    {
                                        int indS = Data.pathPoints.FindIndex(item => item == acEnt.StartPoint);
                                        int indE = Data.pathPoints.FindIndex(item => item == acEnt.EndPoint);
                                        if (((colorPath[i] == indS) && ((colorPath[i + 1] == indE))) || ((colorPath[i + 1] == indS) && ((colorPath[i] == indE))))
                                        {
                                            acEnt.ColorIndex = 3;
                                            if (!Data.pathName[indS].Contains(DataCabel.t_oboznach1))
                                            {
                                                Data.pathName[indS].Add(DataCabel.t_oboznach1);
                                               // Application.ShowAlertDialog("Тут все хорошо 1" + indS.ToString() + " " + DataCabel.t_oboznach1);
                                            }
                                            if (!Data.pathName[indE].Contains(DataCabel.t_oboznach1))
                                            {
                                                Data.pathName[indE].Add(DataCabel.t_oboznach1);
                                               // Application.ShowAlertDialog("Тут все хорошо 2" + indE.ToString() + " " + DataCabel.t_oboznach1);
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                    //Application.ShowAlertDialog((Data.arrayFloidD[indStart, indEnd] + delta).ToString()); показывает длину

                    // Autodesk.AutoCAD.ApplicationServices.Application.ShowModelessDialog(tvf);
                    // tvf.writeText(arrayFloidD[indStart, indEnd]);

                    // Очистка транзакции

                    // Сохранение нового объекта в базе данных
                    acTrans.Commit();
                }
            }
        }
예제 #25
0
        public static void fCWall()
        {
            Utils.Utils.Init();
            Document doc = acApp.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = acApp.DocumentManager.MdiActiveDocument.Editor;

            BulgePolyJig jig = new BulgePolyJig(ed.CurrentUserCoordinateSystem);

            // Get zMin & zMax | height level
            PromptDoubleOptions zMinO = new PromptDoubleOptions("\nEnter Z-min level:");

            zMinO.DefaultValue = zMinOld;
            PromptDoubleResult zMin = ed.GetDouble(zMinO);

            if (zMin.Status != PromptStatus.OK)
            {
                Utils.Utils.End(); return;
            }
            zMinOld = zMin.Value;
            Utils.Utils.SetUCS(zMin.Value);

            if (!Utils.Layers.CurrentLayer().Contains("OBST"))
            {
                Utils.Layers.SetLayerForCurrentFloor("!FDS_OBST[gypsum_board]");
            }

            while (true)
            {
                PromptResult res = ed.Drag(jig);
                switch (res.Status)
                {
                // New point was added, keep going
                case PromptStatus.OK:
                    jig.AddDummyVertex();
                    break;

                // Keyword was entered
                case PromptStatus.Keyword:
                    if (jig.IsUndoing)
                    {
                        jig.RemoveLastVertex();
                    }
                    break;

                // If the jig completed successfully, add the polyline
                case PromptStatus.None:
                    jig.RemoveLastVertex();
                    jig.Append();
                    // Wyciagniecie geometrii
                    jig.ExtrudeToCeiling(zMin.Value);
                    Utils.Utils.End();
                    return;

                // User cancelled the command, get out of here
                // and don't forget to dispose the jigged entity
                default:
                    jig.Entity.Dispose();
                    Utils.Utils.End();
                    return;
                }
            }
        }
예제 #26
0
        //--------------------------------------------------------------------------
        //
        // ���ܣ����õ�ǰ������
        //
        //  ���ߣ�
        //
        //  ���ڣ�200708
        //
        //   ��ʷ��
        //--------------------------------------------------------------------------
        public bool SetScaleAsCurrent()
        {
            bool isSettedAsCurrent = false;
            string message = null;
            ObjectId currentMapId = new ObjectId();
            if (!FindCurrentMapId(ref currentMapId))
            {
                return isSettedAsCurrent;
            }

            MapApplication app = HostMapApplicationServices.Application;
            Editor editor = app.GetDocument(app.ActiveProject).Editor;
            PromptDoubleOptions promptOptions = new PromptDoubleOptions("");
            promptOptions.AllowNone = false;
            promptOptions.AllowZero = false;
            promptOptions.AllowNegative = false;
            promptOptions.Message = "\n����Ҫ��Ϊ��ǰ�ı�����: ";
            double scale = 0;

            try
            {
                PromptDoubleResult doublePromptResult = editor.GetDouble(promptOptions);
                if (doublePromptResult.Status == PromptStatus.OK)
                {
                    scale = doublePromptResult.Value;
                    using (Transaction trans = Utility.TransactionManager.StartTransaction())
                    {
                        Map currentMap = (Map )trans.GetObject(currentMapId, OpenMode.ForWrite);

                        currentMap.SetCurrentScale( scale, true );
                        message = string.Format("\n������ {0}�Ѿ���Ϊ��ǰ��", scale);
                        Utility.ShowMessage(message);
                        isSettedAsCurrent = true;
                        trans.Commit();
                    }
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception)
            {
                message = string.Format("\n�������ñ����� {0}Ϊ��ǰ�����ߡ�", scale);
                Utility.ShowMessage(message);
            }

            return isSettedAsCurrent;
        }
예제 #27
0
        public static void CreateCloset()
        {
            _panels.Clear();

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

            Database db = activeDoc.Database;

            Editor ed = activeDoc.Editor;

            PromptDoubleOptions pdo = new PromptDoubleOptions("Total closet width in feet : ");
            PromptDoubleResult  pdr = ed.GetDouble(pdo);

            if (pdr.Status != PromptStatus.OK)
            {
                return;
            }
            W = pdr.Value * 12.0;

            pdo = new PromptDoubleOptions("Total closet depth in feet : ");
            pdr = ed.GetDouble(pdo);
            if (pdr.Status != PromptStatus.OK)
            {
                return;
            }
            D = pdr.Value * 12.0;

            pdo = new PromptDoubleOptions("Total closet height in feet : ");
            pdr = ed.GetDouble(pdo);
            if (pdr.Status != PromptStatus.OK)
            {
                return;
            }
            H = pdr.Value * 12.0;

            pdo = new PromptDoubleOptions("Ply thickness in inches : ");
            pdr = ed.GetDouble(pdo);
            if (pdr.Status != PromptStatus.OK)
            {
                return;
            }
            t = pdr.Value;

            pdo = new PromptDoubleOptions("Door height as percentage of total closet height : ");
            pdr = ed.GetDouble(pdo);
            if (pdr.Status != PromptStatus.OK)
            {
                return;
            }
            doorH = H * pdr.Value * 0.01;

            PromptIntegerOptions pio = new PromptIntegerOptions("Number of drawer rows : ");
            PromptIntegerResult  pir = ed.GetInteger(pio);

            if (pir.Status != PromptStatus.OK)
            {
                return;
            }
            N = pir.Value;

            pio = new PromptIntegerOptions("Split drawers ? (1 / 0) : ");
            pir = ed.GetInteger(pio);
            if (pir.Status != PromptStatus.OK)
            {
                return;
            }
            splitDrawers = (pir.Value != 0);

            ed.WriteMessage(String.Format("\nTotal closet width  : {0}", W));
            ed.WriteMessage(String.Format("\nTotal closet depth  : {0}", D));
            ed.WriteMessage(String.Format("\nTotal closet height : {0}", H));
            ed.WriteMessage(String.Format("\nPly thickness       : {0}", t));
            ed.WriteMessage(String.Format("\nDoor height : {0}", doorH));
            ed.WriteMessage(String.Format("\nNumber of drawer rows :  {0}", N));
            ed.WriteMessage(String.Format("\nSplit drawers ?  : {0}", splitDrawers ? "yes" : "no"));

            CreateHandleBlock();

            // Left
            PlyYZ(new Point2d[] { new Point2d(0.0, 0.0),
                                  new Point2d(D - t, 0.0),
                                  new Point2d(D - t, H - 2 * t),
                                  new Point2d(0.0, H - 2 * t) }, new Point3d(0.0, t, t), WoodGrainAlignment.Vertical);
            _panels.Add(new PanelDetails("Left panel", String.Format("{0} x {1}", (D - t), H - 2 * t), 1));

            // Right
            PlyYZ(new Point2d[] { new Point2d(0.0, 0.0),
                                  new Point2d(D - t, 0.0),
                                  new Point2d(D - t, H - 2 * t),
                                  new Point2d(0.0, H - 2 * t) }, new Point3d(W - t, t, t), WoodGrainAlignment.Vertical);
            _panels.Add(new PanelDetails("Right panel", String.Format("{0} x {1}", (D - t), H - 2 * t), 1));

            // Top
            PlyXY(new Point2d[] { new Point2d(0.0, 0.0),
                                  new Point2d(W, 0.0),
                                  new Point2d(W, D - t),
                                  new Point2d(0.0, D - t) }, new Point3d(0.0, t, H - t), WoodGrainAlignment.Horizontal);
            _panels.Add(new PanelDetails("Top panel", String.Format("{0} x {1}", W, (D - t)), 1));

            // Bottom
            PlyXY(new Point2d[] { new Point2d(0.0, 0.0),
                                  new Point2d(W, 0.0),
                                  new Point2d(W, D - t),
                                  new Point2d(0.0, D - t) }, new Point3d(0.0, t, 0.0), WoodGrainAlignment.Horizontal);
            _panels.Add(new PanelDetails("Bottom panel", String.Format("{0} x {1}", W, (D - t)), 1));

            // Back
            PlyXZ(new Point2d[] { new Point2d(0.0, 0.0),
                                  new Point2d(-W + 2 * t, 0.0),
                                  new Point2d(-W + 2 * t, H - 2 * t),
                                  new Point2d(0.0, H - 2 * t) }, new Point3d(t, D - t, t), WoodGrainAlignment.Vertical);
            _panels.Add(new PanelDetails("Back panel", String.Format("{0} x {1}", W + 2 * t, H - 2 * t), 1));

            // Front twin doors
            // Left
            ObjectId leftDoorId = PlyXZ(new Point2d[] { new Point2d(0.0, 0.0),
                                                        new Point2d(-W * 0.5, 0.0),
                                                        new Point2d(-W * 0.5, doorH),
                                                        new Point2d(0.0, doorH) }, new Point3d(0.0, 0.0, H - doorH), WoodGrainAlignment.Vertical);

            _panels.Add(new PanelDetails("Front twin doors", String.Format("{0} x {1}", W * 0.5, doorH), 2));

            // Swing the door open
            // comment it to shut the drawer
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Entity ent = tr.GetObject(leftDoorId, OpenMode.ForWrite) as Entity;
                ent.TransformBy(Matrix3d.Rotation(-135 * Math.PI / 180.0, Vector3d.ZAxis, new Point3d(0.0, 0.0, H - doorH)));
                tr.Commit();
            }

            // Right
            ObjectId rightDoorId = PlyXZ(new Point2d[] { new Point2d(0.0, 0.0),
                                                         new Point2d(-W * 0.5, 0.0),
                                                         new Point2d(-W * 0.5, doorH),
                                                         new Point2d(0.0, doorH) }, new Point3d(W * 0.5, 0.0, H - doorH), WoodGrainAlignment.Vertical);

            // Swing the door open
            // comment it to shut the drawer
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Entity ent = tr.GetObject(rightDoorId, OpenMode.ForWrite) as Entity;
                ent.TransformBy(Matrix3d.Rotation(135 * Math.PI / 180.0, Vector3d.ZAxis, new Point3d(W, 0.0, H - doorH)));
                tr.Commit();
            }

            // Inner shelf divider
            PlyXY(new Point2d[] { new Point2d(0.0, 0.0),
                                  new Point2d(W - 2 * t, 0.0),
                                  new Point2d(W - 2 * t, D - 2 * t),
                                  new Point2d(0.0, D - 2 * t) }, new Point3d(t, t, H - doorH), WoodGrainAlignment.Horizontal);
            _panels.Add(new PanelDetails("Inner shelf divider", String.Format("{0} x {1}", W - 2 * t, D - 2 * t), 1));
            CreateDrawerBlock(splitDrawers);

            InsertDrawers();
        }
    public void ImportFromKinect()
    {
      Document doc =
        Autodesk.AutoCAD.ApplicationServices.
          Application.DocumentManager.MdiActiveDocument;
      Editor ed = doc.Editor;

      PromptDoubleOptions pdo =
        new PromptDoubleOptions("\nEnter profile radius");
      pdo.AllowZero = false;
      pdo.AllowNegative = false;
      pdo.AllowNone = false;
      pdo.DefaultValue = 0.05;
      pdo.UseDefaultValue = true;
      PromptDoubleResult pdr = ed.GetDouble(pdo);

      if (pdr.Status != PromptStatus.OK)
        return;

      Transaction tr =
        doc.TransactionManager.StartTransaction();

      KinectSolidsJig kj = new KinectSolidsJig(doc, tr, pdr.Value);

      kj.InitializeSpeech();

      if (!kj.StartSensor())
      {
        ed.WriteMessage(
          "\nUnable to start Kinect sensor - " +
          "are you sure it's plugged in?"
        );
        tr.Dispose();
        return;
      }

      PromptResult pr = ed.Drag(kj);

      if (pr.Status != PromptStatus.OK && !kj.Finished)
      {
        kj.StopSensor();
        kj.Cleanup();
        tr.Dispose();
        return;
      }

      // Generate a final point cloud with color before stopping
      // the sensor

      kj.UpdatePointCloud();
      kj.StopSensor();

      kj.AddSolidOrPath();
      tr.Commit();

      // Manually dispose to avoid scoping issues with
      // other variables

      tr.Dispose();

      kj.WriteAndImportPointCloud(doc, kj.Vectors);
    }
예제 #29
0
        public static void GetCurveLength()
        {
            bool continuePick = true;

            while (continuePick)
            {
                PromptEntityOptions peo = new PromptEntityOptions("\nSelect Entity" + "<Scale " + Scale + ">");
                peo.Keywords.Add("Scale");
                peo.SetRejectMessage("\nObject type not supported");
                peo.AddAllowedClass(typeof(Curve), false);

                PromptEntityResult per = GLOBAL.CurrentEditor.GetEntity(peo);
                if (per.Status == PromptStatus.Keyword)
                {
                    switch (per.StringResult)
                    {
                    case "Scale":
                        PromptDoubleOptions pdo = new PromptDoubleOptions("\nEnter Scale " + "<" + Scale + ">");
                        PromptDoubleResult  pdr = GLOBAL.CurrentEditor.GetDouble(pdo);
                        if (pdr.Status == PromptStatus.OK)
                        {
                            mScale = pdr.Value;
                        }
                        break;
                    }
                }
                else if (per.Status == PromptStatus.OK)
                {
                    ObjectId cId = per.ObjectId;

                    using (Transaction tr = GLOBAL.CurrentDocument.TransactionManager.StartTransaction())
                    {
                        Curve curve = tr.GetObject(cId, OpenMode.ForRead) as Curve;
                        if (curve != null)
                        {
                            PromptPointOptions ppo  = new PromptPointOptions("\nPick 1st Point");
                            PromptPointOptions ppo2 = new PromptPointOptions("\nPick 2nd Point");
                            PromptPointResult  ppr  = GLOBAL.CurrentEditor.GetPoint(ppo);
                            PromptPointResult  ppr2 = GLOBAL.CurrentEditor.GetPoint(ppo2);
                            if (ppr.Status == PromptStatus.OK && ppr2.Status == PromptStatus.OK)
                            {
                                // Transform from UCS to WCS
                                Matrix3d           ucs = GLOBAL.CurrentEditor.CurrentUserCoordinateSystem;
                                CoordinateSystem3d cs  = ucs.CoordinateSystem3d;
                                Matrix3d           mat =
                                    Matrix3d.AlignCoordinateSystem(
                                        Point3d.Origin,
                                        Vector3d.XAxis,
                                        Vector3d.YAxis,
                                        Vector3d.ZAxis,
                                        cs.Origin,
                                        cs.Xaxis,
                                        cs.Yaxis,
                                        cs.Zaxis
                                        );

                                double dis = Math.Abs(curve.GetDistAtPoint(curve.GetClosestPointTo(ppr.Value.TransformBy(mat), false))
                                                      - curve.GetDistAtPoint(curve.GetClosestPointTo(ppr2.Value.TransformBy(mat), false)));
                                GLOBAL.WriteMessage(dis.ToString());

                                PromptEntityOptions peo2 = new PromptEntityOptions("\nSelect Text");
                                peo2.SetRejectMessage("\nObject type not supported");
                                peo2.AddAllowedClass(typeof(DBText), false);

                                PromptEntityResult per2 = GLOBAL.CurrentEditor.GetEntity(peo2);
                                if (per2.Status != PromptStatus.OK)
                                {
                                    return;
                                }
                                ObjectId tId = per2.ObjectId;

                                using (Transaction tr2 = GLOBAL.CurrentDocument.TransactionManager.StartTransaction())
                                {
                                    DBText text = tr2.GetObject(tId, OpenMode.ForWrite) as DBText;
                                    if (text != null)
                                    {
                                        text.TextString = (Math.Round(dis * Scale, 0)).ToString();
                                    }
                                    tr2.Commit();
                                }
                            }
                        }
                        tr.Commit();
                    }
                }
                else
                {
                    continuePick = false;
                }
            }
        }
예제 #30
0
        public void WeldingLineStart()
        {
            #region Select welding mode
            var weldingModeOpts = new PromptKeywordOptions("\nWeld over points or object? ");
            weldingModeOpts.Keywords.Add("Points");
            weldingModeOpts.Keywords.Add("polYline");
            weldingModeOpts.Keywords.Add("Line");
            weldingModeOpts.Keywords.Add("Circle");
            weldingModeOpts.Keywords.Add("Arc");
            weldingModeOpts.Keywords.Add("Block");
            weldingModeOpts.Keywords.Default = "Points";

            var weldingModeRslt = _ed.GetKeywords(weldingModeOpts);
            // If the user pressed cancel - return with no error
            if (weldingModeRslt.Status != PromptStatus.OK)
            {
                return;
            }

            if (weldingModeRslt.StringResult == "Block")
            {
                ImportInsulationBlock();
                return;
            }

            var selectedObjectId = new ObjectId();
            // If the user selected Points mode
            if (weldingModeRslt.StringResult == "Points")
            {
                //Prompt the user for vertices
                _weldingVertices.Clear();
                _weldingVertices = GetPointsFromUser();
                if (_weldingVertices.Count < 1)
                {
                    return;
                }
            }
            // Else the user selected an Object mode from the list
            else
            {
                // Prompt for object
                var objectSelectionOpts = new PromptEntityOptions("\nSelect the object : ");
                objectSelectionOpts.SetRejectMessage("\nEntity is not of the predifined type :" + weldingModeRslt.StringResult);
                objectSelectionOpts.AddAllowedClass(typeof(Line), false);
                objectSelectionOpts.AddAllowedClass(typeof(Polyline), false);
                objectSelectionOpts.AddAllowedClass(typeof(Circle), false);
                objectSelectionOpts.AddAllowedClass(typeof(Arc), false);

                var objectSelectionRslt = _ed.GetEntity(objectSelectionOpts);
                // If the user pressed cancel - return with no error
                if (objectSelectionRslt.Status != PromptStatus.OK)
                {
                    return;
                }
                // else get the slected object id and type
                selectedObjectId = objectSelectionRslt.ObjectId;
            }
            #endregion

            #region Welding side selection

            // Prompt the user to select object side M for middle - draw on the middle of the line or Point - for side.
            var weldingSideOpts = new PromptKeywordOptions("\nPick side point or draw in the middle. ");
            weldingSideOpts.Keywords.Add("Side");
            weldingSideOpts.Keywords.Add("Middle ");
            weldingSideOpts.Keywords.Default = "Side";
            var weldingSideRslt = _ed.GetKeywords(weldingSideOpts);
            // If the user pressed cancel - return with no error
            if (weldingSideRslt.Status != PromptStatus.OK)
            {
                return;
            }

            // If tThe user selected 'Side'
            var sidePoint = new Point3d();
            if (weldingSideRslt.StringResult == "Side")
            {
                // Prompt the user to pick up a side point on the desired side.
                var sidePointOpts = new PromptPointOptions("\nPick side point : ");
                var sidePointRslt = _ed.GetPoint(sidePointOpts);
                // If the user pressed cancel - return with no error
                if (sidePointRslt.Status != PromptStatus.OK)
                {
                    return;
                }
                sidePoint = sidePointRslt.Value;
            }
            // Else If the user selected 'Middle'
            else if (weldingSideRslt.StringResult == "Middle")
            {
                sidePoint = new Point3d(0, 0, 0);
            }
            // else
            // Not supposed to end here, because the choise in the prompt is restricted to two options
            #endregion

            #region Welding arcs lenght and distance selection

            // Prompt the user to set welding arcs lenght
            var weldingArcsChordOpts = new PromptDoubleOptions("\nWelding arcs lenght : ")
            {
                UseDefaultValue = true,
                DefaultValue    = Settings.Default.WeldingArcsLenght
            };

            var weldingArcsChordRslt = _ed.GetDouble(weldingArcsChordOpts);
            // If the user pressed cancel - return with no error
            if (weldingArcsChordRslt.Status != PromptStatus.OK)
            {
                return;
            }
            if (weldingArcsChordRslt.Value <= 0)
            {
                _ed.WriteMessage("Lenght must be positive number.");
                return;
            }
            Settings.Default.WeldingArcsLenght = weldingArcsChordRslt.Value;
            //else
            // The choice is Ok and lenght is provided. Continue...

            // Prompt the user to set the distance between the welding arcs
            var weldingArcsDistanceOpts = new PromptDoubleOptions("\nSet the distance between the welding arcs : ")
            {
                UseDefaultValue = true,
                DefaultValue    = Settings.Default.WeldingArcsDistance
            };
            var weldingArcsOffsetRslt = _ed.GetDouble(weldingArcsDistanceOpts);
            // If the user pressed cancel - return with no error
            if (weldingArcsOffsetRslt.Status != PromptStatus.OK)
            {
                return;
            }
            if (weldingArcsOffsetRslt.Value <= 0)
            {
                _ed.WriteMessage("Distance must be positive number.");
            }
            Settings.Default.WeldingArcsDistance = weldingArcsOffsetRslt.Value;
            Settings.Default.Save();
            //else
            // The choice is Ok and distance is provided. Continue...
            #endregion

            #region Hand over the process to the specific drawing function
            _weldingArcs.Clear();

            switch (weldingModeRslt.StringResult)
            {
                #region Points
            case "Points":

                for (var i = 0; i < _weldingVertices.Count; i++)
                {
                    // слага ги в глобалната
                    _weldingVertices[i] = _weldingVertices[i].TransformBy(GeometryUtility.GetTransforMatrixToWcs());
                }
                using (var tr = _doc.Database.TransactionManager.StartTransaction())
                {
                    var sPt = new Point3d(sidePoint.X + 0.00001, sidePoint.Y + 0.00001, sidePoint.Z);
                    sPt = sPt.TransformBy(GeometryUtility.GetTransforMatrixToWcs());
                    // реперната точка и тя в глобалната

                    var tP1 = new Point3d(0, 0, 0);
                    var tP2 = new Point3d(_weldingVertices[1].X - _weldingVertices[0].X, _weldingVertices[1].Y - _weldingVertices[0].Y, _weldingVertices[1].Z - _weldingVertices[0].Z);
                    var tP3 = new Point3d(sPt.X - _weldingVertices[0].X, sPt.Y - _weldingVertices[0].Y, sPt.Z - _weldingVertices[0].Z);


                    var ucs = GeometryUtility.GetUcs(tP1, tP2, tP3, false);
                    for (var i = 0; i < _weldingVertices.Count; i++)
                    {
                        _weldingVertices[i] = _weldingVertices[i].TransformBy(ucs);
                    }
                    if (weldingSideRslt.StringResult == "Side")
                    {
                        sidePoint = sidePoint.TransformBy(_ed.CurrentUserCoordinateSystem);
                        sidePoint = sidePoint.TransformBy(ucs);
                    }

                    var oldUcs = _ed.CurrentUserCoordinateSystem;
                    _ed.CurrentUserCoordinateSystem = Matrix3d.Identity;

                    _weldingArcs = BuildWeldingArcsOverPts(_weldingVertices,
                                                           sidePoint,
                                                           weldingArcsChordRslt.Value,
                                                           weldingArcsOffsetRslt.Value,
                                                           weldingArcsOffsetRslt.Value / 2);
                    DrawWeldingLine(_weldingArcs, tr);

                    _ed.CurrentUserCoordinateSystem = oldUcs;

                    foreach (Arc a in _weldingArcs)
                    {
                        a.TransformBy(ucs.Inverse());
                    }


                    tr.Commit();
                }
                break;
                #endregion

                #region Line
            case "Line":
                using (var tr = _doc.Database.TransactionManager.StartTransaction())
                {
                    _weldingVertices.Clear();

                    var ent  = tr.GetObject(selectedObjectId, OpenMode.ForRead) as Entity;                                                                     // Lishkov 07/07/2012
                    var name = ent.GetType().ToString();                                                                                                       // Lishkov 07/07/2012
                    if ((name.IndexOf("Line") < 0) || (name.IndexOf("Polyline") >= 0))
                    {
                        MessageBox.Show("Selection is not  Line !", "E R R O R"); break;
                    }                                                                                                                                             // Lishkov 07/07/2012

                    var weldingLine = (Line)tr.GetObject(selectedObjectId, OpenMode.ForWrite);

                    var sPt = new Point3d(sidePoint.X + 0.00001, sidePoint.Y + 0.00001, sidePoint.Z);
                    sPt = sPt.TransformBy(GeometryUtility.GetTransforMatrixToWcs());

                    var tP1 = new Point3d(0, 0, 0);
                    var tP2 = new Point3d(weldingLine.EndPoint.X - weldingLine.StartPoint.X, weldingLine.EndPoint.Y - weldingLine.StartPoint.Y, weldingLine.EndPoint.Z - weldingLine.StartPoint.Z);
                    var tP3 = new Point3d(sPt.X - weldingLine.StartPoint.X, sPt.Y - weldingLine.StartPoint.Y, sPt.Z - weldingLine.StartPoint.Z);

                    var ucs = GeometryUtility.GetUcs(tP1, tP2, tP3, false);
                    weldingLine.TransformBy(ucs);
                    if (weldingSideRslt.StringResult == "Side")
                    {
                        sidePoint = sidePoint.TransformBy(_ed.CurrentUserCoordinateSystem);
                        sidePoint = sidePoint.TransformBy(ucs);
                    }

                    var oldUcs = _ed.CurrentUserCoordinateSystem;
                    _ed.CurrentUserCoordinateSystem = Matrix3d.Identity;

                    _weldingVertices.Add(weldingLine.StartPoint);
                    _weldingVertices.Add(weldingLine.EndPoint);

                    _weldingArcs = BuildWeldingArcsOverPts(_weldingVertices,
                                                           sidePoint,
                                                           weldingArcsChordRslt.Value,
                                                           weldingArcsOffsetRslt.Value,
                                                           weldingArcsOffsetRslt.Value / 2);
                    DrawWeldingLine(_weldingArcs, tr);

                    _ed.CurrentUserCoordinateSystem = oldUcs;

                    foreach (Arc a in _weldingArcs)
                    {
                        a.TransformBy(ucs.Inverse());
                    }

                    weldingLine.TransformBy(ucs.Inverse());


                    tr.Commit();
                }

                break;
                #endregion

                #region Polyline
            case "polYline":
            case "Polyline":
            case "polyline":

                using (var tr = _doc.Database.TransactionManager.StartTransaction())
                {
                    var weldingPoly = tr.GetObject(selectedObjectId, OpenMode.ForWrite) as Polyline;
                    if (weldingPoly == null)
                    {
                        MessageBox.Show("Selection is not  PolyLine !", "E R R O R");
                        break;
                    }

                    var temp  = new Point3dCollection();
                    var temp1 = new Point3dCollection();
                    DBObjectCollection acDbObjColl = null;     //acPoly.GetOffsetCurves(0.25);

                    var acBlkTbl    = tr.GetObject(_db.BlockTableId, OpenMode.ForRead) as BlockTable;
                    var acBlkTblRec = (BlockTableRecord)tr.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite);

                    //офсетирано копие
                    acDbObjColl = weldingPoly.GetOffsetCurves(0.001);    //тестова на много малко разстояние от оригинала // Lishkov 07/07/2012
                    foreach (Entity acEnt in acDbObjColl)
                    {
                        // Add each offset object
                        acBlkTblRec.AppendEntity(acEnt);
                        tr.AddNewlyCreatedDBObject(acEnt, true);
                    }
                    Polyline weldingPolyOffset = null;
                    try
                    {
                        weldingPolyOffset = tr.GetObject(acDbObjColl[0].ObjectId, OpenMode.ForWrite) as Polyline;
                    }
                    catch { }
                    if (weldingPolyOffset != null)
                    {
                        //точките деления по двете полилинии
                        temp  = GeometryUtility.DividePoly(ref weldingPoly, weldingArcsOffsetRslt.Value);
                        temp1 = GeometryUtility.DividePoly(ref weldingPolyOffset, weldingArcsOffsetRslt.Value);

                        //проверка вярна ли е посоката на офсетиране
                        var tP    = sidePoint.TransformBy(GeometryUtility.GetTransforMatrixToWcs());
                        var dist1 = temp[0].DistanceTo(tP);
                        var dist2 = temp1[0].DistanceTo(tP);

                        foreach (Point3d p in temp)
                        {
                            if (p.DistanceTo(tP) < dist1)
                            {
                                dist1 = p.DistanceTo(tP);
                            }
                        }
                        foreach (Point3d p in temp1)
                        {
                            if (p.DistanceTo(tP) < dist2)
                            {
                                dist2 = p.DistanceTo(tP);
                            }
                        }

                        //ако не е вярна посоката на офсетиране
                        #region
                        if (dist1 < dist2)    //ако посоката е грешна изтриваме тестовата и правим в обратна поскока на зададеното разстояние
                        {
                            weldingPolyOffset.Erase();
                            acDbObjColl = weldingPoly.GetOffsetCurves(-weldingArcsChordRslt.Value);
                            foreach (Entity acEnt in acDbObjColl)
                            {
                                // Add each offset object
                                acBlkTblRec.AppendEntity(acEnt);
                                tr.AddNewlyCreatedDBObject(acEnt, true);
                            }
                            try
                            {
                                weldingPolyOffset = tr.GetObject(acDbObjColl[0].ObjectId, OpenMode.ForWrite) as Polyline;
                            }
                            catch
                            {
                                MessageBox.Show("Offset error", "E R R O R");
                                return;
                            }
                            temp1 = GeometryUtility.DividePoly(ref weldingPolyOffset, weldingArcsOffsetRslt.Value);
                        }
                        else     //ако посоката е вярна изтриваме тестовата и правим в същата поскока на зададеното разстояние // Lishkov 07/07/2012
                        {
                            weldingPolyOffset.Erase();
                            acDbObjColl = weldingPoly.GetOffsetCurves(weldingArcsChordRslt.Value);
                            foreach (Entity acEnt in acDbObjColl)
                            {
                                // Add each offset object
                                acBlkTblRec.AppendEntity(acEnt);
                                tr.AddNewlyCreatedDBObject(acEnt, true);
                            }
                            try
                            {
                                weldingPolyOffset = tr.GetObject(acDbObjColl[0].ObjectId, OpenMode.ForWrite) as Polyline;
                            }
                            catch
                            {
                                MessageBox.Show("Offset error", "E R R O R");
                                return;
                            }
                            temp1 = GeometryUtility.DividePoly(ref weldingPolyOffset, weldingArcsOffsetRslt.Value);
                        }
                        #endregion

                        //work
                        var oldUcs = _ed.CurrentUserCoordinateSystem;
                        _ed.CurrentUserCoordinateSystem = Matrix3d.Identity;

                        for (var i = 0; i < temp.Count - 1; i++)
                        {
                            var tempP = temp1[0];
                            var oP    = temp1[0];
                            foreach (Point3d p in temp1)
                            {
                                if (temp[i].DistanceTo(p) < temp[i].DistanceTo(tempP))
                                {
                                    oP    = tempP;
                                    tempP = p;
                                }
                            }

                            var ucs = GeometryUtility.GetUcs(temp[i], temp[i + 1], tempP, true);

                            Arc acArc;
                            if (weldingSideRslt.StringResult != "Side")
                            {
                                acArc = new Arc(
                                    new Point3d(0, 0, 0),
                                    weldingArcsChordRslt.Value / 2,
                                    Math.PI / 2.0 + Math.PI,
                                    Math.PI / 2.0 + Math.PI + Math.PI
                                    );
                            }
                            else
                            {
                                // BricsCAD hack
                                acArc = new Arc(
                                    new Point3d(),
                                    weldingArcsChordRslt.Value / 2,
                                    Math.PI / 2.0 + Math.PI,
                                    Math.PI / 2.0 + Math.PI + Math.PI
                                    )
                                {
                                    Center = new Point3d(0, weldingArcsChordRslt.Value / 2, 0)
                                };
                            }

                            _weldingArcs.Add(acArc);
                            try
                            {
                                acArc.TransformBy(ucs);
                            }
                            catch
                            {
                                _weldingArcs.RemoveAt(_weldingArcs.Count - 1);
                                if (i > 0)
                                {
                                    var tP1 = new Point3d(0, 0, 0);
                                    var tP2 = new Point3d(temp[i].X - temp[i - 1].X, temp[i].Y - temp[i - 1].Y, temp[i].Z - temp[i - 1].Z);
                                    var tP3 = new Point3d(oP.X - temp[i - 1].X, oP.Y - temp[i - 1].Y, oP.Z - temp[i - 1].Z);

                                    ucs = GeometryUtility.GetUcs(tP1, tP2, tP3, true);
                                    try
                                    {
                                        _weldingArcs.Add(acArc);
                                        var lp1 = new Point3d(0, 0, 0);
                                        var lp2 = new Point3d(weldingArcsOffsetRslt.Value, 0, 0);
                                        var l   = new Line3d(acArc.StartPoint, acArc.EndPoint);
                                        acArc.TransformBy(Matrix3d.Displacement(lp1.GetVectorTo(lp2)));
                                        acArc.TransformBy(ucs);
                                        acArc.TransformBy(Matrix3d.Displacement(-temp[i - 1].GetVectorTo(Point3d.Origin)));
                                    }
                                    catch
                                    {
                                        _weldingArcs.RemoveAt(_weldingArcs.Count - 1);
                                    }
                                }
                            }
                            acArc.SetDatabaseDefaults();
                        }
                        if (!weldingPoly.Closed)
                        {
                            var acA   = (Arc)_weldingArcs[_weldingArcs.Count - 1];
                            var acArc = (Entity)acA.Clone();
                            acArc.TransformBy(Matrix3d.Displacement(temp[temp.Count - 2].GetVectorTo(temp[temp.Count - 1])));
                            _weldingArcs.Add(acArc);
                        }
                        weldingPolyOffset.Erase();
                        DrawWeldingLine(_weldingArcs, tr);
                        _ed.CurrentUserCoordinateSystem = oldUcs;
                    }
                    tr.Commit();
                }
                break;
                #endregion

                #region Circle
            case "Circle":
                // ElseIf the user picked up object of type 'arc' or 'circle'
                //    Call the function that makes welding over arc or circle.
                //    _Circle is an Arc with start angle of 0 and end angle of 360
                using (var tr = _doc.Database.TransactionManager.StartTransaction())
                {
                    var weldingCircle = tr.GetObject(selectedObjectId, OpenMode.ForRead) as Circle;
                    if (weldingCircle != null)
                    {
                        using (var T = _doc.Database.TransactionManager.StartTransaction())
                        {
                            var weldingLine = T.GetObject(selectedObjectId, OpenMode.ForWrite) as Circle;

                            var r = new Ray
                            {
                                BasePoint = weldingLine.Center,
                                UnitDir   = weldingLine.Center.GetVectorTo(weldingLine.StartPoint)
                            };

                            var pts = new Point3dCollection();
                            weldingLine.IntersectWith(r, Intersect.OnBothOperands, pts, IntPtr.Zero, IntPtr.Zero);

                            var sPt = new Point3d(sidePoint.X + 0.00001, sidePoint.Y + 0.00001, sidePoint.Z);
                            sPt = sPt.TransformBy(GeometryUtility.GetTransforMatrixToWcs());
                            var ucs = GeometryUtility.GetUcs(weldingLine.Center, pts[0], sPt, false);
                            weldingLine.TransformBy(ucs);
                            if (weldingSideRslt.StringResult == "Side")
                            {
                                sidePoint = sidePoint.TransformBy(_ed.CurrentUserCoordinateSystem);
                                sidePoint = sidePoint.TransformBy(ucs);
                            }

                            var oldUcs = _ed.CurrentUserCoordinateSystem;
                            _ed.CurrentUserCoordinateSystem = Matrix3d.Identity;



                            var arcSide = GeometryUtility.SideOfPointToArc(weldingCircle.Center, weldingCircle.Radius, sidePoint);
                            var sAng    = -1 + weldingCircle.Center.DistanceTo(sidePoint) / weldingCircle.Radius;
                            _weldingArcs = BuildWeldingArcsOverArc(weldingCircle.Center,
                                                                   weldingCircle.Radius,
                                                                   0.0,
                                                                   2 * Math.PI,
                                                                   /* sAng ,  */
                                                                   weldingArcsChordRslt.Value,
                                                                   weldingArcsOffsetRslt.Value,
                                                                   0,
                                                                   arcSide);
                            DrawWeldingLine(_weldingArcs, T);

                            _ed.CurrentUserCoordinateSystem = oldUcs;
                            foreach (Arc a in _weldingArcs)
                            {
                                a.TransformBy(ucs.Inverse());
                            }
                            weldingLine.TransformBy(ucs.Inverse());

                            T.Commit();
                        }
                    }
                    else
                    {
                        MessageBox.Show("\nYou did not slected object of type Circle. Try again...");
                    }
                    tr.Commit();
                }
                break;
                #endregion

                #region Arc
            case "Arc":
                using (var tr = _doc.Database.TransactionManager.StartTransaction())
                {
                    var weldingArc = tr.GetObject(selectedObjectId, OpenMode.ForRead) as Arc;
                    if (weldingArc != null)
                    {
                        using (var T = _doc.Database.TransactionManager.StartTransaction())
                        {
                            var weldingLine = T.GetObject(selectedObjectId, OpenMode.ForWrite) as Arc;

                            var sPt = sidePoint.TransformBy(GeometryUtility.GetTransforMatrixToWcs());

                            var tP1 = new Point3d(0, 0, 0);
                            var tP2 = new Point3d(weldingLine.EndPoint.X - weldingLine.StartPoint.X, weldingLine.EndPoint.Y - weldingLine.StartPoint.Y, weldingLine.EndPoint.Z - weldingLine.StartPoint.Z);
                            var tP3 = new Point3d(sPt.X - weldingLine.StartPoint.X, sPt.Y - weldingLine.StartPoint.Y, sPt.Z - weldingLine.StartPoint.Z);

                            var ucs = GeometryUtility.GetUcs(tP1, tP2, tP3, false);
                            weldingLine.TransformBy(ucs);
                            if (weldingSideRslt.StringResult == "Side")
                            {
                                sidePoint = sidePoint.TransformBy(_ed.CurrentUserCoordinateSystem);
                                sidePoint = sidePoint.TransformBy(ucs);
                            }

                            var oldUcs = _ed.CurrentUserCoordinateSystem;
                            _ed.CurrentUserCoordinateSystem = Matrix3d.Identity;



                            var arcSide = GeometryUtility.SideOfPointToArc(weldingArc.Center, weldingArc.Radius, sidePoint);

                            var sAng = -1 + weldingArc.Center.DistanceTo(sidePoint) / weldingArc.Radius;

                            _weldingArcs = BuildWeldingArcsOverArc(weldingArc.Center,
                                                                   weldingArc.Radius,
                                                                   weldingArc.StartAngle,
                                                                   weldingArc.EndAngle,
                                                                   weldingArcsChordRslt.Value,
                                                                   weldingArcsOffsetRslt.Value,
                                                                   weldingArcsOffsetRslt.Value / 2,
                                                                   arcSide);

                            DrawWeldingLine(_weldingArcs, T);

                            _ed.CurrentUserCoordinateSystem = oldUcs;

                            foreach (Arc a in _weldingArcs)
                            {
                                a.TransformBy(ucs.Inverse());
                            }

                            weldingLine.TransformBy(ucs.Inverse());

                            T.Commit();
                        }
                    }
                    else
                    {
                        MessageBox.Show("\nYou did not slected object of type Arc. Try again...");
                    }
                    tr.Commit();
                }
                break;
                #endregion
            }
            #endregion
        }
예제 #31
0
        public static void TestRegressSplit()
        {
            Matrix3d          ucs   = Tools.GetAcadEditor().CurrentUserCoordinateSystem;
            double            r2Min = 0.5d;
            KeywordCollection keys  = new KeywordCollection();

            keys.Add("R2", "R2", "R2", true, true);
            Func <PromptEntityResult, PromptStatus> promptAction = pr =>
            {
                switch (pr.StringResult)
                {
                case "R2":
                {
                    PromptDoubleOptions pdo = new PromptDoubleOptions("\nУкажите R^2: ");
                    pdo.AllowNegative   = false;
                    pdo.UseDefaultValue = true;
                    pdo.DefaultValue    = r2Min;

                    var res = Tools.GetAcadEditor().GetDouble(pdo);
                    if (res.Status != PromptStatus.OK)
                    {
                        return(PromptStatus.Cancel);
                    }
                    r2Min = res.Value;
                    return(PromptStatus.OK);
                }
                }

                return(PromptStatus.Error);
            };
            Curve curve;

            if (!ObjectCollector.TrySelectAllowedClassObject(out curve, keys, promptAction))
            {
                return;
            }
            Line line = null;

            Tools.StartTransaction(() =>
            {
                Polyline pline    = curve.ConvertToPolyline();
                var points        = pline.GetPoints3d();
                Line regressTotal = stat.LinearRegression(pline);
                regressTotal.SaveToDatebase();

                int start = 0;
                for (int i = 1; i < pline.NumberOfVertices; i++)
                {
                    double r2;
                    stat.LinearRegression(pline, start, i + 1, out r2);
                    r2 = double.IsNaN(r2) ? 1d : r2;
                    if (Math.Abs(r2 - r2Min) < Tolerance.Global.EqualVector)
                    {
                        line  = new Line(pline.GetPoint3dAt(start), pline.GetPoint3dAt(i - 1));
                        start = i - 1;
                        line.SaveToDatebase();
                    }
                }
                line = new Line(pline.GetPoint3dAt(start), pline.EndPoint);
                line.SaveToDatebase();
            });
        }
예제 #32
0
 public static IAcedCmdArg Argument(PromptDoubleOptions options)
 {
     return(new PromptDoubleArgument(options));
 }
예제 #33
0
        public void ImportFromKinect()
        {
            Document doc =
                Autodesk.AutoCAD.ApplicationServices.
                Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;

            PromptDoubleOptions pdo =
                new PromptDoubleOptions("\nEnter profile radius");

            pdo.AllowZero       = false;
            pdo.AllowNegative   = false;
            pdo.AllowNone       = false;
            pdo.DefaultValue    = 0.05;
            pdo.UseDefaultValue = true;
            PromptDoubleResult pdr = ed.GetDouble(pdo);

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

            Transaction tr =
                doc.TransactionManager.StartTransaction();

            KinectSolidsJig kj = new KinectSolidsJig(doc, tr, pdr.Value);

            kj.InitializeSpeech();

            if (!kj.StartSensor())
            {
                ed.WriteMessage(
                    "\nUnable to start Kinect sensor - " +
                    "are you sure it's plugged in?"
                    );
                tr.Dispose();
                return;
            }

            PromptResult pr = ed.Drag(kj);

            if (pr.Status != PromptStatus.OK && !kj.Finished)
            {
                kj.StopSensor();
                kj.Cleanup();
                tr.Dispose();
                return;
            }

            // Generate a final point cloud with color before stopping
            // the sensor

            kj.UpdatePointCloud();
            kj.StopSensor();

            kj.AddSolidOrPath();
            tr.Commit();

            // Manually dispose to avoid scoping issues with
            // other variables

            tr.Dispose();

            kj.WriteAndImportPointCloud(doc, kj.Vectors);
        }
예제 #34
0
        public void drawSpring()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db  = doc.Database;
            Editor   ed  = doc.Editor;

            //??ask about gauge of spring back vs seat
            //seat 8 gauge .1285"
            //back 12 gauge .0808"

            #region get ends of spring to get total distance
            //ask user for points for spring to exist
            PromptPointOptions ppo = new PromptPointOptions("First end of spring:");
            PromptPointResult  ppr = ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK)
            {
                return;
            }
            Point3d startPoint = ppr.Value;

            ppo.Message = "Second end of spring";
            ppr         = ed.GetPoint(ppo);
            if (ppr.Status != PromptStatus.OK)
            {
                return;
            }

            //calculate distance from chosen points
            #endregion
            double totalLength = startPoint.DistanceTo(ppr.Value);

            #region get spring Type (length)
            //given total length, calculate ideal spring length which is total minus some percentage
            double theorySpgLength = (Math.Round(.9 * totalLength * 2)) / 2;
            //find the nearest spring length that is less than or equal to total length(springs tend to come in 1/2" increments)
            //compare to list of spring lengths in stock **(eventually get springs from SQL)

            //present any springs withen an accaptable margin of diviation (maybe 8%)??
            //if none are easily exceptable but might work within a special circumstance, present that with warning (10%)??
            //if none are accaptable at all, then give different warning and end command (user will need to move spring rail or order diff springs)

            //**idealy replace with a user dialoge to choose from springs in system
            //ask user for spring length desired(may prompt with options from list) based on orignal distance
            PromptDoubleOptions pdo = new PromptDoubleOptions("Enter spring length:");
            //needs to pull these dynamically***************
            pdo.Keywords.Add(theorySpgLength.ToString());
            pdo.Keywords.Add((theorySpgLength - .5).ToString());
            PromptDoubleResult pdr = ed.GetDouble(pdo);
            if (pdr.Status != PromptStatus.OK)
            {
                return;
            }
            #endregion
            double springLength = pdr.Value;

            #region Create top view of spring
            //1 Calculate rungs
            //spring length / average gap
            int    rungCount = Convert.ToInt32(springLength / .875);//guessing at the avg rung gap for starters
            double rungGap   = totalLength / rungCount;
            double rungWidth = 2 - rungGap;
            //springs tend to be approx 2" wide
            //rung widths are 2" - rung gap (the two radii of bends)

            //add all parts to object collection then convert to polyline
            DBObjectCollection springParts = new DBObjectCollection();
            //construct first rung (has hooked end)
            springParts = createEnd(springParts, startPoint, rungGap, rungWidth, true, true);

            //construct rungs/bends in middle
            //and bends on alternating runs
            for (int i = 0; i < rungCount; i++)
            {
                Line rung = new Line(
                    new Point3d(startPoint.X - rungWidth / 2, startPoint.Y + i * rungGap, startPoint.Z),
                    new Point3d(startPoint.X + rungWidth / 2, startPoint.Y + i * rungGap, startPoint.Z));
                //add rungs except for either end
                if (i != 0 && i != rungCount)
                {
                    springParts.Add(rung);
                }

                //add bends to either side depending on if it is an even or odd rung
                if (i % 2 == 0)
                {
                    //even
                    Arc leftBend = new Arc(new Point3d(startPoint.X - 1 + rungGap / 2, startPoint.Y + rungGap * i + rungGap / 2, startPoint.Z), rungGap / 2, Math.PI / 2, 3 * Math.PI / 2);
                    springParts.Add(leftBend);
                }
                else
                {
                    //odd
                    Arc rightBend = new Arc(new Point3d(startPoint.X + 1 - rungGap / 2, startPoint.Y + rungGap * i + rungGap / 2, startPoint.Z), rungGap / 2, 3 * Math.PI / 2, Math.PI / 2);
                    springParts.Add(rightBend);
                }
            }

            //construct end
            //if rungCount is even it opens same as first
            bool secondOpen = true;
            if (rungCount % 2 == 0)
            {
                secondOpen = false;
            }
            springParts = createEnd(springParts, new Point3d(startPoint.X, startPoint.Y + totalLength, startPoint.Z), rungGap, rungWidth, secondOpen, false);

            ////just for testing **
            //using (Transaction trans = db.TransactionManager.StartTransaction())
            //{
            //    BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
            //    BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
            //    foreach (DBObject dbo in springParts)
            //    {
            //        Entity ent = dbo as Entity;
            //        btr.AppendEntity(ent);
            //        trans.AddNewlyCreatedDBObject(ent, true);
            //    }

            //    trans.Commit();
            //}

            Polyline pLine = BuildPLine.drawPolyLine(springParts);

            //move spring polyline to the correct Z coordinate, converting to a polyline cuts off z coords leaving it at 0****
            //***************************
            #endregion

            #region create side view (crown)
            //need to account for creating arc along different plane
            //arc is start point, and then total length vertical from first point (same plane) *we'll rotate later
            //for now all springs will use same crown, need a formula later and need an element that accounts for flat vs curly springs
            //create arc flat along same plane as spring polyline, then rotate it??
            Arc     crown    = new Arc();
            Point3d startArc = new Point3d(startPoint.X - 2, startPoint.Y, startPoint.Z);
            Point3d endArc   = new Point3d(startArc.X, startArc.Y + totalLength, startArc.Z);
            Point3d arcMid   = new Point3d(startArc.X - 1.5, startArc.Y + (totalLength / 2), startArc.Z);

            //assuming crown is 1.5 until we derive a diff system
            //radius = height/2 + width^2/height(8)
            crown.Radius = .75 + (Math.Pow(startArc.DistanceTo(endArc), 2) / 12);

            //given that we always will have our arc aligned vertically center is easter to calculate
            crown.Center = new Point3d(arcMid.X + crown.Radius, arcMid.Y, arcMid.Z);

            Matrix3d ocs2wcs = Matrix3d.PlaneToWorld(crown.Normal);
            Plane    plane   = new Plane(ocs2wcs.CoordinateSystem3d.Origin, ocs2wcs.CoordinateSystem3d.Xaxis, ocs2wcs.CoordinateSystem3d.Yaxis);

            //need start and end angles
            //double startAngle = tanAngle(arcCenter, startArc);
            //double endAngle = tanAngle(arcCenter, endArc);
            crown.EndAngle   = (startArc - crown.Center).AngleOnPlane(plane);
            crown.StartAngle = (endArc - crown.Center).AngleOnPlane(plane);

            //Arc crown = new Arc(arcCenter,radius,startAngle,endAngle);

            // Rotate the 3D solid 30 degrees around the axis that is defined by the points
            Vector3d turnArc = crown.StartPoint.GetVectorTo(crown.EndPoint);
            crown.TransformBy(Matrix3d.Rotation(3 * (Math.PI / 2), turnArc, crown.StartPoint));

            #endregion

            //convert collection to polyline
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                BlockTable       bt  = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable;
                BlockTableRecord btr = tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                //Have to have both views inserted to turn into extruded surface
                btr.AppendEntity(pLine);
                tr.AddNewlyCreatedDBObject(pLine, true);
                btr.AppendEntity(crown);
                tr.AddNewlyCreatedDBObject(crown, true);

                #region Extrude surfaces from open curves, polylines
                //extrude two shapes
                Profile3d    profileCrown  = new Profile3d(crown);
                Profile3d    profileSpring = new Profile3d(pLine);
                Vector3d     polylineDir   = new Vector3d(0, 0, 4);
                Vector3d     crownDir      = (crown.StartPoint).GetVectorTo(new Point3d(crown.StartPoint.X + 4, crown.StartPoint.Y, crown.StartPoint.Z));
                SweepOptions sweepOp       = new SweepOptions();

                //need a different vector for crown
                ObjectId surfaceId = Autodesk.AutoCAD.DatabaseServices.Surface.CreateExtrudedSurface(
                    profileCrown, crownDir, sweepOp, true);
                ObjectId surfaceSpringId = Autodesk.AutoCAD.DatabaseServices.Surface.CreateExtrudedSurface(
                    profileSpring, polylineDir, sweepOp, true);

                //remove original lines
                pLine.Erase(true);
                crown.Erase(true);
                #endregion

                //intersect both regions(observe how extrusions work with ucs)
                Autodesk.AutoCAD.DatabaseServices.Surface crownEnt  = tr.GetObject(surfaceId, OpenMode.ForWrite) as Autodesk.AutoCAD.DatabaseServices.Surface;
                Autodesk.AutoCAD.DatabaseServices.Surface springEnt = tr.GetObject(surfaceSpringId, OpenMode.ForWrite) as Autodesk.AutoCAD.DatabaseServices.Surface;
                //convert both surfaces to nurbs
                //the polyline extrusion creates many surfaces in nurb form, loop through intersections creating splines and lines
                springParts = Intersect_Surfaces.IntersectSurf(crownEnt, springEnt);
                //delete surfaces
                crownEnt.Erase(true);
                springEnt.Erase(true);

                //join intersection pieces as spline (maynot be possible)
                //convert collection of splines/lines to single 3Dspline
                Spline springSpline = Intersect_Surfaces.mergeSpline(springParts);
                btr.AppendEntity(springSpline);
                tr.AddNewlyCreatedDBObject(springSpline, true);

                //loft along spline
                try
                {
                    //create circle to to sweep
                    Circle wireGauge = new Circle();
                    wireGauge.Center = springSpline.StartPoint;
                    wireGauge.Radius = .06425;//diameter .1285
                    //Entity sweepEnt = tr.GetObject();

                    Curve pathEnt = tr.GetObject(springSpline.Id, OpenMode.ForRead) as Curve;
                    //Curve pathEnt = tr.GetObject(pLine.Id, OpenMode.ForRead) as Curve;
                    if (wireGauge == null || pathEnt == null)
                    {
                        ed.WriteMessage("\nProblem getting spline made");
                        return;
                    }

                    //builder object to create sweepoptions
                    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 = pathEnt.StartPoint;

                    //the profile will rotate to follow the path
                    sob.Bank = true;

                    Entity  ent;
                    Solid3d sol = new Solid3d();
                    sol.CreateSweptSolid(wireGauge, pathEnt, sob.ToSweepOptions());
                    ent = sol;

                    //and add it to the modelspace
                    btr.AppendEntity(ent);
                    tr.AddNewlyCreatedDBObject(ent, true);
                }
                catch { }

                //re-align spring to first points chosen by user
                tr.Commit();
            }
        }
예제 #35
0
        public void PprArc()

        {
            //准备工作

            Document doc = Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            Transaction trans = db.TransactionManager.StartTransaction();

            BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;

            BlockTableRecord btr = trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;



            PromptPointOptions ppo = new PromptPointOptions("");

            PromptPointResult ppr;

            Point3d temp = new Point3d();

            Point2d p1, p2;

            //获取两个点

            ppo.Message = "\n请输入第一个点:";

            do

            {
                ppr = ed.GetPoint(ppo);

                temp = ppr.Value;

                p1 = new Point2d(temp.X, temp.Y);
            } while (ppr.Status != PromptStatus.OK);



            ppo.Message = "\n请输入第二个点:";

            do

            {
                ppr = ed.GetPoint(ppo);

                temp = ppr.Value;

                p2 = new Point2d(temp.X, temp.Y);
            } while (ppr.Status != PromptStatus.OK);



            double L = p1.GetDistanceTo(p2);

            double R = 0;



            //获取半径

            do

            {//避免出现半径比弦长一半还小的情况出现
                PromptDoubleOptions pdo = new PromptDoubleOptions("\n最后,请输入半径:");

                PromptDoubleResult pdr = ed.GetDouble(pdo);

                if (pdr.Status == PromptStatus.OK)
                {
                    R = pdr.Value;
                }
            } while (R < L / 2);

            double H = R - Math.Sqrt(R * R - L * L / 4);



            Polyline poly = new Polyline();

            poly.AddVertexAt(0, p1, 2 * H / L, 0, 0);

            poly.AddVertexAt(1, p2, 0, 0, 0);

            btr.AppendEntity(poly);

            trans.AddNewlyCreatedDBObject(poly, true);

            trans.Commit();

            trans.Dispose();
        }
        public void JigGrid()
        {
            var doc = Application.DocumentManager.MdiActiveDocument;

            if (null == doc)
            {
                return;
            }
            var db = doc.Database;
            var ed = doc.Editor;

            // Get overall dimensions of the puzzle

            var pdo = new PromptDoubleOptions("\nEnter puzzle width");

            pdo.AllowNegative = false;
            pdo.AllowNone     = false;
            pdo.AllowZero     = false;

            var pdr = ed.GetDouble(pdo);

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

            var width = pdr.Value;

            pdo.Message = "\nEnter puzzle height";
            pdr         = ed.GetDouble(pdo);
            if (pdr.Status != PromptStatus.OK)
            {
                return;
            }

            var height = pdr.Value;

            // Get the (approximate) number of pieces

            var pio =
                new PromptIntegerOptions("\nApproximate number of pieces");

            pio.AllowNegative = false;
            pio.AllowNone     = false;
            pio.AllowZero     = false;

            var pir = ed.GetInteger(pio);

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

            var pieces = pir.Value;

            RectangularJigsaw(
                ed, db,
                new Parameters()
            {
                Width = width, Height = height, Pieces = pieces
            },
                null
                );
        }
예제 #37
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="H"></param>
        /// <param name="zMin"></param>
        void Window(double H, PromptDoubleResult zMin)
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            PromptDoubleOptions zMinWindowO = new PromptDoubleOptions("\nEnter window Z-min level:");

            zMinWindowO.DefaultValue = zMinWindowOld;
            PromptDoubleResult zMinWindow = ed.GetDouble(zMinWindowO);

            if (zMinWindow.Status != PromptStatus.OK || zMinWindow.Status != PromptStatus.Cancel)
            {
                return;
            }
            zMinWindowOld = zMinWindow.Value;

            double             height;
            PromptDoubleResult zMax;
            PromptDoubleResult heightResult;

            // Enter Z-max (and check if > Z-min) or Height
            while (true)
            {
                PromptDoubleOptions zMaxO = new PromptDoubleOptions("\nEnter Z-max level or ");
                zMaxO.DefaultValue = zMaxWindowOld;
                zMaxO.Keywords.Add("Height");
                zMax = ed.GetDouble(zMaxO);
                if (zMax.Status == PromptStatus.Keyword && zMax.StringResult == "Height")
                {
                    PromptDoubleOptions heightO = new PromptDoubleOptions("\nEnter height:");
                    heightO.DefaultValue  = heightWindowOld;
                    heightO.AllowNone     = false;
                    heightO.AllowZero     = false;
                    heightO.AllowNegative = false;
                    heightResult          = ed.GetDouble(heightO);
                    if (heightResult.Status == PromptStatus.OK)
                    {
                        height          = heightResult.Value;
                        heightWindowOld = heightResult.Value;
                        break;
                    }
                }
                else if (zMax.Status != PromptStatus.OK)
                {
                    Utils.Utils.End(); return;
                }
                else if (zMax.Value <= zMin.Value)
                {
                    ed.WriteMessage("\nZ-max level should be greater than Z-min level");
                }
                else
                {
                    zMaxWindowOld = zMax.Value;
                    height        = zMax.Value - zMin.Value;
                    break;
                }
            }

            string currentLayer = Utils.Layers.CurrentLayer();

            Utils.Utils.SetUCS(zMinWindow.Value);
            while (true)
            {
                PromptPointOptions p1O = new PromptPointOptions("\nPick window first corner:");
                PromptPointResult  p1  = ed.GetPoint(p1O);
                if (p1.Status == PromptStatus.Cancel)
                {
                    break;
                }
                if (p1.Status != PromptStatus.OK)
                {
                    return;
                }

                while (true)
                {
                    var p2 = ed.GetUcsCorner("\nPick window opposite corner: ", p1.Value);
                    if (p2.Status == PromptStatus.Cancel)
                    {
                        break;
                    }
                    if (p2.Status != PromptStatus.OK)
                    {
                        return;
                    }

                    if (p1.Value.X != p2.Value.X && p1.Value.Y != p2.Value.Y)
                    {
                        Utils.Utils.CreateBox(p1.Value, p2.Value, zMinWindow.Value, zMin.Value);
                        Utils.Utils.CreateBox(p1.Value, p2.Value, H - (zMinWindow.Value + height), zMinWindow.Value + height);

                        PromptKeywordOptions holeO = new PromptKeywordOptions("\nLeave hole?");
                        holeO.Keywords.Add("Yes");
                        holeO.Keywords.Add("No");
                        holeO.Keywords.Default = "Yes";
                        holeO.AllowNone        = false;
                        PromptResult holeR = ed.GetKeywords(holeO);
                        if (holeR.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        if (holeR.StringResult == "No")
                        {
                            Utils.Layers.CreateLayerForCurrentFloor("!FDS_OBST[glass]");
                            Utils.Layers.SetLayerForCurrentFloor("!FDS_OBST[glass]");
                            Utils.Utils.CreateBox(p1.Value, p2.Value, height, zMinWindow.Value);
                            Utils.Layers.SetLayer(currentLayer);
                        }
                        break;
                    }
                    else
                    {
                        ed.WriteMessage("\nPick correct corner!");
                    }
                }
            }
            Utils.Utils.SetGlobalUCS(zMin.Value);
            return;
        }
        public void getang()
        {
            Autodesk.AutoCAD.ApplicationServices.Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;

            string filepath = "D:\\tdoc.docx";

            using (WordprocessingDocument docX = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                try
                {
                    // Add a main document part.
                    MainDocumentPart mainPart = docX.AddMainDocumentPart();
                    StyleDefinitionsPart styleDefinitionsPart = mainPart.AddNewPart<StyleDefinitionsPart>();
                    Styles styles1 = new Styles();
                    DocDefaults docDefaults =
                        new DocDefaults(
                            new RunPropertiesDefault(new RunPropertiesBaseStyle(new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            }, new FontSize() { Val = "24" },
                                new FontSizeComplexScript() { Val = "24" })),
                                new ParagraphPropertiesDefault(new SpacingBetweenLines() { After = "0", Line = "240", LineRule = LineSpacingRuleValues.Auto }));
                    styles1.AppendChild(docDefaults);
                    styleDefinitionsPart.Styles = styles1;

                    mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                    DocumentFormat.OpenXml.Wordprocessing.Body body = mainPart.Document.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Body());
                    ParagraphProperties paragraphProperties1 = new ParagraphProperties(
                        new Justification() { Val = JustificationValues.Center },
                        new ParagraphMarkRunProperties(
                            new RunFonts()
                            {
                                Ascii = "Times New Roman",
                                HighAnsi = "Times New Roman",
                                ComplexScript = "Times New Roman"
                            },
                            new FontSize() { Val = "24" },
                            new FontSizeComplexScript() { Val = "24" }
                            ));

                    Paragraph para = body.AppendChild(new Paragraph());
                    para.AppendChild(paragraphProperties1);

                    Run run = para.AppendChild(new Run());

                    RunProperties runProperties1 = new RunProperties(
                        new Bold());

                    // String msg contains the text, "Hello, Word!"
                    run.AppendChild(runProperties1);
                    run.AppendChild(new Text("ПРИЛОЖЕНИЕ Ф"));
                    run.AppendChild(new Break());
                    run.AppendChild(new Text("Ведомость углов поворотов"));
                    run.AppendChild(new Break());

                    var table = new DocumentFormat.OpenXml.Wordprocessing.Table();
                    // Create a TableProperties object and specify its border information.
                    TableProperties tblProp = new TableProperties(
                        new TableWidth() { Width = "9782", Type = TableWidthUnitValues.Dxa },
                        new TableIndentation() { Width = -318, Type = TableWidthUnitValues.Dxa },
                        new TableBorders(
                            new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 },
                            new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 4, Space = 0 }),
                        new DocumentFormat.OpenXml.Wordprocessing.TableStyle() { Val = "TableGrid" }
                        );

                    // Append the TableProperties object to the empty table.
                    table.AppendChild<TableProperties>(tblProp);

                    // Add 3 columns to the table.
                    TableGrid tg = new TableGrid(new GridColumn(), new GridColumn(), new GridColumn(), new GridColumn(),
                        new GridColumn(), new GridColumn(), new GridColumn());
                    table.AppendChild(tg);

                    TableRow tr1 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 430 }),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1709" },
                                new VerticalMerge() { Val = MergedCellValues.Restart },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Обозначение точки")))),
                        //new TableCellProperties(new TableCellWidth() {Type = TableWidthUnitValues.Pct, Width = "500"})
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 2 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "3922" }),
                            new Paragraph(
                                new ParagraphProperties(new Justification() { Val = JustificationValues.Center }),
                                new Run(new Text("Координаты точки")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1358" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new VerticalMerge() { Val = MergedCellValues.Restart }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Пикетаж")))),
                        new TableCell(
                            new TableCellProperties(
                                new GridSpan() { Val = 2 },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center },
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2368" }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()),
                                new Run(new Text("Угол")))),
                        new TableCell(new TableCellProperties(
                            new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "425" },
                            new VerticalMerge() { Val = MergedCellValues.Restart },
                            new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Прямая вставка, м"))))
                        );
                    table.AppendChild(tr1);
                    TableRow tr2 = new TableRow(
                        new TableRowProperties(new TableRowHeight() { Val = 419 }),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("Y")))),
                        new TableCell(
                            new TableCellProperties(new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new ParagraphProperties(new Justification() { Val = JustificationValues.Center }), new Paragraph(new Run(new Text("X")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1260" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Лево")))),
                        new TableCell(
                            new TableCellProperties(
                                new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1108" },
                                new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }),
                            new Paragraph(new ParagraphProperties(GetCenterJustify()), new Run(new Text("Право")))),
                        new TableCell(new TableCellProperties(new VerticalMerge()), new Paragraph(new Run())));
                    table.AppendChild(tr2);

                    TableCellProperties tcp = new TableCellProperties(new GridSpan() { Val = 7 });

                    while (true)
                    {
                        double dist = 0, paste = 0;

                        table.AppendChild(new TableRow(
                            new TableCell(
                                new TableCellProperties(
                                    new GridSpan() { Val = 7 }),
                                    new Paragraph(
                                        new ParagraphProperties(
                                            new ParagraphMarkRunProperties(new Bold()),
                                            new Justification() { Val = JustificationValues.Center }),
                                            new Run(new RunProperties(
                                                new Bold()),
                                                new Text("Трасса"))))));

                        PromptEntityOptions peo = new PromptEntityOptions("\nВыбери polyline: ");
                        peo.SetRejectMessage("Можно только polyline.");
                        peo.AddAllowedClass(typeof(Polyline), true);
                        PromptEntityResult per = ed.GetEntity(peo);
                        if (per.Status != PromptStatus.OK) { break; }

                        PromptPointResult pPtRes;
                        PromptPointOptions pPtOpts = new PromptPointOptions("");
                        // Prompt for the start point
                        pPtOpts.Message = "\nВведи начало: ";
                        pPtRes = doc.Editor.GetPoint(pPtOpts);

                        PromptDoubleOptions getpik = new PromptDoubleOptions("\nВведи пикетаж (в формате числа, а не 0+00): ");
                        PromptDoubleResult getpikRes = doc.Editor.GetDouble(getpik);
                        dist = 100 * getpikRes.Value;

                        /*
                        PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter your name: ");
                        pStrOpts.AllowSpaces = true;
                        PromptResult pStrRes = doc.Editor.GetString(pStrOpts);
                        Application.ShowAlertDialog("The name entered was: " + pStrRes.StringResult);
                         */

                        Point3d curr = pPtRes.Value, next = pPtRes.Value;
                        try
                        {
                            using (Transaction tr = db.TransactionManager.StartTransaction())
                            {
                                Polyline pline = (Polyline)tr.GetObject(per.ObjectId, OpenMode.ForRead);
                                if ((pPtRes.Value == pline.GetLineSegmentAt(0).StartPoint) || (pPtRes.Value == pline.GetLineSegmentAt(0).EndPoint))
                                    for (int i = 0; i < pline.NumberOfVertices - 2; i++)
                                    {
                                        TrassaRecord temp = new TrassaRecord();
                                        temp.Name = "ВТ" + (i + 1).ToString();

                                        LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                        LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                        double angle = GetPolylineShape(l1, l2, pline.Normal);
                                        if (angle > Math.PI)
                                        {
                                            if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y);
                                                next = l1.StartPoint;

                                                temp.CoordsX = l1.StartPoint.X.ToString("F");
                                                temp.CoordsY = l1.StartPoint.Y.ToString("F");
                                            }
                                            else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y);
                                                next = l1.EndPoint;

                                                temp.CoordsX = l1.EndPoint.X.ToString("F");
                                                temp.CoordsY = l1.EndPoint.Y.ToString("F");
                                            }
                                            angle = -(angle - Math.PI * 2.0) * 180.0 / Math.PI;
                                            ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60);

                                            temp.AngleT = TrassaRecord.Angle.Right;
                                            temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("F0") + "’";
                                        }
                                        else
                                        {
                                            if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y);
                                                next = l1.StartPoint;

                                                temp.CoordsX = l1.StartPoint.X.ToString("F");
                                                temp.CoordsY = l1.StartPoint.Y.ToString("F");
                                            }
                                            else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y);
                                                next = l1.EndPoint;

                                                temp.CoordsX = l1.EndPoint.X.ToString("F");
                                                temp.CoordsY = l1.EndPoint.Y.ToString("F");
                                            }
                                            angle = angle * 180.0 / Math.PI;
                                            ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60);

                                            temp.AngleT = TrassaRecord.Angle.Left;
                                            temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("F0") + "’";
                                        }

                                        paste = curr.DistanceTo(next);
                                        dist += paste;
                                        curr = next;
                                        ed.WriteMessage(" {0:0.00} {1:0.00}", dist, paste);

                                        temp.Piketaz = ((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F");
                                        temp.DirectInsert = paste.ToString("F");

                                        tr2 = new TableRow(
                                            new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run(new Text(temp.DirectInsert))))
                                            );
                                        table.AppendChild(tr2);
                                        tr1 = new TableRow(
                                            new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                            new TableCell(new Paragraph(new Run(new Text(temp.Name)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.CoordsX)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.CoordsY)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.Piketaz)))),
                                            new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Left) ? temp.AngleVal.ToString() : "")))),
                                            new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Right) ? temp.AngleVal.ToString() : "")))),
                                            new TableCell(new Paragraph(new Run()))
                                            );
                                        table.AppendChild(tr1);
                                    }
                                else
                                    for (int i = pline.NumberOfVertices - 3; i >= 0; i--)
                                    {
                                        TrassaRecord temp = new TrassaRecord();
                                        temp.Name = "ВУ" + (pline.NumberOfVertices - 2 - i).ToString();

                                        LineSegment3d l1 = pline.GetLineSegmentAt(i);
                                        LineSegment3d l2 = pline.GetLineSegmentAt(i + 1);
                                        double angle = GetPolylineShape(l1, l2, pline.Normal);
                                        if (angle > Math.PI)
                                        {
                                            if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y);
                                                next = l1.StartPoint;

                                                temp.CoordsX = l1.StartPoint.X.ToString("F");
                                                temp.CoordsY = l1.StartPoint.Y.ToString("F");
                                            }
                                            else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y);
                                                next = l1.EndPoint;

                                                temp.CoordsX = l1.EndPoint.X.ToString("F");
                                                temp.CoordsY = l1.EndPoint.Y.ToString("F");
                                            }
                                            angle = -(angle - Math.PI * 2.0) * 180.0 / Math.PI;
                                            ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60);

                                            temp.AngleT = TrassaRecord.Angle.Left;
                                            temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("00") + "’";
                                        }
                                        else
                                        {
                                            if ((l1.StartPoint == l2.StartPoint) || (l1.StartPoint == l2.EndPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.StartPoint.X, l1.StartPoint.Y);
                                                next = l1.StartPoint;

                                                temp.CoordsX = l1.StartPoint.X.ToString("F");
                                                temp.CoordsY = l1.StartPoint.Y.ToString("F");
                                            }
                                            else if ((l1.EndPoint == l2.EndPoint) || (l1.EndPoint == l2.StartPoint))
                                            {
                                                ed.WriteMessage("\n({0:0.00}, {1:0.00}): ", l1.EndPoint.X, l1.EndPoint.Y);
                                                next = l1.EndPoint;

                                                temp.CoordsX = l1.EndPoint.X.ToString("F");
                                                temp.CoordsY = l1.EndPoint.Y.ToString("F");
                                            }
                                            angle = angle * 180.0 / Math.PI;
                                            ed.WriteMessage("{0},{1:0}", (int)angle / 1, (angle % 1) * 60);

                                            temp.AngleT = TrassaRecord.Angle.Right;
                                            temp.AngleVal = ((int)angle / 1).ToString("F0") + "°" + ((angle % 1) * 60).ToString("00") + "’";
                                        }

                                        paste = curr.DistanceTo(next);
                                        dist += paste;
                                        curr = next;
                                        ed.WriteMessage(" {0:0.00} {1:0.00}", dist, paste);

                                        temp.Piketaz = ((int)dist / 100).ToString("F0") + "+" + (dist % 100).ToString("F");
                                        temp.DirectInsert = paste.ToString("F");

                                        tr2 = new TableRow(
                                            new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run())),
                                            new TableCell(new Paragraph(new Run(new Text(temp.DirectInsert))))
                                            );
                                        table.AppendChild(tr2);
                                        tr1 = new TableRow(
                                            new TableRowProperties(new TableRowHeight() { Val = 300 }),
                                            new TableCell(new Paragraph(new Run(new Text(temp.Name)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.CoordsX)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.CoordsY)))),
                                            new TableCell(new Paragraph(new Run(new Text(temp.Piketaz)))),
                                            new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Left) ? temp.AngleVal.ToString() : "")))),
                                            new TableCell(new Paragraph(new Run(new Text((temp.AngleT == TrassaRecord.Angle.Right) ? temp.AngleVal.ToString() : "")))),
                                            new TableCell(new Paragraph(new Run()))
                                            );
                                        table.AppendChild(tr1);
                                    }
                            }
                        }
                        catch
                        {
                            ed.WriteMessage("\nInvalid polyline.");
                        }
                    }

                    body.AppendChild(table);
                    body.AppendChild(
                        new SectionProperties(
                            new PageMargin()
                            {
                                Top = 1134,
                                Right = (UInt32Value)850U,
                                Bottom = 1134,
                                Left = (UInt32Value)1418U,
                                Header = (UInt32Value)708U,
                                Footer = (UInt32Value)708U,
                                Gutter = (UInt32Value)0U
                            }));
                    ed.WriteMessage("\nДокумент сохранен в D:\\tdoc.docx");
                }
                catch
                {
                    ed.WriteMessage("\nError.");
                }
            }
        }
예제 #39
0
        public void fOBST()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            Utils.Utils.Init();

            if (!Utils.Layers.CurrentLayer().Contains("!FDS_OBST"))
            {
                Utils.Layers.SetLayerForCurrentFloor("!FDS_OBST[inert]");
            }

            // Get zMin & zMax | height level
            PromptDoubleOptions zMinO = new PromptDoubleOptions("\nEnter Z-min level:");

            zMinO.DefaultValue = zMinOld;
            PromptDoubleResult zMin = ed.GetDouble(zMinO);

            if (zMin.Status != PromptStatus.OK)
            {
                Utils.Utils.End(); return;
            }
            zMinOld = zMin.Value;
            Utils.Utils.SetUCS(zMin.Value);

            double             height;
            PromptDoubleResult zMax;
            PromptDoubleResult heightResult;

            // Enter Z-max (and check if > Z-min) or Height
            while (true)
            {
                PromptDoubleOptions zMaxO = new PromptDoubleOptions("\nEnter Z-max level or ");
                zMaxO.DefaultValue = zMaxOld;
                zMaxO.Keywords.Add("Height");
                zMax = ed.GetDouble(zMaxO);
                if (zMax.Status == PromptStatus.Keyword && zMax.StringResult == "Height")
                {
                    PromptDoubleOptions heightO = new PromptDoubleOptions("\nEnter height:");
                    heightO.DefaultValue  = heightOld;
                    heightO.AllowNone     = false;
                    heightO.AllowZero     = false;
                    heightO.AllowNegative = false;
                    heightResult          = ed.GetDouble(heightO);
                    if (heightResult.Status == PromptStatus.OK)
                    {
                        height    = heightResult.Value;
                        heightOld = heightResult.Value;
                        break;
                    }
                }
                else if (zMax.Status != PromptStatus.OK)
                {
                    Utils.Utils.End(); return;
                }
                else if (zMax.Value <= zMin.Value)
                {
                    ed.WriteMessage("\nZ-max level should be greater than Z-min level");
                }
                else
                {
                    zMaxOld = zMax.Value;
                    height  = zMax.Value - zMin.Value;
                    break;
                }
            }

            PromptPointOptions p1O = new PromptPointOptions("\nSpecify first point or ");

            p1O.Keywords.Add("Door");
            p1O.Keywords.Add("Beam");
            p1O.Keywords.Add("Window");
            p1O.Keywords.Add("Slant");
            p1O.Keywords.Add("Hole");
            PromptPointResult p1;

            while (true)
            {
                p1 = ed.GetPoint(p1O);
                if (p1.Status == PromptStatus.Cancel)
                {
                    break;
                }
                if (p1.Status == PromptStatus.Keyword)
                {
                    switch (p1.StringResult)
                    {
                    case "Door":
                        Door(height, zMin);
                        break;

                    case "Beam":
                        Beam(height, zMin);
                        break;

                    case "Window":
                        Window(height, zMin);
                        break;

                    case "Slant":
                        Slant(height, zMin);
                        break;

                    case "Hole":
                        Hole(zMin);
                        break;
                    }
                }
                else if (p1.Status != PromptStatus.OK)
                {
                    break;
                }
                else
                {
                    while (true)
                    {
                        var p2 = ed.GetUcsCorner("\nPick wall opposite corner: ", p1.Value);
                        if (p2.Status != PromptStatus.OK)
                        {
                            Utils.Utils.End(); return;
                        }
                        if (p1.Value.X != p2.Value.X && p1.Value.Y != p2.Value.Y)
                        {
                            Utils.Utils.CreateBox(p1.Value, p2.Value, height, zMin.Value);
                            break;
                        }
                        else
                        {
                            ed.WriteMessage("\nPick correct corner!");
                        }
                    }
                }
            }
            Utils.Utils.End();
        }
예제 #40
0
        public static void GetLine()
        {
            var doc = Application.DocumentManager.MdiActiveDocument;
            var ed  = doc.Editor;
            var db  = doc.Database;

            var intOpts = new PromptIntegerOptions("\n请输入每隔多少毫米进行点的合并");

            var intRes = ed.GetInteger(intOpts);

            if (intRes.Status == PromptStatus.OK)
            {
                intCmeter = intRes.Value;
            }
            PromptDoubleOptions pkDbOpts = new PromptDoubleOptions("请输入容差");

            //不允许输入负数
            pkDbOpts.AllowNegative = false;

            var keyDoubleRes = ed.GetDouble(pkDbOpts);


            if (keyDoubleRes.Status == PromptStatus.OK)
            {
                rongCha = keyDoubleRes.Value;

                rongCha = rongCha > 500 ? 500 : rongCha;
            }

            PromptDoubleOptions pkDbOpts2 = new PromptDoubleOptions("请输入优化圆弧的范围");

            pkDbOpts2.AllowNegative = false;

            var keyDoubleRes2 = ed.GetDouble(pkDbOpts2);


            if (keyDoubleRes2.Status == PromptStatus.OK)
            {
                range = keyDoubleRes2.Value;
            }

            var selectRes = ed.GetSelection(/*new SelectionFilter(new[] { new TypedValue((int)DxfCode.Start, "POLYLINE") })*/);

            if (selectRes.Status == PromptStatus.OK)
            {
                var selectSet = selectRes.Value;



                List <Polyline3d> listPlold = MyForeach(selectSet);
                //Polyline polyy = MyForeach2(selectSet);

                /*Point2dCollection p3dcoll = new Point2dCollection();
                 *
                 * for (int i = 0; i < polyy.NumberOfVertices; i++)
                 * {
                 *  p3dcoll.Add(polyy.GetPoint2dAt(i));
                 * }*/

                if (null == listPlold || listPlold.Count < 1)
                {
                    return;
                }

                List <Point3dCollection> listP3dColl = new List <Point3dCollection>();

                foreach (var pl3d in listPlold)
                {
                    Point3dCollection p3dcoll1 = new Point3dCollection();

                    if (pl3d != null)
                    {
                        listP3dColl.Add(p3dcoll1);

                        using (var trans = db.TransactionManager.StartTransaction())
                        {
                            foreach (ObjectId objId in pl3d)
                            {
                                var vertex3d = trans.GetObject(objId, OpenMode.ForRead) as PolylineVertex3d;

                                p3dcoll1.Add(vertex3d.Position);
                            }
                        }
                    }
                }

                List <Polyline> listListPolyline     = new List <Polyline>();
                List <Polyline> listListEntity3      = new List <Polyline>();
                List <Polyline> listListEntsOptimize = new List <Polyline>();


                PromptResult re       = null;
                bool         isChoice = false;
                foreach (var p3dcoll in listP3dColl)
                {
                    /*
                     * 在多段线合并的时候,超过合并范围,会取消合并,
                     * 当取消合并为最小的3个点之后还是会超过合并范围,就直接做成polyline
                     * 有一个这样的polyline,就记录下它在listEntity下的索引
                     */
                    List <int> isPolineIndex = new List <int>();

                    List <Entity> listEntity       = new List <Entity>();
                    List <Entity> listEntity2      = new List <Entity>();
                    List <Entity> listEntity3      = new List <Entity>();//等距弧长多段线
                    List <Entity> listEntsOptimize = new List <Entity>();
                    //没合并一个Arc 就产生一个CirculaArc2d
                    List <CircularArc2d> listC2d = new List <CircularArc2d>();

                    for (int i = 0; i < p3dcoll.Count; i++)
                    {
                        int startIndex = i;

                        Point2d pit1 = new Point2d(p3dcoll[i].X, p3dcoll[i].Y);
                        Point2d pit2 = Point2d.Origin;
                        Point2d pit3 = Point2d.Origin;

                        if (i + 1 < p3dcoll.Count)
                        {
                            pit2 = new Point2d(p3dcoll[i + 1].X, p3dcoll[i + 1].Y);
                            i   += 1;
                        }

                        if (i + 1 < p3dcoll.Count)
                        {
                            pit3 = new Point2d(p3dcoll[i + 1].X, p3dcoll[i + 1].Y);
                            i   += 1;
                        }

                        double length = (pit2 - pit1).Length + (pit3 - pit2).Length;

                        //记录循环的点的个数
                        int mid = 0;

                        //当两个点的长度小于要合并的长度就继续循环下一个点
                        while (length < intCmeter)
                        {
                            if (i + 1 < p3dcoll.Count)
                            {
                                pit2 = pit3;
                                pit3 = new Point2d(p3dcoll[i + 1].X, p3dcoll[i + 1].Y);
                            }
                            else
                            {
                                break;
                            }
                            i += 1;

                            mid++;

                            length = (pit2 - pit1).Length + (pit3 - pit2).Length;
                        }
                        Point2d pitMid = Point2d.Origin;

                        //寻找这些要合并的点的中间的个点
                        if (mid / 2 > 0)
                        {
                            pitMid = new Point2d(p3dcoll[startIndex + mid / 2].X, p3dcoll[startIndex + mid / 2].Y);
                        }
                        else
                        {
                            pitMid = pit2;
                        }

                        if (i < p3dcoll.Count && pit3 != Point2d.Origin && pitMid != Point2d.Origin)
                        {
                            //合并成圆弧
                            Arc           arc  = GetArc(pit1, pitMid, pit3);
                            CircularArc2d c2d  = null;
                            Arc           arc2 = GetArc2(pit1, pitMid, pit3, ref c2d);


                            Arc arc3 = GetArc(pit1, pitMid, pit3);

                            //不计算容差的等距圆弧
                            listEntity3.Add(arc3);

                            //计算容差
                            if (!CalRongCha(c2d, startIndex, mid + 2, p3dcoll, listEntity, listEntity2, listC2d, isPolineIndex))
                            {
                                listEntity.Add(arc);
                                listEntity2.Add(arc2);
                                listC2d.Add(c2d);
                            }
                        }

                        if (i == p3dcoll.Count - 1)
                        {
                            break;
                        }
                        i -= 1;
                    }



                    //ed.WriteMessage("进行弧长优化");

                    for (int i = 0; i < listEntity2.Count; i++)
                    {
                        try
                        {
                            //如果是多段线,直接添加
                            if (isPolineIndex.Contains(i))
                            {
                                listEntsOptimize.Add(listEntity2[i]);
                            }
                            else
                            {
                                Arc arc = listEntity2[i] as Arc;

                                Arc arc2 = null;

                                //先把arc添加进去,如果进入while循环,在移除
                                if (arc != null && !listEntsOptimize.Contains(arc))
                                {
                                    listEntsOptimize.Add(arc);
                                }

                                if (i + 1 < listEntity2.Count)
                                {
                                    arc2 = listEntity2[i + 1] as Arc;

                                    if (arc2 == null)
                                    {
                                        listEntsOptimize.Add(listEntity2[i + 1]);
                                        continue;
                                    }

                                    if (arc2 != null && !listEntsOptimize.Contains(arc2))
                                    {
                                        listEntsOptimize.Add(arc2);
                                    }

                                    i += 1;
                                }

                                //要合并优化的圆弧
                                List <CircularArc2d> tempArc = new List <CircularArc2d>();

                                if (arc != null && arc2 != null)
                                {
                                    // double angle1 = arc.EndAngle - arc.StartAngle;

                                    //double angle2 = arc2.EndAngle - arc.StartAngle;

                                    Point3d pt1 = arc.Center;
                                    Point3d pt2 = arc2.Center;

                                    double diffRad = Math.Abs(arc.Radius - arc2.Radius) / Math.Max(arc.Radius, arc2.Radius);

                                    double diffLength = (pt2 - pt1).Length / Math.Min(arc.Radius, arc2.Radius);

                                    //while (Math.Abs(angle1 - angle2) <= Math.PI * (30.0 / 180))

                                    while (diffRad <= range && diffLength <= range)
                                    {
                                        if (listEntsOptimize.Contains(arc))
                                        {
                                            listEntsOptimize.Remove(arc);
                                        }

                                        if (listEntsOptimize.Contains(arc2))
                                        {
                                            listEntsOptimize.Remove(arc2);
                                        }

                                        int index = listEntity2.IndexOf(arc);

                                        int index2 = listEntity2.IndexOf(arc2);
                                        if (index != -1)
                                        {
                                            tempArc.Add(listC2d[index]);
                                        }
                                        if (index2 != -1)
                                        {
                                            tempArc.Add(listC2d[index2]);
                                        }

                                        if (i + 1 < listEntity2.Count)
                                        {
                                            arc2 = listEntity2[i + 1] as Arc;
                                            var po = listEntity2[i + 1] as Polyline;
                                            if (arc2 == null && po != null)
                                            {
                                                listEntsOptimize.Add(listEntity2[i + 1]);
                                                i += 1;
                                                continue;
                                            }
                                            else
                                            {
                                                i += 1;
                                            }
                                        }
                                        else
                                        {
                                            arc2 = null;
                                            break;
                                        }

                                        // angle1 = arc.EndAngle - arc.StartAngle;

                                        // angle2 = arc2.EndAngle - arc.StartAngle;
                                        pt1        = arc.Center;
                                        pt2        = arc2.Center;
                                        diffRad    = Math.Abs(arc.Radius - arc2.Radius) / Math.Max(arc.Radius, arc2.Radius);
                                        diffLength = (pt2 - pt1).Length / Math.Min(arc.Radius, arc2.Radius);
                                    }
                                }

                                //进行圆弧优化
                                if (tempArc.Count > 1)
                                {
                                    Arc     newTempArc = null;
                                    Point2d startPoint = tempArc[0].StartPoint;
                                    Point2d endPoint   = tempArc[tempArc.Count - 1].EndPoint;
                                    if (tempArc.Count == 2)
                                    {
                                        Point2d centerPoint = tempArc[0].EndPoint;

                                        newTempArc = GetArc(startPoint,
                                                            centerPoint, endPoint);
                                    }
                                    else
                                    {
                                        Point2d centerPoint = tempArc[1].EndPoint;

                                        newTempArc = GetArc(startPoint,
                                                            centerPoint, endPoint);
                                    }
                                    //   newTempArc.Color = Autodesk.AutoCAD.Colors.Color.FromColor(System.Drawing.Color.Red);

                                    listEntsOptimize.Add(newTempArc);
                                }

                                if (i == listEntity2.Count - 1)
                                {
                                    break;
                                }
                                i -= 1;
                            }
                        }
                        catch (System.Exception e)
                        {
                            throw;
                        }
                    }
                    try
                    {
                        listEntsOptimize = listEntsOptimize.Distinct().ToList();

                        List <Polyline> listPoly = ArcToPolyline(listEntity3);

                        List <Polyline> listPoly2 = ArcToPolyline(listEntsOptimize);

                        List <Polyline> listPoly3 = ArcToStraightLine(listEntsOptimize);

                        bool a = true, b = true, c = true;

                        Polyline poly = GetPolyline(listPoly, out a);//等距多段线

                        if (a)
                        {
                            poly.Color = Autodesk.AutoCAD.Colors.Color.FromColor(System.Drawing.Color.DeepPink);
                        }
                        else
                        {
                            poly = null;
                        }

                        Polyline poly2 = GetPolyline(listPoly2, out b);

                        if (b)
                        {
                            poly2.Color = Autodesk.AutoCAD.Colors.Color.FromColor(System.Drawing.Color.Red);
                        }
                        else
                        {
                            poly2 = null;
                        }

                        Polyline poly3 = GetPolyline(listPoly3, out c);//不等距优化后的多段直线
                        if (c)
                        {
                            poly3.Color = Autodesk.AutoCAD.Colors.Color.FromColor(System.Drawing.Color.DarkGreen);
                        }
                        else
                        {
                            poly3 = null;
                        }

                        listEntity3.ForEach(p => { p.Color = Autodesk.AutoCAD.Colors.Color.FromColor(System.Drawing.Color.DeepPink); });
                        listEntsOptimize.ForEach(p => { p.Color = Autodesk.AutoCAD.Colors.Color.FromColor(System.Drawing.Color.Red); });
                        listPoly3.ForEach(p => { p.Color = Autodesk.AutoCAD.Colors.Color.FromColor(System.Drawing.Color.DarkGreen); });

                        listListPolyline.Add(poly);
                        listListEntity3.Add(poly3);
                        listListEntsOptimize.Add(poly2);

                        if (!isChoice)
                        {
                            PromptKeywordOptions pkOpts = new PromptKeywordOptions("请输入结果A:等距弧形Polyline,B:优化后不等距弧形polyline,C:优化后多段直线[A/B/C]", "A B C");

                            re       = ed.GetKeywords(pkOpts);
                            isChoice = true;
                        }


                        if (re.Status == PromptStatus.OK && re.StringResult == "A")
                        {
                            //poly!=null? poly.ToSpace():listEntity3.ToSpace();

                            if (poly == null)
                            {
                                listEntity3.ToSpace();
                            }
                            else
                            {
                                poly.ToSpace();
                            }
                        }
                        else if (re.Status == PromptStatus.OK && re.StringResult == "B")
                        {
                            // listListEntsOptimize[i].TransformBy(Matrix3d.Displacement(pt3Arr[2] - Point3d.Origin));

                            if (poly2 == null)
                            {
                                listEntsOptimize.ToSpace();
                            }
                            else
                            {
                                poly2.ToSpace();
                            }
                        }
                        else
                        {
                            //listListEntity3[i].TransformBy(Matrix3d.Displacement(pt3Arr[1] - Point3d.Origin));


                            if (poly3 == null)
                            {
                                listPoly3.ToSpace();
                            }
                            else
                            {
                                poly3.ToSpace();
                            }
                        }


                        //var newDoc = Application.DocumentManager.Add("");
                        //using (var lock1 = newDoc.LockDocument())
                        //{
                        //    var newDb = newDoc.Database;

                        //    if (keyRes.Status == PromptStatus.OK && keyRes.StringResult == "Y")
                        //        poly2.ToSpace(newDb);
                        //    else
                        //        poly.ToSpace(newDb);


                        //}
                    }

                    catch (System.Exception e)
                    {
                        throw;
                    }
                    finally
                    {
                        listEntity.Clear();
                        listEntity2.Clear();
                        listC2d.Clear();
                        //    listEntity3.Clear();
                        isPolineIndex.Clear();
                    }
                }


                //RemoveTwo(listListPolyline);
                // RemoveTwo(listListEntsOptimize);
                // RemoveTwo(listListEntity3);


                //     PromptKeywordOptions pkOpts = new PromptKeywordOptions("请输入结果A:等距弧形Polyline,B:优化后不等距弧形polyline,C:优化后多段直线[A/B/C]", "A B C");

                //      var re = ed.GetKeywords(pkOpts);



                //if (re.Status == PromptStatus.OK && re.StringResult == "A")
                //{

                //    for (int i = 0; i < listListPolyline.Count; i++)
                //    {
                //        listListPolyline[i].TransformBy(Matrix3d.Displacement(pt3Arr[0] - Point3d.Origin));

                //        listListPolyline[i].ToSpace();
                //    }

                //}
                //else if (re.Status == PromptStatus.OK && re.StringResult == "B")
                //{
                //    for (int i = 0; i < listListEntsOptimize.Count; i++)
                //    {
                //        listListEntsOptimize[i].TransformBy(Matrix3d.Displacement(pt3Arr[2] - Point3d.Origin));
                //        listListEntsOptimize[i].ToSpace();
                //    }
                //}
                //else
                //{

                //    for (int i = 0; i < listListEntity3.Count; i++)
                //    {

                //        listListEntity3[i].TransformBy(Matrix3d.Displacement(pt3Arr[1] - Point3d.Origin));

                //        listListEntity3[i].ToSpace();
                //    }

                //}
            }
        }
예제 #41
0
        public void fHOLE()
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            Utils.Utils.Init();
            Utils.Layers.SetLayerForCurrentFloor("!FDS_HOLE");
            string currentLayer = Utils.Layers.CurrentLayer();

            Utils.Layers.SetLayerForCurrentFloor("!FDS_HOLE");

            PromptDoubleOptions zMinHoleO = new PromptDoubleOptions("\nEnter hole Z-min level:");

            zMinHoleO.DefaultValue = zMinHoleOld;
            PromptDoubleResult zMinHole = ed.GetDouble(zMinHoleO);

            if (zMinHole.Status != PromptStatus.OK)
            {
                return;
            }
            zMinHoleOld = zMinHole.Value;

            double             height;
            PromptDoubleResult zMax;
            PromptDoubleResult heightResult;

            // Enter Z-max (and check if > Z-min) or Height
            while (true)
            {
                PromptDoubleOptions zMaxO = new PromptDoubleOptions("\nEnter Z-max level or ");
                zMaxO.DefaultValue = zMaxHoleOld;
                zMaxO.Keywords.Add("Height");
                zMax = ed.GetDouble(zMaxO);
                if (zMax.Status == PromptStatus.Keyword && zMax.StringResult == "Height")
                {
                    PromptDoubleOptions heightO = new PromptDoubleOptions("\nEnter height:");
                    heightO.DefaultValue  = heightHoleOld;
                    heightO.AllowNone     = false;
                    heightO.AllowZero     = false;
                    heightO.AllowNegative = false;
                    heightResult          = ed.GetDouble(heightO);
                    if (heightResult.Status == PromptStatus.OK)
                    {
                        height        = heightResult.Value;
                        heightHoleOld = heightResult.Value;
                        break;
                    }
                }
                else if (zMax.Status != PromptStatus.OK)
                {
                    Utils.Utils.End(); return;
                }
                else if (zMax.Value <= zMinHole.Value)
                {
                    ed.WriteMessage("\nZ-max level should be greater than Z-min level");
                }
                else
                {
                    zMaxHoleOld = zMax.Value;
                    height      = zMax.Value - zMinHole.Value;
                    break;
                }
            }

            Utils.Utils.SetUCS(zMinHole.Value);
            while (true)
            {
                PromptPointOptions p1O = new PromptPointOptions("\nPick hole first corner:");
                PromptPointResult  p1  = ed.GetPoint(p1O);
                if (p1.Status == PromptStatus.Cancel)
                {
                    break;
                }
                if (p1.Status != PromptStatus.OK)
                {
                    return;
                }

                while (true)
                {
                    var p2 = ed.GetUcsCorner("\nPick hole opposite corner: ", p1.Value);
                    if (p2.Status == PromptStatus.Cancel)
                    {
                        break;
                    }
                    if (p2.Status != PromptStatus.OK)
                    {
                        return;
                    }

                    if (p1.Value.X != p2.Value.X && p1.Value.Y != p2.Value.Y)
                    {
                        Utils.Utils.CreateBox(p1.Value, p2.Value, height, zMinHole.Value);
                        Utils.Layers.SetLayer(currentLayer);
                        break;
                    }
                    else
                    {
                        ed.WriteMessage("\nPick correct corner!");
                    }
                }
            }
            Utils.Utils.End();
            return;
        }
예제 #42
0
        public static void DoIt()
        {
            Document            doc       = Application.DocumentManager.MdiActiveDocument;
            Editor              ed        = doc.Editor;
            PromptDoubleOptions optDouble = new PromptDoubleOptions("\n请输入箭头长度:");

            optDouble.AllowNone       = true;
            optDouble.AllowZero       = false;
            optDouble.DefaultValue    = CurrArrowLength;
            optDouble.UseDefaultValue = true;
            PromptDoubleResult resDouble = ed.GetDouble(optDouble);

            if (resDouble.Status == PromptStatus.OK)
            {
                //改变箭头长度设定值
                CurrArrowLength = resDouble.Value;
                PromptPointResult resStartPoint = ed.GetPoint("\n请输入起点:");
                if (resStartPoint.Status == PromptStatus.OK)
                {
                    PromptPointOptions optEndPoint = new PromptPointOptions("\n请输入终点:");
                    optEndPoint.BasePoint    = resStartPoint.Value;
                    optEndPoint.UseBasePoint = true;
                    PromptPointResult resEndPoint = ed.GetPoint(optEndPoint);
                    if (resEndPoint.Status == PromptStatus.OK)
                    {
                        Point3d  startpnt = resStartPoint.Value;
                        Point3d  endpnt   = resEndPoint.Value;
                        Database db       = doc.Database;
                        using (Transaction tr = db.TransactionManager.StartTransaction())
                        {
                            BlockTableRecord btr =
                                (BlockTableRecord)tr.GetObject(
                                    db.CurrentSpaceId,
                                    OpenMode.ForWrite,
                                    false);
                            Line line = new Line(startpnt, endpnt);
                            btr.AppendEntity(line);
                            tr.AddNewlyCreatedDBObject(line, true);
                            RegAppTable rat =
                                (RegAppTable)tr.GetObject(
                                    db.RegAppTableId,
                                    OpenMode.ForRead,
                                    false);
                            if (!rat.Has(RegAppName))
                            {
                                rat.UpgradeOpen();
                                RegAppTableRecord regapp = new RegAppTableRecord();
                                regapp.Name = RegAppName;
                                rat.Add(regapp);
                                tr.AddNewlyCreatedDBObject(regapp, true);
                            }
                            Point3d midpnt = (startpnt + endpnt.GetAsVector()) / 2;
                            LArrow3 la     = new LArrow3(line);
                            //附着当前设定的箭头长度
                            la.ArrowLength = CurrArrowLength;
                            la.Scale       = 0.5;
                            la.SaveExtendedData();
                            tr.Commit();
                        }
                    }
                }
            }
        }
예제 #43
0
        /// <summary>
        ///     TODO
        /// </summary>
        public void GetOutput()
        {
            switch (T)
            {
            case TypeCode.Int16:
            case TypeCode.Int32:
            case TypeCode.Int64:

                var prIntOpts = new PromptIntegerOptions(string.Empty)
                {
                    Message       = Prompt,
                    AllowNone     = false,
                    AllowNegative = false
                };

                if (DefValue != null)
                {
                    try
                    {
                        prIntOpts.DefaultValue    = int.Parse(DefValue);
                        prIntOpts.UseDefaultValue = true;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        throw;
                    }
                }


                //Prompt the editor to receive the double from the user
                var prIntRes = _acCurEd.GetInteger(prIntOpts);

                //If bad input -> return 0
                if (prIntRes.Status != PromptStatus.OK)
                {
                    Output = 0;
                }

                //Return the distance entered into the editor
                Output = prIntRes.Value;
                break;

            case TypeCode.Double:
                var prDobOpts = new PromptDoubleOptions(string.Empty)
                {
                    Message       = Prompt,
                    AllowNone     = false,
                    AllowNegative = true
                };

                if (DefValue != null)
                {
                    try
                    {
                        prDobOpts.DefaultValue    = double.Parse(DefValue);
                        prDobOpts.UseDefaultValue = true;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        throw;
                    }
                }

                //Prompt the editor to receive the double from the user
                var prDobRes = _acCurEd.GetDouble(prDobOpts);

                //If bad input -> return 0
                if (prDobRes.Status != PromptStatus.OK)
                {
                    Output = 0;
                }

                //Return the double entered into the editor
                Output = prDobRes.Value;
                break;

            case TypeCode.String:

                var prStrOpts = new PromptStringOptions(string.Empty)
                {
                    Message         = Prompt,
                    DefaultValue    = DefValue,
                    UseDefaultValue = DefValue != string.Empty
                };

                //Prompt the editor to receive the string from the user
                var prStrRes = _acCurEd.GetString(prStrOpts);

                //If bad input -> return ""
                if (prStrRes.Status != PromptStatus.OK)
                {
                    Output = string.Empty;
                }

                //Return the string entered into the editor
                Output = prStrRes.StringResult;
                break;

            case TypeCode.Boolean:
                var bTrue  = "Yes";
                var bFalse = "No";
                var keys   = new[] { bTrue, bFalse };

                var prKeyOpts = new PromptKeywordOptions(string.Empty)
                {
                    Message   = Prompt + " <" + DefValue + "> ",
                    AllowNone = false
                };


                //Append keywords to the message
                foreach (var key in keys)
                {
                    prKeyOpts.Keywords.Add(key);
                }

                var prKeyRes = _acCurEd.GetKeywords(prKeyOpts);

                // If bad input -> return null
                if (prKeyRes.Status != PromptStatus.OK)
                {
                    Output = false;
                }

                //Return the keyword selected in the editor
                Output = prKeyRes.StringResult == bTrue;
                break;
            }

            if (Output != null)
            {
                DefValue = Output.ToString();
            }
        }
예제 #44
0
        public void Create()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor;
            try
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    //Prompts for each employee detail
                    PromptStringOptions prName = new PromptStringOptions("Enter Employee Name");
                    PromptStringOptions prDiv = new PromptStringOptions("Enter Employee Division");
                    PromptDoubleOptions prSal = new PromptDoubleOptions("Enter Employee Salary");
                    PromptPointOptions prPos = new PromptPointOptions("Enter Employee Position or");

                    //Add keywords when prompting for position
                    prPos.Keywords.Add("Name");
                    prPos.Keywords.Add("Division");
                    prPos.Keywords.Add("Salary");

                    //Set the default values for each of these
                    prName.DefaultValue = "Earnest Shackleton";
                    prDiv.DefaultValue = "Sales";
                    prSal.DefaultValue = 10000.0f;

                    //Set conditions for prompting
                    prPos.AllowNone = false; //Do not allow null values

                    //prompt results - set explicitly to null 
                    PromptResult prNameRes = null;
                    PromptResult prDivRes = null;
                    PromptDoubleResult prSalRes = null;
                    PromptPointResult prPosRes = null;

                    //Loop to get employee details. Exit the loop when positon is entered
                    while (prPosRes == null || prPosRes.Status != PromptStatus.OK)
                    {
                        //Prompt for position
                        prPosRes = ed.GetPoint(prPos);
                        if (prPosRes.Status == PromptStatus.Keyword) //Got a keyword
                        {
                            switch (prPosRes.StringResult)
                            {
                                case "Name":
                                    //Get employee name
                                    prName.AllowSpaces = true;
                                    prNameRes = ed.GetString(prName);
                                    if (prNameRes.Status != PromptStatus.OK)
                                        throw new System.Exception("Error or User Cancelled");
                                    break;
                                case "Division":
                                    //Get employee division
                                    prDiv.AllowSpaces = true;
                                    prDivRes = ed.GetString(prDiv);
                                    if (prDivRes.Status != PromptStatus.OK)
                                        throw new System.Exception("Error or User Cancelled");
                                    break;
                                case "Salary":
                                    //Get employee salary
                                    prSal.AllowNegative = false;
                                    prSal.AllowNone = true;
                                    prSal.AllowZero = false;
                                    prSalRes = ed.GetDouble(prSal);
                                    if (prSalRes.Status != PromptStatus.OK & prSalRes.Status != PromptStatus.None)
                                        throw new System.Exception("Error or User Cancelled");
                                    break;
                            }
                        }
                        if (prPosRes.Status == PromptStatus.Cancel || prPosRes.Status == PromptStatus.Error)
                            throw new System.Exception("Error or User Cancelled");
                    }

                    //Create the Employee - either use the input value or the default value...
                    string empName = (prNameRes == null ? prName.DefaultValue : prNameRes.StringResult);
                    string divName = (prDivRes == null ? prDiv.DefaultValue : prDivRes.StringResult);
                    double salary = (prSalRes == null ? prSal.DefaultValue : prSalRes.Value);

                    CreateEmployee(empName, divName, salary, prPosRes.Value);


                    //Now create the division 
                    //Pass an empty string for manager to check if it already exists
                    string manager = "";
                    ObjectId xRecId = CreateDivision(divName, manager);

                    //Open the department manager XRecord
                    Xrecord depMgrXRec = (Xrecord)trans.GetObject(xRecId, OpenMode.ForRead);
                    TypedValue[] typedVal = depMgrXRec.Data.AsArray();
                    foreach (TypedValue val in typedVal)
                    {
                        string str = (string)val.Value;
                        if (str == "")
                        {
                            //Manager was not set, now set it
                            // Prompt for  manager name first
                            ed.WriteMessage("\r\n");
                            PromptStringOptions prManagerName = new PromptStringOptions("No manager set for the division! Enter Manager Name");
                            prManagerName.DefaultValue = "Delton T. Cransley";
                            prManagerName.AllowSpaces = true;
                            PromptResult prManagerNameRes = ed.GetString(prManagerName);
                            if (prManagerNameRes.Status != PromptStatus.OK)
                                throw new System.Exception("Error or User Cancelled");
                            //Set a manager name
                            depMgrXRec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Text, prManagerNameRes.StringResult));
                        }
                    }
                    trans.Commit();
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nError: " + ex.Message + "\n");
            }
        }
    public void ImportFromKinect()
    {
      Document doc =
        Autodesk.AutoCAD.ApplicationServices.
          Application.DocumentManager.MdiActiveDocument;
      Editor ed = doc.Editor;

      // Get some user input for the number of snapshots...

      PromptIntegerOptions pio =
        new PromptIntegerOptions("\nNumber of captures");
      pio.AllowZero = false;
      pio.DefaultValue = _numShots;
      pio.UseDefaultValue = true;
      pio.UpperLimit = 20;
      pio.LowerLimit = 1;

      PromptIntegerResult pir = ed.GetInteger(pio);

      if (pir.Status != PromptStatus.OK)
        return;

      _numShots = pir.Value;

      // ... and the delay between them

      PromptDoubleOptions pdo =
        new PromptDoubleOptions("\nNumber of seconds delay");
      pdo.AllowZero = false;
      pdo.AllowNegative = false;
      pdo.AllowArbitraryInput = false;
      pdo.DefaultValue = _delay;
      pdo.UseDefaultValue = true;

      PromptDoubleResult pdr = ed.GetDouble(pdo);

      if (pdr.Status != PromptStatus.OK)
        return;

      _delay = pdr.Value;

      Transaction tr =
        doc.TransactionManager.StartTransaction();

      KinectDelayJig kj = new KinectDelayJig(_numShots, _delay);

      if (!kj.StartSensor())
      {
        ed.WriteMessage(
          "\nUnable to start Kinect sensor - " +
          "are you sure it's plugged in?"
        );
        return;
      }
      
      PromptResult pr = ed.Drag(kj);
      if (pr.Status == PromptStatus.OK)
      {
        kj.StartTimer();
        pr = ed.Drag(kj);
      }
      kj.StopSensor();

      if (pr.Status != PromptStatus.OK && !kj.Finished)
      {
        tr.Dispose();
        return;
      }

      tr.Commit();

      // Manually dispose to avoid scoping issues with
      // other variables

      tr.Dispose();

      kj.WriteAndImportPointCloud(doc, kj.Vectors);
    }
예제 #46
0
        public static void getPointsFloor()
        {
            // Получение текущего документа и базы данных
            Document acDoc = Application.DocumentManager.MdiActiveDocument;
            Database acCurDb = acDoc.Database;
            TypeViewerForm tvf = new TypeViewerForm();

            // Старт транзакции
            using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())
            {
                PromptPointResult pPtRes;
                PromptPointOptions pPtOpts = new PromptPointOptions("");

                // Prompt for the start point
                pPtOpts.Message = "\nВведи начало на одном этаже: ";
                pPtRes = acDoc.Editor.GetPoint(pPtOpts);
                Data.floorPointsStart.Add(pPtRes.Value);

                if (!Data.pathPoints.Contains(pPtRes.Value))
                    Data.pathPoints.Add(pPtRes.Value);

                pPtOpts.Message = "\nВведи конец на другом этаже: ";
                pPtRes = acDoc.Editor.GetPoint(pPtOpts);
                Data.floorPointsEnd.Add(pPtRes.Value);

                if (!Data.pathPoints.Contains(pPtRes.Value))
                    Data.pathPoints.Add(pPtRes.Value);

                //PromptStringOptions psoOpt = new PromptStringOptions("nВведите имя блока: ");
                PromptDoubleResult psoRes;
                PromptDoubleOptions psoOpt = new PromptDoubleOptions("");

                psoOpt.Message = "\nВведите длину перехода: ";

                psoRes = acDoc.Editor.GetDouble(psoOpt);
                Data.floorPointsDistance.Add(psoRes.Value);

                // Сохранение нового объекта в базе данных
                acTrans.Commit();
            }
        }
        public static void CreateCloset()
        {
            _panels.Clear();

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

            Database db = activeDoc.Database;

            Editor ed = activeDoc.Editor;

            PromptDoubleOptions pdo = new PromptDoubleOptions("Total closet width in feet : ");
            PromptDoubleResult pdr = ed.GetDouble(pdo);
            if (pdr.Status != PromptStatus.OK)
                return;
            W = pdr.Value * 12.0;

            pdo = new PromptDoubleOptions("Total closet depth in feet : ");
            pdr = ed.GetDouble(pdo);
            if (pdr.Status != PromptStatus.OK)
                return;
            D = pdr.Value * 12.0;

            pdo = new PromptDoubleOptions("Total closet height in feet : ");
            pdr = ed.GetDouble(pdo);
            if (pdr.Status != PromptStatus.OK)
                return;
            H = pdr.Value * 12.0;

            pdo = new PromptDoubleOptions("Ply thickness in inches : ");
            pdr = ed.GetDouble(pdo);
            if (pdr.Status != PromptStatus.OK)
                return;
            t = pdr.Value;

            pdo = new PromptDoubleOptions("Door height as percentage of total closet height : ");
            pdr = ed.GetDouble(pdo);
            if (pdr.Status != PromptStatus.OK)
                return;
            doorH = H * pdr.Value * 0.01;

            PromptIntegerOptions pio = new PromptIntegerOptions("Number of drawer rows : ");
            PromptIntegerResult pir = ed.GetInteger(pio);
            if (pir.Status != PromptStatus.OK)
                return;
            N = pir.Value;

            pio = new PromptIntegerOptions("Split drawers ? (1 / 0) : ");
            pir = ed.GetInteger(pio);
            if (pir.Status != PromptStatus.OK)
                return;
            splitDrawers = (pir.Value != 0);

            ed.WriteMessage(String.Format("\nTotal closet width  : {0}", W));
            ed.WriteMessage(String.Format("\nTotal closet depth  : {0}", D));
            ed.WriteMessage(String.Format("\nTotal closet height : {0}", H));
            ed.WriteMessage(String.Format("\nPly thickness       : {0}", t));
            ed.WriteMessage(String.Format("\nDoor height : {0}", doorH));
            ed.WriteMessage(String.Format("\nNumber of drawer rows :  {0}", N));
            ed.WriteMessage(String.Format("\nSplit drawers ?  : {0}", splitDrawers ? "yes" : "no"));
           
            CreateHandleBlock();

            // Left
            PlyYZ(new Point2d[] { new Point2d(0.0, 0.0), 
                                            new Point2d(D-t, 0.0),
                                            new Point2d(D-t, H-2*t),
                                            new Point2d(0.0, H-2*t)
                                            }, new Point3d(0.0, t, t), WoodGrainAlignment.Vertical);
            _panels.Add(new PanelDetails("Left panel", String.Format("{0} x {1}", (D-t), H-2*t), 1));

            // Right
            PlyYZ(new Point2d[] { new Point2d(0.0, 0.0), 
                                            new Point2d(D-t, 0.0),
                                            new Point2d(D-t, H-2*t),
                                            new Point2d(0.0, H-2*t)
                                            }, new Point3d(W - t, t, t), WoodGrainAlignment.Vertical);
            _panels.Add(new PanelDetails("Right panel", String.Format("{0} x {1}", (D - t), H - 2 * t), 1));

            // Top
            PlyXY(new Point2d[] { new Point2d(0.0, 0.0), 
                                            new Point2d(W, 0.0),
                                            new Point2d(W, D-t),
                                            new Point2d(0.0, D-t)
                                            }, new Point3d(0.0, t, H - t), WoodGrainAlignment.Horizontal);
            _panels.Add(new PanelDetails("Top panel", String.Format("{0} x {1}", W, (D - t)), 1));

            // Bottom
            PlyXY(new Point2d[] { new Point2d(0.0, 0.0), 
                                            new Point2d(W, 0.0),
                                            new Point2d(W, D-t),
                                            new Point2d(0.0, D-t)
                                            }, new Point3d(0.0, t, 0.0), WoodGrainAlignment.Horizontal);
            _panels.Add(new PanelDetails("Bottom panel", String.Format("{0} x {1}", W, (D - t)), 1));

            // Back
            PlyXZ(new Point2d[] { new Point2d(0.0, 0.0), 
                                            new Point2d(-W+2*t, 0.0),
                                            new Point2d(-W+2*t, H-2*t),
                                            new Point2d(0.0, H-2*t)
                                            }, new Point3d(t, D - t, t), WoodGrainAlignment.Vertical);
            _panels.Add(new PanelDetails("Back panel", String.Format("{0} x {1}", W+2*t, H-2*t), 1));

            // Front twin doors
            // Left
            ObjectId leftDoorId = PlyXZ(new Point2d[] { new Point2d(0.0, 0.0), 
                                            new Point2d(-W * 0.5, 0.0),
                                            new Point2d(-W * 0.5, doorH),
                                            new Point2d(0.0, doorH)
                                            }, new Point3d(0.0, 0.0, H - doorH), WoodGrainAlignment.Vertical);
            _panels.Add(new PanelDetails("Front twin doors", String.Format("{0} x {1}", W * 0.5, doorH), 2));

            // Swing the door open
            // comment it to shut the drawer
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Entity ent = tr.GetObject(leftDoorId, OpenMode.ForWrite) as Entity;
                ent.TransformBy(Matrix3d.Rotation(-135 * Math.PI / 180.0, Vector3d.ZAxis, new Point3d(0.0, 0.0, H - doorH)));
                tr.Commit();
            }

            // Right
            ObjectId rightDoorId = PlyXZ(new Point2d[] { new Point2d(0.0, 0.0), 
                                            new Point2d(-W * 0.5, 0.0),
                                            new Point2d(-W * 0.5, doorH),
                                            new Point2d(0.0, doorH)
                                            }, new Point3d(W * 0.5, 0.0, H - doorH), WoodGrainAlignment.Vertical);

            // Swing the door open
            // comment it to shut the drawer
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Entity ent = tr.GetObject(rightDoorId, OpenMode.ForWrite) as Entity;
                ent.TransformBy(Matrix3d.Rotation(135 * Math.PI / 180.0, Vector3d.ZAxis, new Point3d(W, 0.0, H - doorH)));
                tr.Commit();
            }

            // Inner shelf divider
            PlyXY(new Point2d[] { new Point2d(0.0, 0.0), 
                                            new Point2d(W-2*t, 0.0),
                                            new Point2d(W-2*t, D-2*t),
                                            new Point2d(0.0, D-2*t)
                                            }, new Point3d(t, t, H - doorH), WoodGrainAlignment.Horizontal);
            _panels.Add(new PanelDetails("Inner shelf divider", String.Format("{0} x {1}", W - 2 * t, D - 2 * t), 1));
            CreateDrawerBlock(splitDrawers);

            InsertDrawers();
        }
예제 #48
0
        public void NavigateWithKinect()
        {
            Document doc =
                Autodesk.AutoCAD.ApplicationServices.
                Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor   ed = doc.Editor;

            // As the user to select the camera and target locations

            PromptPointResult camRes =
                ed.GetPoint("\nPick camera location");

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

            PromptPointResult tgtRes =
                ed.GetPoint("\nPick target location");

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

            // And also the height from ground level

            PromptDoubleOptions pdo =
                new PromptDoubleOptions("\nEnter height from ground");

            pdo.UseDefaultValue = true;

            // Default height of 6' or 2m

            pdo.DefaultValue = (db.Lunits > 2 ? 6 : 2);

            PromptDoubleResult hgtRes = ed.GetDouble(pdo);

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

            _zoomDist = hgtRes.Value / 10.0;

            // We need a Kinect object

            KinectSensor kinect = null;

            // Make sure we dispose of our Camera (which will
            // commit the transaction)

            Camera camera = new Camera(doc);

            using (camera)
            {
                // Set the height from the ground as a vector

                Vector3d height = new Vector3d(0, 0, hgtRes.Value);
                camera.Location = camRes.Value + height;
                camera.Target   = tgtRes.Value + height;

                camera.ApplyToCurrentView();

                // Unset the loop termination flag

                _finished = false;
                _reset    = true;

                if (KinectSensor.KinectSensors.Count <= 0)
                {
                    ed.WriteMessage(
                        "\nUnable to start Kinect sensor - " +
                        "are you sure it's plugged in?"
                        );
                    return;
                }

                // We need our Kinect sensor

                kinect = KinectSensor.KinectSensors[0];

                // We only care about skeleton information

                kinect.SkeletonFrameReady +=
                    new EventHandler <SkeletonFrameReadyEventArgs>(
                        OnSkeletonFrameReady
                        );

                kinect.SkeletonStream.Enable();

                kinect.Start();

                // Loop until user terminates or cancels

                while (
                    !_finished &&
                    !HostApplicationServices.Current.UserBreak()
                    )
                {
                    // Direction from Kinect is:
                    //
                    // 0, 0, 1  - arm pointing directly at the center
                    // 1, 0, 0  - arm pointing directly left
                    // -1, 0, 0 - arm pointing directly right
                    // 0, 1, 0  - arm pointing directly down
                    // 0, -1, 0 - arm pointing directly up

                    const double distFac = 0.001;
                    const double angFac  = 0.003;

                    if (_reset)
                    {
                        // Reset to the initial view parameters

                        camera.Location = camRes.Value + height;
                        camera.Target   = tgtRes.Value + height;

                        camera.ApplyToCurrentView();

                        _reset = false;
                    }
                    else if (_orbiting || _navigating)
                    {
                        Matrix3d locMat = Matrix3d.Identity;

                        // We only orbit if not too close to the centre

                        if (Math.Abs(_direction.X) > 0.2)
                        {
                            locMat =
                                Matrix3d.Rotation(
                                    -_direction.X * angFac,
                                    Vector3d.ZAxis, camera.Target
                                    ) * locMat;
                        }

                        // And the same for upwards/downwards tilt

                        if (Math.Abs(_direction.Y) > 0.2)
                        {
                            // To tilt upwards/downwards, we need the right axis
                            // of rotation. Use a coordinate system object taking
                            // the view direction as the Y axis and the Z axis of
                            // WCS as the X axis, leaving the Z axis of the
                            // coordinate system as our axis of rotation

                            Vector3d newYaxis =
                                camera.Location - camera.Target;
                            newYaxis = newYaxis / newYaxis.Length;

                            CoordinateSystem3d cs =
                                new CoordinateSystem3d(
                                    camera.Target,
                                    Vector3d.ZAxis,
                                    newYaxis
                                    );

                            locMat =
                                Matrix3d.Rotation(
                                    -_direction.Y * angFac,
                                    cs.Zaxis, camera.Target
                                    ) * locMat;
                        }

                        // If we're zooming, we adjust the camera and target
                        // locations by a displacement along the viewing
                        // direction

                        if (_navigating)
                        {
                            Matrix3d trgMat =
                                Matrix3d.Displacement(
                                    (camera.Target - camera.Location) * distFac
                                    );
                            locMat = trgMat * locMat;
                            camera.TargTransform = trgMat;
                        }
                        camera.LocTransform = locMat;

                        camera.ApplyToCurrentView();
                    }

                    // Reset the transformation values

                    camera.LocTransform  = Matrix3d.Identity;
                    camera.TargTransform = Matrix3d.Identity;

                    System.Windows.Forms.Application.DoEvents();
                }
            }

            kinect.Stop();

            kinect.SkeletonFrameReady -=
                new EventHandler <SkeletonFrameReadyEventArgs>(
                    OnSkeletonFrameReady
                    );
        }
예제 #49
0
        public void Figura2()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.GetDocument(db);
            Editor ed = doc.Editor;

            PromptDoubleOptions GetSpindulys = new PromptDoubleOptions("\nĮveskite detalės spindulį");
            double Spindulys;
            GetSpindulys.AllowNegative = false;
            GetSpindulys.AllowZero = false;
            GetSpindulys.AllowNone = false;
            PromptDoubleResult GetSpindulysRezultatas = ed.GetDouble(GetSpindulys);
            Spindulys = GetSpindulysRezultatas.Value;

            PromptPointOptions GetTaskas = new PromptPointOptions("\nPasirinkite centro tašką");
            Point3d Taskas;
            GetTaskas.AllowNone = false;
            PromptPointResult GetTaskasRezultatas = ed.GetPoint(GetTaskas);
            Taskas = GetTaskasRezultatas.Value;

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

                //Apskritimas
                Circle Apskritimas = new Circle(Taskas, new Vector3d(0, 0, 1), Spindulys);
                btr.AppendEntity(Apskritimas);
                tr.AddNewlyCreatedDBObject(Apskritimas, true);

                //Linijos
                Polyline3d polyline = new Polyline3d();
                btr.AppendEntity(polyline);
                tr.AddNewlyCreatedDBObject(polyline, true);
                PolylineVertex3d vex3d = new PolylineVertex3d();

                // Linija NR1 (centrine)
                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y + Spindulys / 6, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y - Spindulys / 6, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Spindulys / 2, Taskas.Y, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Spindulys / 2, Taskas.Y - Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y - Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y - Spindulys / 2 + Spindulys / 6, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y - Spindulys / 2 - Spindulys / 6, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y - Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Spindulys / 2, Taskas.Y - Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Spindulys / 2, Taskas.Y - Spindulys / 2 - Spindulys / 1.5, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                polyline = new Polyline3d();
                btr.AppendEntity(polyline);
                tr.AddNewlyCreatedDBObject(polyline, true);

                // Linija NR2 (virsutine)
                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y + Spindulys / 2 + Spindulys / 5, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y + Spindulys / 2 - Spindulys / 5, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y + Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Spindulys / 2, Taskas.Y + Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Spindulys / 2, Taskas.Y + Spindulys / 2 + Spindulys / 1.5, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                polyline = new Polyline3d();
                btr.AppendEntity(polyline);
                tr.AddNewlyCreatedDBObject(polyline, true);

                // Linija NR3 (kaire)
                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 2, Taskas.Y + Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 2, Taskas.Y - Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 2 - Spindulys / 2 - Spindulys / 4, Taskas.Y - Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                //Apskritimas FIll Viduryje
                Circle ApskritimasFillMIni = new Circle(new Point3d(Taskas.X + Spindulys / 2, Taskas.Y - Spindulys / 2, 0), new Vector3d(0, 0, 1), Spindulys / 8);
                btr.AppendEntity(ApskritimasFillMIni);
                tr.AddNewlyCreatedDBObject(ApskritimasFillMIni, true);

                Hatch hatch = new Hatch();
                btr.AppendEntity(hatch);
                tr.AddNewlyCreatedDBObject(hatch, true);

                ObjectIdCollection ID = new ObjectIdCollection();
                ID.Add(ApskritimasFillMIni.ObjectId);
                hatch.HatchStyle = HatchStyle.Ignore;
                hatch.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                hatch.Associative = true;
                hatch.AppendLoop(HatchLoopTypes.Outermost, ID);
                hatch.EvaluateHatch(true);

                //Trikampis
                Solid trikampis = new Solid(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y, 0), new Point3d(Taskas.X, Taskas.Y + Spindulys / 6, 0), new Point3d(Taskas.X, Taskas.Y - Spindulys / 6, 0));
                btr.AppendEntity(trikampis);
                tr.AddNewlyCreatedDBObject(trikampis, true);

                tr.Commit();
            }
        }
예제 #50
0
        public void Create()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            try
            {
                using (Transaction trans = db.TransactionManager.StartTransaction())
                {
                    //Prompts for each employee detail
                    PromptStringOptions prName = new PromptStringOptions("Enter Employee Name");
                    PromptStringOptions prDiv = new PromptStringOptions("Enter Employee Division");
                    PromptDoubleOptions prSal = new PromptDoubleOptions("Enter Employee Salary");
                    PromptPointOptions prPos = new PromptPointOptions("Enter Employee Position or");

                    //Add keywords when prompting for position
                    prPos.Keywords.Add("Name");
                    prPos.Keywords.Add("Division");
                    prPos.Keywords.Add("Salary");

                    //Set the default values for each of these
                    prName.DefaultValue = "Earnest Shackleton";
                    prDiv.DefaultValue = "Sales";
                    prSal.DefaultValue = 10000.0f;

                    //Set conditions for prompting
                    prPos.AllowNone = false; //Do not allow null values

                    //prompt results - set explicitly to null
                    PromptResult prNameRes = null;
                    PromptResult prDivRes = null;
                    PromptDoubleResult prSalRes = null;
                    PromptPointResult prPosRes = null;

                    //Loop to get employee details. Exit the loop when positon is entered
                    while (prPosRes == null || prPosRes.Status != PromptStatus.OK)
                    {
                        //Prompt for position
                        prPosRes = ed.GetPoint(prPos);
                        if (prPosRes.Status == PromptStatus.Keyword) //Got a keyword
                        {
                            switch (prPosRes.StringResult)
                            {
                                case "Name":
                                    //Get employee name
                                    prName.AllowSpaces = true;
                                    prNameRes = ed.GetString(prName);
                                    if (prNameRes.Status != PromptStatus.OK)
                                        throw new System.Exception("Error or User Cancelled");
                                    break;
                                case "Division":
                                    //Get employee division
                                    prDiv.AllowSpaces = true;
                                    prDivRes = ed.GetString(prDiv);
                                    if (prDivRes.Status != PromptStatus.OK)
                                        throw new System.Exception("Error or User Cancelled");
                                    break;
                                case "Salary":
                                    //Get employee salary
                                    prSal.AllowNegative = false;
                                    prSal.AllowNone = true;
                                    prSal.AllowZero = false;
                                    prSalRes = ed.GetDouble(prSal);
                                    if (prSalRes.Status != PromptStatus.OK & prSalRes.Status != PromptStatus.None)
                                        throw new System.Exception("Error or User Cancelled");
                                    break;
                            }
                        }
                        if (prPosRes.Status == PromptStatus.Cancel || prPosRes.Status == PromptStatus.Error)
                            throw new System.Exception("Error or User Cancelled");
                    }

                    //Create the Employee - either use the input value or the default value...
                    string empName = (prNameRes == null ? prName.DefaultValue : prNameRes.StringResult);
                    string divName = (prDivRes == null ? prDiv.DefaultValue : prDivRes.StringResult);
                    double salary = (prSalRes == null ? prSal.DefaultValue : prSalRes.Value);

                    CreateEmployee(empName, divName, salary, prPosRes.Value);

                    //Now create the division
                    //Pass an empty string for manager to check if it already exists
                    string manager = "";
                    ObjectId xRecId = CreateDivision(divName, manager);

                    //Open the department manager XRecord
                    Xrecord depMgrXRec = (Xrecord)trans.GetObject(xRecId, OpenMode.ForRead);
                    TypedValue[] typedVal = depMgrXRec.Data.AsArray();
                    foreach (TypedValue val in typedVal)
                    {
                        string str = (string)val.Value;
                        if (str == "")
                        {
                            //Manager was not set, now set it
                            // Prompt for  manager name first
                            ed.WriteMessage("\r\n");
                            PromptStringOptions prManagerName = new PromptStringOptions("No manager set for the division! Enter Manager Name");
                            prManagerName.DefaultValue = "Delton T. Cransley";
                            prManagerName.AllowSpaces = true;
                            PromptResult prManagerNameRes = ed.GetString(prManagerName);
                            if (prManagerNameRes.Status != PromptStatus.OK)
                                throw new System.Exception("Error or User Cancelled");
                            //Set a manager name
                            depMgrXRec.Data = new ResultBuffer(new TypedValue((int)DxfCode.Text, prManagerNameRes.StringResult));
                        }
                    }
                    trans.Commit();
                }
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nError: " + ex.Message + "\n");
            }
        }
예제 #51
0
        public void Figura1()
        {
            Database db  = HostApplicationServices.WorkingDatabase;
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.GetDocument(db);
            Editor   ed  = doc.Editor;

            PromptDoubleOptions GetIlgis = new PromptDoubleOptions("\nĮveskite mikroskemos ilgį");
            double Ilgis;

            GetIlgis.AllowNegative = false;
            GetIlgis.AllowZero     = false;
            GetIlgis.AllowNone     = false;
            PromptDoubleResult GetIlgisRezultatas = ed.GetDouble(GetIlgis);

            Ilgis = GetIlgisRezultatas.Value;

            PromptDoubleOptions GetPlotis = new PromptDoubleOptions("\nĮveskite mikroskemos plotį");
            double Plotis;

            GetPlotis.AllowNegative = false;
            GetPlotis.AllowZero     = false;
            GetPlotis.AllowNone     = false;
            PromptDoubleResult GetPlotisRezultatas = ed.GetDouble(GetPlotis);

            Plotis = GetPlotisRezultatas.Value;

            PromptPointOptions GetTaskas = new PromptPointOptions("\nPasirinkite tašką");
            Point3d            Taskas;

            GetTaskas.AllowNone = false;
            PromptPointResult GetTaskasRezultatas = ed.GetPoint(GetTaskas);

            Taskas = GetTaskasRezultatas.Value;

            Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                BlockTable       bt       = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                BlockTableRecord btr      = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                Polyline3d       polyline = new Polyline3d();
                btr.AppendEntity(polyline);
                tr.AddNewlyCreatedDBObject(polyline, true);
                PolylineVertex3d vex3d = new PolylineVertex3d();

                //Pradinis taskas
                vex3d = new PolylineVertex3d(Taskas);
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                //Atsakos tarp pradinio ir pirmo kampo
                double betaIlgis    = Ilgis / 8;
                double AtsakosIlgis = Math.Min(Ilgis / 4, Plotis / 4);
                for (int i = 1; i < 8; i++)
                {
                    // Linija iki atsakos
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X, Taskas.Y + betaIlgis * i, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos linija
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X - AtsakosIlgis, Taskas.Y + betaIlgis * i, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos grizimas atgal i kontura
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X, Taskas.Y + betaIlgis * i, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);
                }

                // Pirmas kampas
                vex3d = new PolylineVertex3d(new Point3d(Taskas.X, Taskas.Y + Ilgis, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                //Atsakos tarp pirmo ir angtro kampo
                double betaPlotis = Plotis / 2;
                for (int i = 1; i < 2; i++)
                {
                    // Linija iki atsakos
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + betaPlotis * i, Taskas.Y + Ilgis, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos linija
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + betaPlotis * i, Taskas.Y + Ilgis + AtsakosIlgis, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos grizimas atgal i kontura
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + betaPlotis * i, Taskas.Y + Ilgis, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);
                }

                //Antras kampas
                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis, Taskas.Y + Ilgis, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                //Atsakos tarp antro ir trecio kampo
                for (int i = 1; i < 8; i++)
                {
                    // Linija iki atsakos
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis, Taskas.Y + Ilgis - betaIlgis * i, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos linija
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis + AtsakosIlgis, Taskas.Y + Ilgis - betaIlgis * i, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos grizimas atgal i kontura
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis, Taskas.Y + Ilgis - betaIlgis * i, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);
                }

                //Trecias kampas
                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis, Taskas.Y, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                //Atsakos tarp trecio ir pradinio kampo
                for (int i = 1; i < 2; i++)
                {
                    // Linija iki atsakos
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis - betaPlotis * i, Taskas.Y, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos linija
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis - betaPlotis * i, Taskas.Y - AtsakosIlgis, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);

                    //Atsakos grizimas atgal i kontura
                    vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Plotis - betaPlotis * i, Taskas.Y, 0));
                    polyline.AppendVertex(vex3d);
                    tr.AddNewlyCreatedDBObject(vex3d, true);
                }

                //Ketvirtas kampas / Pradinis taskas
                vex3d = new PolylineVertex3d(Taskas);
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);
                tr.Commit();
            }
        }
예제 #52
0
        //--------------------------------------------------------------------------
        //
        // ���ܣ����ñ�����ֵ����ʾ�������ij߶��б�
        //
        //  ���ߣ�
        //
        //  ���ڣ�200708
        //
        //   ��ʷ��
        //--------------------------------------------------------------------------
        public bool AddScale()
        {
            bool isAdded = false;
            string message = null;
            ObjectId currentMapId = new ObjectId();
            if (!FindCurrentMapId(ref currentMapId))
            {
                return isAdded;
            }

            MapApplication app = HostMapApplicationServices.Application;
            Editor editor = app.GetDocument(app.ActiveProject).Editor;
            PromptDoubleOptions promptOptions = new PromptDoubleOptions("");
            promptOptions.AllowNone = false;
            promptOptions.AllowZero = false;
            promptOptions.AllowNegative = false;
            promptOptions.Message = "\n�����µı����ߣ� ";
            double scale = 0.0;
            try
            {
                PromptDoubleResult doublePromptResult = editor.GetDouble(promptOptions);
                if (doublePromptResult.Status == PromptStatus.OK)
                {
                    scale = doublePromptResult.Value;
                    using (Transaction trans = Utility.TransactionManager.StartTransaction())
                    {
                        Map currentMap = (Map)trans.GetObject(currentMapId, OpenMode.ForWrite);
                        // Add the new scale
                        currentMap.AddScaleThreshold(scale, 0);
                        message = string.Format("\n�µı����� {0}����ӡ�", scale);
                        Utility.ShowMessage(message);
                        isAdded = true;
                        trans.Commit();
                    }
                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception)
            {
                message = string.Format("\n��ӱ����� {0}ʧ�ܡ�", scale);
                Utility.ShowMessage(message);
            }

            return isAdded;
        }
예제 #53
0
        public void Figura2()
        {
            Database db  = HostApplicationServices.WorkingDatabase;
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.GetDocument(db);
            Editor   ed  = doc.Editor;

            PromptDoubleOptions GetSpindulys = new PromptDoubleOptions("\nĮveskite detalės spindulį");
            double Spindulys;

            GetSpindulys.AllowNegative = false;
            GetSpindulys.AllowZero     = false;
            GetSpindulys.AllowNone     = false;
            PromptDoubleResult GetSpindulysRezultatas = ed.GetDouble(GetSpindulys);

            Spindulys = GetSpindulysRezultatas.Value;

            PromptPointOptions GetTaskas = new PromptPointOptions("\nPasirinkite centro tašką");
            Point3d            Taskas;

            GetTaskas.AllowNone = false;
            PromptPointResult GetTaskasRezultatas = ed.GetPoint(GetTaskas);

            Taskas = GetTaskasRezultatas.Value;

            Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                BlockTable       bt  = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);

                //Apskritimas
                Circle Apskritimas = new Circle(Taskas, new Vector3d(0, 0, 1), Spindulys);
                btr.AppendEntity(Apskritimas);
                tr.AddNewlyCreatedDBObject(Apskritimas, true);

                //Linijos
                Polyline3d polyline = new Polyline3d();
                btr.AppendEntity(polyline);
                tr.AddNewlyCreatedDBObject(polyline, true);
                PolylineVertex3d vex3d = new PolylineVertex3d();

                // Linija NR1 (centrine)
                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y + Spindulys / 6, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y - Spindulys / 6, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Spindulys / 2, Taskas.Y, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Spindulys / 2, Taskas.Y - Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y - Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y - Spindulys / 2 + Spindulys / 6, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y - Spindulys / 2 - Spindulys / 6, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y - Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Spindulys / 2, Taskas.Y - Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Spindulys / 2, Taskas.Y - Spindulys / 2 - Spindulys / 1.5, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                polyline = new Polyline3d();
                btr.AppendEntity(polyline);
                tr.AddNewlyCreatedDBObject(polyline, true);

                // Linija NR2 (virsutine)
                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y + Spindulys / 2 + Spindulys / 5, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y + Spindulys / 2 - Spindulys / 5, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y + Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Spindulys / 2, Taskas.Y + Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X + Spindulys / 2, Taskas.Y + Spindulys / 2 + Spindulys / 1.5, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                polyline = new Polyline3d();
                btr.AppendEntity(polyline);
                tr.AddNewlyCreatedDBObject(polyline, true);

                // Linija NR3 (kaire)
                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 2, Taskas.Y + Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 2, Taskas.Y - Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                vex3d = new PolylineVertex3d(new Point3d(Taskas.X - Spindulys / 2 - Spindulys / 2 - Spindulys / 4, Taskas.Y - Spindulys / 2, 0));
                polyline.AppendVertex(vex3d);
                tr.AddNewlyCreatedDBObject(vex3d, true);

                //Apskritimas FIll Viduryje
                Circle ApskritimasFillMIni = new Circle(new Point3d(Taskas.X + Spindulys / 2, Taskas.Y - Spindulys / 2, 0), new Vector3d(0, 0, 1), Spindulys / 8);
                btr.AppendEntity(ApskritimasFillMIni);
                tr.AddNewlyCreatedDBObject(ApskritimasFillMIni, true);

                Hatch hatch = new Hatch();
                btr.AppendEntity(hatch);
                tr.AddNewlyCreatedDBObject(hatch, true);

                ObjectIdCollection ID = new ObjectIdCollection();
                ID.Add(ApskritimasFillMIni.ObjectId);
                hatch.HatchStyle = HatchStyle.Ignore;
                hatch.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                hatch.Associative = true;
                hatch.AppendLoop(HatchLoopTypes.Outermost, ID);
                hatch.EvaluateHatch(true);


                //Trikampis
                Solid trikampis = new Solid(new Point3d(Taskas.X - Spindulys / 4, Taskas.Y, 0), new Point3d(Taskas.X, Taskas.Y + Spindulys / 6, 0), new Point3d(Taskas.X, Taskas.Y - Spindulys / 6, 0));
                btr.AppendEntity(trikampis);
                tr.AddNewlyCreatedDBObject(trikampis, true);

                tr.Commit();
            }
        }
예제 #54
0
 public static IAcedCmdArg Argument(PromptDoubleOptions options)
 {
     return new PromptDoubleArgument(options);
 }
예제 #55
0
        public void Figura4()
        {
            Database db  = HostApplicationServices.WorkingDatabase;
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.GetDocument(db);
            Editor   ed  = doc.Editor;

            PromptDoubleOptions GetSpindulys = new PromptDoubleOptions("\nĮveskite didžiausio apskritimo spindulį");
            double Spindulys;

            GetSpindulys.AllowNegative = false;
            GetSpindulys.AllowZero     = false;
            GetSpindulys.AllowZero     = false;
            PromptDoubleResult GetSpindulysRezultatas = ed.GetDouble(GetSpindulys);

            Spindulys = GetSpindulysRezultatas.Value;

            PromptDoubleOptions GetPlotis = new PromptDoubleOptions("\nĮveskite apskirtimo spindulio mažėjimą");
            double Plotis;

            GetPlotis.AllowNegative = false;
            GetPlotis.AllowZero     = false;
            GetPlotis.AllowZero     = false;
            PromptDoubleResult GetPlotisRezultatas = ed.GetDouble(GetPlotis);

            Plotis = GetPlotisRezultatas.Value;

            PromptPointOptions GetTaskas = new PromptPointOptions("\nPasirinkite centro tašką");
            Point3d            Taskas;

            GetTaskas.AllowNone = false;
            PromptPointResult GetTaskasRezultatas = ed.GetPoint(GetTaskas);

            Taskas = GetTaskasRezultatas.Value;

            Transaction tr = db.TransactionManager.StartTransaction();

            using (tr)
            {
                BlockTable       bt  = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead, false);
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite, false);
                int i = 1;
                while (Spindulys > 0)
                {
                    Circle Apskritimas = new Circle(Taskas, new Vector3d(0, 0, 1), Spindulys);
                    btr.AppendEntity(Apskritimas);
                    tr.AddNewlyCreatedDBObject(Apskritimas, true);

                    Hatch hatch = new Hatch();
                    btr.AppendEntity(hatch);
                    tr.AddNewlyCreatedDBObject(hatch, true);

                    ObjectIdCollection ID = new ObjectIdCollection();
                    ID.Add(Apskritimas.ObjectId);
                    hatch.HatchStyle = HatchStyle.Ignore;
                    hatch.SetHatchPattern(HatchPatternType.PreDefined, "SOLID");
                    hatch.Associative = true;
                    hatch.AppendLoop(HatchLoopTypes.Outermost, ID);
                    hatch.EvaluateHatch(true);
                    hatch.ColorIndex = i++;

                    Spindulys -= Plotis;
                }
                tr.Commit();
            }
        }