void InputTail() { asc = UT.GetAnnoScale("CANNOSCALE"); var sset_poly = Input.Objects("Выберите полилинию-хвост. Прикрепление будет к начальной точке"); if (Input.StatusOK) { using (var th = new TransactionHelper()) { try { var pl = th.EditObjects(sset_poly)[0] as Polyline; tail_default = pl.Clone() as Polyline; } catch (System.Exception) { InputTail(); return; } var p1 = Input.Point("Укажите базовую точку"); var p2 = Input.Point("Укажите направление Х"); var p1p2v = p1.Subtract(p2.GetAsVector()).GetAsVector(); tail_default.TransformBy(Matrix3d.AlignCoordinateSystem(p1, p1p2v.DivideBy(p1p2v.Length), p1p2v.GetPerpendicularVector(), Vector3d.ZAxis, Point3d.Origin, Vector3d.XAxis, Vector3d.YAxis, Vector3d.ZAxis)); tail_default.TransformBy(Matrix3d.Scaling(asc.Scale, Point3d.Origin)); } } }
/// <summary> /// Adds a scale to the scalelist if it doesnt exits /// </summary> /// <param name="scaleName"></param> /// <param name="pUnits"></param> /// <param name="dwgUnits"></param> private static void AddScale(string scaleName, int pUnits, int dwgUnits) { try { var cm = Application.DocumentManager.CurrentDocument.Database.ObjectContextManager; // Now get the Annotation Scaling context collection // (named ACDB_ANNOTATIONSCALES_COLLECTION) var occ = cm?.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (occ != null) { if (!occ.HasContext(scaleName)) { // Create a brand new scale context var asc = new AnnotationScale { Name = scaleName, PaperUnits = pUnits, DrawingUnits = dwgUnits }; // Add it to the drawing's context collection occ.AddContext(asc); } } } catch (Exception) { //Ignored } }
static Line Tail(Vector2d direction, AnnotationScale scale, Point2d location, LeftRight leftright) { Line source; try { source = sourceTails[scale.Name]; } catch (KeyNotFoundException) { Messaging.Tweet("Хвосты для данного масштаба не поддерживаются"); return(null); } Matrix3d transform = Matrix3d.Scaling(scale.DrawingUnits / scale.PaperUnits, Point3d.Origin); Line transformed = (Line)source.GetTransformedCopy(transform); var temp_y = transformed.EndPoint.Y; var temp_x = transformed.EndPoint.X * (int)leftright; transformed.EndPoint = new Point3d(temp_x, temp_y, 0); Matrix3d orientation = Matrix3d.Rotation(direction.Angle, Vector3d.ZAxis, Point3d.Origin); var oriented = (Line)transformed.GetTransformedCopy(orientation); Matrix3d offset = Matrix3d.Displacement(new Vector3d(location.X, location.Y, 0)); var displaced = (Line)oriented.GetTransformedCopy(offset); return(displaced); }
public CartogrammLabels(SimpleGride gride) { _gride = gride; TopRow = new List <TableField>(); BottomRow = new List <TableField>(); PreTopRow = new List <TableField>(); AmountTopRow = new List <TableField>(); PreBottomRow = new List <TableField>(); AmountBottomRow = new List <TableField>(); ObjectContextManager ocm = HostApplicationServices.WorkingDatabase.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); _scale = (AnnotationScale)occ.CurrentContext; _tableRowHeight /= _scale.Scale; _firstColumnWidth /= _scale.Scale; _preOrPostColumnWidth /= _scale.Scale; _tableTextHeight /= _scale.Scale; _grideTextHeight /= _scale.Scale; _volumeTextHeight /= _scale.Scale; _horizontalVector = gride.HorizontalVector; _verticalVector = gride.VerticalVector; }
void Init() { acDoc = App.DocumentManager.MdiActiveDocument; acCurDb = acDoc.Database; acEd = acDoc.Editor; mLeader = new MLeader(); asc = UT.GetAnnoScale("CANNOSCALE"); }
/// <inheritdoc/> protected override void ProcessScaleChange(AnnotationScale oldScale, AnnotationScale newScale) { base.ProcessScaleChange(oldScale, newScale); if (oldScale != null && newScale != null) { if (MainSettings.Instance.AxisLineTypeScaleProportionScale) { LineTypeScale = LineTypeScale * newScale.GetNumericScale() / oldScale.GetNumericScale(); } } }
public static bool FixAnnotationScale(this Database db, AnnotationScale annoScale, double scale) { var annoFactor = annoScale.PaperUnits / annoScale.DrawingUnits; var checkFactor = 1 / scale; if (Math.Abs(annoFactor - checkFactor) > 0.0001) { annoScale.PaperUnits = 1; annoScale.DrawingUnits = scale; return(true); } return(false); }
/// <summary> /// Initializes a new instance of the <see cref="SmartEntityProperty"/> class. /// </summary> /// <param name="attribute">Атрибут <see cref="EntityPropertyAttribute"/></param> /// <param name="entityType">Тип интеллектуального объекта</param> /// <param name="value">Значение свойства</param> /// <param name="ownerObjectId">Идентификатор блока</param> public SmartEntityProperty( EntityPropertyAttribute attribute, Type entityType, object value, ObjectId ownerObjectId) { EntityType = entityType; OwnerObjectId = ownerObjectId; Category = attribute.Category; OrderIndex = attribute.OrderIndex; Name = attribute.Name; DisplayNameLocalizationKey = attribute.DisplayNameLocalizationKey; NameSymbolForStyleEditor = attribute.NameSymbol; DescriptionLocalizationKey = attribute.DescriptionLocalizationKey; if (value != null && value.GetType() == typeof(AnnotationScale)) { DefaultValue = new AnnotationScale { Name = attribute.DefaultValue.ToString(), DrawingUnits = double.Parse(attribute.DefaultValue.ToString().Split(':')[0]), PaperUnits = double.Parse(attribute.DefaultValue.ToString().Split(':')[1]) }; } else if (Name == "LayerName" && string.IsNullOrEmpty(attribute.DefaultValue.ToString())) { DefaultValue = ModPlusAPI.Language.GetItem("defl"); } else { DefaultValue = attribute.DefaultValue; } Minimum = attribute.Minimum; Maximum = attribute.Maximum; Value = value; if (value is double d) { DoubleValue = d; } if (value is int i) { IntValue = i; } PropertyScope = attribute.PropertyScope; IsReadOnly = attribute.IsReadOnly; }
/// <summary> /// Добавление масштаба аннотаций в чертеже /// </summary> /// <param name="db">Чертеж</param> /// <param name="nameScale">Имя масштаба</param> /// <param name="scale">Масштаб - 1:scale, PaperUnits=1, DrawingUnits=scale</param> /// <returns>True - масштаб создан. False - такое имя масштаба уже есть (без проверки scale)</returns> public static bool AddAnnotationScale(this Database db, string nameScale, double scale) { var occ = db.ObjectContextManager.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (!occ.HasContext(nameScale)) { var annoScale = new AnnotationScale { Name = nameScale, PaperUnits = 1, DrawingUnits = scale }; occ.AddContext(annoScale); return(true); } return(false); }
/// <summary> /// 为图形添加一个新的注释比例 /// </summary> /// <param name="db">图形数据库对象</param> /// <param name="scaleName">缩放比例名</param> /// <param name="paperUnits">缩放比例的图纸单位</param> /// <param name="drawingUnits">缩放比例的图形单位</param> /// <returns>返回添加的注释比例</returns> public static AnnotationScale AddScale(this Database db, string scaleName, double paperUnits, double drawingUnits) { AnnotationScale scale = null;//声明一个注释比例对象 //获取当前图形的对象比例管理器 ObjectContextManager ocm = db.ObjectContextManager; //获取当前图形的注释比例列表,名为ACDB_ANNOTATIONSCALES ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); //如果没有名为scaleName的注释比例 if (!occ.HasContext(scaleName)) { scale = new AnnotationScale(); //新建一个注释比例对象 scale.Name = scaleName; //注释比例名 scale.PaperUnits = paperUnits; //注释比例的图纸单位 scale.DrawingUnits = drawingUnits; //注释比例的图形单位 occ.AddContext(scale); //将scaleName注释比例添加比例列表中 } return(scale); //返回scaleName注释比例对象 }
private DBText _createDBText(Point3d alignmentPoint, double height) { ObjectContextManager ocm = HostApplicationServices.WorkingDatabase.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); AnnotationScale scale = (AnnotationScale)occ.CurrentContext; DBText text = new DBText(); text.SetDatabaseDefaults(); text.Height = height; /* * scale.DrawingUnits/ scale.PaperUnits;*/ text.Annotative = AnnotativeStates.False; text.Rotation = _textRotation; text.Position = Point3d.Origin; text.HorizontalMode = TextHorizontalMode.TextMid; text.VerticalMode = TextVerticalMode.TextVerticalMid; text.AlignmentPoint = alignmentPoint; //text.AddContext(occ.CurrentContext); text.AdjustAlignment(HostApplicationServices.WorkingDatabase); return(text); }
/// <summary> /// Парсинг аннотативного масштаба из строки /// </summary> /// <param name="str">Строка с масштабом</param> public static AnnotationScale AnnotationScaleFromString(string str) { var defaultScale = new AnnotationScale { Name = "1:1", DrawingUnits = 1.0, PaperUnits = 1.0 }; var splitted = str.Split(':'); if (splitted.Length == 2) { var scale = new AnnotationScale { Name = str, PaperUnits = double.TryParse(splitted[0], out var d) ? d : 1.0, DrawingUnits = double.TryParse(splitted[1], out d) ? d : 1.0 }; return(scale); } return(defaultScale); } }
private void SetStyleAnnotative(DimStyleTableRecord[] resultStyleName, DBObject item, Dimension y) { AnnotationScale mainScale = new AnnotationScale(); ObjectContextManager ocm = targetDB.ObjectContextManager; double scale = 2.5 / (y.Dimscale * y.Dimtxt); double difference = 200; if (ocm != null) { ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); ObjectContext currentContext = occ.CurrentContext; foreach (ObjectContext context in occ) { double currentDifference = 200; AnnotationScale annotScale = (AnnotationScale)context; if (annotScale.Scale == scale) { mainScale = annotScale; break; } else { currentDifference = Math.Abs(scale - annotScale.Scale); if (currentDifference < difference) { difference = currentDifference; mainScale = annotScale; } } } SetStyleByType(resultStyleName, item, y); if (y.HasContext(currentContext)) { y.RemoveContext(currentContext); } y.AddContext(mainScale); y.Dimtxt = 2.5; } }
public static void SetAnnoScaleAndRemoveAllOther([NotNull] this Entity ent, AnnotationScale scale) { if (ent.Annotative != AnnotativeStates.True) { return; } if (!ent.IsWriteEnabled) { ent = ent.UpgradeOpenTr(); } var occ = ent.Database.GetAnnotationScales(); AddScaleAndRemoveOther(ent, scale, occ); if (ent is MLeader ml && ml.ContentType == ContentType.MTextContent) { var mt = ml.MText; if (mt.Annotative == AnnotativeStates.True) { AddScaleAndRemoveOther(mt, scale, occ); ml.MText = mt; } } }
/// <summary> /// Type "CANNOSCALE" to get current scale /// </summary> /// <param name="scalename"></param> /// <returns></returns> public static AnnotationScale GetAnnoScale(string scalename) { if (scalename == "CANNOSCALE") { scalename = App.GetSystemVariable("CANNOSCALE").ToString(); } Document acDoc = App.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; AnnotationScale asc = new AnnotationScale(); ObjectContextManager ocm = acCurDb.ObjectContextManager; if (ocm != null) { ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); if (occ != null) { asc = occ.GetContext(scalename) as AnnotationScale; } } return(asc); }
/// <summary> /// Установка аннотативности объекту и масштаба с удалением текущего масштаба чертежа. /// </summary> /// <param name="ent">Объект поддерживающий аннотативность (текст, размер и т.п.)</param> /// <param name="scale">Масштаб в виде 100, 25 и т.п.</param> public static void SetAnnotativeScale(this Entity ent, int scale) { // Проверка, есть ли нужный масштаб в чертеже string nameScale = string.Format("1:{0}", scale); ObjectContextManager ocm = ent.Database.ObjectContextManager; ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); ObjectContext contextAnnoScale; if (!occ.HasContext(nameScale)) { AnnotationScale annoScale = new AnnotationScale(); annoScale.Name = nameScale; annoScale.PaperUnits = 1; annoScale.DrawingUnits = scale; occ.AddContext(annoScale); contextAnnoScale = annoScale; } else { contextAnnoScale = occ.GetContext(nameScale); } ent.Annotative = AnnotativeStates.True; ent.AddContext(contextAnnoScale); ent.RemoveContext(ent.Database.Cannoscale); }
void CreateDimms() { asc = UT.GetAnnoScale("CANNOSCALE"); for (int i = 1; i < centers_projected.Count; i++) { RotatedDimension dim = new RotatedDimension(); if (i == 1) { current_dimm = centers_projected[i].DistanceTo(centers_projected[i - 1]); } if (i < centers_projected.Count - 1) { next_dim = centers_projected[i].DistanceTo(centers_projected[i + 1]); } else { next_dim = 0; } if (Math.Abs(next_dim - current_dimm) < Dim_tolerance && UniteDimms) //точность определения размеров { continue; //пропускаем выносные линии одинаковых размеров, если выбран режим объединения } //создние размера if (i - start_dim > 2) { //делаем корректировку, чтобы цифры шага и общего размера соответствовали, //потому что из-за низкой точности чертежа //может возникнуть ситуация типа 5х199=1000 int count = i - start_dim; double dim_max = centers_projected[i].DistanceTo(centers_projected[start_dim]); double dim_corrected = dim_max / count; dim.DimensionText = string.Format("{0}х{1:0}=<>", count, dim_corrected); } if (i - start_dim == 2) { //случай когда 2 одинаковых i--; } if (i == 1) { dim.XLine2Point = centers[start_dim]; dim.XLine1Point = centers[i]; if (tails) { dim.Dimtmove = 0; } else { dim.Dimtmove = 1; } } else if (i == centers_projected.Count - 1) { dim.XLine1Point = centers[start_dim]; dim.XLine2Point = centers[i]; if (tails) { dim.Dimtmove = 0; } else { dim.Dimtmove = 1; } } else { dim.XLine2Point = centers[start_dim]; dim.XLine1Point = centers[i]; dim.Dimtmove = 1; } dim.DimLinePoint = centers_projected[i]; dim.Rotation = DimDirection.Angle; dim.DimensionStyle = acCurDb.Dimstyle; dim.Annotative = AnnotativeStates.True; //сужаем тексты if (dim.Measurement < (asc.DrawingUnits / asc.PaperUnits) * 9 && dim.Measurement > (asc.DrawingUnits / asc.PaperUnits) * 4) { if (dim.DimensionText == null | dim.DimensionText == "") { dim.DimensionText = @"{\W0.6;<>}"; } else { dim.DimensionText = @"{\W0.6;" + dim.DimensionText + @"}"; } } //если размер маленький, сужаем dimensions.Add(dim); if (i < centers_projected.Count - 1) { current_dimm = centers_projected[i + 1].DistanceTo(centers_projected[i]); } start_dim = i; } }
/// <summary> /// Создание линий на основе двух отрезков со смещением центральной вершины /// </summary> /// <param name="InputFirst">первый отрезок</param> /// <param name="InputSecond">второй отрезок</param> void Make(Line InputFirst, Line InputSecond) { Tweet("Делаем два отрезка из двух отрезков"); Point3d S1; Point3d S2; Point3d E1; Point3d E2; Point3d middle; Point3d p1; Point3d p2; //выделяем 3 точки S1 = InputFirst.StartPoint; E1 = InputFirst.EndPoint; S2 = InputSecond.StartPoint; E2 = InputSecond.EndPoint; if (S1 == S2) { middle = S1; p1 = E1; p2 = E2; } else if (S1 == E2) { middle = S1; p1 = E1; p2 = S2; } else if (E1 == E2) { middle = E1; p1 = S1; p2 = S2; } else if (E1 == S2) { middle = E1; p1 = S1; p2 = E2; } else { p1 = Point3d.Origin; p2 = Point3d.Origin; middle = Point3d.Origin; Alert("Не совпадают концы отрезков"); status_ok = false; return; } AnnotationScale asc = UT.GetAnnoScale("CANNOSCALE"); Vector3d v1 = p1 - middle; Vector3d v2 = p2 - middle; if ((v1.Length == 0) || (v2.Length == 0)) { Alert("Нулевая длина отрезков"); return; } v1 = v1.MultiplyBy(1 / v1.Length); v2 = v2.MultiplyBy(1 / v2.Length); Vector3d v3 = v1.Add(v2); if (v3.Length == 0) { Alert("Отрезки параллельны"); return; } v3 = v3.MultiplyBy(currscale / (asc.Scale * v3.Length)); //находим длину биссектрисы double a, b, c, lb, p; Line p1p2 = new Line(p1, p2); a = InputFirst.Length; c = InputSecond.Length; b = p1p2.Length; p = (a + b + c) / 2; lb = 2 * Math.Sqrt(a * c * p * (p - b)) / (a + c); //приводим длину вектора к половине этой длины if (v3.Length >= lb * 0.5) { v3 = v3.MultiplyBy(lb * 0.5 / v3.Length); } middle = middle.Add(v3); //создаем 2 новые линии first = new Line(p1, middle); second = new Line(p2, middle); }
void Initialise() { geometry = new List <Entity>(); asc = UT.GetAnnoScale("CANNOSCALE"); }
/// <summary> /// Мультивыноска из объектов со стрелками на одной линии /// </summary> public void MakeArrowsInline() { base.Execute(); asc = UT.GetAnnoScale("CANNOSCALE"); var objects = new List <Entity>(); var points = new List <Point3d>(); Point3d p1, p2; Line p1p2; Vector3d offset = new Vector3d(2, 3.6, 0); var sset = Input.Objects("Выберите объекты"); if (Input.StatusBad) { return; } p1 = Input.Point("Выберите точку мультивыноски"); if (Input.StatusBad) { return; } p2 = Input.Point("Выберите точку для задания направления"); if (Input.StatusBad) { return; } p1p2 = new Line(p1, p2); Tweet("\nНачинаем транзакцию"); using (var th = new TransactionHelper()) { objects = th.ReadObjects(sset); Tweet("\nНачинаем поиск точек"); foreach (Entity ent in objects) { var pt_arr = UT.IntersectWith(p1p2, ent); if (pt_arr.Count > 0) { points.Add(pt_arr[0]); } } Tweet("\nНачинаем подготовку текста"); mtp = p1; text = "хх"; PrepareMtext(0); Tweet("\nНачинаем подготовку выноски"); MLeader mleader = new MLeader(); mleader.SetDatabaseDefaults(); mleader.ContentType = ContentType.MTextContent; mt.TransformBy(Matrix3d.Displacement(offset.DivideBy(asc.Scale))); mleader.MText = mt; Tweet("\nДобавляем линии"); foreach (Point3d ptt in points) { int idx = mleader.AddLeaderLine(p1); mleader.SetFirstVertex(idx, ptt); } Tweet("\nЗаписываем объекты"); th.WriteObject(mleader); } }
private void SetStyleAnnotative(DimStyleTableRecord[] resultStyleName, DBObject item, Dimension y) { AnnotationScale mainScale = new AnnotationScale(); ObjectContextManager ocm = targetDB.ObjectContextManager; double scale = 2.5 / (y.Dimscale * y.Dimtxt); double difference = 200; if (ocm != null) { ObjectContextCollection occ = ocm.GetContextCollection("ACDB_ANNOTATIONSCALES"); ObjectContext currentContext = occ.CurrentContext; foreach (ObjectContext context in occ) { double currentDifference = 200; AnnotationScale annotScale = (AnnotationScale)context; if (annotScale.Scale == scale) { mainScale = annotScale; break; } else { currentDifference = Math.Abs(scale - annotScale.Scale); if (currentDifference < difference) { difference = currentDifference; mainScale = annotScale; } } } SetStyleByType(resultStyleName, item, y); if (y.HasContext(currentContext)) y.RemoveContext(currentContext); y.AddContext(mainScale); y.Dimtxt = 2.5; } }
/// <summary> /// Возвращает численный масштаб (отношение единиц чертежа к единицам листа) /// </summary> /// <param name="scale">Аннотативный масштаб</param> public static double GetNumericScale(this AnnotationScale scale) { return(scale.DrawingUnits / scale.PaperUnits); }
/// <summary> /// Returns Scale Factor(1.0 / AnnotationScale.Scale) /// </summary> /// <param name="annoScale"></param> /// <returns>doubl that equals (1.0 / AnnotationScale.Scale)</returns> public static double GetScaleFactor(this AnnotationScale annoScale) { return(1.0 / annoScale.Scale); }
public DrawTails() { var sset_lines = Input.Objects("Выберите отрезки, на которых нужно нарисовать хвосты ", new string[] { "TAil", "ХВост", "SIde", "СТорона", "OFfset", "смеЩЕние" }, (s, e) => { if (e.Input == "TAil") { InputTail(); } if (e.Input == "SIde") { side *= -1; } if (e.Input == "OFfset") { offsetMode ^= 1; //switching 0 and 1 } }); if (Input.StatusBad) { return; } if (tail_default == null) { InputTail(); if (Input.StatusBad) { return; } } using (var th = new TransactionHelper()) { //забираем линии из выбора var lines = th.EditObjects(sset_lines).OfType <Line>().ToList(); //в новой версии хотим добавить обработку полилиний var polylines = th.EditObjects(sset_lines).OfType <Polyline>().ToList(); foreach (var ln in lines) { Point3d p1, p2; if (ln.Angle >= 0 && ln.Angle <= 3 * Math.PI / 4 || ln.Angle > 7 * Math.PI / 4) { p1 = ln.EndPoint; p2 = ln.StartPoint; } else { p2 = ln.EndPoint; p1 = ln.StartPoint; } var tail_scaled = tail_default.Clone() as Polyline; asc = UT.GetAnnoScale("CANNOSCALE"); tail_scaled.TransformBy(Matrix3d.Scaling(1 / asc.Scale, Point3d.Origin)); var pl_new = DrawTwoTails(p1, p2, tail_scaled); pl_new.SetPropertiesFrom(ln); th.WriteObject(pl_new); ln.Erase(); } foreach (var pl in polylines) { var tail_scaled = tail_default.Clone() as Polyline; asc = UT.GetAnnoScale("CANNOSCALE"); tail_scaled.TransformBy(Matrix3d.Scaling(1 / asc.Scale, Point3d.Origin)); var pl_new = TailsFromPolyline(pl, tail_scaled); pl_new.SetPropertiesFrom(pl); th.WriteObject(pl_new); pl.Erase(); } } }
/// <summary> /// Метод обработки события изменения масштаба /// </summary> /// <param name="oldScale">Старый масштаб</param> /// <param name="newScale">Новый масштаб</param> protected virtual void ProcessScaleChange(AnnotationScale oldScale, AnnotationScale newScale) { }