root/branches/mixin-collappse/SConstruct

Revision 633, 34.3 kB (checked in by allenb, 1 year ago)

First step at adding a memory checking mode to OpenSG2.0. The goal here it to make it easier to detect and track down dangling ptr and other types of memory
issues.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1 #!python
2 #
3 # SCons build script for OpenSG
4 import os, string, sys, re, glob, copy, types, traceback, pprint, tempfile, shutil
5 pj = os.path.join
6
7 # If we have wingide, try loading the debugging extenstions
8 try:
9    import wing.wingdbstub
10    print "Loaded wingdb stub for debugging..."
11 except:
12    pass
13
14 # Extend paths for scons-addons and scons-build if needed
15 # - this allows a development version of scons-addons to be
16 #   in the standard python path and used instead.
17 try:
18    import SConsAddons.Util
19    print "Using SConsAddons from: ", os.path.dirname(SConsAddons.Util.__file__)
20 except:
21    sys.path.insert(0,pj('Tools','scons-addons','src'))
22    print "Using SConsAddons from: Tools/scons-addons/src"
23
24 sys.path.insert(0,pj('Tools','scons-build'))
25
26 print "-------------------------------------------------"
27 print "WARNING: The build is currently in development.  "
28 print "            - It needs the svn version of scons-addons"
29 print "WARNING:"
30
31 import SCons.Environment
32 import SCons
33 import SConsAddons.Util as sca_util
34 import SConsAddons.Options as sca_opts
35 import SConsAddons.Variants as sca_variants
36 import SConsAddons.Builders
37 import SConsAddons.Options.Boost
38 import SConsAddons.Options.VTK
39 from SConsAddons.EnvironmentBuilder import EnvironmentBuilder
40 from LibraryUtils import *
41 from sets import Set
42 from socket import gethostname
43
44 import OpenSG.AddOnHacks
45
46 from BuildInfoScanner import BuildInfoScanner
47 from RevisionTagWriter import RevisionTagWriter
48
49 # If we have pysvn, load it
50 try:
51    import pysvn
52    have_pysvn = True
53 except:
54    have_pysvn = False
55
56 # Aliases
57 GetPlatform = sca_util.GetPlatform
58 Export('GetPlatform')
59 verbose_build = False
60
61 # Build TODO
62 # - Support selection of WS/ES
63 # - Support selection of compiler to build with
64 # - QT support
65 # - Contrib libraries
66 # - Library specific defines (if needed)
67 # - Build on windows
68 # - Project files for windows
69
70 # ---------------------------------------------------------------------------- #
71 # ------------------------------ HELPER METHODS ------------------------------ #
72 # ---------------------------------------------------------------------------- #
73
74 # ---------------- #
75 # --- BUILDERS --- #
76 # ---------------- #
77
78 # fcd2code builder
79 # - Custom builder for fcd2code
80 def registerfcd2codeBuilder(env, required=True):
81    print "Setting up fcd2code builder...",
82    
83    fcd2code_cmd = pj("Tools", "fcd2code","fcd2code")
84    fcd2code_cmd = os.path.abspath(fcd2code_cmd)
85    if not os.path.isfile(fcd2code_cmd):
86       print " Warning: fcd2code not found at: ", fcd2code_cmd
87       if required:
88          sys.exit(1)
89       return
90    
91    template_files = glob.glob(pj("Tools","fcd2code","*Template*"))
92    
93    
94    def prop_emitter(target,source,env, template_files=template_files):
95       """ Returns a list of files including all output forms and
96           The input templates as sources.
97       """
98       assert str(source[0]).endswith(".fcd")
99       assert len(source) == 1
100
101       base_name = os.path.splitext(str(source[0]))[0]
102
103       # Targets are all the files that we build
104       target = []
105       for ext in ["Base.cpp","Base.h","Base.inl","Fields.h"]:
106          target.append(base_name+ext)
107      
108       # Sources are the fcd file and all the template files
109       source.extend(template_files)
110
111       return (target, source)
112    
113    
114    fcd2code_builder = Builder(action = " ".join([sys.executable, fcd2code_cmd]) + ' -c -b -d $SOURCE -p ${TARGET.dir}',
115                               src_suffix = '.fcd',
116                               suffix = 'unused.h',
117                               emitter = prop_emitter)
118    env.Append(BUILDERS = {'fcd2code' : fcd2code_builder})
119    print "[OK]"
120
121
122 def addScanParseSkel(common_env):
123    """ This is an ugly hack to add the lex/yacc support into the build.  It is ugly because of a couple of things.
124       - We use some very custom flags
125       - We need to post process the scanner to include a different file then normal.
126       - We are forcing this to be done in the source tree in a subdir without actually going there.
127       - Dependency management seems to be a little messed up right now in the code or scons.
128       - BUGS: Scons does not seem to recognize that the files we are building here are source
129               files for the libraries.  This makes it so we have to run the build twice if the files change.
130               Scons cannot recognize whether the existing files are current or not, if they come out of
131                svn. This can result in spurious regens, which break the code if the wrong versions of
132                flex/bison are present.
133    """
134    # Hack to handle the generation of the parser from .y
135    # This pretty hacky to allow using a version of the file from the repository if yacc is not installed
136    # 1. Call bison: OSGScanParseSkelParser.yy -> OSGScanParseSkelParser.hpp .cpp .output (we don't need the last one)
137    if "yacc" in common_env["TOOLS"]:
138       if common_env["enable_scanparse_regen"]:
139          parser_env = common_env.Copy()
140          parser_env.Append(YACCFLAGS = ["-d","-v","-pOSGScanParseSkel_","-bOSGScanParseSkel_"])
141          source_file = "Source/System/FileIO/ScanParseSkel/OSGScanParseSkelParser.yy"
142          target_file = "Source/System/FileIO/ScanParseSkel/OSGScanParseSkelParser.cpp"
143          yfiles = parser_env.CXXFile(target=target_file,source=source_file)
144          NoClean(yfiles)
145          #print "yfiles: ", yfiles
146
147          # Make sure the parser files have been found for OSGFileIO
148          y_cpp_file = str(yfiles[0]).replace("Source/","",1)
149          y_hpp_file = str(yfiles[1]).replace("Source/","",1)
150          #if not y_cpp_file in lib_map["OSGSystem"].source_files:
151          #   lib_map["OSGSystem"].source_files.append(y_cpp_file)
152          #if not y_hpp_file in lib_map["OSGSystem"].header_files:
153          #   lib_map["OSGSystem"].header_files.append(y_hpp_file)
154          #print " yy source: %s \n header: %s"%(lib_map["OSGSystem"].source_files, lib_map["OSGSystem"].header_files)
155       else:
156          print "WARNING: enable_scanparse_regen disabled. If you change .yy files they will not be rebuilt."
157          common_env["TOOLS"].remove('yacc')
158    else:
159       print "WARNING: bison not available.  If you change .yy files they cannot be rebuilt."
160    
161    # Hack to handle the generation of the scanner from .lpp
162    # This pretty hacky to allow using a version of the file from the repository if lex is not installed
163    # 2. Call flex: OSGScanParseSkelScanner.lpp -> OSGScanParseSkelScanner.cpp (this one needs to be filtered to change the include)
164    if "lex" in common_env["TOOLS"]:
165       def filter_header(target, source, env):
166          """ Custom filter to change the include file for the flexlexer.h"""
167          fname = str(target[0])
168          contents = open(fname).readlines()
169          for i in range(len(contents)):
170             if contents[i] == "#include <FlexLexer.h>\n":
171                contents[i] = "#include \"%s\"\n" % os.path.split(OSG_flexlexer_h)[1]
172                break
173          open(fname,'w').writelines(contents)
174          #print "filter_header: Created ", fname
175
176       if common_env["enable_scanparse_regen"]:
177          lexer_env = common_env.Copy()
178          lexer_env.Append(LEXFLAGS = ["-+","-POSGScanParseSkel_"])
179
180          lexer_dir       = pj('Source','System','FileIO','ScanParseSkel')
181          sys_flexlexer_h = "/usr/include/FlexLexer.h"
182          OSG_flexlexer_h = pj(lexer_dir,"OSGScanParseSkelScanner_FlexLexer.h")
183          source_file     = pj(lexer_dir,"OSGScanParseSkelScanner.ll")
184          target_file     = pj(lexer_dir,"OSGScanParseSkelScanner.cpp")
185
186          # Replace lex builder with new action that calls flex and then filters
187          std_lex_action = Action("$LEXCOM", "$LEXCOMSTR")
188          filter_action = Action(filter_header, lambda t,s,e: "Filtering header: %s %s"%(str(t),str(s)))
189          cxx_file_builder = lexer_env['BUILDERS']['CXXFile']
190          cxx_file_builder.add_action('.ll', Action([std_lex_action, filter_action]))
191          lfiles = lexer_env.CXXFile(target=target_file,source=source_file)
192          NoClean(lfiles)
193          #print "lfiles: ", lfiles
194
195          # If available, copy the system FlexLexer.h file to local source dir
196          if os.path.exists(sys_flexlexer_h):
197             flexlex_cp = lexer_env.Command(OSG_flexlexer_h, sys_flexlexer_h,[Copy('$TARGET','$SOURCE'),])
198             Depends(lfiles, flexlex_cp)
199
200          #Depends(lfiles, "Source/System/FileIO/ScanParseSkel/OSGScanParseSkelParser.hpp") # the scanner includes the token header from the parser...
201          if vars().has_key('yfiles'):
202             Depends(lfiles, yfiles)
203
204          # Strip off "Source/" since this will be in the build dir
205          scanner_src = target_file.replace("Source/","",1)
206          #if not scanner_src in lib_map["OSGSystem"].source_files:
207          #   lib_map["OSGSystem"].source_files.append(scanner_src)
208          #print "FileIO source files: ", lib_map["OSGSystem"].source_files
209       else:
210          print "WARNING: enable_scanparse_regen disabled. If you change .ll files they will not be rebuilt."
211          common_env["TOOLS"].remove('lex')
212    else:
213       print "WARNING: flex not available.  If you change .ll files they cannot be rebuilt."
214
215 # -------------------- #
216 # --- OPTION TYPES --- #
217 # -------------------- #
218
219 class SimpleAppendOption(sca_opts.SimpleOption):
220    """
221    Variant of the simple option wrapper that appends a value to the environment instead
222    of replacing it.
223    """
224    def __init__(self, name, key, help):
225       """
226       Create an option
227       name - the name of the commandline option
228       key - the name of the key in the environment to append to
229       help - Help text about the option object
230       """
231       sca_opts.SimpleOption.__init__(self, name, name, help + " (Use ':' to separate multiple)", \
232                                      None, None, None, None)
233       self.key = key
234
235    """
236    We want these options to be applied before all others, to have them have effect on e.g.
237    StandardPackageOption tests, so override completeProcess instead of apply.
238    """
239    def completeProcess(self, env):
240       if self.value:
241          for i in self.value.split(os.pathsep):
242             exec("env.Append(%s = [i])" % self.key)
243
244 # ---------------------------------------------------------------------------- #
245 # ----------------------------- Main build setup ----------------------------- #
246 # ---------------------------------------------------------------------------- #
247
248 EnsureSConsVersion(0,96,92)
249 SourceSignatures('MD5')
250 #SourceSignatures('timestamp')
251 opensg_version_string = file("VERSION").readline().strip()
252
253 print "Building OpenSG ", opensg_version_string
254
255 # Allow user to pass an options file on the command line, with the
256 # option_file=myOptFile syntax
257
258 platform = sca_util.GetPlatform()
259 unspecified_prefix = "use-instlinks"
260
261
262 # Create base environment to use for option processing
263 if GetPlatform() == "win32":
264    # XXX: Temp hack to get msvs version setting
265    if ARGUMENTS.has_key("MSVS_VERSION"):
266       common_env = Environment(MSVS_VERSION=ARGUMENTS["MSVS_VERSION"],
267                                 tools = ['default', 'doxygen'],
268                                 toolpath = '.')
269    else:
270       common_env = Environment(tools = ['default', 'doxygen'], toolpath = '.')
271 else:
272    if ARGUMENTS.has_key("icc"):
273       use_cxxlib_icc = False
274
275       if ARGUMENTS.has_key("cxxlib-icc"):
276          use_cxxlib_icc = True
277
278       OpenSG.AddOnHacks.apply()
279      
280       common_env = Environment(ENV = os.environ,
281                                tools=['gnulink', 'intelicc', 'intelicpc', 'doxygen'],
282                                cxxlib_icc=use_cxxlib_icc,
283                                toolpath = ['.', 'Tools/scons-build/OpenSG/Tools'])
284    else:
285       common_env = Environment(ENV = os.environ,
286                                toolpath = '.',
287                                tools = ['default', 'doxygen'])
288
289 SConsignFile('.sconsign.'+GetPlatform()+common_env.subst('$CXX'))
290 buildDir = "build." + platform + '.' + common_env.subst('$CXX')
291
292 option_filename = "option.cache." + platform + '.' + common_env.subst('$CXX')
293
294 if ARGUMENTS.has_key("options_file"):
295    opt_file = ARGUMENTS["options_file"]
296    if os.path.exists(opt_file):
297       print "Reading options from: %s" % str(opt_file)
298       option_filename = opt_file
299    else:
300       print "Options file '%s' not found.. will continue with default '%s'" % \
301       (opt_file, option_filename)
302
303
304 # Setup the directories used for sconf processing
305 common_env["CONFIGUREDIR"] = '.sconf_temp_'+platform+'_'+common_env.subst('$CXX')
306 common_env["CONFIGURELOG"] = 'sconf.log_'+platform+'_'+common_env.subst('$CXX')
307 if common_env.has_key("MSVS"):
308    common_env["CONFIGUREDIR"] += "." + common_env["MSVS"]["VERSION"]
309    common_env["CONFIGURELOG"] += "." + common_env["MSVS"]["VERSION"]
310
311 SConsAddons.Builders.registerDefineBuilder(common_env)
312 SConsAddons.Builders.registerSubstBuilder(common_env)
313
314 # Create variant helper and builder
315 variant_helper = sca_variants.VariantsHelper(variantKeys=["type", "arch"])
316 base_bldr = EnvironmentBuilder()
317
318 # ----------------- #
319 # --- CONFIGURE --- #
320 # ----------------- #
321
322 # There is nothing to do ATM - sca_opts.StandardPackageOption can handle
323 # everything so far.
324
325 # --------------- #
326 # --- OPTIONS --- #
327 # --------------- #
328
329 # Options are stored in one of these groups:
330 # - required_libs_options:  Libraries needed to build OpenSG
331 # - optional_libs_options:  Libraries needed for/providing additional functionality
332 # - build_options:          Options to select build/install directories and
333 #                           special build steps.
334 # - feature_options:        Options to enable/disable or tweak certain features
335 #                           of OpenSG.
336 # - misc_options:           Options that do not fit anywhere else.
337 # - extra_libs_options:     Should not be changed - it's only to allow building
338 #                           with additional libraries that are not integrated into
339 #                           the build
340 #
341 # There is special handling for image formats, because some are directly
342 # supported and others require external libs, they may end up in different
343 # option groups, but in the help message they should show up together - see below.
344
345 #
346 # 1) Setup options
347 #    Create Option objects and store them in their group.
348
349 opts = sca_opts.Options(files = [option_filename, 'options.custom'],
350                                    args= ARGUMENTS)
351
352 # Handle library name differences between platforms
353 if "win32" == platform:
354     glut_libname = "glut32"
355     tiff_libname = "tif32"
356     zlib_libname = "zlib"
357     jpeg_libname = "libjpeg"
358     png_libname = "libpng"
359 else:
360     glut_libname = "glut"
361     tiff_libname = "tiff"
362     zlib_libname = "z"
363     jpeg_libname = "jpeg"
364     png_libname = "png"
365
366
367 # Build options - source and destination directories etc.
368 build_options = {}
369 build_options["install_prefix"] = sca_opts.SimpleOption(
370     "prefix", "prefix", "Installation prefix", unspecified_prefix, None, None, None)
371 build_options["build_suffix"] = sca_opts.SimpleOption(
372     "build_suffix", "build_suffix",
373     "Suffix to append to build directory.  Useful for compiling multiple variations on the same platform",
374     "", None, None, None)
375 build_options["enable_fcd2code"] = sca_opts.BoolOption(
376     "enable_fcd2code", "Enable code generation pass (from .fcd files) during build", False)
377 build_options["enable_distcc"] = sca_opts.BoolOption(
378     "enable_distcc", "Enable use of distcc during build. (distcc must be in your path)", False)
379 build_options["enable_unittests"] = sca_opts.BoolOption(
380     "enable_unittests", "Enable building and running of the unit tests after build", True)
381 build_options["enable_revision_tags"] = sca_opts.BoolOption(
382     "enable_revision_tags", "Enable updating of OSG*Def.cpp files with current svn revision numbers", False)
383
384 # Options for required external libraries
385 required_libs_options = {}
386 if "win32" == platform:
387
388     toolset = "auto"
389
390     if common_env.has_key("MSVS"):
391        toolset = 'vc' + common_env["MSVS"]["VERSION"].replace('.', '')
392
393     required_libs_options["boost"] = sca_opts.Boost.Boost(
394         "boost", "1.31.0", libs = ["filesystem"], required = True,
395         useVersion = True, allowLibNameFallbacks=True, toolset = toolset);
396 else:
397     required_libs_options["boost"] = sca_opts.Boost.Boost(
398         "boost", "1.31.0", libs = ["filesystem"], required = True, useVersion = True, allowLibNameFallbacks=True);
399
400 # Options for optional external libraries
401 optional_libs_options = {}
402 optional_libs_options["jpeg"] = sca_opts.StandardPackageOption(
403     "jpeg", "Location of the JPEG library", library = jpeg_libname, required = False)
404
405 optional_libs_options["tiff"] = sca_opts.StandardPackageOption(
406     "tiff", "Location of the TIFF library", library = tiff_libname, required = False)
407
408 optional_libs_options["png"] = sca_opts.StandardPackageOption(
409     "png", "Location of the PNG library", library = png_libname, required = False)
410
411 optional_libs_options["glut"] = sca_opts.StandardPackageOption(
412     "glut", "Location of the GLUT library", library = glut_libname,
413     header = "GL/glut.h", required = False)
414
415 optional_libs_options["freetype"] = sca_opts.StandardPackageOption(
416     "freetype", "Location of freetype2 library", library = "freetype",
417     header = "freetype/config/ftheader.h", required = False)
418
419 if "win32" != platform:
420    optional_libs_options["freetype"].incDir = '/usr/include/freetype2'
421
422 optional_libs_options["fontconfig"] = sca_opts.StandardPackageOption(
423     "fontconfig", "Location of fontconfig library", library = "fontconfig",
424     header = "fontconfig/fontconfig.h", required = False)
425
426 optional_libs_options["zlib"] = sca_opts.StandardPackageOption(
427     "zlib", "Location of the zlib compression library", library = zlib_libname,
428     header = "zlib.h", required = False)
429
430 optional_libs_options["NVPerfSDK"] = sca_opts.StandardPackageOption(
431     "NVPerfSDK", "Location of the NVPerfSDK library", library = "NVPerfSDK",
432     header = "NVPerfSDK.h", required = False)
433
434 optional_libs_options['vtk'] = sca_opts.VTK.VTK(
435    "vtk",
436    "Location of the vtk libraries",
437    required = False,
438    libList = ['vtkRendering',
439               'vtkIO',
440               'vtkGraphics',
441               'vtkImaging',
442               'vtkFiltering',
443               'vtkCommon',
444               'vtkftgl',
445               'vtkDICOMParser',
446               'vtksys',
447               'vtkMPEG2Encode'])
448
449 # Feature options - select library/interface features
450 feature_options = {}
451 feature_options["gif"] = sca_opts.BoolOption(
452     "enable_gif", "Enable GIF support", True)
453
454 feature_options["fcptr_mode"] = sca_opts.EnumOption(
455     "fcptr_mode", "Select the mode for field container pointers",
456     "MT_FCPTR", ["SINGLE_THREAD", "MT_CPTR", "MT_FCPTR"])
457
458 feature_options["disable_deprecated"] = sca_opts.BoolOption(
459     "disable_deprecated", "Disable deprecated interfaces and code", False)
460
461 feature_options["disable_glut_glsubdir"] = sca_opts.BoolOption(
462     "disable_glut_glsubdir", "Do not use GL subdir when including glut.h", False)
463
464 feature_options["enable_osg1_compat"] = sca_opts.BoolOption(
465     "enable_osg1_compat", "Enable OpenSG 1.x compatibility", False)
466
467 feature_options["enable_deprecated_props"] = sca_opts.BoolOption(
468     "enable_deprecated_props", "Enable deprecated property types.", False)
469
470 feature_options["enable_new_osb_io"] = sca_opts.BoolOption(
471     "enable_new_osb_io", "Enable the new OSB IO facilities.", False)
472
473 feature_options["enable_scanparse_regen"] = sca_opts.BoolOption(
474     "enable_scanparse_regen", "Enable regenerating the scanner/parser files using flex and bison", False);
475
476 feature_options["docs_mode"] = sca_opts.EnumOption(
477     "docs_mode", "Select the mode for documentation generation",
478     "NONE", ["NONE", "STANDALONE", "TRAC", "DEVELOPER"])
479
480 feature_options["enable_valgrind_checks"] = sca_opts.BoolOption(
481     "enable_valgrind_checks", "Enable valgrind check code embedded in OpenSG.", False)
482
483 feature_options["enable_memory_debugging"] = sca_opts.BoolOption(
484     "enable_memory_debugging", "Enable memory debugging checks in OpenSG.", False)
485
486 if "win32" == platform:
487     feature_options["enable_win_localstorage"] = sca_opts.BoolOption(
488         "enable_win_localstorage", "Enable use of local storage instead of __declspec to "+
489         "get thread local storage on windows", True)
490
491 if "win32" != platform:
492     feature_options["enable_elf_localstorage"] = sca_opts.BoolOption(
493         "enable_elf_localstorage", "Enable use of elf thread local storage with pthreads",
494         ("linux" == platform))
495
496 # Misc options
497 misc_options = {}
498 #misc_options["icc_compat"] = sca_opts.SimpleOption(
499 #    "icc_gnu_compat", "icc_gnu_compat", "<GCC Version> Make the binaries built " +
500 #                      "with icc compatible with the given verion of gcc. (unsupported)",
501 #                      "", None, None, None)
502
503 # Options to specify additional library/header search paths and librarys to
504 # link agains.
505 extra_libs_options = {}
506 extra_libs_options["incdir"] = SimpleAppendOption('add_incdir', 'CPPPATH', 'Additional include dir')
507 extra_libs_options["libdir"] = SimpleAppendOption('add_libdir', 'LIBPATH', 'Additional library dir')
508 extra_libs_options["lib"]    = SimpleAppendOption('add_lib',    'LIBS',    'Additional library')
509
510 # Group all image format options together.
511 image_format_options = {}
512 image_format_options["jpeg"] = optional_libs_options["jpeg"]
513 image_format_options["tiff"] = optional_libs_options["tiff"]
514 image_format_options["png"]  = optional_libs_options["png"]
515 image_format_options["gif"]  = feature_options["gif"]
516
517 #
518 # 2) Register options
519 #    This should not require any changes unless a new option group is added.
520
521 for opt in extra_libs_options.itervalues():
522     if opt not in image_format_options.itervalues():
523         opts.AddOption(opt)
524
525 opts.AddOption(sca_opts.SeparatorOption("\nBuild/Install settings"))
526 for opt in build_options.itervalues():
527     if opt not in image_format_options.itervalues():
528         opts.AddOption(opt)
529
530 opts.AddOption(sca_opts.SeparatorOption("\nPackage settings (required libs)"))
531 for opt in required_libs_options.itervalues():
532     if opt not in image_format_options.itervalues():
533         opts.AddOption(opt)
534
535 opts.AddOption(sca_opts.SeparatorOption("\nPackage settings (optional libs)"))
536 for opt in optional_libs_options.itervalues():
537     if opt not in image_format_options.itervalues():
538         opts.AddOption(opt)
539
540 for opt in image_format_options.itervalues():
541     opts.AddOption(opt)
542
543
544 opts.AddOption(sca_opts.SeparatorOption("\nAdvanced options"))
545 for opt in feature_options.itervalues():
546     if opt not in image_format_options.itervalues():
547         opts.AddOption(opt)
548
549 for opt in misc_options.itervalues():
550     if opt not in image_format_options.itervalues():
551         opts.AddOption(opt)
552
553 # Add environment builder options
554 base_bldr.addOptions(opts)
555
556 # Add variant building options
557 variant_helper.addOptions(opts)
558
559 #
560 # 3) Process options
561
562 try:
563    opts.Process(common_env)
564 except Exception, ex:
565    if not SConsAddons.Util.hasHelpFlag():
566       print "Option error: ", str(ex)
567       traceback.print_exc()
568       sys.exit(1)
569
570 #
571 # 4) Generate help message
572
573 help_text = \
574 """--- OpenSG Build system ---
575 %s
576 Targets:
577    install - Install OpenSG
578       ex: 'scons install prefix=$HOME/software' to install in your account
579    Type 'scons' to just build it
580
581 """ % (opts.GenerateHelpText(common_env),)
582
583 Help(help_text)
584
585 # --------------------------------------------------------------------------- #
586 # ---------------------------- MAIN BUILD STEPS ----------------------------- #
587 # --------------------------------------------------------------------------- #
588
589 # If we are running the build
590 if not SConsAddons.Util.hasHelpFlag():
591    try:                                   # Try to save the options if possible
592       if not ARGUMENTS.has_key("options_file"):
593          opts.Save(option_filename, common_env)
594    except LookupError, le:
595       pass
596    
597    if common_env.has_key("MSVS"):
598       import pprint
599       print "Found MSVS. using version: ", common_env["MSVS"]["VERSION"]
600       pprint.pprint(common_env["MSVS"])
601
602    # Update settings
603    if common_env.has_key("MSVS"):
604       buildDir += "." + common_env["MSVS"]["VERSION"]
605    if common_env["build_suffix"] != "":
606       buildDir += "." + common_env["build_suffix"]
607      
608    # .fcd processing
609    if common_env["enable_fcd2code"]:
610       registerfcd2codeBuilder(common_env)
611      
612       fcd_files = []
613       for root, dirs, files in os.walk(pj(os.getcwd(),'Source')):
614          fcd_files += [pj(root,f) for f in files if f.endswith(".fcd")]
615      
616       for f in fcd_files:
617          fcd_targets = common_env.fcd2code(source=f)
618          NoClean(fcd_targets)
619    
620    # Distcc enable
621    if common_env["enable_distcc"] and WhereIs("distcc"):
622       common_env.Prepend(CXX = "distcc ", CC = "distcc ")
623    
624    # Trigger recursive scanning of library directorties
625    if not verbose_build:
626       print "Scanning libraries: ",
627    biScanner = BuildInfoScanner("Source", opts, common_env,
628                                 [".svn", "ES", "EGL"], verbose_build)
629    lib_map   = biScanner.scan()
630    if not verbose_build:
631       print "  found %s libraries" % len(lib_map)
632    
633    # Add lexer to the build
634    addScanParseSkel(common_env)     
635      
636    # -- Common builder settings
637    variant_helper.readOptions(common_env)
638    base_bldr.readOptions(common_env)
639    #base_bldr.enableWarnings()
640    base_bldr.enableWarnings(EnvironmentBuilder.MINIMAL)
641    
642    # Apply any common package options
643    # Update environment for boost options
644    required_libs_options["boost"].apply(common_env)
645      
646    # If defaulting to instlinks prefix:
647    #  - Use symlinks
648    #  - Manually set the used prefix to the instlinks of the build dir
649    if common_env['prefix'] == unspecified_prefix:
650       if hasattr(os,'symlink'):
651          common_env['INSTALL'] = SConsAddons.Util.symlinkInstallFunc
652       common_env['prefix'] = pj( Dir('.').get_abspath(), buildDir, 'instlinks')
653    
654    # --- Setup installation paths --- #
655    paths = {}
656    paths['base']      = os.path.abspath(common_env['prefix'])
657    paths['lib']       = pj(paths['base'], 'lib')
658    paths['include']   = pj(paths['base'], 'include')
659    paths['bin']       = pj(paths['base'], 'bin')
660    print "Using prefix: ", paths['base']
661    common_env.Append(CPPPATH = [paths['include'],pj(paths['include'],"OpenSG")])
662
663    if not common_env.has_key("icc_gnu_compat"):
664       common_env["icc_gnu_compat"] = False
665    
666    # ---- Generate OSGConfigured.h --- #
667    definemap = {"OSG_DISABLE_DEPRECATED"   : (common_env["disable_deprecated"],
668                                               "Disable interface that will go away in the future"),
669                 "OSG_NO_GLUT_GLSUBDIR"     : (common_env["disable_glut_glsubdir"],
670                                               "Don't use GL subdir for glut"),
671                 "OSG_MT_FIELDCONTAINERPTR" : ("MT_FCPTR" == common_env["fcptr_mode"]),
672                 "OSG_MT_CPTR_ASPECT"       : ("MT_CPTR" == common_env["fcptr_mode"]),
673                 "OSG_1_COMPAT"             : common_env["enable_osg1_compat"],
674                 "OSG_DEPRECATED_PROPS"     : common_env["enable_deprecated_props"],
675                 "OSG_NEW_OSB_IO"           : common_env["enable_new_osb_io"],
676                 "OSG_ICC_GNU_COMPAT"       : common_env["icc_gnu_compat"],
677                 "OSG_ENABLE_VALGRIND_CHECKS" : common_env["enable_valgrind_checks"],
678                 "OSG_ENABLE_MEMORY_DEBUGGING" : common_env["enable_memory_debugging"],
679                
680                 "OSG_WITH_JPG"       : image_format_options["jpeg"].isAvailable(),
681                 "OSG_WITH_TIF"       : image_format_options["tiff"].isAvailable(),
682                 "OSG_WITH_PNG"       : image_format_options["png"].isAvailable(),
683                 "OSG_WITH_GIF"       : image_format_options["gif"].getValue(),
684                 "OSG_WITH_GLUT"      : optional_libs_options["glut"].isAvailable(),
685                 "OSG_WITH_ZLIB"      : optional_libs_options["zlib"].isAvailable(),
686                 "OSG_WITH_NVPERFSDK" : optional_libs_options["NVPerfSDK"].isAvailable(),
687                 "OSG_WITH_VTK"       : optional_libs_options["vtk"].isAvailable(),
688                }
689    if "win32" == platform:   # Win32 specific defines
690       definemap.update(
691          {"OSG_WIN32_ASPECT_USE_LOCALSTORAGE" : (common_env["enable_win_localstorage"],
692                                                  "Enable use of local storage instead of __declspec."),} )
693    else:
694       definemap.update(
695          {"OSG_PTHREAD_ELF_TLS" : (common_env["enable_elf_localstorage"], "Use elf tls with pthreads."),
696           "OSG_WITH_FT2"        : optional_libs_options["freetype"].isAvailable(),
697           "OSG_WITH_FONTCONFIG" : optional_libs_options["fontconfig"].isAvailable()
698          } )
699
700    if "darwin" == platform:
701       definemap.update( {"OSG_WITH_GLUT" : True,} )
702    
703    common_env.DefineBuilder(pj(paths["include"], "OpenSG", "OSGConfigured.h"),
704                             Value(definemap), definemap=definemap)
705
706    if "win32" == platform:
707        common_env.Append(LINKFLAGS = SCons.Util.CLVar('/nodefaultlib'))
708
709    #common_env.Append(CXXFLAGS = "-H") # Use this for pch script generation
710   
711    # Unit Testing framework
712    # - Build the framework
713    if common_env["enable_unittests"]:
714       # Until they have the SConstruct in their svn, let's just copy it over
715       SConscript(pj("Tools", "unittest-cpp.SConstruct"))
716      
717       # set the needed vars
718       unittest_inc     = pj(os.getcwd(), "Tools", "unittest-cpp", "UnitTest++", "src")
719       unittest_libpath = pj(os.getcwd(), "Tools", "unittest-cpp", "UnitTest++")
720       unittest_lib     = "UnitTest++"
721       unittest_runner  = pj(os.getcwd(), "Tools", "UnitTestRunner.cpp")
722       Export('unittest_inc', 'unittest_lib', 'unittest_libpath', 'unittest_runner')
723    
724