雪山飞狐_lzh 发表于 2014-7-15 13:05:49

Teigha的简单应用 DwgView

本帖最后由 雪山飞狐_lzh 于 2014-7-17 18:09 编辑

19982月,独立的、非营利的"OpenDWG Alliance" 组织成立,目标是让dwg文件成为一个开放的、大家都可以用的图形存储标准。这个联盟是由Visio牵头的多家公司组成的。"OpenDWG Alliance"致力于开发读写dwg文件的程序,开始开发供成员使用的OpenDWG Toolkit和 Viewkit(在以前 MarComp 发AUTODIRECT 库基础上)



Teigha即DWGdirect(OpenDWG )
关于Teigha的由来可以看看这个http://www.25kx.com/art/706332
Teigha的最新版是4.0
但是我只在CSDN上找到了较老的3.03版,但基本能用。。。
下面是个简单的测试例子

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Drawing;

using TDb = Teigha.DatabaseServices;
using TRx = Teigha.Runtime;
using TGe = Teigha.Geometry;
using TGi = Teigha.GraphicsInterface;
using TGs = Teigha.GraphicsSystem;


namespace TlsCad.Trans
{
    public class DwgView : IDisposable
    {
      private Panel _panel = null;

      private TDb.Database _db;
      private TGs.LayoutHelperDevice _dev = null;
      private Graphics _graphics = null;

      public Panel Panel
      {
            set
            {
                _panel = value;
                InitializeGraphics();
            }
            get
            {
                return _panel;
            }
      }

      public TDb.Database Database
      {
            get { return _db; }
      }

      private void ReSize()
      {
            if (_dev != null)
            {
                Rectangle rec = _panel.Bounds;
                rec.Offset(-_panel.Location.X, -_panel.Location.Y);
                // HDC assigned to the device corresponds to the whole client area of the panel
                _dev.OnSize(rec);
            }
      }

      protected void OnPaint(object sender, PaintEventArgs e)
      {
            if (_dev != null)
            {
                _dev.Update();
            }
      }

      protected void OnReSize(object sender, EventArgs e)
      {
            ReSize();
      }

      public DwgView(Panel panel)
      {
            _db = new TDb.Database(true, false);
            _panel = panel;
            InitializeGraphics();
      }

      public DwgView(Panel panel, string dwgFileName)
      {
            _db = new TDb.Database(false, false);
            _db.ReadDwgFile(dwgFileName, TDb.FileOpenMode.OpenForReadAndAllShare, true, "");
            _panel = panel;
            InitializeGraphics();
      }

      private void InitializeGraphics()
      {
            _graphics = Graphics.FromHwnd(_panel.Handle);
            _panel.Resize += OnReSize;
            _panel.Paint += OnPaint;
            //rendering module (may be also "WinDirectX" or "WinOpenGL")
            using (var module = (TGs.GsModule)TRx.SystemObjects.DynamicLinker.LoadModule("WinOpenGL.txv", false, true))
            {

                if (module != null)
                {
                  // create graphics device
                  using (var device = module.CreateDevice())
                  {

                        if (device != null)
                        {
                            //setup device properties
                            using (TRx.Dictionary props = device.Properties)
                            {
                              if (props.Contains("WindowHWND")) // Check if property is supported
                                    props.AtPut("WindowHWND", new TRx.RxVariant(_panel.Handle)); // hWnd necessary for DirectX device
                              if (props.Contains("WindowHDC")) // Check if property is supported
                                    props.AtPut("WindowHDC", new TRx.RxVariant(_graphics.GetHdc())); // hWindowDC necessary for Bitmap device
                              if (props.Contains("DoubleBufferEnabled")) // Check if property is supported
                                    props.AtPut("DoubleBufferEnabled", new TRx.RxVariant(true));
                              if (props.Contains("EnableSoftwareHLR")) // Check if property is supported
                                    props.AtPut("EnableSoftwareHLR", new TRx.RxVariant(true));
                              if (props.Contains("DiscardBackFaces")) // Check if property is supported
                                    props.AtPut("DiscardBackFaces", new TRx.RxVariant(true));

                            }

                            var ctx = new TGi.ContextForDbDatabase(_db);
                            ctx.UseGsModel = true;
                            _dev = TGs.LayoutHelperDevice.SetupActiveLayoutViews(device, ctx);
                            _dev.UserGiContext = ctx;
                            _dev.SetLogicalPalette(TGs.Device.DarkPalette);
                            Rectangle rec = _panel.Bounds;
                            rec.Offset(-_panel.Location.X, -_panel.Location.Y);
                            // HDC assigned to the device corresponds to the whole client area of the panel
                            _dev.OnSize(rec);
                        }
                  }
                }
            }
      }

      public void AddEntity(params TDb.Entity[] ents)
      {
            using (var tr = _db.TransactionManager.StartTransaction())
            {
                var btr = (TDb.BlockTableRecord)tr.GetObject(_db.CurrentSpaceId, TDb.OpenMode.ForWrite);
                foreach (var ent in ents)
                {
                  btr.AppendEntity(ent);
                  tr.AddNewlyCreatedDBObject(ent, false);
                }
                tr.Commit();
            }
      }

      public void AddEntity(IEnumerable<TDb.Entity> ents)
      {
            using (var tr = _db.TransactionManager.StartTransaction())
            {
                var btr = (TDb.BlockTableRecord)tr.GetObject(_db.CurrentSpaceId, TDb.OpenMode.ForWrite);
                foreach (var ent in ents)
                {
                  btr.AppendEntity(ent);
                  tr.AddNewlyCreatedDBObject(ent, false);
                }
                tr.Commit();
            }
      }

      public void Zoom(TGe.BoundBlock3d box)
      {

            using (var vtr = (TDb.ViewportTableRecord)_db.CurrentViewportTableRecordId.GetObject(TDb.OpenMode.ForWrite))
            {
                // using protocol extensions we handle PS and MS viewports in the same manner
                using (var vpd = new TDb.AbstractViewportData(vtr))
                {
                  var view = vpd.GsView;
                  // do actual zooming - change GS view
                  // here protocol extension is used again, that provides some helpful functions
                  using (var vpe = new TDb.AbstractViewPE(view))
                  {
                        box.TransformBy(view.ViewingMatrix);
                        vpe.ZoomExtents(box);
                  }
                  vpd.SetView(view);
                }
            }
            ReSize();
      }


      public void Zoom(TDb.Extents3d ext)
      {
            TGe.BoundBlock3d box = new TGe.BoundBlock3d();
            box.Set(ext.MinPoint, ext.MaxPoint);
            Zoom(box);
      }

      public void ZoomWindow(TGe.Point3d minPoint, TGe.Point3d maxPoint)
      {
            TGe.BoundBlock3d box = new TGe.BoundBlock3d();
            box.Set(minPoint, maxPoint);
            Zoom(box);
      }

      private bool GetLayoutExtents(TDb.Database db, TGs.View view, ref TGe.BoundBlock3d box)
      {
            var bt = (TDb.BlockTable)db.BlockTableId.GetObject(TDb.OpenMode.ForRead);
            var space = (TDb.BlockTableRecord)bt.GetObject(TDb.OpenMode.ForRead);
            var layout = (TDb.Layout)space.LayoutId.GetObject(TDb.OpenMode.ForRead);
            var ext = new TDb.Extents3d();
            if (layout.GetViewports().Count > 0)
            {
                bool bOverall = true;
                foreach (TDb.ObjectId id in layout.GetViewports())
                {
                  if (bOverall)
                  {
                        bOverall = false;
                        continue;
                  }
                  var pVp = (TDb.Viewport)id.GetObject(TDb.OpenMode.ForRead);
                }
                ext.TransformBy(view.ViewingMatrix);
                box.Set(ext.MinPoint, ext.MaxPoint);
            }
            else
            {
                ext = layout.Extents;
            }
            box.Set(ext.MinPoint, ext.MaxPoint);
            return ext.MinPoint != ext.MaxPoint;
      }

      public void ZoomExtents()
      {

            using (var vtr = _db.CurrentViewportTableRecordId.GetObject(TDb.OpenMode.ForWrite))
            {
                // using protocol extensions we handle PS and MS viewports in the same manner
                using (var vpd = new TDb.AbstractViewportData(vtr))
                {
                  var view = vpd.GsView;
                  // do actual zooming - change GS view
                  // here protocol extension is used again, that provides some helpful functions
                  using (var vpe = new TDb.AbstractViewPE(view))
                  {
                        TGe.BoundBlock3d box = new TGe.BoundBlock3d();
                        bool bValid = vpe.GetViewExtents(box);

                        if (vtr is TDb.Viewport && ((TDb.Viewport)vtr).Number == 1)
                        {
                            if (!bValid || !(box.GetMinimumPoint().X < box.GetMaximumPoint().X && box.GetMinimumPoint().Y < box.GetMaximumPoint().Y))
                            {
                              bValid = GetLayoutExtents(_db, view, ref box);
                            }
                        }
                        else if (!bValid) // model space viewport
                        {
                            bValid = GetLayoutExtents(_db, view, ref box);
                        }

                        if (!bValid)
                        {
                            // set to somewhat reasonable (e.g. paper size)
                            if (_db.Measurement == TDb.MeasurementValue.Metric)
                            {
                              box.Set(TGe.Point3d.Origin, new TGe.Point3d(297.0, 210.0, 0.0)); // set to papersize ISO A4 (portrait)
                            }
                            else
                            {
                              box.Set(TGe.Point3d.Origin, new TGe.Point3d(11.0, 8.5, 0.0)); // ANSI A (8.50 x 11.00) (landscape)
                            }
                            box.TransformBy(view.ViewingMatrix);
                        }
                        vpe.ZoomExtents(box);
                  }
                  vpd.SetView(view);
                }
            }
            ReSize();
      }

      public void Dispose()
      {

            if (_db != null)
            {
                _db.Dispose();
                _db = null;
            }

            if (_dev != null)
            {
                _dev.Dispose();
                _dev = null;
            }

      }
    }
}



/////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2003-2014, Open Design Alliance (the "Alliance").
// All rights reserved.
//
// This software and its documentation and related materials are owned by
// the Alliance. The software may only be incorporated into application
// programs owned by members of the Alliance, subject to a signed
// Membership Agreement and Supplemental Software License Agreement with the
// Alliance. The structure and organization of this software are the valuable
// trade secrets of the Alliance and its suppliers. The software is also
// protected by copyright law and international treaty provisions. Application
// programs incorporating this software must include the following statement
// with their copyright notices:
//   
//   This application incorporates Teigha(R) software pursuant to a license
//   agreement with Open Design Alliance.
//   Teigha(R) Copyright (C) 2003-2014 by Open Design Alliance.
//   All rights reserved.
//
// By use of this software, its documentation or related materials, you
// acknowledge and accept the above terms.
///////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;

using Teigha;
using Teigha.DatabaseServices;

using Microsoft.Win32;

namespace TlsCad.ApplicationServices
{
    class HostAppServ : HostApplicationServices
    {
      public HostAppServ()
      {
      }

      public String FindConfigPath(String configType)
      {
            String subkey = GetRegistryAcadProfilesKey();
            if (subkey.Length > 0)
            {
                subkey += String.Format("\\General");
                String searchPath;
                if (GetRegistryString(Registry.CurrentUser, subkey, configType, out searchPath))
                  return searchPath;
            }
            return String.Format("");
      }

      private String FindConfigFile(String configType, String file)
      {
            String searchPath = FindConfigPath(configType);
            if (searchPath.Length > 0)
            {
                searchPath = String.Format("{0}\\{1}", searchPath, file);
                if (System.IO.File.Exists(searchPath))
                  return searchPath;
            }
            return String.Format("");
      }

      public override String FindFile(String file, Database db, FindFileHint hint)
      {
            String sFile = this.FindFileEx(file, db, hint);
            if (sFile.Length > 0)
                return sFile;

            String strFileName = file;
            String ext;
            if (strFileName.Length > 3)
                ext = strFileName.Substring(strFileName.Length - 4, 4).ToUpper();
            else
                ext = file.ToUpper();
            if (ext == String.Format(".PC3"))
                return FindConfigFile(String.Format("PrinterConfigDir"), file);
            if (ext == String.Format(".STB") || ext == String.Format(".CTB"))
                return FindConfigFile(String.Format("PrinterStyleSheetDir"), file);
            if (ext == String.Format(".PMP"))
                return FindConfigFile(String.Format("PrinterDescDir"), file);

            switch (hint)
            {
                case FindFileHint.FontFile:
                case FindFileHint.CompiledShapeFile:
                case FindFileHint.TrueTypeFontFile:
                case FindFileHint.PatternFile:
                case FindFileHint.FontMapFile:
                case FindFileHint.TextureMapFile:
                  break;
                default:
                  return sFile;
            }

            if (hint != FindFileHint.TextureMapFile && ext != String.Format(".SHX") && ext != String.Format(".PAT") && ext != String.Format(".TTF") && ext != String.Format(".TTC"))
            {
                strFileName += String.Format(".shx");
            }
            else if (hint == FindFileHint.TextureMapFile)
            {
                strFileName.Replace(String.Format("/"), String.Format("\\"));
                int last = strFileName.LastIndexOf("\\");
                if (last == -1)
                  strFileName = "";
                else
                  strFileName = strFileName.Substring(0, last);
            }


            sFile = (hint != FindFileHint.TextureMapFile) ? GetRegistryACADFromProfile() : GetRegistryAVEMAPSFromProfile();
            while (sFile.Length > 0)
            {
                int nFindStr = sFile.IndexOf(";");
                String sPath;
                if (-1 == nFindStr)
                {
                  sPath = sFile;
                  sFile = String.Format("");
                }
                else
                {
                  sPath = String.Format("{0}\\{1}", sFile.Substring(0, nFindStr), strFileName);
                  if (System.IO.File.Exists(sPath))
                  {
                        return sPath;
                  }
                  sFile = sFile.Substring(nFindStr + 1, sFile.Length - nFindStr - 1);
                }
            }

            if (hint == FindFileHint.TextureMapFile)
            {
                return sFile;
            }

            if (sFile.Length <= 0)
            {
                String sAcadLocation = GetRegistryAcadLocation();
                if (sAcadLocation.Length > 0)
                {
                  sFile = String.Format("{0}\\Fonts\\{1}", sAcadLocation, strFileName);
                  if (System.IO.File.Exists(sFile))
                  {
                        sFile = String.Format("{0}\\Support\\{1}", sAcadLocation, strFileName);
                        if (System.IO.File.Exists(sFile))
                        {
                            sFile = String.Format("");
                        }
                  }
                }
            }
            return sFile;
      }

      public override bool GetPassword(String fileName, PasswordOptions options, out String pass)
      {
            //PasswordDlg pwdDlg = new PasswordDlg();
            /*pwdDlg.TextFileName.Text = fileName;
            if (pwdDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
            pass = pwdDlg.password.Text;
            return true;
            }*/
            pass = String.Format("");
            return false;
      }

      public override String FontMapFileName
      {
            get
            {
                String subkey = GetRegistryAcadProfilesKey();
                if (subkey.Length > 0)
                {
                  subkey += String.Format("\\Editor Configuration");
                  String fontMapFile;
                  if (GetRegistryString(Registry.CurrentUser, subkey, String.Format("FontMappingFile"), out fontMapFile))
                        return fontMapFile;
                }
                return String.Format("");
            }
      }

      bool GetRegistryString(RegistryKey rKey, String subkey, String name, out String value)
      {
            bool rv = false;
            object objData = null;

            RegistryKey regKey;
            regKey = rKey.OpenSubKey(subkey);
            if (regKey != null)
            {
                objData = regKey.GetValue(name);
                if (objData != null)
                {
                  rv = true;
                }
                regKey.Close();
            }
            if (rv)
                value = objData.ToString();
            else
                value = String.Format("");

            rKey.Close();
            return rv;
      }

      String GetRegistryAVEMAPSFromProfile()
      {
            String subkey = GetRegistryAcadProfilesKey();
            if (subkey.Length > 0)
            {
                subkey += String.Format("\\General");
                // get the value for the ACAD entry in the registry
                String tmp;
                if (GetRegistryString(Registry.CurrentUser, subkey, String.Format("AVEMAPS"), out tmp))
                  return tmp;
            }
            return String.Format("");
      }

      String GetRegistryAcadProfilesKey()
      {
            String subkey = String.Format("SOFTWARE\\Autodesk\\AutoCAD");
            String tmp;

            if (!GetRegistryString(Registry.CurrentUser, subkey, String.Format("CurVer"), out tmp))
                return String.Format("");
            subkey += String.Format("\\{0}", tmp);

            if (!GetRegistryString(Registry.CurrentUser, subkey, String.Format("CurVer"), out tmp))
                return String.Format("");
            subkey += String.Format("\\{0}\\Profiles", tmp);

            if (!GetRegistryString(Registry.CurrentUser, subkey, String.Format(""), out tmp))
                return String.Format("");
            subkey += String.Format("\\{0}", tmp);
            return subkey;
      }

      String GetRegistryAcadLocation()
      {
            String subkey = String.Format("SOFTWARE\\Autodesk\\AutoCAD");
            String tmp;

            if (!GetRegistryString(Registry.CurrentUser, subkey, String.Format("CurVer"), out tmp))
                return String.Format("");
            subkey += String.Format("\\{0}", tmp);

            if (!GetRegistryString(Registry.CurrentUser, subkey, String.Format("CurVer"), out tmp))
                return String.Format("");
            subkey += String.Format("\\{0}", tmp);

            if (!GetRegistryString(Registry.CurrentUser, subkey, String.Format(""), out tmp))
                return String.Format("");
            return tmp;
      }

      String GetRegistryACADFromProfile()
      {
            String subkey = GetRegistryAcadProfilesKey();
            if (subkey.Length > 0)
            {
                subkey += String.Format("\\General");
                // get the value for the ACAD entry in the registry
                String tmp;
                if (GetRegistryString(Registry.CurrentUser, subkey, String.Format("ACAD"), out tmp))
                  return tmp;
            }
            return String.Format("");
      }
    };
}






寒风 发表于 2019-8-20 11:21:11

有没有最新的.net版本呢?

雪山飞狐_lzh 发表于 2014-7-15 13:06:32

本帖最后由 雪山飞狐_lzh 于 2014-7-15 13:25 编辑

测试的Form.cs
注意自己加panel控件和Resize 、FormClosed 事件

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using TDb = Teigha.DatabaseServices;
using TRx = Teigha.Runtime;
using TGe = Teigha.Geometry;
using TGi = Teigha.GraphicsInterface;
using TGs = Teigha.GraphicsSystem;

using TlsCad.ApplicationServices;

namespace GhaTest
{
    public partial class Form1 : Form
    {
      TRx.Services _srv;
      TlsCad.Trans.DwgView _dview;

      public Form1()
      {
            _srv = new TRx.Services();
            TDb.HostApplicationServices.Current = new HostAppServ();
            InitializeComponent();

            _dview = new TlsCad.Trans.DwgView(panel1);
            //_dview.AddEntity(
            //    new TDb.Line(new TGe.Point3d(-20, 0, 0), new TGe.Point3d(20, 0, 0)),
            //    new TDb.Line(new TGe.Point3d(0, -20, 0), new TGe.Point3d(0, 20, 0)),
            //    new TDb.Circle(TGe.Point3d.Origin, TGe.Vector3d.ZAxis, 10));

            //_dview = new TlsCad.Trans.DwgView(panel1, "d:\\我的文档\\静力平衡6.dwg");

            var txt = new TDb.DBText
                {
                  Position = new TGe.Point3d(10,10,0),
                  TextString = "123",
                };
            txt.Height = 2;
            var line = new TDb.Line(new TGe.Point3d(0, 0, 0), new TGe.Point3d(10, 10, 0));
            _dview.AddEntity(txt, line);
            _dview.ZoomExtents();
            _dview.Database.SaveAs("d:\\11.dwg", TDb.DwgVersion.AC1800);
      }

      private void Form1_Resize(object sender, EventArgs e)
      {
            panel1.SetBounds(0, 0, Bounds.Width - 5, Bounds.Height - 30);
      }

      private void Form1_FormClosed(object sender, FormClosedEventArgs e)
      {
            _dview.Dispose();
            _srv.Dispose();
      }

    }
}

飞诗(fsxm) 发表于 2014-7-15 13:44:55

热烈欢迎雪山飞狐重出江湖!

sieben 发表于 2014-7-15 16:20:50

请问3.0版本的能读的最新的Dwg文件是哪个版本呢?Dwg 2010 2013 这两个版本能不能读?

雪山飞狐_lzh 发表于 2014-7-15 20:22:52

本帖最后由 雪山飞狐_lzh 于 2014-7-15 20:28 编辑

到官网(http://www.opendesign.com/)去下载了最新的Teigha Viewer +上SDK组合在一起 发现是可用的 。。。

DwgView类的InitializeGraphics函数这里要改下要
using (var module = (TGs.GsModule)TRx.SystemObjects.DynamicLinker.LoadModule("WinBitmap.txv", false, true))


飞诗(fsxm) 发表于 2014-7-15 21:30:16

第三方插件;
集成来自 Siemens PLM软件的 D-Cubed 2D DCM(2D标注约束管理器 )

对这个很感兴趣哈,低版本CAD做标准件裤的希望

寒风 发表于 2014-7-23 00:58:01

太需要这个东西了,资料太少了。谢谢雪山飞狐_lzh

lgf727 发表于 2014-8-3 11:43:13

有没有更多参考资料呢。

雪山飞狐_lzh 发表于 2014-8-4 20:48:55

Teigha的代码基本和.Net二次开发的没有很大区别

guohq 发表于 2014-8-4 22:31:24

谢谢,终于看到4.0的了
页: [1] 2 3 4
查看完整版本: Teigha的简单应用 DwgView