Debian Codegraph @

docs/HACKING

raw
1 If you want to work _with_ the Coin sourcecode (not just writing
2 applications _using_ the Coin library) -- for helping us fixing bugs,
3 improve performance, or whatever reasons -- this file contains some
4 hints and tips for you.
5
6 ==============================================================================
7
8 1 The Bleeding Edge
9 ===================
10
11 First of all, you should make sure you are building from the latest
12 sources from the Mercurial repository you want to work with. This is
13 done by using the Mercurial for staying in sync with the sourcecode
14 repository we at Kongsberg Oil & Gas Technologies are using. Follow
15 the instructions on the webpages at
16 <URL:http://www.coin3d.org/doc/mercurial_access>.
17
18 Be aware that Coin has three source repositories. "Coin" is the head
19 development repository which is unstable and may contain unportable
20 code and break binary compatibility from time to time. "Coin-1" is the
21 repository that contains the code for the latest Coin-1.* release.
22 "Coin-2" is the repository we release the Coin 2.* releases from and
23 will always contain stable code that does not break upwards binary
24 compatibility. You can hack on either, but for your application
25 development efforts' sake you might want to follow Coin-2.
26
27 If you are not familiar with Mercurial, check out the Mercurial
28 homepages at <URL:http://mercurial.selenic.com/> and specifically the
29 Mercurial documentation in the available online book at
30 <URL:http://hgbook.red-bean.com/>.
31
32
33 2 Surviving a Large C++ Project
34 ===============================
35
36 The main problem all large C or C++ projects bump into sooner or later
37 is that the turn-around time for doing compile, link and run gets too
38 long for development to be efficient. When we're talking re-linking of
39 library files of >30MB (with debug information), its gonna get painful
40 to do rapid incremental bugfixing / testing cycles.
41
42 So I'm going to explain now how we at SIM have (more or less
43 fundamentally) solved this problem for our core Coin library. First of
44 all: use a "UNIX-like" system. MSWindows systems are no good for
45 working with the kind of setup we have, we do all new development on
46 UNIX systems (mostly Linux and SGI IRIX) and so the build process have
47 been tuned for these platforms.
48
49 A typical set-up session for me for doing Coin development on a virgin
50 machine looks like this (I'm using SoXt as the GUI library for
51 demonstration purposes):
52
53 $ cd $HOME
54 $ mkdir code
55 $ cd code
56 $ hg clone http://hg.sim.no/simage/default simage
57 [Mercurial doing its thing]
58 $ hg clone http://hg.sim.no/Coin/default Coin
59 [Mercurial doing its thing]
60 $ hg clone http://hg.sim.no/SoXt/default SoXt
61 [Mercurial doing its thing]
62
63 Note: you might want to work with a particular branch from
64 Mercurial, if so use the "branches" instead of "default"
65 repository above.
66
67 Note2: if you have already checked out the sources at an
68 earlier point in time, you just ``cd'' to the sourcecode
69 directories and do
70
71 $ hg pull -u
72
73 instead of the full checkout.
74
75
76 $ export WORKDIR=<somewhere on a local disc>
77 $ mkdir compile install
78 $ cd $WORKDIR/compile
79 $ mkdir simage Coin SoXt
80
81 $ cd $WORKDIR/compile/simage
82 $ $HOME/code/simage/configure --prefix=$WORKDIR/install
83 [configure running]
84 $ make install
85 [build should complete quickly]
86
87 $ cd $WORKDIR/compile/Coin
88 $ $HOME/code/Coin/configure --prefix=$WORKDIR/install --enable-hacking
89 [configure running]
90
91 Note the "--enable-hacking" option to configure. This is the
92 brilliant part. What happens with this option is that instead
93 of making one monolithic libCoin.so file, the Coin library
94 will be linked into many shared libraries, one for each
95 subdirectory under $WORKDIR/compile/Coin/src/. The brilliance of
96 this little trick will be explained later in the walk-through.
97
98 Note for Mac OS X users: --enable-hacking requires Mac OS
99 version 10.3 or higher. It also works with the Mac OS X
100 framework build, however note that you'll need to set your
101 DYLD_LIBRARY_PATH to include Inventor.framework/Libraries.
102 Universal Binaries are not supported.
103
104 $ make install
105
106 Building will take quite some time, go for a coffee.
107
108 The build process should complete without any compiler
109 warnings or errors -- if you see any, please notify us.
110
111 Shared library files for all sub-dirs in the Coin sourcecode
112 tree should now have been installed in $WORKDIR/install, along
113 with a top-level libCoin.so file.
114
115 Now, Libtool's .la-scheme for storing information about
116 installed libraries doesn't work too well when trying to build
117 further Libtool-based libraries or executables with the
118 "hacking enabled" Coin sub-library files. But we don't really
119 lose anything important without the .la-files, so we just
120 remove them:
121
122 $ cd $WORKDIR/install/lib
123 $ rm lib*LINKHACK*.la
124
125 Next step is to configure and build an interface library which
126 "connects" Coin with an underlying native 2D GUI toolkit. We
127 use SoXt in the example walk-through, but you can also use
128 SoQt (for TrollTech's Qt), SoGtk (for gtk+) or SoWin (for
129 interfacing against "pure" Win32 API under MSWindows).
130
131 $ cd $WORKDIR/compile/SoXt
132 $ $HOME/code/SoXt/configure --prefix=$WORKDIR/install
133 [configure running]
134 $ make install
135 [build shouldn't take long]
136
137 Ok, that's it. You should now have libsimage, libCoin and libSoXt
138 built and installed under $WORKDIR/install/lib/.
139
140 If you go look in the $WORKDIR/install/lib/ directory, you will see a
141 bunch of files named lib**something**LINKHACK.so. For each of the
142 "submodules" in Coin where you will be working, you should now remove
143 the relevant .so-files and instead symlink them directly from the
144 build directory. I.e., if you are going to work with the node classes,
145 execute the following:
146
147 $ cd $WORKDIR/install/lib
148 $ ls -c1 *nodesLINKHACK*
149 libnodesLINKHACK.la*
150 libnodesLINKHACK.so@
151 libnodesLINKHACK.so.0@
152 libnodesLINKHACK.so.0.0.0*
153 $ rm libnodesLINKHACK.so.0.0.0
154 $ ln -s $WORKDIR/compile/Coin/src/nodes/.libs/libnodesLINKHACK.so.0.0.0 libnodesLINKHACK.so.0.0.0
155
156 (The other two .so-files are just symlinks to the .so.0.0.0 file, so
157 we don't need to do anything about those.)
158
159 You should now be able to do development with very short compile &
160 link turn-around cycles on the classes in the $HOME/code/Coin/nodes/
161 directory. Each time you have made a change to the sourcecode, just
162
163 $ cd $WORKDIR/compile/Coin/src/nodes
164 $ make
165
166 Only the relevant .cpp will now be re-compiled and only the
167 libnodesLINKHACK.so sub-library will be re-linked. And the
168 libnodesLINKHACK.so in the install directory which client applications
169 are using is a symlink pointing to the one in your build directory, so
170 no re-installation need to happen.
171
172
173 One caveat emptor: if any of the class-definitions change in a non-ABI
174 compatible way in any of the corresponding .h files, you need to
175 recompile and relink _all_ sourcecode depending on this class, not
176 just the class itself. Or core dumps will happen. (See footnote 1 at
177 the end of this document for an explanation of the term "ABI".)
178
179 There are many, many ways to break ABI compatibility in C++:
180
181 - variables being added or removed from / to a class, making it's
182 sizeof() change
183 - functions added or removed
184 - functions made virtual or "un-made" from virtual
185 - function signatures changed in general
186
187 ...etc. See footnote 1 at the end of this document for more
188 discussion on the issue. Anyway, as long as you're only changing the
189 .cpp files, you should be home free.
190
191
192 Right after we implemented this scheme, there was an article called
193 "Pseudo-Incremental Linking For C/C++" in the Dr Dobb's Journal. The
194 article is available at
195
196 <URL:http://www.ddj.com/articles/1999/9910/9910d/9910d.htm>
197
198 and explains the principles applied fairly well.
199
200
201 3 Debugging Tricks
202 ==================
203
204 * COIN_DEBUG_BREAK
205
206 All calls to SoDebugError::post*() have the first argument (the
207 function name) compared to the $COIN_DEBUG_BREAK environment variable.
208 If they match, an assert will fail, and you can then inspect the stack
209 backtrace (if symbol/debugging information was built into the library).
210 This can be very useful and is not limited to Coin usage - all client
211 programs can take advantage of this functionality too.
212
213 Example:
214
215 $ env COIN_DEBUG_BREAK="SoAction::apply" ./mytestprogram
216
217 [using 'env var=val prog ...' is the most portable syntax for this kind
218 of thing, which is why the example uses it instead of the Bourne syntax]
219
220
221 * Make yourself familiar with the Valgrind tool, which is *extremely*
222 useful for tracking down memory corruption problems. A link to
223 Valgrind can be found on <URL:http://freshmeat.net>.
224
225 Note that Valgrind, can also be used for profiling code _without_
226 having to re-compile everything (like what is necessary for gprof,
227 for instance).
228
229 Another interesting feature of Valgrind is that it has a skin called
230 "helgrind" which supposedly can do analysis of code to see if it's
231 re-entrant / thread-safe. I (mortene) haven't tested it yet, but if
232 it works, it would be extremely useful for debugging hard to find
233 bugs suspected to be due to synchronization problems over multiple
234 threads.
235
236
237 * OpenGL debugging:
238
239 - Useful environment variables for the Mesa OpenGL implementation:
240
241 * LIBGL_ALWAYS_INDIRECT=yes
242
243 (Avoids any use of hardware acceleration -- useful for
244 running Coin-on-Mesa under Valgrind.)
245
246 * LIBGL_DEBUG=yes
247 * MESA_DEBUG=yes
248
249
250 - To turn off SSE/MMX use in the NVidia Linux drivers, which avoids
251 problems with at least pre-2.0 Valgrind version:
252
253 * __GL_FORCE_GENERIC_CPU=1
254
255
256
257 4 Misc Configurations
258 =====================
259
260 * Mercurial
261
262 In order to allow the storage of your Mercurial password with the
263 standard Mercurial command line client in a convenient but secure
264 fashion have a look at the Keyring Extension:
265
266 http://mercurial.selenic.com/wiki/KeyringExtension
267
268 As the default on Mercurial is to prompt you for a password it is
269 somewhat safe apart from the regular caveats to check in outside of
270 your trusted workstation.
271
272 * emacs
273
274 To enable C++ mode for the template *.in source files, add this to
275 your ~/.emacs file:
276
277 (setq auto-mode-alist (cons '("\\.h\\.in\\'" . c++-mode) auto-mode-alist))
278 (setq auto-mode-alist (cons '("\\.cpp\\.in\\'" . c++-mode) auto-mode-alist))
279 (setq auto-mode-alist (cons '("\\.icc\\'" . c++-mode) auto-mode-alist))
280
281 Also, to make emacs insert spaces instead of tabulator characters when
282 indenting (we don't want any tabulators):
283
284 (let ((loadhook (lambda () (setq indent-tabs-mode nil))))
285 (add-hook 'find-file-hooks loadhook)
286 (add-hook 'find-file-not-found-hooks loadhook))
287
288 * vim
289
290 To insert spaces instead of tab characters (using 2 space characters
291 every time you press 'tab', and also using 2 spaces for
292 auto-indentation), add the following to your ~/.vimrc file:
293
294 set expandtab
295 set tabstop=2
296 set shiftwidth=2
297
298 * MS Visual Studio
299
300 Under tools -> options, choose the Tabs group and check the radio button
301 that says "insert spaces" and choose tab size 2.
302
303
304 5 The Build Environment
305 =======================
306
307 * Defines
308
309 HAVE_CONFIG_H
310
311 This define should always be defined, but if it isn't, then the
312 config.h header will not be included. Lots of features will then be
313 disabled. Lots of files will probably not even compile since we do
314 not test this case. Anyways, this case is usually the case when
315 someone tries building the library without using the Autoconf setup.
316
317 COIN_INTERNAL
318
319 This is a define that is set when the Coin library is being compiled.
320 Setting it when compiling things outside the Coin library is a
321 mistake.
322
323 COIN_DEBUG
324
325 This define should be set to either 0 or 1. It is therefore used
326 with the #if directive, not the #ifdef directive. Actually, this define
327 is now preferably used as an if-condition to avoid littering the source
328 code with too many preprocessing directives.
329
330 COIN_EXTRA_DEBUG
331
332 This define is ordinarily not used, but can be defined to enable some
333 extra sanity checks that may detect obvious, but otherwise hard to
334 detect bugs like specifying indexes out of an arrays range, etc.
335 Enabling this define may slow things down considerably, depending on
336 how heavily the parts of Coin you use most are instrumented.
337
338
339 6 The Run-Time Environment
340 ==========================
341
342 * See So@Gui@/src/Inventor/@Gui@/common/HACKING for debugging hints.
343
344
345 7 How To Add / Modify A Class In Coin
346 =====================================
347
348 * Implement the class.
349
350 * Write Doxygen documentation for the class. Remember to tag the doc
351 with \since YYYY-MM-DD, either for the class itself or for any
352 functions with a new or changed API.
353
354 * Update cross-references from other documentation if necessary.
355
356 * If new source files were introduced:
357
358 * Add them to the Mercurial repository.
359
360 * Add the header and any generated doc files for the class to
361 build/coin.spec.in (for RPM generation).
362
363 * Add the source files to docs/coin.doxygen.in (for
364 documentation generation).
365
366 * If we are a subtype of SoBase, update the correct files for
367 initializing the class (i.e. src/nodes/SoNode.cpp).
368
369 * Add the source files to the corresponding all.cpp file.
370
371 * Add the header file to the corresponding common include file
372 (i.e. include/Inventor/nodes/SoNodes.h)
373
374 * Add the source files to the Makefile.am file in the source
375 file directory (for building).
376
377 * If the class is public, add the header file to
378 src/Makefile.am or any of src/*/Makefile.am (for
379 installation).
380
381 * Remember to rerun bootstrap when changing any
382 Makefile.am. See below.
383
384
385
386 8 Bootstrapping
387 ===============
388
389 "Bootstrapping" is the process of making or updating the
390 program-generated files of the Coin library (and other SIM modules),
391 typically those used for configuration and building.
392
393 Bootstrapping needs to at least be done when changes or additions are
394 done on configure.ac, or any of its dependencies (like the *.m4 files
395 mentioned below), or to any of the Makefile.am files. Bootstrapping
396 will run the GNU Autotools; Autoconf, Automake and Libtool, which will
397 use the aforementioned configure.ac, *.m4 files and Makefile.am files
398 to make shell scripts and "true" Makefile-files for configuration and
399 build.
400
401 To be able to bootstrap the Coin repository (or any other SIM code
402 repository), you need to check out the "simacros" modules from Coin's
403 Mercurial main repository. Then, in a UNIX shell, ''cd'' to the base
404 directory of the Coin module (where the source code for Coin is
405 located) and run ''<simacrosdir>/bin/bootstrap''.
406
407 Note that bootstrapping before committing changes to
408 Autotools-generated files should _always_ happen on the internal
409 valhalla.trh.sim.no server. There are several reasons for this:
410
411 - When trying to trace down bugs related to the configure and / or
412 the build process, it helps a _lot_ to only have to do this for
413 one particular version of Autoconf / Automake / Libtool.
414
415 - Sometimes we have to patch up one or more of the Autotools. Doing
416 this in a centralized manner on valhalla.trh.sim.no is of course
417 time-saving, and not prone to sync'ing errors.
418
419 - We don't want to have _heaps_ of differences in bootstrapped,
420 generated files for each commit -- which we would get if we all
421 used slightly different versions of the Autotools.
422
423 Note that it can be a bit of a hassle to *always* bootstrap on
424 valhalla.trh.sim.no, and that is not necessary either. What we advice
425 when valhalla.trh.sim.no is somewhat out of reach is: install
426 Autoconf, Automake and Libtool on your local development
427 box. Bootstrap locally when developing. When done, commit all changes
428 _except_ files generated by Autoconf, Automake and Libtool. Then ssh
429 into valhalla.trh.sim.no, bootstrap, then commit the freshly
430 bootstrapped, generated files.
431
432
433 9 How To Backport Development-Branch Extensions to Coin-2
434 =========================================================
435
436 You are not allowed to break forward ABI compatibility with versions
437 of Coin-2 (or Coin-1, for that matter) when you backport extensions
438 which have been added to the Coin development branch. Virtual methods
439 is one of the biggest problems with regards to this.
440
441 * Backporting Virtualism
442
443 If you need to packport virtualism from Coin to Coin-2, one suggestion
444 is to add a non-virtual callback handler system on the lowest level in
445 the class hierarchy that needs this virtual function, and then the
446 deriving classes can register their overriding functions in the
447 constructor. If they need to emulate invoking the inherited::*
448 function, they must of course store the callback/closure pair locally in
449 the class (private part) that was already set by the parent class when
450 they register the overriding function.
451
452
453 10 Include Files
454 ================
455
456 A few points about include files.
457
458 * Include as few files as possible in header files, but not so few
459 that the header file depends on other headers having been included
460 before it. Including a header on it's own should not produce
461 syntax errors.
462
463 The techniques used to do that is mainly to pre-declare class types,
464 and to hide class internals with the Cheshire Cat / Bridge pattern.
465
466 * When setting up which include files to include in source files,
467 keep the order structured. Follow this pattern:
468
469 <config.h>, if included, should be the first header.
470
471 Start with the most basic / standard libraries, and work your way
472 down through non-standard external libraries and optional libraries
473 (and do it library by library), before finally including headers
474 internal in the current project.
475
476 * libc/CRT includes first
477 * other ANSI / POSIX libraries (pthreads++)
478 * X libraries (or other GUI stuff)
479 * optional libraries (for instance audio)
480 * Open Inventor *core* headers
481 * Open Inventor toolkit headers
482 * Open Inventor extensions headers
483 * internal headers
484 * "inline" source files
485
486 If for some reason you can't follow this ordering, it's most likely
487 a design problem on your behalf, which you should fix sooner, rather
488 than later...
489
490 =======================================================================
491 XXX FIXME: complete doc. XXX
492
493 * Building Coin for development (UNIX)
494 - solutions applied in Coin
495 o make install-data
496 o make *-am
497
498 * Differences, MSWin
499
500 * Build hacking, bootstrap/Autoconf/Automake/Libtool
501
502 * Submitting patches
503 - technical walk-through
504 - legal aspects
505
506 ==============================================================================
507
508 Library versioning
509 ==================
510
511 When making releases, we follow these rules:
512
513 * If there has been made any incompatible changes to the ABI (see
514 footnote 1 at end of document for an explanation of the term "ABI"):
515
516 COIN_MAJOR_VERSION += 1,
517 COIN_MINOR_VERSION = 0,
518 COIN_MICRO_VERSION = 0.
519
520 (If you don't know if the changes that have been made since last
521 release is binary incompatible with the last ABI, you shouldn't
522 be making releases.)
523
524 Typical cases: public interfaces have been changed in a manner that
525 is not compatible with old code. Classes have add private data
526 members added or removed.
527
528 We might also have just simply added many new significant major
529 features to the library, which in itself justifies increasing the
530 major version number.
531
532
533 * If there has been made additions to the API (see footnote 2 at the
534 end of the document for an explanation of the term "API"), but the
535 ABI is still backwards compatible:
536
537 COIN_MAJOR_VERSION unchanged,
538 COIN_MINOR_VERSION += 1,
539 COIN_MICRO_VERSION = 0.
540
541 Typical cases: new functionality has been added through new C
542 functions, new C++ class member functions have been added (but not
543 virtual functions, as that changes the sizeof() value of a class),
544 or completely new classes have been added.
545
546
547 * For bugfix releases and other changes which do not change the interface
548 at all:
549
550 COIN_MAJOR_VERSION unchanged,
551 COIN_MINOR_VERSION unchanged,
552 COIN_MICRO_VERSION += 1.
553
554 ==
555
556 The following text pertains to the versioning that is set up in
557 configure.ac, with regard to Libtool library versioning:
558
559 Note that our MAJOR.MINOR.MICRO versioning scheme differs somewhat from
560 the idea of library versioning applied by Libtool. According to Libtool,
561 libraries should be versioned according to a CURRENT.AGE.REVISION scheme.
562 Here CURRENT is supposed to be increased by 1 each time the API changes,
563 and AGE increased by 1 along with CURRENT each time the API changes in a
564 way which keeps the ABI backwards compatible. If compatibility is broken,
565 AGE is set to 0 (while CURRENT is still increased by 1). The REVISION
566 number has the same semantics as our MICRO number.
567
568 To cooperate in a painless way with Libtool, we choose to "convert" our
569 MAJOR.MINOR.MICRO scheme to Libtool's idea of versioning like this:
570
571 * Libtool's CURRENT number is increased when the MAJOR or MINOR number is
572 changed. If development and releases were done in a linear fashion, we
573 would just have to increase CURRENT by one when the above happens, but
574 since we intend to continue to support Coin 1.* after the release of
575 Coin 2.* we have had to make up a different scheme. What we have done is
576 to reserve room for 20 minor releases between each major release. This
577 should hopefully be more than enough. With this premise, we can calculate
578 CURRENT with the formula MAJOR * 20 + MINOR. This will ensure that
579 CURRENT for 2.0 will be greater than CURRENT for 1.3 (and 1.17 for that
580 matter).
581
582 Note that this scheme has the "strange" (it's actually completely natural)
583 effect that Coin 1.0 will be found as /usr/local/lib/libCoin.so.20.*
584 (for Linux) and Coin 2.0 will be libCoin.so.40.*.
585
586 * Libtool's AGE number is the number of previous CURRENT version numbers
587 that the library is binary compatible with. This should always be the same
588 number as MINOR is - when we make a new release with a new MAJOR number
589 and 0 as MINOR number, ABI compatibility *will* be broken.
590
591 * Libtool's REVISION number is the number of the release with the exact same
592 API/ABI as the previous release. This is typical for patch-releases
593 where some implementation bugs are fixed without touching anything in the
594 library API. In other words, when we up the MICRO number. This means
595 REVISION = MICRO.
596
597 ==============================================================================
598
599 Mercurial maintenance
600 ======================
601
602 New "Coin-MAJOR" repositories will be branched off the head "Coin"
603 repository. "Branching" in this context means to clone the "default/"
604 subdirectory to the "Coin/" directory through the standard
605 Mercurial "clone" command.
606
607 When this happens, the Coin repository should be tagged with the
608 symbolic name "coin-MAJOR.MINOR".
609
610 All releases will be made from the Coin-MAJOR.MINOR repositories.
611 When a new release is made from one of those, the sources will be
612 tagged with the symbolic name "Coin-MAJOR.MINOR.MICRO". This was
613 forgotten for the Coin-1.0.0 release, but for MAJOR.0.0 releases this
614 is not very important as it will coincide with the initial import of
615 the repository.
616
617 Releases made from Coin-MAJOR repositories will be in sequence. When
618 the MINOR version number is increased, no more releases of the MINOR -
619 1 branch will be made.
620
621
622 Making Releases
623 ===============
624
625 Make sure to consult Coin/docs/RELEASE.txt for detailed and up2date
626 release procedures.
627
628 When a new release is to be made, configure.ac must be updated with
629 new version information. Make sure COIN_BETA is set to [] (empty), and
630 the release version number is set up. Run bootstrap and check that
631 "make distcheck" works. Commit the changes with a message about
632 setting the version number to MAJOR.MINOR.MICRO.
633
634 Add a Mercurial tag on the new version number.
635
636 $ hg tag Coin-MAJOR.MINOR.MICRO \
637 -m "Tagging the MAJOR.MINOR.MICRO release of the 'Coin' project."
638
639 Edit configure.ac again and increase micro (unless a new minor will be
640 the next release) and set COIN_BETA to [a]. Rerun bootstrap, and
641 commit the new setup with a message about setting the version number
642 again.
643
644 These two version-increment commits should happen without getting any
645 unrelated commits in between them so there won't be multiple states of
646 the Mercurial repository with a release version number.
647
648 Then go back to the tag (hg update -rCoin-MAJOR.MINOR.MICRO) and
649 prepare the release.
650
651 Source release tarballs are created with:
652
653 $ hg archive -tzip Coin-MAJOR.MINOR.MICRO.zip
654 $ hg archive -ttgz Coin-MAJOR.MINOR.MICRO.tar.gz
655
656 Binary releases are created from the source release tarball combining
657 the respective the buildbot output from the binary snapshot directory.
658
659
660 Correcting Erroneous Log Messages
661 =================================
662
663 Sometimes commits ends up with incorrect log messages due to the
664 committer being a bit too trigger-happy. The following Mercurial book
665 chapter describes how to achieve that:
666
667 http://hgbook.red-bean.com/read/finding-and-fixing-mistakes.html
668
669 Do this instead of reversing and reapplying, or other round-about and
670 confusing techniques...
671
672
673 ==============================================================================
674
675 Coin Code Standards
676 ===================
677
678 The main goal is of course to write good, bugfree, portable C++ code,
679 in a way that clearly expresses the intent of what is attempted
680 accomplished.
681
682 First, the larger issues:
683
684 I. PORTABILITY.
685
686 Some specific remarks about portability: this is very far from
687 being a trivial matter with C++, as not only is system
688 portability difficult (due to differences in core libraries for
689 various platforms), but _compiler_ portability is also a big
690 issue with C++. The main reason behind this is that the ISO C++
691 standard evolved gradually and slowly, and many C++ compilers
692 that are still around on much used platforms were written before
693 the standard was complete. And even today, it is actually
694 doubtful if any C++ compiler around implements the full
695 standard, as it is so huge and complex.
696
697 To keep everything as portable as possible, we basically use the
698 C++ language as more or less a "C with classes".
699
700 For the full monty on C++ portability, please read the C++
701 portability guide written for the Mozilla browser project:
702
703 <URL:http://www.mozilla.org/hacking/portable-cpp.html>
704
705 We consider this a must read for any internal resources writing
706 production C++ code. One issue it's particularly easy to "sin"
707 against is the following:
708
709 Use the ``SbBool'' type instead of bool, and ``TRUE'' and
710 ``FALSE'' keywords instead of ``true'' and ``false''. Compilers
711 that do not support the ``bool'' type is still in widespread use
712 (SGI MIPSPro v7.30 is but one example), so we are using the more
713 portable ``SbBool'' instead to make sure our code build on those
714 systems.
715
716
717 II. THE CHESHIRE CAT / THE BRIDGE PATTERN
718
719 There is one important "trick" to apply to C++ classes when they
720 are part of a library with a public API where binary
721 compatibility (i.e. a stable ABI (see footnote 1 at end of
722 document)) between releases are important -- as it is for the
723 Coin library. The trick is to hide all the private
724 implementation data within an internal class, only visible to
725 the .cpp-file of the "real" class.
726
727 This is a common design pattern that goes under many different
728 names; the Bridge pattern (from «Design Patterns», Gamma et al),
729 the Cheshire Cat (from the character in Lewis Carroll's «Alice's
730 Adventures in Wonderland»), pimpl (short for "private
731 implementation") or the d-pointer (for "data-pointer"). For
732 consistency, it will be called "Cheshire Cat" from now on in
733 this explanation.
734
735 The main advantage of applying the Cheshire Cat is that one can
736 add new data members to the implementation of a class without
737 breaking it's ABI -- which avoids the need to hold back new
738 features, new functionality or even bugfixes to the next major
739 release of the library.
740
741 The general idea of the Cheshire Cat is as follows:
742
743 <APublicClass.h>:
744
745 ---8<------8<------8<------8<------8<------8<------8<------8<---
746
747 class APublicClass {
748 public:
749 // [public API here]
750
751 protected:
752 // [protected API here]
753
754 private:
755 class APublicClassP * pimpl; // contains internal implementation data
756 };
757
758 ---8<------8<------8<------8<------8<------8<------8<------8<---
759
760 ..where the "APublicClassP" (notice the trailing "P" for
761 "Private") declaration could be embedded in the APublicClass.cpp
762 file, for simplicity:
763
764 <APublicClass.cpp>:
765
766 ---8<------8<------8<------8<------8<------8<------8<------8<---
767
768 #include "APublicClass.h"
769
770 class APublicClassP {
771 public: // all data publicly available for "owner" APublicClass
772 int number1;
773 float number2;
774 // [etc]
775 };
776
777 // [then follows the implementation of APublicClass]
778
779 APublicClass::APublicClass()
780 {
781 // set up internal data class
782 this->pimpl = new APublicClassP;
783 // ...
784 }
785
786 APublicClass::~APublicClass()
787 {
788 // ...
789 delete this->pimpl;
790 }
791
792 // [for other code, all data are accessed through the "pimpl" pointer]
793 this->pimpl->number2 = obj->doSomeThing(this->pimpl->number1);
794 // ...
795
796 ---8<------8<------8<------8<------8<------8<------8<------8<---
797
798 If we then noticed that we need more data members for new
799 features or to fix bugs in APublicClass, we can just add those
800 to the internal class without breaking the ABI compatibility.
801
802 For a real example of how to use this pattern, see for instance
803 the declaration and implementation of the SoExtSelection node
804 class or the SoRayPickAction class (among many others), or any
805 class in the So* libraries (where the pattern has been used most
806 extensively).
807
808 There are basically just a few cases where the Cheshire Cat
809 should /not/ be applied: for very light-weight small classes, we
810 don't want the extra overhead it introduces in memory usage and
811 time to redirect all data request to the internal class. So the
812 Sb* base classes are for instance not using the pattern, and
813 neither are SoBase and SoField -- which both permeates library
814 usage at run-time, so we want to keep them as slim as possible.
815
816 The preferred way to access the pimpl pointer, and to access the
817 "real" class (in the public interface) back from the private
818 class, is to set up a couple of macros:
819
820 #define PRIVATE(p) ((p)->pimpl)
821 #define PUBLIC(p) ((p)->master)
822
823
824 ..and then use it in statements like this:
825
826 PRIVATE(this)->number2 = obj->doSomeThing(PRIVATE(this)->number1);
827
828 Specifically, don't use the "THIS" define which we used to do in
829 earlier times:
830
831 #define THIS this->pimpl
832
833 ..as it clashes with a define for "THIS" made somewhere in the
834 header files of Microsoft Visual Studio.
835
836
837 III. GLOBAL NAMESPACE POLLUTION
838
839 Don't you ever dare pollute the global namespace unnecessary!
840
841 That goes for: defines, macros, enums, typedefs, function names,
842 etc etc. If you *have* to make something global, you should at
843 least prefix it with "COIN_" (or some such) that minimizes the
844 chances of clashes with client code, system / compiler symbols,
845 or symbols from Coin's dependencies.
846
847 One common mistake you should in particular be careful to avoid
848 is to specify stand-alone functions in source code
849 implementations like this:
850
851 void
852 myhelperfunc(int a, int b)
853 {
854 // ...
855 }
856
857 Use the "static" keyword to make sure the function symbol is
858 *truly* local, to exclude such functions from the global
859 namespace!:
860
861 static void
862 myhelperfunc(int a, int b)
863 {
864 // ...
865 }
866
867
868 IV. C++ FEATURES UNAVAILABLE TO COIN PROGRAMMERS
869
870 Because we want to support fairly old C++ compilers, there are a
871 number of C++ features that are forbidden to use for Coin source
872 code. What follows may not be a comprehensive list, more items
873 will likely be added. Anyway, one must at least avoid these:
874
875 - Don't use functionality out of the Standard Template Library
876 ("STL") -- the implementation and compatibility of this seems
877 to be sub-par on a lot of C++ compiler systems.
878
879 - Don't use functionality out of the C++ library, like e.g. file
880 streams -- we don't want to force a link dependency on
881 libstdc++, since it has been (and still is?) very unstable
882 with regard to binary compatibility, making it harder to make
883 binary distributions for e.g. Linux systems.
884
885 - Don't use namespaces. They are not supported on some older
886 compilers we want the code to be compatible with.
887
888 - Don't use exceptions.
889
890
891 Enough about the larger issues, now for the mucky details that has
892 been written down to guide the Coin programmers in being consistent
893 versus the code "layout" (to make it more easily readable):
894
895 0) If the code you write is not 100% complete;
896
897 - Leave a "FIXME" message if you believe the code is fairly
898 correct, but you are unsure and have not checked the correctness
899 yet, or if there are known deficiencies. This includes cases
900 like ambiguities in the OIV docs that will require some
901 investigation to resolve, error-cases or places where one should
902 be more robust that haven't been fixed yet due to time
903 constraints, etc.
904
905 - Insert "COIN_STUB();" statements if the code lacks certain
906 important functionality, so situations where unimplemented
907 features are used will be detected at run-time.
908
909 - Leave FIXMEs if you see obvious cases for performance
910 improvements which should be explored.
911
912 A FIXME-message must include a description of the problem, who
913 wrote the message, and when. Please include whatever you have
914 already found out about the problem in the FIXME text, so your
915 next of kin don't have to painstakingly re-do all the thought-work
916 you already have laid down. Example:
917
918 // FIXME: should be possible to simplify cylinder test, since this
919 // cylinder is aligned with the y-axis. 19991110 pederb.
920
921 or
922
923 // FIXME: this action seems completely bogus, as if something fails,
924 // all bets are off and we should simply terminate the import
925 // operation. (flushInput() continues to read and scans for a
926 // closing brace). Run with this code disabled for a while and axe
927 // it if nothing bad seems to come from it. 20020531 mortene.
928 //
929 // if (!ret && flush) SoBase::flushInput(in);
930
931 This goes also for other keywords in comments (see below). It
932 makes it much easier when others try to fix code that doesn't
933 work. You will know who to ask if you don't understand the
934 problem, and the date could indicate among other things the
935 urgency of the problem.
936
937 If you have postponed implementing something, which has to
938 be implemented before Coin is officially released again, put a
939 section like this in the code to assert that it won't be
940 forgotten:
941
942 #ifndef COIN_BETA_VERSION
943 #error implementation missing: something or other
944 #endif // !COIN_BETA_VERSION
945
946 Don't use this trick more than absolutely necessary. The release
947 master will be pretty pissed off each time a planned release has
948 to be aborted.
949
950 1) If blocks of code are commented out (obsoleted) to make place for
951 new code, or because it has become superfluous, one should mark it
952 like the example below if it is a large block of code, if the new
953 code is very experimental, or if the new code is obfuscated
954 (e.g. because of optimizations).
955
956 #if 0// OBSOLETE: <textual description>. <yyyymmdd userid>.
957 ...old code...
958 #else // short description of new code
959 ...new code...
960 #endif // newcode
961
962 See also the next rule.
963
964 2) Under *no* circumstances should developers leave any code which
965 has been commented out with the language constructs "// ..." or
966 "/* ... */" in anything you check into the repository, at least
967 not without commenting _why_ the code is still present.
968
969 It's often very time-consuming and just a bloody pain in the ass
970 and a waste of resources trying to figure out why commented-out
971 code is still present in a source file (is it new code which
972 *might* fix a bug, but which haven't been tested yet? is it old
973 code found to be buggy which have been removed? is it commented
974 out because it is a new feature which is yet to be completed? etc
975 etc etc).
976
977 Programmers who continues to sin against this rule after having
978 this pointed out to them should be taken out behind the barn to be
979 shot.
980
981 3) During debugging, write debug code like this:
982
983 #if COIN_DEBUG && 1 // debug
984 SoDebugError::postInfo(...
985 #endif // debug
986
987 Then, flip the "#if COIN_DEBUG && 1" to "#if COIN_DEBUG && 0" if
988 there is a chance that the debug information might be useful
989 later. If not, remove it before making a patch or checking in.
990
991 If there are many debug statements in the same category, use a
992 define for that category (#if DEBUG_<category>) and define it to 0
993 at the top of the file before checking in the code. See
994 src/sensors/SoSensorManager.cpp for examples of how this should be
995 done.
996
997 UPDATE 2001-11-21 larsa: Actually, we now prefer that you use this
998 define as an if-condition instead, because of the cleaner look the
999 source code gets when it is not littered with preprocessing
1000 directives. For permanent debugging code, write therefore source
1001 code like this instead:
1002
1003 if ( COIN_DEBUG ) {
1004 SoDebugError::postInfo("SoDB::funnyRabbit", "follow the white rabbit");
1005 }
1006
1007 UPDATE 2002-06-17 mortene: this decision has been reversed, at
1008 least temporarily, as we can't seem to get a definitive answer to
1009 whether or not code and data within an "if (0) { ... }" construct
1010 is still taking up space in the generated object and library
1011 files.
1012
1013 4) Do not under any circumstances use printf() / fprintf() / puts()
1014 or related functions for output. It should not be necessary --
1015 the Coin class SoDebugError (and SoReadError) was implemented for
1016 a reason. Debug messages with printf() / fprintf() is extremely
1017 uncool when you use Coin as a DLL under Windows (it's likely to
1018 cause mysterious crashes), and besides it's bloody irritating to
1019 walk through the code later to remove them.
1020
1021 5) Don't use any variablename, classname, define, functionname or any
1022 other identifier that starts with an underscore. That namespace is
1023 per the C and C++ specs fully reserved for the compiler
1024 implementation.
1025
1026 Identifier names with double underscores anywhere in the name is
1027 also reserved.
1028
1029 For more information about this than you really want to know, see
1030 Section 17.4.3.1 "Reserved names" and its subsections in the C++
1031 language spec.
1032
1033 6) Prefix with the "this" keyword for dynamic functions and member
1034 variables, prefix with the classname for static functions and
1035 variables.
1036
1037 The rationale for doing this extra typing is that it makes the
1038 code immensely more easily readable when skimming it. If the
1039 prefixes are missing, one has often to scroll back and forth to
1040 find out if variables are input arguments to methods or stack
1041 variables -- with "this->" or "ClassName::" prefixes there is
1042 immediately no doubt where the variable comes from.
1043
1044 7) Code formatting rules. The default is to use Kernighan and Ritchie style.
1045
1046 a) Braces: keep opening braces on the end of the line, and closing
1047 braces at the start. Like this:
1048
1049 if (...) {
1050 ...
1051 }
1052
1053 And not like this:
1054
1055 if (...)
1056 {
1057 ...
1058 }
1059
1060 The exception from this rule is functions, which should have the
1061 opening brace on the next line.
1062
1063 b) Indentation: use 2 spaces extra for each level of nesting.
1064
1065 *Never* use tabulator characters (ie ASCII code 0x09), as
1066 editors expands them differently. The code indentation will
1067 therefore more often than not look like crap with the default
1068 settings of any other editor than the one you happen to be using
1069 yourself.
1070
1071 c) Spacing: use 1 space after commas and around operators (like +,
1072 -, *, /, ==, &&, etc), but not after or before parentheses.
1073
1074 Like this:
1075
1076 if (val) { i = sqrt(a) * func(b, c); }
1077
1078 Not like this:
1079
1080 if ( val ) { i=sqrt(a)*func(b,c); }
1081
1082 d) Naming: class names should be uppercased for each word, function
1083 names for each word except the first one, variable names should
1084 be all lowercase, and defines, enums and constants should be all
1085 uppercase. Example:
1086
1087 float
1088 MathClass::calculateValue(float in)
1089 {
1090 const float FACTOR = 2.78;
1091 ...
1092 ...
1093 }
1094
1095 For C functions and C++ functions that doesn't belong to any
1096 particular class, name them with underscores between words, in
1097 all lowercase.
1098
1099 NOTE: do *not* use Hungarian-style naming, ie prefixing names
1100 with indicators about type. So don't for instance name classes
1101 with a leading "c", or member variables with an "m", or integers
1102 with an "i" and so on and so on. You're better off in the
1103 readability-department by using the "this" prefix, as explained
1104 above, and then the Hungarian naming style just obfuscates the
1105 code.
1106
1107 e) Pointer types and references: use a space on each side of the
1108 '*' and '&' operators, like this
1109
1110 SoNode * mynode = NULL;
1111
1112 not like this
1113
1114 SoNode *mynode = NULL;
1115
1116 because it makes it look like the '*' "belongs" to the variable
1117 name (which of course is wrong -- it's part of the type), and
1118 not like this either
1119
1120 SoNode* mynode = NULL;
1121
1122 because it's ugly and unusual. So for consistency, _please_
1123 stick with the space-on-both-sides convention in Coin code.
1124
1125 f) Use
1126 return x;
1127 and not
1128 return (x);
1129
1130 (Since "return" is not a function with arguments, the latter
1131 just looks plain wrong.)
1132
1133 ==============================================================================
1134
1135 API Documentation Guidelines
1136 ============================
1137
1138 Documentation of the Coin API is done with a setup and syntax
1139 compatible with the Doxygen tool. For general information and detailed
1140 documentation about the Doxygen syntax, see
1141 <URL:http://www.doxygen.org>.
1142
1143 We allow documentation to be done in a rather free-form manner, as
1144 long as it conforms to the valid syntax of Doxygen. There is basically
1145 just one rule which is an absolute must:
1146
1147 * New functions and classes in the API have to be tagged with
1148 "\since", to make it possible for application programmers to
1149 know when the API was extended -- in case they want to
1150 support a range of older versions of the library, for
1151 instance. Valid parameters to "\since" are:
1152 * Coin x.y - What Coin version it first occurred in.
1153 * TGS Inventor x.y[.z] - What TGS OIV version it first occurred in.
1154 * Inventor x.y[.z] - What SGI OIV version it first occurred in.
1155 * YYYY-MM-DD - What date it was added to Coin. Will be
1156 converted to the correct COIN-x.y for each
1157 Coin release.
1158 Use ',' as a separator if more than one implementation supports
1159 the extension. If an extension is introduced in two branches of
1160 Coin, tag both in cases as (COIN-1.1, COIN-2.1) but only once if
1161 you mean COIN-1.1 and later (e.g. all 2.x releases support the
1162 extension). The z release numbers should normally never be used
1163 as adding features between patchlevel releases would break binary
1164 compatibility, but at least TGS is known to break this "rule".
1165
1166 Other than this, use your common sense and look at the already
1167 existing documentation that is available.
1168
1169 A few hints:
1170
1171 * We never started using the common "JavaDoc"-style way of
1172 forcing tags and documentation on all arguments and return
1173 types with "\param" and "\return" -- so there's no point in
1174 doing that for the functions you write.
1175
1176 * Cross-reference to other functions and / or classes with the
1177 "\sa" ("see also") tag where it seems helpful for the
1178 application programmer. Remember that Doxygen automatically
1179 finds and cross-references class or function names found in
1180 the doc anyway, so don't overuse the "\sa" tag.
1181
1182 * We do not force a third-person vs an imperative style, or
1183 vice versa. Use the same style as "nearby" documentation.
1184
1185 * Make sure *all* important aspects of a class or a function
1186 is documented properly -- _don't_ expect the application
1187 programmer to ever having to resort to the header files or
1188 implementation sourcecode.
1189
1190 * Use "\e" in front of words you want to emphasize, "\c" in
1191 front of words that should be shown in a font appropriate
1192 for code keywords (like "TRUE" or "FALSE") and "\a" in front
1193 of function argument names.
1194
1195 ==============================================================================
1196
1197 Footnotes
1198 =========
1199
1200 [1] "ABI" is short for "Application Binary Interface". The ABI of a
1201 software component of object code (usually a dynamic or static
1202 library) covers any publicly exposed functions, function
1203 signatures, structures (and classes for C++ code). If any
1204 functions has been removed or changed, or if any
1205 structures/classes has been modified in any way, the ABI has most
1206 likely been made incompatible with earlier releases.
1207
1208 What this means for practical purposes is that application
1209 programs (or other client code, like other libraries using the
1210 library in question) must be relinked when ABI compatibility is
1211 broken.
1212
1213 A quick example of why re-building is necessary when the ABI is
1214 made incompatible with the previous version: let's say that a
1215 class has gotten a few new member variables added. This breaks the
1216 ABI in a manner which is neither upwards nor downwards compatible,
1217 as the statement
1218
1219 AClass * anobject = new AClass;
1220
1221 ...in client code will allocate a chunk of memory with the size
1222 sizeof(AClass). Adding member variables will increase
1223 sizeof(AClass) in the /library/ object code, but the compiled
1224 /client code/ will still use the old sizeof(AClass), with the
1225 boundary overwrites and other "interesting" effects that may come
1226 out of it if the client code is not re-compiled.
1227
1228 Documentation on ABI- and API-compatiblity
1229 ------------------------------------------
1230
1231 Matthias Ettrich and Lubos Lunak have published a document called
1232 Binary Compatibility Issues With C++. It deals with the details a
1233 developer should know about when working on APIs and
1234 RPC-Interfaces.
1235
1236 Certain compiler flags may change the ABI of the resulting code
1237 and should be used with care. Such flags are marked with text
1238 indicating compatibility problems in the compiler manuals.
1239
1240 <URL:http://developer.kde.org/documentation/other/binarycompatibility.html>
1241
1242 (It's the "You frequently say that you cannot add this or that
1243 feature because it would break binary compatibility. What does
1244 this mean, really?" question.)
1245
1246
1247
1248 [2] Application Programmer's Interface. This is the functions and data
1249 structures/classes exposed to the application programmer for
1250 interaction with the library.
1251
1252 ==============================================================================