DxfUtils.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. using System.Drawing;
  2. using System.Drawing.Drawing2D;
  3. using InABox.Core;
  4. using netDxf;
  5. using netDxf.Entities;
  6. using netDxf.Objects;
  7. using netDxf.Tables;
  8. using Svg;
  9. using Syncfusion.Pdf;
  10. namespace InABox.Dxf;
  11. public class DxfImportSettings
  12. {
  13. public Size ImageSize;
  14. public string[]? SupportFolders;
  15. public string? LayoutName { get; set; }
  16. public bool AutoFit { get; set; }
  17. public DxfImportSettings(Size? imageSize = null, string[]? supportFolders = null, string? layoutName = null, bool autoFit = true)
  18. {
  19. AutoFit = autoFit;
  20. ImageSize = imageSize ?? new(2048, 2048);
  21. SupportFolders = supportFolders;
  22. LayoutName = layoutName ?? "Model";
  23. }
  24. }
  25. public class DxfData
  26. {
  27. public DxfDocument Document { get; set; }
  28. public DxfImportSettings Settings { get; set; }
  29. public SizeF Size { get; set; }
  30. public PointF Origin { get; set; }
  31. public Layout Layout { get; set; }
  32. public IEnumerable<string> LayoutNames => Document.Layouts.Select(x => x.Name);
  33. public HashSet<string>? Layers { get; set; }
  34. public bool HasLayer(Layer layer)
  35. {
  36. return Layers is null || Layers.Contains(layer.Name);
  37. }
  38. public void SetLayers(params string[] layers)
  39. {
  40. Layers = layers.ToHashSet();
  41. }
  42. public void SetLayers(IEnumerable<string> layers)
  43. {
  44. Layers = layers.ToHashSet();
  45. }
  46. public bool ShouldDraw(EntityObject obj)
  47. {
  48. return obj.IsVisible && HasLayer(obj.Layer);
  49. }
  50. public string LayoutName
  51. {
  52. get => Layout.Name;
  53. set
  54. {
  55. Layout = Document.Layouts.First(x => x.Name == value);
  56. UpdateSizeAndOrigin();
  57. }
  58. }
  59. public DxfData(DxfDocument document, DxfImportSettings settings)
  60. {
  61. Document = document;
  62. Settings = settings;
  63. Layout = settings.LayoutName is not null ? document.Layouts.First(x => x.Name == settings.LayoutName) : document.Layouts.First();
  64. UpdateSizeAndOrigin();
  65. }
  66. private void UpdateSizeAndOrigin()
  67. {
  68. if (Settings.AutoFit)
  69. {
  70. var bounds = DxfUtils.CalculateDxfSize(this) ?? new();
  71. var margin = 0.1f * Math.Min(bounds.Width, bounds.Height);
  72. if (bounds.IsEmpty)
  73. {
  74. bounds.Size = new(100, 100);
  75. bounds.Location = new(0, 0);
  76. }
  77. else
  78. {
  79. bounds.Size = new(bounds.Width + margin * 2, bounds.Height + margin * 2);
  80. bounds.Location = new(bounds.X - margin, bounds.Y - margin);
  81. }
  82. Size = bounds.Size;
  83. Origin = bounds.Location;
  84. }
  85. else
  86. {
  87. Size = new((float)(Layout.MaxLimit.X - Layout.MinLimit.X), (float)(Layout.MaxLimit.Y - Layout.MinLimit.Y));
  88. Origin = new((float)Layout.MinLimit.X, (float)Layout.MinLimit.Y);
  89. }
  90. }
  91. }
  92. public static class DxfUtils
  93. {
  94. public static event ProcessError OnProcessError;
  95. public delegate void ProcessError(string message);
  96. internal static IDxfObject? ConvertEl(EntityObject el)
  97. {
  98. if(el is Line line)
  99. {
  100. return new DxfLine { Line = line };
  101. }
  102. else if(el is Insert insert)
  103. {
  104. return new DxfInsert(insert);
  105. }
  106. else if(el is Ellipse ellipse)
  107. {
  108. return new DxfEllipse(ellipse);
  109. }
  110. else if(el is MText text)
  111. {
  112. return new DxfMText(text);
  113. }
  114. else if(el is Polyline2D ln2D)
  115. {
  116. return new DxfPolyline2D(ln2D);
  117. }
  118. else if(el is Dimension dim)
  119. {
  120. return new DxfDimension(dim);
  121. }
  122. else if(el is Solid solid)
  123. {
  124. return new DxfSolid(solid);
  125. }
  126. else if (el is netDxf.Entities.Point point)
  127. {
  128. return null;
  129. }
  130. else if (el is netDxf.Entities.Viewport viewport)
  131. {
  132. return null;
  133. }
  134. else if (el is Arc a)
  135. {
  136. return new DxfArc(a);
  137. }
  138. else if(el is Text t)
  139. {
  140. return new DxfText(t);
  141. }
  142. else
  143. {
  144. return null;
  145. }
  146. }
  147. public static void DrawDxf(DxfData data, IGraphics graphics, float width, float height)
  148. {
  149. // Calculate the scaling factor to fit the image within the bounds
  150. float ratioX = (float)data.Settings.ImageSize.Width / data.Size.Width;
  151. float ratioY = (float)data.Settings.ImageSize.Height / data.Size.Height;
  152. var scale = Math.Min(ratioX, ratioY);
  153. var drawData = new DrawData() { Graphics = graphics, Data = data };
  154. graphics.Clear(Color.White);
  155. // drawData.Translate(graphics.VisibleClipBounds.Width / 2, graphics.VisibleClipBounds.Height / 2);
  156. drawData.Scale(scale, scale);
  157. drawData.Translate(-data.Origin.X, -data.Origin.Y);
  158. // drawData.Translate(-data.Origin.X - data.Size.Width / 2, -data.Origin.Y - data.Size.Height / 2);
  159. foreach(var el in data.Layout.AssociatedBlock.Entities)
  160. {
  161. var item = ConvertEl(el);
  162. item?.Draw(drawData);
  163. }
  164. graphics.Finish();
  165. }
  166. public static DxfData LoadDxf(string filename, DxfImportSettings? settings = null)
  167. {
  168. using var stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
  169. settings ??= new();
  170. var document = DxfDocument.Load(stream, settings.SupportFolders ?? Array.Empty<string>());
  171. document.BuildDimensionBlocks = true;
  172. return new(document, settings);
  173. }
  174. public static DxfData LoadDxf(Stream stream, DxfImportSettings? settings = null)
  175. {
  176. settings ??= new();
  177. var document = DxfDocument.Load(stream, settings.SupportFolders ?? Array.Empty<string>());
  178. return new(document, settings);
  179. }
  180. /// <summary>
  181. /// Returns <see langword="null"/> if the bounds are completely empty.
  182. /// </summary>
  183. /// <param name="data"></param>
  184. /// <returns></returns>
  185. public static RectangleF? CalculateDxfSize(DxfData data)
  186. {
  187. var transformData = new TransformData { Data = data };
  188. RectangleF? bounds = null;
  189. foreach(var el in data.Document.Entities.All)
  190. {
  191. if(ConvertEl(el) is IDxfObject obj)
  192. {
  193. bounds = Utils.CombineBounds(bounds, obj.GetBounds(transformData));
  194. }
  195. }
  196. return bounds;
  197. }
  198. public static Bitmap ProcessImage(DxfData data)
  199. {
  200. var height = data.Size.Height;
  201. var width = data.Size.Width;
  202. // Calculate the scaling factor to fit the image within the bounds
  203. float ratioX = (float)data.Settings.ImageSize.Width / width;
  204. float ratioY = (float)data.Settings.ImageSize.Height / height;
  205. var scale = Math.Min(ratioX, ratioY);
  206. var _result = new Bitmap((int)(width * scale), (int)(height * scale));
  207. using (var _graphics = Graphics.FromImage(_result))
  208. {
  209. _graphics.SmoothingMode = SmoothingMode.AntiAlias;
  210. DrawDxf(data, new GdiGraphics(_graphics), _result.Width, _result.Height);
  211. }
  212. _result.RotateFlip(RotateFlipType.RotateNoneFlipY);
  213. return _result;
  214. }
  215. public static PdfDocument ProcessPdf(DxfData data)
  216. {
  217. var doc = new PdfDocument();
  218. doc.PageSettings.Size = data.Size;
  219. doc.PageSettings.SetMargins(0);
  220. var page = doc.Pages.Add();
  221. var graphics = page.Graphics;
  222. var drawData = new DrawData() { Graphics = new PdfGraphics(page.Graphics), Data = data };
  223. drawData.PushTransform();
  224. drawData.Translate(data.Size.Width / 2, data.Size.Height / 2);
  225. drawData.Scale(1, -1);
  226. drawData.Translate(-data.Size.Width / 2, -data.Size.Height / 2);
  227. drawData.Translate(-data.Origin.X, -data.Origin.Y);
  228. if (data.Layout.IsPaperSpace)
  229. {
  230. var modelSpace = data.Document.Layouts.First(x => x.Name == "Model");
  231. foreach(var el in modelSpace.AssociatedBlock.Entities)
  232. {
  233. var item = ConvertEl(el);
  234. item?.Draw(drawData);
  235. }
  236. }
  237. foreach(var el in data.Layout.AssociatedBlock.Entities)
  238. {
  239. var item = ConvertEl(el);
  240. item?.Draw(drawData);
  241. }
  242. drawData.PopTransform();
  243. drawData.Graphics.Finish();
  244. return doc;
  245. }
  246. // public static PdfDocument ProcessPdf(DxfData data)
  247. // {
  248. // var doc = new PdfDocument();
  249. // var size = data.Size;
  250. // var origin = data.Origin;
  251. // foreach(var layout in data.LayoutNames)
  252. // {
  253. // data.LayoutName = layout;
  254. // Matrix4x4 transform;
  255. // if (data.Layout.IsPaperSpace)
  256. // {
  257. // var viewport = data.Layout.Viewport;
  258. // var scale = (float)(viewport.ViewHeight == 0 ? 0 : viewport.Height / viewport.ViewHeight);
  259. // data.Origin = new((float)(viewport.ViewCenter.X - viewport.Width / 2), (float)(viewport.ViewCenter.Y - viewport.Height / 2));
  260. // data.Size = new((float)viewport.Width, (float)viewport.Height);
  261. // var normal = -System.Numerics.Vector3.Cross(viewport.UcsXAxis.ToVec3(), viewport.UcsYAxis.ToVec3());
  262. // transform = Matrix4x4.CreateLookAt(viewport.UcsOrigin.ToVec3(), viewport.UcsOrigin.ToVec3() + normal, viewport.UcsYAxis.ToVec3())
  263. // * Matrix4x4.CreateScale(scale)
  264. // * Matrix4x4.CreateRotationZ((float)viewport.TwistAngle);
  265. // }
  266. // else
  267. // {
  268. // data.Size = size;
  269. // data.Origin = origin;
  270. // transform = Matrix4x4.Identity;
  271. // }
  272. // var section = doc.Sections.Add();
  273. // section.PageSettings.Size = data.Size;
  274. // section.PageSettings.SetMargins(0);
  275. // var page = section.Pages.Add();
  276. // var graphics = page.Graphics;
  277. // var drawData = new DrawData() { Graphics = new PdfGraphics(page.Graphics), Data = data };
  278. // drawData.PushTransform();
  279. // drawData.Translate(data.Size.Width / 2, data.Size.Height / 2);
  280. // drawData.Scale(1, -1);
  281. // drawData.Translate(-data.Size.Width / 2, -data.Size.Height / 2);
  282. // drawData.Translate(-data.Origin.X, -data.Origin.Y);
  283. // drawData.TransformBy(transform);
  284. // if (data.Layout.IsPaperSpace)
  285. // {
  286. // var modelSpace = data.Document.Layouts.First(x => x.Name == "Model");
  287. // foreach(var el in modelSpace.AssociatedBlock.Entities)
  288. // {
  289. // var item = ConvertEl(el);
  290. // item?.Draw(drawData);
  291. // }
  292. // }
  293. // foreach(var el in data.Layout.AssociatedBlock.Entities)
  294. // {
  295. // var item = ConvertEl(el);
  296. // item?.Draw(drawData);
  297. // }
  298. // drawData.PopTransform();
  299. // drawData.Graphics.Finish();
  300. // }
  301. // return doc;
  302. // }
  303. public static SvgDocument ProcessSvg(DxfData data)
  304. {
  305. var doc = new SvgDocument
  306. {
  307. ViewBox = new(data.Origin.X, data.Origin.Y, data.Size.Width, data.Size.Height)
  308. };
  309. var drawData = new DrawData() { Graphics = new SvgGraphics(doc), Data = data };
  310. foreach(var el in data.Layout.AssociatedBlock.Entities)
  311. {
  312. var item = ConvertEl(el);
  313. item?.Draw(drawData);
  314. }
  315. drawData.Graphics.Finish();
  316. return doc;
  317. }
  318. public static Bitmap ProcessImage(Stream stream, DxfImportSettings? settings = null)
  319. {
  320. return ProcessImage(LoadDxf(stream, settings));
  321. }
  322. public static Result<Bitmap, Exception> DXFToBitmap(string filename, DxfImportSettings? settings = null)
  323. {
  324. using var stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
  325. try
  326. {
  327. return Result.Ok(ProcessImage(stream, settings: settings));
  328. }
  329. catch (Exception e)
  330. {
  331. OnProcessError?.Invoke(e.Message);
  332. return Result.Error(e);
  333. }
  334. }
  335. }