VTK and MFC Single document program joint programming

Source: Internet
Author: User

Interest needs, want to do next VTK and MFC want to combine the program, MFC near the desktop program lost market share, and now most use QT to do, but the undergraduate time to learn is MFC, is relatively familiar with, so you want to use MFC to write a simple single document program. First we need to compile the useguisupport->usemfc tick, in order to use VTK on the MFC platform. Network now most popular two kinds of VTK and MFC methods, in fact, the key is to combine the VTK drawing window Vtkrenderwindow with the View window in MFC, so that the VTK on the graphics can be displayed on the view class on MFC. So online method One: is to use the Vtkmfcwindow class, method two: Using Renwin->setparentid (Myhwnd), in the choice of these two methods, juicy the great God in the CSDN blog above is the use of method two, But in his journal paper is recommended to use one, so I have to test the method one, but unfortunately, I follow the online step by step of the Add code, compile error-free, but in the runtime exception, check the reason is that there is a null pointer, in C + +, the appearance of NULL pointer is undoubtedly the most deadly So in the Netizen's persuasion, I used the second method to test, although on the way also appeared null pointer error, but after thinking to solve the problem, I think it may actually be the first method of the problem is similar, so the code and the results written on, lest their time long forgotten.

1. First put the console program in the program, in fact, is to read a format of XYZ three-dimensional point coordinates, and these points in order to connect together to form a coil.

#include <iostream> #include <vector> #include "vtkActor.h" #include "vtkRenderer.h" #include " VtkRenderWindow.h "#include" vtkRenderWindowInteractor.h "#include" vtkProperty.h "#include" VtkInteractorStyleTrackballCamera.h "#include" vtkPoints.h "#include" vtkPolyVertex.h "#include" VtkUnstructuredGrid.h "#include" vtkDataSetMapper.h "#include" vtkPolyData.h "#include" vtkCellArray.h "#include" VtkInteractorStyleTrackball.h "#include" vtkPolyDataMapper.h "#include" vtkSmartPointer.h "#include" vtkLine.h "# Include "VtkLineSource.h" using namespace std;void main (int argc, char* argv[]) {vtkpoints *m_points = vtkpoints::new (); VT Kcellarray *vertices = Vtkcellarray::new ();//_ store cell vertices for rendering (necessary for displaying point clouds) vtkpolydata *polydata = Vtkpolydata::new (); Vtkpolydatamapper *pointmapper = Vtkpolydatamapper::new (); Vtkactor *pointactor = Vtkactor::new (); VtkRenderer *ren1= Vtkrenderer::new (); Vtkrenderwindow *renwin = Vtkrenderwindow::new (); Vtkrenderwindowinteractor *iren = Vtkrenderwindowinteractor::new (); vtkinteractoRstyletrackball *istyle = Vtkinteractorstyletrackball::new ();//_ read-In point cloud data information FILE*FP = Null;fp=fopen ("Point.txt", "R");// Read the xyz coordinate in txt if (!FP) {printf ("Open file failed!! \ n "); exit (0);} Double X=0,y=0,z=0;int i = 0;while (!feof (FP)) {fscanf (FP, "%lf%lf%lf", &x,&y,&z); m_points->insertpoint (i,x,y,z);//_ Join point information//cout<<x<< "<<y<<" "<<z<<endl;cout<<x<<endl; Vertices->insertnextcell (1);//_ Add cell vertex information----used to render point set vertices->insertcellpoint (i); i + +;} Fclose (FP);cout<< "i-1=" <<i-1<<endl;vtkcellarray *lines=vtkcellarray::new (); for (int m=0;m<= i-1;m++) {if (m<i-1) {vtksmartpointer<vtkline> line =vtksmartpointer<vtkline>::new ();line-> Getpointids ()->setid (0,m); Line->getpointids ()->setid (1,m+1); Lines->insertnextcell (line);} Else{vtksmartpointer<vtkline> line =vtksmartpointer<vtkline>::new (); Line->getpointids ()->SetId (0,m); Line->getpointids ()->setid (); Lines->insertnextcell (line);}} _ Create pending displayData source polydata->setpoints (m_points);//_ set point set polydata->setverts (vertices);//_ set render vertex polydata->setlines ( Lines);p ointmapper->setinput (polydata);p ointactor->setmapper (pointmapper);p ointactor->getproperty ()- >setcolor (0.0,0.1,1.0);p ointactor->getproperty ()->setambient (0.5);p ointactor->getproperty () Setpointsize (2);//pointactor->getproperty ()->setrepresentationtowireframe ();//pointactor->getproperty ()->setrepresentationtosurface (); Ren1->addactor (Pointactor); Ren1->setbackground (0, 0, 0);renWin->  Addrenderer (REN1); renwin->setsize (800,800); Iren->setinteractorstyle (Istyle);  Iren->setrenderwindow (Renwin); Interactive Renwin->render (); Iren->start ();//delete each pointer m_points->delete (); Vertices->delete ();p olydata-> Delete ();p ointmapper->delete ();p ointactor->delete (); Ren1->delete (); Renwin->delete ();iren-> Delete (); Istyle->delete ();}

(2) followed by the creation of a single document in the MFC program, the configuration of the VTK environment, this time can be used juicy great God in the blog to write CmakeList.txt method, can also be a in the MFC Program additional library path, including the library path settings, but also the same effect.

After setting up the environment, we create a new class CVTK in MFC, in order to write our console program as a class, convenient for subsequent calls.

First, add the header file to the CVTK.h and declare the various pointer variables

Vtk.h:interface for the CVTK class.////////////////////////////////////////////////////////////////////////#if! Defined (afx_vtk_h__b872aed3_7a78_4473_bb74_44d3e9117a8f__included_) #define Afx_vtk_h__b872aed3_7a78_4473_bb74_ 44d3e9117a8f__included_#if _msc_ver > 1000#pragma once#endif//_msc_ver > 1000#include <iostream> #include & lt;vector> #include "vtkActor.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include " VtkRenderWindowInteractor.h "#include" vtkProperty.h "#include" vtkInteractorStyleTrackballCamera.h "#include" VtkPoints.h "#include" vtkPolyVertex.h "#include" vtkUnstructuredGrid.h "#include" vtkDataSetMapper.h "#include" VtkPolyData.h "#include" vtkCellArray.h "#include" vtkInteractorStyleTrackball.h "#include" vtkPolyDataMapper.h "# Include "VtkSmartPointer.h" #include "vtkLine.h" #include "vtkLineSource.h" class Cvtk {public:vtkpoints *m_points; Vtkcellarray *lines;vtkcellarray *vertices;vtkpolydata *polydata;vtkline *line;vtkpolydatamapper *pointMapper; Vtkactor *pointactor;vtkrenderer *ren1;vtkrenderwindow *renwin;vtkrenderwindowinteractor *iren;int i;// Vtkinteractorstyletrackball *istyle;void Beginrenderon (HWND myhwnd); CVTK (); virtual ~cvtk (); void TextRenderer (void);}; #endif//!defined (AFX_VTK_H__B872AED3_7A78_4473_BB74_44D3E9117A8F__INCLUDED_)

(3) We add a member function TextRenderer () in CVTK.cpp, its code is as follows, the key is to pop up a file dialog box, and you can select a three-dimensional text file format xyz, and insert it into the vtkpoints, and connected to a closed string.

void Cvtk::textrenderer (void) {CString filepathname; CString Wenjianhouzhui; CFileDialog Dlg (true,null,null,ofn_hidereadonly| Ofn_overwriteprompt, (LPCTSTR) _text ("Dciom Files (*.DCM) |*.dcm| TIFF Files (*.tif) |*.tif| TXT Files (*.txt) |*.txt| BMP Files (*.bmp) |*.bmp| JPG Files (*.jpg) |*.jpg| All Files (*. *) |*.*| | "), NULL), if (dlg. DoModal () ==idok) {Filepathname=dlg. GetPathName (); Wenjianhouzhui=dlg. Getfileext ();//wenjianhouzhui=dlg. Getfileext ();//afxmessagebox (Wenjianhouzhui);} Else{return;} if (wenjianhouzhui== "txt") {FILE*FP = Null;fp=fopen (Filepathname, "R");//Read the XYZ coordinates in TXT if (!FP) {AfxMessageBox ("Open file failed!! \ n "); exit (0);} Double X=0,y=0,z=0;int i = 0;m_points=vtkpoints::new (); Vertices=vtkcellarray::new (); while (!feof (FP)) {fscanf (FP, "% Lf%lf%lf ", &x,&y,&z); M_points->insertpoint (i,x,y,z);//_ Join dot Letter//cout<<x<<" "<<y << "" <<z<<endl;cout<<x<<endl;vertices->insertnextcell (1);//_ Added cell vertex information----used for render point set vertices->insertcellpoint (i); i + +;} Fclose (FP); LINES=VTKCellarray::new (); for (int. m=0;m<=i-1;m++) {if (m<i-1) {line =vtkline::new (); Line->getpointids ()->setid (0 , m); Line->getpointids ()->setid (1,m+1); Lines->insertnextcell (line);} Else{line =vtkline::new (); Line->getpointids ()->setid (0,m); Line->getpointids ()->SetId (); lines- >insertnextcell (line);}} _ Create a data source to display polydata=vtkpolydata::new ();p olydata->setpoints (m_points);//_ set point set polydata->setverts (vertices) ;//_ set render vertex polydata->setlines (lines);p ointmapper=vtkpolydatamapper::new ();p ointmapper->setinput (PolyData) ;p ointactor=vtkactor::new ();p ointactor->setmapper (pointmapper);p ointactor->getproperty ()->SetColor ( 0.0,0.1,1.0);p Ointactor->getproperty ()->setpointsize (2); ren1=vtkrenderer::new (); Ren1->addactor ( Pointactor); Ren1->setbackground (1,1,1);//ren1->setbackground (0, 0, 0); Renwin=vtkrenderwindow::new (); Renwin->addrenderer (REN1); Iren=vtkrenderwindowinteractor::new ();//istyle=vtkinteractorstyletrackball::new () ;//iren->setinteraCtorstyle (Istyle); Iren->setrenderwindow (Renwin);}}

(4) We add a member function Beginrenderer () in CVTK.cpp, whose code is as follows to get the current window pointer and set it as the parent window of the VTK drawing window

void Cvtk::beginrenderon (HWND myhwnd) {Renwin->setparentid (Myhwnd);//Start implementing if (Ren1) {Renwin->render ();}}

(5) Then we are in the CVTK of the destructor! Delete a declared pointer object in ~CVTK ()

CVTK::~CVTK () {m_points->delete (); Vertices->delete (); Line->delete (); Lines->delete ();p olydata-> Delete ();p ointmapper->delete ();p ointactor->delete (); Ren1->delete (); Renwin->delete ();iren-> Delete ();}

(6) So far, the VTK console program to MFC code has been completed, followed by the implementation of the graphics in MFC, we now add a button on the main menu to open the file, and add his event handler under the CView class.



Its event handlers are as follows, and in this call CVTK's TextRenderer () function, the following M_PVTK is the object of the CVTK class, which is the declaration made in the view's header file,

void Cmymfcpointview::ontxtfileopen () {//TODO: Add Command Handler Code m_pvtk.textrenderer () here;
       Invalidate ();}
The following is a declaration of the view class header file

Mymfcpointview.h:interface of the Cmymfcpointview class///////////////////////////////////////////////////////// #if!defined (afx_mymfcpointview_h__a74c4d7e_8977_4d06_9f00_610a95a7cff9__included_) # Define afx_mymfcpointview_h__a74c4d7e_8977_4d06_9f00_610a95a7cff9__included_#if _msc_ver > 1000#pragma once# endif//_msc_ver > 1000#include "Vtk.h" class Cmymfcpointview:public cview{protected://Create from serialization on Lycmymfcpointview ();D eclare_dyncreate (Cmymfcpointview)//attributespublic:cmymfcpointdoc* GetDocument ();/* CString Filepathname; CString wenjianhouzhui;*///operationspublic:cvtk m_pvtk;double sx;double sy;//overrides//ClassWizard generated  virtual function overrides//{{afx_virtual (cmymfcpointview) public:virtual void OnDraw (cdc* pDC); Overridden to draw this viewvirtual bool PreCreateWindow (createstruct& CS);p rotected:virtual BOOL OnPreparePrinting (cprintinfo* pInfo); virtual void onbeginprinting (cdc* PDC, cprintinfo* pInfo); Virtual void OnEndPrinting (cdc* PDC, cprintinfo* pInfo);//}}afx_virtual//implementationpublic:virtual ~cmymfcpointview (); ifdef _debugvirtual void AssertValid () const;virtual void Dump (cdumpcontext& dc) const; #endifprotected://Generated Message map functionsprotected://{{afx_msg (Cmymfcpointview)//Note-the ClassWizard would add and remove member functions  here.//do not EDIT the what you see in these blocks of generated code!//}}afx_msgdeclare_message_map () public:afx_msg void OnSize (UINT nType, int cx, int cy), afx_msg void Ontxtfileopen ();//afx_msg void OnFileOpen ();}; #ifndef _DEBUG//DEBUG version in Mymfcpointview.cppinline cmymfcpointdoc* cmymfcpointview::getdocument () {return (CM ymfcpointdoc*) m_pdocument; } #endif///////////////////////////////////////////////////////////////////////////////{{afx_insert_location}}/ /Microsoft Visual C + + would insert additional declarations immediately before the previous line. #endif//!defined (AFX_MYM fcpointview_h__a74c4d7e_8977_4d06_9f00_610a95A7CFF9__INCLUDED_) 
In order to be able to change the drawing as the window size changes, at first I was in the view of the OnSize () function to write the following code, M_pvtk.renwin->setsize (Cx,cy), but this time there will be a null pointer error, because, When the window was first created we have not renwin this pointer object, this is we click the Open File button to select a good file after the object is created, so there will be a null pointer error, in order to solve this problem, I defined in the View.h two variables sx,sy, Then write the following code in the OnSize () function to assign the value of the current window's size to Sx,sy. And I can use this value in other places.

void Cmymfcpointview::onsize (UINT nType, int cx, int cy) {cview::onsize (NType, CX, CY);//TODO: Add Message Handler code here Sx=cx;sy=cy;}

Finally, I draw in the OnDraw () function of the view class and realize the function of the graph changing with the window size

void Cmymfcpointview::ondraw (cdc* pDC) {cmymfcpointdoc* PDoc = GetDocument (); Assert_valid (PDOC);//Todo:add Draw code for native data Herem_pvtk.beginrenderon (This->m_hwnd);m_pvtk.renwin-> SetSize (Sx,sy);}

At this point, we have completed the combination of VTK and MFC program, when we click the Open File button, will appear in the view window of the drawn coil, and with the size of the window changes


You can do more three-dimensional reconstruction in this program and continue to develop. As for the availability of the Vtkmfcwindow class has not been confirmed, left for later experiments.

VTK and MFC Single document program joint programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.