forked from xenia-project/xenia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xenia-build
executable file
·1699 lines (1442 loc) · 56.3 KB
/
xenia-build
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
#!/usr/bin/env python3
# Copyright 2020 Ben Vanik. All Rights Reserved.
"""Main build script and tooling for xenia.
Run with --help or no arguments for possible commands.
"""
from __future__ import print_function
from datetime import datetime
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
__author__ = 'ben.vanik@gmail.com (Ben Vanik)'
self_path = os.path.dirname(os.path.abspath(__file__))
# Detect if building on Android via Termux.
host_linux_platform_is_android = False
if sys.platform == 'linux':
try:
host_linux_platform_is_android = subprocess.Popen(
['uname', '-o'], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
universal_newlines=True).communicate()[0] == 'Android\n'
except Exception:
pass
def import_subprocess_environment(args):
popen = subprocess.Popen(
args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
variables, _ = popen.communicate()
envvars_to_save = (
'devenvdir',
'include',
'lib',
'libpath',
'path',
'pathext',
'systemroot',
'temp',
'tmp',
'windowssdkdir',
)
for line in variables.splitlines():
for envvar in envvars_to_save:
if re.match(envvar + '=', line.lower()):
var, setting = line.split('=', 1)
if envvar == 'path':
setting = os.path.dirname(sys.executable) + os.pathsep + setting
os.environ[var.upper()] = setting
break
def import_vs_environment():
"""Finds the installed Visual Studio version and imports
interesting environment variables into os.environ.
Returns:
A version such as 2015 or None if no installation is found.
"""
if sys.platform != 'win32':
return None
version = 0
install_path = None
env_tool_args = None
vswhere = subprocess.check_output('third_party/vswhere/vswhere.exe -version "[15,)" -latest -prerelease -format json -utf8', shell=False, universal_newlines=True, encoding="utf-8")
if vswhere:
vswhere = json.loads(vswhere)
if vswhere and len(vswhere) > 0:
version = int(vswhere[0].get("catalog", {}).get("productLineVersion", 2017))
install_path = vswhere[0].get("installationPath", None)
if version < 2017:
if 'VS140COMNTOOLS' in os.environ:
version = 2015
vcvars_path = os.environ['VS140COMNTOOLS']
vcvars_path = os.path.join(tools_path, '..\\..\\vc\\vcvarsall.bat')
env_tool_args = [vcvars_path, 'x64', '&&', 'set']
else:
vsdevcmd_path = os.path.join(install_path, 'Common7\\Tools\\VsDevCmd.bat')
if os.path.isfile(vsdevcmd_path) and os.access(vsdevcmd_path, os.X_OK):
env_tool_args = [vsdevcmd_path, '-arch=amd64', '-host_arch=amd64', '&&', 'set']
else:
vcvars_path = os.path.join(install_path, 'VC\\Auxiliary\\Build\\vcvarsall.bat')
env_tool_args = [vcvars_path, 'x64', '&&', 'set']
if version == 0:
return None
import_subprocess_environment(env_tool_args)
os.environ['VSVERSION'] = str(version)
return version
vs_version = import_vs_environment()
def main():
# Add self to the root search path.
sys.path.insert(0, self_path)
# Augment path to include our fancy things.
os.environ['PATH'] += os.pathsep + os.pathsep.join([
self_path,
os.path.abspath(os.path.join('tools', 'build')),
])
# Check git exists.
if not has_bin('git'):
print('WARNING: Git should be installed and on PATH. Version info will be omitted from all binaries!')
print('')
elif not git_is_repository():
print('WARNING: The source tree is unversioned. Version info will be omitted from all binaries!')
print('')
# Check python version.
if not sys.version_info[:2] >= (3, 6):
print('ERROR: Python 3.6+ must be installed and on PATH')
sys.exit(1)
# Grab Visual Studio version and execute shell to set up environment.
if sys.platform == 'win32' and vs_version is None:
print('WARNING: Visual Studio not found!')
print('Building for Windows will not be supported.')
print('Please refer to the building guide:')
print('https://github.com/xenia-project/xenia/blob/master/docs/building.md')
# Setup main argument parser and common arguments.
parser = argparse.ArgumentParser(prog='xenia-build')
# Grab all commands and populate the argument parser for each.
subparsers = parser.add_subparsers(title='subcommands',
dest='subcommand')
commands = discover_commands(subparsers)
# If the user passed no args, die nicely.
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
# Gather any arguments that we want to pass to child processes.
command_args = sys.argv[1:]
pass_args = []
try:
pass_index = command_args.index('--')
pass_args = command_args[pass_index + 1:]
command_args = command_args[:pass_index]
except Exception:
pass
# Parse command name and dispatch.
args = vars(parser.parse_args(command_args))
command_name = args['subcommand']
try:
command = commands[command_name]
return_code = command.execute(args, pass_args, os.getcwd())
except Exception:
raise
sys.exit(return_code)
def print_box(msg):
"""Prints an important message inside a box
"""
print(
'┌{0:─^{2}}╖\n'
'│{1: ^{2}}║\n'
'╘{0:═^{2}}╝\n'
.format('', msg, len(msg) + 2))
def has_bin(binary):
"""Checks whether the given binary is present.
Args:
binary: binary name (without .exe, etc).
Returns:
True if the binary exists.
"""
bin_path = get_bin(binary)
if not bin_path:
return False
return True
def get_bin(binary):
"""Checks whether the given binary is present and returns the path.
Args:
binary: binary name (without .exe, etc).
Returns:
Full path to the binary or None if not found.
"""
for path in os.environ['PATH'].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, binary)
if os.path.isfile(exe_file) and os.access(exe_file, os.X_OK):
return exe_file
exe_file += '.exe'
if os.path.isfile(exe_file) and os.access(exe_file, os.X_OK):
return exe_file
return None
def shell_call(command, throw_on_error=True, stdout_path=None, stderr_path=None, shell=False):
"""Executes a shell command.
Args:
command: Command to execute, as a list of parameters.
throw_on_error: Whether to throw an error or return the status code.
stdout_path: File path to write stdout output to.
stderr_path: File path to write stderr output to.
Returns:
If throw_on_error is False the status code of the call will be returned.
"""
stdout_file = None
if stdout_path:
stdout_file = open(stdout_path, 'w')
stderr_file = None
if stderr_path:
stderr_file = open(stderr_path, 'w')
result = 0
try:
if throw_on_error:
result = 1
subprocess.check_call(command, shell=shell, stdout=stdout_file, stderr=stderr_file)
result = 0
else:
result = subprocess.call(command, shell=shell, stdout=stdout_file, stderr=stderr_file)
finally:
if stdout_file:
stdout_file.close()
if stderr_file:
stderr_file.close()
return result
def generate_version_h():
"""Generates a build/version.h file that contains current git info.
"""
if git_is_repository():
(branch_name, commit, commit_short) = git_get_head_info()
else:
branch_name = 'tarball'
commit = ':(-dont-do-this'
commit_short = ':('
contents = '''// Autogenerated by `xb premake`.
#ifndef GENERATED_VERSION_H_
#define GENERATED_VERSION_H_
#define XE_BUILD_BRANCH "%s"
#define XE_BUILD_COMMIT "%s"
#define XE_BUILD_COMMIT_SHORT "%s"
#define XE_BUILD_DATE __DATE__
#endif // GENERATED_VERSION_H_
''' % (branch_name, commit, commit_short)
with open('build/version.h', 'w') as f:
f.write(contents)
def generate_source_class(path):
header_path = '{}.h'.format(path)
source_path = '{}.cc'.format(path)
if os.path.isfile(header_path) or os.path.isfile(source_path):
print('ERROR: Target file already exists')
return 1
if generate_source_file(header_path) > 0:
return 1
if generate_source_file(source_path) > 0:
# remove header if source file generation failed
os.remove(os.path.join(source_root, header_path))
return 1
return 0
def generate_source_file(path):
"""Generates a source file at the specified path containing copyright notice
"""
copyright = '''/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright {} Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/'''.format(datetime.now().year)
if os.path.isfile(path):
print('ERROR: Target file already exists')
return 1
try:
with open(path, 'w') as f:
f.write(copyright)
except Exception as e:
print('ERROR: Could not write to file [path {}]'.format(path))
return 1
return 0
def git_get_head_info():
"""Queries the current branch and commit checksum from git.
Returns:
(branch_name, commit, commit_short)
If the user is not on any branch the name will be 'detached'.
"""
p = subprocess.Popen([
'git',
'symbolic-ref',
'--short',
'-q',
'HEAD',
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
branch_name = stdout.decode('ascii').strip() or 'detached'
p = subprocess.Popen([
'git',
'rev-parse',
'HEAD',
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
commit = stdout.decode('ascii').strip() or 'unknown'
p = subprocess.Popen([
'git',
'rev-parse',
'--short',
'HEAD',
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = p.communicate()
commit_short = stdout.decode('ascii').strip() or 'unknown'
return branch_name, commit, commit_short
def git_is_repository():
"""Checks if git is available and this source tree is versioned.
"""
if not has_bin('git'):
return False
return shell_call([
'git',
'rev-parse',
'--is-inside-work-tree',
], throw_on_error=False, stdout_path=os.devnull, stderr_path=os.devnull) == 0
def git_submodule_update():
"""Runs a full recursive git submodule init and update.
"""
shell_call([
'git',
'submodule',
'update',
'--init',
'--recursive',
])
def get_clang_format_binary():
"""Finds a clang-format binary. Aborts if none is found.
Returns:
A path to the clang-format executable.
"""
attempts = [
'C:\\Program Files\\LLVM\\bin\\clang-format.exe',
'C:\\Program Files (x86)\\LLVM\\bin\\clang-format.exe',
'clang-format-9',
'clang-format',
]
for binary in attempts:
if has_bin(binary):
return binary
print('ERROR: clang-format is not on PATH')
print('LLVM is available from https://llvm.org/releases/download.html')
print('At least version 9 is required.')
print('See docs/style_guide.md for instructions on how to get it.')
sys.exit(1)
def get_premake_target_os(target_os_override=None):
"""Gets the target --os to pass to premake, either for the current platform
or for the user-specified cross-compilation target.
Args:
target_os_override: override specified by the user for cross-compilation,
or None to target the host platform.
Returns:
Target --os to pass to premake. If a return value of this function valid
for the current configuration is passed to it again, the same value will
be returned.
"""
if sys.platform == 'darwin':
target_os = 'macosx'
elif sys.platform == 'win32':
target_os = 'windows'
elif host_linux_platform_is_android:
target_os = 'android'
else:
target_os = 'linux'
if target_os_override is not None and target_os_override != target_os:
if target_os_override == 'android':
target_os = target_os_override
else:
print(
'ERROR: cross-compilation is only supported for Android target')
sys.exit(0)
return target_os
def run_premake(target_os, action, cc=None):
"""Runs premake on the main project with the given format.
Args:
target_os: target --os to pass to premake.
action: action to preform.
"""
args = [
sys.executable,
os.path.join('tools', 'build', 'premake'),
'--file=premake5.lua',
'--os=%s' % target_os,
'--test-suite-mode=combined',
'--verbose',
action,
]
if cc:
args.insert(4, '--cc=%s' % cc)
ret = subprocess.call(args, shell=False)
if ret == 0:
generate_version_h()
return ret
def run_platform_premake(target_os_override=None, cc='clang', devenv=None):
"""Runs all gyp configurations.
"""
target_os = get_premake_target_os(target_os_override)
if devenv is None:
if target_os == 'macosx':
devenv = 'xcode4'
elif target_os == 'windows':
vs_version = '2015'
if 'VSVERSION' in os.environ:
vs_version = os.environ['VSVERSION']
devenv = 'vs' + vs_version
elif target_os == 'android':
devenv = 'androidmk'
else:
devenv = 'gmake2'
if target_os != 'linux':
cc = None
return run_premake(target_os=target_os, action=devenv, cc=cc)
def get_build_bin_path(args):
"""Returns the path of the bin/ path with build results based on the
configuration specified in the parsed arguments.
Args:
args: Parsed arguments.
Returns:
A full path for the bin folder.
"""
if sys.platform == 'darwin':
platform = 'macosx'
elif sys.platform == 'win32':
platform = 'windows'
else:
platform = 'linux'
return os.path.join(self_path, 'build', 'bin', platform.capitalize(), args['config'].capitalize())
def create_clion_workspace():
"""Creates some basic workspace information inside the .idea directory for first start.
"""
if os.path.exists('.idea'):
# No first start
return False
print('Generating CLion workspace files...')
# Might become easier in the future: https://youtrack.jetbrains.com/issue/CPP-7911
# Set the location of the CMakeLists.txt
os.mkdir('.idea')
with open(os.path.join('.idea', 'misc.xml'), 'w') as f:
f.write("""<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeWorkspace" PROJECT_DIR="$PROJECT_DIR$/build">
<contentRoot DIR="$PROJECT_DIR$" />
</component>
</project>
""")
# Set available configurations
# TODO Find a way to trigger a cmake reload
with open(os.path.join('.idea', 'workspace.xml'), 'w') as f:
f.write("""<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeSettings">
<configurations>
<configuration PROFILE_NAME="Checked" CONFIG_NAME="Checked" />
<configuration PROFILE_NAME="Debug" CONFIG_NAME="Debug" />
<configuration PROFILE_NAME="Release" CONFIG_NAME="Release" />
</configurations>
</component>
</project>""")
return True
def discover_commands(subparsers):
"""Looks for all commands and returns a dictionary of them.
In the future commands could be discovered on disk.
Args:
subparsers: Argument subparsers parent used to add command parsers.
Returns:
A dictionary containing name-to-Command mappings.
"""
commands = {
'setup': SetupCommand(subparsers),
'pull': PullCommand(subparsers),
'premake': PremakeCommand(subparsers),
'build': BuildCommand(subparsers),
'devenv': DevenvCommand(subparsers),
'genspirv': GenSpirvCommand(subparsers),
'gentests': GenTestsCommand(subparsers),
'test': TestCommand(subparsers),
'gputest': GpuTestCommand(subparsers),
'clean': CleanCommand(subparsers),
'nuke': NukeCommand(subparsers),
'lint': LintCommand(subparsers),
'format': FormatCommand(subparsers),
'style': StyleCommand(subparsers),
'tidy': TidyCommand(subparsers),
'stub': StubCommand(subparsers),
}
if sys.platform == 'win32':
commands['buildhlsl'] = BuildHlslCommand(subparsers)
return commands
class Command(object):
"""Base type for commands.
"""
def __init__(self, subparsers, name, help_short=None, help_long=None,
*args, **kwargs):
"""Initializes a command.
Args:
subparsers: Argument subparsers parent used to add command parsers.
name: The name of the command exposed to the management script.
help_short: Help text printed alongside the command when queried.
help_long: Extended help text when viewing command help.
"""
self.name = name
self.help_short = help_short
self.help_long = help_long
self.parser = subparsers.add_parser(name,
help=help_short,
description=help_long)
self.parser.set_defaults(command_handler=self)
def execute(self, args, pass_args, cwd):
"""Executes the command.
Args:
args: Arguments hash for the command.
pass_args: Arguments list to pass to child commands.
cwd: Current working directory.
Returns:
Return code of the command.
"""
return 1
class SetupCommand(Command):
"""'setup' command."""
def __init__(self, subparsers, *args, **kwargs):
super(SetupCommand, self).__init__(
subparsers,
name='setup',
help_short='Setup the build environment.',
*args, **kwargs)
self.parser.add_argument(
'--target_os', default=None,
help='Target OS passed to premake, for cross-compilation')
def execute(self, args, pass_args, cwd):
print('Setting up the build environment...')
print('')
# Setup submodules.
print('- git submodule init / update...')
if git_is_repository():
git_submodule_update()
else:
print('WARNING: Git not available or not a repository. Dependencies may be missing.')
print('')
print('- running premake...')
if run_platform_premake(target_os_override=args['target_os']) == 0:
print('')
print('Success!')
return 0
class PullCommand(Command):
"""'pull' command."""
def __init__(self, subparsers, *args, **kwargs):
super(PullCommand, self).__init__(
subparsers,
name='pull',
help_short='Pulls the repo and all dependencies and rebases changes.',
*args, **kwargs)
self.parser.add_argument(
'--merge', action='store_true',
help='Merges on master instead of rebasing.')
self.parser.add_argument(
'--target_os', default=None,
help='Target OS passed to premake, for cross-compilation')
def execute(self, args, pass_args, cwd):
print('Pulling...')
print('')
print('- switching to master...')
shell_call([
'git',
'checkout',
'master',
])
print('')
print('- pulling self...')
if args['merge']:
shell_call([
'git',
'pull',
])
else:
shell_call([
'git',
'pull',
'--rebase',
])
print('')
print('- pulling dependencies...')
git_submodule_update()
print('')
print('- running premake...')
if run_platform_premake(target_os_override=args['target_os']) == 0:
print('')
print('Success!')
return 0
class PremakeCommand(Command):
"""'premake' command."""
def __init__(self, subparsers, *args, **kwargs):
super(PremakeCommand, self).__init__(
subparsers,
name='premake',
help_short='Runs premake to update all projects.',
*args, **kwargs)
self.parser.add_argument(
'--cc', default='clang', help='Compiler toolchain passed to premake')
self.parser.add_argument(
'--devenv', default=None, help='Development environment')
self.parser.add_argument(
'--target_os', default=None,
help='Target OS passed to premake, for cross-compilation')
def execute(self, args, pass_args, cwd):
# Update premake. If no binary found, it will be built from source.
print('Running premake...')
print('')
if run_platform_premake(target_os_override=args['target_os'],
cc=args['cc'], devenv=args['devenv']) == 0:
print('Success!')
return 0
class BaseBuildCommand(Command):
"""Base command for things that require building."""
def __init__(self, subparsers, *args, **kwargs):
super(BaseBuildCommand, self).__init__(
subparsers,
*args, **kwargs)
self.parser.add_argument(
'--cc', default='clang', help='Compiler toolchain passed to premake')
self.parser.add_argument(
'--config', choices=['checked', 'debug', 'release'], default='debug',
type=str.lower, help='Chooses the build configuration.')
self.parser.add_argument(
'--target', action='append', default=[],
help='Builds only the given target(s).')
self.parser.add_argument(
'--force', action='store_true',
help='Forces a full rebuild.')
self.parser.add_argument(
'--no_premake', action='store_true',
help='Skips running premake before building.')
self.parser.add_argument(
'-j', default=4, type=int, help='Number of parallel threads')
def execute(self, args, pass_args, cwd):
if not args['no_premake']:
print('- running premake...')
run_platform_premake(cc=args['cc'])
print('')
threads = args['j']
if threads < 0:
threads = 0
print('- building (%s):%s...' % (
'all' if not len(args['target']) else ', '.join(args['target']),
args['config']))
if sys.platform == 'win32':
if vs_version is None:
print('ERROR: Visual Studio is not installed.');
result = 1
else:
targets = None
if len(args['target']):
targets = '/t:' + ';'.join(
target + (':Rebuild' if args['force'] else '')
for target in args['target'])
else:
targets = '/t:Rebuild' if args['force'] else None
result = subprocess.call([
'msbuild',
'build/xenia.sln',
'/nologo',
'/m',
'/v:m',
'/p:Configuration=' + args['config'],
] + ([targets] if targets is not None else []) + pass_args,
shell=False)
elif sys.platform == 'darwin':
# TODO(benvanik): other platforms.
print('ERROR: don\'t know how to build on this platform.')
result = 1
else:
result = subprocess.call([
'make',
'-j' if threads == 0 else '-j%d' % threads,
'-Cbuild/',
'config=%s_linux' % (args['config']),
] + pass_args + args['target'], shell=False, env=dict(os.environ))
print('')
if result != 0:
print('ERROR: build failed with one or more errors.')
return result
return 0
class BuildCommand(BaseBuildCommand):
"""'build' command."""
def __init__(self, subparsers, *args, **kwargs):
super(BuildCommand, self).__init__(
subparsers,
name='build',
help_short='Builds the project with the default toolchain.',
*args, **kwargs)
def execute(self, args, pass_args, cwd):
print('Building %s...' % (args['config']))
print('')
result = super(BuildCommand, self).execute(args, pass_args, cwd)
if not result:
print('Success!')
return result
class GenSpirvCommand(Command):
"""'genspirv' command."""
def __init__(self, subparsers, *args, **kwargs):
super(GenSpirvCommand, self).__init__(
subparsers,
name='genspirv',
help_short='Generates SPIR-V binaries and header files.',
help_long='''
Generates the .spv/.h binaries under src/xenia/*/vulkan/shaders/bin/).
Run after modifying any .vert/.geom/.frag files.
''',
*args, **kwargs)
def execute(self, args, pass_args, cwd):
print('Generating SPIR-V binaries...')
print('')
vulkan_sdk_path = os.environ['VULKAN_SDK']
vulkan_bin_path = os.path.join(vulkan_sdk_path, 'bin')
glslang = os.path.join(vulkan_bin_path, 'glslangValidator')
spirv_dis = os.path.join(vulkan_bin_path, 'spirv-dis')
spirv_remap = os.path.join(vulkan_bin_path, 'spirv-remap')
# Ensure we have the tools.
if not os.path.exists(vulkan_sdk_path):
print('ERROR: could not find the Vulkan SDK')
return 1
elif not has_bin(glslang):
print('ERROR: could not find glslangValidator')
return 1
elif not has_bin(spirv_dis):
print('ERROR: could not find spirv-dis')
return 1
elif not has_bin(spirv_remap):
print('ERROR: could not find spirv-remap')
return 1
src_files = [os.path.join(root, name)
for root, dirs, files in os.walk('src')
for name in files
if (name.endswith('.vert') or name.endswith('.geom') or
name.endswith('.frag'))]
any_errors = False
for src_file in src_files:
print('- %s' % (src_file))
src_name = os.path.splitext(os.path.basename(src_file))[0]
identifier = os.path.basename(src_file).replace('.', '_')
bin_path = os.path.join(os.path.dirname(src_file), 'bin')
spv_file = os.path.join(bin_path, identifier) + '.spv'
txt_file = os.path.join(bin_path, identifier) + '.txt'
h_file = os.path.join(bin_path, identifier) + '.h'
# GLSL source -> .spv binary
shell_call([
glslang,
'-Os',
'-V', src_file,
'-o', spv_file,
])
# Disassemble binary into human-readable text.
shell_call([
spirv_dis,
'-o', txt_file,
spv_file,
])
# TODO(benvanik): remap?
# bin2c so we get a header file we can compile in.
with open(h_file, 'w') as out_file:
out_file.write('// generated from `xb genspirv`\n')
out_file.write('// source: %s\n' % os.path.basename(src_file))
out_file.write('const uint8_t %s[] = {' % (identifier))
with open(spv_file, 'rb') as in_file:
index = 0
c = in_file.read(1)
while len(c) != 0:
if index % 12 == 0:
out_file.write('\n ')
else:
out_file.write(' ')
index += 1
out_file.write('0x%02X,' % ord(c))
c = in_file.read(1)
out_file.write('\n};\n')
if any_errors:
print('ERROR: failed to build one or more SPIR-V files.')
return 1
return 0
class BuildHlslCommand(Command):
"""'buildhlsl' command."""
def __init__(self, subparsers, *args, **kwargs):
super(BuildHlslCommand, self).__init__(
subparsers,
name='buildhlsl',
help_short='Generates Direct3D shader binaries and header files.',
help_long='''
Generates the .cso/.h binaries under src/xenia/*/d3d12/shaders/dxbc/.
Run after modifying any .hs/vs/ds/gs/ps/cs.hlsl files.
''',
*args, **kwargs)
def execute(self, args, pass_args, cwd):
print('Building Direct3D shaders...')
print('')
windows_sdk_bin_path = os.path.join(os.environ['ProgramFiles(x86)'],
'Windows Kits/10/bin/x64')
fxc = os.path.join(windows_sdk_bin_path, 'fxc')
# Ensure we have the tools.
if not os.path.exists(windows_sdk_bin_path):
print('ERROR: could not find Windows 10 SDK binaries')
return 1
elif not has_bin(fxc):
print('ERROR: could not find fxc')
return 1
src_files = [os.path.join(root, name)
for root, dirs, files in os.walk('src')
for name in files
if (name.endswith('.hs.hlsl') or
name.endswith('.vs.hlsl') or
name.endswith('.ds.hlsl') or
name.endswith('.gs.hlsl') or
name.endswith('.ps.hlsl') or
name.endswith('.cs.hlsl'))]
# TODO(Triang3l): Handle any_errors.
any_errors = False
for src_file in src_files:
print('- %s' % (src_file))
src_name = os.path.splitext(os.path.basename(src_file))[0]
identifier = os.path.basename(src_file)[:-5].replace('.', '_')
bin_path = os.path.join(os.path.dirname(src_file), 'dxbc')
if not os.path.exists(bin_path):
os.mkdir(bin_path)
cso_file = os.path.join(bin_path, identifier) + '.cso'
txt_file = os.path.join(bin_path, identifier) + '.txt'
h_file = os.path.join(bin_path, identifier) + '.h'
# HLSL source -> .cso binary and DXBC disassembly.
shell_call([
fxc,
'/nologo',
'/T', identifier[-2:] + '_5_1',
'/Fo', cso_file,
'/Fc', txt_file,
src_file,
])
# bin2c so we get a header file we can compile in.
with open(h_file, 'w') as out_file:
out_file.write('// generated from `xb buildhlsl`\n')
out_file.write('// source: %s\n' % os.path.basename(src_file))
out_file.write('const uint8_t %s[] = {' % (identifier))
with open(cso_file, 'rb') as in_file:
index = 0
c = in_file.read(1)
while len(c) != 0:
if index % 12 == 0:
out_file.write('\n ')
else:
out_file.write(' ')
index += 1
out_file.write('0x%02X,' % ord(c))
c = in_file.read(1)
out_file.write('\n};\n')
if any_errors:
print('ERROR: failed to build one or more shaders.')
return 1
return 0
class TestCommand(BaseBuildCommand):