Esempio n. 1
4
        private static void WriteDxfFile()
        {
            DxfDocument dxf = new DxfDocument();

            //arc
            Arc arc = new Arc(new Vector3(10, 10, 0), 10, 45, 135);
            arc.Layer = new Layer("arc");
            arc.Layer.Color.Index = 1;
            dxf.AddEntity(arc);

            //xData sample
            XData xdata = new XData(new ApplicationRegistry("netDxf"));
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.String, "extended data with netDxf"));
            xdata.XDataRecord.Add(XDataRecord.OpenControlString);
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionX, 0));
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionY, 0));
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionZ, 0));
            xdata.XDataRecord.Add(XDataRecord.CloseControlString);

            XData xdata2 = new XData(new ApplicationRegistry("other application"));
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.String, "extended data with netDxf"));
            xdata2.XDataRecord.Add(XDataRecord.OpenControlString);
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.String, "string record"));
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.Real, 15.5));
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.Int32, 350));
            xdata2.XDataRecord.Add(XDataRecord.CloseControlString);

            //circle
            Vector3 extrusion = new Vector3(1, 1, 1);
            Vector3 centerWCS = new Vector3(1, 1, 1);
            Vector3 centerOCS = MathHelper.Transform(centerWCS,
                                                        extrusion,
                                                        CoordinateSystem.World,
                                                        CoordinateSystem.Object);

            Circle circle = new Circle(centerOCS, 5);
            circle.Layer = new Layer("circle with spaces");
            circle.Layer.Color=AciColor.Yellow;
            circle.LineType = LineType.Dashed;
            circle.Normal = extrusion;
            circle.XData.Add(xdata);
            circle.XData.Add(xdata2);

            dxf.AddEntity(circle);

            //points
            Point point1 = new Point(new Vector3(-3, -3, 0));
            point1.Layer = new Layer("point");
            point1.Color = new AciColor(30);
            Point point2 = new Point(new Vector3(1, 1, 1));
            point2.Layer = point1.Layer;
            point2.Layer.Color.Index = 9;
            point2.Normal = new Vector3(1, 1, 1);
            dxf.AddEntity(point1);
            dxf.AddEntity(point2);

            //3dface
            Face3d face3D = new Face3d(new Vector3(-5, -5, 5),
                                        new Vector3(5, -5, 5),
                                        new Vector3(5, 5, 5),
                                        new Vector3(-5, 5, 5));
            face3D.Layer = new Layer("3dface");
            face3D.Layer.Color.Index = 3;
            dxf.AddEntity(face3D);
            
            //polyline
            LwPolylineVertex polyVertex;
            List<LwPolylineVertex> polyVertexes = new List<LwPolylineVertex>();
            polyVertex = new LwPolylineVertex(new Vector2(-50, -50));
            polyVertex.StartWidth = 2;
            polyVertexes.Add(polyVertex);
            polyVertex = new LwPolylineVertex(new Vector2(50, -50));
            polyVertex.StartWidth = 1;
            polyVertexes.Add(polyVertex);
            polyVertex = new LwPolylineVertex(new Vector2(50, 50));
            polyVertex.Bulge = 1;
            polyVertexes.Add(polyVertex);
            polyVertex = new LwPolylineVertex(new Vector2(-50, 50));
            polyVertexes.Add(polyVertex);
            LwPolyline polyline2d = new LwPolyline(polyVertexes, true);
            polyline2d.Layer = new Layer("polyline2d");
            polyline2d.Layer.Color.Index = 5;
            polyline2d.Normal = new Vector3(1, 1, 1);
            polyline2d.Elevation = 100.0f;
            dxf.AddEntity(polyline2d);

            //lightweight polyline
            LwPolylineVertex lwVertex;
            List<LwPolylineVertex> lwVertexes = new List<LwPolylineVertex>();
            lwVertex = new LwPolylineVertex(new Vector2(-25, -25));
            lwVertex.StartWidth = 2;
            lwVertexes.Add(lwVertex);
            lwVertex = new LwPolylineVertex(new Vector2(25, -25));
            lwVertex.StartWidth = 1;
            lwVertexes.Add(lwVertex);
            lwVertex = new LwPolylineVertex(new Vector2(25, 25));
            lwVertex.Bulge = 1;
            lwVertexes.Add(lwVertex);
            lwVertex = new LwPolylineVertex(new Vector2(-25, 25));
            lwVertexes.Add(lwVertex);
            LwPolyline lwPolyline = new LwPolyline(lwVertexes, true);
            lwPolyline.Layer = new Layer("lwpolyline");
            lwPolyline.Layer.Color.Index = 5;
            lwPolyline.Normal = new Vector3(1, 1, 1);
            lwPolyline.Elevation = 100.0f;
            dxf.AddEntity(lwPolyline);

            // polyfaceMesh
            List<PolyfaceMeshVertex> meshVertexes = new List<PolyfaceMeshVertex>
                                                    {
                                                        new PolyfaceMeshVertex(0, 0, 0),
                                                        new PolyfaceMeshVertex(10, 0, 0),
                                                        new PolyfaceMeshVertex(10, 10, 0),
                                                        new PolyfaceMeshVertex(5, 15, 0),
                                                        new PolyfaceMeshVertex(0, 10, 0)
                                                    };
            List<PolyfaceMeshFace> faces = new List<PolyfaceMeshFace>
                                                {
                                                    new PolyfaceMeshFace(new short[] {1, 2, -3}),
                                                    new PolyfaceMeshFace(new short[] {-1, 3, -4}),
                                                    new PolyfaceMeshFace(new short[] {-1, 4, 5})
                                                };

            PolyfaceMesh mesh = new PolyfaceMesh(meshVertexes, faces);
            mesh.Layer = new Layer("polyfacemesh");
            mesh.Layer.Color.Index = 104;
            dxf.AddEntity(mesh);

            //line
            Line line = new Line(new Vector3(0, 0, 0), new Vector3(10, 10, 10));
            line.Layer = new Layer("line");
            line.Layer.Color.Index = 6;
            dxf.AddEntity(line);

            //3d polyline
            PolylineVertex vertex;
            List<PolylineVertex> vertexes = new List<PolylineVertex>();
            vertex = new PolylineVertex(new Vector3(-50, -50, 0));
            vertexes.Add(vertex);
            vertex = new PolylineVertex(new Vector3(50, -50, 10));
            vertexes.Add(vertex);
            vertex = new PolylineVertex(new Vector3(50, 50, 25));
            vertexes.Add(vertex);
            vertex = new PolylineVertex(new Vector3(-50, 50, 50));
            vertexes.Add(vertex);
            Polyline polyline = new Polyline(vertexes, true);
            polyline.Layer = new Layer("polyline3d");
            polyline.Layer.Color.Index = 24;
            dxf.AddEntity(polyline);

            //block definition
            Block block = new Block("TestBlock");
            block.Entities.Add(new Line(new Vector3(-5, -5, 5), new Vector3(5, 5, 5)));
            block.Entities.Add(new Line(new Vector3(5, -5, 5), new Vector3(-5, 5, 5)));
           
            //insert
            Insert insert = new Insert(block, new Vector3(5, 5, 5));
            insert.Layer = new Layer("insert");
            insert.Layer.Color.Index = 4;
            dxf.AddEntity(insert);

            //text
            TextStyle style=new TextStyle("True type font","Arial.ttf");
            Text text = new Text("Hello world!", Vector3.Zero, 10.0f,style);
            text.Layer = new Layer("text");
            text.Layer.Color.Index = 8;
            text.Alignment = TextAlignment.TopRight;
            dxf.AddEntity(text);

            dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2010;
            dxf.Save("AutoCad2010.dxf");
            dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2007;
            dxf.Save("AutoCad2007.dxf");
            dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2004;
            dxf.Save("AutoCad2004.dxf");
            dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2000;
            dxf.Save("AutoCad2000.dxf");
            dxf = DxfDocument.Load("AutoCad2000.dxf");
            dxf.Save("AutoCad2000 result.dxf");
        }
Esempio n. 2
1
        private static void DimensionNestedBlock()
        {
            DxfDocument dxf = new DxfDocument();

            Vector3 p1 = new Vector3(0, 0, 0);
            Vector3 p2 = new Vector3(5, 5, 0);
            Line line = new Line(p1, p2);

            DimensionStyle myStyle = new DimensionStyle("MyStyle");
            myStyle.DIMPOST = "<>mm";
            myStyle.DIMDEC = 2;
            LinearDimension dim = new LinearDimension(line, 7, 0.0, myStyle);

            Block nestedBlock = new Block("NestedBlock");
            nestedBlock.Entities.Add(line);
            Insert nestedIns = new Insert(nestedBlock);

            Block block = new Block("MyBlock");
            block.Entities.Add(dim);
            block.Entities.Add(nestedIns);

            Insert ins = new Insert(block);
            ins.Position = new Vector3(10, 10, 0);
            dxf.AddEntity(ins);

            Circle circle = new Circle(p2, 5);
            Block block2 = new Block("MyBlock2");
            block2.Entities.Add(circle);

            Insert ins2 = new Insert(block2);
            ins2.Position = new Vector3(-10, -10, 0);
            dxf.AddEntity(ins2);

            Block block3 = new Block("MyBlock3");
            block3.Entities.Add((EntityObject)ins.Clone());
            block3.Entities.Add((EntityObject)ins2.Clone());

            Insert ins3 = new Insert(block3);
            ins3.Position = new Vector3(-10, 10, 0);
            dxf.AddEntity(ins3);

            dxf.Save("nested blocks.dxf");

            dxf = DxfDocument.Load("nested blocks.dxf");

            dxf.Save("nested blocks.dxf");
        }
Esempio n. 3
0
        void ReadInsert(netDxf.Entities.Insert insert)
        {
            List <netDxf.Entities.IEntityObject> entities = insert.Block.Entities;

            netDxf.Entities.IEntityObject entity = null;

            for (int index = 1; index < entities.Count; index++)
            {
                entity = entities[index];

                if (entity is Line)
                {
                    ReadLine((Line)entity, insert.InsertionPoint.X, insert.InsertionPoint.Y);
                }
                else if (entity is netDxf.Entities.Arc)
                {
                    ReadArc((netDxf.Entities.Arc)entity, insert.InsertionPoint.X, insert.InsertionPoint.Y);
                }
                else if (entity is netDxf.Entities.Circle)
                {
                    ReadCircle((netDxf.Entities.Circle)entity, insert.InsertionPoint.X, insert.InsertionPoint.Y);
                }
                else if (entity is IPolyline)
                {
                    netDxf.Entities.Polyline polyline = CastPolyline((IPolyline)entity);
                    if (polyline != null)
                    {
                        ReadPolyline(polyline.Vertexes, polyline.IsClosed, 0, 0);
                    }
                }
            }
        }
Esempio n. 4
0
		/*Draw Leader*/
		public static void DrawLeader(Leader xLeader, Canvas mainCanvas)
		{
			Size txtSize = new Size(0, 0);
			/*ajout du texte*/
			if (xLeader.Annotation.Type == EntityType.MText) {
				netDxf.Entities.MText mText = (netDxf.Entities.MText)xLeader.Annotation;
				txtSize = DrawMText(mText, mainCanvas);
			}
			
			if (xLeader.Annotation.Type == EntityType.Text) {
				netDxf.Entities.Text mText = (netDxf.Entities.Text)xLeader.Annotation;
				DrawText(mText, mainCanvas);
			}
			if (xLeader.Annotation.Type == EntityType.Insert) {
				netDxf.Entities.Insert mText = (netDxf.Entities.Insert)xLeader.Annotation;
				DrawInsert(mText, mainCanvas);
			}
			
			
			
			
			
			System.Windows.Shapes.Polyline wPoly = new System.Windows.Shapes.Polyline();
			
			foreach (netDxf.Vector2 xVertex in xLeader.Vertexes) {
				System.Windows.Point myPt = TypeConverter.Vertex2ToPoint(xVertex);
				myPt.Y = mainCanvas.Height - myPt.Y;
				wPoly.Points.Add(myPt);
			}
			System.Windows.Point myPt2 = TypeConverter.Vertex2ToPoint(xLeader.Hook);
			myPt2.Y = mainCanvas.Height - myPt2.Y;
			wPoly.Points.Add(myPt2);
			
			if (txtSize.Width > 0) {
				myPt2.X = myPt2.X + txtSize.Width;
				wPoly.Points.Add(myPt2);
			}
			
			xLeader.Lineweight = Lineweight.W0;
			
			TypeConverter.Entity2Shape(xLeader, wPoly);
			
			if (xLeader.ShowArrowhead == true) {
				System.Windows.Shapes.Polygon arrow = DrawUtils.GetArrowhead(xLeader.Vertexes[0], xLeader.Vertexes[1], mainCanvas);
				TypeConverter.Entity2Shape(xLeader, arrow);
				arrow.StrokeThickness = 0.1;
				arrow.Fill = arrow.Stroke;
				mainCanvas.Children.Add(arrow);
			}
			
			mainCanvas.Children.Add(wPoly);
			
			

			

		}
Esempio n. 5
0
        void ReadEntities()
        {
            foreach (IEntityObject aEntity in doc.Entities)
            {
                switch (aEntity.Type)
                {
                case EntityType.Arc:
                    ReadArc(aEntity as netDxf.Entities.Arc, 0, 0);
                    (drawing.Figures[drawing.Figures.Count - 1] as FigureBase).Tag = aEntity;
                    break;

                case EntityType.Circle:
                    ReadCircle(aEntity as netDxf.Entities.Circle, 0, 0);
                    (drawing.Figures[drawing.Figures.Count - 1] as FigureBase).Tag = aEntity;
                    break;

                //case EntityType.Ellipse:
                //    ReadEllipse(aEntity as netDxf.Entities.Ellipse, 0, 0);
                //    break;
                case EntityType.Line:
                    ReadLine(aEntity as netDxf.Entities.Line, 0, 0);
                    (drawing.Figures[drawing.Figures.Count - 1] as FigureBase).Tag = aEntity;
                    break;

                case EntityType.Polyline:
                    netDxf.Entities.Polyline polyline = CastPolyline(aEntity);
                    if (polyline != null)
                    {
                        ReadPolyline(polyline.Vertexes, polyline.IsClosed, 0, 0);
                    }
                    (drawing.Figures[drawing.Figures.Count - 1] as FigureBase).Tag = aEntity;
                    break;

                case EntityType.Insert:
                    netDxf.Entities.Insert insert = aEntity as netDxf.Entities.Insert;
                    foreach (netDxf.Entities.Line aLine in insert.Block.Entities)
                    {
                        ReadLine(aLine, insert.InsertionPoint.X, insert.InsertionPoint.Y);
                        (drawing.Figures[drawing.Figures.Count - 1] as FigureBase).Tag = aLine;
                    }
                    break;

                default:
                    break;
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Creates a new Insert that is a copy of the current instance.
        /// </summary>
        /// <returns>A new Insert that is a copy of this instance.</returns>
        public override object Clone()
        {
            // copy attributes
            List <Attribute> copyAttributes = new List <Attribute>();

            foreach (Attribute att in this.attributes)
            {
                copyAttributes.Add((Attribute)att.Clone());
            }

            Insert entity = new Insert(copyAttributes)
            {
                //EntityObject properties
                Layer         = (Layer)this.Layer.Clone(),
                Linetype      = (Linetype)this.Linetype.Clone(),
                Color         = (AciColor)this.Color.Clone(),
                Lineweight    = this.Lineweight,
                Transparency  = (Transparency)this.Transparency.Clone(),
                LinetypeScale = this.LinetypeScale,
                Normal        = this.Normal,
                IsVisible     = this.IsVisible,
                //Insert properties
                Position = this.position,
                Block    = (Block)this.block.Clone(),
                Scale    = this.scale,
                Rotation = this.rotation,
            };

            // copy extended data
            foreach (XData data in this.XData.Values)
            {
                entity.XData.Add((XData)data.Clone());
            }

            return(entity);
        }
Esempio n. 7
0
        private static void BlockAttributes()
        {
            DxfDocument dxf = new DxfDocument( );
            Block block = new Block("BlockWithAttributes");
            block.Layer = new Layer("BlockSample");

            AttributeDefinition attdef = new AttributeDefinition("NewAttribute");
            attdef.Text = "InfoText";
            attdef.BasePoint = new Vector3d(1, 1, 1);
            attdef.Style.IsVertical = true;
            attdef.Rotation = 45;

            block.Attributes.Add(attdef.Id, attdef);
            block.Entities.Add(new Line(new Vector3d(-5, -5, 0), new Vector3d(5, 5, 0)));
            block.Entities.Add(new Line(new Vector3d(5, -5, 0), new Vector3d(-5, 5, 0)));

            Insert insert = new Insert(block, new Vector3d(5, 5, 5));
            insert.Layer = new Layer("insert");
            insert.Rotation = 45;
            insert.Layer.Color.Index = 4;
            insert.Attributes[0].Value = 24;

            Insert insert2 = new Insert(block, new Vector3d(-5, -5, -5));
            insert2.Attributes[0].Value = 34;

            XData xdata1 = new XData(new ApplicationRegistry("netDxf"));
            xdata1.XDataRecord.Add(new XDataRecord(XDataCode.String, "extended data with netDxf"));
            xdata1.XDataRecord.Add(XDataRecord.OpenControlString);
            xdata1.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionX, 0));
            xdata1.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionY, 0));
            xdata1.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionZ, 0));
            xdata1.XDataRecord.Add(XDataRecord.CloseControlString);

            XData xdata2 = new XData(new ApplicationRegistry("other application"));
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.String, "extended data with netDxf"));
            xdata2.XDataRecord.Add(XDataRecord.OpenControlString);
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.String, "string record"));
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.Real, 15.5));
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.Long, 350));
            xdata2.XDataRecord.Add(XDataRecord.CloseControlString);

            insert.XData = new Dictionary<ApplicationRegistry, XData>
                             {
                                 {xdata1.ApplicationRegistry, xdata1},
                             };
            dxf.AddEntity(insert);
            dxf.AddEntity(insert2);

            Circle circle = new Circle(Vector3d.Zero, 5);
            circle.Layer = new Layer("circle");
            circle.Layer.Color.Index = 2;
            circle.XData = new Dictionary<ApplicationRegistry, XData>
                             {
                                 {xdata2.ApplicationRegistry, xdata2},
                             };
            dxf.AddEntity(circle);

            dxf.Save("Block with attributes.dxf", DxfVersion.AutoCad2000);
            dxf.Load("Block with attributes.dxf");
            dxf.Save("Block with attributes result.dxf", DxfVersion.AutoCad2000); // both results must be equal only the handles might be different
        }
        private void WriteInsert(Insert insert)
        {
            this.chunk.Write(100, SubclassMarker.Insert);

            this.chunk.Write(2, this.EncodeNonAsciiCharacters(insert.Block.Name));

            // It is a lot more intuitive to give the center in world coordinates and then define the orientation with the normal.
            Vector3 ocsInsertion = MathHelper.Transform(insert.Position, insert.Normal, CoordinateSystem.World, CoordinateSystem.Object);

            this.chunk.Write(10, ocsInsertion.X);
            this.chunk.Write(20, ocsInsertion.Y);
            this.chunk.Write(30, ocsInsertion.Z);

            // we need to apply the scaling factor between the block and the document or the block that owns it in case of nested blocks
            double scale = UnitHelper.ConversionFactor(insert.Block.Record.Units, insert.Owner.Record.IsForInternalUseOnly ? this.doc.DrawingVariables.InsUnits : insert.Owner.Record.Units);

            this.chunk.Write(41, insert.Scale.X*scale);
            this.chunk.Write(42, insert.Scale.Y*scale);
            this.chunk.Write(43, insert.Scale.Z*scale);

            this.chunk.Write(50, insert.Rotation);

            this.chunk.Write(210, insert.Normal.X);
            this.chunk.Write(220, insert.Normal.Y);
            this.chunk.Write(230, insert.Normal.Z);

            if (insert.Attributes.Count > 0)
            {
                //Obsolete; formerly an entities follow flag (optional; ignore if present)
                //AutoCAD will fail loading the file if it is not there, more dxf voodoo
                this.chunk.Write(66, (short) 1);

                this.WriteXData(insert.XData);

                foreach (Attribute attrib in insert.Attributes)
                    this.WriteAttribute(attrib);

                this.chunk.Write(0, insert.EndSequence.CodeName);
                this.chunk.Write(5, insert.EndSequence.Handle);
                this.chunk.Write(100, SubclassMarker.Entity);
                this.chunk.Write(8, this.EncodeNonAsciiCharacters(insert.Layer.Name));
            }
            else
            {
                this.WriteXData(insert.XData);
            }
        }
Esempio n. 9
0
        private Insert ReadInsert(ref CodeValuePair code)
        {
            string handle = string.Empty;
            Vector3d basePoint = Vector3d.Zero;
            Vector3d normal = Vector3d.UnitZ;
            Vector3d scale = new Vector3d(1, 1, 1);
            float rotation = 0.0f;
            Block block = null;
            Layer layer = Layer.Default;
            AciColor color = AciColor.ByLayer;
            LineType lineType = LineType.ByLayer;
            List<Attribute> attributes = new List<Attribute>();
            Dictionary<ApplicationRegistry, XData> xData = new Dictionary<ApplicationRegistry, XData>();

            code = this.ReadCodePair();
            while (code.Code != 0)
            {
                switch (code.Code)
                {
                    case 5:
                        handle = code.Value;
                        code = this.ReadCodePair();
                        break;
                    case 2:
                        block = this.GetBlock(code.Value);
                        if (block == null)
                            throw new DxfEntityException(DxfObjectCode.Insert, this.file, "Block " + code.Value + " not defined line " + this.fileLine);
                        code = this.ReadCodePair();
                        break;
                    case 8: //layer code
                        layer = this.GetLayer(code.Value);
                        code = this.ReadCodePair();
                        break;
                    case 62: //aci color code
                        color = new AciColor(short.Parse(code.Value));
                        code = this.ReadCodePair();
                        break;
                    case 6: //type line code
                        lineType = this.GetLineType(code.Value);
                        code = this.ReadCodePair();
                        break;
                    case 10:
                        basePoint.X = double.Parse(code.Value);
                        code = this.ReadCodePair();
                        break;
                    case 20:
                        basePoint.Y = double.Parse(code.Value);
                        code = this.ReadCodePair();
                        break;
                    case 30:
                        basePoint.Z = double.Parse(code.Value);
                        code = this.ReadCodePair();
                        break;
                    case 41:
                        scale.X = double.Parse(code.Value);
                        code = this.ReadCodePair();
                        break;
                    case 42:
                        scale.X = double.Parse(code.Value);
                        code = this.ReadCodePair();
                        break;
                    case 43:
                        scale.X = double.Parse(code.Value);
                        code = this.ReadCodePair();
                        break;
                    case 50:
                        rotation = float.Parse(code.Value);
                        code = this.ReadCodePair();
                        break;
                    case 210:
                        normal.X = double.Parse(code.Value);
                        code = this.ReadCodePair();
                        break;
                    case 220:
                        normal.Y = double.Parse(code.Value);
                        code = this.ReadCodePair();
                        break;
                    case 230:
                        normal.Z = double.Parse(code.Value);
                        code = this.ReadCodePair();
                        break;
                    case 1001:
                        XData xDataItem = this.ReadXDataRecord(code.Value, ref code);
                        xData.Add(xDataItem.ApplicationRegistry, xDataItem);
                        break;
                    default:
                        if (code.Code >= 1000 && code.Code <= 1071)
                            throw new DxfInvalidCodeValueEntityException(code.Code, code.Value, this.file,
                                                                         "The extended data of an entity must start with the application registry code " + this.fileLine);

                        code = this.ReadCodePair();
                        break;
                }
            }

            // if there are attributes
            string endSequenceHandle = string.Empty;
            Layer endSequenceLayer = Layer.Default;
            if (code.Value == DxfObjectCode.Attribute)
            {
                while (code.Value != StringCode.EndSequence)
                {
                    if (code.Value == DxfObjectCode.Attribute)
                    {
                        Debug.Assert(code.Code == 0);
                        Attribute attribute = this.ReadAttribute(block, ref code);
                        attributes.Add(attribute);
                    }
                }
                // read the end end sequence object until a new element is found
                code = this.ReadCodePair();
                while (code.Code != 0)
                {
                    switch (code.Code)
                    {
                        case 5:
                            endSequenceHandle = code.Value;
                            code = this.ReadCodePair();
                            break;
                        case 8:
                            endSequenceLayer = this.GetLayer(code.Value);
                            code = this.ReadCodePair();
                            break;
                        default:
                            code = this.ReadCodePair();
                            break;
                    }
                }
            }

            Insert insert = new Insert(block)
                                {
                                    Color = color,
                                    Layer = layer,
                                    LineType = lineType,
                                    InsertionPoint = basePoint,
                                    Rotation = rotation,
                                    Scale = scale,
                                    Normal = normal,
                                    Handle = handle
                                };

            insert.EndSequence.Handle = endSequenceHandle;
            insert.EndSequence.Layer = endSequenceLayer;
            insert.Attributes.Clear();
            insert.Attributes.AddRange(attributes);
            insert.XData = xData;

            return insert;
        }
Esempio n. 10
0
        private static EntityObject EndArrowHead(Vector2 position, double rotation, DimensionStyle style)
        {
            Block block = style.DimArrow2;

            if (block == null)
            {
                Vector2 arrowRef = Vector2.Polar(position, -style.ArrowSize*style.DimScaleOverall, rotation);
                Solid arrow = new Solid(position,
                    Vector2.Polar(arrowRef, -(style.ArrowSize/6)*style.DimScaleOverall, rotation + MathHelper.HalfPI),
                    Vector2.Polar(arrowRef, (style.ArrowSize/6)*style.DimScaleOverall, rotation + MathHelper.HalfPI))
                {
                    Color = style.DimLineColor
                };
                return arrow;
            }
            else
            {
                Insert arrow = new Insert(block, position)
                {
                    Color = style.DimLineColor,
                    Scale = new Vector3(style.ArrowSize*style.DimScaleOverall),
                    Rotation = rotation*MathHelper.RadToDeg,
                    Lineweight = style.DimLineLineweight
                };
                return arrow;
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Updates the leader hook (last leader vertex) according to the actual annotation position.
        /// </summary>
        /// <remarks>
        /// This method should be manually called if the annotation position is modified, or the leader properties like Style, Annotation, TextVerticalPosition, and/or Offset.
        /// </remarks>
        public void Update()
        {
            if (this.vertexes.Count < 2)
            {
                throw new Exception("The leader vertexes list requires at least two points.");
            }

            if (this.annotation == null)
            {
                return;
            }

            Vector3 ocsHook;

            switch (this.annotation.Type)
            {
            case EntityType.MText:
                MText mText = (MText)this.annotation;
                ocsHook = MathHelper.Transform(mText.Position, this.normal, CoordinateSystem.World, CoordinateSystem.Object);
                int mTextSide = Math.Sign(ocsHook.X - this.vertexes[this.vertexes.Count - 2].X);

                if (this.TextVerticalPosition == LeaderTextVerticalPosition.Centered)
                {
                    if (mTextSide < 0 && mText.AttachmentPoint == MTextAttachmentPoint.TopLeft)
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.TopRight;
                    }
                    else if (mTextSide > 0 && mText.AttachmentPoint == MTextAttachmentPoint.TopRight)
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.TopLeft;
                    }
                    else if (mTextSide < 0 && mText.AttachmentPoint == MTextAttachmentPoint.MiddleLeft)
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.MiddleRight;
                    }
                    else if (mTextSide > 0 && mText.AttachmentPoint == MTextAttachmentPoint.MiddleRight)
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.MiddleLeft;
                    }
                    else if (mTextSide < 0 && mText.AttachmentPoint == MTextAttachmentPoint.BottomLeft)
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.BottomRight;
                    }
                    else if (mTextSide > 0 && mText.AttachmentPoint == MTextAttachmentPoint.BottomRight)
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.BottomLeft;
                    }

                    double xOffset = 0.0;
                    switch (mText.AttachmentPoint)
                    {
                    case MTextAttachmentPoint.TopLeft:
                    case MTextAttachmentPoint.MiddleLeft:
                    case MTextAttachmentPoint.BottomLeft:
                        xOffset = -this.style.DIMGAP * this.style.DIMSCALE;
                        break;

                    case MTextAttachmentPoint.TopCenter:
                    case MTextAttachmentPoint.MiddleCenter:
                    case MTextAttachmentPoint.BottomCenter:
                        xOffset = 0.0;
                        break;

                    case MTextAttachmentPoint.TopRight:
                    case MTextAttachmentPoint.MiddleRight:
                    case MTextAttachmentPoint.BottomRight:
                        xOffset = this.style.DIMGAP * this.style.DIMSCALE;
                        break;
                    }
                    this.vertexes[this.vertexes.Count - 1] = new Vector2(ocsHook.X + xOffset, ocsHook.Y) + this.offset;
                }
                else
                {
                    ocsHook -= new Vector3(mTextSide * this.style.DIMGAP * this.style.DIMSCALE, this.style.DIMGAP * this.style.DIMSCALE, 0.0);
                    mText.AttachmentPoint = mTextSide >= 0 ? MTextAttachmentPoint.BottomLeft : MTextAttachmentPoint.BottomRight;
                    this.vertexes[this.vertexes.Count - 1] = new Vector2(ocsHook.X, ocsHook.Y) + this.offset;
                }
                mText.Height     = this.style.DIMTXT * this.style.DIMSCALE;
                mText.Color      = this.style.DIMCLRT.IsByBlock ? AciColor.ByLayer : this.style.DIMCLRT;
                this.hasHookline = true;
                break;

            case EntityType.Insert:
                Insert ins = (Insert)this.annotation;
                ocsHook = MathHelper.Transform(ins.Position, this.normal, CoordinateSystem.World, CoordinateSystem.Object);
                this.vertexes[this.vertexes.Count - 1] = new Vector2(ocsHook.X, ocsHook.Y) + this.offset;
                ins.Color        = this.style.DIMCLRT.IsByBlock ? AciColor.ByLayer : this.style.DIMCLRT;
                this.hasHookline = false;
                break;

            case EntityType.Tolerance:
                Tolerance tol = (Tolerance)this.annotation;
                ocsHook = MathHelper.Transform(tol.Position, this.normal, CoordinateSystem.World, CoordinateSystem.Object);
                this.vertexes[this.vertexes.Count - 1] = new Vector2(ocsHook.X, ocsHook.Y) + this.offset;
                tol.Color        = this.style.DIMCLRT.IsByBlock ? AciColor.ByLayer : this.style.DIMCLRT;
                this.hasHookline = false;
                break;

            case EntityType.Text:
                Text text = (Text)this.annotation;
                ocsHook = MathHelper.Transform(text.Position, this.normal, CoordinateSystem.World, CoordinateSystem.Object);
                int textSide = Math.Sign(ocsHook.X - this.vertexes[this.vertexes.Count - 2].X);
                ocsHook       -= new Vector3(textSide * this.style.DIMGAP * this.style.DIMSCALE, this.style.DIMGAP * this.style.DIMSCALE, 0.0);
                text.Alignment = textSide >= 0 ? TextAlignment.BottomLeft : TextAlignment.BottomRight;
                text.Height    = this.style.DIMTXT * this.style.DIMSCALE;
                text.Color     = this.style.DIMCLRT.IsByBlock ? AciColor.ByLayer : this.style.DIMCLRT;
                this.vertexes[this.vertexes.Count - 1] = new Vector2(ocsHook.X, ocsHook.Y) + this.offset;
                this.hasHookline = true;
                break;

            default:
                throw new Exception(string.Format("The entity type: {0} not supported as a leader annotation.", this.annotation.Type));
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Resets the leader hook position according to the annotation position.
        /// </summary>
        private void ResetHookPosition()
        {
            if (vertexes.Count < 2)
            {
                throw new Exception("The leader vertexes list requires at least two points.");
            }

            if (annotation == null)
            {
                return;
            }

            DimensionStyleOverride styleOverride;
            DimensionStyleTextVerticalPlacement textVerticalPlacement = Style.TextVerticalPlacement;

            if (StyleOverrides.TryGetValue(DimensionStyleOverrideType.TextVerticalPlacement, out styleOverride))
            {
                textVerticalPlacement = (DimensionStyleTextVerticalPlacement)styleOverride.Value;
            }
            double textOffset = Style.TextOffset;

            if (StyleOverrides.TryGetValue(DimensionStyleOverrideType.TextOffset, out styleOverride))
            {
                textOffset = (double)styleOverride.Value;
            }
            double dimScale = Style.DimScaleOverall;

            if (StyleOverrides.TryGetValue(DimensionStyleOverrideType.DimScaleOverall, out styleOverride))
            {
                dimScale = (double)styleOverride.Value;
            }
            double textHeight = Style.TextHeight;

            if (StyleOverrides.TryGetValue(DimensionStyleOverrideType.TextHeight, out styleOverride))
            {
                textHeight = (double)styleOverride.Value;
            }
            AciColor textColor = Style.TextColor;

            if (StyleOverrides.TryGetValue(DimensionStyleOverrideType.TextColor, out styleOverride))
            {
                textColor = (AciColor)styleOverride.Value;
            }

            Vector3 ocsHook;

            switch (annotation.Type)
            {
            case EntityType.MText:
                MText mText = (MText)annotation;
                ocsHook = MathHelper.Transform(mText.Position, Normal, CoordinateSystem.World, CoordinateSystem.Object);
                int mTextSide = Math.Sign(ocsHook.X - vertexes[vertexes.Count - 2].X);

                if (textVerticalPlacement == DimensionStyleTextVerticalPlacement.Centered)
                {
                    double xOffset;

                    if (mTextSide >= 0)
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.MiddleLeft;
                        xOffset = -textOffset * dimScale;
                    }
                    else
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.MiddleRight;
                        xOffset = textOffset * dimScale;
                    }
                    vertexes[vertexes.Count - 1] = new Vector2(ocsHook.X + xOffset, ocsHook.Y) - offset;
                }
                else
                {
                    ocsHook -= new Vector3(mTextSide * textOffset * dimScale, textOffset * dimScale, 0.0);
                    mText.AttachmentPoint        = mTextSide >= 0 ? MTextAttachmentPoint.BottomLeft : MTextAttachmentPoint.BottomRight;
                    vertexes[vertexes.Count - 1] = new Vector2(ocsHook.X, ocsHook.Y) - offset;
                }
                mText.Height = textHeight * dimScale;
                mText.Color  = textColor.IsByBlock ? AciColor.ByLayer : textColor;
                break;

            case EntityType.Insert:
                Insert ins = (Insert)annotation;
                ocsHook = MathHelper.Transform(ins.Position, Normal, CoordinateSystem.World, CoordinateSystem.Object);
                vertexes[vertexes.Count - 1] = new Vector2(ocsHook.X, ocsHook.Y) - offset;
                ins.Color = textColor.IsByBlock ? AciColor.ByLayer : textColor;
                break;

            case EntityType.Tolerance:
                Tolerance tol = (Tolerance)annotation;
                ocsHook = MathHelper.Transform(tol.Position, Normal, CoordinateSystem.World, CoordinateSystem.Object);
                vertexes[vertexes.Count - 1] = new Vector2(ocsHook.X, ocsHook.Y) - offset;
                tol.Color = textColor.IsByBlock ? AciColor.ByLayer : textColor;
                break;

            case EntityType.Text:
                Text text = (Text)annotation;
                ocsHook = MathHelper.Transform(text.Position, Normal, CoordinateSystem.World, CoordinateSystem.Object);
                int textSide = Math.Sign(ocsHook.X - vertexes[vertexes.Count - 2].X);
                if (textVerticalPlacement == DimensionStyleTextVerticalPlacement.Centered)
                {
                    double xOffset;

                    if (textSide >= 0)
                    {
                        text.Alignment = TextAlignment.MiddleLeft;
                        xOffset        = -textOffset * dimScale;
                    }
                    else
                    {
                        text.Alignment = TextAlignment.MiddleRight;
                        xOffset        = textOffset * dimScale;
                    }
                    vertexes[vertexes.Count - 1] = new Vector2(ocsHook.X + xOffset, ocsHook.Y) - offset;
                }
                else
                {
                    ocsHook       -= new Vector3(textSide * textOffset * dimScale, textOffset * dimScale, 0.0);
                    text.Alignment = textSide >= 0 ? TextAlignment.BottomLeft : TextAlignment.BottomRight;
                    vertexes[vertexes.Count - 1] = new Vector2(ocsHook.X, ocsHook.Y) - offset;
                }
                text.Height = textHeight * dimScale;
                text.Color  = textColor.IsByBlock ? AciColor.ByLayer : textColor;
                break;

            default:
                throw new Exception(string.Format("The entity type: {0} not supported as a leader annotation.", annotation.Type));
            }
        }
Esempio n. 13
0
        private void Insert_AttributeAdded(Insert sender, AttributeChangeEventArgs e)
        {
            this.NumHandles = e.Item.AsignHandle(this.NumHandles);

            e.Item.Layer = this.layers.Add(e.Item.Layer);
            this.layers.References[e.Item.Layer.Name].Add(e.Item);
            e.Item.LayerChanged += this.Entity_LayerChanged;

            e.Item.Linetype = this.linetypes.Add(e.Item.Linetype);
            this.linetypes.References[e.Item.Linetype.Name].Add(e.Item);
            e.Item.LinetypeChanged -= this.Entity_LinetypeChanged;

            e.Item.Style = this.textStyles.Add(e.Item.Style);
            this.textStyles.References[e.Item.Style.Name].Add(e.Item);
            e.Item.TextStyleChanged += this.Entity_TextStyleChanged;
        }
Esempio n. 14
0
        private static void Angular2LineDimensionDrawing()
        {
            double offset = 7.5;
            
            Line line1 = new Line(new Vector2(1, 2), new Vector2(6, 0));
            Line line2 = new Line(new Vector2(2, 1), new Vector2(4,5));

            Angular2LineDimension dim = new Angular2LineDimension(line1, line2, offset);
            
            DxfDocument dxf = new DxfDocument();
            //dxf.AddEntity(line1);
            //dxf.AddEntity(line2);
            //dxf.AddEntity(dim);

            Block block = new Block("DimensionBlock");
            block.Entities.Add(line1);
            block.Entities.Add(line2);
            block.Entities.Add(dim);
            Insert insert = new Insert(block);

            dxf.AddEntity(insert);

            dxf.Save("angular 2 line dimension.dxf");
            dxf = DxfDocument.Load("angular 2 line dimension.dxf");
            dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2010;
            dxf.Save("angular 2 line dimension.dxf");
        }
Esempio n. 15
0
        private static void AlignedDimensionDrawing()
        {
            DxfDocument dxf = new DxfDocument();
            double offset = -0.9;
            Vector3 p1 = new Vector3(1, 2, 0);
            Vector3 p2 = new Vector3(2, 6, 0);
            Line line1 = new Line(p1, p2);
            Vector3 l1;
            Vector3 l2;
            MathHelper.OffsetLine(line1.StartPoint, line1.EndPoint, line1.Normal, offset, out l1, out l2);

            DimensionStyle myStyle = new DimensionStyle("MyStyle");
            myStyle.DIMPOST = "<>mm";
            AlignedDimension dim1 = new AlignedDimension(p1, p2, offset, myStyle);

            Vector3 p3 = p1 + new Vector3(4, 0, 0);
            Vector3 p4 = p2 + new Vector3(4, 0, 0);
            Line line2 = new Line(p3, p4);
            AlignedDimension dim2 = new AlignedDimension(p3, p4, -offset, myStyle);


            Vector2 perp = Vector2.Perpendicular(new Vector2(p2.X, p2.Y) - new Vector2(p1.X, p1.Y));
            //dim.Normal = -new Vector3(perp.X, perp.Y, 0.0) ;

            XData xdata = new XData(new ApplicationRegistry("other application"));
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.String, "extended data with netDxf"));
            xdata.XDataRecord.Add(XDataRecord.OpenControlString);
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.String, "Aligned Dimension"));
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.Real, 15.5));
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.Int32, 350));
            xdata.XDataRecord.Add(XDataRecord.CloseControlString);
            dim1.XData.Add(xdata);

            //dxf.AddEntity(line1);
            //dxf.AddEntity(line2);
            //dxf.AddEntity(dim1);
            //dxf.AddEntity(dim2);



            Block block = new Block("DimensionBlock");
            block.Entities.Add(line1);
            block.Entities.Add(line2);
            block.Entities.Add(dim1);
            block.Entities.Add(dim2);
            Insert insert = new Insert(block);
            dxf.AddEntity(insert);

            dxf.Save("aligned dimension.dxf");

            dxf = DxfDocument.Load("aligned dimension.dxf");

        }
Esempio n. 16
0
        private static void WriteInsert()
        {
            // nested blocks
            DxfDocument dxf = new DxfDocument();

            Block nestedBlock = new Block("Nested block");
            nestedBlock.Entities.Add(new Line(new Vector3(-5, -5, 0), new Vector3(5, 5, 0)));
            nestedBlock.Entities.Add(new Line(new Vector3(5, -5, 0), new Vector3(-5, 5, 0)));

            Insert nestedInsert = new Insert(nestedBlock, new Vector3(0, 0, 0)); // the position will be relative to the position of the insert that nest it

            Circle circle = new Circle(Vector3.Zero, 5);
            circle.Layer = new Layer("circle");
            circle.Layer.Color.Index = 2;
            Block block = new Block("MyBlock");
            block.Entities.Add(circle);
            block.Entities.Add(nestedInsert);

            Insert insert = new Insert(block, new Vector3(5, 5, 5));
            insert.Layer = new Layer("insert");

            dxf.AddEntity(insert);

            dxf.Save("insert.dxf");
            dxf = DxfDocument.Load("insert.dxf");

        }
Esempio n. 17
0
        private static void WriteImage()
        {
            ImageDefinition imageDefinition = new ImageDefinition("img\\image01.jpg");
            Image image = new Image(imageDefinition, Vector3.Zero, 10, 10);

            XData xdata1 = new XData(new ApplicationRegistry("netDxf"));
            xdata1.XDataRecord.Add(new XDataRecord(XDataCode.String, "xData image position"));
            xdata1.XDataRecord.Add(XDataRecord.OpenControlString);
            xdata1.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionX, image.Position.X));
            xdata1.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionY, image.Position.Y));
            xdata1.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionZ, image.Position.Z));
            xdata1.XDataRecord.Add(XDataRecord.CloseControlString);
            image.XData.Add(xdata1);

            //image.Normal = new Vector3(1, 1, 1);
            //image.Rotation = 30;

            // you can pass a name that must be unique for the image definiton, by default it will use the file name without the extension
            ImageDefinition imageDef2 = new ImageDefinition("img\\image02.jpg", "MyImage");
            Image image2 = new Image(imageDef2, new Vector3(0, 150, 0), 10, 10);
            Image image3 = new Image(imageDef2, new Vector3(150, 150, 0), 10, 10);

            // clipping boundary definition in local coordinates
            ClippingBoundary clip = new ClippingBoundary(100, 100, 500, 300);
            image.ClippingBoundary = clip;
            // set to null to restore the default clipping boundary (full image)
            image.ClippingBoundary = null;

            // images can be part of a block definition
            Block block = new Block("ImageBlock");
            block.Entities.Add(image2);
            block.Entities.Add(image3);
            Insert insert = new Insert(block, new Vector3(0, 100, 0));

            DxfDocument dxf = new DxfDocument();

            dxf.AddEntity(image);
            //dxf.AddEntity(image2);
            //dxf.AddEntity(image3);
            dxf.AddEntity(insert);

            dxf.Save("image.dxf");
            dxf = DxfDocument.Load("image.dxf");
            dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2010;
            dxf.Save("test.dxf");

            //dxf.RemoveEntity(image2);
            //dxf.Save("image2.dxf");
            //dxf.RemoveEntity(image3);
            //dxf.RemoveEntity(image);
            //dxf.Save("image3.dxf");

        }
Esempio n. 18
0
        private static void TextAndDimensionStyleUsesAndRemove()
        {
            DxfDocument dxf = new DxfDocument();

            Layer layer1 = new Layer("Layer1");
            layer1.Color = AciColor.Blue;
            layer1.LineType = LineType.Center;

            Layer layer2 = new Layer("Layer2");
            layer2.Color = AciColor.Red;

            // blocks needs an special attention
            Layer layer3 = new Layer("Layer3");
            layer3.Color = AciColor.Yellow;

            Circle circle = new Circle(Vector3.Zero, 15);
            // it is always recommended that all block entities will be located in layer 0, but this is up to the user.
            circle.Layer = new Layer("circle");
            circle.Layer.Color = AciColor.Green;

            Block block = new Block("MyBlock");
            block.Entities.Add(circle);
            AttributeDefinition attdef = new AttributeDefinition("NewAttribute");

            block.AttributeDefinitions.Add(attdef);

            Insert insert = new Insert(block, new Vector2(5, 5));
            insert.Attributes[0].Style = new TextStyle("Arial.ttf");

            dxf.AddEntity(insert);

            dxf.Save("style.dxf");
            DxfDocument dxf2;
            dxf2 = DxfDocument.Load("style.dxf");

            dxf.RemoveEntity(circle);

            Vector3 p1 = new Vector3(0, 0, 0);
            Vector3 p2 = new Vector3(5, 5, 0);
            Line line = new Line(p1, p2);

            dxf.AddEntity(line);

            DimensionStyle myStyle = new DimensionStyle("MyStyle");
            myStyle.DIMTXSTY = new TextStyle("Tahoma.ttf");
            myStyle.DIMPOST = "<>mm";
            myStyle.DIMDEC = 2;
            double offset = 7;
            LinearDimension dimX = new LinearDimension(line, offset, 0.0, myStyle);
            dimX.Rotation += 30.0;
            LinearDimension dimY = new LinearDimension(line, offset, 90.0, myStyle);
            dimY.Rotation += 30.0;

            dxf.AddEntity(dimX);
            dxf.AddEntity(dimY);

            dxf.Save("style2.dxf");
            dxf2 = DxfDocument.Load("style2.dxf");


            dxf.RemoveEntity(dimX);
            dxf.RemoveEntity(dimY);

            bool ok;

            // we can remove myStyle it was only referenced by dimX and dimY
            ok = dxf.DimensionStyles.Remove(myStyle.Name);

            // we cannot remove myStyle.TextStyle since it is in use by the internal blocks created by the dimension entities
            ok = dxf.Blocks.Remove(dimX.Block.Name);
            ok = dxf.Blocks.Remove(dimY.Block.Name);

            // no we can remove the unreferenced textStyle
            ok = dxf.TextStyles.Remove(myStyle.DIMTXSTY.Name);

            dxf.Save("style3.dxf");
            dxf2 = DxfDocument.Load("style3.dxf");
        }
Esempio n. 19
0
        private static void LayerAndLineTypesUsesAndRemove()
        {
            DxfDocument dxf = new DxfDocument();

            Layer layer1 = new Layer("Layer1");
            layer1.Color = AciColor.Blue;
            layer1.LineType = LineType.Center;

            Layer layer2 = new Layer("Layer2");
            layer2.Color = AciColor.Red;

            LwPolyline poly = new LwPolyline();
            poly.Vertexes.Add(new LwPolylineVertex(0, 0));
            poly.Vertexes.Add(new LwPolylineVertex(10, 10));
            poly.Vertexes.Add(new LwPolylineVertex(20, 0));
            poly.Vertexes.Add(new LwPolylineVertex(30, 10));
            poly.Layer = layer1;
            dxf.AddEntity(poly);

            Ellipse ellipse = new Ellipse(new Vector3(2, 2, 0), 5, 3);
            ellipse.Rotation = 30;
            ellipse.Layer = layer1;
            dxf.AddEntity(ellipse);

            Line line = new Line(new Vector2(10, 5), new Vector2(-10, -5));
            line.Layer = layer2;
            line.LineType = LineType.DashDot;
            dxf.AddEntity(line);


            bool ok;

            // this will return false since layer1 is not empty
            ok = dxf.Layers.Remove(layer1.Name);

            List<DxfObject> entities = dxf.Layers.GetReferences(layer1.Name);
            foreach (DxfObject o in entities)
            {
                dxf.RemoveEntity(o as EntityObject);
            }

            // now this should return true since layer1 is empty
            ok = dxf.Layers.Remove(layer1.Name);

            // blocks needs an special attention
            Layer layer3 = new Layer("Layer3");
            layer3.Color = AciColor.Yellow;

            Circle circle = new Circle(Vector3.Zero, 15);
            // it is always recommended that all block entities will be located in layer 0, but this is up to the user.
            circle.Layer = new Layer("circle");
            circle.Layer.Color = AciColor.Green;

            Block block = new Block("MyBlock");
            block.Entities.Add(circle);
            block.Layer = new Layer("blockLayer");
            AttributeDefinition attdef = new AttributeDefinition("NewAttribute");
            attdef.Layer = new Layer("attDefLayer");
            attdef.LineType = LineType.Center;
            block.AttributeDefinitions.Add(attdef);

            Insert insert = new Insert(block, new Vector2(5, 5));
            insert.Layer = layer3;
            insert.Attributes[0].Layer = new Layer("attLayer");
            insert.Attributes[0].LineType = LineType.Dashed;
            dxf.AddEntity(insert);

            dxf.Save("test.dxf");

            DxfDocument dxf2 = DxfDocument.Load("test.dxf");

            // this list will contain the circle entity
            List<DxfObject> dxfObjects;
            dxfObjects = dxf.Layers.GetReferences("circle");

            // but we cannot removed since it is part of a block
            ok = dxf.RemoveEntity(circle);
            // we need to remove first the block, but to do this we need to make sure there are no references of that block in the document
            dxfObjects = dxf.Blocks.GetReferences(block.Name);
            foreach (DxfObject o in dxfObjects)
            {
                dxf.RemoveEntity(o as EntityObject);
            }


            // now it is safe to remove the block since we do not have more references in the document
            ok = dxf.Blocks.Remove(block.Name);
            // now it is safe to remove the layer "circle", the circle entity was removed with the block since it was part of it
            ok = dxf.Layers.Remove("circle");

            // purge all document layers, only empty layers will be removed
            dxf.Layers.Clear();

            // purge all document line types, only line types without references will be removed
            dxf.LineTypes.Clear();

            dxf.Save("test2.dxf");
        }
Esempio n. 20
0
        private static void ImageUsesAndRemove()
        {
            ImageDefinition imageDef1 = new ImageDefinition("img\\image01.jpg");
            Image image1 = new Image(imageDef1, Vector3.Zero, 10, 10);

            ImageDefinition imageDef2 = new ImageDefinition("img\\image02.jpg");
            Image image2 = new Image(imageDef2, new Vector3(0, 220, 0), 10, 10);
            Image image3 = new Image(imageDef2, image2.Position + new Vector3(280, 0, 0), 10, 10);

            Block block =new Block("MyImageBlock");
            block.Entities.Add(image1);

            Insert insert = new Insert(block);

            DxfDocument dxf = new DxfDocument();
            dxf.AddEntity(insert);
            dxf.AddEntity(image2);
            dxf.AddEntity(image3);
            dxf.Save("test netDxf.dxf");

           
            dxf.RemoveEntity(insert);
            dxf.Blocks.Remove(insert.Block.Name);
            // imageDef1 has no references in the document
            List<DxfObject> uses = dxf.ImageDefinitions.GetReferences(imageDef1.Name);
            dxf.Save("test netDxf with unreferenced imageDef.dxf");
            dxf = DxfDocument.Load("test netDxf with unreferenced imageDef.dxf");

            // once we have removed the insert and then the block that contained image1 we don't have more references to imageDef1
            dxf.ImageDefinitions.Remove(imageDef1.Name);
            dxf.Save("test netDxf with deleted imageDef.dxf");

        }
Esempio n. 21
0
        private static void DocumentUnits()
        {
            DxfDocument dxf = new DxfDocument();

            // setting the LUnit variable to engineering or architectural will also set the InsUnits variable to Inches,
            // this need to be this way since AutoCad will show those units in feet and inches and will always consider the drawing base units as inches.
            // You can change again the InsUnits it at your own risk.
            // its main purpose is at the user interface level
            //dxf.DrawingVariables.LUnits = LinearUnitType.Engineering;

            // this is the recommended document unit type
            dxf.DrawingVariables.LUnits = LinearUnitType.Decimal;

            // this is the real important unit,
            // it is used when inserting blocks or images into the drawing as this and the block units will give the scale of the resulting Insert
            dxf.DrawingVariables.InsUnits = DrawingUnits.Millimeters;

            // the angle unit type is purely cosmetic as it has no influence on how the angles are stored in the dxf 
            // its purpose is only at the user interface level
            dxf.DrawingVariables.AUnits = AngleUnitType.Radians;

            // even though we have set the drawing angles in radians the dxf always stores angle data in degrees,
            // this arc goes from 45 to 270 degrees and not radians or whatever the AUnits header variable says.
            Arc arc = new Arc(Vector2.Zero, 5, 45, 270);
            // Remember, at the moment, once the entity has been added to the document is not safe to modify it, changes in some of their properties might generate problems
            dxf.AddEntity(arc);

            // the units of this line will correspond to the ones set in InsUnits
            Line lineM = new Line(new Vector2(-5, -5), new Vector2(5, 5));
            dxf.AddEntity(lineM);

            // All entities added to a block are expressed in the coordinates defined by the block
            // You can set a default unit so all new blocks will use them, the default value is Unitless
            // You might want to use the same units as the drawing, this is just a convenient way to make sure all blocks share the same units 
            BlockRecord.DefaultUnits = dxf.DrawingVariables.InsUnits;

            // In this case the line will be 10 cm long
            Line lineCm = new Line(new Vector2(-5, 0), new Vector2(5, 0));
            Block blockCm = new Block("CmBlock");
            // You can override the default units changing the block.Record.Units value
            blockCm.Record.Units = DrawingUnits.Centimeters;
            blockCm.Entities.Add(lineCm);
            Insert insCm = new Insert(blockCm);

            // In this case the line will be 10 dm long
            Line lineDm = new Line(new Vector2(0, 5), new Vector2(0, -5));
            Block blockDm = new Block("DmBlock");
            blockDm.Record.Units = DrawingUnits.Decimeters;
            // AllowExploding and ScaleUniformy properties will only be recognized by dxf version AutoCad2007 and upwards
            blockDm.Record.AllowExploding = false;
            blockDm.Record.ScaleUniformly = true;
            blockDm.Entities.Add(lineDm);
            blockDm.Entities.Add(insCm);
            Insert insDm = new Insert(blockDm);

            dxf.AddEntity(insDm);

            // the image units are stored in the raster variables units, it is recommended to use the same units as the document to avoid confusions
            dxf.RasterVariables.Units = ImageUnits.Millimeters;
            // Sometimes AutoCad does not like image file relative paths, in any case reloading the references will fix the problem
            ImageDefinition imgDefinition = new ImageDefinition("image.jpg");
            // the resolution units is only used to calculate the image resolution that will return pixels per inch or per centimeter (the use of NoUnits is not recommended).
            imgDefinition.ResolutionUnits = ImageResolutionUnits.Inches;
            // this image will be 10x10 mm in size
            Image img = new Image(imgDefinition, Vector3.Zero, 10, 10);
            dxf.AddEntity(img);

            dxf.Save("Document Units.dxf");

            DxfDocument dxfLoad = DxfDocument.Load("Document Units.dxf");

        }
Esempio n. 22
0
        private static void WriteNestedInsert()
        {
            // nested blocks
            DxfDocument dxf = new DxfDocument();
            
            Block nestedBlock = new Block("Nested block");
            Circle circle = new Circle(Vector3.Zero, 5);
            circle.Layer = new Layer("circle");
            circle.Layer.Color.Index = 2;
            nestedBlock.Entities.Add(circle);
            
            AttributeDefinition attdef = new AttributeDefinition("NewAttribute");
            attdef.Prompt = "InfoText";
            attdef.Alignment = TextAlignment.MiddleCenter;
            nestedBlock.AttributeDefinitions.Add(attdef);

            Insert nestedInsert = new Insert(nestedBlock, new Vector3(0, 0, 0)); // the position will be relative to the position of the insert that nest it
            nestedInsert.Attributes[0].Value = 24;

            Insert nestedInsert2 = new Insert(nestedBlock, new Vector3(-20, 0, 0)); // the position will be relative to the position of the insert that nest it
            nestedInsert2.Attributes[0].Value = -20;

            Block block = new Block("MyBlock");
            block.Entities.Add(new Line(new Vector3(-5, -5, 0), new Vector3(5, 5, 0)));
            block.Entities.Add(new Line(new Vector3(5, -5, 0), new Vector3(-5, 5, 0)));
            block.Entities.Add(nestedInsert);
            block.Entities.Add(nestedInsert2);

            Insert insert = new Insert(block, new Vector3(5, 5, 5));
            insert.Layer = new Layer("insert");

            dxf.AddEntity(insert);
            //dxf.AddEntity(circle); // this is not allowed the circle is already part of a block

            dxf.Save("nested insert.dxf");
            dxf = DxfDocument.Load("nested insert.dxf");
            dxf.DrawingVariables.AcadVer = DxfVersion.AutoCad2010;
            dxf.Save("nested insert copy.dxf");

        }
Esempio n. 23
0
        private Insert ReadAcadTable(bool isBlockEntity)
        {
            Vector3 basePoint = Vector3.Zero;
            Vector3 normal = Vector3.UnitZ;
            Vector3 direction = Vector3.UnitX;
            string blockName = null;
            Block block = null;
            List<XData> xData = new List<XData>();

            this.chunk.Next();
            while (this.chunk.Code != 0)
            {
                switch (this.chunk.Code)
                {
                    case 2:
                        blockName = this.DecodeEncodedNonAsciiCharacters(this.chunk.ReadString());
                        if (!isBlockEntity)
                            block = this.GetBlock(blockName);
                        this.chunk.Next();
                        break;
                    case 10:
                        basePoint.X = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 20:
                        basePoint.Y = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 30:
                        basePoint.Z = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 11:
                        direction.X = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 21:
                        direction.Y = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 31:
                        direction.Z = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 210:
                        normal.X = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 220:
                        normal.Y = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 230:
                        normal.Z = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 1001:
                        string appId = this.DecodeEncodedNonAsciiCharacters(this.chunk.ReadString());
                        XData data = this.ReadXDataRecord(this.GetApplicationRegistry(appId));
                        xData.Add(data);
                        break;
                    default:
                        if (this.chunk.Code >= 1000 && this.chunk.Code <= 1071)
                            throw new Exception("The extended data of an entity must start with the application registry code.");

                        this.chunk.Next();
                        break;
                }
            }

            // It is a lot more intuitive to give the position in world coordinates and then define the orientation with the normal.
            Vector3 wcsBasePoint = MathHelper.Transform(basePoint, normal, CoordinateSystem.Object, CoordinateSystem.World);
            Insert insert = new Insert(new List<Attribute>())
            {
                Block = block,
                Position = wcsBasePoint,
                Normal = normal
            };
            // since we are converting the table entity to an insert we also need to assign a new handle to the internal EndSequence
            this.doc.NumHandles = insert.EndSequence.AsignHandle(this.doc.NumHandles);
            insert.XData.AddRange(xData);

            //Vector3 ocsDirection = MathHelper.Transform(direction, normal, CoordinateSystem.World, CoordinateSystem.Object);
            //insert.Rotation = Vector2.Angle(new Vector2(ocsDirection.X, ocsDirection.Y))*MathHelper.RadToDeg;
            //insert.Scale = new Vector3(1.0);

            // post process nested inserts
            if (isBlockEntity)
                this.nestedInserts.Add(insert, blockName);

            return insert;
        }
Esempio n. 24
0
        public static void LoadAndSaveBlocks()
        {
            // Create a block to be used as sample
            Block baseBlk = new Block("BaseBlock");
            baseBlk.Record.Units = DrawingUnits.Millimeters;
            baseBlk.Entities.Add(new Line(new Vector3(-5, -5, 0), new Vector3(5, 5, 0)));
            baseBlk.Entities.Add(new Line(new Vector3(5, -5, 0), new Vector3(-5, 5, 0)));
            AttributeDefinition attdef = new AttributeDefinition("MyAttribute")
            {
                Prompt = "Enter a value:",
                Value = 0,
                Position = Vector3.Zero,
                Layer = new Layer("MyLayer")
                {
                    Color = AciColor.Red
                }
            };
            baseBlk.AttributeDefinitions.Add(attdef);

            // Blocks are saved in a similar way as other dxf, just pass the dxf file name, the DxfVersion, and optionally if the dxf needs to be saved in binary format
            // Only AutoCad2000 and newer versions are supported.
            // The block entities and attribute definitions will be added to the Model layout.
            // The drawing header units will be the ones defined in the block record.
            baseBlk.Save(baseBlk.Name + ".dxf", DxfVersion.AutoCad2000);

            DxfDocument dxf = new DxfDocument();

            // Blocks are loaded as any other dxf, just pass the dxf file name,
            // optionally you can also give it a name, by default the file name without extension will be used.
            // Only AutoCad2000 and newer versions are supported,
            // Only the entities contained in the Model layout will be used.
            // The block units will be the ones defined in the dxf header.
            Block block = Block.Load(baseBlk.Name + ".dxf", "MyBlock");

            // in case the loading process has failed check for null
            // In DEBUG mode the loading process will raise exceptions while in RELEASE it will just return null, the same as loading a DxfDocument
            if (block == null)
            {
                Console.WriteLine("Error loading the block dxf file.");
                Console.WriteLine("Press a key to continue...");
                Console.ReadKey();
                return;
            }

            // once the block is loaded we can use it in insert entities
            Insert insert = new Insert(block, new Vector2(10));

            // the block might also contain attribute definitions
            int attdefCount = block.AttributeDefinitions.Count;

            // this is the list of attribute definition tags
            // remember netDxf does not allow the use of duplicate tag names, although AutoCad allows it, it is not recommended
            ICollection<string> tags = block.AttributeDefinitions.Tags;

            // we can assign values to the insert attributes
            foreach (Attribute att in insert.Attributes)
            {
                att.Value = string.Format("{0} value", att.Tag);
            }

            // optionally we can manually add the block definition to the document
            dxf.Blocks.Add(block);

            // we add the insert entity to the document, if the block associated with the block has not been added this method will do it automatically
            dxf.AddEntity(insert);

            // also it is possible to manually add attribute definitions to a document
            AttributeDefinition def = new AttributeDefinition("AttDefOutsideBlock")
            {
                Prompt = "Enter value:",
                Value = 0,
                Color = AciColor.Blue,
                Position = new Vector3(0, 30, 0)
            };

            // we will add the attribute definition to the document just like anyother entity
            dxf.AddEntity(def);
            
            // now we can save our new document
            dxf.Save("CreateBlockFromDxf.dxf");

            DxfDocument load = DxfDocument.Load("CreateBlockFromDxf.dxf");

        }
Esempio n. 25
0
        /// <summary>
        /// Resets the annotation position according to the leader hook.
        /// </summary>
        private void ResetAnnotationPosition()
        {
            DimensionStyleOverride styleOverride;

            DimensionStyleTextVerticalPlacement textVerticalPlacement = this.Style.TextVerticalPlacement;

            if (this.StyleOverrides.TryGetValue(DimensionStyleOverrideType.TextVerticalPlacement, out styleOverride))
            {
                textVerticalPlacement = (DimensionStyleTextVerticalPlacement)styleOverride.Value;
            }

            double textGap = this.Style.TextOffset;

            if (this.StyleOverrides.TryGetValue(DimensionStyleOverrideType.TextOffset, out styleOverride))
            {
                textGap = (double)styleOverride.Value;
            }

            double dimScale = this.Style.DimScaleOverall;

            if (this.StyleOverrides.TryGetValue(DimensionStyleOverrideType.DimScaleOverall, out styleOverride))
            {
                dimScale = (double)styleOverride.Value;
            }

            double textHeight = this.Style.TextHeight;

            if (this.StyleOverrides.TryGetValue(DimensionStyleOverrideType.TextHeight, out styleOverride))
            {
                textHeight = (double)styleOverride.Value;
            }

            AciColor textColor = this.Style.TextColor;

            if (this.StyleOverrides.TryGetValue(DimensionStyleOverrideType.TextColor, out styleOverride))
            {
                textColor = (AciColor)styleOverride.Value;
            }

            Vector2 hook = this.Hook;
            Vector2 position;
            Vector2 textOffset;
            Vector2 dir = this.Direction;
            int     side;

            textGap *= dimScale;

            switch (this.annotation.Type)
            {
            case EntityType.MText:
                MText mText = (MText)this.annotation;
                side = MathHelper.Sign(dir.X);
                if (side == 0)
                {
                    side = MathHelper.Sign(dir.Y);
                }
                if (mText.Rotation > 90.0 && mText.Rotation <= 270.0)
                {
                    side *= -1;
                }

                if (side >= 0)
                {
                    switch (mText.AttachmentPoint)
                    {
                    case MTextAttachmentPoint.TopRight:
                        mText.AttachmentPoint = MTextAttachmentPoint.TopLeft;
                        break;

                    case MTextAttachmentPoint.MiddleRight:
                        mText.AttachmentPoint = MTextAttachmentPoint.MiddleLeft;
                        break;

                    case MTextAttachmentPoint.BottomRight:
                        mText.AttachmentPoint = MTextAttachmentPoint.BottomLeft;
                        break;
                    }
                }
                else
                {
                    switch (mText.AttachmentPoint)
                    {
                    case MTextAttachmentPoint.TopLeft:
                        mText.AttachmentPoint = MTextAttachmentPoint.TopRight;
                        break;

                    case MTextAttachmentPoint.MiddleLeft:
                        mText.AttachmentPoint = MTextAttachmentPoint.MiddleRight;
                        break;

                    case MTextAttachmentPoint.BottomLeft:
                        mText.AttachmentPoint = MTextAttachmentPoint.BottomRight;
                        break;
                    }
                }

                textOffset = textVerticalPlacement == DimensionStyleTextVerticalPlacement.Centered ?
                             new Vector2(side * textGap, 0.0) :
                             new Vector2(side * textGap, textGap);

                position = hook + this.offset + Vector2.Rotate(textOffset, mText.Rotation * MathHelper.DegToRad);

                mText.Position = MathHelper.Transform(position, Normal, this.elevation);
                mText.Height   = textHeight * dimScale;
                mText.Color    = textColor.IsByBlock ? AciColor.ByLayer : textColor;
                break;

            case EntityType.Text:
                Text text = (Text)this.annotation;
                side = MathHelper.Sign(dir.X);
                if (side == 0)
                {
                    side = MathHelper.Sign(dir.Y);
                }
                if (text.Rotation > 90.0 && text.Rotation <= 270.0)
                {
                    side *= -1;
                }

                if (side >= 0)
                {
                    switch (text.Alignment)
                    {
                    case TextAlignment.TopRight:
                        text.Alignment = TextAlignment.TopLeft;
                        break;

                    case TextAlignment.MiddleRight:
                        text.Alignment = TextAlignment.MiddleLeft;
                        break;

                    case TextAlignment.BottomRight:
                        text.Alignment = TextAlignment.BottomLeft;
                        break;

                    case TextAlignment.BaselineRight:
                        text.Alignment = TextAlignment.BaselineLeft;
                        break;
                    }
                }
                else
                {
                    switch (text.Alignment)
                    {
                    case TextAlignment.TopLeft:
                        text.Alignment = TextAlignment.TopRight;
                        break;

                    case TextAlignment.MiddleLeft:
                        text.Alignment = TextAlignment.MiddleRight;
                        break;

                    case TextAlignment.BottomLeft:
                        text.Alignment = TextAlignment.BottomRight;
                        break;

                    case TextAlignment.BaselineLeft:
                        text.Alignment = TextAlignment.BaselineRight;
                        break;
                    }
                }

                textOffset = textVerticalPlacement == DimensionStyleTextVerticalPlacement.Centered ?
                             new Vector2(side * textGap, 0.0) :
                             new Vector2(side * textGap, textGap);

                position      = hook + this.offset + Vector2.Rotate(textOffset, text.Rotation * MathHelper.DegToRad);
                text.Position = MathHelper.Transform(position, this.Normal, this.elevation);
                text.Height   = textHeight * dimScale;
                text.Color    = textColor.IsByBlock ? AciColor.ByLayer : textColor;
                break;

            case EntityType.Insert:
                Insert ins = (Insert)this.annotation;
                position     = hook + this.offset;
                ins.Position = MathHelper.Transform(position, this.Normal, this.elevation);
                ins.Color    = textColor.IsByBlock ? AciColor.ByLayer : textColor;
                break;

            case EntityType.Tolerance:
                Tolerance tol = (Tolerance)this.annotation;
                position     = hook + this.offset;
                tol.Position = MathHelper.Transform(position, this.Normal, this.elevation);
                tol.Color    = textColor.IsByBlock ? AciColor.ByLayer : textColor;
                break;

            default:
                throw new Exception(string.Format("The entity type: {0} not supported as a leader annotation.", this.annotation.Type));
            }
        }
Esempio n. 26
0
        private static void NestedBlock()
        {
            Block blockMM = new Block("BlockMM");
            blockMM.Record.Units = DrawingUnits.Millimeters;
            AttributeDefinition attDefMM = new AttributeDefinition("MyAttributeMM");
            attDefMM.Height = 1.0;
            attDefMM.Value = "This is block mm";
            blockMM.AttributeDefinitions.Add(attDefMM);
            Line line1MM = new Line(Vector2.Zero, Vector2.UnitX);
            blockMM.Entities.Add(line1MM);
            Insert insMM = new Insert(blockMM);
            insMM.TransformAttributes();

            Block blockCM = new Block("BlockCM");
            blockCM.Record.Units = DrawingUnits.Centimeters;
            AttributeDefinition attDefCM = new AttributeDefinition("MyAttributeCM");
            attDefCM.Height = 1.0;
            attDefCM.Value = "This is block cm";
            blockCM.AttributeDefinitions.Add(attDefCM);
            Line line1CM = new Line(Vector2.Zero, Vector2.UnitY);
            blockCM.Entities.Add(line1CM);
            blockCM.Entities.Add(insMM);
            Insert insCM = new Insert(blockCM);

            DxfDocument doc = new DxfDocument();
            doc.DrawingVariables.InsUnits = DrawingUnits.Meters;
            //doc.AddEntity(insMM);
            doc.AddEntity(insCM);

            doc.Save("test.dxf");
        }
Esempio n. 27
0
        private void Insert_AttributeRemoved(Insert sender, AttributeChangeEventArgs e)
        {
            this.layers.References[e.Item.Layer.Name].Remove(e.Item);
            e.Item.LayerChanged += this.Entity_LayerChanged;

            this.linetypes.References[e.Item.Linetype.Name].Remove(e.Item);
            e.Item.LinetypeChanged -= this.Entity_LinetypeChanged;

            this.textStyles.References[e.Item.Style.Name].Remove(e.Item);
            e.Item.TextStyleChanged += this.Entity_TextStyleChanged;
        }
Esempio n. 28
0
        public static void ModifyingBlockProperties()
        {
            DxfDocument doc = new DxfDocument();
            doc.DrawingVariables.InsUnits = DrawingUnits.Centimeters;
            Line existingLine = new Line(new Vector2(-10, 10), new Vector2(10, -10));
            doc.AddEntity(existingLine);

            AttributeDefinition attDef4 = new AttributeDefinition("MyAttribute4");
            attDef4.Value = "MyValue4";
            attDef4.Alignment = TextAlignment.TopCenter;
            Block block = new Block("MyBlock", null, new List<AttributeDefinition>{attDef4});
            block.Record.Units = DrawingUnits.Millimeters;

            // this is incorrect we cannot add an entity that belongs to a document when the block does not belong to anyone.
            //block.Entities.Add(existingLine);
            doc.Blocks.Add(block);
            // when the block and the entity that is being added belong to the same document, the entity will be removed from its current layout and added to the block
            // you cannot add an entity that belongs to a different document or block. Clone it instead.
            block.Entities.Add(existingLine);

            // now we can modify the block properties even if it has been already added to the document
            Line line = new Line(new Vector2(-10, -10), new Vector2(10, 10));

            // when new entities that do not belong to anyone are added to an existing block, they will also be added to the document
            block.Entities.Add(line);

            DxfDocument doc2 = new DxfDocument();
            Circle circle = new Circle(Vector2.Zero, 5);
            doc2.AddEntity(circle);

            // this is incorrect the circle already belongs to another document
            //block.Entities.Add(circle);
            // we need to clone it first
            Circle circle2 = (Circle) circle.Clone();
            circle2.Radius = 2.5;
            block.Entities.Add(circle2);

            //you could also remove circle2 from doc2 and add it to the block
            doc2.RemoveEntity(circle);
            block.Entities.Add(circle);

            AttributeDefinition attDef = new AttributeDefinition("MyAttribute1");
            attDef.Value = "MyValue1";
            block.AttributeDefinitions.Add(attDef);

            // the same that is applicable to entities is also true to attribute definitions
            AttributeDefinition attDef2 = new AttributeDefinition("MyAttribute2");
            attDef2.Value = "MyValue2";
            attDef2.Alignment = TextAlignment.BaselineRight;
            block.AttributeDefinitions.Add(attDef2);

            Insert ins = new Insert(block);
            doc.AddEntity(ins);

            // if the insert has been added to a document, any new attribute definitions added to the block will not be reflected in the insert
            // this mimics the behavior in AutoCad
            AttributeDefinition attDef3 = new AttributeDefinition("MyAttribute3");
            attDef3.Value = "MyValue3";
            attDef3.Alignment = TextAlignment.TopCenter;
            block.AttributeDefinitions.Add(attDef3);
            ins.Rotation = 30;

            // to update the insert attributes call the method Sync, this method will also call the method TransformAttributes
            ins.Sync();

            // the ins2 will have all three attributes
            Insert ins2 = new Insert(block, new Vector2(20,0));
            doc.AddEntity(ins2);

            doc.Save("Test.dxf");

            block.Name = "MyBlockRenamed";

            doc.Save("BlockRename.dxf");

            doc = Test("BlockRename.dxf");
        }
Esempio n. 29
0
        private void WriteInsert(Insert insert)
        {
            if (this.activeSection != StringCode.EntitiesSection && ! this.isBlockEntities)
            {
                throw new InvalidDxfSectionException(this.activeSection, this.file);
            }

            this.WriteCodePair(0, insert.CodeName);
            this.WriteCodePair(5, insert.Handle);
            this.WriteCodePair(100, SubclassMarker.Entity);
            this.WriteEntityCommonCodes(insert);
            this.WriteCodePair(100, SubclassMarker.Insert);

            this.WriteCodePair(2, insert.Block);

            this.WriteCodePair(10, insert.InsertionPoint.X);
            this.WriteCodePair(20, insert.InsertionPoint.Y);
            this.WriteCodePair(30, insert.InsertionPoint.Z);

            this.WriteCodePair(41, insert.Scale.X);
            this.WriteCodePair(42, insert.Scale.Y);
            this.WriteCodePair(43, insert.Scale.Z);

            this.WriteCodePair(50, insert.Rotation);

            this.WriteCodePair(210, insert.Normal.X);
            this.WriteCodePair(220, insert.Normal.Y);
            this.WriteCodePair(230, insert.Normal.Z);

            if (insert.Attributes.Count > 0)
            {
                //Obsolete; formerly an “entities follow flag” (optional; ignore if present)
                //but its needed to load the dxf file in AutoCAD
                this.WriteCodePair(66, "1");

                this.WriteXData(insert.XData);

                foreach (Attribute attrib in insert.Attributes)
                {
                    this.WriteAttribute(attrib, insert.InsertionPoint);
                }

                this.WriteCodePair(0, insert.EndSequence.CodeName);
                this.WriteCodePair(5, insert.EndSequence.Handle);
                this.WriteCodePair(100, SubclassMarker.Entity);
                this.WriteCodePair(8, insert.EndSequence.Layer);
            }
            else
            {
                this.WriteXData(insert.XData);
            }
        }
Esempio n. 30
0
        private static void WriteDxfFile()
        {
            DxfDocument dxf = new DxfDocument();

            //arc
            Arc arc = new Arc(new Vector3d(10, 10, 0), 10, 45, 135);
            arc.Layer = new Layer("arc");
            arc.Layer.Color.Index = 1;
            dxf.AddEntity(arc);

            //xData sample
            XData xdata = new XData(new ApplicationRegistry("netDxf"));
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.String, "extended data with netDxf"));
            xdata.XDataRecord.Add(XDataRecord.OpenControlString);
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionX, 0));
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionY, 0));
            xdata.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionZ, 0));
            xdata.XDataRecord.Add(XDataRecord.CloseControlString);

            XData xdata2 = new XData(new ApplicationRegistry("other application"));
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.String, "extended data with netDxf"));
            xdata2.XDataRecord.Add(XDataRecord.OpenControlString);
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.String, "string record"));
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.Real, 15.5));
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.Long, 350));
            xdata2.XDataRecord.Add(XDataRecord.CloseControlString);

            //circle
            Vector3d extrusion = new Vector3d(1, 1, 1);
            Vector3d centerWCS = new Vector3d(1, 1, 1);
            Vector3d centerOCS = MathHelper.Transform(centerWCS,
                                                      extrusion,
                                                      MathHelper.CoordinateSystem.World,
                                                      MathHelper.CoordinateSystem.Object);

            Circle circle = new Circle(centerOCS, 5);
            circle.Layer = new Layer("circle with spaces");
            circle.Layer.Color=AciColor.Yellow;
            circle.LineType = LineType.Dashed;
            circle.Normal = extrusion;
            circle.XData=new Dictionary<ApplicationRegistry, XData>
                             {
                                 {xdata.ApplicationRegistry, xdata},
                                 {xdata2.ApplicationRegistry, xdata2}
                             };

            dxf.AddEntity(circle);

            //points
            Point point1 = new Point(new Vector3d(-3, -3, 0));
            point1.Layer = new Layer("point");
            point1.Color = new AciColor(30);
            Point point2 = new Point(new Vector3d(1, 1, 1));
            point2.Layer = point1.Layer;
            point2.Layer.Color.Index = 9;
            point2.Normal = new Vector3d(1, 1, 1);
            dxf.AddEntity(point1);
            dxf.AddEntity(point2);

            //3dface
            Face3d face3D = new Face3d(new Vector3d(-5, -5, 5),
                                       new Vector3d(5, -5, 5),
                                       new Vector3d(5, 5, 5),
                                       new Vector3d(-5, 5, 5));
            face3D.Layer = new Layer("3dface");
            face3D.Layer.Color.Index = 3;
            dxf.AddEntity(face3D);

            //polyline
            PolylineVertex polyVertex;
            List<PolylineVertex> polyVertexes = new List<PolylineVertex>();
            polyVertex = new PolylineVertex(new Vector2d(-50, -50));
            polyVertex.BeginThickness = 2;
            polyVertexes.Add(polyVertex);
            polyVertex = new PolylineVertex(new Vector2d(50, -50));
            polyVertex.BeginThickness = 1;
            polyVertexes.Add(polyVertex);
            polyVertex = new PolylineVertex(new Vector2d(50, 50));
            polyVertex.Bulge = 1;
            polyVertexes.Add(polyVertex);
            polyVertex = new PolylineVertex(new Vector2d(-50, 50));
            polyVertexes.Add(polyVertex);
            Polyline polyline2d = new Polyline(polyVertexes, true);
            polyline2d.Layer = new Layer("polyline2d");
            polyline2d.Layer.Color.Index = 5;
            polyline2d.Normal = new Vector3d(1, 1, 1);
            polyline2d.Elevation = 100.0;
            dxf.AddEntity(polyline2d);

            //lightweight polyline
            LightWeightPolylineVertex lwVertex;
            List<LightWeightPolylineVertex> lwVertexes = new List<LightWeightPolylineVertex>();
            lwVertex = new LightWeightPolylineVertex(new Vector2d(-25, -25));
            lwVertex.BeginThickness = 2;
            lwVertexes.Add(lwVertex);
            lwVertex = new LightWeightPolylineVertex(new Vector2d(25, -25));
            lwVertex.BeginThickness = 1;
            lwVertexes.Add(lwVertex);
            lwVertex = new LightWeightPolylineVertex(new Vector2d(25, 25));
            lwVertex.Bulge = 1;
            lwVertexes.Add(lwVertex);
            lwVertex = new LightWeightPolylineVertex(new Vector2d(-25, 25));
            lwVertexes.Add(lwVertex);
            LightWeightPolyline lwPolyline = new LightWeightPolyline(lwVertexes, true);
            lwPolyline.Layer = new Layer("lwpolyline");
            lwPolyline.Layer.Color.Index = 5;
            lwPolyline.Normal = new Vector3d(1, 1, 1);
            lwPolyline.Elevation = 100.0;
            dxf.AddEntity(lwPolyline);

            //line
            Line line = new Line(new Vector3d(0, 0, 0), new Vector3d(10, 10, 10));
            line.Layer = new Layer("line");
            line.Layer.Color.Index = 6;
            dxf.AddEntity(line);

            //3d polyline
            Polyline3dVertex vertex;
            List<Polyline3dVertex> vertexes = new List<Polyline3dVertex>();
            vertex = new Polyline3dVertex(new Vector3d(-50, -50, 0));
            vertexes.Add(vertex);
            vertex = new Polyline3dVertex(new Vector3d(50, -50, 10));
            vertexes.Add(vertex);
            vertex = new Polyline3dVertex(new Vector3d(50, 50, 25));
            vertexes.Add(vertex);
            vertex = new Polyline3dVertex(new Vector3d(-50, 50, 50));
            vertexes.Add(vertex);
            Polyline3d polyline = new Polyline3d(vertexes, true);
            polyline.Layer = new Layer("polyline3d");
            polyline.Layer.Color.Index = 24;
            dxf.AddEntity(polyline);

            //block definition
            Block block = new Block("TestBlock");
            block.Entities.Add(new Line(new Vector3d(-5, -5, 5), new Vector3d(5, 5, 5)));
            block.Entities.Add(new Line(new Vector3d(5, -5, 5), new Vector3d(-5, 5, 5)));

            //insert
            Insert insert = new Insert(block, new Vector3d(5, 5, 5));
            insert.Layer = new Layer("insert");
            insert.Layer.Color.Index = 4;
            dxf.AddEntity(insert);

            //text
            TextStyle style=new TextStyle("True type font","Arial.ttf");
            Text text = new Text("Hello world!", Vector3d.Zero, 10.0f,style);
            text.Layer = new Layer("text");
            text.Layer.Color.Index = 8;
            text.Alignment = TextAlignment.TopRight;
            dxf.AddEntity(text);

            dxf.Save("AutoCad2007.dxf", DxfVersion.AutoCad2007);
            dxf.Save("AutoCad2004.dxf", DxfVersion.AutoCad2004);
            dxf.Save("AutoCad2000.dxf", DxfVersion.AutoCad2000);
            dxf.Save("AutoCad12.dxf", DxfVersion.AutoCad12);
        }
Esempio n. 31
0
        /// <summary>
        /// Resets the annotation position according to the leader hook.
        /// </summary>
        private void ResetAnnotationPosition()
        {
            if (this.vertexes.Count < 2)
            {
                throw new Exception("The leader vertexes list requires at least two points.");
            }

            if (this.annotation == null)
            {
                return;
            }

            Vector2 hook = this.vertexes[this.vertexes.Count - 1];
            Vector2 position;

            switch (this.annotation.Type)
            {
            case EntityType.MText:
                MText   mText     = (MText)this.annotation;
                Vector2 dir       = this.vertexes[this.vertexes.Count - 1] - this.vertexes[this.vertexes.Count - 2];
                double  xOffset   = 0.0;
                int     mTextSide = Math.Sign(dir.X);
                if (this.TextVerticalPosition == LeaderTextVerticalPosition.Centered)
                {
                    if (mTextSide < 0 && mText.AttachmentPoint == MTextAttachmentPoint.TopLeft)
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.TopRight;
                    }
                    else if (mTextSide > 0 && mText.AttachmentPoint == MTextAttachmentPoint.TopRight)
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.TopLeft;
                    }
                    else if (mTextSide < 0 && mText.AttachmentPoint == MTextAttachmentPoint.MiddleLeft)
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.MiddleRight;
                    }
                    else if (mTextSide > 0 && mText.AttachmentPoint == MTextAttachmentPoint.MiddleRight)
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.MiddleLeft;
                    }
                    else if (mTextSide < 0 && mText.AttachmentPoint == MTextAttachmentPoint.BottomLeft)
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.BottomRight;
                    }
                    else if (mTextSide > 0 && mText.AttachmentPoint == MTextAttachmentPoint.BottomRight)
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.BottomLeft;
                    }

                    switch (mText.AttachmentPoint)
                    {
                    case MTextAttachmentPoint.TopLeft:
                    case MTextAttachmentPoint.MiddleLeft:
                    case MTextAttachmentPoint.BottomLeft:
                        xOffset = -this.style.TextOffset * this.style.DimScaleOverall;
                        break;

                    case MTextAttachmentPoint.TopCenter:
                    case MTextAttachmentPoint.MiddleCenter:
                    case MTextAttachmentPoint.BottomCenter:
                        xOffset = 0.0;
                        break;

                    case MTextAttachmentPoint.TopRight:
                    case MTextAttachmentPoint.MiddleRight:
                    case MTextAttachmentPoint.BottomRight:
                        xOffset = this.style.TextOffset * this.style.DimScaleOverall;
                        break;
                    }
                    position = hook;
                }
                else
                {
                    position = hook + new Vector2(mTextSide * this.style.TextOffset * this.style.DimScaleOverall, this.style.TextOffset * this.style.DimScaleOverall);
                    mText.AttachmentPoint = mTextSide >= 0 ? MTextAttachmentPoint.BottomLeft : MTextAttachmentPoint.BottomRight;
                }

                position         = position - this.offset;
                mText.Position   = MathHelper.Transform(new Vector3(position.X - xOffset, position.Y, this.elevation), this.Normal, CoordinateSystem.Object, CoordinateSystem.World);
                mText.Height     = this.style.TextHeight * this.style.DimScaleOverall;
                mText.Color      = this.style.TextColor.IsByBlock ? AciColor.ByLayer : this.style.TextColor;
                this.hasHookLine = true;
                break;

            case EntityType.Insert:
                Insert ins = (Insert)this.annotation;
                position         = hook - this.offset;
                ins.Position     = MathHelper.Transform(new Vector3(position.X, position.Y, this.elevation), this.Normal, CoordinateSystem.Object, CoordinateSystem.World);
                ins.Color        = this.style.TextColor.IsByBlock ? AciColor.ByLayer : this.style.TextColor;
                this.hasHookLine = false;
                break;

            case EntityType.Tolerance:
                Tolerance tol = (Tolerance)this.annotation;
                position         = hook - this.offset;
                tol.Position     = MathHelper.Transform(new Vector3(position.X, position.Y, this.elevation), this.Normal, CoordinateSystem.Object, CoordinateSystem.World);
                tol.Color        = this.style.TextColor.IsByBlock ? AciColor.ByLayer : this.style.TextColor;
                this.hasHookLine = false;
                break;

            case EntityType.Text:
                Text    text     = (Text)this.annotation;
                Vector2 textDir  = this.vertexes[this.vertexes.Count - 1] - this.vertexes[this.vertexes.Count - 2];
                int     textSide = Math.Sign(textDir.X);
                position         = hook + new Vector2(textSide * this.style.TextOffset * this.style.DimScaleOverall, this.style.TextOffset * this.style.DimScaleOverall) - this.offset;
                text.Position    = MathHelper.Transform(new Vector3(position.X, position.Y, this.elevation), this.Normal, CoordinateSystem.Object, CoordinateSystem.World);
                text.Alignment   = textSide >= 0 ? TextAlignment.BottomLeft : TextAlignment.BottomRight;
                text.Height      = this.style.TextHeight * this.style.DimScaleOverall;
                text.Color       = this.style.TextColor.IsByBlock ? AciColor.ByLayer : this.style.TextColor;
                this.hasHookLine = true;
                break;

            default:
                throw new Exception(string.Format("The entity type: {0} not supported as a leader annotation.", this.annotation.Type));
            }
        }
Esempio n. 32
0
        private static void RemoveBlock()
        {
            DxfDocument dxf = new DxfDocument();
            Block block = new Block("MyBlock");

            Line line1 = new Line(new Vector3(-5, -5, 0), new Vector3(5, 5, 0));
            Line line2 = new Line(new Vector3(5, -5, 0), new Vector3(-5, 5, 0));
            block.Entities.Add(line1);
            block.Entities.Add(line2);

            Insert insert = new Insert(block);

            dxf.AddEntity(insert);

            bool ok;
            // line1 is used by block and cannot be removed (ok = false)
            ok = dxf.RemoveEntity(line1);
            // block is used by insert and cannot be removed (ok = false)
            ok = dxf.Blocks.Remove(block);
            // it is safe to remove insert, it doesn't belong to anybody (ok = true)
            ok = dxf.RemoveEntity(insert);
            // it is safe to remove block, it doesn't belong to anybody (ok = true)
            // at the same time, all entities that were part of the block have been also removed
            ok = dxf.Blocks.Remove(block);
            // obj is null the line1 does not exist in the document, the block was removed
            DxfObject obj = dxf.GetObjectByHandle(line1.Handle);

            Console.WriteLine("Press a key...");
            Console.ReadKey();

        }
Esempio n. 33
0
        /// <summary>
        /// Creates a new Insert that is a copy of the current instance.
        /// </summary>
        /// <returns>A new Insert that is a copy of this instance.</returns>
        public override object Clone()
        {
            List<Attribute> copyAttributes = new List<Attribute>();
            foreach (Attribute att in this.attributes.Values)
                copyAttributes.Add((Attribute)att.Clone());

            Insert entity = new Insert
                {
                    //EntityObject properties
                    Layer = (Layer)this.layer.Clone(),
                    LineType = (LineType)this.lineType.Clone(),
                    Color = (AciColor)this.color.Clone(),
                    Lineweight = (Lineweight)this.lineweight.Clone(),
                    Transparency = (Transparency)this.transparency.Clone(),
                    LineTypeScale = this.lineTypeScale,
                    Normal = this.normal,
                    //Insert properties
                    Position = this.position,
                    Block = (Block)this.block.Clone(),
                    Scale = this.scale,
                    Rotation = this.rotation,
                    Attributes = new AttributeDictionary(copyAttributes)
                };

            foreach (XData data in this.XData.Values)
                entity.XData.Add((XData)data.Clone());

            return entity;
        }
Esempio n. 34
0
        private static EntityObject EndArrowHead(Vector2 position, double rotation, DimensionStyle style)
        {
            Block block = style.DIMSAH ? style.DIMBLK2 : style.DIMBLK;

            if (block == null)
            {
                Vector2 arrowRef = Vector2.Polar(position, -style.DIMASZ*style.DIMSCALE, rotation);
                Solid arrow = new Solid(position,
                    Vector2.Polar(arrowRef, -(style.DIMASZ/6)*style.DIMSCALE, rotation + MathHelper.HalfPI),
                    Vector2.Polar(arrowRef, (style.DIMASZ/6)*style.DIMSCALE, rotation + MathHelper.HalfPI))
                {
                    Color = style.DIMCLRD
                };
                return arrow;
            }
            else
            {
                Insert arrow = new Insert(block, position)
                {
                    Color = style.DIMCLRD,
                    Scale = new Vector3(style.DIMASZ*style.DIMSCALE),
                    Rotation = rotation*MathHelper.RadToDeg
                };
                return arrow;
            }
        }
Esempio n. 35
0
        /// <summary>
        /// Resets the annotation position according to the leader hook.
        /// </summary>
        private void ResetAnnotationPosition()
        {
            if (this.vertexes.Count < 2)
            {
                throw new Exception("The leader vertexes list requires at least two points.");
            }

            if (this.annotation == null)
            {
                return;
            }

            DimensionStyleOverride styleOverride;
            DimensionStyleTextVerticalPlacement textVerticalPlacement = this.Style.TextVerticalPlacement;

            if (this.StyleOverrides.TryGetValue(DimensionStyleOverrideType.TextVerticalPlacement, out styleOverride))
            {
                textVerticalPlacement = (DimensionStyleTextVerticalPlacement)styleOverride.Value;
            }
            double textOffset = this.Style.TextOffset;

            if (this.StyleOverrides.TryGetValue(DimensionStyleOverrideType.TextOffset, out styleOverride))
            {
                textOffset = (double)styleOverride.Value;
            }
            double dimScale = this.Style.DimScaleOverall;

            if (this.StyleOverrides.TryGetValue(DimensionStyleOverrideType.DimScaleOverall, out styleOverride))
            {
                dimScale = (double)styleOverride.Value;
            }
            double textHeight = this.Style.TextHeight;

            if (this.StyleOverrides.TryGetValue(DimensionStyleOverrideType.TextHeight, out styleOverride))
            {
                textHeight = (double)styleOverride.Value;
            }
            AciColor textColor = this.Style.TextColor;

            if (this.StyleOverrides.TryGetValue(DimensionStyleOverrideType.TextColor, out styleOverride))
            {
                textColor = (AciColor)styleOverride.Value;
            }

            Vector2 hook = this.vertexes[this.vertexes.Count - 1];
            Vector2 position;

            switch (this.annotation.Type)
            {
            case EntityType.MText:
                MText   mText        = (MText)this.annotation;
                Vector2 dir          = this.vertexes[this.vertexes.Count - 1] - this.vertexes[this.vertexes.Count - 2];
                double  mTextXoffset = 0.0;
                int     mTextSide    = Math.Sign(dir.X);
                if (textVerticalPlacement == DimensionStyleTextVerticalPlacement.Centered)
                {
                    if (mTextSide >= 0)
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.MiddleLeft;
                        mTextXoffset          = -textOffset * dimScale;
                    }
                    else
                    {
                        mText.AttachmentPoint = MTextAttachmentPoint.MiddleRight;
                        mTextXoffset          = textOffset * dimScale;
                    }
                    position = hook;
                }
                else
                {
                    position = hook + new Vector2(mTextSide * textOffset * dimScale, textOffset * dimScale);
                    mText.AttachmentPoint = mTextSide >= 0 ? MTextAttachmentPoint.BottomLeft : MTextAttachmentPoint.BottomRight;
                }

                position       = position + this.offset;
                mText.Position = MathHelper.Transform(new Vector3(position.X - mTextXoffset, position.Y, this.elevation), this.Normal, CoordinateSystem.Object, CoordinateSystem.World);
                mText.Height   = textHeight * dimScale;
                mText.Color    = textColor.IsByBlock ? AciColor.ByLayer : textColor;
                break;

            case EntityType.Insert:
                Insert ins = (Insert)this.annotation;
                position     = hook + this.offset;
                ins.Position = MathHelper.Transform(new Vector3(position.X, position.Y, this.elevation), this.Normal, CoordinateSystem.Object, CoordinateSystem.World);
                ins.Color    = textColor.IsByBlock ? AciColor.ByLayer : textColor;
                break;

            case EntityType.Tolerance:
                Tolerance tol = (Tolerance)this.annotation;
                position     = hook + this.offset;
                tol.Position = MathHelper.Transform(new Vector3(position.X, position.Y, this.elevation), this.Normal, CoordinateSystem.Object, CoordinateSystem.World);
                tol.Color    = textColor.IsByBlock ? AciColor.ByLayer : textColor;
                break;

            case EntityType.Text:
                Text    text        = (Text)this.annotation;
                double  textXoffset = 0.0;
                Vector2 textDir     = this.vertexes[this.vertexes.Count - 1] - this.vertexes[this.vertexes.Count - 2];
                int     textSide    = Math.Sign(textDir.X);

                if (textVerticalPlacement == DimensionStyleTextVerticalPlacement.Centered)
                {
                    if (textSide >= 0)
                    {
                        text.Alignment = TextAlignment.MiddleLeft;
                        textXoffset    = -textOffset * dimScale;
                    }
                    else
                    {
                        text.Alignment = TextAlignment.MiddleRight;
                        textXoffset    = textOffset * dimScale;
                    }
                    position = hook;
                }
                else
                {
                    position       = hook + new Vector2(textSide * textOffset * dimScale, textOffset * dimScale);
                    text.Alignment = textSide >= 0 ? TextAlignment.BottomLeft : TextAlignment.BottomRight;
                }

                position      = position + this.offset;
                text.Position = MathHelper.Transform(new Vector3(position.X - textXoffset, position.Y, this.elevation), this.Normal, CoordinateSystem.Object, CoordinateSystem.World);
                text.Height   = textHeight * dimScale;
                text.Color    = textColor.IsByBlock ? AciColor.ByLayer : textColor;
                break;

            default:
                throw new Exception(string.Format("The entity type: {0} not supported as a leader annotation.", this.annotation.Type));
            }
        }
Esempio n. 36
0
        private Insert ReadInsert(bool isBlockEntity)
        {
            Vector3 basePoint = Vector3.Zero;
            Vector3 normal = Vector3.UnitZ;
            Vector3 scale = new Vector3(1.0, 1.0, 1.0);
            double rotation = 0.0;
            string blockName = null;
            Block block = null;
            List<Attribute> attributes = new List<Attribute>();
            List<XData> xData = new List<XData>();

            this.chunk.Next();
            while (this.chunk.Code != 0)
            {
                switch (this.chunk.Code)
                {
                    case 2:
                        blockName = this.DecodeEncodedNonAsciiCharacters(this.chunk.ReadString());
                        if (!isBlockEntity)
                            block = this.GetBlock(blockName);
                        this.chunk.Next();
                        break;
                    case 10:
                        basePoint.X = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 20:
                        basePoint.Y = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 30:
                        basePoint.Z = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 41:
                        scale.X = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 42:
                        scale.Y = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 43:
                        scale.Z = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 50:
                        rotation = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 210:
                        normal.X = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 220:
                        normal.Y = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 230:
                        normal.Z = this.chunk.ReadDouble();
                        this.chunk.Next();
                        break;
                    case 1001:
                        string appId = this.DecodeEncodedNonAsciiCharacters(this.chunk.ReadString());
                        XData data = this.ReadXDataRecord(this.GetApplicationRegistry(appId));
                        xData.Add(data);
                        break;
                    default:
                        if (this.chunk.Code >= 1000 && this.chunk.Code <= 1071)
                            throw new Exception("The extended data of an entity must start with the application registry code.");

                        this.chunk.Next();
                        break;
                }
            }

            if (this.chunk.ReadString() == DxfObjectCode.Attribute)
            {
                while (this.chunk.ReadString() != DxfObjectCode.EndSequence)
                {
                    Attribute attribute = this.ReadAttribute(block, isBlockEntity);
                    if (attribute != null)
                        attributes.Add(attribute);
                }
            }

            string endSequenceHandle = string.Empty;
            if (this.chunk.ReadString() == DxfObjectCode.EndSequence)
            {
                // read the end sequence object until a new element is found
                this.chunk.Next();
                while (this.chunk.Code != 0)
                {
                    switch (this.chunk.Code)
                    {
                        case 5:
                            endSequenceHandle = this.chunk.ReadHex();
                            this.chunk.Next();
                            break;
                        case 8:
                            // the EndSquence layer and the Insert layer are the same
                            this.chunk.Next();
                            break;
                        default:
                            this.chunk.Next();
                            break;
                    }
                }
            }

            // It is a lot more intuitive to give the position in world coordinates and then define the orientation with the normal.
            Vector3 wcsBasePoint = MathHelper.Transform(basePoint, normal, CoordinateSystem.Object, CoordinateSystem.World);
            Insert insert = new Insert(attributes)
            {
                Block = block,
                Position = wcsBasePoint,
                Rotation = rotation,
                Scale = scale,
                Normal = normal
            };
            insert.EndSequence.Handle = endSequenceHandle;
            insert.XData.AddRange(xData);

            // post process nested inserts
            if (isBlockEntity)
                this.nestedInserts.Add(insert, blockName);

            return insert;
        }
Esempio n. 37
0
        public static void ModifyingGroups()
        {
            Line line1 = new Line(new Vector2(0, 0), new Vector2(100, 100));
            line1.Color = AciColor.Red;
            Line line2 = new Line(new Vector2(100, 0), new Vector2(200, 100));
            line2.Color = AciColor.Yellow;
            Line line3 = new Line(new Vector2(200, 0), new Vector2(300, 100));
            line3.Color = AciColor.Magenta;

            DxfDocument doc = new DxfDocument();

            Block blk = new Block("MyBlock");
            blk.Entities.Add(line1);
            Insert ins = new Insert(blk);
            doc.AddEntity(ins);

            doc.AddEntity(line2);

            Layout layout = new Layout("Layout1");
            doc.Layouts.Add(layout);
            doc.ActiveLayout = layout.Name;
            doc.AddEntity(line3);
            
            // group
            Group group = new Group("MyGroup");
            doc.Groups.Add(group);

            // the Add method will also add the entities contained in a group to the document (in the active layout).
            doc.Groups.Add(group);

            // when the group belongs to a document, all entities must belong to the same document.
            // even if it does not sound very useful, a group can contain entities that belongs to different layouts and even blocks.
            group.Entities.Add(line1);
            group.Entities.Add(line2);
            group.Entities.Add(line3);

            Line line4 = new Line(new Vector2(300, 0), new Vector2(400, 100));
            line4.Color = AciColor.Blue;
            // if a new entity, that does not belong to any document, is added to the group, it will be added to the group document active layout.
            doc.ActiveLayout = Layout.ModelSpaceName;
            group.Entities.Add(line4);

            Line line5 = new Line(new Vector2(400, 0), new Vector2(500, 100));
            line5.Color = AciColor.Green;
            DxfDocument doc2 = new DxfDocument();
            doc2.AddEntity(line5);

            // this is illegal, line5 belongs to another document.
            //group.Entities.Add(line5);
            // you need to clone the entity before adding it to the group. This is also the common practice to copy entities between documents.
            group.Entities.Add((EntityObject) line5.Clone());

            // remember removing a group only deletes it from the collection not the entities
            //doc.Groups.Remove(group);
            doc.Save("group.dxf");

            doc = DxfDocument.Load("group.dxf");
        }
Esempio n. 38
0
        private static void BlockWithAttributes()
        {
            DxfDocument dxf = new DxfDocument();
            Block block = new Block("BlockWithAttributes");
            block.Layer = new Layer("BlockSample");
            // It is possible to change the block position, even though it is recommended to keep it at Vector3.Zero,
            // since the block geometry is expressed in local coordinates of the block.
            // The block position defines the base point when inserting an Insert entity.
            block.Origin = new Vector3(10, 5, 0);

            // create an attribute definition, the attDef tag must be unique as it is the way to identify the attribute.
            // even thought AutoCad allows multiple attribute definition in block definitions, it is not recommended
            AttributeDefinition attdef = new AttributeDefinition("NewAttribute");
            // this is the text prompt shown to introduce the attribute value when a new Insert entity is inserted into the drawing
            attdef.Prompt = "InfoText";
            // optionally we can set a default value for new Insert entities
            attdef.Value = 0;
            // the attribute definition position is in local coordinates to the Insert entity to which it belongs
            attdef.Position = new Vector3(1, 1, 0);

            // modifying directly the text style might not get the desired results. Create one or get one from the text style table, modify it and assign it to the attribute text style.
            // one thing to note, if there is already a text style with the assigned name, the existing one in the text style table will override the new one.
            //attdef.Style.IsVertical = true;

            TextStyle txt = new TextStyle("MyStyle", "Arial.ttf");
            txt.IsVertical = true;
            attdef.Style = txt;
            attdef.WidthFactor = 2;
            // not all alignment options are available for TTF fonts 
            attdef.Alignment = TextAlignment.MiddleCenter;
            attdef.Rotation = 90;

            // remember, netDxf does not allow adding attribute definitions with the same tag, even thought AutoCad allows this behavior, it is not recommended in anyway.
            // internally attributes and their associated attribute definitions are handled through dictionaries,
            // and the tags work as ids to easily identify the information stored in the attribute value.
            // When reading a file the attributes or attribute definitions with duplicate tags will be automatically removed.
            // This is subject to change on public demand, it is possible to reimplement this behavior with simple collections to allow for duplicate tags.
            block.AttributeDefinitions.Add(attdef);

            // The entities list defines the actual geometry of the block, they are expressed in th block local coordinates
            Line line1 = new Line(new Vector3(-5, -5, 0), new Vector3(5, 5, 0));
            Line line2 = new Line(new Vector3(5, -5, 0), new Vector3(-5, 5, 0));
            block.Entities.Add(line1);
            block.Entities.Add(line2);

            // You can check the entity ownership with:
            Block line1Owner = line1.Owner;
            Block line2Owner = line2.Owner;
            // in this example line1Oner = line2Owner = block
            // As explained in the PaperSpace() sample, the layout associated with a common block will always be null
            Layout associatedLayout = line1.Owner.Record.Layout;
            // associatedLayout = null

            // create an Insert entity with the block definition, during the initialization the Insert attributes list will be created with the default attdef properties
            Insert insert1 = new Insert(block)
            {
                Position = new Vector3(5, 5, 5),
                Normal = new Vector3(1, 1, 1),
                Rotation = 45
            };

            // When the insert position, rotation, normal and/or scale are modified we need to transform the attributes.
            // It is not recommended to manually change the attribute position and orientation and let the Insert entity handle the transformations to maintain them in the same local position.
            // In this particular case we have changed the position, normal and rotation.
            insert1.TransformAttributes();
            
            // Once the insert has been created we can modify the attributes properties, the list cannot be modified only the items stored in it
            insert1.Attributes[0].Value = 24;

            // Modifying directly the layer might not get the desired results. Create one or get one from the layers table, modify it and assign it to the insert
            // One thing to note, if there is already a layer with the same name, the existing one in the layers table will override the new one, when the entity is added to the document.
            Layer layer = new Layer("MyInsertLayer");
            layer.Color.Index = 4;

            // optionally we can add the new layer to the document, if not the new layer will be added to the Layers collection when the insert entity is added to the document
            // in case a new layer is found in the list the add method will return the layer already stored in the list
            // this behavior is similar for all TableObject elements, all table object names must be unique (case insensitive)
            layer = dxf.Layers.Add(layer);

            // assign the new layer to the insert
            insert1.Layer = layer;

            // add the entity to the document
            dxf.AddEntity(insert1);

            // create a second insert entity
            // the constructor will automatically reposition the insert2 attributes to the insert local position
            Insert insert2 = new Insert(block, new Vector3(10, 5, 0));

            // as before now we can change the insert2 attribute value
            insert2.Attributes[0].Value = 34;

            // additionally we can insert extended data information
            XData xdata1 = new XData(new ApplicationRegistry("netDxf"));
            xdata1.XDataRecord.Add(new XDataRecord(XDataCode.String, "extended data with netDxf"));
            xdata1.XDataRecord.Add(XDataRecord.OpenControlString);
            xdata1.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionX, 0.0));
            xdata1.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionY, 0.0));
            xdata1.XDataRecord.Add(new XDataRecord(XDataCode.WorldSpacePositionZ, 0.0));
            xdata1.XDataRecord.Add(XDataRecord.CloseControlString);

            insert2.XData.Add(xdata1);
            dxf.AddEntity(insert2);

            // all entities support this feature
            XData xdata2 = new XData(new ApplicationRegistry("MyApplication1"));
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.String, "extended data with netDxf"));
            xdata2.XDataRecord.Add(XDataRecord.OpenControlString);
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.String, "string record"));
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.Real, 15.5));
            xdata2.XDataRecord.Add(new XDataRecord(XDataCode.Int32, 350));
            xdata2.XDataRecord.Add(XDataRecord.CloseControlString);

            // multiple extended data entries might be added
            XData xdata3 = new XData(new ApplicationRegistry("MyApplication2"));
            xdata3.XDataRecord.Add(new XDataRecord(XDataCode.String, "extended data with netDxf"));
            xdata3.XDataRecord.Add(XDataRecord.OpenControlString);
            xdata3.XDataRecord.Add(new XDataRecord(XDataCode.String, "string record"));
            xdata3.XDataRecord.Add(new XDataRecord(XDataCode.Real, 15.5));
            xdata3.XDataRecord.Add(new XDataRecord(XDataCode.Int32, 350));
            xdata3.XDataRecord.Add(XDataRecord.CloseControlString);

            Circle circle = new Circle(Vector3.Zero, 5);
            circle.Layer = new Layer("MyCircleLayer");
            // AutoCad 2000 does not support true colors, in that case an approximated color index will be used instead
            circle.Layer.Color = new AciColor(Color.MediumSlateBlue);
            circle.XData.Add(xdata2);
            circle.XData.Add(xdata3);

            dxf.AddEntity(circle);

            dxf.Save("BlockWithAttributes.dxf");
            DxfDocument dxfLoad = DxfDocument.Load("BlockWithAttributes.dxf");
        }