public static void Close() { Entity scene = share; share = null; scene?.Dispose(); }
public static void Close() { Entity?.Dispose(); Entity = null; EventSystem.Close(); ObjectPool.Close(); Hotfix.Close(); }
public virtual void LeaveWorld(Entity entity) { if (entity is Player) { Player dummy; Players.TryRemove(entity.Id, out dummy); PlayersCollision.Remove(entity); // if in trade, cancel it... if (dummy.tradeTarget != null) { dummy.CancelTrade(); } if (dummy.Pet != null) { LeaveWorld(dummy.Pet); } } else if (entity is Enemy) { Enemy dummy; Enemies.TryRemove(entity.Id, out dummy); EnemiesCollision.Remove(entity); if (entity.ObjectDesc.Quest) { Quests.TryRemove(entity.Id, out dummy); } } else if (entity is Projectile) { var p = entity as Projectile; Projectiles.TryRemove(new Tuple <int, byte>(p.ProjectileOwner.Self.Id, p.ProjectileId), out p); } else if (entity is StaticObject) { StaticObject dummy; StaticObjects.TryRemove(entity.Id, out dummy); if (entity.ObjectDesc?.BlocksSight == true) { if (Blocking == 3) { Sight.UpdateRegion(Map, (int)entity.X, (int)entity.Y); } foreach (var plr in Players.Values .Where(p => MathsUtils.DistSqr(p.X, p.Y, entity.X, entity.Y) < Player.RadiusSqr)) { plr.Sight.UpdateCount++; } } if (entity is Decoy) { PlayersCollision.Remove(entity); } else { EnemiesCollision.Remove(entity); } } else if (entity is Pet) { Pet dummy; Pets.TryRemove(entity.Id, out dummy); PlayersCollision.Remove(entity); } entity.Dispose(); }
public static void Breakatpoint() { Document acDoc = acApp.DocumentManager.MdiActiveDocument; Database acDb = acDoc.Database; Editor acEd = acDoc.Editor; PromptSelectionResult psr = acEd.GetSelection(); if (psr.Status != PromptStatus.OK) { return; } foreach (ObjectId id in psr.Value.GetObjectIds()) { using (Transaction acTrans = acDb.TransactionManager.StartTransaction()) { BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; Line line = (Line)acTrans.GetObject(id, OpenMode.ForRead); PromptPointResult pr = acEd.GetPoint("Select break point"); if (pr.Status != PromptStatus.Cancel) { ObjectId objId; Point3d pointPr = pr.Value; //Test to ensure that point selected actually lies on the line if (IsPointOnCurve(line, pointPr)) { //create new line from selected line start point to point chosen var lineseg = new LineSegment3d(line.StartPoint, pointPr); var vec = lineseg.Direction.MultiplyBy(2).Negate(); Line line_seg1 = new Line(line.StartPoint, pointPr.Add(vec)); line_seg1.Layer = line.Layer; objId = acBlkTblRec.AppendEntity(line_seg1); acTrans.AddNewlyCreatedDBObject(line_seg1, true); //create new line from point chosen to end point on selected line lineseg = new LineSegment3d(pointPr, line.EndPoint); vec = lineseg.Direction.MultiplyBy(2).Negate(); Line line_seg2 = new Line(pointPr.Subtract(vec), line.EndPoint); line_seg2.Layer = line.Layer; objId = acBlkTblRec.AppendEntity(line_seg2); acTrans.AddNewlyCreatedDBObject(line_seg2, true); //remove origionally selected line Entity acEnt = acTrans.GetObject(id, OpenMode.ForWrite) as Entity; acEnt.Erase(); acEnt.Dispose(); } else { MessageBox.Show("Point chosen does not lie on the line selected"); } } else { return; } acTrans.Commit(); } } }
public void JoinText() { var acObjList = new List <Entity>(); var acObjList_Mtext = new List <String>(); Document acDoc = acApp.DocumentManager.MdiActiveDocument; Database acCurDb = acDoc.Database; using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction()) { BlockTable acBlkTbl; acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, OpenMode.ForRead) as BlockTable; BlockTableRecord acBlkTblRec; acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord; // Request Mtext object to be selected PromptSelectionResult acSSPrompt = acDoc.Editor.GetSelection(); // If OK if (acSSPrompt.Status == PromptStatus.OK) { SelectionSet acSSet = acSSPrompt.Value; // Step through the objects foreach (SelectedObject acSSobj in acSSet) { // Check if valid if (acSSobj != null) { // Open object for read Entity acEnt = acTrans.GetObject(acSSobj.ObjectId, OpenMode.ForRead) as Entity; if (acEnt != null) { // Seperate out text and mtext entities if (acEnt.GetType() == typeof(MText) || acEnt.GetType() == typeof(DBText)) { // add entity to array acObjList.Add(acEnt); } } } } } if (acObjList.Count != 0) { //TO-DO: //iterate through acObjList if object is mtext save over to acObjMtext //if objuect is DBtext then convert to mtext and save over to acObjMtext MText acNewMText = new MText(); ObjectId objId; Point3d acPosition = new Point3d(); //get the insertion point of the new mtext block based on the first selected block of text //TO-DO in future figure out which text is the on top in the drawing and use that point if (acObjList[0].GetType() == typeof(DBText)) { DBText tempDBtext = acTrans.GetObject(acObjList[0].ObjectId, OpenMode.ForRead) as DBText; acPosition = tempDBtext.Position; } else if (acObjList[0].GetType() == typeof(MText)) { MText tempMtext = acTrans.GetObject(acObjList[0].ObjectId, OpenMode.ForRead) as MText; acPosition = tempMtext.Location; } else { acPosition = new Point3d(0, 0, 0); } //iterate though the list of entities and use properties of the first Mtext entity found //for the new mtext entity try { MText firstMtext = (MText)acObjList.Find(x => x.GetType() == typeof(MText)); //set relevant properties to the new mtext entity acNewMText.SetDatabaseDefaults(); acNewMText.Location = acPosition; acNewMText.TextHeight = firstMtext.TextHeight; acNewMText.TextStyleId = firstMtext.TextStyleId; acNewMText.Width = firstMtext.Width; acNewMText.Layer = firstMtext.Layer; } catch (System.Exception) { //set relevant properties to the new mtext entity MText firstMtext = new MText(); acNewMText.SetDatabaseDefaults(); acNewMText.Location = acPosition; } //iterate though each entity add the entities text to the acObjList_Mtext based on //if the entity is DBText or Mtext foreach (Entity acEnt in acObjList) { //test to see if acEnt is Mtext if (acEnt.GetType() == typeof(MText)) { //add text contents to acObjList_Mtest MText acMtextTemp = acTrans.GetObject(acEnt.ObjectId, OpenMode.ForRead) as MText; acObjList_Mtext.Add(acMtextTemp.Text); } //if acEnt is not mtext else if (acEnt.GetType() == typeof(DBText)) { //add text contents to acObjList_Mtext DBText acDBText = acTrans.GetObject(acEnt.ObjectId, OpenMode.ForWrite) as DBText; acObjList_Mtext.Add(acDBText.TextString); } } //check to make sure that the List acObjList_Mtext is not empty if (acObjList_Mtext.Count != 0) { //add all strings stored in acObjList_Mtext to the new acNewMtext entity string tempStr = ""; foreach (string str in acObjList_Mtext) { tempStr += str; tempStr += "\\P"; } acNewMText.Contents = tempStr; objId = acBlkTblRec.AppendEntity(acNewMText); acTrans.AddNewlyCreatedDBObject(acNewMText, true); } //remove initially selected objects from the database. for (int i = 0; i < acObjList.Count; i++) { Entity acEnt = acTrans.GetObject(acObjList[i].ObjectId, OpenMode.ForWrite) as Entity; acEnt.Erase(); acEnt.Dispose(); } acTrans.Commit(); } } }
private void Create3dProfile(object arg) { try { if (doc != null) { List <ObjectId> toHighlight = new List <ObjectId>(); using (doc.LockDocument()) { Editor ed = doc.Editor; Database db = doc.Database; using (Transaction tr = db.TransactionManager.StartTransaction()) { //найти координату X начала профиля (крайнюю левую) double minx = double.PositiveInfinity; List <ObjectId> allSelected = new List <ObjectId>(soilHatchIds); foreach (ObjectId id in allSelected) { Entity ent = null; try { ent = (Entity)tr.GetObject(id, OpenMode.ForRead); } catch (Autodesk.AutoCAD.Runtime.Exception) { continue; } Extents3d?ext = ent.Bounds; if (ext != null) { Point3d minPt = ext.Value.MinPoint; if (minx > minPt.X) { minx = minPt.X; } } } //Штриховки должны быть заранее раскиданы по слоям в соответствии с ИГЭ! //пересчет всех точек штриховок в координаты: //X - положение отностиельно начала профиля с учетом горизонтального масштаба профиля, //Y - отметка расчитанная согласно базовой отметке с учетом вертикального масштаба профиля Matrix2d transform = new Matrix2d(new double[] { HorScaling, 0, 0, 0, VertScaling, 0, 0, 0, 1 }) * Matrix2d.Displacement(new Vector2d(-minx, -ElevBasePoint.Value.Y + ElevationInput / VertScaling)); C5.IntervalHeap <HatchEvent> eventQueue = new C5.IntervalHeap <HatchEvent>(); List <HatchData> allHatchData = new List <HatchData>(); List <Point2dCollection> selfintersectingLoops = new List <Point2dCollection>(); foreach (ObjectId id in soilHatchIds) { //получить все точки штриховок с учетом возможных дуг, сплайнов и проч //Для каждой штриховки создается набор композитных кривых, состоящих из линейных сегментов Hatch hatch = null; try { hatch = (Hatch)tr.GetObject(id, OpenMode.ForRead); } catch (Autodesk.AutoCAD.Runtime.Exception) { continue; } List <CompositeCurve2d> boundaries = new List <CompositeCurve2d>(); List <Extents2d> extends = new List <Extents2d>(); List <Point2dCollection> ptsCollList = new List <Point2dCollection>(); List <List <double> > ptParamsList = new List <List <double> >(); for (int i = 0; i < hatch.NumberOfLoops; i++) { HatchLoop hl = hatch.GetLoopAt(i); if (!hl.LoopType.HasFlag(HatchLoopTypes.SelfIntersecting) && !hl.LoopType.HasFlag(HatchLoopTypes.Textbox) && !hl.LoopType.HasFlag(HatchLoopTypes.TextIsland) && !hl.LoopType.HasFlag(HatchLoopTypes.NotClosed)) { List <Curve2d> curves = Utils.GetHatchLoopCurves(hl); List <Curve2d> compositeCurveElems = new List <Curve2d>(); double _minx = double.PositiveInfinity; double _miny = double.PositiveInfinity; double _maxx = double.NegativeInfinity; double _maxy = double.NegativeInfinity; Action <Point2d> updateExtends = new Action <Point2d>(p => { _minx = p.X < _minx ? p.X : _minx; _miny = p.Y < _miny ? p.Y : _miny; _maxx = p.X > _maxx ? p.X : _maxx; _maxy = p.Y > _maxy ? p.Y : _maxy; }); Point2dCollection ptsColl = new Point2dCollection(); List <double> ptParams = new List <double>(); double currParam = 0; foreach (Curve2d c in curves) { if (!(c is LineSegment2d)) { Interval interval = c.GetInterval(); PointOnCurve2d[] samplePts = c.GetSamplePoints(interval.LowerBound, interval.UpperBound, 0.02); Point2d[] pts = samplePts.Select(p => transform * p.Point).ToArray(); for (int n = 0; n < pts.Length - 1; n++) { LineSegment2d lineSeg = new LineSegment2d(pts[n], pts[n + 1]); compositeCurveElems.Add(lineSeg); ptsColl.Add(pts[n]); ptParams.Add(currParam); updateExtends(pts[n]); currParam += lineSeg.Length; } } else { LineSegment2d lineSeg = (LineSegment2d)c; lineSeg.TransformBy(transform); compositeCurveElems.Add(lineSeg); ptsColl.Add(lineSeg.StartPoint); ptParams.Add(currParam); updateExtends(lineSeg.StartPoint); currParam += lineSeg.Length; } } CompositeCurve2d boundary = new CompositeCurve2d(compositeCurveElems.ToArray()); Extents2d ext = new Extents2d(_minx, _miny, _maxx, _maxy); boundaries.Add(boundary); ptsCollList.Add(ptsColl); ptParamsList.Add(ptParams); extends.Add(ext); } } //контуры штриховок не могут иметь самопересечений! #region Проверка на пересечения //проверка на самопересечения //bool badBoundaries = false; HashSet <int> badBoundaries = new HashSet <int>(); HashSet <int> splitBoundaries = new HashSet <int>();//Если 2 контура в одной штриховке пересекаются, то разносить их по разным штриховкам //List<HatchData> decomposeHatchData = new List<HatchData>();//TODO: самопересекающиеся полигоны нужно разбить на отдельные по количеству самопересечний. for (int i = 0; i < boundaries.Count; i++) { CompositeCurve2d b = boundaries[i]; CurveCurveIntersector2d intersector = new CurveCurveIntersector2d(b, b); if (intersector.NumberOfIntersectionPoints > 0) { //если происходит только наложение??? badBoundaries.Add(i); selfintersectingLoops.Add(ptsCollList[i]); } } if (boundaries.Count > 1) { //проверка на взаимные пересечения. //Исп RBush для того чтобы избежать проверки на пересечение каждого с каждым и квадратичной сложности //(работает только если контуры разнесены) //Не брать в расчет пересечения по касательной RBush <Spatial> boundariesRBush = new RBush <Spatial>(); List <Spatial> spatialData = new List <Spatial>(); for (int i = 0; i < extends.Count; i++) { spatialData.Add(new Spatial(extends[i], i)); } boundariesRBush.BulkLoad(spatialData); foreach (Spatial s in spatialData) { IReadOnlyList <Spatial> nearestNeighbors = boundariesRBush.Search(s.Envelope); if (nearestNeighbors.Count > 1) { CompositeCurve2d thisCurve = boundaries[(int)s.Obj]; foreach (Spatial n in nearestNeighbors) { if (!s.Equals(n)) { CompositeCurve2d otherCurve = boundaries[(int)n.Obj]; CurveCurveIntersector2d intersector = new CurveCurveIntersector2d(thisCurve, otherCurve); if (intersector.NumberOfIntersectionPoints > 0 || intersector.OverlapCount > 0) { bool matches = false; //Проверить, что кривые не накладываются друг на друга по всей длине (то есть полностью совпадают) if (intersector.OverlapCount > 0) { //сумма длин всех интервалов перекрытия равна общей длине кривой double thisCurveOverlapLength = 0; double otherCurveOverlapLength = 0; for (int i = 0; i < intersector.OverlapCount; i++) { Interval[] intervals = intersector.GetOverlapRanges(i); Interval thisOverlapInterval = intervals[0]; thisCurveOverlapLength += thisOverlapInterval.Length; Interval otherOverlapInterval = intervals[1]; otherCurveOverlapLength += otherOverlapInterval.Length; } Interval thisCurveInterval = thisCurve.GetInterval(); Interval otherCurveInterval = otherCurve.GetInterval(); if (Utils.LengthIsEquals(thisCurveOverlapLength, thisCurveInterval.Length) && Utils.LengthIsEquals(otherCurveOverlapLength, otherCurveInterval.Length)) { matches = true; } } if (!matches) { splitBoundaries.Add((int)s.Obj); splitBoundaries.Add((int)n.Obj); } else { badBoundaries.Add((int)s.Obj); badBoundaries.Add((int)n.Obj); } } } } } } } splitBoundaries.ExceptWith(badBoundaries); List <HatchData> splitHatchData = new List <HatchData>(); if (badBoundaries.Count > 0 || splitBoundaries.Count > 0) { List <CompositeCurve2d> boundariesClear = new List <CompositeCurve2d>(); List <Extents2d> extendsClear = new List <Extents2d>(); List <Point2dCollection> ptsCollListClear = new List <Point2dCollection>(); List <List <double> > ptParamsListClear = new List <List <double> >(); for (int i = 0; i < boundaries.Count; i++) { if (!badBoundaries.Contains(i) && !splitBoundaries.Contains(i)) { boundariesClear.Add(boundaries[i]); extendsClear.Add(extends[i]); ptsCollListClear.Add(ptsCollList[i]); ptParamsListClear.Add(ptParamsList[i]); } } foreach (int index in splitBoundaries) { splitHatchData.Add(new HatchData( new HatchNestingNode( boundaries[index], extends[index], ptsCollList[index], ptParamsList[index], hatch))); } boundaries = boundariesClear; extends = extendsClear; ptsCollList = ptsCollListClear; ptParamsList = ptParamsListClear; } #endregion //определяется вложенность контуров штриховки //ЕСЛИ ШТРИХОВКА СОСТОИТ ИЗ 2 И БОЛЕЕ КОНТУРОВ, КОТОРЫЕ НЕ ВЛОЖЕНЫ ДРУГ В ДРУГА, //ТО ЭТИ КОНТУРЫ ДОЛЖНЫ РАССМАТРИВАТЬСЯ КАК ОТДЕЛЬНЫЕ ШТРИХОВКИ!!! HatchNestingTree hatchNestingTree = new HatchNestingTree(boundaries, extends, ptsCollList, ptParamsList, hatch); List <HatchData> currHatchData = hatchNestingTree.GetHatchData(); currHatchData.AddRange(splitHatchData);//добавить контуры, полученные из взаимно пересекающихся контуров //currHatchData.AddRange(decomposeHatchData); allHatchData.AddRange(currHatchData); //Каждая штриховка имеет диапазон по X от начала до конца по оси. //В общую очередь событий сохраняются события начала и конца штриховки foreach (HatchData hd in currHatchData) { hd.AddEventsToQueue(eventQueue); } } //Трассу разбить на отрезки, на которых будут вставлены прямолинейные сегменты штриховок Polyline alignmentPoly = null; try { alignmentPoly = (Polyline)tr.GetObject(AlignmentPolyId, OpenMode.ForRead); } catch (Autodesk.AutoCAD.Runtime.Exception) { return; } int segments = alignmentPoly.NumberOfVertices - 1; List <AlignmentSegment> alignmentSegments = new List <AlignmentSegment>(); Action <Point2d, Point2d> addAlignmentSegment = new Action <Point2d, Point2d>((p0, p1) => { double start = alignmentPoly.GetDistAtPoint(new Point3d(p0.X, p0.Y, 0)); double end = alignmentPoly.GetDistAtPoint(new Point3d(p1.X, p1.Y, 0)); if (Math.Abs(start - end) > Tolerance.Global.EqualPoint)//TODO: Это спорный момент - ведь может быть большое множество очень коротких участков подряд! { Vector2d startDir = p1 - p0; alignmentSegments.Add(new AlignmentSegment(start, end, p0, startDir)); } }); for (int i = 0; i < segments; i++) { SegmentType segmentType = alignmentPoly.GetSegmentType(i); Point2d startLoc = alignmentPoly.GetPoint2dAt(i); Point2d endLoc = alignmentPoly.GetPoint2dAt(i + 1); switch (segmentType) { case SegmentType.Line: addAlignmentSegment(startLoc, endLoc); break; case SegmentType.Arc: CircularArc2d arc = new CircularArc2d(startLoc, endLoc, alignmentPoly.GetBulgeAt(i), false); Interval interval = arc.GetInterval(); PointOnCurve2d[] samplePts = arc.GetSamplePoints(interval.LowerBound, interval.UpperBound, 0.1); for (int n = 0; n < samplePts.Length - 1; n++) { addAlignmentSegment(samplePts[n].Point, samplePts[n + 1].Point); } break; } } //проход по каждому отрезку трассы (диапазон отрезка - диапазон длины полилинии) HashSet <HatchData> currentHatchData = new HashSet <HatchData>(); foreach (AlignmentSegment alignmentSegment in alignmentSegments) { if (eventQueue.Count == 0) { break; //штриховки закончились } //Получить те штриховки, диапазон по X которых пересекается с диапазоном текущего отрезка //(СКАНИРУЮЩАЯ ЛИНИЯ: события - начало, конец штриховки) HashSet <HatchData> intervalHatchData = new HashSet <HatchData>(currentHatchData);//штриховки пришедшие из предыдущего участка остаются все //Собрать все события до конца сегмента //Если при проходе от начала до конца сегмента какая-то штриховка проходится полностью от начала до конца, то //все ее контуры без изменений должны быть переданы для создания М-полигона!!! (для них обход графа не нужен!) HashSet <HatchData> startedInsideInterval = new HashSet <HatchData>(); List <HatchData> hatchesCompletelyInsideInterval = new List <HatchData>(); while (eventQueue.Count > 0) { HatchEvent nextEvent = eventQueue.FindMin(); if (nextEvent.Position > alignmentSegment.End) { break; } else if (nextEvent.Start) { //добавить штриховку в текущий набор HatchData hd = eventQueue.DeleteMin().HatchData; currentHatchData.Add(hd); //добавлять в набор текущего интервла только в том случае, //если сканирующая линия еще не дошла до конца интервала if (nextEvent.Position < alignmentSegment.End && !Utils.LengthIsEquals(nextEvent.Position, alignmentSegment.End)) //Допуск нужен { startedInsideInterval.Add(hd); intervalHatchData.Add(hd); } } else { //убрать штриховку из текущего набора HatchData hd = eventQueue.DeleteMin().HatchData; currentHatchData.Remove(hd); if (startedInsideInterval.Contains(hd)) { hatchesCompletelyInsideInterval.Add(hd); } } } foreach (HatchData hd in hatchesCompletelyInsideInterval) { HatchSegmentData hsd = new HatchSegmentData(hd); alignmentSegment.HatchSegmentData.Add(hsd); hsd.Polygons = hd.GetAllBoundaries(); } intervalHatchData.ExceptWith(hatchesCompletelyInsideInterval); foreach (HatchData hd in intervalHatchData) { HatchSegmentData hsd = new HatchSegmentData(hd); alignmentSegment.HatchSegmentData.Add(hsd); //для каждой штриховки выполнить построение и обход графа сегмента штриховки HatchSegmentGraph graph = new HatchSegmentGraph(alignmentSegment.Start, alignmentSegment.End, hd, doc.Editor); //сохранить наборы полигонов для текущего диапазона hsd.Polygons = graph.Result; } } //для каждого диапазона создать полученные полигоны в 3d BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForWrite) as BlockTable; BlockTableRecord ms = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite); BlockTableRecord btr = new BlockTableRecord();//Каждый профиль в отдельный блок btr.Name = Guid.NewGuid().ToString(); ObjectId btrId = bt.Add(btr); tr.AddNewlyCreatedDBObject(btr, true); foreach (AlignmentSegment alignmentSegment in alignmentSegments) { List <Entity> flatObjs = new List <Entity>(); foreach (HatchSegmentData hsd in alignmentSegment.HatchSegmentData) { //PlaneSurface hsd.GetNesting(); Dictionary <Point2dCollection, List <Point2dCollection> > bwhs = hsd.GetBoundariesWithHoles(); foreach (KeyValuePair <Point2dCollection, List <Point2dCollection> > bwh in bwhs) { //создать Region Region region = null; using (Polyline poly = new Polyline()) { for (int i = 0; i < bwh.Key.Count; i++) { poly.AddVertexAt(i, bwh.Key[i], 0, 0, 0); } poly.Closed = true; DBObjectCollection coll = new DBObjectCollection(); coll.Add(poly); try { DBObjectCollection regionColl = Region.CreateFromCurves(coll); foreach (DBObject dbo in regionColl) { region = (Region)dbo; break; } } catch { } } //из Region создать PlaneSurface if (region != null) { using (PlaneSurface planeSurface = new PlaneSurface()) { planeSurface.CreateFromRegion(region); planeSurface.LayerId = hsd.Hatch.LayerId; planeSurface.ColorIndex = 256; ObjectId planeSurfaceId = ms.AppendEntity(planeSurface); tr.AddNewlyCreatedDBObject(planeSurface, true); //вырезать отверстия в PlaneSurface foreach (Point2dCollection holePts2d in bwh.Value) { if (holePts2d.Count < 3) { continue; } using (Polyline poly = new Polyline()) { for (int i = 0; i < holePts2d.Count; i++) { poly.AddVertexAt(i, holePts2d[i], 0, 0, 0); } poly.Closed = true; ObjectIdCollection trimPolyColl = new ObjectIdCollection(); trimPolyColl.Add(ms.AppendEntity(poly)); tr.AddNewlyCreatedDBObject(poly, true); List <Point2d> ptsList = new List <Point2d>(holePts2d.ToArray()); Point2d pickPt2d = Utils.GetAnyPointInsidePoligon(ptsList, Utils.DirectionIsClockwise(ptsList)); try { AcadDB.Surface.TrimSurface(planeSurfaceId, new ObjectIdCollection(), trimPolyColl, new Vector3dCollection() { Vector3d.ZAxis }, new Point3d(pickPt2d.X, pickPt2d.Y, 0), -Vector3d.ZAxis, false, false); } catch /*(Exception ex)*/ { //Вывод в командную строку Utils.ErrorToCommandLine(doc.Editor, "Ошибка при попытке вырезания отверстия в поверхности" /*, ex*/); } //Удалить все объекты, добавленные в чертеж! poly.Erase(); } } flatObjs.Add((Entity)planeSurface.Clone()); //Удалить все объекты, добавленные в чертеж! planeSurface.Erase(); } region.Dispose(); } } } foreach (Entity ent in flatObjs) { ent.TransformBy(alignmentSegment.Transform); /*ms*/ btr.AppendEntity(ent); tr.AddNewlyCreatedDBObject(ent, true); ent.Dispose(); } } BlockReference br = new BlockReference(Point3d.Origin, btrId); ms.AppendEntity(br); tr.AddNewlyCreatedDBObject(br, true); if (selfintersectingLoops.Count > 0) { Utils.ErrorToCommandLine(doc.Editor, "Отбраковано самопересекающихся контуров штриховок - " + selfintersectingLoops.Count + " (отмечены на профиле)"); ObjectId layerId = Utils.CreateLayerIfNotExists("САМОПЕРЕСЕКАЮЩИЙСЯ КОНТУР ШТРИХОВКИ", db, tr, color: Color.FromColorIndex(ColorMethod.ByAci, 1), lineWeight: LineWeight.LineWeight200); Matrix2d returnTransform = transform.Inverse(); foreach (Point2dCollection pts in selfintersectingLoops) { using (Polyline selfIntersectingPoly = new Polyline()) { selfIntersectingPoly.LayerId = layerId; selfIntersectingPoly.ColorIndex = 256; for (int i = 0; i < pts.Count; i++) { Point2d pt = pts[i].TransformBy(returnTransform); selfIntersectingPoly.AddVertexAt(i, pt, 0, 0, 0); } toHighlight.Add(ms.AppendEntity(selfIntersectingPoly)); tr.AddNewlyCreatedDBObject(selfIntersectingPoly, true); //selfIntersectingPoly.Highlight(); } } } tr.Commit(); } } ps.Visible = false; if (toHighlight.Count > 0) { using (Transaction tr = doc.Database.TransactionManager.StartTransaction()) { foreach (ObjectId id in toHighlight) { Entity ent = (Entity)tr.GetObject(id, OpenMode.ForRead); ent.Highlight(); } tr.Commit(); } } } } catch (System.Exception ex) { GeologyConvertationCommand.ClosePalette(null, null); CommonException(ex, "Ошибка при создании 3d профиля геологии"); } }
public void Dispose() { _settingEntity?.Dispose(); _settingEntity = null; }
public virtual void LeaveWorld(Entity entity) { if (entity is Player) { Player dummy; Players.TryRemove(entity.Id, out dummy); PlayersCollision.Remove(entity); } else if (entity is Enemy) { Enemy dummy; Enemies.TryRemove(entity.Id, out dummy); EnemiesCollision.Remove(entity); if (entity.ObjectDesc.Quest) Quests.TryRemove(entity.Id, out dummy); if (entity.isPet) { Entity dummy2; Pets.TryRemove(entity.Id, out dummy2); } } else if (entity is Projectile) { var p = entity as Projectile; Projectiles.TryRemove(new Tuple<int, byte>(p.ProjectileOwner.Self.Id, p.ProjectileId), out p); } else if (entity is StaticObject) { StaticObject dummy; StaticObjects.TryRemove(entity.Id, out dummy); if (entity is Decoy) PlayersCollision.Remove(entity); else EnemiesCollision.Remove(entity); } entity.Owner = null; entity.Dispose(); }
public virtual void LeaveWorld(Entity entity) { if (entity is Player) { Player dummy; if (!Players.TryRemove(entity.Id, out dummy)) Log.WarnFormat("Could not remove {0} from world {1}", entity.Name, Name); PlayersCollision.Remove(entity); } else if (entity is Enemy) { Enemy dummy; Enemies.TryRemove(entity.Id, out dummy); EnemiesCollision.Remove(entity); if (entity.ObjectDesc.Quest) Quests.TryRemove(entity.Id, out dummy); } else { var projectile = entity as Projectile; if (projectile != null) { var p = projectile; Projectiles.TryRemove(new Tuple<int, byte>(p.ProjectileOwner.Self.Id, p.ProjectileId), out p); } else if (entity is StaticObject) { StaticObject dummy; StaticObjects.TryRemove(entity.Id, out dummy); if (entity is Decoy) PlayersCollision.Remove(entity); else EnemiesCollision.Remove(entity); } else if (entity is Pet) { if (entity.IsPet) { Pet dummy2; Pets.TryRemove(entity.Id, out dummy2); PlayersCollision.Remove(entity); } } } entity.Owner = null; entity.Dispose(); }
public override void Start(Entity entity) { Storage.Get <Storage>().Add(Target.Get <ItemStack>()); Target.Dispose(); }
protected override bool WorldDrawData(WorldDraw draw) { if (!base.WorldDrawData(draw)) { return(false); } var ctm = TransientManager.CurrentTransientManager; var ints = new IntegerCollection(); while (_lineSegs.Count > 0) { // Get the line segment and remove it from the list var ls = _lineSegs[0]; _lineSegs.RemoveAt(0); // Create an equivalent, red, database line // (or yellow, if calibrating) var ln = new Line(ls.StartPoint, ls.EndPoint); ln.ColorIndex = 1; _lines.Add(ln); // Draw it as transient graphics ctm.AddTransient( ln, TransientDrawingMode.DirectShortTerm, 128, ints ); } if (_drawing) { if (_cursor == null) { if (_vertices.Count > 0) { // Clear our skeleton ClearTransients(); _curPt = _vertices[_vertices.Count - 1]; // Make our sphere 10cm in diameter (5cm radius) var sol = new Solid3d(); sol.CreateSphere(0.05); _cursor = sol; _cursor.TransformBy( Matrix3d.Displacement(_curPt - Point3d.Origin) ); _cursor.ColorIndex = 2; ctm.AddTransient( _cursor, TransientDrawingMode.DirectShortTerm, 128, ints ); } } else { if (_vertices.Count > 0) { var newPt = _vertices[_vertices.Count - 1]; _cursor.TransformBy( Matrix3d.Displacement(newPt - _curPt) ); _curPt = newPt; ctm.UpdateTransient(_cursor, ints); } } } else // !_drawing { if (_cursor != null) { ctm.EraseTransient(_cursor, ints); _cursor.Dispose(); _cursor = null; } } return(true); }
protected override void Dispose(bool disposing) { _player.Dispose(); base.Dispose(disposing); }
public static void Start() { if (gvar.isMenu) { return; } if (!Local.InGame) { return; } if (Settings.userSettings.TriggerbotSettings.Knifebot && Local.ActiveWeapon.isKnife()) { if (CanKnife()) { Local.Attack2(); } } else { if (!Local.ActiveWeapon.CanFire) { return; } if (Local.CrosshairID < 0 || Local.CrosshairID > 65) { return; } LoadSetting(); if (!TriggerbotSettings.Enabled) { return; } var target = new Entity(Local.CrosshairID); if (target.Dormant) { return; } if (target.isTeam && !TriggerbotSettings.TargetTeam) { return; } if (target.Health <= 0) { return; } target.Dispose(); Thread.Sleep(TriggerbotSettings.Delay); if (TriggerbotSettings.TriggerbotMode == Settings.TriggerMode.Auto) { Local.Attack(true); } else if (TriggerbotSettings.TriggerbotMode == Settings.TriggerMode.Burst) { Local.Attack(TriggerbotSettings.BurstAmount); } else { Local.Attack(); Thread.Sleep(500); } } }
public void Dispose() { CheckInitialized(); Entity.Dispose(); }
public void Cmd_EdgeBand() { var acCurDoc = Application.DocumentManager.MdiActiveDocument; var acCurDb = acCurDoc.Database; var acCurEd = acCurDoc.Editor; //Call user to select a face var userSel = acCurEd.SelectSubentity(SubentityType.Face, "\nSelect a FACE to use as cutting criteria: "); if (userSel == null) { return; } if (userSel.Item1 == ObjectId.Null) { return; } if (userSel.Item2 == SubentityId.Null) { return; } var insetOpts = new PromptDistanceOptions("\nEnter edge banding thickness: ") { AllowNone = false, AllowZero = false, AllowNegative = false, DefaultValue = SettingsUser.EdgeBandThickness }; //Get the offset distance var insetRes = acCurEd.GetDistance(insetOpts); if (insetRes.Status != PromptStatus.OK) { return; } SettingsUser.EdgeBandThickness = insetRes.Value; // ReSharper disable once CompareOfFloatsByEqualityOperator if (SettingsUser.EdgeBandThickness <= 0) { return; } Entity faceEnt = null; Surface tempSurf = null; Solid3d tempSol = null; try { //Open a transaction using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { var acSol = acTrans.GetObject(userSel.Item1, OpenMode.ForWrite) as Solid3d; if (acSol == null) { acTrans.Abort(); return; } var innerSol = acSol.Clone() as Solid3d; if (innerSol == null) { acTrans.Abort(); return; } acSol.Layer = acCurDb.GetCLayer(acTrans); acCurDb.AppendEntity(innerSol); faceEnt = acSol.GetSubentity(userSel.Item2); var eInfo = new EntInfo(acSol, acCurDb, acTrans); var largestM = eInfo.GetLargestMeasurement(); using (tempSurf = faceEnt.CreateSurfaceFromFace(acCurDb, acTrans, false)) { var thickness = largestM + SettingsUser.EdgeBandThickness; using (tempSol = tempSurf.Thicken(-(thickness * 2), true)) { tempSol.OffsetBody(-SettingsUser.EdgeBandThickness); var cutSol = tempSol.Slice(tempSurf, true); cutSol.Dispose(); acSol.BooleanOperation(BooleanOperationType.BoolSubtract, tempSol); } } var acBool1 = new[] { innerSol.ObjectId }; var acBool2 = new[] { acSol.ObjectId }; acBool1.SolidSubtrahend(acBool2, acCurDb, acTrans, false); acTrans.Commit(); } } catch (Exception e) { acCurEd.WriteMessage(e.Message); } finally { if (faceEnt != null) { faceEnt.Dispose(); } if (tempSurf != null) { tempSurf.Dispose(); } if (tempSol != null) { tempSol.Dispose(); } } }
public void closeGroup(Entity group) { group.Dispose(); end_Transaction(); }
public void Cmd_RCChop() { if (!LicensingAgent.Check()) { return; } var acCurDoc = Application.DocumentManager.MdiActiveDocument; var acCurDb = acCurDoc.Database; var acCurEd = acCurDoc.Editor; //Call user to select a face var userSel = acCurEd.SelectSubentity(SubentityType.Face, "\nSelect a FACE to use as chopping criteria: "); if (userSel == null) { return; } if (userSel.Item1 == ObjectId.Null) { return; } if (userSel.Item2 == SubentityId.Null) { return; } var prSelOpts = new PromptDistanceOptions("\nEnter chop distance: ") { AllowNone = false, AllowZero = false, AllowNegative = false, DefaultValue = SettingsUser.RcChopDepth }; //Get the offset distance var prSelRes = acCurEd.GetDistance(prSelOpts); if (prSelRes.Status != PromptStatus.OK) { return; } SettingsUser.RcChopDepth = prSelRes.Value; // ReSharper disable once CompareOfFloatsByEqualityOperator if (SettingsUser.RcChopDepth == 0) { return; } var sList = new List <Surface>(); Entity faceEnt = null; Surface tempSurf = null; try { //Open a transaction using (var acTrans = acCurDb.TransactionManager.StartTransaction()) { var acSol = acTrans.GetObject(userSel.Item1, OpenMode.ForWrite) as Solid3d; if (acSol == null) { acTrans.Abort(); return; } faceEnt = acSol.GetSubentity(userSel.Item2); using (tempSurf = faceEnt.CreateSurfaceFromFace(acCurDb, acTrans, false)) { var canSlice = true; var multiplier = 1; using (var pWorker = new ProgressAgent("Testing Chops: ", 100)) { while (canSlice) { if (!pWorker.Progress()) { break; } var sliceSurf = Surface.CreateOffsetSurface(tempSurf, -SettingsUser.RcChopDepth * multiplier) as Surface; if (sliceSurf == null) { break; } canSlice = CanSlice(acSol, sliceSurf); if (!canSlice) { sliceSurf.Dispose(); continue; } sList.Add(sliceSurf); multiplier++; } if (sList.Count > 0) { pWorker.SetTotalOperations(sList.Count); pWorker.Reset("Chopping Solid: "); foreach (var su in sList) { if (!pWorker.Progress()) { acTrans.Abort(); break; } var obj = acSol.Slice(su, true); obj.SetPropertiesFrom(acSol); acCurDb.AppendEntity(obj); } } else { acCurEd.WriteMessage("\nNo Chopping Criteria found!"); } } } acTrans.Commit(); } } catch (Exception e) { acCurEd.WriteMessage(e.Message); MailAgent.Report(e.Message); } finally { foreach (var suf in sList) { suf.Dispose(); } if (faceEnt != null) { faceEnt.Dispose(); } if (tempSurf != null) { tempSurf.Dispose(); } } }
private void MyMirror(List <Entity> listEnt, Line line, string xY) { if (listEnt == null || line == null) { return; } Line3d line3d = new Line3d(line.StartPoint, line.EndPoint); for (int i = 0; i < listEnt.Count; i++) { var entity = listEnt[i]; Entity ent = entity; //if((ent as Dimension) != null) //{ // continue; //} if (ent is DBText || ent is MText) { listOId.Add(ent.ToSpace(blkRef.Database)); } else { ent = entity.GetTransformedCopy(Matrix3d.Mirroring(line3d)); if ((ent as Dimension) == null) { list.Add(ent); } //continue; } /* var ptMin = ent.Bounds.Value.MinPoint; * * var ptMax = ent.Bounds.Value.MaxPoint; * * var w = Math.Abs(ptMax.X - ptMin.X); * var h = Math.Abs(ptMax.Y - ptMin.Y); * * var ptCenter = new Point3d((ptMin.X + ptMax.X) / 2, (ptMin.Y + ptMax.Y) / 2, 0);*/ if (ent is DBText) { var a = ent as DBText; MirrorText(a, line3d); } else if (ent is MText) { var a = ent as MText; MirrorText(a, line3d); } else if ((ent as Dimension) != null) { var dim = ent as Dimension; Plane p = null; if (xY == "X") { p = new Plane(dim.TextPosition, dim.Normal); ent = dim.GetTransformedCopy(Matrix3d.Mirroring(p)); } else if (xY == "Y") { p = new Plane(dim.TextPosition, dim.Normal); ent = dim.GetTransformedCopy(Matrix3d.Mirroring(p)); } if (ent is RotatedDimension) { var rDim = ent as RotatedDimension; var rDim1 = new RotatedDimension(rDim.Rotation, rDim.XLine1Point, rDim.XLine2Point, rDim.DimLinePoint, rDim.DimensionText, rDim.DimensionStyle); Dim2Dim(rDim1, rDim); list.Add(rDim1); } else if (ent is AlignedDimension) { var rDim = ent as AlignedDimension; var rDim1 = new AlignedDimension(rDim.XLine1Point, rDim.XLine2Point, rDim.DimLinePoint, rDim.DimensionText, rDim.DimensionStyle); Dim2Dim(rDim1, rDim); list.Add(rDim1); } else if (ent is ArcDimension) { var rDim = ent as ArcDimension; var rDim1 = new ArcDimension(rDim.CenterPoint, rDim.XLine1Point, rDim.XLine2Point, rDim.ArcPoint, rDim.DimensionText, rDim.DimensionStyle); Dim2Dim(rDim1, rDim); list.Add(rDim1); } else if (ent is DiametricDimension) { var rDim = ent as DiametricDimension; var rDim1 = new DiametricDimension(rDim.ChordPoint, rDim.FarChordPoint, rDim.LeaderLength, rDim.DimensionText, rDim.DimensionStyle); Dim2Dim(rDim1, rDim); list.Add(rDim1); } else if (ent is LineAngularDimension2) { var rDim = ent as LineAngularDimension2; var rDim1 = new LineAngularDimension2(rDim.XLine1Start, rDim.XLine1End, rDim.XLine2Start, rDim.XLine2End, rDim.ArcPoint, rDim.DimensionText, rDim.DimensionStyle); Dim2Dim(rDim1, rDim); list.Add(rDim1); } else if (ent is Point3AngularDimension) { var rDim = ent as Point3AngularDimension; var rDim1 = new Point3AngularDimension(rDim.CenterPoint, rDim.XLine1Point, rDim.XLine2Point, rDim.ArcPoint, rDim.DimensionText, rDim.DimensionStyle); Dim2Dim(rDim1, rDim); list.Add(rDim1); } else if (ent is RadialDimension) { var rDim = ent as RadialDimension; var rDim1 = new RadialDimension(rDim.Center, rDim.ChordPoint, rDim.LeaderLength, rDim.DimensionText, rDim.DimensionStyle); Dim2Dim(rDim1, rDim); list.Add(rDim1); } else if (ent is RadialDimensionLarge) { var rDim = ent as RadialDimensionLarge; var rDim1 = new RadialDimensionLarge(rDim.Center, rDim.ChordPoint, rDim.OverrideCenter, rDim.JogPoint, rDim.JogAngle, rDim.DimensionText, rDim.DimensionStyle); Dim2Dim(rDim1, rDim); list.Add(rDim1); } } } listEnt.ForEach(ent => ent.Dispose()); }
public void Dispose() { XArrow.Dispose(); YArrow.Dispose(); ZArrow.Dispose(); }
/// <summary> /// Removes the physics body of the given entity from the physics world. /// </summary> public void RemoveEntity(Entity e, World.World worldState) { e.Dispose(); worldState.RemoveEntity(e); if (e.PhysicsBody != null) { EntityIdByPhysicsBody.Remove(e.PhysicsBody); RemoveBody(e.PhysicsBody); e.PhysicsBody = null; } }
public static System.Data.DataTable GetAllPolylineNums() { System.Data.DataTable table = new System.Data.DataTable("编码"); table.Columns.Add(new System.Data.DataColumn(("多段线id"), typeof(string))); table.Columns.Add(new System.Data.DataColumn(("个体编码"), typeof(string))); table.Columns.Add(new System.Data.DataColumn(("个体要素"), typeof(string))); table.Columns.Add(new System.Data.DataColumn(("个体名称"), typeof(string))); table.Columns.Add(new System.Data.DataColumn(("数量"), typeof(string))); table.Columns.Add(new System.Data.DataColumn(("个体阶段"), typeof(string))); System.Data.DataColumn column; System.Data.DataRow row; Document doc = Application.DocumentManager.MdiActiveDocument; Editor ed = doc.Editor; Database db = doc.Database; DocumentLock m_DocumentLock = Application.DocumentManager.MdiActiveDocument.LockDocument(); try { using (Transaction tr = db.TransactionManager.StartTransaction()) { foreach (ObjectId layerId in LayersToList(db)) { LayerTableRecord layer = tr.GetObject(layerId, OpenMode.ForRead) as LayerTableRecord; TypedValue[] filList = new TypedValue[1] { new TypedValue((int)DxfCode.LayerName, layer.Name) }; SelectionFilter sfilter = new SelectionFilter(filList); PromptSelectionResult result = ed.SelectAll(sfilter); if (result.Status == PromptStatus.OK) { SelectionSet acSSet = result.Value; foreach (ObjectId id in acSSet.GetObjectIds()) { DBObject obj = id.GetObject(OpenMode.ForRead); //以读的方式打开对象 ObjectId dictId = obj.ExtensionDictionary; //获取对象的扩展字典的id Entity ent1 = tr.GetObject(id, OpenMode.ForRead) as Entity; if (ent1 is Polyline && !dictId.IsNull) { DBDictionary dict = dictId.GetObject(OpenMode.ForRead) as DBDictionary;//获取对象的扩展字典 if (!dict.Contains("polylineNumber")) { continue;//如果扩展字典中没有包含指定关键 字的扩展记录,则返回null; } //先要获取对象的扩展字典或图形中的有名对象字典,然后才能在字典中获取要查询的扩展记录 ObjectId xrecordId = dict.GetAt("polylineNumber"); //获取扩展记录对象的id Xrecord xrecord = xrecordId.GetObject(OpenMode.ForRead) as Xrecord; //根据id获取扩展记录对象 ResultBuffer resBuf = xrecord.Data; ResultBufferEnumerator rator = resBuf.GetEnumerator(); int i = 0; List <string> values = new List <string>(); while (rator.MoveNext()) { TypedValue re = rator.Current; values.Add((string)re.Value); } bool hasData = false; foreach (System.Data.DataRow item in table.Rows) { if ((string)item["个体编码"] == values[0] && (string)item["个体要素"] == values[1] && (string)item["个体名称"] == values[2] && (string)item["个体阶段"] == values[3]) { item["多段线id"] += id.Handle.Value.ToString() + ","; int count = 0; int.TryParse((string)item["数量"], out count); item["数量"] = count + 1; hasData = true; break; } } if (!hasData) { row = table.NewRow(); row["多段线id"] = id.Handle.Value.ToString() + ","; row["数量"] = 1; while (rator.MoveNext()) { TypedValue re = rator.Current; if (i == 0) { row["个体编码"] = re.Value; } if (i == 1) { row["个体要素"] = re.Value; } if (i == 2) { row["个体名称"] = re.Value; } if (i == 3) { row["个体阶段"] = re.Value; } i++; } table.Rows.Add(row); } resBuf.Dispose(); xrecord.Dispose(); dict.Dispose(); } ent1.Dispose(); obj.Dispose(); } } layer.Dispose(); } tr.Commit(); } } catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.ToString()); } finally { m_DocumentLock.Dispose(); } return(table); }
public void Dispose() { DoubleClickedCommand = null; Entity?.Dispose(); }
public void Dispose() { game.SceneSystem.SceneInstance.RootScene.Entities.Remove(entity); entity.Dispose(); }