forked from NatWeiss/RapidGame
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrapidgame.js
1655 lines (1515 loc) · 44.5 KB
/
rapidgame.js
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
//
// Part of the [RapidGame](https://github.com/natweiss/rapidgame) project.
// See the `LICENSE` file for the license governing this code.
// Developed by Nathanael Weiss.
//
// To-do:
// - Mention how to use a manual download of cocos2d-x in readme.
// - Fix Mac project name search and replace so names with spaces work. (It used to...)
// - Regarding the linux build: http://stackoverflow.com/questions/21168141/can-not-install-packages-using-node-package-manager-in-ubuntu
// - Why did `sudo npm unlink rapidgame -g; sudo npm link .` fix "Error: Cannot find module 'path-extra'"?
// - Mac prebuild fails if the user has changed Xcode's temporary build directory to "relative to project". Here's some details:
// export TARGET_TEMP_DIR=/Users/user/Library/Developer/RapidGame/src/proj.ios_mac/build/cocos2dx-prebuilt.build/Debug/Mac.build
// export TEMP_DIR=/Users/user/Library/Developer/RapidGame/src/proj.ios_mac/build/cocos2dx-prebuilt.build/Debug/Mac.build
// export TEMP_FILES_DIR=/Users/user/Library/Developer/RapidGame/src/proj.ios_mac/build/cocos2dx-prebuilt.build/Debug/Mac.build
// export TEMP_FILE_DIR=/Users/user/Library/Developer/RapidGame/src/proj.ios_mac/build/cocos2dx-prebuilt.build/Debug/Mac.build
// /bin/sh -c /Users/user/Library/Developer/RapidGame/src/proj.ios_mac/build/cocos2dx-prebuilt.build/Debug/Mac.build/Script-419E8E9E18A9BB3400232A34.sh
// outputDir=/Users/user/Library/Developer/RapidGame/src/proj.ios_mac/../../latest/cocos2d/x/lib/Debug-Mac/macosx
// error: libtool: can't open file: /Users/user/Library/Developer/RapidGame/src/proj.ios_mac/build/Debug/*.a (No such file or directory)
// It may be that we just need to set CONFIGURATION_BUILD_DIR, see: https://developer.apple.com/library/mac/documentation/DeveloperTools/Reference/XcodeBuildSettingRef/1-Build_Setting_Reference/build_setting_ref.html
//
var http = require("http"),
path = require("path-extra"),
fs = require("fs"),
cmd = require("commander"),
replace = require("replace"),
download = require("download"),
glob = require("glob"),
wrench = require("wrench"),
child_process = require("child_process"),
packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"))),
cmdName = packageJson.name,
version = packageJson.version,
cocos2djsUrlMac = "http://cdn.cocos2d-x.org/cocos2d-x-3.7.zip", // also, http://www.cocos2d-x.org/filedown/cocos2d-x-v3.7.zip
cocos2djsUrlWin = "http://cdn.cocos2d-x.org/cocos2d-x-3.7.zip",
cocos2djsUrl = (process.platform === "darwin" ? cocos2djsUrlMac : cocos2djsUrlWin),
cocos2dDirGlob = "*ocos2d-x*",
category,
engines = [],
templates = [],
builds = [],
orientations = ["landscape", "portrait"],
platforms = ["headers", "ios", "mac", "android", "windows", "linux"],
copyCount = 0,
msBuildExePath,
libExePath,
vcTargetsPath,
defaults = {
engine: "cocos2dx",
template: "TwoScene",
package: "org.mycompany.mygame",
dest: process.cwd(),
prefix: __dirname,
orientation: orientations[0]
};
//
// list directories (path.join is called on all arguments)
//
var listDirectories = function() {
var i, src, dirs;
for (i = 0; i < arguments.length; i += 1) {
src = (src ? path.join(src, arguments[i]) : arguments[i]);
}
dirs = glob.sync(src);
for (i = 0; i < dirs.length; i++) {
dirs[i] = path.basename(dirs[i]);
}
return dirs;
};
//
// get engines and templates
//
engines = listDirectories(__dirname, "templates", "*");
templates = listDirectories(__dirname, "templates", "cocos2dx", "*");
//
// Main run method.
//
var run = function(args) {
var i, commands = [], commandFound = false;
checkUpdate();
args = args || process.argv;
cmd
.version(version)
.option("-t, --template <name>", "template (" + templates.join(", ") + ") [" + defaults.template + "]", defaults.template)
.option("-p, --prefix <name>", "library directory [" + defaults.prefix + "]", defaults.prefix)
.option("-f, --folder <path>", "output folder [" + defaults.dest + "]", defaults.dest)
//.option("-o, --orientation <orientation>", "orientation (" + orientations.join(", ") + ") [" + defaults.orientation + "]", defaults.orientation)
.option("--nostrip", "do not strip the prebuilt libraries", false)
.option("--minimal", "prebuild only debug libraries and use minimal architectures", false)
.option("-v, --verbose", "be verbose", false);
cmd
.command("create <engine> <project-name> <package-name>")
.description(" Create a new cross-platform game project [engines: " + engines.join(", ") + "]")
.action(createProject);
commands.push("create");
cmd
.command("prebuild [platform]")
.description(" Prebuild cocos2d-x static libraries [platforms: " + platforms.join(", ") + "]")
.action(prebuild);
commands.push("prebuild");
cmd
.command("init <directory>")
.description(" Create a symlink in the given directory to the libraries")
.action(init);
commands.push("init");
cmd.on("--help", usageExamples);
cmd
.parse(args)
.name = cmdName;
if (!cmd.args.length) {
usage();
} else {
// Check if command exists
for (i = 0; i < commands.length; i += 1) {
if (args[2] === commands[i]) {
commandFound = true;
break;
}
}
if (!commandFound) {
console.log("Command '" + args[2] + "' not found");
usage();
}
}
};
//
// Initialize the given directory.
//
var init = function(directory) {
var src, dest;
if (!checkPrefix()) {
usage();
return 1;
}
if (!dirExists(directory)) {
console.log("Output directory must exist: " + directory);
return 1;
}
// Create lib symlink
// Windows: If you get Error: EPERM: operation not permitted: 'folder name\lib' it probably means you need to Run As Administrator
src = path.join(cmd.prefix, version);
dest = path.join(directory, "lib");
console.log("Symlinking" + (cmd.verbose ? ": " + dest + " -> " + src : " lib folder"));
try {
fs.symlinkSync(src, dest);
} catch(e) {
logErr("Error creating symlink: " + e);
}
};
//
// Create project.
//
var createProject = function(engine, name, package) {
var dir = path.join(cmd.folder, name),
src,
dest,
fileCount,
i,
onFinished,
files,
isCocos2d = false,
packageSrc = "com.wizardfu." + cmd.template.toLowerCase();
cmd.engine = engine.toString().toLowerCase();
category = "createProject";
if (!checkPrefix()) {
usage();
return 1;
}
// Check engine and name
if (!cmd.engine || !name || !package) {
console.log("Engine, project name and package name are required, for example: " + cmdName + " cocos2dx \"HeckYeah\" com.mycompany.heckyeah");
usage();
return 1;
}
// Check if dirs exist
if (dirExists(dir) || fileExists(dir)) {
console.log("Output directory already exists: " + dir);
return 1;
}
// Check engine
if (engines.indexOf(cmd.engine) < 0) {
console.log("Engine '" + cmd.engine + "' not found");
console.log("Available engines are: " + engines.join(", "));
usage();
return 1;
}
// Check template
src = path.join(__dirname, "templates", cmd.engine, cmd.template);
if (!dirExists(src)) {
console.log("Missing template directory: " + src);
files = listDirectories(__dirname, "templates", cmd.engine, "*");
if (files.length > 0) {
console.log("Available templates for " + cmd.engine + " are: " + files.join(", ") + ".");
}
usage();
return 1;
}
// Start
report("start", cmd.engine + "/" + cmd.template);
console.log("Rapidly creating a game");
console.log("Engine: " + cmd.engine.charAt(0).toUpperCase() + cmd.engine.slice(1));
console.log("Template: " + cmd.template + (cmd.verbose ? " " + packageSrc : ""));
isCocos2d = (cmd.engine.indexOf("cocos") >= 0);
// Copy all template files to destination
dest = dir;
console.log("Copying project files" + (cmd.verbose ? " from " + src + " to " + dest : ""));
fileCount = copyRecursive(src, dest, true);
if (cmd.verbose) {
console.log("Successfully copied " + fileCount + " files");
}
// Replace project name
console.log("Setting project name: " + name);
replace({
regex: cmd.template,
replacement: name,
paths: [dest],
include: "*.js,*.plist,*.cpp,*.md,*.lua,*.html,*.json,*.xml,*.xib,*.pbxproj,*.xcscheme,*.xcworkspacedata,*.xccheckout,*.sh,*.cmd,*.py,*.rc,*.sln,*.txt,.classpath,.project,.cproject,makefile,manifest,*.vcxproj,*.user,*.filters,.name",
recursive: true,
silent: !cmd.verbose
});
// Replace package name
console.log("Setting package name: " + package);
replace({
regex: packageSrc,
replacement: package,
paths: [dest],
include: "*.js,*.plist,*.xml,makefile,manifest,*.settings,*.lua,.project,.identifier",
recursive: true,
silent: !cmd.verbose
});
// Rename files & dirs
from = path.join(dest, "**", cmd.template + ".*");
if (cmd.verbose) {
console.log("Renaming all " + from + " files");
}
files = glob.sync(from);
for (i = 0; i < files.length; i++) {
from = files[i];
to = path.join(path.dirname(from), path.basename(from).replace(cmd.template, name));
if (cmd.verbose) {
console.log("Moving " + from + " to " + to);
}
try {
fs.renameSync(from, to);
} catch(e) {
logErr("Error moving file " + e);
}
}
// Symlink
if (isCocos2d) {
init(dir);
}
// Npm install
i = null;
dest = path.join(dir, "server");
onFinished = function(){
// Show readme
console.log("Done");
try {
var text = fs.readFileSync(path.join(dir, "README.md")).toString();
console.log("");
console.log(text);
console.log("");
} catch(e) {
}
report("done");
// Auto prebuild
if (isCocos2d && !dirExists(path.join(cmd.prefix, version))) {
console.log("");
console.log("Static libraries must be prebuilt");
prebuild();
}
};
if (dirExists(dest) && !dirExists(path.join(dest, "node_modules"))) {
console.log("Installing node modules");
try {
child_process.exec("npm install", {cwd: dest, env: process.env}, function(a, b, c){
execCallback(a, b, c);
onFinished();
});
} catch(e) {
logErr("Error installing node modules: " + e);
}
} else {
onFinished();
}
};
//
// run the prebuild command
//
var prebuild = function(platform, config, arch) {
category = "prebuild";
platform = (platform || "");
platform = platform.toString().toLowerCase();
config = config || "";
arch = arch || "";
if (platforms.indexOf(platform) < 0) {
platform = "";
}
if (!checkPrefix()) {
usage();
return 1;
}
// initialize build log
cmd.buildLog = path.join(cmd.prefix, "build.log");
try {
fs.writeFileSync(cmd.buildLog, "");
console.log("Writing build log to: " + cmd.buildLog);
} catch(e) {
cmd.buildLog = "";
}
getToolPaths(function(success) {
if (!success) {
return;
}
logBuild("Happily prebuilding " + platform, true);
report("start");
copySrcFiles(function() {
downloadCocos(function() {
setupPrebuild(platform, function() {
runPrebuild(platform, config, arch, function() {
report("done");
});
});
});
});
});
};
//
// copy src directory to prefix
//
var copySrcFiles = function(callback) {
var src, dest;
// Synchronously copy src directory to dest
src = path.join(__dirname, "src");
dest = path.join(cmd.prefix, "src");
if (src !== dest) {
logBuild("Copying " + src + " to " + dest, true);
copyRecursive(src, dest, true);
}
callback();
};
//
// download cocos2d-x source
//
var downloadCocos = function(callback) {
var dir = path.join(cmd.prefix, "src"),
src,
dest = path.join(dir, "cocos2d-x"),
downloaded = path.join(cmd.prefix, "src", "downloaded.txt"),
doDownload = !dirExists(dest),
ver;
// check downloaded version
try{
ver = fs.readFileSync(downloaded).toString().trim();
} catch(e) {
}
if (ver !== cocos2djsUrl) {
if (typeof ver !== "undefined") {
logBuild("Current cocos2d-x URL: " + cocos2djsUrl, true);
logBuild("Downloaded cocos2d-x URL: " + ver, true);
logBuild("Re-downloading", true);
}
doDownload = true;
try {
wrench.rmdirSyncRecursive(dest, true);
} catch(e) {
logBuild(e, cmd.verbose);
// try again
try {wrench.rmdirSyncRecursive(dest, true);} catch(e) {}
}
}
// no need to download
if (!doDownload) {
callback();
return;
}
// warn about git existing
src = path.join(cmd.prefix, ".git");
if (dirExists(src)) {
logBuild("WARNING: Directory " + src + " may prevent cocos2d-x from being patched with git apply", true);
}
// copy latest patch
copyGlobbed(path.join(__dirname, "src"), dir, "*.patch");
// download
downloadUrl(cocos2djsUrl, dir, function(success) {
if (!success) {
return;
}
var globPath = path.join(dir, cocos2dDirGlob),
files = glob.sync(globPath),
cmd;
if (!files || files.length !== 1) {
logErr("Couldn't glob " + globPath);
return;
}
// Rename extract dir
try {
logBuild("Moving " + files[0] + " to " + dest, true);
fs.renameSync(files[0], dest);
// Save downloaded version
fs.writeFileSync(downloaded, cocos2djsUrl);
// Apply latest patch
// (see comments at the end of this file for how to create the patch)
src = path.join(dir, "cocos2d.patch");
logBuild("Applying patch file: " + src, true);
// for some reason git apply sometimes does not work and produces no output...
// (use the patch command instead)
cmd = "patch -p1 < ";
if (process.platform === "win32") {
cmd = "git apply --whitespace=nowarn ";
}
cmd += '"' + src + '"';
exec(cmd, {cwd: dest, env: process.env}, function(err){
callback();
});
} catch(e) {
logErr("Couldn't move " + files[0] + " to " + dest)
}
});
};
//
// prebuild setup (copies headers, java files, etc.)
//
var setupPrebuild = function(platform, callback) {
var ver, dir, src, dest, i, files,
srcRoot = path.join(cmd.prefix, "src", "cocos2d-x");
if (platform && platform !== "headers") {
callback();
return;
}
logBuild("Copying header files...", true);
// reset cocos2d dir
ver = path.join(cmd.prefix, version);
dest = path.join(ver, "cocos2d");
files = ["html", path.join("x", "include"), path.join("x", "java"), path.join("x", "script")];
try {
for (i = 0; i < files.length; i += 1) {
src = path.join(dest, files[i]);
logBuild("rm -r " + src, cmd.verbose);
wrench.rmdirSyncRecursive(src, true);
logBuild("mkdir " + src, cmd.verbose);
wrench.mkdirSyncRecursive(src);
}
} catch(e) {
logBuild("Error cleaning destination: " + dest, cmd.verbose);
logBuild(e, cmd.verbose);
}
// copy cocos2d-html5
dest = path.join(ver, "cocos2d", "html");
src = path.join(srcRoot, "web");
copyRecursive(src, dest, false, true);
// copy headers
dir = dest = path.join(ver, "cocos2d", "x", "include");
src = srcRoot;
copyGlobbed(src, dest, '*.h');
copyGlobbed(src, dest, '*.hpp');
copyGlobbed(src, dest, '*.msg');
copyGlobbed(src, dest, '*.inl');
/*
dest = path.join(dir, "bindings");
src = path.join(srcRoot, "js-bindings", "bindings");
copyGlobbed(src, dest, '*.h');
copyGlobbed(src, dest, '*.hpp');
dest = path.join(dir, "external");
src = path.join(srcRoot, "js-bindings", "external");
copyGlobbed(src, dest, '*.h');
copyGlobbed(src, dest, '*.msg');
*/
// remove unneeded
files = ["docs", "build", "tests", "samples", "templates", "tools",
path.join("plugin", "samples"), path.join("plugin", "plugins"), path.join("extensions", "proj.win32")];
for (i = 0; i < files.length; i += 1) {
wrench.rmdirSyncRecursive(path.join(dir, files[i]), true);
}
// jsb
dest = path.join(ver, "cocos2d", "x", "script");
src = path.join(srcRoot, "cocos", "scripting", "js-bindings", "script");
copyGlobbed(src, dest, '*.js');
/*
src = path.join(srcRoot, "js-bindings", "bindings", "auto", "api");
copyGlobbed(src, dest, '*.js');
*/
// java
dir = path.join(ver, "cocos2d", "x", "java");
dest = path.join(dir, "cocos2d-x");
src = path.join(srcRoot, "cocos", "platform", "android", "java");
copyRecursive(src, dest);
// .mk and .a
dest = path.join(dir, "mk");
src = path.join(cmd.prefix, "src");
copyGlobbed(src, dest, "*.mk");
copyGlobbed(src, path.join(ver, "cocos2d", "x", "lib", "Debug-Android"), "*.a", "android", 1);
copyGlobbed(src, path.join(ver, "cocos2d", "x", "lib", "Release-Android"), "*.a", "android", 1);
/*
src = path.join(srcRoot, "js-bindings");
copyGlobbed(src, dest, "*.mk");
copyGlobbed(src, dest, "*.a", "android");
*/
// # bonus: call android/strip on mk/*.a
files = ["proj.android", "cocos2d-js", path.join("cocos2d-x", "tools"), path.join("cocos2d-x", "templates"), path.join("cocos2d-x", "tests")];
for (i = 0; i < files.length; i += 1) {
wrench.rmdirSyncRecursive(path.join(dest, files[i]), true);
}
files = glob.sync(path.join(dir, "*", "bin"));
for (i = 0; i < files.length; i += 1) {
wrench.rmdirSyncRecursive(files[i], true);
}
files = glob.sync(path.join(dir, "*", "gen"));
for (i = 0; i < files.length; i += 1) {
wrench.rmdirSyncRecursive(files[i], true);
}
// find ${dir} | xargs xattr -c >> ${logFile} 2>&1
// symlink latest -> version
dest = path.join(cmd.prefix, "latest");
try {
fs.unlinkSync(dest);
} catch(e) {
logErr("Error deleting symlink: " + e);
}
try {
fs.symlinkSync(version, dest/*, "dir"*/);
} catch(e) {
logErr("Error creating symlink: " + e);
}
callback();
};
//
// run the prebuild command
//
var runPrebuild = function(platform, config, arch, callback) {
config = "";
arch = "";
if (platform === "headers") {
callback();
} else if (process.platform === "darwin") {
if (platform === "ios") {
prebuildMac("iOS", config, arch, function(){
callback();
});
} else if (platform === "mac") {
prebuildMac("Mac", config, arch, function(){
callback();
});
} else if (platform === "android") {
if ("NDK_ROOT" in process.env) {
prebuildAndroid(config, arch, function(){
callback();
});
} else {
logBuild("Android build cancelled. You need to setup additional programs to develop for Android. See the Android README on RapidGame's Github page.", true);
callback();
}
} else {
prebuildMac("Mac", config, arch, function(){
prebuildMac("iOS", config, arch, function(){
// Sam: See comments below for why this check is here.
if ("NDK_ROOT" in process.env) {
prebuildAndroid(config, arch, function(){
callback();
});
} else {
logBuild("Android build cancelled. You need to setup additional programs to develop for Android. See the Android README on RapidGame's Github page.", true);
callback();
}
});
});
}
} else if (process.platform === "win32") {
if (platform === "android") {
// Sam: All Cygwin terminals add TERM to their environment variables.
// Even though the value might vary ('cygwin' or 'xterm'), we can
// reasonably assume that someone running RapidGame in a shell with
// TERM as an environment variable is using Cygwin. Windows does
// not using this variable, which is why this check is used. The
// same check is applied when prebuilding without any arguments
// (see a few lines below).
if ("TERM" in process.env) {
// Sam: We can assume that if the user has setup NDK_ROOT, they
// have also setup everything else needed to prebuild the Android
// libraries. If they happen to have NDK_ROOT set but not everything
// else, they will still get an error when trying to prebuild the
// Android libraries, but it won't be as helpful.
if ("NDK_ROOT" in process.env) {
prebuildAndroid(config, arch, function(){
callback();
});
} else {
logBuild("Android build cancelled. You need to setup additional programs to develop for Android. See the Android README on RapidGame's Github page.", true);
callback();
}
} else {
// Sam: User reaches here only if they are on Windows and they specifically run `rapidgame prebuild android`
logBuild("Build cancelled. You must prebuild the Android libraries in a Cygwin shell.", true);
callback();
}
}
else if (platform === "windows") {
prebuildWin(config, arch, function(){
callback();
});
}
else {
if ("TERM" in process.env) {
prebuildWin(config, arch, function(){
prebuildAndroid(config, arch, function(){
callback();
});
});
} else {
prebuildWin(config, arch, function(){
callback();
});
}
}
} else {
logBuild("No prebuild command written for " + process.platform + " yet", true);
}
};
//
// prebuild mac
//
var prebuildMac = function(platform, config, arch, callback) {
var i, j, k,
sdks = (platform === "Mac" ? ["macosx"] : ["iphoneos", "iphonesimulator"]),
configs = (config ? [config] : (cmd.minimal ? ["Debug"] : ["Debug", "Release"])),
projs = ["cocos2dx-prebuilt"];
// create builds array
builds = [];
for (i = 0; i < configs.length; i += 1) {
for (j = 0; j < sdks.length; j += 1) {
for (k = 0; k < projs.length; k += 1) {
builds.push([configs[i], sdks[j], projs[k]]);
}
}
}
nextBuild(platform, callback);
};
//
// prebuild android
//
var prebuildAndroid = function(config, arch, callback) {
var i, j,
configs = (config ? [config] : (cmd.minimal ? ["Debug"] : ["Debug", "Release"])),
archs = (cmd.minimal ? ["armeabi"] : ["armeabi", "armeabi-v7a", "x86"]);
// create builds array
builds = [];
if (process.platform === "win32") {
if (cmd.minimal) {
if (cmd.nostrip) {
builds.push(["non-stripped minimal (Debug armeabi)"]);
} else {
builds.push(["minimal (Debug armeabi)"]);
}
} else {
if (cmd.nostrip) {
builds.push(["non-stripped libraries for all platforms"]);
} else {
builds.push(["libraries for all platforms"]);
}
}
} else {
for (i = 0; i < configs.length; i += 1) {
for (j = 0; j < archs.length; j += 1) {
if (cmd.nostrip) {
builds.push([configs[i], archs[j], "nostrip"]);
} else {
builds.push([configs[i], archs[j]]);
}
}
}
}
nextBuild("Android", callback);
};
//
// prebuild windows
//
var prebuildWin = function(config, arch, callback) {
var i, j, command, targets, args, projs = [],
base = path.join(cmd.prefix, "src", "cocos2d-x"),
configs = (config ? [config] : (cmd.minimal ? ["Debug"] : ["Debug", "Release"]));
// set VCTargetsPath
// (overcome error MSB4019: The imported project "C:\Microsoft.Cpp.Default.props" was not found.)
process.env["VCTargetsPath"] = vcTargetsPath;
// manually add bindings projects
//projs = glob.sync(path.join(base, "cocos", "scripting", "js-bindings", "proj.win32", "*.vcxproj")) || [];
// create builds
builds = [];
for (i = 0; i < configs.length; i += 1) {
command = msBuildExePath;
//targets = ["libcocos2d", "libjscocos2d", "libbox2d", "libbullet", "librecast", "libSpine"];
targets = ["libcocos2d", "libjscocos2d"];
args = [
path.join(base, "build", "cocos2d-js-win32.sln"),
"/nologo",
"/maxcpucount:4",
"/t:" + targets.join(";"),
//"/p:VisualStudioVersion=12.0",
//"/p:PlatformTarget=x86",
//"/verbosity:diag",
//"/clp:ErrorsOnly",
//"/p:nowarn=4005",
//'/p:WarningLevel=0',
"/p:configuration=" + configs[i] + ";platform=Win32"
];
// main solution
builds.push([configs[i], command, args, projs.length == 0 ? linkWin : false]);
// additional projects
for (j = 0; j < projs.length; j+=1) {
args = [
projs[j],
"/nologo",
"/maxcpucount:4",
"/p:configuration=" + configs[i]
];
builds.push([configs[i], command, args, (j == projs.length - 1) ? linkWin : false]);
}
}
// start
nextBuild("Windows", callback);
};
//
// launch the next build
//
var nextBuild = function(platform, callback){
if (builds.length) {
startBuild(platform, callback, builds.shift());
} else {
callback();
}
};
//
// start a given build
//
var startBuild = function(platform, callback, settings) {
var dir, command, args, config, sdk, proj, arch, targets, archSettings = [], xcodeSettings = [];
if (platform === "iOS" || platform === "Mac") {
config = settings[0];
sdk = settings[1];
proj = settings[2];
command = "xcodebuild";
dir = path.join(cmd.prefix, "src", "proj.ios_mac");
xcodeSettings = ["GCC_SYMBOLS_PRIVATE_EXTERN=NO"];
if (!cmd.nostrip) {
xcodeSettings.push("DEPLOYMENT_POSTPROCESSING=YES");
xcodeSettings.push("STRIP_INSTALLED_PRODUCT=YES");
xcodeSettings.push("STRIP_STYLE=non-global");
}
if (cmd.minimal) {
archSettings = (sdk === "iphoneos" ? ["-arch", "armv7"] : ["-arch", "i386"]);
} else if (sdk === "iphonesimulator") {
// why doesn't this force the iphonesimulator builds to have both i386 and x86_64?
// is one of them being stripped away?
//archSettings = ["-arch", "x86_64", "-arch", "i386"]
archSettings = ["-arch", "x86_64"]
}
args = [
"-project", path.join(dir, proj + ".xcodeproj"),
"-scheme", platform,
"-configuration", config,
"-sdk", sdk
];
args = args.concat(archSettings);
args = args.concat(xcodeSettings);
} else if (platform === "Android") {
dir = path.join(cmd.prefix, "src", "proj.android");
command = path.join(dir, "build.sh");
config = settings[0];
arch = settings[1];
args = [
arch,
config
];
if (process.platform === "win32") {
command = "make";
if (cmd.minimal) {
args = cmd.nostrip ? ["minimal-nostrip"] : ["minimal"];
} else {
args = cmd.nostrip ? ["nostrip"] : [];
}
}
} else if (platform === "Windows") {
dir = cmd.prefix;
command = settings[1];
args = settings[2];
settings[1] = "";
settings[2] = path.basename(args[0]);
}
logBuild("Building " + platform + " " + settings[0] +
(settings[1] ? " " + settings[1] : "") +
(settings[2] ? " " + settings[2] : "") + "...", true);
spawn(command, args, {cwd: dir, env: process.env}, function(err){
var onFinished = function(){
logBuild("Succeeded.", true);
nextBuild(platform, callback);
};
if (!err){
if (typeof settings[3] === "function") {
settings[3](settings[0], onFinished);
} else {
onFinished();
}
} else {
if (!cmd.verbose) {
console.log("Build failed. Please run with --verbose or check the build log: " + cmd.buildLog);
}
}
});
};
//
// link windows
//
var linkWin = function(config, callback) {
var i, src,
srcRoot = path.join(cmd.prefix, "src", "cocos2d-x"),
libDir = path.join(srcRoot, "build", config + ".win32"),
options = {
cwd: cmd.prefix,
env: process.env
},
dest = path.join(cmd.prefix, version, "cocos2d", "x", "lib", config + "-win32", "x86"),
command = '"' + libExePath + '" ' +
'/NOLOGO ' +
'/IGNORE:4006 ' +
//'/OPT:REF ' +
//'/OPT:ICF ' +
'/OUT:"' + path.join(dest, "libcocos2dx-prebuilt.lib") + '"';
// make output dir
wrench.mkdirSyncRecursive(dest);
// copy dlls and finish creating command
//copyGlobbed(path.join(srcRoot, "external", "lua", "luajit", "prebuilt", "win32"), dest, "*.dll");
copyGlobbed(libDir, dest, "*.dll");
copyGlobbed(libDir, dest, "glfw3.lib"); // possibly because of the new duplicate -2015.lib files, this is necessary...
copyGlobbed(libDir, dest, "glfw3-2015.lib");
copyGlobbed(libDir, dest, "libchipmunk.lib");
copyGlobbed(libDir, dest, "libchipmunk-2015.lib");
copyGlobbed(libDir, dest, "libjpeg.lib");
copyGlobbed(libDir, dest, "libjpeg-2015.lib");
copyGlobbed(libDir, dest, "libpng.lib");
copyGlobbed(libDir, dest, "libpng-2015.lib");
copyGlobbed(libDir, dest, "libtiff.lib");
copyGlobbed(libDir, dest, "libtiff-2015.lib");
command += ' "' + path.join(libDir, "*.lib") + '"';
// move unneeded file(s)
try {
// this must be done because both of these libpng.lib files contain pngwin.res and lib.exe errors with LNK1241
// (consider instead using /REMOVE option: https://msdn.microsoft.com/en-us/library/0xb6w1f8.aspx)
fs.renameSync(path.join(libDir, "libpng-2015.lib"), path.join(libDir, "libpng-2015.duplicate-lib"));
} catch(e) {
}
// execute
exec(command, options, function(err){
if (!err) {
callback();
} else {
logBuild(err, true);
}
});
};
//
// Get paths to needed tools.
//
var getToolPaths = function(callback) {
if (process.platform === "win32") {
getMSBuildPath(function(success){
if (!success) {
callback(false);
return;
}
getLibExePath(function(success){
if (!success) {
callback(false);
return;
}
getVCTargetsPath(function(success){
callback(success);
});
});
});
} else {
callback(true);
}
};
//
// get the ms build tools path
//
var getMSBuildPath = function(cb) {
var Winreg = require("winreg"),
root = '\\Software\\Microsoft\\MSBuild\\ToolsVersions',
regKey,
savePath = path.join(cmd.prefix, "msbuildpath.txt"),
callback = function() {
if (fileExists(msBuildExePath)) {
try{
fs.writeFileSync(savePath, msBuildExePath).toString().trim();
} catch (e) {
}
logBuild("MSBUILD: " + msBuildExePath, true);
cb(true);
} else {
console.log("Unable to locate MSBuild.exe. Please set the contents of the following file to the absolute path to MSBuild.exe:\n\n\t" + savePath + "\n\nExample: C:\\Path\\to\\MSBuild.exe");
cb();
}
};
// try to load saved path
try{
msBuildExePath = fs.readFileSync(savePath).toString().trim();
if (msBuildExePath.length > 0) {
callback();
return;
}
} catch(e) {
}