Jump to content

Leaderboard

Popular Content

Showing content with the highest reputation since 09/08/2026 in Posts

  1. Attached is an improved version of getfiled that implements powershell with the option to select single or multiple files returning a list of the selected item(s): Examples: (pl:getfiledps "Select Files" (getvar"dwgprefix") "dwg" 0) ; for single selection of file type dwg (pl:getfiledps "Select Files" (strcat (getenv "userprofile") "\\downloads") "dwg;dxf" 1) ; for multiple selection of file types dwg & dxf Feedback & comments are welcome. pl_getfiledps.lsp
    3 points
  2. From @Steven P's thread. AutoLISP Code Scroll down to Blk_Lib.lsp Blk_Lib.dcl Blk_Lib.doc Also some information on making these types of DCL. Getting Started with Dcl Dialogs just scroll down for DCLs with slide images and Image buttons. This is pretty good as well. https://www.theswamp.org/index.php?topic=20878.msg253445#msg253445
    3 points
  3. Another way to do it: transform lines, polylines/polyarcs, circles or arcs into mutilines. This way we retain the properties of the chosen multiline style. Arcs are simulated with segments. ;; ListBox (gile) ;; Boite de dialogue permettant un ou plusieurs choix dans une liste ;; ;; Arguments ;; title : le titre de la boite de dialogue (chaîne) ;; msg ; message (chaîne), "" ou nil pour aucun ;; keylab : une liste d'association du type ((key1 . label1) (key2 . label2) ...) ;; flag : 0 = liste déroulante ;; 1 = liste choix unique ;; 2 = liste choix multipes ;; ;; Retour : la clé de l'option (flag = 0 ou 1) ou la liste des clés des options (flag = 2) ;; ;; Exemple d'utilisation ;; (listbox "Présentation" "Choisir une présentation" (mapcar 'cons (layoutlist) (layoutlist)) 1) (defun ListBox (title msg keylab flag / tmp file dcl_id choice) (setq tmp (vl-filename-mktemp "tmp.dcl") file (open tmp "w") ) (write-line (strcat "ListBox:dialog{label=\"" title "\";") file ) (if (and msg (/= msg "")) (write-line (strcat ":text{label=\"" msg "\";}") file) ) (write-line (cond ((= 0 flag) "spacer;:popup_list{key=\"lst\";") ((= 1 flag) "spacer;:list_box{key=\"lst\";") (T "spacer;:list_box{key=\"lst\";multiple_select=true;") ) file ) (write-line "}spacer;ok_button;}" file) (close file) (setq dcl_id (load_dialog tmp)) (if (not (new_dialog "ListBox" dcl_id)) (exit) ) (start_list "lst") (mapcar 'add_list (mapcar 'cdr keylab)) (end_list) (action_tile "accept" "(or (= (get_tile \"lst\") \"\") (if (= 2 flag) (progn (foreach n (str2lst (get_tile \"lst\") \" \") (setq choice (cons (nth (atoi n) (mapcar 'car keylab)) choice)) ) (setq choice (reverse choice)) ) (setq choice (nth (atoi (get_tile \"lst\")) (mapcar 'car keylab))) ) ) (done_dialog)" ) (start_dialog) (unload_dialog dcl_id) (vl-file-delete tmp) choice ) (defun def_bulg_pl (ls lb flag_closed / ls lb rad a l_new) (if (not (zerop flag_closed)) (setq ls (append ls (list (car ls))))) (while (cadr ls) (if (zerop (car lb)) (setq l_new (append l_new (list (car ls)))) (progn (setq rad (/ (distance (car ls) (cadr ls)) (sin (* 2.0 (atan (abs (car lb))))) 2.0) a (- (/ pi 2.0) (- pi (* 2.0 (atan (abs (car lb)))))) ) (if (< a 0.0) (setq a (- (* 2.0 pi) a))) (if (or (and (< (car lb) 0.0) (> (car lb) -1.0)) (> (car lb) 1.0)) (setq l_new (append l_new (reverse (cdr (reverse (bulge_pts (polar (car ls) (- (angle (car ls) (cadr ls)) a) rad) (car ls) (cadr ls) rad (car lb))))))) (setq l_new (append l_new (reverse (cdr (reverse (bulge_pts (polar (car ls) (+ (angle (car ls) (cadr ls)) a) rad) (car ls) (cadr ls) rad (car lb))))))) ) ) ) (setq ls (cdr ls) lb (cdr lb)) ) (append l_new (list (car ls))) ) (defun bulge_pts (pt_cen pt_begin pt_end rad sens / inc ang nm p1 p2 lst) (setq inc (angle pt_cen (if (< sens 0.0) pt_end pt_begin)) ang (+ (* 2.0 pi) (angle pt_cen (if (< sens 0.0) pt_begin pt_end))) nm (fix (/ (rem (- ang inc) (* 2.0 pi)) (/ (* pi 2.0) 36.0))) ) (repeat nm (setq p1 (polar pt_cen inc rad) inc (+ inc (/ (* pi 2.0) 36.0)) lst (append lst (list p1)) ) ) (setq p2 (polar pt_cen ang rad) lst (append lst (list p2)) ) (if (< sens 0.0) (reverse lst) lst) ) (defun c:polyarc2ml ( / jspl nbr l_mlstyl sel_styl ent dxf_ent typent name_layer closed lst l_bulg e_next dxf_next oldlayer oldosm key_mod scale_ml) (princ "\nSelect polylines/lines/circles/arcs for transform to multilines: ") (setq jspl (ssget '((0 . "*POLYLINE,LINE,CIRCLE,ARC") (-4 . "<NOT") (-4 . "&") (70 . 124) (-4 . "NOT>"))) nbr 0 ) (cond (jspl (setq l_mlstyl (mapcar 'cdr (vl-remove-if-not '(lambda (x) (= (car x) 3)) (dictsearch (namedobjdict) "ACAD_MLINESTYLE") ) ) ) (while (not (setq sel_styl (listbox "Multilines style" "Choose a Multiline style" (mapcar 'cons l_mlstyl l_mlstyl) 1)))) (setvar "cmlstyle" sel_styl) (initget "Top Zero Bottom") (setq key_mod (getkword (strcat "\nGive justification type [Top/Zero/Bottom] <" (cond ((eq (getvar "cmljust") 0) "Top" ) ((eq (getvar "cmljust") 1) "Zero" ) ((eq (getvar "cmljust") 2) "Bottom" ) ) ">: " ) ) ) (if key_mod (cond ((eq key_mod "Top") (setvar "cmljust" 0)) ((eq key_mod "Zero") (setvar "cmljust" 1)) ((eq key_mod "Bottom") (setvar "cmljust" 2)) ) ) (setq scale_ml (getdist (strcat "\nGive scale for multiline <" (rtos (getvar "cmlscale")) ">: "))) (if scale_ml (setvar "cmlscale" scale_ml)) (setq oldlayer (getvar "clayer") oldosm (getvar "osmode")) (setvar "osmode" 0) (setvar "cmdecho" 0) (command "_.ucs" "_world") (repeat (sslength jspl) (setq typent (cdr (assoc 0 (setq dxf_ent (entget (setq ent (ssname jspl nbr)))))) name_layer (cdr (assoc 8 dxf_ent)) ) (cond ((eq typent "LWPOLYLINE") (setq closed (boole 1 (cdr (assoc 70 dxf_ent)) 1) lst (mapcar '(lambda (x) (trans x ent 1)) (mapcar 'cdr (vl-remove-if '(lambda (x) (/= (car x) 10)) dxf_ent))) l_bulg (mapcar 'cdr (vl-remove-if '(lambda (x) (/= (car x) 42)) dxf_ent)) lst (def_bulg_pl lst l_bulg closed) ) ) ((eq typent "POLYLINE") (setq closed (boole 1 (cdr (assoc 70 dxf_ent)) 1) e_next (entnext ent) ) (while (= "VERTEX" (cdr (assoc 0 (setq dxf_next (entget e_next))))) (if (zerop (boole 1 223 (cdr (assoc 70 dxf_next)))) (setq lst (cons (trans (cdr (assoc 10 dxf_next)) ent 1) lst) l_bulg (cons (cdr (assoc 42 dxf_next)) l_bulg) ) ) (setq e_next (entnext e_next)) ) (setq lst (reverse lst) l_bulg (reverse l_bulg) lst (def_bulg_pl lst l_bulg closed) ) ) ((eq typent "LINE") (setq lst (list (trans (cdr (assoc 10 dxf_ent)) 0 1) (trans (cdr (assoc 11 dxf_ent)) 0 1)) closed 0 ) ) ((eq typent "CIRCLE") (setq lst (bulge_pts (trans (cdr (assoc 10 dxf_ent)) ent 1) (polar (trans (cdr (assoc 10 dxf_ent)) ent 1) 0.0 (cdr (assoc 40 dxf_ent))) (polar (trans (cdr (assoc 10 dxf_ent)) ent 1) (- (* 2.0 pi) (/ (* pi 2.0) 36.0)) (cdr (assoc 40 dxf_ent))) (cdr (assoc 40 dxf_ent)) 1 ) lst (append lst (list (car lst))) closed 1 ) ) ((eq typent "ARC") (setq lst (bulge_pts (trans (cdr (assoc 10 dxf_ent)) ent 1) (polar (trans (cdr (assoc 10 dxf_ent)) ent 1) (cdr (assoc 50 dxf_ent)) (cdr (assoc 40 dxf_ent))) (polar (trans (cdr (assoc 10 dxf_ent)) ent 1) (cdr (assoc 51 dxf_ent)) (cdr (assoc 40 dxf_ent))) (cdr (assoc 40 dxf_ent)) 1 ) closed 0 ) ) ) (cond (lst (setvar "clayer" name_layer) (command "_.mline") (foreach n lst (command n)) (if (not (zerop closed)) (command "_close") (command "")) (entdel ent) ) ) (setq nbr (1+ nbr) lst nil l_bulg nil) ) (command "_.ucs" "_previous") (setvar "clayer" oldlayer) (setvar "osmode" oldosm) (setvar "cmdecho" 1) ) (T (princ "\nSelect is empty")) ) (prin1) )
    3 points
  4. @Danielm103 Well I did managed to scrape some milliseconds. However not where it counts in the pairing. Most of the gain in collection of entities. So in the end it is still gile's code. ymg Command: PAIRKD --------- TIMING ------------------------------- Collecting entities: 236 milliseconds Building kdTree: 67 milliseconds Pairing lines and texts: 34 milliseconds Coloring lines and texts: 123 milliseconds Total Elapsed Time: 460 milliseconds Total Number of Groups: 102 using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Gile.AutoCAD.R20.Geometry; using Autodesk.AutoCAD.EditorInput; using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.Geometry; using Autodesk.AutoCAD.Runtime; using AcAp = Autodesk.AutoCAD.ApplicationServices.Core.Application; [assembly: CommandClass(typeof(PairLinesWithTextsR17.Commands))] namespace PairLinesWithTextsR17 { public class Commands { private struct EntityPosition { public Entity Entity { get; } public Point3d Position { get; } public EntityPosition(Entity entity, Point3d position) { Entity = entity; Position = position; } } [CommandMethod("PAIRKD")] public void ParallelPairTextsWithLines3() { // Force GC collection prior to timing to avoid GC halts during execution GC.Collect(); GC.WaitForPendingFinalizers(); Stopwatch stopwatch = Stopwatch.StartNew(); Document doc = AcAp.DocumentManager.MdiActiveDocument; Database db = doc.Database; Editor ed = doc.Editor; RXClass lineClass = RXObject.GetClass(typeof(Line)); RXClass textClass = RXObject.GetClass(typeof(DBText)); // Pre-allocate generous capacity to prevent memory reallocations List<EntityPosition> midLines = new List<EntityPosition>(16384); List<EntityPosition> textList = new List<EntityPosition>(16384); using (doc.LockDocument()) using (Transaction tr = db.TransactionManager.StartOpenCloseTransaction()) { LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead); ObjectId lineLayerId = lt.Has("1") ? lt["1"] : ObjectId.Null; ObjectId textLayerId = lt.Has("4") ? lt["4"] : ObjectId.Null; BlockTableRecord modelSpace = (BlockTableRecord)tr.GetObject( SymbolUtilityServices.GetBlockModelSpaceId(db), OpenMode.ForRead); // 1. Fast Collection Phase foreach (ObjectId id in modelSpace) { RXClass rxClass = id.ObjectClass; if (rxClass == lineClass) { Line line = (Line)tr.GetObject(id, OpenMode.ForRead); if (line.LayerId == lineLayerId) { Point3d midPoint = new Point3d( (line.StartPoint.X + line.EndPoint.X) * 0.5, (line.StartPoint.Y + line.EndPoint.Y) * 0.5, (line.StartPoint.Z + line.EndPoint.Z) * 0.5 ); midLines.Add(new EntityPosition(line, midPoint)); } } else if (rxClass == textClass) { DBText text = (DBText)tr.GetObject(id, OpenMode.ForRead); if (text.LayerId == textLayerId) { Point3d pos = (text.Justify == AttachmentPoint.BaseLeft) ? text.Position : text.AlignmentPoint; textList.Add(new EntityPosition(text, pos)); } } } EntityPosition[][] textGroups = textList .GroupBy(t => ((DBText)t.Entity).TextString) .Select(g => g.ToArray()) .ToArray(); long t1 = stopwatch.ElapsedMilliseconds; // 2. KdTree Construction KdTree<EntityPosition> lineTree = new KdTree<EntityPosition>(midLines, ml => ml.Position, 2); long t2 = stopwatch.ElapsedMilliseconds; // 3. Parallel pairing (Math + Spatial Search) int numGroups = textGroups.Length; HashSet<Entity>[] uniqueGroupEntities = new HashSet<Entity>[numGroups]; Parallel.For(0, numGroups, i => { EntityPosition[] group = textGroups[i]; HashSet<Entity> uniqueSet = new HashSet<Entity>(group.Length * 2); for (int j = 0; j < group.Length; j++) { EntityPosition textItem = group[j]; uniqueSet.Add(textItem.Entity); Entity nearestLine = lineTree.GetNearestNeighbour(textItem.Position).Entity; uniqueSet.Add(nearestLine); } uniqueGroupEntities[i] = uniqueSet; }); long t3 = stopwatch.ElapsedMilliseconds; // 4. Sequential Database Modification Phase for (int i = 0; i < numGroups; i++) { int colorIndex = (i % 255) + 1; HashSet<Entity> uniqueSet = uniqueGroupEntities[i]; foreach (Entity entity in uniqueSet) { if (entity.ColorIndex != colorIndex) { if (!entity.IsWriteEnabled) { entity.UpgradeOpen(); } entity.ColorIndex = colorIndex; } } } long t4 = stopwatch.ElapsedMilliseconds; stopwatch.Stop(); ed.WriteMessage($"\n--------- TIMING -------------------------------"); ed.WriteMessage($"\nCollecting entities: {t1} milliseconds"); ed.WriteMessage($"\nBuilding kdTree: {t2 - t1} milliseconds"); ed.WriteMessage($"\nPairing lines and texts: {t3 - t2} milliseconds"); ed.WriteMessage($"\nColoring lines and texts: {t4 - t3} milliseconds\n"); ed.WriteMessage($"\nTotal Elapsed Time: {t4} milliseconds"); ed.WriteMessage($"\nTotal Number of Groups: {numGroups}"); tr.Commit(); } } } } pairkd.dll
    2 points
  5. The latest version is now in the first post. I used the @BIGAL codes for MS Excel and LibreOffice Calc, all credit given. Hopefully works in non-AutoCAD programs as well, it worked in AutoCAD 2000i on my home computer, batch wasn't an available option, so I may or may not see why. I forgot how much better Calc looks than Excel, it really looked better with my dark theme, I might need to work on my Excel at work. I just used a quickly made Metric drawing, so hopefully everything is correct, I know getting metric measurements in my Imperial drawings is correct. It now has option for the complete report or just the totals. It also gives the actual measurement of a scaled block and the 1:1 total. It also should first ask to save the CSV in the same folder as the drawing now.
    2 points
  6. (that was an awesome thread....) Yes, that was the start of me making the above, and using BigAl for inspiration
    2 points
  7. Professionally all updates are via email. Recorded in the company systems and auditable.
    1 point
  8. Works great often do old fashioned DOS to get file names list or use the VL files functions. A suggestion remove "result" from the local variables list. As the answer disappears. Or ; Example: ; (setq files (pl:getfiledps "Select Files" (getvar"dwgprefix") "dwg" 1)) A side comment I have used Powershell with Bricscad and sometimes does not work. Your code may help as you do a deeper dive into running Powershell. I generally only do a "Power shell and script" I have used it to change programs, I jump to Excel from CAD.
    1 point
  9. One observation: in older versions of AutoCAD (2000 and 2002, at least), 'vla-get-HWND' applies to the Document object rather than the Acad object.
    1 point
  10. I'm not going to troubleshoot it since Powershell is blocked at work, but if the load has that error, then it's something in the Code, probable in the DCL write-line part.
    1 point
  11. if you're running Civil 3D 2019, then xdrx.x64.25.arx is not the correct version, it would be xdrx.x64.23.arx
    1 point
  12. I forgot to mention, for keeping up with the revisions we have Excel drawing lists with the Drawing names, dates and latest revision number on the network. P&IDs keep a dated track of each and every revision in cast things get put back to an older revision.
    1 point
  13. Well done, nice use of Parallel.For! Kdtree’s are definitely a must have in the CAD programmer’s tool box.
    1 point
  14. could you share your dwg?
    1 point
  15. @Danielm103, I did build gile's code to autocad 2017 and ran it testmore.dwg Results for PLWT_KDTREE: --------- TIMING------------------------------- Collecting entities: 315 milliseconds Building kdTree: 69 milliseconds Pairing lines and texts: 28 milliseconds Coloring lines and texts: 121 milliseconds Total Elapsed Time: 533 milliseconds Total Number of Colors: 102 colors With that kind of results, I don't see what I could improve on here. I am attaching the cs file converted for acad 2017 and Gile.AutoCAD.R20.Geometry ymg pairs.cs
    1 point
  16. this was a fun challenge using KDTrees https://www.theswamp.org/index.php?topic=59487.0
    1 point
  17. @gile, Here I build a bridge to your GeometryExtensions.NET library, exposing essentially the same command that I had in mine . The only addition being GC:KD-MINNODE. I have also built a concavehull in C# using your kd-tree if anybody is interested. ymg using System; using System.IO; using System.Linq; using System.Globalization; using System.Collections.Generic; using Autodesk.AutoCAD.Runtime; using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.Geometry; using Gile.AutoCAD.R20.Geometry; namespace LispGileBridge { public class ExtensionLoader : IExtensionApplication { public void Initialize() { try { var ed = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Editor; // Extracts the absolute running file path dynamically via Reflection string assemblyPath = System.Reflection.Assembly.GetExecutingAssembly().Location; string assemblyName = System.IO.Path.GetFileName(assemblyPath); ed.WriteMessage($"\n--> Assembly File Loaded: \"{assemblyName}\""); ed.WriteMessage($"\n--> Full Path: {assemblyPath}"); ed.WriteMessage("\n--> Available commands:"); ed.WriteMessage("\n (GC:KD-BUILD pointList [dimensions] [customHandle])"); ed.WriteMessage("\n (GC:KD-NEAREST handle Point [count] [maxRadius] [sortFlag])"); ed.WriteMessage("\n (GC:KD-NEAREST-INFO handle Point [count] [maxRadius])"); ed.WriteMessage("\n (GC:KD-RANGE handle Point radius)"); ed.WriteMessage("\n (GC:KD-MINNODE handle dimension)"); ed.WriteMessage("\n (GC:KD-FREE [handle])"); } catch { // Fallback safety silent escape check } } public void Terminate() { } } public class KdTreeBridge { // Thread-safe dictionary tracking string handles to their specific tree instances and properties private static readonly Dictionary<string, (Point3dTree Tree, bool Is2D)> _registry = new Dictionary<string, (Point3dTree, bool)>(StringComparer.OrdinalIgnoreCase); private static int _autoId = 1; // -------------------------------------------------------------------------------- // 1. (gc:kd-build pointList [dimensions] [customHandle]) // -------------------------------------------------------------------------------- [LispFunction("GC:KD-BUILD")] public static object GileKdBuild(ResultBuffer args) { if (args == null) return null; TypedValue[] arr = args.AsArray(); if (arr.Length == 0) return null; try { List<Point3d> pts = ParseLispPoints(arr, 0, out int pointsReadCount); if (pts.Count == 0) return null; // Default dimension to 2D unless explicitly specified as 3 int dimensions = 2; string customHandle = null; if (arr.Length > pointsReadCount) { int nextIdx = pointsReadCount; if (arr[nextIdx].TypeCode == (int)LispDataType.Int32 || arr[nextIdx].TypeCode == (int)LispDataType.Int16) { dimensions = Convert.ToInt32(arr[nextIdx].Value); nextIdx++; } if (arr.Length > nextIdx && arr[nextIdx].TypeCode == (int)LispDataType.Text) { customHandle = Convert.ToString(arr[nextIdx].Value); } } bool is2D = (dimensions == 2); // Gilles' constructor: ignoreZ parameter directly matches our is2D rule Point3dTree tree = new Point3dTree(pts, is2D); string handle = string.IsNullOrEmpty(customHandle) ? $"<KD-TREE-{_autoId++}>" : customHandle; _registry[handle] = (tree, is2D); return handle; } catch (System.Exception ex) { Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage($"\nError in KD-BUILD: {ex.Message}\n"); return null; } } // -------------------------------------------------------------------------------- // 2. (gc:kd-nearest handle targetPoint [count] [maxRadius] [sortFlag]) // -------------------------------------------------------------------------------- [LispFunction("GC:KD-NEAREST")] public static object GileKdNearest(ResultBuffer args) { if (args == null) return null; TypedValue[] arr = args.AsArray(); if (arr.Length < 2) return null; try { string handle = Convert.ToString(arr[0].Value); if (!_registry.TryGetValue(handle, out var entry)) return null; if (arr[1].TypeCode != (int)LispDataType.Point3d) return null; Point3d targetPt = (Point3d)arr[1].Value; int count = 1; double maxRadius = double.MaxValue; int sortFlag = 1; // Default: Sort by Angle if (arr.Length >= 3) count = Convert.ToInt32(arr[2].Value); if (arr.Length >= 4) maxRadius = Convert.ToDouble(arr[3].Value); if (arr.Length >= 5) sortFlag = Convert.ToInt32(arr[4].Value); var searchCollection = entry.Tree.GetNearestNeighbours(targetPt, count); if (searchCollection == null) return null; // Filter by radius limit and compile working list List<Point3d> filtered = new List<Point3d>(); foreach (Point3d pt in searchCollection) { double dist = entry.Is2D ? targetPt.DistanceTo(new Point3d(pt.X, pt.Y, targetPt.Z)) : targetPt.DistanceTo(pt); if (dist <= maxRadius) filtered.Add(pt); } if (filtered.Count == 0) return null; // Execute selected Sort mode if (sortFlag == 0) { filtered = filtered.OrderBy(p => entry.Is2D ? targetPt.DistanceTo(new Point3d(p.X, p.Y, targetPt.Z)) : targetPt.DistanceTo(p)).ToList(); } else { filtered = filtered.OrderBy(p => { double angle = Math.Atan2(p.Y - targetPt.Y, p.X - targetPt.X); return angle < 0 ? angle + (2 * Math.PI) : angle; }).ToList(); } // API Standard Rule Check: If count is 1, return single item. Else, return list. if (count == 1) { return filtered[0]; } ResultBuffer rb = new ResultBuffer(); rb.Add(new TypedValue((int)LispDataType.ListBegin)); foreach (Point3d pt in filtered) rb.Add(new TypedValue((int)LispDataType.Point3d, pt)); rb.Add(new TypedValue((int)LispDataType.ListEnd)); return rb; } catch { return null; } } // -------------------------------------------------------------------------------- // 3. (gc:kd-nearest-info handle targetPoint [count] [maxRadius]) // -------------------------------------------------------------------------------- [LispFunction("GC:KD-NEAREST-INFO")] public static object GileKdNearestInfo(ResultBuffer args) { if (args == null) return null; TypedValue[] arr = args.AsArray(); if (arr.Length < 2) return null; try { string handle = Convert.ToString(arr[0].Value); if (!_registry.TryGetValue(handle, out var entry)) return null; Point3d targetPt = (Point3d)arr[1].Value; int count = 1; double maxRadius = double.MaxValue; if (arr.Length >= 3) count = Convert.ToInt32(arr[2].Value); if (arr.Length >= 4) maxRadius = Convert.ToDouble(arr[3].Value); var searchCollection = entry.Tree.GetNearestNeighbours(targetPt, count); if (searchCollection == null) return null; ResultBuffer rb = new ResultBuffer(); rb.Add(new TypedValue((int)LispDataType.ListBegin)); // Re-locate matches to extract array index mappings cleanly int idx = 0; foreach (Point3d pt in searchCollection) { double dist = entry.Is2D ? targetPt.DistanceTo(new Point3d(pt.X, pt.Y, targetPt.Z)) : targetPt.DistanceTo(pt); if (dist <= maxRadius) { rb.Add(new TypedValue((int)LispDataType.ListBegin)); rb.Add(new TypedValue((int)LispDataType.Point3d, pt)); rb.Add(new TypedValue((int)LispDataType.Int32, idx)); // Metadata index placement rb.Add(new TypedValue((int)LispDataType.Double, dist)); rb.Add(new TypedValue((int)LispDataType.ListEnd)); } idx++; } rb.Add(new TypedValue((int)LispDataType.ListEnd)); return rb; } catch { return null; } } // -------------------------------------------------------------------------------- // 4. (gc:kd-range handle centerPoint radius) // -------------------------------------------------------------------------------- [LispFunction("GC:KD_RANGE")] public static object GileKdRange(ResultBuffer args) { if (args == null) return null; TypedValue[] arr = args.AsArray(); if (arr.Length < 3) return null; try { string handle = Convert.ToString(arr[0].Value); if (!_registry.TryGetValue(handle, out var entry)) return null; Point3d centerPt = (Point3d)arr[1].Value; double radius = Convert.ToDouble(arr[2].Value); // Passing a double directly to GetNearestNeighbours switches Gilles' engine to range search var searchCollection = entry.Tree.GetNearestNeighbours(centerPt, radius); if (searchCollection == null) return null; // Enforce distance sort ordering var sorted = searchCollection.OrderBy(p => entry.Is2D ? centerPt.DistanceTo(new Point3d(p.X, p.Y, centerPt.Z)) : centerPt.DistanceTo(p)).ToList(); ResultBuffer rb = new ResultBuffer(); rb.Add(new TypedValue((int)LispDataType.ListBegin)); foreach (Point3d pt in sorted) rb.Add(new TypedValue((int)LispDataType.Point3d, pt)); rb.Add(new TypedValue((int)LispDataType.ListEnd)); return rb; } catch { return null; } } // -------------------------------------------------------------------------------- // 5. NEW! (gc:kd-minnode handle dimension) -> Useful for Concave Hull base logic // -------------------------------------------------------------------------------- [LispFunction("GC:KD-MINNODE")] public static object GileKdMinNode(ResultBuffer args) { if (args == null) return null; TypedValue[] arr = args.AsArray(); if (arr.Length < 2) return null; try { string handle = Convert.ToString(arr[0].Value); if (!_registry.TryGetValue(handle, out var entry)) return null; int dimension = Convert.ToInt32(arr[1].Value); // 0=X, 1=Y, 2=Z // Target standard range query over all nodes to run aggregate matching var allPoints = entry.Tree.GetNearestNeighbours(Point3d.Origin, double.MaxValue); if (allPoints == null || !allPoints.Any()) return null; Point3d minPoint; switch (dimension) { case 0: // Minimum X coordinate minPoint = allPoints.OrderBy(p => p.X).First(); break; case 1: // Minimum Y coordinate minPoint = allPoints.OrderBy(p => p.Y).First(); break; case 2: // Minimum Z coordinate minPoint = allPoints.OrderBy(p => p.Z).First(); break; default: return null; } return minPoint; } catch { return null; } } // -------------------------------------------------------------------------------- // 6. (gc:kd-free [handle]) // -------------------------------------------------------------------------------- [LispFunction("GC:KD-FREE")] public static object GileKdFree(ResultBuffer args) { int removedCount = 0; if (args == null) { removedCount = _registry.Count; _registry.Clear(); _autoId = 1; } else { TypedValue[] arr = args.AsArray(); if (arr.Length > 0 && arr[0].TypeCode == (int)LispDataType.Text) { string handle = Convert.ToString(arr[0].Value); if (_registry.Remove(handle)) removedCount = 1; } else { removedCount = _registry.Count; _registry.Clear(); _autoId = 1; } } GC.Collect(); GC.WaitForPendingFinalizers(); return removedCount; } // -------------------------------------------------------------------------------- // INTERNAL ROUTINE: Streamlined input coordinate list extractor // -------------------------------------------------------------------------------- private static List<Point3d> ParseLispPoints(TypedValue[] arr, int startIndex, out int readCount) { var collected = new List<Point3d>(); readCount = 0; for (int i = startIndex; i < arr.Length; i++) { if (arr[i].Value is Point3d pt) { collected.Add(pt); readCount++; } else if (arr[i].TypeCode == (int)LispDataType.ListEnd || arr[i].TypeCode == (int)LispDataType.Int32 || arr[i].TypeCode == (int)LispDataType.Text) { break; // Stopped at non-point parameter boundaries } } return collected; } } } essentially the same command that I had in my post.
    1 point
  18. I don't know if there was ever another LISP/Program to do this type of get length at least I never found one, my original just did what I needed, I have since made it more generally useful (I hope). As per the drawing I will attach, I just need to get the length of the center between the inner and outer of the perimeter of guards, etc. to determine the unrolled length. Normally the guards are 3D and I create the profiles with SOLPROF which creates an anonymous block (I used to change these with UNANON) or sometimes in the past I have used SOLVIEW and SOLDRAW, the same issue arises that you just can't select them and get the profile length. So originally that's what this LISP was created to do (I still have some of the older basic versions). I have upgraded it to it's current state and also still working on another version, but only small enhancements. For inside a block that is scaled, you will need to multiply the results by the scale factor, working through a viewport the viewport needs to be active, so I might tackle those issues as well as make a more detailed CSV. I also will try to make sure it works in non-AutoCAD like BricsCAD, CMS IntelliCAD, nanoCAD, etc. when I get time. I lightly tested in most situations, I have no idea how it acts on non-uniformly scaled blocks, though. It handles gaps and slight overlaps, I have some settings at the top, hopefully with enough instructions to modify on your own. Where I work (except for the machine shop which uses decimal inches) they use Architectural units, I did not double check this in Metric, so if someone would report back on that it would help. Guard Test Met.dwg BlkLenTest.dwg GETLEN_2.1.lsp
    1 point
  19. The best thing about QuickSelect is that you can append or remove your selections to/from the previous set. If you need all the manhole blocks on one layer and all the sewer lines on a different layer, for instance, you can pick one of each and use Similar. On the other hand, if you need the pipes in a particular range of lengths, you build one set without the shorter pipes, then remove the pipes that are too long, QED. It may be more complex than other methods, but if there are hundreds or thousands of items to process, it will be quicker.
    1 point
  20. Believe it or not there are still 3 sets of icon menus embedded into the current CUI under: ACAD>Legacy>Image Tile Menus The following are snippets of code to launch each of them for user selection: #1) 3D Objects ; 3D Objects (defun c:3dm ()(menucmd "I=image_3DObjects")(menucmd "I=*")(princ)) After loading 3dm.lsp at the command prompt enter: 3dm #2) Set Spline Fit Variables ; Set Spline Fit Variables (defun c:sfv ()(menucmd "I=image_poly")(menucmd "I=*")(princ)) After loading sfv.lsp at the command prompt enter: sfv #3) Tiled Viewport Layout ; Tiled Viewport Layout (defun c:vpt ()(menucmd "I=image_vporti")(menucmd "I=*")(princ)) After loading vpt.lsp at the command prompt enter: vpt
    1 point
  21. @CivilTechSource the Block/dwg select is part of the POP menu interface, in particular the Icon section. It's just made with Notepad and you save a MNU file., Autocad handles the actual dcl. Re images yes they are slides, SLD files. Ok the how to. 1st step is you must shrink your screen area down to about 1/4 size. When slides were introduced screens were 640x480 so current screens are way more pixels. I use a lisp to make the slides insert say a block, zoom E, Zoom 0.9XP then MSLIDE, Erase last and insert next. Obviously the name of the saved slide is in the lisp. Without going into now you can make like 200 slides very quickly including inserting other block dwg's. You can use a program called Slide library it compresses all your slides into one SLB file a bit easier to manage, I have numerous slb files that contain common items eg landscaping, cars. ***MENUGROUP=CADARC ***POP1 **CADARC2018 [CADARC] LOAD CADARC]^C^C(LOAD "CA3ENTR2013")(LOAD "CA4USRLA-2") [->Set Up] [DRAWING SETUP]^c^C^p(load "ca11set") [--] ............. ............. ............. ............. ***icon **FURN [FURNITURE:] [CTONE(CHAIR-1)]^c^cINSERT ca3ch-1 DRAG \1;;DRAG [CTONE(CHAIR-2)]^c^cINSERT ca3ch-2 DRAG \1;;DRAG [CTONE(SOFA-1)]^c^cINSERT ca3sof1 DRAG \1;;DRAG
    1 point
  22. Block Library pallet - I had that 20 years ago with FastCAD - which inspired me to make something very similar to BigALs - though I think the workings behind are a bit different - might be wrong, BigAl, do you use slide files for the thumbnails? (I remember you giving me a good instruction of them a few years ago now... which I then ignored.... and went with vector images). Can apply any command / LISP to the thumbnails (for example I have a tab 'Get': "Google", "CAD Standards", "Current Folder" which runs just the LISP to open chrome / explorer) - I think BigAl can do the same too. (B&W because I got too lazy to colour them all in)
    1 point
  23. When that is what you need done, NCOPY is a wonderful tool. You don't have to worry about orientation or layers, you don't have to cut and paste from somewhere else, you just select the object(s) you want. I don't use it often, but when I do, it's a real time saver. It's been in AutoCAD since 2013, so there's no excuse not to know about it.
    1 point
  24. @BIGAL this is beautiful, probably this is where AutoDesk got inspiration for the Block Library Pallette. Do you mind sharing the DCL code?
    1 point
  25. I'll try to get to this and finish the Excel today if I can free up some time. I can only test Calc on my home computer, but I'll give it a blind shot at work if I get time, then test and trouble shoot at home. Is the GetLen 2.0.lsp working better in Metric now?
    1 point
  26. @gile, Did not know that. At least I learned something while doing mine. I've look at the extension and there are many interesting things in there.
    1 point
  27. Hi, The GeometryExtensions.NET library provides a generic KdTree<T> class which uses parallel computation for building the tree. It also provides an example of Point3dTree class but can used with any type of object providing a 'getPosition' function. // public KdTree(IEnumerable<T> source, Func<T, Point3d>?getPosition, int dimension) var tree = new KdTree<BlockReference>(blockList, br => br.Position, 2);
    1 point
  28. Does it break an Ellipse that was created with PELLIPSE = 1, which is the old style Polyline, a.k.a. Heavy Polyline and 2D Polyline? 3D Polylines?
    1 point
  29. If you go old fashioned this is built into a pop menu. If you can use Notepad then you can make one. Note the Next and Previous inbuilt options. But I also have 2x2, 3x3, 4x4 and so on dcl's they are used when relevant to limited choices in code via an image pick.
    1 point
  30. You could also add these 2, purgezerolangth and purgezerotxt, they will remove some entities but not generally make a massive change to size. (defun PurgeZeroLengths ( / MySS Fuzz acount DelSS MyEnt EndA EndB) ;; for within blocks (setq MySS (ssget (list (cons 0 "LINE,SPLINE,LWPOLYLINE,POLYLINE,ARC,CIRCLE,ELLIPSE")))) (setq Fuzz 0.0001) ; Fuzz factor to delete very short entities (setq acount 0) (setq DelSS (ssadd)) (while (< acount (sslength MySS)) (setq MyEnt (ssname MySS acount)) (if (equal (vlax-curve-getDistAtParam MyEnt (vlax-curve-getEndParam MyEnt)) 0) (progn (setq DelSS (ssadd MyEnt DelSS)) ) ) ; end if ;;If less then a length (if (< (vlax-curve-getDistAtParam MyEnt (vlax-curve-getEndParam MyEnt)) Fuzz) (progn (setq DelSS (ssadd MyEnt DelSS)) ) ) ; end if (setq acount (+ acount 1)) ) ; end while (princ "\nDeleting ")(princ (sslength DelSS))(princ " lines") (command "erase" DelSS "") (princ) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun c:PurgeZeroTexts ( / MySS acount DelSS MyEnt MyText) (setq MySS (ssget (list (cons 0 "*TEXT")(cons 1 "")))) (setq acount 0) (setq DelSS (ssadd)) (if MySS (progn (while (< acount (sslength MySS)) (setq MyEnt (ssname MySS acount)) (setq MyText (cdr (assoc 1 (entget MyEnt)))) (if (equal MyText "") (progn (setq DelSS (ssadd MyEnt DelSS)) ) ) ; end if (setq acount (+ acount 1)) ) ; end while (princ "\nDeleting ")(princ (sslength DelSS))(princ " lines") (command "erase" DelSS "") ) ; end progn (progn (princ "No zero content texts found") ) ) ; end if (princ) )
    1 point
  31. Not sure if this is considered elegant but sure takes advantage of the number of image tiles that can be spread onto a giant custom dialog to preview slide files. This is a screen capture of SMV (SMVslide) which is one of the commands included in my free Script Magician App:
    1 point
  32. Whilst I probably won't use it, have you looked at compiling for Non Acad, say Bricscad a lot of users here.
    1 point
  33. Hi All I have changed this code to have more options, you can select ByLayer = Layer 0 + ByLayer color ByBlock = Layer 0 + ByBlock color") KeepAllLayers = Keep original layers and colors") you can also select a block or select everything hope someone finds it useful Burst Nested Blocks.lsp
    1 point
  34. Did you try Recover, it checks a dwg, you choose the dwg to check.
    1 point
  35. What is the error message you are seeing?
    1 point
  36. All of you here are elite. I don't have any idea what the topic means. I am a newbie here. I am very willing to learn new things. Hope you accept me here.. Thanks in advance
    1 point
×
×
  • Create New...