Draw jig oject extend with section line extend draw oject

Draw jig oject extend with section line extend draw oject

kmkxperia
Advocate Advocate
684 Views
6 Replies
Message 1 of 7

Draw jig oject extend with section line extend draw oject

kmkxperia
Advocate
Advocate
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Autodesk.AutoCAD.Geometry;
using palet.Startup;

using System.Runtime.InteropServices;
using Exception = System.Exception;
using Autodesk.AutoCAD.ApplicationServices;
using System.Security.Cryptography;
using System.Globalization;
using Autodesk.AutoCAD.Interop.Common;

namespace palet.Jig
{
    

    public class MyBlockJig_sec : DrawJig
    {
        public Point3d _point;
        private ObjectId _blockId = ObjectId.Null;
        private string str_Prompt = "";
        private bool IsKeyword=false;
        public static Point3d _basePoint;
        public PromptResult DragMe(ObjectId i_blockId, out Point3d o_pnt, String Prompt, ref bool IsKeyword)
        {
            str_Prompt = Prompt;
            _blockId = i_blockId;
            var ed = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor;
            var jigRes = ed.Drag(this);
            //o_pnt = _point;
            o_pnt = _basePoint;
            return jigRes;
        }

        protected override SamplerStatus Sampler(JigPrompts prompts)
        {
            var jigOpts = new JigPromptPointOptions("");
            jigOpts.UserInputControls = UserInputControls.Accept3dCoordinates | UserInputControls.NullResponseAccepted;
            
            try
            {
                jigOpts.Message = str_Prompt; // "Select a point:";
                if (str_Prompt.Contains("bubble"))
                {
                    jigOpts.Keywords.Add("neXt");
                    jigOpts.Keywords.Add("Prev");
                }
                else if (str_Prompt.Contains("flip Vert"))
                {
                    if (str_Prompt.Contains("TL/TC/TR/ML/MC/MR/BL/BC/BR")) //These are OT selection
                    {
                        jigOpts.Keywords.Add("Horiz");
                        jigOpts.Keywords.Add("Vert");
                        jigOpts.Keywords.Add("TL");
                        jigOpts.Keywords.Add("TC");
                        jigOpts.Keywords.Add("TR");
                        jigOpts.Keywords.Add("ML");
                        jigOpts.Keywords.Add("MC");
                        jigOpts.Keywords.Add("MR");
                        jigOpts.Keywords.Add("BL");
                        jigOpts.Keywords.Add("BC");
                        jigOpts.Keywords.Add("BR");
                    }
                    else
                    {
                        jigOpts.Keywords.Add("Vert");
                        jigOpts.Keywords.Add("Manual");
                    }
                }
                else if (str_Prompt.Contains("flip Horiz/ flip Vert / Auto"))
                {
                    jigOpts.Keywords.Add("Horiz");
                    jigOpts.Keywords.Add("Vert");

                }
                else if (str_Prompt.Contains("Flip/Manual"))
                {
                    jigOpts.Keywords.Add("Flip");
                    jigOpts.Keywords.Add("Manual");
                }
                else if (str_Prompt.Contains("Flip/Auto"))
                {
                    jigOpts.Keywords.Add("Flip");
                    jigOpts.Keywords.Add("Auto");
                }
                else if (str_Prompt.Contains("TL / TC / TR / ML / MC / MR / BL / BC / BR"))
                {
                    jigOpts.Keywords.Add("Horiz");
                    jigOpts.Keywords.Add("Vert");
                    jigOpts.Keywords.Add("TL");
                    jigOpts.Keywords.Add("TC");
                    jigOpts.Keywords.Add("TR");
                    jigOpts.Keywords.Add("ML");
                    jigOpts.Keywords.Add("MC");
                    jigOpts.Keywords.Add("MR");
                    jigOpts.Keywords.Add("BL");
                    jigOpts.Keywords.Add("BC");
                    jigOpts.Keywords.Add("BR");
                }
                else if (str_Prompt.Contains("Inspoint"))
                {
                    jigOpts.Keywords.Add("Inspoint");
                }
                else if (str_Prompt.Contains("Rotate"))
                {
                    jigOpts.Keywords.Add("Flip");
                    jigOpts.Keywords.Add("Rotate");
                    jigOpts.Keywords.Add("Auto gap off");
                    //jigOpts.Keywords.Add("Set default gap");
                    //jigOpts.Keywords.Add("reSet default gap");
                }
                else
                {
                    jigOpts.Keywords.Add("Flip");
                }


                //jigOpts.Keywords.Add("No");
                //jigOpts.AllowNone = false;
                
                jigOpts.BasePoint = _basePoint;
                jigOpts.UseBasePoint = true;
                jigOpts.Cursor = CursorType.RubberBand;
                
               /* jigOpts.UserInputControls = UserInputControls.Accept3dCoordinates | UserInputControls.AnyBlankTerminatesInput
               | UserInputControls.GovernedByOrthoMode | UserInputControls.GovernedByUCSDetect | UserInputControls.UseBasePointElevation
               | UserInputControls.InitialBlankTerminatesInput | UserInputControls.NullResponseAccepted;*/

                Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView();
                var jigRes = prompts.AcquirePoint(jigOpts);
                Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView();
                
                var pt = jigRes.Value;
                if (pt == _point)
                    return SamplerStatus.NoChange;
                _point = pt;
                
                if (jigRes.Status == PromptStatus.OK)
                    return SamplerStatus.OK;
                return SamplerStatus.Cancel;
            }
            
            catch (Exception ex) 
            {
                if (ex.Message.IndexOf("User input is a keyword", StringComparison.InvariantCultureIgnoreCase) != -1)
                {
                    //' One of the keywords was entered
                    IsKeyword = true;
                    return SamplerStatus.Cancel;
                }
                else
                {
                    return SamplerStatus.Cancel;
                }

            }
        }

        protected override bool WorldDraw(Autodesk.AutoCAD.GraphicsInterface.WorldDraw draw)
        {
            var inMemoryBlockInsert = new BlockReference(_basePoint, _blockId);
            inMemoryBlockInsert.TransformBy(Matrix3d.Scaling(mod_DC_Main.dbl_DC_ScaleFactor, _basePoint));
            draw.Geometry.Draw(inMemoryBlockInsert);
            inMemoryBlockInsert.Dispose();
            return true;
        }

        public class mod_BlockJig_Sec
        {
            //public static Point3d _basePoint;
            public static dynamic BlockJig_sec(string BL, String Prompt, double[] v_InsertionPoint, ref bool IsKeyword)
            {

                object Ret = null;
                var ed = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument.Editor;
                var db = ed.Document.Database;
                var CadDocument = Autodesk.AutoCAD.ApplicationServices.Core.Application.DocumentManager.MdiActiveDocument;
                BlockReference ent = null;
                try
                {
                    using (var tr = db.TransactionManager.StartTransaction())
                    {
                        BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, Autodesk.AutoCAD.DatabaseServices.OpenMode.ForRead);
                        BlockTableRecord blockTbRec = (BlockTableRecord)tr.GetObject(bt[BL], Autodesk.AutoCAD.DatabaseServices.OpenMode.ForRead);
                        var attInfos = new Dictionary<string, TextInfo>();
                       
                        var blockJig = new MyBlockJig_sec();
                        
                        //Point3d point;
                        Point3d point = new Point3d(v_InsertionPoint[0], v_InsertionPoint[1], v_InsertionPoint[2]);
                        _basePoint = point;

                        var res = blockJig.DragMe(blockTbRec.ObjectId, out point, Prompt, ref IsKeyword);//blockJig.DragMe(blockTbRec.ObjectId, out point,  Prompt, ref IsKeyword);

                        Ret = res; // blockJig.DragMe(block.ObjectId, out point);
                        if (res.Status == PromptStatus.OK)
                        {
                            using (CadDocument.LockDocument())
                            {
                                BlockTableRecord curSpace = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, Autodesk.AutoCAD.DatabaseServices.OpenMode.ForWrite);
                                var insert = new BlockReference(point, blockTbRec.ObjectId);
                                insert.TransformBy(Matrix3d.Scaling(mod_DC_Main.dbl_DC_ScaleFactor, point));

                                curSpace.AppendEntity(insert);
                                tr.AddNewlyCreatedDBObject(insert, true);
                                // insert.ExplodeToOwnerSpace()

                                IsKeyword = true;
                                insert.Erase();
                                //Variables.StartPoint = point;

                            }

                        }
                        else
                        {
                            IsKeyword = true;
                        }

                        //mod__GetBlockReferenceByName.GetBlockReferenceByName(BL);
                        tr.Commit();
                        ed.Regen();
                        return Ret;
                    }
                }

                catch (System.Exception ex)
                {
                    ed.WriteMessage(ex.ToString());
                    return null;
                }

            }
            struct TextInfo
            {
                public Point3d Position { get; private set; }
                public Point3d Alignment { get; private set; }
                public bool IsAligned { get; private set; }
                public double Rotation { get; private set; }
                public TextInfo(Point3d position, Point3d alignment, bool aligned, double rotation)
                {
                    Position = position;
                    Alignment = alignment;
                    IsAligned = aligned;
                    Rotation = rotation;
                }
            }
            private static Point3d GetAttributePosition(ObjectId id)
            {
                Point3d p = new Point3d();
                Document doc = Application.DocumentManager.MdiActiveDocument;
                Database db = doc.Database;
                Editor ed = doc.Editor;
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    BlockReference br = (BlockReference)tr.GetObject(id, OpenMode.ForRead);

                    // if the block rotation cosine is negative (i.e. 90° < br.Rotation < 270°) 
                    if (Math.Cos(br.Rotation) > 0.0)
                    {
                        // search for "OUTSIDE_DISPLAY" attribute
                        foreach (ObjectId id1 in br.AttributeCollection)
                        {
                            AttributeReference attRef = (AttributeReference)tr.GetObject(id1, OpenMode.ForRead);
                            /*if (attRef.Tag == "OUTSIDE_DISPLAY")
                            {*/
                            // compute the displacement vector
                            double angle = attRef.Rotation - Math.PI * 0.5; // rotation - 90°
                                                                            //double height = attRef.MTextAttribute.ActualHeight; // mtext total height
                                                                            //Vector3d vector = new Vector3d(height * Math.Cos(angle), height * Math.Sin(angle), 0.0);
                            Vector3d vector = new Vector3d(Math.Cos(angle), Math.Sin(angle), 0.0);
                            attRef.Position = br.Position;
                            // move and rotate the attribute
                            attRef.UpgradeOpen();
                            // attRef.AlignmentPoint += vector;
                            attRef.Rotation += Math.PI;
                            p = attRef.Position;
                            // }
                        }
                    }
                    tr.Commit();
                    return p;
                }
            }
        }
    }
}

I am trying to perform the elow operation where I place the Oject then use drag oject to place the section attached is one expected and other what I am getting
Expected:

 


Issue When I runthe elow code.. I can inscert oject ut when I dreag it does not drag properly.. as in ist video



0 Likes
685 Views
6 Replies
Replies (6)
Message 2 of 7

18348401357
Enthusiast
Enthusiast

I tried to achieve the effect

screenshots.gif

 

[CommandMethod("Cs6")]
public static void Main2()
{
using var tr = new DBTrans();
// make a block
var btrId = tr.BlockTable.Add("tempBlock", btr =>
{
var pl = new Polyline();
pl.AddVertexAt(0, new Point2d(0, 0), 0, 0, 0);
pl.AddVertexAt(1, new Point2d(10, 0), 0, 0, 0);
pl.AddVertexAt(2, new Point2d(0, 20), 0, 0, 0);
pl.Closed = true;
pl.ColorIndex = 7;
btr.AddEntity(pl);
});
var ed = Env.Editor;
var r1 = ed.GetPoint("\nchoose first point");
if (r1.Status != PromptStatus.OK)
return;
var pt1 = r1.Value.Ucs2Wcs();
using var brf1 = new BlockReference(pt1, btrId);
// jig for rotation
using var j2 = new JigEx((mpw, de) =>
{
var angle = pt1.GetAngle(mpw);
brf1.Rotation = angle;
});
j2.DatabaseEntityDraw(wd => wd.Geometry.Draw(brf1));
j2.SetOptions(pt1, CursorType.RubberBand, "\nchoose angle");
var r2 = ed.Drag(j2);
if (r2.Status != PromptStatus.OK)
return;
var v1 = Vector3d.XAxis.RotateBy(brf1.Rotation, Vector3d.ZAxis);
using var brf2 = brf1.CloneEx();
brf2.Mirror(new Plane(pt1, v1));
using var line = new Line(pt1, pt1);
// jig for second point
using var j3 = new JigEx((mpw, de) =>
{
var v2 = pt1.GetVectorTo(mpw);
var pt2 = pt1 + v1 * v1.DotProduct(v2);
brf2.Position = pt2;
line.EndPoint = pt2;
});
j3.DatabaseEntityDraw(wd => wd.Geometry.Draw(brf1,brf2, line));
j3.SetOptions(pt1, CursorType.Crosshair, "\nchoose second point");
var r3 = ed.Drag(j3);
if (r3.Status != PromptStatus.OK)
return;
tr.CurrentSpace.AddEntity(brf1,brf2, line);
}

There's a lot of encapsulation in there, but I just want to show you how it works. You need to abstract out the common jig parts so that you can focus on the logic when using it.

 

the codes of jigEx is here,DBTrans doesn't matter, I didn't put it, you can use your own encapsulation.

 

 

 

 

namespace IFoxCAD.Cad;

public delegate void WorldDrawEvent(WorldDraw draw);

public class JigEx : DrawJig, IDisposable
{
    #region Members

    event WorldDrawEvent? WorldDrawEvent;

    public Point3d MousePointWcsLast;

    public Entity[] Entitys => _drawEntitys.ToArray();

    readonly Action<Point3d, Queue<Entity>>? _mouseAction;
    readonly Tolerance _tolerance;
    readonly Queue<Entity> _drawEntitys;
    JigPromptPointOptions? _options;
    private bool _worldDrawFlag;
    private bool _systemVariablesOrthomode;

    bool SystemVariablesOrthomode
    {
        get => _systemVariablesOrthomode;
        set
        {
            if (Env.OrthoMode != value)
                Env.OrthoMode = _systemVariablesOrthomode = value;
        }
    }

    #endregion

    #region Ctor

    JigEx()
    {
        _drawEntitys = new();
        DimensionEntities = new();
        _options = JigPointOptions();
    }

    public JigEx(Action<Point3d, Queue<Entity>>? action = null, double tolerance = 1e-6) : this()
    {
        _mouseAction = action;
        _tolerance = new(tolerance, tolerance);
    }

    #endregion

    private static bool lastIsKw;

    #region Overrides

    protected override SamplerStatus Sampler(JigPrompts prompts)
    {
        if (_worldDrawFlag)
            return SamplerStatus.NoChange;
        if (_options is null)
            throw new NullReferenceException(nameof(_options));
        var pro = prompts.AcquirePoint(_options);
        if (pro.Status != PromptStatus.OK && pro.Status != PromptStatus.Keyword)
            return SamplerStatus.Cancel;
        bool isOk = !lastIsKw;
        lastIsKw = pro.Status == PromptStatus.Keyword;

        var mousePointWcs = pro.Value;

        if (isOk && mousePointWcs.IsEqualTo(MousePointWcsLast, _tolerance))
        {
            return SamplerStatus.NoChange;
        }

        while (_drawEntitys.Count > 0)
            _drawEntitys.Dequeue().Dispose();

        _mouseAction?.Invoke(mousePointWcs, _drawEntitys);
        MousePointWcsLast = mousePointWcs;

        return SamplerStatus.OK;
    }

    public void DatabaseEntityDraw(WorldDrawEvent action)
    {
        WorldDrawEvent = action;
    }

    protected override bool WorldDraw(WorldDraw draw)
    {
        _worldDrawFlag = true;
        WorldDrawEvent?.Invoke(draw);
        _drawEntitys.ForEach(ent =>
        {
            draw.Geometry.Draw(ent);
        });
        _worldDrawFlag = false;
        return true;
    }

    #endregion

    #region Method

    public JigPromptPointOptions SetOptions(Point3d basePoint,
        CursorType cursorType = CursorType.RubberBand,
        string msg = "Choose a point",
        bool orthoMode = false)
    {
        if (orthoMode)
            SystemVariablesOrthomode = true;

        _options = JigPointOptions();
        _options.Message = Environment.NewLine + msg;
        _options.Cursor = cursorType;
        _options.UseBasePoint = true;
        _options.BasePoint = basePoint;
        return _options;
    }

    public JigPromptPointOptions SetOptions(string msg,
        Dictionary<string, string>? keywords = null,
        bool orthoMode = false)
    {
        if (orthoMode)
            SystemVariablesOrthomode = true;

        _options = JigPointOptions();
        _options.Message = Environment.NewLine + msg;

        if (keywords != null)
            foreach (var item in keywords)
                _options.Keywords.Add(item.Key, item.Key, item.Value);

        return _options;
    }

    public void SetOptions(Action<JigPromptPointOptions> action, bool orthoMode = false)
    {
        if (orthoMode)
            SystemVariablesOrthomode = true;

        _options = new JigPromptPointOptions();
        action.Invoke(_options);
    }

    public PromptResult Drag()
    {
        var dm = Acap.DocumentManager;
        var doc = dm.MdiActiveDocument;
        var ed = doc.Editor;
        var dr = ed.Drag(this);

        if (SystemVariablesOrthomode)
            SystemVariablesOrthomode = !SystemVariablesOrthomode;
        return dr;
    }

    static JigPromptPointOptions JigPointOptions()
    {
        return new JigPromptPointOptions()
        {
            UserInputControls =
                UserInputControls.GovernedByUCSDetect
                | UserInputControls.Accept3dCoordinates
                | UserInputControls.NullResponseAccepted
                | UserInputControls.AnyBlankTerminatesInput
        };
    }

    public void SetSpaceIsKeyword()
    {
        var opt = _options;
        ArgumentNullEx.ThrowIfNull(opt);
        if ((opt.UserInputControls & UserInputControls.NullResponseAccepted) == UserInputControls.NullResponseAccepted)
            opt.UserInputControls ^= UserInputControls.NullResponseAccepted;
        if ((opt.UserInputControls & UserInputControls.AnyBlankTerminatesInput) == UserInputControls.AnyBlankTerminatesInput)
            opt.UserInputControls ^= UserInputControls.AnyBlankTerminatesInput;
    }

    #endregion


    public DynamicDimensionDataCollection DimensionEntities { get; set; }

    protected override DynamicDimensionDataCollection GetDynamicDimensionData(double dimScale)
    {
        base.GetDynamicDimensionData(dimScale);
        return DimensionEntities;
    }

    #region IDisposable

    public bool IsDisposed { get; private set; }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~JigEx()
    {
        Dispose(false);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (IsDisposed)
            return;
        IsDisposed = true;
        if (disposing)
        {
            _drawEntitys.ForEach(ent =>
            {
                if (ent.Database == null && !ent.IsDisposed)
                    ent.Dispose();
            });
        }

        _drawEntitys.Clear();
    }

    #endregion
}

 

 

 

 

 

it's powered by ifoxcad v0.7.2, a MIT protocol library that is completely free and can be searched directly in nuget.org.

If you're interested, you can read about it.

 

Message 3 of 7

kmkxperia
Advocate
Advocate

Thanks. for response and code  will try .. ut is there other way other then using ifoxcad v0.7.2 .. as need to have least dependency on any external liraries. 

0 Likes
Message 4 of 7

18348401357
Enthusiast
Enthusiast

You can copy the JigEx code directly from ifox (I have pasted it on) into your project, this is allowed, I am one of the developers of this project, our project can be completely free to use, welcome to exchange and learn.

0 Likes
Message 5 of 7

18348401357
Enthusiast
Enthusiast

There's something about OrthoMode in the JigEx code above, using the Env class, you can just delete it

0 Likes
Message 6 of 7

kmkxperia
Advocate
Advocate

was following https://github.com/InspireFunction/IFoxCAD/tree/v0.7 if I am no wrong .. is correct directory.
ut looks like its in Chinies which I am not familer and my rowser is not translating it.. if you point me to the location of code and if paste it here it wil help Thanks 

0 Likes
Message 7 of 7

kmkxperia
Advocate
Advocate

Was trying getting some error lik e inn 

[CommandMethod("Cs6")] code

brf2.Mirror(new Plane(pt1, v1)); and .CloneEx(); are not part of rf2

wd.Geometry.Draw(brf1, brf2, line) => looks like Draw dies not take 3 entities

 

also tr.CurrentSpace.AddEntity(brf1, brf2, line);  => CurrentSpace is not part of tr

 

Can you help me to get with these errors not ale to get along this? so I try this 

0 Likes