56beed15d08aa87c5292b38211b7f911bdd18b2c
[occt.git] / dox / dev_guides / upgrade / upgrade.md
1 Upgrade from older OCCT versions  {#occt_dev_guides__upgrade}
2 ================================
3
4 @tableofcontents
5
6 @section upgrade_intro Introduction
7
8 This document provides technical details on changes made in particular versions of OCCT, and is aimed to help upgrading user applications based on previous versions of OCCT to newer ones.
9
10 @subsection upgrade_intro_precautions Precautions
11
12 Back-up your code before upgrade.
13 We strongly recommend using version control system during upgrade process, saving one or several commits for each step of upgrade, until overall result is verified.
14 This will facilitate identification and correction of possible problems that can occur on intermediate steps of upgrade.
15 Carefully document each step to be able to repeat it if necessary.
16
17 @subsection upgrade_intro_disclaim Disclaimer
18
19 This document describes known issues that have been encountered in porting of OCCT and some applications, and approaches that helped to resolve these issues in known cases.
20 It does not pretend to cover all possible migration issues that can appear in your application.
21 Please take this document with discretion; apply your expertise and knowledge of your application to ensure correct result. 
22
23 The automatic upgrade tool is provided as-is, without warranty of any kind, and we explicitly disclaim any liability for possible errors that may appear due to use of this tool. 
24 It is your responsibility to ensure that the changes you made in your code are correct. 
25 When upgrading your code by automatic script, make sure to carefully review the changes made by it, on each step, before committing them.
26
27 @section upgrade_700 Upgrade to OCCT 7.0.0
28
29 @subsection upgrade_700_persist Removal of legacy persistence
30
31 Legacy persistence for shapes and OCAF data based on Storage_Schema (toolkits TKShapeShcema, TLStdLSchema, TKStdSchema, TKXCAFSchema) has been removed in OCCT 7.0.0.
32 Applications that used these persistence tools for their data need to be updated to use other persistence mechanisms.
33
34 The existing data files in standard formats can be converted using OCCT 6.9.0 or previous version, as follows.
35
36 #### CSFDB files
37
38 Files in CSFDB format (usually with extension .csfdb) contain OCCT shape data that can be converted to BRep format. 
39 The easiest way to do that is to use ImportExport sample provided with OCCT 6.9.0 (or earlier):
40
41 - Start ImportExport sample
42 - Select File / New
43 - Select File / Import / CSFDB... and specify the file to be converted
44 - Drag mouse with right button pressed across the view to select all shapes by rectangle
45 - Select File / Export / BREP... and specify location and name for the resulting file
46
47 #### OCAF and XCAF documents
48
49 Files containing OCAF data saved in old format usually have extensions .std or .sgd or .dxc (XDE documents).
50 These files can be converted to XML or binary OCAF formats using DRAW Test Harness commands available in OCCT 6.9.0 or earlier.
51
52 For that, start *DRAWEXE* and perform the following commands: 
53
54   * for the conversion of the "*.std" and "*.sgd" file formats to the binary format "*.cbf" (Created document should be in **BinOcaf** format instead of **MDTV-Standard**):
55
56   @code
57   Draw[]> pload ALL
58   Draw[]> Open [path to *.std or *.sgd file] Doc
59   Draw[]> Format Doc BinOcaf
60   Draw[]> SaveAs Doc [path to the new file]
61   @endcode
62
63   * for the conversion of the "*.dxc" file format to the binary format "*.xbf" (Created document should be in **BinXCAF** format instead of **MDTV-XCAF**):
64
65   @code
66   Draw[]> pload ALL
67   Draw[]> XOpen [path to *.dxc file] Doc
68   Draw[]> Format Doc BinXCAF
69   Draw[]> XSave Doc [path to the new file]
70   @endcode
71
72 On Windows, be careful to replace back slashes in the file path by either direct slash or pairs of back slashes.
73 Use "XmlOcaf" or "XmlXCAF" instead of "BinOcaf" and "BinXCAF", respectively, to save in XML format instead of binary one.
74
75 @subsection upgrade_occt700_cdl Removal of CDL and WOK
76
77 OCCT code has been completely refactored in version 7.0 to get rid of obsolete technologies used since its inception: CDL (Cas.Cade Definition Language) and WOK (Workshop Organization Kit).
78 C++ code previously generated by WOK from CDL declarations is now included directly in OCCT sources.
79
80 This modification did not change names, API, and behavior of existing OCCT classes, thus in general the code based on OCCT 6.x should compile and work fine with OCCT 7.0.
81 However, due to redesign of basic mechanisms (CDL generic classes, Handles and RTTI) using C++ templates, some changes may be necessary in the code when porting to OCCT 7.0, as described below.
82
83 WOK is not necessary anymore for building OCCT from sources, though it still can be used in traditional way -- auxiliary files required for that are preserved.
84 The recommended method for building OCCT 7.x is CMake, see @ref occt_dev_guides__building_cmake.
85 Alternative solution is to use legacy generator of project files (extracted from WOK), see @ref occt_dev_guides__building_wok.
86
87 @subsubsection upgrade_occt700_cdl_auto Automatic upgrade
88
89 Most of typical changes required for upgrading code to use OCCT 7.0 can be done automatically using the *upgrade* tool included in OCCT 7.0.
90 This tool is a Tcl script, thus Tcl should be available on your workstation to run it.
91
92 Example:
93 ~~~~~
94  $ tclsh
95  % source <path_to_occt>/adm/upgrade.tcl
96  % upgrade -recurse -all -src=<path_to_your_sources>
97 ~~~~~
98
99 On Windows, helper batch script upgrade.bat can be used, provided that Tcl is either available in PATH, or configured via custom.bat script (for instance, if you use OCCT installed from Windows installer package). Start it from command prompt:
100
101 ~~~~~
102 cmd> <path_to_occt>\upgrade.bat -recurse -all -inc=<path_to_occt>\inc -src=<path_to_your_sources> [options]
103 ~~~~~
104
105 Run upgrade tool without arguments to see the list of available options.
106
107 Upgrade tool performs the following changes in the code.
108
109 1. Adds second argument to macro DEFINE_STANDARD_RTTI indicating base class for its argument class (if inheritance is recognized by the script):
110 ~~~~~
111 DEFINE_STANDARD_RTTI(Class) -> DEFINE_STANDARD_RTTI(Class, Base)
112 ~~~~~
113
114 2. Replaces forward declarations of collection classes previously generated from CDL generics (defined in TCollection package) by \#include of corresponding header:
115 ~~~~~
116 class TColStd_Array1OfReal; -> #include <TColStd_Array1OfReal.hxx>
117 ~~~~~
118
119 3. Replaces underscored names of Handle classes by usage of a macro:
120 ~~~~~
121 Handle_Class -> Handle(Class)
122 ~~~~~
123   This change is not applied if source or header file is recognized as containing definition of Qt class with signals or slots, to avoid possible compilation errors of MOC files caused by inability of MOC to recognize macros (see http://doc.qt.io/qt-4.8/signalsandslots.html).
124   The file is considered as defining Qt object if it contains strings "Q_OBJECT" and either "slots:" or "signals". 
125
126 4. Removes forward declarations of classes with names Handle(C) or Handle_C, replacing these either by forward declaration of its argument class, or (for files defining Qt objects) \#include statement for header with name of the argument class and extension .hxx:
127 ~~~~~
128 class Handle(TColStd_HArray1OfReal); -> #include <TColStd_HArray1OfReal.hxx>
129 ~~~~~
130
131 5. Removes \#includes of files Handle_...hxx disappeared in OCCT 7.0:
132 ~~~~~
133 #include <Handle_Geom_Curve.hxx> ->
134 ~~~~~
135
136 6. Removes typedef statements that use Handle macro to generate name:
137 ~~~~~
138 typedef NCollection_Handle<Message_Msg> Handle(Message_Msg); ->
139 ~~~~~
140
141 7. Converts C-style casts applied to Handles to calls to DownCast() method:
142 ~~~~~
143     ((Handle(A)&)b)     -> Handle(A)::DownCast(b)
144     (Handle(A)&)b       -> Handle(A)::DownCast(b)
145     (*((Handle(A)*)&b)) -> Handle(A)::DownCast(b)
146     *((Handle(A)*)&b)   -> Handle(A)::DownCast(b)
147     (*(Handle(A)*)&b)   -> Handle(A)::DownCast(b)
148 ~~~~~
149
150 8. Moves Handle() macro out of namespace scope:
151 ~~~~~
152 Namespace::Handle(Class) -> Handle(Namespace::Class)
153 ~~~~~
154
155 9. Converts local variables of reference type initialized by temporary object returned by call to DownCast(), to non-references (to avoid using reference to destroyed memory):
156 ~~~~~
157     const Handle(A)& a = Handle(B)::DownCast (b); -> Handle(A) a (Handle(B)::DownCast (b));
158 ~~~~~
159
160 10. Adds \#include for all classes used as argument to macro STANDARD_TYPE(), except of already included ones;
161
162 11. Removes uses of obsolete macros IMPLEMENT_DOWNCAST() and IMPLEMENT_STANDARD_*().
163
164   > If you plan to keep compatibility of your code with older versions of OCCT, add option "-compat" to avoid the latter change. See also @ref upgrade_occt700_cdl_compat.
165
166 As long as the upgrade routine runs, some information messages are sent to the standard output. 
167 In some cases the warnings or errors like the following may appear:
168
169 ~~~~~
170   Error in {HEADER_FILE}: Macro DEFINE_STANDARD_RTTI used for class {CLASS_NAME} whose declaration is not found in this file, cannot fix
171 ~~~~~
172
173 Be sure to check carefully all reported errors and warnings, as corresponding places likely will require manual corrections.
174 In some cases these messages may help you to detect errors in your code, for instance, cases where DEFINE_STANDARD_RTTI macro passes invalid class name as an argument.
175
176 @subsubsection upgrade_occt700_cdl_compiler Possible compiler errors
177
178 Some situations requiring upgrade cannot be detected and / or handled by automatic procedure.
179 If you get compiler errors or warnings when trying to build upgraded code, you will need to fix them manually. 
180 The following paragraphs list known situations of this kind.
181
182 #### Missing header files
183
184 Use of handle objects (construction, comparison using operators == or !=, use of function STANDRAD_TYPE() and method DownCast()) now requires the type of the object pointed by Handle to be completely known at compile time. Thus it may be necessary to include header of the corresponding class to make the code compilable.
185
186 For example, the following lines will fail to compile if Geom_Line.hxx is not included:
187
188 ~~~~~
189 Handle(Geom_Line) aLine = 0;
190 if (aLine != aCurve) {...} 
191 if (aCurve->IsKind(STANDARD_TYPE(Geom_Line)) {...}
192 aLine = Handle(Geom_Line)::DownCast (aCurve);
193 ~~~~~
194
195 Note that it is not necessary to include header of the class to declare Handle to it.
196 However, if you define a class *B* that uses Handle(*A*) in its fields, or contains a method returning Handle(*A*), it is advisable to have header defining *A* included in the header of *B*.
197 This will eliminate the need to include the header *A* in each source file where class *B* is used.
198
199 #### Ambiguity of calls to overloaded functions
200
201 This issue appears in compilers that do not support default arguments in template functions (known cases are Visual C++ 10 and 11): compiler reports ambiguity error if handle is used in argument of call to function that has two or move overloaded versions, accepting handles to different types. 
202 The problem is that operator const handle<T2>& is defined for any type T2, thus compiler cannot make a right choice.
203
204 Example:
205 ~~~~~
206 void func (const Handle(Geom_Curve)&);
207 void func (const Handle(Geom_Surface)&);
208
209 Handle(Geom_TrimmedCurve) aCurve = new Geom_TrimmedCurve (...);
210 func (aCurve); // ambiguity error in VC++ 10
211 ~~~~~
212
213 To resolve this ambiguity, change your code so that argument type corresponds exactly to the function signature. 
214 In some cases this can be done by using relevant type for the corresponding variable, like in the example above:
215
216 ~~~~~
217 Handle(Geom_Curve) aCurve = new Geom_TrimmedCurve (...);  
218 ~~~~~
219
220 Other variants are assigning the argument to local variable of correct type, using direct cast or constructor:
221
222 ~~~~~
223 const Handle(Geom_Curve)& aGCurve (aTrimmedCurve);
224 func (aGCurve); // OK - argument has exact type
225 func (static_cast(aCurve)); // OK - direct cast 
226 func (Handle(Geom_Curve)(aCurve)); // OK - temporary handle is constructed
227 ~~~~~
228
229 Another possibility is defining additional templated variant of the overloaded function causing ambiguity, and use SFINAE to resolve the ambiguity.
230 For example of this technique, see definition of the template variant of the method IGESData_IGESWriter::Send().
231
232 #### Lack of implicit cast to base type
233
234 Due to the fact that now cast of handle to reference to handle to the base type is user-defined operation, conversions that require this cast combined with other user-defined cast will not be resolved automatically by compiler.
235
236 For example:
237
238 ~~~~~
239 Handle(Geom_Geometry) aC = GC_MakeLine (p, v); // compiler error
240 ~~~~~
241
242 The problem here is that class GCE2d_MakeSegment has user-defined conversion to const Handle(Geom_TrimmedCurve)&, which is not the same as type of the local variable aC.
243
244 To resolve this, use method Value():
245
246 ~~~~~
247 Handle(Geom_Geometry) aC = GC_MakeLine (p, v).Value(); // ok
248 ~~~~~
249
250 or use variable of appropriate type:
251
252 ~~~~~
253 Handle(Geom_TrimmedCurve) aC = GC_MakeLine (p, v); // ok
254 ~~~~~
255
256 #### Incorrect use of STANDARD_TYPE and Handle macros
257
258 You might need to clean your code from incorrect use of macros *STANDARD_TYPE*() and *Handle*().
259
260 1. Explicit definitions of static functions with names generated by macro STANDARD_TYPE(), which are artifacts of old implementation of RTTI, should be removed.
261    
262    Example:
263 ~~~~~
264 const Handle(Standard_Type)& STANDARD_TYPE(math_GlobOptMin)
265 {
266   static Handle(Standard_Type) _atype = new Standard_Type ("math_GlobOptMin", sizeof (math_GlobOptMin));
267   return _atype;
268 }
269 ~~~~~
270
271 2. Incorrect location of closing parenthesis of Handle() macro that was not detectable in OCCT 6.x will cause compiler error and must be corrected.
272
273    Example (note misplaced closing parenthesis):
274 ~~~~~
275 aBSpline = Handle( Geom2d_BSplineCurve::DownCast(BS->Copy()) );
276 ~~~~~
277
278 #### Use of class Standard_AncestorIterator
279
280 Class Standard_AncestorIterator has been removed; use method Parent() of Standard_Type class to parse inheritance chain.
281
282 #### Absence of cast to Standard_Transient*
283
284 Handles in OCCT 7.0 do not have operator of conversion to Standard_Transient*, which was present in earlier versions.
285 This is done to prevent possible unintended errors like this:
286
287 ~~~~~
288 Handle(Geom_Line) aLine = ...;
289 Handle(Geom_Surface) aSurf = ...;
290 ...
291 if (aLine == aSurf) {...} // will cause compiler error in OCCT 7.0, but not OCCT 6.x
292 ~~~~~
293
294 Places where this implicit cast has been used should be corrected manually.
295 The typical situation is when Handle is passed to stream:
296
297 ~~~~~
298 Handle(Geom_Line) aLine = ...;
299 os << aLine; // in OCCT 6.9.0, resolves to operator << (void*) 
300 ~~~~~
301
302 Call method get() explicitly to output address of the Handle.
303
304 @subsubsection upgrade_occt700_cdl_runtime Possible runtime problems
305
306 Known situations when problems are possible at run time after upgrade to OCCT 7.0 are listed here.
307
308 #### References to temporary objects
309
310 In previous versions, compiler was able to detect situation when local variable of reference type to Handle is initialized by temporary object, and ensured that lifetime of that object is longer than that of the variable. 
311 Since OCCT 7.0, it will not work if types of the temporary object and variable are different (due to involvement of user-defined type cast), thus such temporary object will be destroyed immediately.
312
313 Example:
314
315 ~~~~~
316 // note that DownCast() returns new temporary object!
317 const Handle(Geom_BoundedCurve)& aBC =
318 Handle(Geom_TrimmedCurve)::DownCast(aCurve);
319 aBC->Transform (T); // access violation in OCCT 7.0
320 ~~~~~
321
322 @subsubsection upgrade_occt700_cdl_compat Preserving compatibility with OCCT 6.x
323
324 If you like to preserve compatibility of your application code with OCCT versions 6.x even after upgrade to 7.0, consider the following suggestions:
325
326 1. When running automatic upgrade tool, add option *-compat*.
327
328 2. In order to overcome incompatibility of macro DEFINE_STANDARD_RTTI which has additional argument in OCCT 7.0, you can replace (after upgrade) its use in your code by your own version-dependent macro, which resolves to either 6.x or 7.x version.
329
330    Example:
331 ~~~~~   
332 #if OCC_VERSION_HEX < 0x070000
333   #define DEFINE_STANDARD_RTTI_COMPAT(C1,C2) DEFINE_STANDARD_RTTI(C1) 
334 #else
335   #define DEFINE_STANDARD_RTTI_COMPAT(C1,C2) DEFINE_STANDARD_RTTI(C1,C2) 
336 #endif
337 ~~~~~
338
339 @subsubsection upgrade_occt700_cdl_wok Applications based on CDL and WOK
340
341 If you have application essentially based on CDL, and need to upgrade it to OCCT 7.0, you will very likely need to convert your application code to non-CDL form.
342 This is non-trivial effort; the required actions would depend strongly on the structure of the code and used features of CDL.
343
344 The upgrade script and sources of specialized version of WOK used for upgrading OCCT code can be found in WOK Git repository in branch [CR0_700_2](http://git.dev.opencascade.org/gitweb/?p=occt-wok.git;a=log;h=refs/heads/CR0_700_2).
345
346 [Contact us](http://www.opencascade.com/contact/) if you need more help.
347
348 @subsection upgrade_occt700_bspline Separation of BSpline cache
349
350 Implementation of NURBS curves and surfaces has been revised: cache of polynomial coefficients, used to accelerate calculate values of B-spline, is separated from data objects (Geom2d_BSplineCurve, Geom_BSplineCurve, Geom_BSplineSurface), into dedicated classes (BSplCLib_Cache and BSplSLib_Cache). 
351
352 The benefits of this change are:
353
354 * Reduced memory footprint of OCCT shapes (up to 20% on some cases)
355 * Possibility to evaluate the same B-Spline concurrently in parallel threads without data races and mutex locks 
356
357 The drawback is that direct evaluation of B-Splines using methods of curves and surfaces becomes slower, due to absence of cache. The way to avoid slow down is to use adaptor classes (Geom2dAdaptor_Curve, GeomAdaptor_Curve and GeomAdaptor_Surface): they now use cache when the curve or surface is a B-spline.
358
359 OCCT algorithms are changed to use adaptors for B-spline calculations instead of direct methods of curves and surfaces.
360 The same changes (use of adaptors instead of direct call to curve and surface methods) should be implemented in relevant places in applications based on OCCT in order to get maximum performance.
361
362 @subsection upgrade_occt700_sorttools Removal of SortTools package
363
364 Package SortTools has been removed. 
365 The code that used the tools provided by that package should be corrected manually.
366 The recommended approach is to use sorting algorithms provided by STL.
367
368 For instance:
369 ~~~~~
370 #include <SortTools_StraightInsertionSortOfReal.hxx>
371 #include <SortTools_ShellSortOfReal.hxx>
372 #include <TCollection_CompareOfReal.hxx>
373 ...
374 TCollection_Array1OfReal aValues = ...;
375 ...
376 TCollection_CompareOfReal aCompReal;
377 SortTools_StraightInsertionSortOfReal::Sort(aValues, aCompReal);
378 ~~~~~
379 can be replaced by:
380 ~~~~~
381 #include <algorithm>
382 ...
383 TCollection_Array1OfReal aValues = ...;
384 ...
385 std::stable_sort (aValues->begin(), aValues->end());
386 ~~~~~
387
388 @subsection upgrade_occt700_2dlayers New implementation of 2d-layers
389
390 In latest OCCT version API that provided old implementation of 2d-layers was removed. Classes Aspect_Clayer2d, OpenGl_GrahpicDriver_Layer, Visual3d_Layer, Visual3d_LayerItem, V3d_LayerMgr, V3d_LayerMgrPointer were deleted.
391
392 Now 2d-layers are implemented through Z-layers. In order to create a 2d-object it is necessary to follow several steps:
393 1. Create an AIS interactive object
394 2. Set a Z-layer for it to determine in which layer this object will be displayed (layer system provides order of displaying objects, ones in the lower layer will be displayed behind the others in the higher layer)
395 3. Set transform persistence (flag Graphic3d_TMF_2d or Graphic3d_TMF_2d_IsTopDown and a gp_Pnt point, where X and Y are used to set the coordinates’ origin in 2d space of the view and Z coordinate defines the gap from border of view window, except center position)
396
397 One more feature of new 2d-layers imlementation is a ColorScale based on  a new class AIS_ColorScale. Old implementation of ColorScale as a global property of V3d_View has been removed with associated methods V3d_View::ColorScaleDisplay(), V3d_View::ColorScaleErase(), V3d_View::ColorScaleIsDisplayed(), V3d_View::ColorScale() and classes V3d_ColorScale, V3d_ColorScaleLayerItem, Aspect_ColorScale.
398
399 New interactive object AIS_ColorScale provides the same configuration API as previously Aspect_ColorScale and V3d_ColorScale. It should be used in the following way to display a 2D presentation of ColorScale:
400
401 ~~~~~
402 Handle(AIS_ColorScale) aCS = new AIS_ColorScale();
403 // configuring
404 aCS->SetHeight            (0.95);
405 aCS->SetRange             (0.0, 10.0);
406 aCS->SetNumberOfIntervals (10);
407 // displaying
408 aCS->SetZLayer (Graphic3d_ZLayerId_TopOSD);
409 aCS->SetTransformPersistence (Graphic3d_TMF_2d, gp_Pnt (-1,-1,0));
410 aCS->SetToUpdate();
411 theContextAIS->Display (aCS);
412 ~~~~~
413
414 To see how 2d objects are realized in OCCT you can call draw commands vcolorscale, vlayerline or vdrawtext (with -2d option). Draw command vcolorscale now requires a name of ColorScale object as an argument. To display this object use command vdisplay. Example:
415
416 ~~~~~
417 pload VISUALIZATION
418 vinit
419 vcolorscale cs â€“demo
420 pload MODELING
421 box b 100 100 100
422 vdisplay b
423 vsetdispmode 1
424 vfit
425 vlayerline 0 300 300 300 10
426 vdrawtext t "2D-TEXT" -2d -pos 0 150 0 -color red
427 ~~~~~
428
429 Here is a small example in c++ how to display a custom AIS object in 2d:
430 ~~~~~
431 Handle(AIS_InteractiveContext) aContext = ...; //get AIS context
432 Handle(AIS_InteractiveObject) anObj =...; //create an AIS object
433 anObj->SetZLayer(Graphic3d_ZLayerId_TopOSD); //display object in overlay
434 anObj->SetTransformPersistence (Graphic3d_TMF_2d, gp_Pnt (-1,-1,0)); //set 2d flag, coordinate origin is set to down-left corner
435 aContext->Display (anObj); //display the object
436 ~~~~~