-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathbuild_usd.py
2876 lines (2438 loc) · 119 KB
/
build_usd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright 2017 Pixar
#
# Licensed under the terms set forth in the LICENSE.txt file available at
# https://openusd.org/license.
#
# Check whether this script is being run under Python 2 first. Otherwise,
# any Python 3-only code below will cause the script to fail with an
# unhelpful error message.
import sys
if sys.version_info.major == 2:
sys.exit("ERROR: USD does not support Python 2. Use a supported version "
"of Python 3 instead.")
import argparse
import codecs
import contextlib
import ctypes
import datetime
import fnmatch
import glob
import hashlib
import locale
import multiprocessing
import os
import platform
import re
import shlex
import shutil
import subprocess
import sys
import sysconfig
import zipfile
from urllib.request import urlopen
from shutil import which
# Helpers for printing output
verbosity = 1
def Print(msg):
if verbosity > 0:
print(msg)
def PrintWarning(warning):
if verbosity > 0:
print("WARNING:", warning)
def PrintStatus(status):
if verbosity >= 1:
print("STATUS:", status)
def PrintInfo(info):
if verbosity >= 2:
print("INFO:", info)
def PrintCommandOutput(output):
if verbosity >= 3:
sys.stdout.write(output)
def PrintError(error):
if verbosity >= 3 and sys.exc_info()[1] is not None:
import traceback
traceback.print_exc()
print ("ERROR:", error)
# Helpers for determining platform
def Windows():
return platform.system() == "Windows"
def Linux():
return platform.system() == "Linux"
def MacOS():
return platform.system() == "Darwin"
if MacOS():
import apple_utils
def MacOSTargetEmbedded(context):
return MacOS() and apple_utils.TargetEmbeddedOS(context)
def GetLocale():
if Windows():
# Windows handles encoding a little differently then Linux / Mac
# For interactive streams (isatty() == True) it will use the
# console codepage, otherwise it will return an ANSI codepage.
# To keep things consistent we'll force UTF-8 for non-interactive
# streams (which is recommended by Microsoft). See:
# https://docs.python.org/3.6/library/sys.html#sys.stdout
# https://docs.microsoft.com/en-us/windows/win32/intl/code-page-identifiers
if sys.stdout.isatty():
return sys.stdout.encoding
else:
return "UTF-8"
return sys.stdout.encoding or locale.getdefaultlocale()[1] or "UTF-8"
def GetCommandOutput(command):
"""Executes the specified command and returns output or None."""
try:
return subprocess.check_output(
shlex.split(command),
stderr=subprocess.STDOUT).decode(GetLocale(), 'replace').strip()
except subprocess.CalledProcessError:
pass
return None
def GetXcodeDeveloperDirectory():
"""Returns the active developer directory as reported by 'xcode-select -p'.
Returns None if none is set."""
if not MacOS():
return None
return GetCommandOutput("xcode-select -p")
def GetVisualStudioCompilerAndVersion():
"""Returns a tuple containing the path to the Visual Studio compiler
and a tuple for its version, e.g. (14, 0). If the compiler is not found
or version number cannot be determined, returns None."""
if not Windows():
return None
msvcCompiler = which('cl')
if msvcCompiler:
# VCToolsVersion environment variable should be set by the
# Visual Studio Command Prompt.
match = re.search(
r"(\d+)\.(\d+)",
os.environ.get("VCToolsVersion", ""))
if match:
return (msvcCompiler, tuple(int(v) for v in match.groups()))
return None
def IsVisualStudioVersionOrGreater(desiredVersion):
if not Windows():
return False
msvcCompilerAndVersion = GetVisualStudioCompilerAndVersion()
if msvcCompilerAndVersion:
_, version = msvcCompilerAndVersion
return version >= desiredVersion
return False
# Helpers to determine the version of "Visual Studio" (also support the Build Tools) based
# on the version of the MSVC compiler.
# See MSVC++ versions table on https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B
def IsVisualStudio2022OrGreater():
VISUAL_STUDIO_2022_VERSION = (14, 30)
return IsVisualStudioVersionOrGreater(VISUAL_STUDIO_2022_VERSION)
def IsVisualStudio2019OrGreater():
VISUAL_STUDIO_2019_VERSION = (14, 20)
return IsVisualStudioVersionOrGreater(VISUAL_STUDIO_2019_VERSION)
def IsVisualStudio2017OrGreater():
VISUAL_STUDIO_2017_VERSION = (14, 1)
return IsVisualStudioVersionOrGreater(VISUAL_STUDIO_2017_VERSION)
def GetPythonInfo(context):
"""Returns a tuple containing the path to the Python executable, shared
library, and include directory corresponding to the version of Python
currently running. Returns None if any path could not be determined.
This function is used to extract build information from the Python
interpreter used to launch this script. This information is used
in the Boost and USD builds. By taking this approach we can support
having USD builds for different Python versions built on the same
machine. This is very useful, especially when developers have multiple
versions installed on their machine.
"""
# If we were given build python info then just use it.
if context.build_python_info:
return (context.build_python_info['PYTHON_EXECUTABLE'],
context.build_python_info['PYTHON_LIBRARY'],
context.build_python_info['PYTHON_INCLUDE_DIR'],
context.build_python_info['PYTHON_VERSION'])
# First we extract the information that can be uniformly dealt with across
# the platforms:
pythonExecPath = sys.executable
pythonVersion = sysconfig.get_config_var("py_version_short") # "3.7"
# Lib path is unfortunately special for each platform and there is no
# config_var for it. But we can deduce it for each platform, and this
# logic works for any Python version.
def _GetPythonLibraryFilename(context):
if Windows():
return "python{version}{suffix}.lib".format(
version=sysconfig.get_config_var("py_version_nodot"),
suffix=('_d' if context.buildDebug and context.debugPython
else ''))
elif Linux():
return sysconfig.get_config_var("LDLIBRARY")
elif MacOS():
return "libpython{version}.dylib".format(
version=(sysconfig.get_config_var('LDVERSION') or
sysconfig.get_config_var('VERSION') or
pythonVersion))
else:
raise RuntimeError("Platform not supported")
pythonIncludeDir = sysconfig.get_path("include")
if not pythonIncludeDir or not os.path.isdir(pythonIncludeDir):
# as a backup, and for legacy reasons - not preferred because
# it may be baked at build time
pythonIncludeDir = sysconfig.get_config_var("INCLUDEPY")
# if in a venv, installed_base will be the "original" python,
# which is where the libs are ("base" will be the venv dir)
pythonBaseDir = sysconfig.get_config_var("installed_base")
if Windows():
pythonLibPath = os.path.join(pythonBaseDir, "libs",
_GetPythonLibraryFilename(context))
elif Linux():
pythonMultiarchSubdir = sysconfig.get_config_var("multiarchsubdir")
# Try multiple ways to get the python lib dir
for pythonLibDir in (sysconfig.get_config_var("LIBDIR"),
os.path.join(pythonBaseDir, "lib")):
if pythonMultiarchSubdir:
pythonLibPath = \
os.path.join(pythonLibDir + pythonMultiarchSubdir,
_GetPythonLibraryFilename(context))
if os.path.isfile(pythonLibPath):
break
pythonLibPath = os.path.join(pythonLibDir,
_GetPythonLibraryFilename(context))
if os.path.isfile(pythonLibPath):
break
elif MacOS():
pythonLibPath = os.path.join(pythonBaseDir, "lib",
_GetPythonLibraryFilename(context))
else:
raise RuntimeError("Platform not supported")
return (pythonExecPath, pythonLibPath, pythonIncludeDir, pythonVersion)
def GetCPUCount():
try:
return multiprocessing.cpu_count()
except NotImplementedError:
return 1
def Run(cmd, logCommandOutput = True, env = None):
"""Run the specified command in a subprocess."""
PrintInfo('Running "{cmd}"'.format(cmd=cmd))
with codecs.open("log.txt", "a", "utf-8") as logfile:
logfile.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
logfile.write("\n")
logfile.write(cmd)
logfile.write("\n")
# Let exceptions escape from subprocess calls -- higher level
# code will handle them.
if logCommandOutput:
p = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, env=env)
while True:
l = p.stdout.readline().decode(GetLocale(), 'replace')
if l:
logfile.write(l)
PrintCommandOutput(l)
elif p.poll() is not None:
break
else:
p = subprocess.Popen(shlex.split(cmd), env=env)
p.wait()
if p.returncode != 0:
# If verbosity >= 3, we'll have already been printing out command output
# so no reason to print the log file again.
if verbosity < 3:
with open("log.txt", "r") as logfile:
Print(logfile.read())
raise RuntimeError("Failed to run '{cmd}' in {path}.\nSee {log} for more details."
.format(cmd=cmd, path=os.getcwd(), log=os.path.abspath("log.txt")))
@contextlib.contextmanager
def CurrentWorkingDirectory(dir):
"""Context manager that sets the current working directory to the given
directory and resets it to the original directory when closed."""
curdir = os.getcwd()
os.chdir(dir)
try: yield
finally: os.chdir(curdir)
def CopyFiles(context, src, dest):
"""Copy files like shutil.copy, but src may be a glob pattern."""
filesToCopy = glob.glob(src)
if not filesToCopy:
raise RuntimeError("File(s) to copy {src} not found".format(src=src))
instDestDir = os.path.join(context.instDir, dest)
if not os.path.isdir(instDestDir):
try:
os.mkdir(instDestDir)
except Exception as e:
raise RuntimeError(
"Unable to create {destDir}".format(destDir=instDestDir)) from e
for f in filesToCopy:
PrintCommandOutput("Copying {file} to {destDir}\n"
.format(file=f, destDir=instDestDir))
shutil.copy(f, instDestDir)
def CopyDirectory(context, srcDir, destDir):
"""Copy directory like shutil.copytree."""
instDestDir = os.path.join(context.instDir, destDir)
if os.path.isdir(instDestDir):
shutil.rmtree(instDestDir)
PrintCommandOutput("Copying {srcDir} to {destDir}\n"
.format(srcDir=srcDir, destDir=instDestDir))
shutil.copytree(srcDir, instDestDir)
def AppendCXX11ABIArg(buildFlag, context, buildArgs):
"""Append a build argument that defines _GLIBCXX_USE_CXX11_ABI
based on the settings in the context. This may either do nothing
or append an entry to buildArgs like:
<buildFlag>="-D_GLIBCXX_USE_CXX11_ABI={0, 1}"
If buildArgs contains settings for buildFlag, those settings will
be merged with the above define."""
if context.useCXX11ABI is None:
return
cxxFlags = ["-D_GLIBCXX_USE_CXX11_ABI={}".format(context.useCXX11ABI)]
# buildArgs might look like:
# ["-DFOO=1", "-DBAR=2", ...] or ["-DFOO=1 -DBAR=2 ...", ...]
#
# See if any of the arguments in buildArgs start with the given
# buildFlag. If so, we want to take whatever that buildFlag has
# been set to and merge it in with the cxxFlags above.
#
# For example, if buildArgs = ['-DCMAKE_CXX_FLAGS="-w"', ...]
# we want to add "-w" to cxxFlags.
splitArgs = [shlex.split(a) for a in buildArgs]
for p in [item for arg in splitArgs for item in arg]:
if p.startswith(buildFlag):
(_, _, flags) = p.partition("=")
cxxFlags.append(flags)
buildArgs.append('{flag}="{flags}"'.format(
flag=buildFlag, flags=" ".join(cxxFlags)))
def FormatMultiProcs(numJobs, generator):
tag = "-j"
if generator:
if "Visual Studio" in generator:
tag = "/M:" # This will build multiple projects at once.
elif "Xcode" in generator:
tag = "-j "
return "{tag}{procs}".format(tag=tag, procs=numJobs)
def RunCMake(context, force, extraArgs = None):
"""Invoke CMake to configure, build, and install a library whose
source code is located in the current working directory."""
# Create a directory for out-of-source builds in the build directory
# using the name of the current working directory.
if extraArgs is None:
extraArgs = []
else:
# ensure we can freely modify our extraArgs without affecting caller
extraArgs = list(extraArgs)
if context.cmakeBuildArgs:
extraArgs.insert(0, context.cmakeBuildArgs)
srcDir = os.getcwd()
instDir = (context.usdInstDir if srcDir == context.usdSrcDir
else context.instDir)
buildDir = os.path.join(context.buildDir, os.path.split(srcDir)[1])
if force and os.path.isdir(buildDir):
shutil.rmtree(buildDir)
if not os.path.isdir(buildDir):
os.makedirs(buildDir)
generator = context.cmakeGenerator
# On Windows, we need to explicitly specify the generator to ensure we're
# building a 64-bit project. (Surely there is a better way to do this?)
# TODO: figure out exactly what "vcvarsall.bat x64" sets to force x64
if generator is None and Windows():
if IsVisualStudio2022OrGreater():
generator = "Visual Studio 17 2022"
elif IsVisualStudio2019OrGreater():
generator = "Visual Studio 16 2019"
elif IsVisualStudio2017OrGreater():
generator = "Visual Studio 15 2017 Win64"
if generator is not None:
generator = '-G "{gen}"'.format(gen=generator)
# Note - don't want to add -A (architecture flag) if generator is, ie, Ninja
if IsVisualStudio2019OrGreater() and "Visual Studio" in generator:
generator = generator + " -A x64"
toolset = context.cmakeToolset
if toolset is not None:
toolset = '-T "{toolset}"'.format(toolset=toolset)
# On MacOS, enable the use of @rpath for relocatable builds.
osx_rpath = None
if MacOS():
osx_rpath = "-DCMAKE_MACOSX_RPATH=ON"
# For macOS cross compilation, set the Xcode architecture flags.
targetArch = apple_utils.GetTargetArch(context)
if context.targetNative or targetArch == apple_utils.GetHostArch():
extraArgs.append('-DCMAKE_XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH=YES')
else:
extraArgs.append('-DCMAKE_XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH=NO')
extraArgs.append('-DCMAKE_OSX_ARCHITECTURES={0}'.format(targetArch))
extraArgs = apple_utils.ConfigureCMakeExtraArgs(context, extraArgs)
if context.ignorePaths:
ignoredPaths = ";".join(context.ignorePaths)
extraArgs.append("-DCMAKE_IGNORE_PATH={0}".format(ignoredPaths))
extraArgs.append("-DCMAKE_IGNORE_PREFIX_PATH={0}".format(ignoredPaths))
# We use -DCMAKE_BUILD_TYPE for single-configuration generators
# (Ninja, make), and --config for multi-configuration generators
# (Visual Studio); technically we don't need BOTH at the same
# time, but specifying both is simpler than branching
config = "Release"
if context.buildDebug:
config = "Debug"
elif context.buildRelease:
config = "Release"
elif context.buildRelWithDebug:
config = "RelWithDebInfo"
# Append extra argument controlling libstdc++ ABI if specified.
AppendCXX11ABIArg("-DCMAKE_CXX_FLAGS", context, extraArgs)
with CurrentWorkingDirectory(buildDir):
Run('cmake '
'-DCMAKE_INSTALL_PREFIX="{instDir}" '
'-DCMAKE_PREFIX_PATH="{depsInstDir}" '
'-DCMAKE_BUILD_TYPE={config} '
'{osx_rpath} '
'{generator} '
'{toolset} '
'{extraArgs} '
'"{srcDir}"'
.format(instDir=instDir,
depsInstDir=context.instDir,
config=config,
srcDir=srcDir,
osx_rpath=(osx_rpath or ""),
generator=(generator or ""),
toolset=(toolset or ""),
extraArgs=(" ".join(extraArgs) if extraArgs else "")))
Run("cmake --build . --config {config} --target install -- {multiproc}"
.format(config=config,
multiproc=FormatMultiProcs(context.numJobs, generator)))
def GetCMakeVersion():
"""
Returns the CMake version as tuple of integers (major, minor) or
(major, minor, patch) or None if an error occured while launching cmake and
parsing its output.
"""
output_string = GetCommandOutput("cmake --version")
if not output_string:
PrintWarning("Could not determine cmake version -- please install it "
"and adjust your PATH")
return None
# cmake reports, e.g., "... version 3.14.3"
match = re.search(r"version (\d+)\.(\d+)(\.(\d+))?", output_string)
if not match:
PrintWarning("Could not determine cmake version")
return None
major, minor, patch_group, patch = match.groups()
if patch_group is None:
return (int(major), int(minor))
else:
return (int(major), int(minor), int(patch))
def ComputeSHA256Hash(filename):
"""Returns the SHA256 hash of the specified file."""
hasher = hashlib.sha256()
with open(filename, "rb") as f:
buf = None
while buf != b'':
buf = f.read(4096)
hasher.update(buf)
return hasher.hexdigest()
def PatchFile(filename, patches, multiLineMatches=False):
"""Applies patches to the specified file. patches is a list of tuples
(old string, new string)."""
if multiLineMatches:
oldLines = [open(filename, 'r').read()]
else:
oldLines = open(filename, 'r').readlines()
newLines = oldLines
for (oldString, newString) in patches:
newLines = [s.replace(oldString, newString) for s in newLines]
if newLines != oldLines:
PrintInfo("Patching file {filename} (original in {oldFilename})..."
.format(filename=filename, oldFilename=filename + ".old"))
shutil.copy(filename, filename + ".old")
open(filename, 'w').writelines(newLines)
def DownloadFileWithCurl(url, outputFilename):
# Don't log command output so that curl's progress
# meter doesn't get written to the log file.
Run("curl {progress} -L -o {filename} {url}".format(
progress="-#" if verbosity >= 2 else "-s",
filename=outputFilename, url=url),
logCommandOutput=False)
def DownloadFileWithPowershell(url, outputFilename):
# It's important that we specify to use TLS v1.2 at least or some
# of the downloads will fail.
cmd = "powershell [Net.ServicePointManager]::SecurityProtocol = \
[Net.SecurityProtocolType]::Tls12; \"(new-object \
System.Net.WebClient).DownloadFile('{url}', '{filename}')\""\
.format(filename=outputFilename, url=url)
Run(cmd,logCommandOutput=False)
def DownloadFileWithUrllib(url, outputFilename):
r = urlopen(url)
with open(outputFilename, "wb") as outfile:
outfile.write(r.read())
def DownloadURL(url, context, force, extractDir = None,
dontExtract = None, destFileName = None,
expectedSHA256 = None):
"""Download and extract the archive file at given URL to the
source directory specified in the context.
dontExtract may be a sequence of path prefixes that will
be excluded when extracting the archive.
destFileName may be a string containing the filename where
the file will be downloaded. If unspecified, this filename
will be derived from the URL.
expectedSHA256 may be a string containing the expected SHA256
checksum for the downloaded file. If provided, this function
will raise a RuntimeError if the SHA256 checksum computed from
the file does not match.
Returns the absolute path to the directory where files have
been extracted."""
with CurrentWorkingDirectory(context.srcDir):
if destFileName:
filename = destFileName
else:
filename = url.split("/")[-1]
if force and os.path.exists(filename):
os.remove(filename)
if os.path.exists(filename):
PrintInfo("{0} already exists, skipping download"
.format(os.path.abspath(filename)))
else:
PrintInfo("Downloading {0} to {1}"
.format(url, os.path.abspath(filename)))
# To work around occasional hiccups with downloading from websites
# (SSL validation errors, etc.), retry a few times if we don't
# succeed in downloading the file.
maxRetries = 5
lastError = None
# Download to a temporary file and rename it to the expected
# filename when complete. This ensures that incomplete downloads
# will be retried if the script is run again.
tmpFilename = filename + ".tmp"
if os.path.exists(tmpFilename):
os.remove(tmpFilename)
for i in range(maxRetries):
try:
context.downloader(url, tmpFilename)
break
except Exception as e:
PrintCommandOutput("Retrying download due to error: {err}\n"
.format(err=e))
lastError = e
else:
errorMsg = str(lastError)
if "SSL: TLSV1_ALERT_PROTOCOL_VERSION" in errorMsg:
errorMsg += ("\n\n"
"Your OS or version of Python may not support "
"TLS v1.2+, which is required for downloading "
"files from certain websites. This support "
"was added in Python 2.7.9."
"\n\n"
"You can use curl to download dependencies "
"by installing it in your PATH and re-running "
"this script.")
raise RuntimeError("Failed to download {url}: {err}"
.format(url=url, err=errorMsg))
if expectedSHA256:
computedSHA256 = ComputeSHA256Hash(tmpFilename)
if computedSHA256 != expectedSHA256:
raise RuntimeError(
"Unexpected SHA256 for {url}: got {computed}, "
"expected {expected}".format(
url=url, computed=computedSHA256,
expected=expectedSHA256))
shutil.move(tmpFilename, filename)
# Open the archive and retrieve the name of the top-most directory.
# This assumes the archive contains a single directory with all
# of the contents beneath it, unless a specific extractDir is specified,
# which is to be used.
archive = None
rootDir = None
members = None
try:
if zipfile.is_zipfile(filename):
archive = zipfile.ZipFile(filename)
if extractDir:
rootDir = extractDir
else:
rootDir = archive.namelist()[0].split('/')[0]
if dontExtract != None:
members = (m for m in archive.namelist()
if not any((fnmatch.fnmatch(m, p)
for p in dontExtract)))
else:
raise RuntimeError("unrecognized archive file type")
with archive:
extractedPath = os.path.abspath(rootDir)
if force and os.path.isdir(extractedPath):
shutil.rmtree(extractedPath)
if os.path.isdir(extractedPath):
PrintInfo("Directory {0} already exists, skipping extract"
.format(extractedPath))
else:
PrintInfo("Extracting archive to {0}".format(extractedPath))
# Extract to a temporary directory then move the contents
# to the expected location when complete. This ensures that
# incomplete extracts will be retried if the script is run
# again.
tmpExtractedPath = os.path.abspath("extract_dir")
if os.path.isdir(tmpExtractedPath):
shutil.rmtree(tmpExtractedPath)
archive.extractall(tmpExtractedPath, members=members)
shutil.move(os.path.join(tmpExtractedPath, rootDir),
extractedPath)
shutil.rmtree(tmpExtractedPath)
return extractedPath
except Exception as e:
# If extraction failed for whatever reason, assume the
# archive file was bad and move it aside so that re-running
# the script will try downloading and extracting again.
shutil.move(filename, filename + ".bad")
raise RuntimeError("Failed to extract archive {filename}: {err}"
.format(filename=filename, err=e))
############################################################
# 3rd-Party Dependencies
AllDependencies = list()
AllDependenciesByName = dict()
class Dependency(object):
def __init__(self, name, installer, *files):
self.name = name
self.installer = installer
self.filesToCheck = files
AllDependencies.append(self)
AllDependenciesByName.setdefault(name.lower(), self)
def Exists(self, context):
return any([os.path.isfile(os.path.join(context.instDir, f))
for f in self.filesToCheck])
class PythonDependency(object):
def __init__(self, name, getInstructions, moduleNames):
self.name = name
self.getInstructions = getInstructions
self.moduleNames = moduleNames
def Exists(self, context):
# If one of the modules in our list imports successfully, we are good.
for moduleName in self.moduleNames:
try:
pyModule = __import__(moduleName)
return True
except:
pass
return False
def AnyPythonDependencies(deps):
return any([type(d) is PythonDependency for d in deps])
############################################################
# zlib
ZLIB_URL = "https://github.com/madler/zlib/archive/v1.2.13.zip"
def InstallZlib(context, force, buildArgs):
with CurrentWorkingDirectory(DownloadURL(ZLIB_URL, context, force)):
# The following test files aren't portable to embedded platforms.
# They're not required for use on any platforms, so we elide them
# for efficiency
PatchFile("CMakeLists.txt",
[("add_executable(example test/example.c)",
""),
("add_executable(minigzip test/minigzip.c)",
""),
("target_link_libraries(example zlib)",
""),
("target_link_libraries(minigzip zlib)",
""),
("add_test(example example)",
"")])
RunCMake(context, force, buildArgs)
ZLIB = Dependency("zlib", InstallZlib, "include/zlib.h")
############################################################
# boost
# The default installation of boost on Windows puts headers in a versioned
# subdirectory, which we have to account for here. Specifying "layout=system"
# would cause the Windows header install to match Linux/MacOS, but the
# "layout=system" flag also changes the naming of the boost dlls in a
# manner that causes problems for dependent libraries that rely on boost's
# trick of automatically linking the boost libraries via pragmas in boost's
# standard include files. Dependencies that use boost's pragma linking
# facility in general don't have enough configuration switches to also coerce
# the naming of the dlls and so it is best to rely on boost's most default
# settings for maximum compatibility.
#
# It's tricky to determine which version of boost we'll be using at this
# point in the script, so we simplify the logic by checking for any of the
# possible boost header locations that are possible outcomes from running
# this script.
BOOST_VERSION_FILES = [
"include/boost/version.hpp",
"include/boost-1_76/boost/version.hpp",
"include/boost-1_78/boost/version.hpp",
"include/boost-1_82/boost/version.hpp",
"include/boost-1_86/boost/version.hpp"
]
def InstallBoost_Helper(context, force, buildArgs):
# In general we use boost 1.76.0 to adhere to VFX Reference Platform CY2022.
# However, there are some cases where a newer version is required.
# - Building with Visual Studio 2022 with the 14.4x toolchain requires boost
# 1.86.0 or newer, we choose it for all Visual Studio 2022 versions for
# simplicity.
# - Building with Python 3.11 requires boost 1.82.0 or newer
# (https://github.com/boostorg/python/commit/a218ba)
# - Building on MacOS requires v1.82.0 or later for C++17 support starting
# with Xcode 15. We choose to use this version for all MacOS builds for
# simplicity."
# - Building with Python 3.10 requires boost 1.76.0 or newer
# (https://github.com/boostorg/python/commit/cbd2d9)
# XXX: Due to a typo we've been using 1.78.0 in this case for a while.
# We're leaving it that way to minimize potential disruption.
# - Building on MacOS requires boost 1.78.0 or newer to resolve Python 3
# compatibility issues on Big Sur and Monterey.
pyInfo = GetPythonInfo(context)
pyVer = (int(pyInfo[3].split('.')[0]), int(pyInfo[3].split('.')[1]))
if IsVisualStudio2022OrGreater():
BOOST_VERSION = (1, 86, 0)
BOOST_SHA256 = "cd20a5694e753683e1dc2ee10e2d1bb11704e65893ebcc6ced234ba68e5d8646"
elif MacOS() or (context.buildBoostPython and pyVer >= (3,11)):
BOOST_VERSION = (1, 82, 0)
BOOST_SHA256 = "f7c9e28d242abcd7a2c1b962039fcdd463ca149d1883c3a950bbcc0ce6f7c6d9"
elif context.buildBoostPython and pyVer >= (3, 10):
BOOST_VERSION = (1, 78, 0)
BOOST_SHA256 = "f22143b5528e081123c3c5ed437e92f648fe69748e95fa6e2bd41484e2986cc3"
else:
BOOST_VERSION = (1, 76, 0)
BOOST_SHA256 = "0fd43bb53580ca54afc7221683dfe8c6e3855b351cd6dce53b1a24a7d7fbeedd"
# Documentation files in the boost archive can have exceptionally
# long paths. This can lead to errors when extracting boost on Windows,
# since paths are limited to 260 characters by default on that platform.
# To avoid this, we skip extracting all documentation.
#
# For some examples, see: https://svn.boost.org/trac10/ticket/11677
dontExtract = [
"*/doc/*",
"*/libs/*/doc/*",
"*/libs/wave/test/testwave/testfiles/utf8-test-*"
]
# Provide backup sources for downloading boost to avoid issues when
# one mirror goes down.
major, minor, patch = BOOST_VERSION
version = f"{major}.{minor}.{patch}"
filename = f"boost_{major}_{minor}_{patch}.zip"
urls = [
# The sourceforge mirror is typically faster than archives.boost.io
# so we use that first.
f"https://sourceforge.net/projects/boost/files/boost/{version}/{filename}/download",
f"https://archives.boost.io/release/{version}/source/{filename}"
]
sourceDir = None
for url in urls:
try:
sourceDir = DownloadURL(url, context, force,
dontExtract=dontExtract,
destFileName=filename,
expectedSHA256=BOOST_SHA256)
break
except Exception as e:
PrintWarning(str(e))
if url != urls[-1]:
PrintWarning("Trying alternative sources")
else:
raise RuntimeError("Failed to download boost")
with CurrentWorkingDirectory(sourceDir):
if Windows():
bootstrap = "bootstrap.bat"
else:
bootstrap = "./bootstrap.sh"
# zip doesn't preserve file attributes, so force +x manually.
Run('chmod +x ' + bootstrap)
Run('chmod +x ./tools/build/src/engine/build.sh')
# For cross-compilation on macOS we need to specify the architecture
# for both the bootstrap and the b2 phase of building boost.
bootstrapCmd = '{bootstrap} --prefix="{instDir}"'.format(
bootstrap=bootstrap, instDir=context.instDir)
macOSArch = ""
if MacOS():
if apple_utils.GetTargetArch(context) == \
apple_utils.TARGET_X86:
macOSArch = "-arch {0}".format(apple_utils.TARGET_X86)
elif apple_utils.GetTargetArch(context) == \
apple_utils.GetTargetArmArch():
macOSArch = "-arch {0}".format(
apple_utils.GetTargetArmArch())
elif context.targetUniversal:
(primaryArch, secondaryArch) = \
apple_utils.GetTargetArchPair(context)
macOSArch="-arch {0} -arch {1}".format(
primaryArch, secondaryArch)
if macOSArch:
bootstrapCmd += " cxxflags=\"{0} -std=c++17 -stdlib=libc++\" " \
" cflags=\"{0}\" " \
" linkflags=\"{0}\"".format(macOSArch)
bootstrapCmd += " --with-toolset=clang"
Run(bootstrapCmd)
# b2 supports at most -j64 and will error if given a higher value.
num_procs = min(64, context.numJobs)
# boost only accepts three variants: debug, release, profile
boostBuildVariant = "profile"
if context.buildDebug:
boostBuildVariant= "debug"
elif context.buildRelease:
boostBuildVariant= "release"
elif context.buildRelWithDebug:
boostBuildVariant= "profile"
b2_settings = [
'--prefix="{instDir}"'.format(instDir=context.instDir),
'--build-dir="{buildDir}"'.format(buildDir=context.buildDir),
'-j{procs}'.format(procs=num_procs),
'address-model=64',
'link=shared',
'runtime-link=shared',
'threading=multi',
'variant={variant}'.format(variant=boostBuildVariant),
'--with-atomic',
'--with-regex'
]
if context.buildBoostPython:
b2_settings.append("--with-python")
pythonInfo = GetPythonInfo(context)
# This is the only platform-independent way to configure these
# settings correctly and robustly for the Boost jam build system.
# There are Python config arguments that can be passed to bootstrap
# but those are not available in boostrap.bat (Windows) so we must
# take the following approach:
projectPath = 'python-config.jam'
with open(projectPath, 'w') as projectFile:
# Note that we must escape any special characters, like
# backslashes for jam, hence the mods below for the path
# arguments. Also, if the path contains spaces jam will not
# handle them well. Surround the path parameters in quotes.
projectFile.write('using python : %s\n' % pythonInfo[3])
projectFile.write(' : "%s"\n' % pythonInfo[0].replace("\\","/"))
projectFile.write(' : "%s"\n' % pythonInfo[2].replace("\\","/"))
projectFile.write(' : "%s"\n' % os.path.dirname(pythonInfo[1]).replace("\\","/"))
if context.buildDebug and context.debugPython:
projectFile.write(' : <python-debugging>on\n')
projectFile.write(' ;\n')
b2_settings.append("--user-config=python-config.jam")
if context.buildDebug and context.debugPython:
b2_settings.append("python-debugging=on")
if context.buildOIIO:
b2_settings.append("--with-date_time")
if context.buildOIIO or context.enableOpenVDB:
b2_settings.append("--with-chrono")
b2_settings.append("--with-system")
b2_settings.append("--with-thread")
if context.enableOpenVDB:
b2_settings.append("--with-iostreams")
# b2 with -sNO_COMPRESSION=1 fails with the following error message:
# error: at [...]/boost_1_61_0/tools/build/src/kernel/modules.jam:107
# error: Unable to find file or target named
# error: '/zlib//zlib'
# error: referred to from project at
# error: 'libs/iostreams/build'
# error: could not resolve project reference '/zlib'
# But to avoid an extra library dependency, we can still explicitly
# exclude the bzip2 compression from boost_iostreams (note that
# OpenVDB uses blosc compression).
b2_settings.append("-sNO_BZIP2=1")
if context.buildOIIO:
b2_settings.append("--with-filesystem")
if force:
b2_settings.append("-a")
if Windows():
# toolset parameter for Visual Studio documented here:
# https://github.com/boostorg/build/blob/develop/src/tools/msvc.jam
if context.cmakeToolset == "v143":
b2_settings.append("toolset=msvc-14.3")
elif context.cmakeToolset == "v142":
b2_settings.append("toolset=msvc-14.2")
elif context.cmakeToolset == "v141":
b2_settings.append("toolset=msvc-14.1")
elif IsVisualStudio2022OrGreater():
b2_settings.append("toolset=msvc-14.3")
elif IsVisualStudio2019OrGreater():
b2_settings.append("toolset=msvc-14.2")
elif IsVisualStudio2017OrGreater():
b2_settings.append("toolset=msvc-14.1")
if MacOS():
# Must specify toolset=clang to ensure install_name for boost
# libraries includes @rpath
b2_settings.append("toolset=clang")
#
# Xcode 15.3 (and hence Apple Clang 15) removed the global
# declaration of std::piecewise_construct which causes boost build
# to fail.
# https://developer.apple.com/documentation/xcode-release-notes/xcode-15_3-release-notes.
# A fix for the same is also available in boost 1.84:
# https://github.com/boostorg/container/commit/79a75f470e75f35f5f2a91e10fcc67d03b0a2160
b2_settings.append(f"define=BOOST_UNORDERED_HAVE_PIECEWISE_CONSTRUCT=0")
if macOSArch:
b2_settings.append("cxxflags=\"{0} -std=c++17 -stdlib=libc++\"".format(macOSArch))
b2_settings.append("cflags=\"{0}\"".format(macOSArch))
b2_settings.append("linkflags=\"{0}\"".format(macOSArch))
if context.buildDebug:
b2_settings.append("--debug-configuration")
# Add on any user-specified extra arguments.
b2_settings += buildArgs
# Append extra argument controlling libstdc++ ABI if specified.
AppendCXX11ABIArg("cxxflags", context, b2_settings)
b2 = "b2" if Windows() else "./b2"
Run('{b2} {options} install'
.format(b2=b2, options=" ".join(b2_settings)))
def InstallBoost(context, force, buildArgs):
# Boost's build system will install the version.hpp header before