Author Topic: BlockTesting2011  (Read 10101 times)

0 Members and 1 Guest are viewing this topic.

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 10832
  • class keyThumper<T>:ILazy<T>
BlockTesting2011
« on: March 30, 2011, 09:26:38 pm »
This will be an ongoing thread with functions added as I get a chance.
Refer to the attached Zip for the full solution.
The routines are noted for functionality.

There are some gotcha's and traps in these incomplete samples.
The intent was to proceed step by step to explore the concepts involved.
//---------------------------------------------------------------
Jeff H has volunteered to convert these Methods to VB.net
Thanks Jeff.

gile has volunteered to convert these Methods to F#
Thanks gile.
//---------------------------------------------------------------

NOTE Solutions updated
//------------------------------- Sample Blocks
3DBlock.dwg  - block with no attibutes is attached to this first post :
 
3DBlock_A.dwg - block with one attibute is attached to this first post :

3DBlock_4A.dwg - block with 4 attibutes is attached to this post :
http://www.theswamp.org/index.php?topic=37686.msg427676#msg427676

 //------------------------------- C# Solutions
BlockTesting2011 _20110331.1115.zip is attached to this first post :

BlockTesting2011 _20110401.0936.zip is attached to this post :
http://www.theswamp.org/index.php?topic=37686.msg427348#msg427348

BlockTesting2011 _ 20110405.1206.zip  is attached to this post :
http://www.theswamp.org/index.php?topic=37686.msg427833#msg427833

//------------------------------- VB Solutions
BlockTesting2011VB_04012011.zip is attached to this post :
http://www.theswamp.org/index.php?topic=37686.msg427562#msg427562

BlockTesting2011VB_04042011.zip is attached to this post :
http://www.theswamp.org/index.php?topic=37686.msg427562#msg427562

//------------------------------- F# Solutions
BlockTesting2011FS_20110403.zip is attached to this post :
http://www.theswamp.org/index.php?topic=37686.msg427619#msg427619

BlockTesting2011FS_20110405.zip   is attached to this post :
http://www.theswamp.org/index.php?topic=37686.msg427843#msg427843
//---------------------------------------------------------------

Container :
Code - C#: [Select]
  1. // CodeHimBelonga kdub@theSwamp 20110331
  2. //
  3. using System;
  4. using System.IO;
  5.  
  6. using Autodesk.AutoCAD.Runtime;
  7. using Autodesk.AutoCAD.ApplicationServices;
  8. using Autodesk.AutoCAD.DatabaseServices;
  9. using Autodesk.AutoCAD.Geometry;
  10. using Autodesk.AutoCAD.EditorInput;
  11. //
  12. using AcadApp = Autodesk.AutoCAD.ApplicationServices.Application;
  13. using AcUtils = Autodesk.AutoCAD.Internal.Utils;
  14.  
  15. [assembly: CommandClass(typeof(KdubTesting.BlockTesting2011))]
  16.  
  17. namespace KdubTesting
  18. {
  19.    public class BlockTesting2011
  20.    {
  21.        Document doc;
  22.        Database db;
  23.        Editor ed;
  24.  
  25.        public BlockTesting2011()
  26.        {
  27.            ActiveDoc = AcadApp.DocumentManager.MdiActiveDocument;
  28.        }
  29.  
  30.        Document ActiveDoc
  31.        {
  32.            get { return doc; }
  33.            set
  34.            {
  35.                doc = value;
  36.                if( doc == null ) {
  37.                    db = null;
  38.                    ed = null;
  39.                } else {
  40.                    db = doc.Database;
  41.                    ed = doc.Editor;
  42.                }
  43.            }
  44.        }
  45.        //=======================================================================
  46.  
  47.        // Methods go here < snip>
  48.        //=======================================================================
  49.    }
  50. }
  51.  
  52.  

Code - C#: [Select]
  1.        //=======================================================================
  2.        // add the block to the ActiveDrawing blockTable
  3.  
  4.        [CommandMethod("BI_1")]
  5.        public void BlockInsert_1()
  6.        {
  7.            string blockQualifiedFileName = "K:\\ToTest\\3Dblock_A.dwg";
  8.            string blockName = "3Dblock_A";
  9.            Database tmpDb = new Database(false, true);
  10.            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");
  11.  
  12.            // add the block to the ActiveDrawing blockTable
  13.            db.Insert(blockName, tmpDb, true);
  14.  
  15.            // add the block to the ActiveDrawing blockTable with a Temporary Name
  16.            db.Insert("TmpTest", tmpDb, true);
  17.        }
  18.        //=======================================================================
  19.  

Code - C#: [Select]
  1.       //=======================================================================
  2.        // add the block to the current space (Model or Paper).
  3.        // block is exploded IE: copy of original
  4.        // Insert will be at World 0,0,0 and transformed for Scale
  5.  
  6.        [CommandMethod("BI_2")]
  7.        public void BlockInsert_2()
  8.        {
  9.            string blockQualifiedFileName = "K:\\ToTest\\3Dblock_A.dwg";
  10.            double scale = 5.0;
  11.  
  12.            Database tmpDb = new Database(false, true);
  13.            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");
  14.  
  15.            Matrix3d Transform = Matrix3d.Identity;
  16.            Transform = Transform *
  17.                Matrix3d.Scaling(scale, Point3d.Origin);
  18.  
  19.            db.Insert(Transform, tmpDb, true);
  20.        }
  21.        //=======================================================================
  22.  

Code - C#: [Select]
  1.       //=======================================================================
  2.        // add the block to the current space (Model or Paper).
  3.        // block is exploded IE: copy of original
  4.        // Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
  5.        // and transformed for Scale
  6.  
  7.        [CommandMethod("BI_3")]
  8.        public void BlockInsert_3()
  9.        {
  10.            string blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg";
  11.            double scale = 2.5;
  12.  
  13.            Database tmpDb = new Database(false, true);
  14.            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");
  15.  
  16.            Matrix3d Transform = ed.CurrentUserCoordinateSystem;
  17.            Transform = Transform *
  18.                Matrix3d.Scaling(scale, Point3d.Origin);
  19.  
  20.            db.Insert(Transform, tmpDb, true);
  21.        }
  22.        //=======================================================================
  23.  

Code - C#: [Select]
  1.       //=======================================================================
  2.        // add the block to the current space (Model or Paper).
  3.        // block is exploded IE: copy of original
  4.        // Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
  5.        // and transformed for Scale
  6.        // and transformed for Displacement
  7.        // note that the nominated displacement will be scaled !!
  8.  
  9.        [CommandMethod("BI_4")]
  10.        public void BlockInsert_4()
  11.        {
  12.            string blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg";
  13.            double scale = 3.0;
  14.            Vector3d DispacementVector = new Vector3d(20, 50, 0);
  15.            //
  16.            Database tmpDb = new Database(false, true);
  17.            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");
  18.  
  19.            Matrix3d Transform = ed.CurrentUserCoordinateSystem;
  20.  
  21.            Transform = Transform *
  22.                Matrix3d.Scaling(scale, Point3d.Origin) *
  23.                Matrix3d.Displacement(DispacementVector);
  24.  
  25.            db.Insert(Transform, tmpDb, true);
  26.        }
  27.        //=======================================================================
  28.  

Code - C#: [Select]
  1.  
  2.       //=======================================================================
  3.        // add the block to the current space (Model or Paper).
  4.        // block is exploded IE: copy of original
  5.        // Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
  6.        // and transformed for Scale
  7.        // and transformed for Displacement
  8.        // note that the nominated displacement will be honoured
  9.  
  10.        [CommandMethod("BI_5")]
  11.        public void BlockInsert_5()
  12.        {
  13.            string blockQualifiedFileName = "K:\\ToTest\\3Dblock_a.dwg";
  14.            double scale = 3.0;
  15.            Vector3d DispacementVector = new Vector3d(20, 50, 0);
  16.            //
  17.            Database tmpDb = new Database(false, true);
  18.            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");
  19.  
  20.            Matrix3d Transform = ed.CurrentUserCoordinateSystem;
  21.  
  22.            Transform = Transform *
  23.                Matrix3d.Scaling(scale, Point3d.Origin) *
  24.                Matrix3d.Displacement(DispacementVector / scale);
  25.  
  26.            db.Insert(Transform, tmpDb, true);
  27.        }
  28.        //=======================================================================
  29.  
  30.  
« Last Edit: December 18, 2011, 12:36:00 am by Kerry »
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate<--

gile

  • Water Moccasin
  • Posts: 1741
  • Marseille, France
Re: BlockTesting2011
« Reply #1 on: March 31, 2011, 01:45:12 am »
Hi Kerry,

In the last code (honoured displacement), you can replace:

Code - C#: [Select]
  1. Transform = Transform *
  2.                Matrix3d.Scaling(scale, Point3d.Origin) *
  3.                Matrix3d.Displacement(DispacementVector / scale);

with:

Code - C#: [Select]
  1. Transform = Transform *
  2.                Matrix3d.Displacement(DispacementVector) *
  3.                Matrix3d.Scaling(scale, Point3d.Origin);

The Matrix3d multiplication operator (*) is equivalent to PostMultiplyBy that means transformations occur in reverse order : Scaling, then Displacement, then UCS rotation(s) and origin displacement.

Maybe it's more 'readable' to use the PreMultiplyBy method to write the transformations the same order they occur:

Code - C#: [Select]
  1. Transform = Matrix3d
  2.    .Scaling(scale, Point3d.Origin)
  3.    .PreMultiplyBy(Matrix3d.Displacement(DispacementVector))
  4.    .PreMultiplyBy(Transform);
« Last Edit: December 18, 2011, 12:36:55 am by Kerry »
Speaking English as a French Frog

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 10832
  • class keyThumper<T>:ILazy<T>
Re: BlockTesting2011
« Reply #2 on: March 31, 2011, 03:09:48 am »
Thanks gile, that's a better option ... and valuable information.
I had planned on doing some more investigation on the Transform but ran out of time :)

I'll update the Solution next time I post it.

Quote
Maybe it's more 'readable' to use the PreMultiplyBy method to write the transformations the same order they occur:

I think the PreMultiplyBy method will be better also
« Last Edit: March 31, 2011, 03:14:16 am by Kerry »
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate<--

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 10832
  • class keyThumper<T>:ILazy<T>
Re: BlockTesting2011
« Reply #3 on: March 31, 2011, 03:31:16 am »
Thinking about it, this may be better ... but a little more difficult to debug ( if ever necessary) :)

Code - C#: [Select]
  1.  
  2.  
  3.            // **remove** Matrix3d Transform = ed.CurrentUserCoordinateSystem;
  4.  
  5.            Matrix3d Transform = Matrix3d
  6.                .Scaling(scale, Point3d.Origin)
  7.                .PreMultiplyBy( Matrix3d.Displacement(DispacementVector))
  8.                .PreMultiplyBy(ed.CurrentUserCoordinateSystem);
  9.  
  10.            db.Insert(Transform, tmpDb, true);
  11.  
  12.  
« Last Edit: December 18, 2011, 12:37:27 am by Kerry »
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate<--

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 10832
  • class keyThumper<T>:ILazy<T>
Re: BlockTesting2011
« Reply #4 on: March 31, 2011, 04:58:29 am »
Next series :
Refer notations.

Transforms use PreMultiplyBy method as suggested by gile :)


Code - C#: [Select]
  1.       //=======================================================================
  2.        // add the block to the ActiveDrawing CurrentSpace
  3.        // Expects to find the Block in the BlockTable
  4.        // does not handle Attributes
  5.  
  6.        [CommandMethod("BI_10")]
  7.        public void BlockInsert_10()
  8.        {
  9.            string blockName = "3Dblock";
  10.  
  11.            using( Transaction tr = db.TransactionManager.StartTransaction() ) {
  12.                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
  13.                if( !bt.Has(blockName) ) {
  14.                    ed.WriteMessage("\nBlock '{0}' is not available in the current drawing.", blockName);
  15.                    return;
  16.                }
  17.                PromptPointResult ppr = ed.GetPoint("\nSpecify insertion point: ");
  18.                if( ppr.Status != PromptStatus.OK )
  19.                    return;
  20.  
  21.                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
  22.                BlockReference br = new BlockReference(Point3d.Origin, bt[ blockName ]);
  23.  
  24.                br.TransformBy(Matrix3d
  25.                    .Displacement(ppr.Value - Point3d.Origin)
  26.                    .PreMultiplyBy(ed.CurrentUserCoordinateSystem));
  27.  
  28.                btr.AppendEntity(br);
  29.                tr.AddNewlyCreatedDBObject(br, true);
  30.                tr.Commit();
  31.            }
  32.        }
  33.        //=======================================================================
  34.  

Code - C#: [Select]
  1.       //=======================================================================
  2.        // add the block to the ActiveDrawing CurrentSpace
  3.        // Imports the Block if not found in the BlockTable
  4.        // does not handle Attributes
  5.  
  6.        [CommandMethod("BI_11")]
  7.        public void BlockInsert_11()
  8.        {
  9.            string blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg";
  10.            string blockName = "3Dblock";
  11.  
  12.            using( Transaction tr = db.TransactionManager.StartTransaction() ) {
  13.                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
  14.                if( !bt.Has(blockName) ) {
  15.                    Database tmpDb = new Database(false, true);
  16.                    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");
  17.                    // add the block to the ActiveDrawing blockTable
  18.                    db.Insert(blockName, tmpDb, true);
  19.                }
  20.  
  21.                PromptPointResult ppr = ed.GetPoint("\nSpecify insertion point: ");
  22.                if( ppr.Status != PromptStatus.OK )
  23.                    return;
  24.  
  25.                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
  26.                BlockReference br = new BlockReference(Point3d.Origin, bt[ blockName ]);
  27.  
  28.                br.TransformBy(Matrix3d
  29.                    .Displacement(ppr.Value - Point3d.Origin)
  30.                    .PreMultiplyBy(ed.CurrentUserCoordinateSystem));
  31.  
  32.                btr.AppendEntity(br);
  33.                tr.AddNewlyCreatedDBObject(br, true);
  34.                tr.Commit();
  35.            }
  36.        }
  37.        //=======================================================================
  38.  
« Last Edit: December 18, 2011, 12:44:55 am by Kerry »
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate<--

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 10832
  • class keyThumper<T>:ILazy<T>
Re: BlockTesting2011
« Reply #5 on: March 31, 2011, 05:19:18 am »
Next; Rotations with Displacement and Scale
.
Be carefull with the sequence for the PreMultiplyBy method
We usually do not want the  Displacement rotated.

If you DO want the displacement rotated swap the sequence of the Rotation and Displacement
Like this
Code - C#: [Select]
  1.  
  2.            Matrix3d Transform = Matrix3d
  3.                .Scaling(scale, Point3d.Origin)                
  4.                .PreMultiplyBy(Matrix3d.Displacement(DispacementVector))
  5.                .PreMultiplyBy(Matrix3d.Rotation(rotation, zAxis, Point3d.Origin))              
  6.                .PreMultiplyBy(ed.CurrentUserCoordinateSystem);
  7.  
  8.  

Code - C#: [Select]
  1.  
  2.        //=======================================================================
  3.        public const double kPi = 3.14159265358979323846;
  4.        //=======================================================================
  5.        public static double RadiansToDegrees(double radians)
  6.        {
  7.            return (radians * (kPi / 180.0));
  8.        }
  9.        //=======================================================================
  10.  

Code - C#: [Select]
  1.       //=======================================================================
  2.        // add the block to the current space (Model or Paper).
  3.        // block is exploded IE: copy of original
  4.        // Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
  5.        // and transformed for Scale
  6.        // and transformed for Rotation
  7.        // and transformed for Displacement
  8.        // does not handle Attributes
  9.  
  10.        [CommandMethod("BI_6")]
  11.        public void BlockInsert_6()
  12.        {
  13.            string blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg";
  14.            double scale = 3.0;
  15.            Vector3d DispacementVector = new Vector3d(-20, -50, 0);
  16.            Vector3d zAxis = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis;
  17.            double rotation = RadiansToDegrees(15.0);
  18.            //
  19.            Database tmpDb = new Database(false, true);
  20.            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");
  21.  
  22.            Matrix3d Transform = Matrix3d
  23.                .Scaling(scale, Point3d.Origin)
  24.                .PreMultiplyBy(Matrix3d.Rotation(rotation, zAxis, Point3d.Origin))
  25.                .PreMultiplyBy(Matrix3d.Displacement(DispacementVector))                
  26.                .PreMultiplyBy(ed.CurrentUserCoordinateSystem);
  27.  
  28.            db.Insert(Transform, tmpDb, true);
  29.        }
  30.        //=======================================================================
  31.  
« Last Edit: December 18, 2011, 12:45:34 am by Kerry »
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate<--

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 10832
  • class keyThumper<T>:ILazy<T>
Re: BlockTesting2011
« Reply #6 on: March 31, 2011, 07:34:23 pm »
Next Stage :
Inserting Attributes.

Updated Solution Zip added:

Library stuff:
Code - C#: [Select]
  1.        //=======================================================================
  2.        /// <summary>
  3.        /// Insert ALL AttributeReferences from BlockTableRecord into BlockReference
  4.        /// </summary>
  5.        /// <param name="blkRef"></param>
  6.        /// <param name="tr"></param>
  7.        public static void InsertAttibuteInBlockRef(
  8.            BlockReference blkRef,
  9.            Transaction tr)
  10.        {
  11.            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead);
  12.            foreach( ObjectId attId in btr ) {
  13.                Entity ent = (Entity)tr.GetObject(attId, OpenMode.ForRead);
  14.                if( ent is AttributeDefinition ) {
  15.                    AttributeDefinition attDef = (AttributeDefinition)ent;
  16.                    AttributeReference attRef = new AttributeReference();
  17.                    attRef.SetAttributeFromBlock(attDef, blkRef.BlockTransform);
  18.                    ObjectId id = blkRef.AttributeCollection.AppendAttribute(attRef);
  19.                    tr.AddNewlyCreatedDBObject(attRef, true);
  20.                }
  21.            }
  22.        }
  23.        //=======================================================================
  24.        /// <summary>
  25.        ///  Insert ALL AttributeReferences from BlockTableRecord into BlockReference
  26.        ///  Set the value of Attribute 'attributeTag' to 'attributeText'
  27.        /// </summary>
  28.        /// <param name="blkRef"></param>
  29.        /// <param name="attributeTag"></param>
  30.        /// <param name="attributeText"></param>
  31.        /// <param name="tr"></param>
  32.        public static void InsertAttibuteInBlockRef(
  33.            BlockReference blkRef,
  34.            string attributeTag,
  35.            string attributeText,
  36.            Transaction tr)
  37.        {
  38.            BlockTableRecord btr = (BlockTableRecord)tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead);
  39.            foreach( ObjectId attId in btr ) {
  40.                Entity ent = (Entity)tr.GetObject(attId, OpenMode.ForRead);
  41.                if( ent is AttributeDefinition ) {
  42.                    AttributeDefinition attDef = (AttributeDefinition)ent;
  43.                    AttributeReference attRef = new AttributeReference();
  44.                    attRef.SetAttributeFromBlock(attDef, blkRef.BlockTransform);
  45.                    if( attRef.Tag == attributeTag )
  46.                        attRef.TextString = attributeText;
  47.                    ObjectId id = blkRef.AttributeCollection.AppendAttribute(attRef);
  48.                    tr.AddNewlyCreatedDBObject(attRef, true);
  49.                }
  50.            }
  51.        }
  52.        //=======================================================================
  53.  


Test Routines:
Code - C#: [Select]
  1.       //=======================================================================
  2.        // add the block to the ActiveDrawing CurrentSpace
  3.        // Imports the Block if not found in the BlockTable
  4.        // Adds ALL AttributeReference to the BlockReference
  5.  
  6.        [CommandMethod("BI_15")]
  7.        public void BlockInsert_15()
  8.        {
  9.            string blockQualifiedFileName = "K:\\ToTest\\3Dblock_A.dwg";
  10.            string blockName = "3Dblock_A";
  11.  
  12.            using( Transaction tr = db.TransactionManager.StartTransaction() ) {
  13.                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
  14.                if( !bt.Has(blockName) ) {
  15.                    Database tmpDb = new Database(false, true);
  16.                    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");
  17.                    // add the block to the ActiveDrawing blockTable
  18.                    db.Insert(blockName, tmpDb, true);
  19.                }
  20.  
  21.                PromptPointResult ppr = ed.GetPoint("\nSpecify insertion point: ");
  22.                if( ppr.Status != PromptStatus.OK )
  23.                    return;
  24.  
  25.                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
  26.  
  27.                using( BlockReference br = new BlockReference(Point3d.Origin, bt[ blockName ]) ) {
  28.                    br.TransformBy(Matrix3d
  29.                        .Displacement(ppr.Value - Point3d.Origin)
  30.                        .PreMultiplyBy(ed.CurrentUserCoordinateSystem));
  31.  
  32.                    btr.AppendEntity(br);
  33.                    tr.AddNewlyCreatedDBObject(br, true);
  34.                    //                    
  35.                    InsertAttibuteInBlockRef(br, tr);
  36.                }
  37.                tr.Commit();
  38.            }
  39.        }
  40.        //=======================================================================
  41.  

Code - C#: [Select]
  1.        //=======================================================================
  2.        // add the block to the ActiveDrawing CurrentSpace
  3.        // Imports the Block if not found in the BlockTable
  4.        // Adds ALL AttributeReference to the BlockReference
  5.        // Set the attributeText in a nominated
  6.  
  7.        [CommandMethod("BI_16")]
  8.        public void BlockInsert_16()
  9.        {
  10.            string blockQualifiedFileName = "K:\\ToTest\\3Dblock_A.dwg";
  11.            string blockName = "3Dblock_A";
  12.            string attTag = "ATTRIBUTETAG";
  13.            string attText = "Yes, we have no bananas";
  14.  
  15.            using( Transaction tr = db.TransactionManager.StartTransaction() ) {
  16.                BlockTable bt = (BlockTable)tr.GetObject(db.BlockTableId, OpenMode.ForRead);
  17.                if( !bt.Has(blockName) ) {
  18.                    Database tmpDb = new Database(false, true);
  19.                    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "");
  20.                    // add the block to the ActiveDrawing blockTable
  21.                    db.Insert(blockName, tmpDb, true);
  22.                }
  23.  
  24.                PromptPointResult ppr = ed.GetPoint("\nSpecify insertion point: ");
  25.                if( ppr.Status != PromptStatus.OK )
  26.                    return;
  27.  
  28.                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
  29.  
  30.                using( BlockReference br = new BlockReference(Point3d.Origin, bt[ blockName ]) ) {
  31.                    br.TransformBy(Matrix3d
  32.                        .Displacement(ppr.Value - Point3d.Origin)
  33.                        .PreMultiplyBy(ed.CurrentUserCoordinateSystem));
  34.  
  35.                    btr.AppendEntity(br);
  36.                    tr.AddNewlyCreatedDBObject(br, true);
  37.                    //                    
  38.                    InsertAttibuteInBlockRef(br, attTag, attText, tr);
  39.                }
  40.                tr.Commit();
  41.            }
  42.        }
  43.        //=======================================================================
  44.  
« Last Edit: December 18, 2011, 12:46:16 am by Kerry »
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate<--

Jeff H

  • Needs a day job
  • Posts: 4707
Re: BlockTesting2011
« Reply #7 on: April 01, 2011, 07:47:27 pm »
Laying it out the same as Kerry.
You will notice the extra calls to DirectCast because
Option strict is on.

I used http://www.developerfusion.com/tools/convert/csharp-to-vb/ to check and did good job only messed up a couple of things.

I will attach zip in last post and update along with kerry.

Container:
Code - vb.net: [Select]
  1. 'Option strict and explicit are turned on
  2. 'Code converted from C#
  3. 'Original C# code located  @ http://www.theswamp.org/index.php?topic=37686.0
  4. 'Check link in above line as code is posted for learning resource and likely to be updated.
  5. 'Please thank Kerry at above link
  6. 'If something is wrong it is probably error converting from C#
  7.  
  8. 'CodeHimBelonga kdub@theSwamp 20110331
  9.  
  10.  
  11. Imports Autodesk.AutoCAD.Runtime
  12. Imports Autodesk.AutoCAD.ApplicationServices
  13. Imports Autodesk.AutoCAD.DatabaseServices
  14. Imports Autodesk.AutoCAD.Geometry
  15. Imports Autodesk.AutoCAD.EditorInput
  16. Imports Autodesk.AutoCAD.ApplicationServices.Application
  17. Imports AcUtils = Autodesk.AutoCAD.Internal.Utils
  18.  
  19. <Assembly: CommandClass(GetType(KdubTesting.BlockTesting2011))>
  20.  
  21.    Namespace KdubTesting
  22.        Public Class BlockTesting2011
  23.            Private doc As Document
  24.            Private db As Database
  25.            Private ed As Editor
  26.  
  27.            Public Sub New()
  28.                ActiveDoc = AcadApp.DocumentManager.MdiActiveDocument
  29.            End Sub
  30.  
  31.            Private Property ActiveDoc() As Document
  32.                Get
  33.                    Return doc
  34.                End Get
  35.  
  36.                Set(ByVal value As Document)
  37.                    doc = value
  38.  
  39.                    If doc = Nothing Then
  40.                        db = Nothing
  41.                        ed = Nothing
  42.                    Else
  43.                        db = doc.Database
  44.                        ed = doc.Editor
  45.                    End If
  46.                End Set
  47.  
  48.            End Property
  49.            '=======================================================================
  50.  
  51.            ' Methods go here < snip>
  52.            '=======================================================================
  53.        End Class
  54.  
  55.    End Namespace
  56.  

Code - vb.net: [Select]
  1.  
  2.        <CommandMethod("BI_1")> _
  3.        Public Sub BlockInsert_1()
  4.            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock_A.dwg"
  5.            Dim blockName As String = "3Dblock_A"
  6.            Dim tmpDb As New Database(False, True)
  7.            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")
  8.  
  9.            ' add the block to the ActiveDrawing blockTable
  10.            db.Insert(blockName, tmpDb, True)
  11.  
  12.            ' add the block to the ActiveDrawing blockTable with a Temporary Name
  13.            db.Insert("TmpTest", tmpDb, True)
  14.        End Sub
  15.  
Code - vb.net: [Select]
  1. '=======================================================================
  2.        ' add the block to the current space (Model or Paper).
  3.        ' block is exploded IE: copy of original
  4.        ' Insert will be at World 0,0,0 and transformed for Scale
  5.  
  6.        <CommandMethod("BI_2")> _
  7.        Public Sub BlockInsert_2()
  8.            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock_A.dwg"
  9.            Dim scale As Double = 5.0
  10.  
  11.            Dim tmpDb As New Database(False, True)
  12.            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")
  13.  
  14.            Dim Transform As Matrix3d = Matrix3d.Scaling(scale, Point3d.Origin).PreMultiplyBy(Matrix3d.Identity)
  15.  
  16.            db.Insert(Transform, tmpDb, True)
  17.        End Sub
  18.  

Code - vb.net: [Select]
  1. '=======================================================================
  2.        ' add the block to the current space (Model or Paper).
  3.        ' block is exploded IE: copy of original
  4.        ' Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
  5.        ' and transformed for Scale
  6.  
  7.        <CommandMethod("BI_3")> _
  8.        Public Sub BlockInsert_3()
  9.            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock.dwg"
  10.            Dim scale As Double = 2.5
  11.  
  12.            Dim tmpDb As New Database(False, True)
  13.            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")
  14.  
  15.            Dim Transform As Matrix3d = Matrix3d _
  16.                .Scaling(scale, Point3d.Origin) _
  17.                .PreMultiplyBy(ed.CurrentUserCoordinateSystem)
  18.  
  19.            db.Insert(Transform, tmpDb, True)
  20.        End Sub
  21.  
Code - vb.net: [Select]
  1.  '=======================================================================
  2.        ' add the block to the current space (Model or Paper).
  3.        ' block is exploded IE: copy of original
  4.        ' Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
  5.        ' and transformed for Scale
  6.        ' and transformed for Displacement
  7.  
  8.        <CommandMethod("BI_4")> _
  9.        Public Sub BlockInsert_4()
  10.            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock.dwg"
  11.            Dim scale As Double = 3.0
  12.            Dim DispacementVector As New Vector3d(20, 50, 0)
  13.            '
  14.            Dim tmpDb As New Database(False, True)
  15.            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")
  16.  
  17.            Dim Transform As Matrix3d = Matrix3d _
  18.                                        .Scaling(scale, Point3d.Origin) _
  19.                                        .PreMultiplyBy(Matrix3d.Displacement(DispacementVector)) _
  20.                                        .PreMultiplyBy(ed.CurrentUserCoordinateSystem)
  21.  
  22.            db.Insert(Transform, tmpDb, True)
  23.        End Sub
  24.  
Code - vb.net: [Select]
  1.  
  2.        '=======================================================================
  3.        ' add the block to the current space (Model or Paper).
  4.        ' block is exploded IE: copy of original
  5.        ' Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
  6.        ' and transformed for Scale
  7.        ' and transformed for Displacement
  8.  
  9.        <CommandMethod("BI_5")> _
  10.        Public Sub BlockInsert_5()
  11.            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock_a.dwg"
  12.            Dim scale As Double = 3.0
  13.            Dim DispacementVector As New Vector3d(20, 50, 0)
  14.            '
  15.            Dim tmpDb As New Database(False, True)
  16.            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")
  17.  
  18.            Dim Transform As Matrix3d = Matrix3d _
  19.                                        .Scaling(scale, Point3d.Origin) _
  20.                                        .PreMultiplyBy(Matrix3d.Displacement(DispacementVector)) _
  21.                                        .PreMultiplyBy(ed.CurrentUserCoordinateSystem)
  22.  
  23.            db.Insert(Transform, tmpDb, True)
  24.        End Sub
  25.  
« Last Edit: January 25, 2012, 07:01:31 am by Kerry »

Jeff H

  • Needs a day job
  • Posts: 4707
Re: BlockTesting2011
« Reply #8 on: April 01, 2011, 07:55:19 pm »
Next series :
Refer notations.

Transforms use PreMultiplyBy method as suggested by gile  :-)


Code - vb.net: [Select]
  1.  '=======================================================================
  2.  
  3.        '=======================================================================
  4.        ' add the block to the ActiveDrawing CurrentSpace
  5.        ' Expects to find the Block in the BlockTable
  6.        ' does not handle Attributes
  7.  
  8.        <CommandMethod("BI_10")> _
  9.        Public Sub BlockInsert_10()
  10.            Dim blockName As String = "3Dblock"
  11.  
  12.            Using tr As Transaction = db.TransactionManager.StartTransaction()
  13.                Dim bt As BlockTable = DirectCast(tr.GetObject(db.BlockTableId, OpenMode.ForRead), BlockTable)
  14.  
  15.                If Not bt.Has(blockName) Then
  16.                    ed.WriteMessage(vbLf & "Block '{0}' is not available in the current drawing.", blockName)
  17.                    Return
  18.                End If
  19.  
  20.                Dim ppr As PromptPointResult = ed.GetPoint(vbLf & "Specify insertion point: ")
  21.  
  22.                If ppr.Status <> PromptStatus.OK Then
  23.                    Return
  24.                End If
  25.  
  26.                Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
  27.                Dim br As New BlockReference(Point3d.Origin, bt(blockName))
  28.  
  29.                br.TransformBy(Matrix3d.Displacement(ppr.Value - Point3d.Origin) _
  30.                               .PreMultiplyBy(ed.CurrentUserCoordinateSystem))
  31.  
  32.                btr.AppendEntity(br)
  33.                tr.AddNewlyCreatedDBObject(br, True)
  34.                tr.Commit()
  35.  
  36.            End Using
  37.        End Sub
  38.  

Code - vb.net: [Select]
  1. '=======================================================================
  2.        ' add the block to the ActiveDrawing CurrentSpace
  3.        ' Imports the Block if not found in the BlockTable
  4.        ' does not handle Attributes
  5.  
  6.        <CommandMethod("BI_11")> _
  7.        Public Sub BlockInsert_11()
  8.  
  9.            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock.dwg"
  10.            Dim blockName As String = "3Dblock"
  11.  
  12.            Using tr As Transaction = db.TransactionManager.StartTransaction()
  13.                Dim bt As BlockTable = DirectCast(tr.GetObject(db.BlockTableId, OpenMode.ForRead), BlockTable)
  14.  
  15.                If Not bt.Has(blockName) Then
  16.                    Dim tmpDb As New Database(False, True)
  17.                    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")
  18.                    ' add the block to the ActiveDrawing blockTable
  19.                    db.Insert(blockName, tmpDb, True)
  20.                End If
  21.  
  22.                Dim ppr As PromptPointResult = ed.GetPoint(vbLf & "Specify insertion point: ")
  23.  
  24.                If ppr.Status <> PromptStatus.OK Then
  25.                    Return
  26.                End If
  27.  
  28.                Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
  29.                Dim br As New BlockReference(Point3d.Origin, bt(blockName))
  30.  
  31.                br.TransformBy(Matrix3d.Displacement(ppr.Value - Point3d.Origin) _
  32.                               .PreMultiplyBy(ed.CurrentUserCoordinateSystem))
  33.  
  34.                btr.AppendEntity(br)
  35.                tr.AddNewlyCreatedDBObject(br, True)
  36.                tr.Commit()
  37.  
  38.            End Using
  39.        End Sub
  40.  



Rotations with Displacement and Scale
.
Be carefull with the sequence for the PreMultiplyBy method
We usually do not want the  Displacement rotated.

If you DO want the displacement rotated swap the sequence of the Rotation and Displacement
Like this
Code - vb.net: [Select]
  1.            Dim Transform As Matrix3d = Matrix3d _
  2.                                     .Scaling(scale, Point3d.Origin) _
  3.                                     .PreMultiplyBy(Matrix3d.Displacement(DispacementVector)) _
  4.                                     .PreMultiplyBy(Matrix3d.Rotation(rotation, zAxis, Point3d.Origin)) _
  5.                                     .PreMultiplyBy(ed.CurrentUserCoordinateSystem)
  6.  
  7.            db.Insert(Transform, tmpDb, True)
  8.  

Code - vb.net: [Select]
  1.        '=======================================================================
  2.        Public Const kPi As Double = 3.1415926535897931
  3.        '=======================================================================
  4.        Public Shared Function RadiansToDegrees(ByVal radians As Double) As Double
  5.            Return radians * (kPi / 180.0)
  6.        End Function
  7.  

Code - vb.net: [Select]
  1.  
  2.        '=======================================================================
  3.        '=======================================================================
  4.        ' add the block to the current space (Model or Paper).
  5.        ' block is exploded IE: copy of original
  6.        ' Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
  7.        ' and transformed for Scale
  8.        ' and transformed for Rotation
  9.        ' and transformed for Displacement
  10.        ' does not handle Attributes
  11.  
  12.        <CommandMethod("BI_6")> _
  13.        Public Sub BlockInsert_6()
  14.            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock.dwg"
  15.            Dim scale As Double = 3.0
  16.            Dim DispacementVector As New Vector3d(-20, -50, 0)
  17.            Dim zAxis As Vector3d = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis
  18.            Dim rotation As Double = RadiansToDegrees(15.0)
  19.            '
  20.            Dim tmpDb As New Database(False, True)
  21.            tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")
  22.  
  23.            Dim Transform As Matrix3d = Matrix3d _
  24.                                        .Scaling(scale, Point3d.Origin) _
  25.                                        .PreMultiplyBy(Matrix3d.Rotation(rotation, zAxis, Point3d.Origin)) _
  26.                                        .PreMultiplyBy(Matrix3d.Displacement(DispacementVector)) _
  27.                                        .PreMultiplyBy(ed.CurrentUserCoordinateSystem)
  28.  
  29.        End Sub
  30.  
« Last Edit: January 25, 2012, 07:00:51 am by Kerry »

Jeff H

  • Needs a day job
  • Posts: 4707
Re: BlockTesting2011
« Reply #9 on: April 01, 2011, 08:03:59 pm »
********************Edit***************
Solution Updated 4/4/2011
********************End Edit***************
Next Stage :
Inserting Attributes.

Solution Zip added for everything posted:
Library stuff:
Code - vb.net: [Select]
  1.        '=======================================================================
  2.        '=======================================================================
  3.        ''' <summary>
  4.        ''' Insert ALL AttributeReferences from BlockTableRecord into BlockReference
  5.        ''' </summary>
  6.        ''' <param name="blkRef"></param>
  7.        ''' <param name="tr"></param>
  8.        Public Shared Sub InsertAttibuteInBlockRef(blkRef As BlockReference, tr As Transaction)
  9.            Dim btr As BlockTableRecord = DirectCast(tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead), BlockTableRecord)
  10.  
  11.            For Each attId As ObjectId In btr
  12.                Dim ent As Entity = DirectCast(tr.GetObject(attId, OpenMode.ForRead), Entity)
  13.  
  14.                If TypeOf ent Is AttributeDefinition Then
  15.  
  16.                    Dim attDef As AttributeDefinition = DirectCast(ent, AttributeDefinition)
  17.                    Dim attRef As New AttributeReference()
  18.  
  19.                    attRef.SetAttributeFromBlock(attDef, blkRef.BlockTransform)
  20.  
  21.                    Dim id As ObjectId = blkRef.AttributeCollection.AppendAttribute(attRef)
  22.                    tr.AddNewlyCreatedDBObject(attRef, True)
  23.  
  24.                End If
  25.  
  26.            Next
  27.  
  28.        End Sub
  29.  
  30.        '=======================================================================
  31.        ''' <summary>
  32.        '''  Insert ALL AttributeReferences from BlockTableRecord into BlockReference
  33.        '''  Set the value of Attribute 'attributeTag' to 'attributeText'
  34.        ''' </summary>
  35.        ''' <param name="blkRef"></param>
  36.        ''' <param name="attributeTag"></param>
  37.        ''' <param name="attributeText"></param>
  38.        ''' <param name="tr"></param>
  39.        Public Shared Sub InsertAttibuteInBlockRef(blkRef As BlockReference, attributeTag As String, attributeText As String, tr As Transaction)
  40.  
  41.            Dim btr As BlockTableRecord = DirectCast(tr.GetObject(blkRef.BlockTableRecord, OpenMode.ForRead), BlockTableRecord)
  42.  
  43.            For Each attId As ObjectId In btr
  44.                Dim ent As Entity = DirectCast(tr.GetObject(attId, OpenMode.ForRead), Entity)
  45.  
  46.                If TypeOf ent Is AttributeDefinition Then
  47.  
  48.                    Dim attDef As AttributeDefinition = DirectCast(ent, AttributeDefinition)
  49.                    Dim attRef As New AttributeReference()
  50.                    attRef.SetAttributeFromBlock(attDef, blkRef.BlockTransform)
  51.  
  52.                    If attRef.Tag = attributeTag Then
  53.                        attRef.TextString = attributeText
  54.                    End If
  55.  
  56.                    Dim id As ObjectId = blkRef.AttributeCollection.AppendAttribute(attRef)
  57.                    tr.AddNewlyCreatedDBObject(attRef, True)
  58.  
  59.                End If
  60.  
  61.            Next
  62.  
  63.        End Sub
  64.  


Test Routines:
Code - vb.net: [Select]
  1.        '=======================================================================
  2.        '=======================================================================
  3.        ' add the block to the ActiveDrawing CurrentSpace
  4.        ' Imports the Block if not found in the BlockTable
  5.        ' Adds ALL AttributeReference to the BlockReference
  6.  
  7.        <CommandMethod("BI_15")> _
  8.        Public Sub BlockInsert_15()
  9.  
  10.            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock_A.dwg"
  11.            Dim blockName As String = "3Dblock_A"
  12.  
  13.            Using tr As Transaction = db.TransactionManager.StartTransaction()
  14.  
  15.                Dim bt As BlockTable = DirectCast(tr.GetObject(db.BlockTableId, OpenMode.ForRead), BlockTable)
  16.  
  17.                If Not bt.Has(blockName) Then
  18.                    Dim tmpDb As New Database(False, True)
  19.                    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")
  20.                    ' add the block to the ActiveDrawing blockTable
  21.                    db.Insert(blockName, tmpDb, True)
  22.                End If
  23.  
  24.                Dim ppr As PromptPointResult = ed.GetPoint(vbLf & "Specify insertion point: ")
  25.  
  26.                If ppr.Status <> PromptStatus.OK Then
  27.                    Return
  28.                End If
  29.  
  30.                Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
  31.  
  32.                Using br As New BlockReference(Point3d.Origin, bt(blockName))
  33.                    br.TransformBy(Matrix3d.Displacement(ppr.Value - Point3d.Origin).PreMultiplyBy(ed.CurrentUserCoordinateSystem))
  34.  
  35.                    btr.AppendEntity(br)
  36.                    tr.AddNewlyCreatedDBObject(br, True)
  37.                    '                    
  38.                    InsertAttibuteInBlockRef(br, tr)
  39.                End Using
  40.  
  41.                tr.Commit()
  42.            End Using
  43.        End Sub
  44.  

Code - vb.net: [Select]
  1.        '=======================================================================
  2.        ' add the block to the ActiveDrawing CurrentSpace
  3.        ' Imports the Block if not found in the BlockTable
  4.        ' Adds ALL AttributeReference to the BlockReference
  5.        ' Set the attributeText in a nominated
  6.  
  7.        <CommandMethod("BI_16")> _
  8.        Public Sub BlockInsert_16()
  9.  
  10.            Dim blockQualifiedFileName As String = "K:\ToTest\3Dblock_A.dwg"
  11.            Dim blockName As String = "3Dblock_A"
  12.            Dim attTag As String = "ATTRIBUTETAG"
  13.            Dim attText As String = "Yes, we have no bananas"
  14.  
  15.            Using tr As Transaction = db.TransactionManager.StartTransaction()
  16.  
  17.                Dim bt As BlockTable = DirectCast(tr.GetObject(db.BlockTableId, OpenMode.ForRead), BlockTable)
  18.  
  19.                If Not bt.Has(blockName) Then
  20.                    Dim tmpDb As New Database(False, True)
  21.                    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, True, "")
  22.                    ' add the block to the ActiveDrawing blockTable
  23.                    db.Insert(blockName, tmpDb, True)
  24.                End If
  25.  
  26.                Dim ppr As PromptPointResult = ed.GetPoint(vbLf & "Specify insertion point: ")
  27.  
  28.                If ppr.Status <> PromptStatus.OK Then
  29.                    Return
  30.                End If
  31.  
  32.                Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
  33.  
  34.                Using br As New BlockReference(Point3d.Origin, bt(blockName))
  35.                    br.TransformBy(Matrix3d.Displacement(ppr.Value - Point3d.Origin).PreMultiplyBy(ed.CurrentUserCoordinateSystem))
  36.  
  37.                    btr.AppendEntity(br)
  38.                    tr.AddNewlyCreatedDBObject(br, True)
  39.                    '                    
  40.                    InsertAttibuteInBlockRef(br, attTag, attText, tr)
  41.                End Using
  42.  
  43.                tr.Commit()
  44.            End Using
  45.  
  46.        End Sub
  47.  
« Last Edit: January 25, 2012, 07:08:56 am by Kerry »

gile

  • Water Moccasin
  • Posts: 1741
  • Marseille, France
Re: BlockTesting2011
« Reply #10 on: April 02, 2011, 12:34:22 pm »
Should I try a F# translation ?
Speaking English as a French Frog

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 10832
  • class keyThumper<T>:ILazy<T>
Re: BlockTesting2011
« Reply #11 on: April 02, 2011, 05:22:34 pm »

Sure gile.
I'm trying to concentrate on concepts not language so any 'language' questions that arise  can be split off this topic.

Regards,
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate<--

gile

  • Water Moccasin
  • Posts: 1741
  • Marseille, France
Re: BlockTesting2011
« Reply #12 on: April 02, 2011, 06:09:59 pm »
So, here's a F# translation of  the C# code from the 'BlockTesting2011 _20110331.1115' source.
Maybe it's not 'very good' F# coding (I'm newby) but every command seems to work as expected (and it was a fine exercice).

If you don't use VS 2010 pro,
- to run the dll, you have to install the F# runtime.
- to play with F#, you can add F# to Visual Studio 2008 (Standard edition or greater) or use a free Visual Studio Shell (2008 or 2010) see here.

I'll post the code the same way as Kerry and Jeff H to make easier comparisons, just adding some 'off code' comments for F# main differences from C# or VB.

Container
No need to contain all functions in a class
Code - F#: [Select]
  1. // Code translated from C#
  2. // Original C# code located  @ http://www.theswamp.org/index.php?topic=37686.0
  3. // Check link in above line as code is posted for learning resource and likely to be updated.
  4. // Please thank Kerry at above link
  5.  
  6. module KdubTesting.BlockTesting2011
  7.  
  8. open System
  9. open System.IO
  10. open Autodesk.AutoCAD.ApplicationServices
  11. open Autodesk.AutoCAD.DatabaseServices
  12. open Autodesk.AutoCAD.EditorInput
  13. open Autodesk.AutoCAD.Geometry
  14. open Autodesk.AutoCAD.Runtime
  15.  
  16. type AcAp = Autodesk.AutoCAD.ApplicationServices.Application
  17. type AcUt = Autodesk.AutoCAD.Internal.Utils
  18.  
  19. let doc = AcAp.DocumentManager.MdiActiveDocument
  20. let db = doc.Database
  21. let ed = doc.Editor
  22.  
  23. // Functions go here
  24. //=======================================================================

Code - F#: [Select]
  1. //=======================================================================
  2. // add the block to the ActiveDrawing blockTable
  3. [<CommandMethod("BI_1")>]
  4. let blockInsert_1 () =
  5.    let blockQualifiedFileName = "K:\\ToTest\\3Dblock_A.dwg"
  6.    let blockName = "3DBlock_a"
  7.  
  8.    use tmpDb = new Database()
  9.    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "")
  10.  
  11.    // add the block to the ActiveDrawing blockTable
  12.    db.Insert(blockName, tmpDb, true) |> ignore
  13.  
  14.    // add the block to the ActiveDrawing blockTable with a Temporary Name
  15.    db.Insert("TmpTest", tmpDb, true) |> ignore
  16. //=======================================================================

Code - F#: [Select]
  1. //=======================================================================
  2. // add the block to the current space (Model or Paper).
  3. // block is exploded IE: copy of original
  4. // Insert will be at World 0,0,0 and transformed for Scale
  5. [<CommandMethod("BI_2")>]
  6. let blockInsert_2 () =
  7.    let blockQualifiedFileName = "K:\\ToTest\\3Dblock_A.dwg"
  8.    let scale = 5.0
  9.  
  10.    use tmpDb = new Database()
  11.    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "")
  12.    let transform = Matrix3d.Scaling(scale, Point3d.Origin)
  13.    db.Insert(transform, tmpDb, true)
  14. //=======================================================================

The matrix multiplication uses 'pipe-lining' operator which looks like the PreMultiplyBy method
Code - F#: [Select]
  1. //=======================================================================
  2. // add the block to the current space (Model or Paper).
  3. // block is exploded IE: copy of original
  4. // Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
  5. // and transformed for Scale
  6. [<CommandMethod("BI_3")>]
  7. let blockInsert_3 () =
  8.    let blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg"
  9.    let scale = 2.5
  10.  
  11.    use tmpDb = new Database()
  12.    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "")
  13.    let transform = Matrix3d.Scaling(scale, Point3d.Origin)
  14.                    |> (*) ed.CurrentUserCoordinateSystem
  15.    db.Insert(transform, tmpDb, true)
  16. //=======================================================================

Code - F#: [Select]
  1. //=======================================================================
  2. // add the block to the current space (Model or Paper).
  3. // block is exploded IE: copy of original
  4. // Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
  5. // and transformed for Scale
  6. // and transformed for Displacement
  7. [<CommandMethod("BI_4")>]
  8. let blockInsert_4 () =
  9.    let blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg"
  10.    let scale = 3.0
  11.    let dispacementVector = new Vector3d(20.0, 50.0, 0.0)
  12.  
  13.    use tmpDb = new Database()
  14.    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "")
  15.    let transform = Matrix3d.Scaling(scale, Point3d.Origin)
  16.                    |> (*) (Matrix3d.Displacement(dispacementVector))
  17.                    |> (*) ed.CurrentUserCoordinateSystem
  18.    db.Insert(transform, tmpDb, true)
  19. //=======================================================================

« Last Edit: January 25, 2012, 07:12:18 am by Kerry »
Speaking English as a French Frog

gile

  • Water Moccasin
  • Posts: 1741
  • Marseille, France
Re: BlockTesting2011
« Reply #13 on: April 02, 2011, 06:15:51 pm »
Next; Rotations with Displacement and Scale

renamed RadiansToDegrees into degreesToRadians which seems more correct
Code - F#: [Select]
  1. //=======================================================================
  2. let kPi = 3.14159265358979323846
  3. //=======================================================================
  4. let degreesToRadians degrees =
  5.    degrees * (kPi / 180.0)
  6. //=======================================================================

Code - F#: [Select]
  1. //=======================================================================
  2. // add the block to the current space (Model or Paper).
  3. // block is exploded IE: copy of original
  4. // Insert will be at UCS 0,0,0 honouring current X, Y, Z Axis.
  5. // and transformed for Scale
  6. // and transformed for Rotation
  7. // and transformed for Displacement
  8. // does not handle Attributes
  9. [<CommandMethod("BI_6")>]
  10. let blockInsert_6 () =
  11.    let blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg"
  12.    let scale = 3.0
  13.    let dispacementVector = new Vector3d(-20.0, -50.0, 0.0)
  14.    let zAxis = ed.CurrentUserCoordinateSystem.CoordinateSystem3d.Zaxis
  15.    let rotation = degreesToRadians 15.0
  16.  
  17.    use tmpDb = new Database()
  18.    tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "")
  19.    let transform = Matrix3d.Scaling(scale, Point3d.Origin)
  20.                    |> (*) (Matrix3d.Rotation(rotation, zAxis, Point3d.Origin))
  21.                    |> (*) (Matrix3d.Displacement(dispacementVector))
  22.                    |> (*) ed.CurrentUserCoordinateSystem
  23.    db.Insert(transform, tmpDb, true)
  24. //=======================================================================
« Last Edit: January 25, 2012, 07:14:25 am by Kerry »
Speaking English as a French Frog

gile

  • Water Moccasin
  • Posts: 1741
  • Marseille, France
Re: BlockTesting2011
« Reply #14 on: April 02, 2011, 06:18:21 pm »
Next series

Looking in the BlockTable

Code - F#: [Select]
  1. //=======================================================================
  2. // add the block to the ActiveDrawing CurrentSpace
  3. // Expects to find the Block in the BlockTable
  4. // does not handle Attributes
  5. [<CommandMethod("BI_10")>]
  6. let blockInsert_10 () =
  7.    let blockName = "3Dblock"
  8.  
  9.    use tr = db.TransactionManager.StartTransaction()
  10.    let bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) :?> BlockTable
  11.    if bt.Has(blockName) then
  12.        let ppr = ed.GetPoint("\nSpecify insertion point: ")
  13.        if ppr.Status = PromptStatus.OK then
  14.            let btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) :?> BlockTableRecord
  15.            let br = new BlockReference(Point3d.Origin, bt.[blockName])
  16.            br.TransformBy(Matrix3d.Displacement(ppr.Value.GetAsVector())
  17.                           |> (*) ed.CurrentUserCoordinateSystem)
  18.            btr.AppendEntity(br) |> ignore
  19.            tr.AddNewlyCreatedDBObject(br, true)
  20.            tr.Commit()
  21.    else
  22.        ed.WriteMessage("\nBlock '{0}' is not available in the current drawing.", blockName)
  23. //=======================================================================

Code - F#: [Select]
  1. //=======================================================================
  2. // add the block to the ActiveDrawing CurrentSpace
  3. // Imports the Block if not found in the BlockTable
  4. // does not handle Attributes
  5. [<CommandMethod("BI_11")>]
  6. let blockInsert_11 () =
  7.    let blockQualifiedFileName = "K:\\ToTest\\3Dblock.dwg"
  8.    let blockName = "3Dblock"
  9.  
  10.    use tr = db.TransactionManager.StartTransaction()
  11.    let bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) :?> BlockTable
  12.    if not (bt.Has(blockName)) then
  13.        use tmpDb = new Database()
  14.        tmpDb.ReadDwgFile(blockQualifiedFileName, System.IO.FileShare.Read, true, "")
  15.        // add the block to the ActiveDrawing blockTable
  16.        db.Insert(blockName, tmpDb, true) |> ignore
  17.  
  18.    let ppr = ed.GetPoint("\nSpecify insertion point: ")
  19.    if ppr.Status = PromptStatus.OK then
  20.        let btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) :?> BlockTableRecord
  21.        let br = new BlockReference(Point3d.Origin, bt.[blockName])
  22.        br.TransformBy(Matrix3d.Displacement(ppr.Value.GetAsVector())
  23.                       |> (*) ed.CurrentUserCoordinateSystem)
  24.        btr.AppendEntity(br) |> ignore
  25.        tr.AddNewlyCreatedDBObject(br, true)
  26.        tr.Commit()
  27. //=======================================================================
« Last Edit: January 25, 2012, 07:18:28 am by Kerry »
Speaking English as a French Frog