DxfUtils.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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
  139. {
  140. return null;
  141. }
  142. }
  143. public static void DrawDxf(DxfData data, IGraphics graphics, float width, float height)
  144. {
  145. // Calculate the scaling factor to fit the image within the bounds
  146. float ratioX = (float)data.Settings.ImageSize.Width / data.Size.Width;
  147. float ratioY = (float)data.Settings.ImageSize.Height / data.Size.Height;
  148. var scale = Math.Min(ratioX, ratioY);
  149. var drawData = new DrawData() { Graphics = graphics, Data = data };
  150. graphics.Clear(Color.White);
  151. // drawData.Translate(graphics.VisibleClipBounds.Width / 2, graphics.VisibleClipBounds.Height / 2);
  152. drawData.Scale(scale, scale);
  153. drawData.Translate(-data.Origin.X, -data.Origin.Y);
  154. // drawData.Translate(-data.Origin.X - data.Size.Width / 2, -data.Origin.Y - data.Size.Height / 2);
  155. foreach(var el in data.Layout.AssociatedBlock.Entities)
  156. {
  157. var item = ConvertEl(el);
  158. item?.Draw(drawData);
  159. }
  160. graphics.Finish();
  161. }
  162. public static DxfData LoadDxf(string filename, DxfImportSettings? settings = null)
  163. {
  164. using var stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
  165. settings ??= new();
  166. var document = DxfDocument.Load(stream, settings.SupportFolders ?? Array.Empty<string>());
  167. document.BuildDimensionBlocks = true;
  168. return new(document, settings);
  169. }
  170. public static DxfData LoadDxf(Stream stream, DxfImportSettings? settings = null)
  171. {
  172. settings ??= new();
  173. var document = DxfDocument.Load(stream, settings.SupportFolders ?? Array.Empty<string>());
  174. return new(document, settings);
  175. }
  176. /// <summary>
  177. /// Returns <see langword="null"/> if the bounds are completely empty.
  178. /// </summary>
  179. /// <param name="data"></param>
  180. /// <returns></returns>
  181. public static RectangleF? CalculateDxfSize(DxfData data)
  182. {
  183. var transformData = new TransformData { Data = data };
  184. RectangleF? bounds = null;
  185. foreach(var el in data.Document.Entities.All)
  186. {
  187. if(ConvertEl(el) is IDxfObject obj)
  188. {
  189. bounds = Utils.CombineBounds(bounds, obj.GetBounds(transformData));
  190. }
  191. }
  192. return bounds;
  193. }
  194. public static Bitmap ProcessImage(DxfData data)
  195. {
  196. var height = data.Size.Height;
  197. var width = data.Size.Width;
  198. // Calculate the scaling factor to fit the image within the bounds
  199. float ratioX = (float)data.Settings.ImageSize.Width / width;
  200. float ratioY = (float)data.Settings.ImageSize.Height / height;
  201. var scale = Math.Min(ratioX, ratioY);
  202. var _result = new Bitmap((int)(width * scale), (int)(height * scale));
  203. using (var _graphics = Graphics.FromImage(_result))
  204. {
  205. _graphics.SmoothingMode = SmoothingMode.AntiAlias;
  206. DrawDxf(data, new GdiGraphics(_graphics), _result.Width, _result.Height);
  207. }
  208. _result.RotateFlip(RotateFlipType.RotateNoneFlipY);
  209. return _result;
  210. }
  211. public static PdfDocument ProcessPdf(DxfData data)
  212. {
  213. var doc = new PdfDocument();
  214. doc.PageSettings.Size = data.Size;
  215. doc.PageSettings.SetMargins(0);
  216. var page = doc.Pages.Add();
  217. var graphics = page.Graphics;
  218. var drawData = new DrawData() { Graphics = new PdfGraphics(page.Graphics), Data = data };
  219. drawData.PushTransform();
  220. drawData.Translate(data.Size.Width / 2, data.Size.Height / 2);
  221. drawData.Scale(1, -1);
  222. drawData.Translate(-data.Size.Width / 2, -data.Size.Height / 2);
  223. drawData.Translate(-data.Origin.X, -data.Origin.Y);
  224. if (data.Layout.IsPaperSpace)
  225. {
  226. var modelSpace = data.Document.Layouts.First(x => x.Name == "Model");
  227. foreach(var el in modelSpace.AssociatedBlock.Entities)
  228. {
  229. var item = ConvertEl(el);
  230. item?.Draw(drawData);
  231. }
  232. }
  233. foreach(var el in data.Layout.AssociatedBlock.Entities)
  234. {
  235. var item = ConvertEl(el);
  236. item?.Draw(drawData);
  237. }
  238. drawData.PopTransform();
  239. drawData.Graphics.Finish();
  240. return doc;
  241. }
  242. // public static PdfDocument ProcessPdf(DxfData data)
  243. // {
  244. // var doc = new PdfDocument();
  245. // var size = data.Size;
  246. // var origin = data.Origin;
  247. // foreach(var layout in data.LayoutNames)
  248. // {
  249. // data.LayoutName = layout;
  250. // Matrix4x4 transform;
  251. // if (data.Layout.IsPaperSpace)
  252. // {
  253. // var viewport = data.Layout.Viewport;
  254. // var scale = (float)(viewport.ViewHeight == 0 ? 0 : viewport.Height / viewport.ViewHeight);
  255. // data.Origin = new((float)(viewport.ViewCenter.X - viewport.Width / 2), (float)(viewport.ViewCenter.Y - viewport.Height / 2));
  256. // data.Size = new((float)viewport.Width, (float)viewport.Height);
  257. // var normal = -System.Numerics.Vector3.Cross(viewport.UcsXAxis.ToVec3(), viewport.UcsYAxis.ToVec3());
  258. // transform = Matrix4x4.CreateLookAt(viewport.UcsOrigin.ToVec3(), viewport.UcsOrigin.ToVec3() + normal, viewport.UcsYAxis.ToVec3())
  259. // * Matrix4x4.CreateScale(scale)
  260. // * Matrix4x4.CreateRotationZ((float)viewport.TwistAngle);
  261. // }
  262. // else
  263. // {
  264. // data.Size = size;
  265. // data.Origin = origin;
  266. // transform = Matrix4x4.Identity;
  267. // }
  268. // var section = doc.Sections.Add();
  269. // section.PageSettings.Size = data.Size;
  270. // section.PageSettings.SetMargins(0);
  271. // var page = section.Pages.Add();
  272. // var graphics = page.Graphics;
  273. // var drawData = new DrawData() { Graphics = new PdfGraphics(page.Graphics), Data = data };
  274. // drawData.PushTransform();
  275. // drawData.Translate(data.Size.Width / 2, data.Size.Height / 2);
  276. // drawData.Scale(1, -1);
  277. // drawData.Translate(-data.Size.Width / 2, -data.Size.Height / 2);
  278. // drawData.Translate(-data.Origin.X, -data.Origin.Y);
  279. // drawData.TransformBy(transform);
  280. // if (data.Layout.IsPaperSpace)
  281. // {
  282. // var modelSpace = data.Document.Layouts.First(x => x.Name == "Model");
  283. // foreach(var el in modelSpace.AssociatedBlock.Entities)
  284. // {
  285. // var item = ConvertEl(el);
  286. // item?.Draw(drawData);
  287. // }
  288. // }
  289. // foreach(var el in data.Layout.AssociatedBlock.Entities)
  290. // {
  291. // var item = ConvertEl(el);
  292. // item?.Draw(drawData);
  293. // }
  294. // drawData.PopTransform();
  295. // drawData.Graphics.Finish();
  296. // }
  297. // return doc;
  298. // }
  299. public static SvgDocument ProcessSvg(DxfData data)
  300. {
  301. var doc = new SvgDocument
  302. {
  303. ViewBox = new(data.Origin.X, data.Origin.Y, data.Size.Width, data.Size.Height)
  304. };
  305. var drawData = new DrawData() { Graphics = new SvgGraphics(doc), Data = data };
  306. foreach(var el in data.Layout.AssociatedBlock.Entities)
  307. {
  308. var item = ConvertEl(el);
  309. item?.Draw(drawData);
  310. }
  311. drawData.Graphics.Finish();
  312. return doc;
  313. }
  314. public static Bitmap ProcessImage(Stream stream, DxfImportSettings? settings = null)
  315. {
  316. return ProcessImage(LoadDxf(stream, settings));
  317. }
  318. public static Result<Bitmap, Exception> DXFToBitmap(string filename, DxfImportSettings? settings = null)
  319. {
  320. using var stream = new FileStream(filename, FileMode.Open, FileAccess.Read);
  321. try
  322. {
  323. return Result.Ok(ProcessImage(stream, settings: settings));
  324. }
  325. catch (Exception e)
  326. {
  327. OnProcessError?.Invoke(e.Message);
  328. return Result.Error(e);
  329. }
  330. }
  331. }