Example #1
0
    public void Draw()
    {
        UCS.ClearChild(towerBase.transform);
        float   renderZ = 0.0f;
        Vector2 orgPos  = new Vector2(0, 0.3f);

        for (int i = 0; i < spriteDat.Count; i++)
        {
            GameObject go     = new GameObject("towerPart");
            var        render = go.AddComponent <SpriteRenderer>();
            if (i == 0)
            {
                render.sprite = baseSprites[spriteDat[i]];
            }
            else
            {
                if (i == spriteDat.Count - 1)
                {
                    render.sprite = topSprites[spriteDat[i]];
                }
                else
                {
                    render.sprite = midSprites[spriteDat[i]];
                }
            }
            go.transform.SetParent(towerBase.transform);
            Vector2 pos = orgPos + i * new Vector2(0, 0.3f);
            go.transform.localPosition = new Vector3(pos.x, pos.y, renderZ - 1);
            //go.transform.SetPositionAndRotation(new Vector3(pos.x, pos.y, renderZ), new Quaternion());
            renderZ -= 0.001f;
        }
    }
Example #2
0
        public static Pair <Point3d, Point3d> GetVPortToModelSpaceDiagpnal(ref Viewport vpr)
        {
            double xLnegth = vpr.Width / vpr.CustomScale;
            double yLength = vpr.Height / vpr.CustomScale;

            Quaternion q1 = new Quaternion(0, 1, 0, 0);
            Quaternion q2 = new Quaternion(0, 0, 1, 0);

            q1 = q1.get_rotateAroundAxe(new Quaternion(0, 0, 0, 1), vpr.TwistAngle);
            q2 = q2.get_rotateAroundAxe(new Quaternion(0, 0, 0, 1), vpr.TwistAngle);

            UCS        ucs  = new UCS(new Quaternion(), q1, q2);
            Vector3d   vMOV = vpr.ViewTarget - Point3d.Origin;
            Quaternion qMOV = new Quaternion(0, vMOV.X, vMOV.Y, vMOV.Z);

            Quaternion c  = new Quaternion(0, vpr.ViewCenter.X, vpr.ViewCenter.Y, 0);
            Quaternion c1 = new Quaternion(0, c.GetX() + xLnegth / 2.0, c.GetY() + yLength / 2.0, 0);
            Quaternion c2 = new Quaternion(0, c.GetX() - xLnegth / 2.0, c.GetY() - yLength / 2.0, 0);

            c  = ucs.FromACS(c);
            c1 = ucs.FromACS(c1);
            c2 = ucs.FromACS(c2);

            c += qMOV; c1 += qMOV; c2 += qMOV;

            return(new Pair <Point3d, Point3d>(new Point3d(c1.GetX(), c1.GetY(), 0), new Point3d(c2.GetX(), c2.GetY(), 0)));
        }
Example #3
0
        public void TransformEnties()
        {
            Vector3d UserXaxis = db.Ucsxdir;
            Vector3d WXaxis    = new Vector3d(1, 0, 0);
            Vector3d Zaxis     = new Vector3d(0, 0, 1);
            double   Rangle    = UserXaxis.GetAngleTo(WXaxis);

            if (UserXaxis.Y < 0)
            {
                Zaxis = Zaxis.Negate();                                           //1.03版修改,修正角度旋转正负问题
            }
            Matrix3d Rmat = Matrix3d.Rotation(Rangle, Zaxis, mdragPT);            //旋转矩阵

            if (mdragPT.TransformBy(UCS.Inverse()).X >= mbasePT.TransformBy(UCS.Inverse()).X)
            {
                mIsRight = true;
                Matrix3d mat = Matrix3d.Displacement(mbasePT.GetVectorTo(mdragPT)).PreMultiplyBy(Rmat);  //旋转矩阵左乘位移矩阵
                foreach (Entity ent in mEntities)
                {
                    ent.TransformBy(mat);
                }
            }
            else
            {
                mIsRight = false;
                Line     L   = (Line)mEntitiesL[0];
                Vector3d Vt  = new Vector3d(L.Length, 0, 0);
                Matrix3d mat = Matrix3d.Displacement(mbasePT.GetVectorTo(mdragPT) - Vt).PreMultiplyBy(Rmat);//旋转矩阵左乘位移矩阵,然后镜像矩阵左乘前结果
                foreach (Entity ent in mEntitiesL)
                {
                    ent.TransformBy(mat);
                }
            }
        }
Example #4
0
        protected override AcEd.SamplerStatus Sampler(AcEd.JigPrompts prompts)
        {
            AcEd.JigPromptPointOptions jppo = new AcEd.JigPromptPointOptions();
            AcEd.PromptPointResult     ppr;

            jppo.Message      = this.methodConstructing.GetMessage();
            jppo.UseBasePoint = false;

            ppr = prompts.AcquirePoint(jppo);

            if (ppr.Status == AcEd.PromptStatus.Cancel || ppr.Status == AcEd.PromptStatus.Error)
            {
                return(AcEd.SamplerStatus.Cancel);
            }
            AcGe.Point3d tmpPt = ppr.Value.TransformBy(UCS.Inverse());
            if (!this.diagonalPoint.IsEqualTo(tmpPt, new AcGe.Tolerance(10e-10, 10e-10)))
            {
                this.diagonalPoint = tmpPt;
                return(AcEd.SamplerStatus.OK);
            }
            else
            {
                return(AcEd.SamplerStatus.NoChange);
            }
        }
Example #5
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.WriteLine("Usage: CNG462_A1 <operation> <filename>");
                Console.WriteLine("Available operations: shortestpath, solvetsp");
                Environment.Exit(1);
            }

            string[] txtFileContent = null;

            try
            {
                txtFileContent = System.IO.File.ReadAllLines(args[1]);
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("File " + args[1] + " not found!");
                Environment.Exit(1);
            }

            mainArray = txtFileContent.Select(item => item.ToArray()).ToArray();

            PositionOfPoints = new Dictionary <string, Tuple <int, int> >();
            ShortestPaths    = new Dictionary <Tuple <string, string>, int>();

            FillPositionOfPoints();

            if (args[0] == "shortestpath")
            {
                FindShortestPaths();
                PrintShortestPaths();
            }
            else if (args[0] == "solvetsp")
            {
                FindShortestPaths();
                var BFSWatch = System.Diagnostics.Stopwatch.StartNew();
                bFS       = new BFS(ShortestPaths);
                BFSResult = bFS.Search("A");
                BFSWatch.Stop();
                var UCSWatch = System.Diagnostics.Stopwatch.StartNew();
                uCS       = new UCS(ShortestPaths);
                UCSResult = uCS.Search("A");
                UCSWatch.Stop();

                BFSResultElapsedTime = BFSWatch.ElapsedTicks * 100; // 1 tick = 100 ns
                UCSResultElapsedTime = UCSWatch.ElapsedTicks * 100; // 1 tick = 100 ns

                PrintSolveTSP();
            }
            else
            {
                Console.WriteLine("Error: Wrong <operation> field!");
                Environment.Exit(1);
            }
        }
Example #6
0
 public void UpdateList(CMLadderInfo cm)
 {
     UCS.ClearChild(labelParent.transform);
     for (int i = 0; i < cm.members.Length; i++)
     {
         var obj = Instantiate(labelPrefab, labelParent.transform);
         var lab = obj.GetComponent <LadderLabel>();
         lab.SetLabel(cm.members[cm.members.Length - i - 1]);
     }
 }
Example #7
0
        // --- function --
        public static double AngleBetweenZaxes(UCS ucs1, UCS ucs2)
        {
            double     ang = 0;
            Quaternion q1  = new Quaternion(ucs1.ToACS(new Quaternion(0, 0, 0, 100)) - ucs1.ToACS(new Quaternion(0, 0, 0, 0)));
            Quaternion q2  = new Quaternion(ucs2.ToACS(new Quaternion(0, 0, 0, 100)) - ucs2.ToACS(new Quaternion(0, 0, 0, 0)));

            ang = q1.angTo(q2);

            return(ang);
        }
Example #8
0
        /// <summary>
        /// Initializes a new instance of the <c>SystemVariables</c>.
        /// </summary>
        /// <remarks>The default values are the same ones that are apply to a new AutoCad drawing.</remarks>
        public HeaderVariables()
        {
            this.variables = new Dictionary <string, HeaderVariable>(StringComparer.OrdinalIgnoreCase)
            {
                { HeaderVariableCode.AcadVer, new HeaderVariable(HeaderVariableCode.AcadVer, 1, DxfVersion.AutoCad2000) },
                { HeaderVariableCode.DwgCodePage, new HeaderVariable(HeaderVariableCode.DwgCodePage, 3, "ANSI_" + Encoding.ASCII.WindowsCodePage) },
                { HeaderVariableCode.LastSavedBy, new HeaderVariable(HeaderVariableCode.LastSavedBy, 1, Environment.UserName) },
                { HeaderVariableCode.HandleSeed, new HeaderVariable(HeaderVariableCode.HandleSeed, 5, "1") },
                { HeaderVariableCode.Angbase, new HeaderVariable(HeaderVariableCode.Angbase, 50, 0.0) },
                { HeaderVariableCode.Angdir, new HeaderVariable(HeaderVariableCode.Angdir, 70, AngleDirection.CCW) },
                { HeaderVariableCode.AttMode, new HeaderVariable(HeaderVariableCode.AttMode, 70, AttMode.Normal) },
                { HeaderVariableCode.AUnits, new HeaderVariable(HeaderVariableCode.AUnits, 70, AngleUnitType.DecimalDegrees) },
                { HeaderVariableCode.AUprec, new HeaderVariable(HeaderVariableCode.AUprec, 70, (short)0) },
                { HeaderVariableCode.CeColor, new HeaderVariable(HeaderVariableCode.CeColor, 62, AciColor.ByLayer) },
                { HeaderVariableCode.CeLtScale, new HeaderVariable(HeaderVariableCode.CeLtScale, 40, 1.0) },
                { HeaderVariableCode.CeLtype, new HeaderVariable(HeaderVariableCode.CeLtype, 6, "ByLayer") },
                { HeaderVariableCode.CeLweight, new HeaderVariable(HeaderVariableCode.CeLweight, 370, Lineweight.ByLayer) },
                { HeaderVariableCode.CLayer, new HeaderVariable(HeaderVariableCode.CLayer, 8, "0") },
                { HeaderVariableCode.CMLJust, new HeaderVariable(HeaderVariableCode.CMLJust, 70, MLineJustification.Top) },
                { HeaderVariableCode.CMLScale, new HeaderVariable(HeaderVariableCode.CMLScale, 40, 20.0) },
                { HeaderVariableCode.CMLStyle, new HeaderVariable(HeaderVariableCode.CMLStyle, 2, "Standard") },
                { HeaderVariableCode.DimStyle, new HeaderVariable(HeaderVariableCode.DimStyle, 2, "Standard") },
                { HeaderVariableCode.TextSize, new HeaderVariable(HeaderVariableCode.TextSize, 40, 2.5) },
                { HeaderVariableCode.TextStyle, new HeaderVariable(HeaderVariableCode.TextStyle, 7, "Standard") },
                { HeaderVariableCode.LUnits, new HeaderVariable(HeaderVariableCode.LUnits, 70, LinearUnitType.Decimal) },
                { HeaderVariableCode.LUprec, new HeaderVariable(HeaderVariableCode.LUprec, 70, (short)4) },
                { HeaderVariableCode.MirrText, new HeaderVariable(HeaderVariableCode.MirrText, 70, false) },
                { HeaderVariableCode.Extnames, new HeaderVariable(HeaderVariableCode.Extnames, 290, true) },
                { HeaderVariableCode.InsBase, new HeaderVariable(HeaderVariableCode.InsBase, 10, Vector3.Zero) },
                { HeaderVariableCode.InsUnits, new HeaderVariable(HeaderVariableCode.InsUnits, 70, DrawingUnits.Unitless) },
                { HeaderVariableCode.LtScale, new HeaderVariable(HeaderVariableCode.LtScale, 40, 1.0) },
                { HeaderVariableCode.LwDisplay, new HeaderVariable(HeaderVariableCode.LwDisplay, 290, false) },
                { HeaderVariableCode.PdMode, new HeaderVariable(HeaderVariableCode.PdMode, 70, PointShape.Dot) },
                { HeaderVariableCode.PdSize, new HeaderVariable(HeaderVariableCode.PdSize, 40, 0.0) },
                { HeaderVariableCode.PLineGen, new HeaderVariable(HeaderVariableCode.PLineGen, 70, (short)0) },
                { HeaderVariableCode.PsLtScale, new HeaderVariable(HeaderVariableCode.PsLtScale, 70, (short)1) },
                { HeaderVariableCode.SplineSegs, new HeaderVariable(HeaderVariableCode.SplineSegs, 70, (short)8) },
                { HeaderVariableCode.SurfU, new HeaderVariable(HeaderVariableCode.SurfU, 70, (short)6) },
                { HeaderVariableCode.SurfV, new HeaderVariable(HeaderVariableCode.SurfV, 70, (short)6) },
                { HeaderVariableCode.TdCreate, new HeaderVariable(HeaderVariableCode.TdCreate, 40, DateTime.Now) },
                { HeaderVariableCode.TduCreate, new HeaderVariable(HeaderVariableCode.TduCreate, 40, DateTime.UtcNow) },
                { HeaderVariableCode.TdUpdate, new HeaderVariable(HeaderVariableCode.TdUpdate, 40, DateTime.Now) },
                { HeaderVariableCode.TduUpdate, new HeaderVariable(HeaderVariableCode.TduUpdate, 40, DateTime.UtcNow) },
                { HeaderVariableCode.TdinDwg, new HeaderVariable(HeaderVariableCode.TdinDwg, 40, new TimeSpan()) }
            };

            this.currentUCS      = new UCS("Unnamed");
            this.customVariables = new Dictionary <string, HeaderVariable>(StringComparer.OrdinalIgnoreCase);
        }
Example #9
0
        protected override bool WorldDraw(Autodesk.AutoCAD.GraphicsInterface.WorldDraw draw)
        {
            mleader.EndPoint = mdragPT;
            Vector3d UserXaxis = db.Ucsxdir;
            Vector3d WXaxis    = new Vector3d(1, 0, 0);
            Vector3d Zaxis     = new Vector3d(0, 0, 1);
            double   Rangle    = UserXaxis.GetAngleTo(WXaxis);

            if (UserXaxis.Y < 0)
            {
                Zaxis = Zaxis.Negate();                                           //1.03版修改,修正角度旋转正负问题
            }
            Matrix3d Rmat = Matrix3d.Rotation(Rangle, Zaxis, mdragPT);            //旋转矩阵

            if (mdragPT.TransformBy(UCS.Inverse()).X >= mbasePT.TransformBy(UCS.Inverse()).X)
            {
                Matrix3d      mat = Matrix3d.Displacement(mbasePT.GetVectorTo(mdragPT)).PreMultiplyBy(Rmat); //旋转矩阵左乘位移矩阵
                WorldGeometry geo = draw.Geometry;
                if (geo != null)
                {
                    geo.Draw(mleader);
                    geo.PushModelTransform(mat);
                    foreach (Entity ent in mEntities)
                    {
                        geo.Draw(ent);
                    }
                    geo.PopModelTransform();
                }
            }
            else
            {
                Line          L   = (Line)mEntitiesL[0];
                Vector3d      Vt  = new Vector3d(L.Length, 0, 0);
                Matrix3d      mat = Matrix3d.Displacement(mbasePT.GetVectorTo(mdragPT) - Vt).PreMultiplyBy(Rmat);//旋转矩阵左乘位移矩阵
                WorldGeometry geo = draw.Geometry;
                if (geo != null)
                {
                    geo.Draw(mleader);
                    geo.PushModelTransform(mat);
                    foreach (Entity ent in mEntitiesL)
                    {
                        geo.Draw(ent);
                    }
                    geo.PopModelTransform();
                }
            }
            return(true);
        }
Example #10
0
        public void PositionMarkStart()
        {
            Matrix3d ucs = _editorHelper.CurrentUcs;
            Point3d  pO  = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d.Origin;

            PromptPointResult firstPointResult = _editorHelper.PromptForPoint("Pick arrow point : ", false, false);

            if (firstPointResult.Status != PromptStatus.OK)
            {
                return;
            }
            var firstPoint = firstPointResult.Value.TransformBy(GeometryUtility.GetTransforMatrixToWcs());


            PromptPointResult secondPointResult = _editorHelper.PromptForPoint("Pick pos number sign point : ", true, true, firstPoint);

            if (secondPointResult.Status != PromptStatus.OK)
            {
                return;
            }
            var secondPoint = secondPointResult.Value.TransformBy(GeometryUtility.GetTransforMatrixToWcs());

            PromptIntegerResult posNumberResult = _editorHelper.PromptForInteger("Enter POS integer number :");

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

            _editorHelper.CurrentUcs = Matrix3d.Identity;
            Quaternion S = new Quaternion(0, secondPoint.X, secondPoint.Y, secondPoint.Z);
            Quaternion F = new Quaternion(0, firstPoint.X, firstPoint.Y, firstPoint.Z);

            Vector3d v1 = pO.GetVectorTo(secondPoint);
            Vector3d v  = secondPoint.GetVectorTo(new Point3d(0, 0, 0));

            secondPoint = secondPoint.TransformBy(Matrix3d.Displacement(v));
            firstPoint  = firstPoint.TransformBy(Matrix3d.Displacement(v));

            Quaternion ucsOrigin = new Quaternion(0, pO.X, pO.Y, pO.Z);
            Quaternion Xaxe      = new Quaternion(0, ucs.CoordinateSystem3d.Xaxis.X, ucs.CoordinateSystem3d.Xaxis.Y, ucs.CoordinateSystem3d.Xaxis.Z);
            Quaternion Yaxe      = new Quaternion(0, ucs.CoordinateSystem3d.Yaxis.X, ucs.CoordinateSystem3d.Yaxis.Y, ucs.CoordinateSystem3d.Yaxis.Z);

            Xaxe = ucsOrigin + Xaxe;
            Yaxe = ucsOrigin + Yaxe;
            UCS        UCS = new UCS(ucsOrigin, Xaxe, Yaxe);
            Quaternion FS  = UCS.FromACS(S) - UCS.FromACS(F);
            double     ang = FS.angToX();

            if (FS.GetY() < 0)
            {
                ang *= -1;
            }


            Hashtable dynamicBlockProperties = new Hashtable();
            Hashtable dynamicBlockAttributes = new Hashtable();

            dynamicBlockProperties.Add("Base Point", secondPoint);
            dynamicBlockProperties.Add("Distance", secondPoint.DistanceTo(firstPoint));

            dynamicBlockProperties.Add("Angle", ang);

            dynamicBlockAttributes.Clear();
            dynamicBlockAttributes.Add("POS", posNumberResult.Value);

            string dynamicBlockFullName = _blockDrawingProvider.GetBlockFile(MethodBase.GetCurrentMethod().DeclaringType.Name);

            if (dynamicBlockFullName == null)
            {
                _editorHelper.WriteMessage("Dynamic block PositionMark.dwg does not exist.");
                return;
            }
            ObjectId refO = _drawingHelper.ImportDynamicBlockAndFillItsProperties(
                dynamicBlockFullName,
                secondPoint,
                dynamicBlockProperties,
                dynamicBlockAttributes);

            using (Transaction acTrans = Application.DocumentManager.MdiActiveDocument.Database.TransactionManager.StartTransaction())
            {
                Entity ent = (Entity)acTrans.GetObject(refO, OpenMode.ForWrite);
                ent.TransformBy(ucs);
                ent.TransformBy(Matrix3d.Displacement(v1));
                acTrans.Commit();
            }
            _editorHelper.CurrentUcs = ucs;

            _logger.Info(MethodBase.GetCurrentMethod().DeclaringType.Name);
        }
Example #11
0
 public void Start()
 {
     ObjBuilder.tileSize = tileSize;
     UCS.ClearChild(transform);
     Generator();
 }
Example #12
0
        public static void DrawSolidDescription(ObjectIdCollection OuterContours, Point3d origin, Point3d Xaxe, Point3d Yaxe, PromptPointResult target, bool bds)
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;  

            Vector3d vX, vY, vZ;
            ObjectId ID = OuterContours[OuterContours.Count - 1];
            Point3d centroid = new Point3d();
            string layer;
            ObjectId[] solids = { ID, ID, ID, ID, ID, ID, ID };
            using (Transaction acTrans = db.TransactionManager.StartTransaction())
            {
                BlockTable acBlkTbl = acTrans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord modelSpace = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                Entity ent = acTrans.GetObject(ID, OpenMode.ForRead) as Entity;

                #region check selection
                String[] str = ent.GetType().ToString().Split('.');
                if (str[str.Length - 1] != "Solid3d")//check for solid
                {
                    MessageBox.Show("No selected Solid !");
                    return;
                }

                Quaternion q1 = new Quaternion(Xaxe.X - origin.X, Xaxe.Y - origin.Y, Xaxe.Z - origin.Z, 0);
                Quaternion q2 = new Quaternion(Yaxe.X - origin.X, Yaxe.Y - origin.Y, Yaxe.Z - origin.Z, 0);

                if (q1.abs() < 10E-11)
                {
                    MessageBox.Show("origin = Xaxe !");
                    return;
                }

                if (q2.abs() < 10E-11)
                {
                    MessageBox.Show("origin = Xaxe !");
                    return;
                }


                q1 /= q1.abs();
                q2 /= q2.abs();

                Quaternion q = q2 / q1;
                q = new Quaternion(0, q.GetX(), q.GetY(), q.GetZ());
                if (q.norm() < 10E-14)
                {
                    MessageBox.Show("three points in one line !");
                    return;
                }
                #endregion

                Solid3d solid = acTrans.GetObject(ID, OpenMode.ForWrite) as Solid3d;
                layer = solid.Layer;
                solids[0] = solid.ObjectId;

                centroid = solid.MassProperties.Centroid;

                UCS UCS = new UCS(new Quaternion(0, origin.X, origin.Y, origin.Z), new Quaternion(0, Xaxe.X, Xaxe.Y, Xaxe.Z), new Quaternion(0, Yaxe.X, Yaxe.Y, Yaxe.Z));
                Quaternion ucsX = UCS.ToACS(new Quaternion(0, 1, 0, 0));
                Quaternion ucsY = UCS.ToACS(new Quaternion(0, 0, 1, 0));
                Quaternion ucsZ = UCS.ToACS(new Quaternion(0, 0, 0, 1));
                vX = origin.GetVectorTo(new Point3d(ucsX.GetX(), ucsX.GetY(), ucsX.GetZ()));
                vY = origin.GetVectorTo(new Point3d(ucsY.GetX(), ucsY.GetY(), ucsY.GetZ()));
                vZ = origin.GetVectorTo(new Point3d(ucsZ.GetX(), ucsZ.GetY(), ucsZ.GetZ()));

                _centroid = centroid;
                vO[0] = vX; vO[1] = vY; vO[2] = vZ;
                _target = target.Value;

                Matrix3d newMatrix = new Matrix3d();
                newMatrix = Matrix3d.AlignCoordinateSystem(centroid, vX, vY, vZ, centroid, Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis);
                solid.TransformBy(newMatrix);


                Point3d MIN = new Point3d(solid.GeometricExtents.MinPoint.X - centroid.X, solid.GeometricExtents.MinPoint.Y - centroid.Y, solid.GeometricExtents.MinPoint.Z - centroid.Z);
                Point3d MAX = new Point3d(solid.GeometricExtents.MaxPoint.X - centroid.X, solid.GeometricExtents.MaxPoint.Y - centroid.Y, solid.GeometricExtents.MaxPoint.Z - centroid.Z);

                double MaxX = (Math.Abs(MIN.X) > Math.Abs(MAX.X)) ? Math.Abs(MIN.X) : Math.Abs(MAX.X);
                double MaxY = (Math.Abs(MIN.Y) > Math.Abs(MAX.Y)) ? Math.Abs(MIN.Y) : Math.Abs(MAX.Y);
                double MaxZ = (Math.Abs(MIN.Z) > Math.Abs(MAX.Z)) ? Math.Abs(MIN.Z) : Math.Abs(MAX.Z);


                Solid3d[] solidARR = { solid.Clone() as Solid3d, solid.Clone() as Solid3d, solid.Clone() as Solid3d, solid.Clone() as Solid3d, solid.Clone() as Solid3d };

                for (int i = 0; i < 5; i++)
                {
                    modelSpace.AppendEntity(solidARR[i]);
                    acTrans.AddNewlyCreatedDBObject(solidARR[i], true);
                }

                Vector3d vRot1 = centroid.GetVectorTo(new Point3d(centroid.X, centroid.Y + 2.5 * Math.Abs(MAX.X), centroid.Z));
                Vector3d vRot2 = centroid.GetVectorTo(new Point3d(centroid.X + 2.5 * Math.Abs(MAX.X), centroid.Y, centroid.Z));
                Vector3d vRot3 = centroid.GetVectorTo(new Point3d(centroid.X, centroid.Y, centroid.Z + 2.5 * Math.Abs(MAX.Z)));


                if (bds)
                {
                    solidARR[0].TransformBy(Matrix3d.Rotation(-Math.PI / 2.0, vRot1, centroid));
                    solidARR[0].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X - MaxZ - 1.5 * MaxX, centroid.Y, centroid.Z))));
                    solids[1] = solidARR[0].ObjectId;
                    solidARR[1].TransformBy(Matrix3d.Rotation(Math.PI / 2.0, vRot1, centroid));
                    solidARR[1].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X + MaxZ + 1.5 * MaxX, centroid.Y, centroid.Z))));
                    solids[2] = solidARR[1].ObjectId;
                    solidARR[2].TransformBy(Matrix3d.Rotation(Math.PI, vRot1, centroid));
                    solidARR[2].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X + 3 * MaxZ + 2.5 * MaxX, centroid.Y, centroid.Z))));
                    solids[3] = solidARR[2].ObjectId;
                    solidARR[3].TransformBy(Matrix3d.Rotation(Math.PI / 2, vRot2, centroid));
                    solidARR[3].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X, centroid.Y - MaxZ - 1.5 * MaxY, centroid.Z))));
                    solids[4] = solidARR[3].ObjectId;
                    solidARR[4].TransformBy(Matrix3d.Rotation(-Math.PI / 2, vRot2, centroid));
                    solidARR[4].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X, centroid.Y + MaxZ + 1.5 * MaxY, centroid.Z))));
                    solids[5] = solidARR[4].ObjectId;
                }
                else
                {
                    solidARR[0].TransformBy(Matrix3d.Rotation(-Math.PI / 2.0, vRot1, centroid));
                    solidARR[0].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X + MaxZ + 1.5 * MaxX, centroid.Y, centroid.Z))));
                    solids[1] = solidARR[0].ObjectId;

                    solidARR[1].TransformBy(Matrix3d.Rotation(Math.PI / 2.0, vRot1, centroid));
                    solidARR[1].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X - MaxZ - 1.5 * MaxX, centroid.Y, centroid.Z))));
                    solids[2] = solidARR[1].ObjectId;

                    solidARR[2].TransformBy(Matrix3d.Rotation(Math.PI, vRot1, centroid));
                    solidARR[2].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X + 3 * MaxZ + 2.5 * MaxX, centroid.Y, centroid.Z))));
                    solids[3] = solidARR[2].ObjectId;
                    solidARR[3].TransformBy(Matrix3d.Rotation(Math.PI / 2, vRot2, centroid));
                    solidARR[3].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X, centroid.Y + MaxZ + 1.5 * MaxY, centroid.Z))));
                    solids[4] = solidARR[3].ObjectId;
                    solidARR[4].TransformBy(Matrix3d.Rotation(-Math.PI / 2, vRot2, centroid));
                    solidARR[4].TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X, centroid.Y - MaxZ - 1.5 * MaxY, centroid.Z))));
                    solids[5] = solidARR[4].ObjectId;
                }

                Solid3d solid1 = solid.Clone() as Solid3d;
                modelSpace.AppendEntity(solid1);
                acTrans.AddNewlyCreatedDBObject(solid1, true);

                solids[6] = solid1.ObjectId;

                solid1.TransformBy(Matrix3d.Rotation(Math.PI / 4, vRot3, centroid));
                solid1.TransformBy(Matrix3d.Rotation(-Math.PI / 3.28854, vRot2, centroid));

                double dX = Math.Abs(solid1.GeometricExtents.MinPoint.X - centroid.X) + Math.Abs(solid.GeometricExtents.MaxPoint.X - centroid.X);
                double dY = Math.Abs(solid1.GeometricExtents.MinPoint.Y - centroid.Y) + Math.Abs(solid.GeometricExtents.MaxPoint.Y - centroid.Y);
                solid1.TransformBy(Matrix3d.Displacement(centroid.GetVectorTo(new Point3d(centroid.X + dX + 1.5 * MaxX, centroid.Y + dY + 1.5 * MaxY, 0))));

                acTrans.Commit();
            }

            for (int i = 0; i < 7; i++)
            {
                solids_buff[i] = solids[i];
            }


            doc.SendStringToExecute("-view\rO\rT\r", false, false, false);
            doc.SendStringToExecute("TILEMODE\r0\r", false, false, false);
            // Autodesk.AutoCAD.ApplicationServices.Application.SetSystemVariable("TILEMODE", 0);
            // Doc.Editor.SwitchToPaperSpace();
            doc.SendStringToExecute("MSPACE\r", false, false, false);
            doc.SendStringToExecute("SOLPROF\rall\r\rY\rY\rY\r", false, false, false);
            doc.SendStringToExecute("PSPACE\r", false, false, false);
            doc.SendStringToExecute("TILEMODE\r1\r", false, false, false);
            //Doc.SendStringToExecute("ZOOM\rE\r" , false , false , false);
            doc.SendStringToExecute("hideflat\r", false, false, false);

            if (target.Status == PromptStatus.OK)
            {
                string bs = centroid.X.ToString() + "," + centroid.Y.ToString();
                string ts = target.Value.X.ToString() + "," + target.Value.Y.ToString();

                doc.SendStringToExecute("move\rlast\r\r" + bs + "\r" + ts + "\r", false, false, false);
                doc.SendStringToExecute("ZOOM\rE\r", false, false, false);

            }

            doc.SendStringToExecute("eraseflat\r", false, false, false);
            doc.SendStringToExecute("finalflat\r", false, false, false);
            doc.SendStringToExecute("ZOOM\rE\r", false, false, false);
        }
Example #13
0
        private TableEntry readEntry(DxfEntryTemplate template)
        {
            TableEntry table = null;

            //Get the entry
            switch (template.TableName)
            {
            case DxfFileToken.TableAppId:
                table = new AppId(template);
                break;

            case DxfFileToken.TableBlockRecord:
                table = new BlockRecord(template);
                break;

            case DxfFileToken.TableDimstyle:
                table = new DimensionStyle(template);
                break;

            case DxfFileToken.TableLayer:
                table = new Layer(template);
                break;

            case DxfFileToken.TableLinetype:
                table = new LineType(template);
                break;

            case DxfFileToken.TableStyle:
                table = new Style(template);
                break;

            case DxfFileToken.TableUcs:
                table = new UCS(template);
                break;

            case DxfFileToken.TableView:
                table = new View(template);
                break;

            case DxfFileToken.TableVport:
                table = new VPort(template);
                break;

            default:
                Debug.Fail($"Unhandeled table {template.Name}.");
                break;
            }

            //Jump the SubclassMarker
            m_reader.ReadNext();

            Dictionary <DxfCode, object> map = table?.GetCadObjectMap() ?? new Dictionary <DxfCode, object>();

            while (m_reader.LastDxfCode != DxfCode.Start)
            {
                //Check if the dxf code is registered
                if (map.ContainsKey(m_reader.LastDxfCode))
                {
                    //Set the value
                    map[m_reader.LastDxfCode] = m_reader.LastValue;
                }

                m_reader.ReadNext();
            }

            //Build the table based on the map
            table?.Build(map);

            return(table);
        }
Example #14
0
        private void readEntries <T>(DwgTableTemplate <T> tableTemplate)
            where T : TableEntry
        {
            //Read all the entries until the end of the table
            while (this._reader.LastValueAsString != DxfFileToken.EndTable)
            {
                this.readCommonObjectData(out string name, out ulong handle, out ulong?ownerHandle, out ulong?xdictHandle, out List <ulong> reactors);

                Debug.Assert(this._reader.LastValueAsString == DxfSubclassMarker.TableRecord);
                Debug.Assert(this._reader.LastValueAsString == DxfSubclassMarker.TableRecord);

                this._reader.ReadNext();

                CadTemplate template = null;

                //Get the entry
                switch (name)
                {
                case DxfFileToken.TableAppId:
                    AppId appid = new AppId();
                    template = new CadTableEntryTemplate <AppId>(appid);
                    this.readMapped <AppId>(appid, template);
                    break;

                case DxfFileToken.TableBlockRecord:
                    BlockRecord record = new BlockRecord();
                    template = new CadBlockRecordTemplate(record);
                    this.readMapped <BlockRecord>(record, template);
                    break;

                case DxfFileToken.TableDimstyle:
                    DimensionStyle dimStyle = new DimensionStyle();
                    template = new DwgDimensionStyleTemplate(dimStyle);
                    this.readMapped <DimensionStyle>(dimStyle, template);
                    break;

                case DxfFileToken.TableLayer:
                    Layer layer = new Layer();
                    template = new CadLayerTemplate(layer);
                    this.readMapped <Layer>(layer, template);
                    break;

                case DxfFileToken.TableLinetype:
                    LineType ltype = new LineType();
                    template = new CadLineTypeTemplate(ltype);
                    this.readMapped <LineType>(ltype, template);
                    break;

                case DxfFileToken.TableStyle:
                    TextStyle style = new TextStyle();
                    template = new CadTableEntryTemplate <TextStyle>(style);
                    this.readMapped <TextStyle>(style, template);
                    break;

                case DxfFileToken.TableUcs:
                    UCS ucs = new UCS();
                    template = new CadUcsTemplate(ucs);
                    this.readMapped <UCS>(ucs, template);
                    break;

                case DxfFileToken.TableView:
                    View view = new View();
                    template = new CadViewTemplate(view);
                    this.readMapped <View>(view, template);
                    break;

                case DxfFileToken.TableVport:
                    VPort vport = new VPort();
                    template = new CadVPortTemplate(vport);
                    this.readMapped <VPort>(vport, template);
                    break;

                default:
                    Debug.Fail($"Unhandeled table {name}.");
                    break;
                }

                //Setup the common fields
                template.CadObject.Handle = handle;
                template.OwnerHandle      = ownerHandle;
                template.XDictHandle      = xdictHandle;
                template.ReactorsHandles  = reactors;

                tableTemplate.EntryHandles.Add(template.CadObject.Handle);

                //Add the object and the template to the builder
                this._builder.AddTemplate(template);
            }
        }
Example #15
0
        public void ArrowMarkStart()
        {
            var basePointResult = _editorHelper.PromptForPoint("Pick arrow point : ");

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

            var directionPointResult = _editorHelper.PromptForPoint("Pick direction point : ", true, true, basePointResult.Value);

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

            if (directionPointResult.Value == basePointResult.Value)
            {
                _editorHelper.WriteMessage("\nBase point and direction point can not be the same or be less then 8 units closer. Try again and place the direction point further from the base point.");
                return;
            }

            Vector3d xAxis = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d.Xaxis;
            Vector3d yAxis = Application.DocumentManager.MdiActiveDocument.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d.Yaxis;

            xAxis = (xAxis + yAxis) / 2.0;

            Matrix3d ucs = _editorHelper.CurrentUcs;

            basePointResult.Value.TransformBy(GeometryUtility.GetTransforMatrixToWcs());
            directionPointResult.Value.TransformBy(GeometryUtility.GetTransforMatrixToWcs());



            _editorHelper.CurrentUcs = Matrix3d.Identity;
            Point3d    endPoint = directionPointResult.Value;
            Vector3d   vx       = new Vector3d(endPoint.X - basePointResult.Value.X, endPoint.Y - basePointResult.Value.Y, endPoint.Z - basePointResult.Value.Z);
            Quaternion qx       = new Quaternion(0, vx.X, vx.Y, vx.Z);
            Quaternion qy       = new Quaternion(0, xAxis.X, xAxis.Y, xAxis.Z);
            UCS        UCS      = new UCS(new Quaternion(0, 0, 0, 0), qx, qy);

            qx = UCS.ToACS(new Quaternion(0, 1, 0, 0));
            qy = UCS.ToACS(new Quaternion(0, 0, 1, 0));
            Quaternion qz = UCS.ToACS(new Quaternion(0, 0, 0, 1));

            vx    = new Vector3d(qx.GetX(), qx.GetY(), qx.GetZ());
            yAxis = new Vector3d(qy.GetX(), qy.GetY(), qy.GetZ());
            Vector3d vZ = new Vector3d(qz.GetX(), qz.GetY(), qz.GetZ());

            Matrix3d newUcs = Matrix3d.AlignCoordinateSystem(Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis, basePointResult.Value, vx, yAxis, vZ);

            double dist = basePointResult.Value.DistanceTo(endPoint);

            endPoint = new Point3d(dist, 0, 0);

            Hashtable dynamicBlockProperties = new Hashtable();
            Hashtable dynamicBlockAttributes = new Hashtable();

            dynamicBlockProperties.Add("Base Point", basePointResult);
            dynamicBlockProperties.Add("Arrow Direction", (Int16)0); // always to the right
            double rotationAngle = GeometryUtility.GetAngleFromXAxis(new Point3d(), endPoint);

            dynamicBlockProperties.Add("Arrow Rotation", rotationAngle);

            ObjectId refO = new ObjectId();
            string   dynamicBlockFullName = _blockDrawingProvider.GetBlockFile(MethodBase.GetCurrentMethod().DeclaringType.Name);

            if (dynamicBlockFullName == null)
            {
                _editorHelper.WriteMessage("Dynamic block ArrowMark.dwg does not exist.");
                return;
            }

            try
            {
                refO = _drawingHelper.ImportDynamicBlockAndFillItsProperties(dynamicBlockFullName, new Point3d(), dynamicBlockProperties, dynamicBlockAttributes);
            }
            catch (Exception exception)
            {
                _logger.Error("Error importing Arrow mark.", exception);
                _editorHelper.WriteMessage("Error importing Arrow mark.");
                return;
            }


            using (Transaction startTransaction = Application.DocumentManager.MdiActiveDocument.Database.TransactionManager.StartTransaction())
            {
                var entity = (Entity)startTransaction.GetObject(refO, OpenMode.ForWrite);
                entity.TransformBy(newUcs);
                startTransaction.Commit();
            }

            _editorHelper.CurrentUcs = ucs;
            _logger.Info(MethodBase.GetCurrentMethod().Name);
        }
Example #16
0
        public void LevelHeightSignStart()
        {
            var insertionPointResult = _editorHelper.PromptForPoint("Pick insertion point : ");

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

            var dynamicBlockProperties = new Hashtable();
            var dynamicBlockAttributes = new Hashtable();

            dynamicBlockProperties.Add("Base Point", insertionPointResult.Value);
            var dynamicBlockPath = _blockDrawingProvider.GetBlockFile(MethodBase.GetCurrentMethod().DeclaringType.Name);

            if (dynamicBlockPath == null)
            {
                _editorHelper.WriteMessage("Dynamic block LevelHeightSign.dwg does not exist.");
                return;
            }
            var brefId = _drawingHelper.ImportDynamicBlockAndFillItsProperties(
                dynamicBlockPath, insertionPointResult.Value, dynamicBlockProperties, dynamicBlockAttributes);

            using (var transaction = _doc.TransactionManager.StartTransaction())
            {
                var blockReference = (BlockReference)transaction.GetObject(brefId, OpenMode.ForWrite);

                var zAxis  = _doc.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis;
                var xAxis  = _doc.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d.Xaxis;
                var yAxis  = _doc.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d.Yaxis;
                var origin = _doc.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d.Origin;

                var mat = Matrix3d.AlignCoordinateSystem(
                    Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis, origin, xAxis, yAxis, zAxis);

                blockReference.TransformBy(mat);

                var ORIGIN = new Quaternion(0, origin.X, origin.Y, origin.Z);
                var axeX   = new Quaternion(0, xAxis.X, xAxis.Y, xAxis.Z);
                var axeY   = new Quaternion(0, yAxis.X, yAxis.Y, yAxis.Z);

                var ucs       = new UCS(ORIGIN, ORIGIN + axeX, ORIGIN + axeY);
                var basePoint = new Quaternion(
                    0, insertionPointResult.Value.X, insertionPointResult.Value.Y, insertionPointResult.Value.Z);
                basePoint = ucs.ToACS(basePoint);
                ucs       = new UCS(ORIGIN, ORIGIN + axeX, basePoint);

                var y = ucs.FromACS(basePoint).GetY();
                if (double.IsNaN(y))
                {
                    y = 0.0;
                }

                foreach (ObjectId attId in blockReference.AttributeCollection)
                {
                    var attributeReference = (AttributeReference)transaction.GetObject(attId, OpenMode.ForWrite);
                    if (attributeReference.Tag == "LEVEL")
                    {
                        var mess = y.ToString("0.#####");
                        attributeReference.TextString = (mess.Length > 0) ? mess : "0.0";
                    }
                }
                transaction.Commit();
            }
            _logger.Info(MethodBase.GetCurrentMethod().Name);
        }
Example #17
0
        public void RecalcLevelHeightSignStart()
        {
            var objectIdCollection = _editorHelper.PromptForSelection("Select LEVEL  Entites:");

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

            var origin = _doc.Editor.CurrentUserCoordinateSystem.CoordinateSystem3d.Origin;
            var ORIGIN = new Quaternion(0, origin.X, origin.Y, origin.Z);

            using (var transaction = _doc.TransactionManager.StartTransaction())
            {
                var blockTable = (BlockTable)transaction.GetObject(_db.BlockTableId, OpenMode.ForRead);

                // TODO : Level must not be hard coded. TDD - convensions test
                var blockTableRecordLevelSign =
                    (BlockTableRecord)transaction.GetObject(blockTable["Level"], OpenMode.ForWrite);
                var btrIDs = new UtilityClass().GetAllRefernecesOfBtr(blockTableRecordLevelSign.ObjectId, transaction);
                foreach (ObjectId asObjId in btrIDs)
                {
                    var ok = false;
                    for (var i = 0; i < objectIdCollection.Value.GetObjectIds().Length; i++)
                    {
                        if (asObjId == objectIdCollection.Value.GetObjectIds()[i])
                        {
                            ok = true;
                            break;
                        }
                    }
                    if (ok == false)
                    {
                        continue;
                    }
                    var blockReference = transaction.GetObject(asObjId, OpenMode.ForWrite) as BlockReference;
                    var basePoint      = blockReference.Position;
                    var normal         = blockReference.Normal;
                    var xAxis          = new Point3d();
                    var testP          = new Point3d();

                    var dbObjectCollection = new DBObjectCollection();
                    blockReference.Explode(dbObjectCollection);
                    foreach (Entity entity in dbObjectCollection)
                    {
                        if (entity.ColorIndex == 1)
                        {
                            var line = entity as Line;
                            xAxis = line.StartPoint;

                            if (xAxis.DistanceTo(basePoint) < 0.5)
                            {
                                xAxis = line.EndPoint;
                            }
                        }
                        else
                        {
                            var str = entity.GetType().ToString();
                            if (str.Contains("Poly"))
                            {
                                var polyline = entity as Polyline;
                                testP = polyline.GetLineSegmentAt(1).MidPoint;
                            }
                        }
                    }
                    var op    = new Quaternion(0, basePoint.X, basePoint.Y, basePoint.Z);
                    var ox    = new Quaternion(0, xAxis.X, xAxis.Y, xAxis.Z);
                    var oz    = new Quaternion(0, normal.X, normal.Y, normal.Z);
                    var testQ = new Quaternion(0, testP.X, testP.Y, testP.Z);

                    var ucs = new UCS(op, ox, op + oz);
                    if (ucs.FromACS(testQ).GetZ() < 0)
                    {
                        ucs = new UCS(op, op + oz, ox);
                    }

                    var y = -ucs.FromACS(ORIGIN).GetZ();

                    foreach (ObjectId attId in blockReference.AttributeCollection)
                    {
                        var attributeReference = (AttributeReference)transaction.GetObject(attId, OpenMode.ForWrite);
                        if (attributeReference.Tag != "LEVEL")
                        {
                            continue;
                        }
                        var oldStr = "\nold = " + attributeReference.TextString;
                        if (double.IsNaN(y))
                        {
                            y = 0.0;
                        }
                        var mess = y.ToString("0.#####");
                        attributeReference.TextString = ((mess.Length > 0) ? mess : "0.0");
                        _doc.Editor.WriteMessage(oldStr + " / " + DateTime.Now.ToString("d"));
                    }
                }
                transaction.Commit();
            }
            _logger.Info(MethodBase.GetCurrentMethod().Name);
        }
Example #18
0
        private void CreateInsulationPolylineAndAppendToModelSpace(Point3d[] inputPoints, int rk,
                                                                   bool drawPerimeterOfInsulation)
        {
            var inputQPoints = new Quaternion[4]; // completed after sorting

            #region sorting

            var longestDistance = 0.0;
            var indexFirstPoint = 0;
            for (var i = 1; i < 4; i++)
            {
                var currentDistance = inputPoints[i - 1].DistanceTo(inputPoints[i]);
                if (currentDistance > longestDistance)
                {
                    longestDistance = currentDistance;
                    indexFirstPoint = i - 1;
                }
            }
            if (inputPoints[3].DistanceTo(inputPoints[0]) > longestDistance)
            {
                indexFirstPoint = 3;
            }

            var tempPoints = new Point3d[4];
            for (var i = indexFirstPoint; i < 4 + indexFirstPoint; i++)
            {
                if (i < 4)
                {
                    tempPoints[i - indexFirstPoint] = inputPoints[i];
                }
                else
                {
                    tempPoints[i - indexFirstPoint] = inputPoints[i - 4];
                }
            }

            for (var i = 0; i < 4; i++)
            {
                inputPoints[i]  = tempPoints[i];
                inputQPoints[i] = new Quaternion(0.0, inputPoints[i].X, inputPoints[i].Y, inputPoints[i].Z);
            }

            #endregion

            var uCSOfInputPoints = new UCS(inputQPoints[0], inputQPoints[1], inputQPoints[2]);

            if (Math.Abs((uCSOfInputPoints.FromACS(inputQPoints[3])).GetZ()) > 0.00000254)
            {
                _editorHelper.WriteMessage("Four Points are not in the same Plane !");
                _logger.Info("User input is invalid.");
                return;
            }

            #region counterclockwise selection test

            var centerUcsOfInputPoints  = new Quaternion(0, 0, 0, 0);
            var zAxisInUscOfInputPoints = new Quaternion(0, 0, 0, 1000);
            var zAxisInAcs = uCSOfInputPoints.ToACS(zAxisInUscOfInputPoints) -
                             uCSOfInputPoints.ToACS(centerUcsOfInputPoints);
            if (zAxisInAcs.GetZ() < 0)
            {
                var tempPoint      = new Point3d();
                var tempQuaternion = new Quaternion();

                tempPoint      = inputPoints[0];
                inputPoints[0] = inputPoints[1];
                inputPoints[1] = tempPoint;

                tempQuaternion  = inputQPoints[0];
                inputQPoints[0] = inputQPoints[1];
                inputQPoints[1] = tempQuaternion;

                tempPoint      = inputPoints[2];
                inputPoints[2] = inputPoints[3];
                inputPoints[3] = tempPoint;

                tempQuaternion  = inputQPoints[2];
                inputQPoints[2] = inputQPoints[3];
                inputQPoints[3] = tempQuaternion;

                uCSOfInputPoints = new UCS(inputQPoints[0], inputQPoints[1], inputQPoints[2]);
            }

            #endregion

            var ucsPoints = new Point3d[4];
            //are coordinates in a 0.0 WCS to draw (drawing only in oXY 0,0 per WCS and transform when it is ready polyline transform)
            var ucsQPoints = new Quaternion[4];
            //are coordinates in a 0.0 WCS to draw (drawing only in oXY 0,0 per WCS and when it is ready polyline transform)

            var complexPoints   = new Complex[4];
            var sidesOffPolygon = new Complex[4];

            #region 2d prepare

            for (int i = 0; i < 4; i++)
            {
                Quaternion q = uCSOfInputPoints.FromACS(inputQPoints[i]);
                ucsQPoints[i] = new Quaternion(0, (Math.Abs(q.GetX()) > 0.00000254) ? q.GetX() : 0.0,
                                               (Math.Abs(q.GetY()) > 0.00000254) ? q.GetY() : 0.0,
                                               (Math.Abs(q.GetZ()) > 0.00000254) ? q.GetZ() : 0.0);
                ucsPoints[i]     = new Point3d(ucsQPoints[i].GetX(), ucsQPoints[i].GetY(), ucsQPoints[i].GetZ());
                complexPoints[i] = new Complex(ucsQPoints[i].GetX(), ucsQPoints[i].GetY());
                if (i > 0)
                {
                    sidesOffPolygon[i - 1] = complexPoints[i] - complexPoints[i - 1];
                }
            }
            sidesOffPolygon[3] = complexPoints[0] - complexPoints[3];

            #endregion

            #region convex check

            for (var i = 0; i < 4; i++)
            {
                if (Math.Abs(GetAngleInPointIndex(i, complexPoints)) >= Math.PI)
                {
                    break;
                }
            }

            #endregion

            var minThickness = (complexPoints[2].imag() < complexPoints[3].imag())
                                   ? complexPoints[2].imag()
                                   : complexPoints[3].imag();
            var segmentsCount = (int)Math.Ceiling((sidesOffPolygon[0].abs() / minThickness) / 0.35);

            var radius = sidesOffPolygon[0].abs() * 2 / (segmentsCount * 2);
            radius /= rk;

            var lowerLine = new List <Complex>();
            var upperLine = new List <Complex>();


            var insulationPerimeter = new Polyline();
            insulationPerimeter.SetDatabaseDefaults();
            insulationPerimeter.AddVertexAt(0, new Point2d(complexPoints[0].real(), complexPoints[0].imag()), 0, 0,
                                            0);
            insulationPerimeter.AddVertexAt(1, new Point2d(complexPoints[1].real(), complexPoints[1].imag()), 0, 0,
                                            0);
            insulationPerimeter.AddVertexAt(2, new Point2d(complexPoints[2].real(), complexPoints[2].imag()), 0, 0,
                                            0);
            insulationPerimeter.AddVertexAt(3, new Point2d(complexPoints[3].real(), complexPoints[3].imag()), 0, 0,
                                            0);
            insulationPerimeter.AddVertexAt(4, new Point2d(complexPoints[0].real(), complexPoints[0].imag()), 0, 0,
                                            0);

            var objectsCollection = insulationPerimeter.GetOffsetCurves(-radius);
            var acPolyOffset      = objectsCollection[0] as Polyline;

            var pointsFromOffset = new Complex[4];
            for (var i = 0; i < 4; i++)
            {
                var point = acPolyOffset.GetPoint3dAt(i);
                pointsFromOffset[i] = new Complex(point.X, point.Y);
            }

            var variant = 0;
            if (pointsFromOffset[3].real() < pointsFromOffset[0].real() &&
                (pointsFromOffset[3] - pointsFromOffset[0]).abs() / (radius * 2) > 1 &&
                Math.Abs(pointsFromOffset[2].real() - pointsFromOffset[1].real()) > radius * 2)
            {
                variant = 1;
                lowerLine.Add(pointsFromOffset[0]);
                var xPos = pointsFromOffset[0].real();
                do
                {
                    xPos += radius * 2.0;
                    if (xPos <= pointsFromOffset[1].real() + radius * 2 / 3)
                    {
                        lowerLine.Add(new Complex(xPos, radius));
                    }
                } while (xPos < (pointsFromOffset[0] - pointsFromOffset[1]).abs() + radius * 2 / 3);

                xPos = 0;
                var ort = (pointsFromOffset[3] - pointsFromOffset[0]) /
                          (pointsFromOffset[3] - pointsFromOffset[0]).abs();
                var k = Math.Abs(Math.Cos(ort.arg()));
                k -= 0.01;
                do
                {
                    xPos += 2 * radius / Math.Abs(k);
                    if (xPos < (pointsFromOffset[3] - pointsFromOffset[0]).abs() + radius * 2 / 3)
                    {
                        lowerLine.Insert(0, ort * xPos + pointsFromOffset[0]);
                    }
                } while (xPos < (pointsFromOffset[3] - pointsFromOffset[0]).abs() + radius * 2 / 3);
                lowerLine.RemoveAt(0);
            }

            if (pointsFromOffset[1].real() < pointsFromOffset[2].real() &&
                (pointsFromOffset[2] - pointsFromOffset[1]).abs() / (radius * 2) > 1 &&
                Math.Abs(pointsFromOffset[2].real() - pointsFromOffset[1].real()) > radius * 2)
            {
                variant = 2;
                lowerLine.Add(pointsFromOffset[1]);
                var xPos = pointsFromOffset[1].real();
                do
                {
                    xPos -= radius * 2.0;
                    if (xPos >= pointsFromOffset[0].real() - radius * 2.0 / 3.0)
                    {
                        lowerLine.Insert(0, new Complex(xPos, radius));
                    }
                } while (xPos > pointsFromOffset[0].real() - radius * 2.0 / 3.0);


                xPos = 0;
                var ort = (pointsFromOffset[2] - pointsFromOffset[1]) /
                          (pointsFromOffset[2] - pointsFromOffset[1]).abs();
                var k = Math.Abs(Math.Cos(ort.arg()));
                k -= 0.01;
                do
                {
                    xPos += 2 * radius / Math.Abs(k);
                    if (xPos < (pointsFromOffset[2] - pointsFromOffset[1]).abs() + radius * 2.0 / 3.0)
                    {
                        lowerLine.Add(ort * xPos + pointsFromOffset[1]);
                    }
                } while (xPos < (pointsFromOffset[2] - pointsFromOffset[1]).abs() + radius * 2.0 / 3.0);
            }
            if (variant == 0)
            {
                lowerLine.Add(pointsFromOffset[0]);
                var xPos = pointsFromOffset[0].real();
                do
                {
                    xPos += radius * 2.0;
                    if (xPos <= pointsFromOffset[1].real() + radius * 2.0)
                    {
                        lowerLine.Add(new Complex(xPos, radius));
                    }
                } while (xPos < (pointsFromOffset[0] - pointsFromOffset[1]).abs() + radius * 2.0);
            }

            var insulationPolyline = new Polyline();
            insulationPolyline.SetDatabaseDefaults();
            var old = new KeyValuePair <Complex, Complex>();
            for (var i = 1; i < lowerLine.Count; i++)
            {
                var hlpPoint = (lowerLine[i] + lowerLine[i - 1]) / 2.0;

                var verticalLine = new Line(new Point3d(hlpPoint.real(), hlpPoint.imag(), 0),
                                            new Point3d(hlpPoint.real(), hlpPoint.imag() + 0.01, 0));

                var pts = new Point3dCollection();
                try
                {
                    acPolyOffset.IntersectWith(verticalLine, Intersect.ExtendBoth, pts, IntPtr.Zero, IntPtr.Zero);
                }
                catch (Exception aCadRuntimeException)
                {
                    _logger.Error("Unable to Intersect 2 entities", aCadRuntimeException);
                }
                if (pts.Count != 2)
                {
                    continue;
                }
                var p  = (pts[0].Y > pts[1].Y) ? pts[0] : pts[1];
                var cc = new Complex(p.X, p.Y);
                if ((cc - hlpPoint).abs() > 2 * radius)
                {
                    upperLine.Add(new Complex(p.X, p.Y));

                    var tangentPointsTopLeftBotRight = GetTangentPointsOfCommonInternalTanget(cc, radius,
                                                                                              lowerLine[i], radius,
                                                                                              true);
                    var tangentPointsBotRightTopLeft = GetTangentPointsOfCommonInternalTanget(lowerLine[i - 1],
                                                                                              radius, cc, radius,
                                                                                              false);

                    if (i > 1)
                    {
                        double ang1 = 0;

                        ang1 =
                            ((lowerLine[i - 1] - tangentPointsBotRightTopLeft.Key) / (lowerLine[i - 1] - old.Value))
                            .arg();
                        insulationPolyline.AddVertexAt(0,
                                                       new Point2d(tangentPointsBotRightTopLeft.Key.real(),
                                                                   tangentPointsBotRightTopLeft.Key.imag()),
                                                       -Math.Tan(ang1 / 4), 0, 0);
                    }
                    else
                    {
                        insulationPolyline.AddVertexAt(0,
                                                       new Point2d(tangentPointsBotRightTopLeft.Key.real(),
                                                                   tangentPointsBotRightTopLeft.Key.imag()), 0, 0, 0);
                    }
                    double ang =
                        ((cc - tangentPointsBotRightTopLeft.Value) / (cc - tangentPointsTopLeftBotRight.Key)).arg();
                    insulationPolyline.AddVertexAt(0,
                                                   new Point2d(tangentPointsBotRightTopLeft.Value.real(),
                                                               tangentPointsBotRightTopLeft.Value.imag()), 0, 0, 0);

                    insulationPolyline.AddVertexAt(0,
                                                   new Point2d(tangentPointsTopLeftBotRight.Key.real(),
                                                               tangentPointsTopLeftBotRight.Key.imag()),
                                                   Math.Tan(ang / 4), 0, 0);
                    insulationPolyline.AddVertexAt(0,
                                                   new Point2d(tangentPointsTopLeftBotRight.Value.real(),
                                                               tangentPointsTopLeftBotRight.Value.imag()), 0, 0, 0);

                    old = tangentPointsTopLeftBotRight;
                }
                else
                {
                    if (i < lowerLine.Count / 2)
                    {
                        lowerLine.RemoveAt(i - 1);
                    }
                    else
                    {
                        lowerLine.RemoveAt(i);
                    }
                    i--;
                }
            }

            var vectorBaseLine = new Complex(inputPoints[1].X, inputPoints[1].Y) -
                                 new Complex(inputPoints[0].X, inputPoints[0].Y);

            #region transforms

            insulationPolyline.TransformBy(Matrix3d.Rotation(vectorBaseLine.arg(), new Vector3d(0, 0, 1),
                                                             Point3d.Origin));
            insulationPerimeter.TransformBy(Matrix3d.Rotation(vectorBaseLine.arg(), new Vector3d(0, 0, 1),
                                                              Point3d.Origin));

            insulationPolyline.TransformBy(Matrix3d.Displacement(Point3d.Origin.GetVectorTo(inputPoints[0])));
            insulationPerimeter.TransformBy(Matrix3d.Displacement(Point3d.Origin.GetVectorTo(inputPoints[0])));

            insulationPolyline.TransformBy(_editorHelper.CurrentUcs);
            insulationPerimeter.TransformBy(_editorHelper.CurrentUcs);

            #endregion

            var oldLayer = _documentHelper.Database.Clayer;

            _documentHelper.LayerManipulator.CreateLayer("3-0", System.Drawing.Color.Lime);
            insulationPolyline.Layer = "0";
            var softInsulationBlock = new BlockTableRecord();
            var nameSalt            = DateTime.Now.GetHashCode().ToString();
            softInsulationBlock.Name   = "SoftInsulation_" + nameSalt;
            softInsulationBlock.Origin = inputPoints[0];

            using (var acTrans = _documentHelper.TransactionManager.StartTransaction())
            {
                var acBlkTbl = acTrans.GetObject(_documentHelper.Database.BlockTableId, OpenMode.ForWrite) as BlockTable;
                acBlkTbl.Add(softInsulationBlock);
                acTrans.AddNewlyCreatedDBObject(softInsulationBlock, true);
                softInsulationBlock.AppendEntity(insulationPolyline);
                acTrans.AddNewlyCreatedDBObject(insulationPolyline, true);
                if (drawPerimeterOfInsulation)
                {
                    insulationPerimeter.Layer = "0";
                    softInsulationBlock.AppendEntity(insulationPerimeter);
                    acTrans.AddNewlyCreatedDBObject(insulationPerimeter, true);
                }
                var rigidInsulationRef = new BlockReference(inputPoints[0],
                                                            softInsulationBlock.ObjectId)
                {
                    Layer = "3-0"
                };
                var currentSpace =
                    (BlockTableRecord)acTrans.GetObject(_documentHelper.Database.CurrentSpaceId, OpenMode.ForWrite);
                currentSpace.AppendEntity(rigidInsulationRef);
                acTrans.AddNewlyCreatedDBObject(rigidInsulationRef, true);
                acTrans.Commit();
            }
            _documentHelper.LayerManipulator.ChangeLayer(oldLayer);
        }
Example #19
0
 public UCS(UCS ucs)
 {
     ang = ucs.ang;
     o   = ucs.o;
 }
Example #20
0
 void OnGUI()
 {
     Debug.Log(UCS.ConvertRect(new Rect(-1.0f, -1.0f, 2.0f, 2.0f)));
     GUI.Box(UCS.ConvertRect(new Rect(-1.0f, -1.0f, 2.0f, 2.0f)), "Test");
 }
Example #21
0
        ///ThreadPoolSolveMaze <summary>
        /// thrding to solve maze
        /// </summary>
        /// <param name="p">name to solve</param>
        public void ThreadPoolSolveMaze(object p)
        {
            bool         flag   = false;
            bool         exict  = false;
            string       Name   = (string)p;
            extendedMaze m_Maze = new extendedMaze();

            m_Status = string.Format("started Solving Maze {0}...", p);
            PrintEvent();
            try
            {
                m_Maze = MazeDictionary[Name];
                if (SolutionDictionary.ContainsKey(m_Maze))
                {
                    m_Status = string.Format("Solution For {0} Allready Exict In Dictionary", p);
                    PrintEvent();
                    exict = true;
                }
            }
            catch (System.Exception ex)
            {
                m_Status = ex.Message;
                PrintEvent();
            }


            if (!exict)
            {
                IStoppable Alg;
                if (Curr_Alg == "A*")                                           //Setting Cunfigure
                {                                                               //*****************
                    if (Curr_Heuristic == "MazeAirDistance")                    //3 Diffrent Algorithm
                    {
                        Alg = new Astar(new MazeAirDistance());                 //Astar->MazeAirDistance
                    }
                    else                                                        //Astar->MazeManhattanDistance
                    {
                        Alg = new Astar(new MazeManhattanDistance());           //UCS
                    }
                }
                else
                {
                    Alg = new UCS();
                }
                Workers.Add(Alg);
                try
                {
                    foreach_Mutex.WaitOne();
                    foreach (KeyValuePair <extendedMaze, Solution> item in SolutionDictionary)
                    {
                        if (item.Key.getGrid() == m_Maze.getGrid())                                                                               // Ovaride equals to chack if
                        {                                                                                                                         //a sol is Allready  Exict
                            m_Status = string.Format("Solution  for {0} Allready Exict In {1}", m_Maze.getName(), item.Key.getName());            // if he does copy it
                            PrintEvent();
                            Solution sol = SolutionDictionary[item.Key];
                            if (sol != null && sol.GetSolutionPath().Count > 0)
                            {
                                addSol(m_Maze, sol);
                            }
                            flag = true;
                            break;
                        }
                    }
                    foreach_Mutex.ReleaseMutex();

                    if (!flag)
                    {
                        ISearchable Searchable_Maze;
                        if (!IsDiagonal)                                                               //Diagonal Setting
                        {
                            Searchable_Maze = new SearchableMaze(m_Maze, false);                       //****************
                        }
                        else                                                                           //False->Without
                        {
                            Searchable_Maze = new SearchableMaze(m_Maze, true);                        //True->With
                        }
                        Solution  sol    = (Solution)(((ASearchingAlgorithm)Alg).Solve(Searchable_Maze));
                        ArrayList list   = sol.GetSolutionPath();
                        ArrayList states = new ArrayList();
                        foreach (AState item in list)
                        {
                            states.Add(item.GetState());
                        }
                        m_Maze.m_Solution = m_Maze.printAfterSolution(states);

                        m_Status = string.Format("{0} result Finished...", p);
                        PrintEvent();
                        if (sol != null && sol.GetSolutionPath().Count > 0)
                        {
                            addSol(m_Maze, sol);
                        }
                    }
                }
                catch
                {
                    m_Status = "Cant Find Maze";
                    PrintEvent();
                }
            }
        }