-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathupdate.php
More file actions
1611 lines (1369 loc) · 48.2 KB
/
update.php
File metadata and controls
1611 lines (1369 loc) · 48.2 KB
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
#!/bin/env php
<?php
chdir(__DIR__);
error_reporting(-1);
setlocale(LC_ALL, 'en_US.UTF-8');
date_default_timezone_set('UTC');
set_error_handler(function ($severity, $msg, $file, $line) {
throw new ErrorException($msg, 0, $severity, $file, $line);
}, -1);
define('WINDOWS', !strncasecmp(PHP_OS, 'win', 3));
if (WINDOWS) {
// Needed for minify() (minify, Node), do_wav2ogg() (oggenc2).
putenv('PATH='.getenv('PATH').';'.__DIR__.'\\tools');
}
if (count($argv) > 1) {
$targets = [
'databank' => 'd',
'tutorial' => 't',
'maps' => 'm',
];
foreach (get_defined_functions()['user'] as $func) {
strncmp($func, 'do_', 3) or $targets += [substr($func, 3) => false];
}
$arg = $argv[1];
if ($arg === '-h' or $arg === '/?') {
// Help, help...
} elseif (count($argv) === 2 and
(isset($targets[$target = strtolower($arg)]) or
$target = array_search($target, $targets, true))) {
$SKIP_PENDING = true;
exit((int) !call_user_func("do_$target"));
} elseif (count($argv) <= 3 and in_array($arg, ['min', 'minify'])) {
exit((int) !minify($argv[2] ?? null));
} elseif (file_exists($arg)) {
exit((int) !h3m2herowo($arg, array_slice($argv, 2)));
} else {
printf('Unrecognized arguments: %s%s',
join(', ', array_slice($argv, 1)), PHP_EOL);
printf(PHP_EOL);
}
$ds = DIRECTORY_SEPARATOR;
echo <<<ECHO
Interactively update everything:
update.php
Show this help text:
update.php -h | /?
Interactively update specific target, ignoring prerequisites:
update.php TARGET
Convert specific HoMM 3 map to maps$ds:
update.php MAP.H3M|DIR/ [-options of h3m2herowo.php | -h]
Minify CSS and JS resources for game client:
update.php min[ify] [/]
Useful h3m2herowo.php -options (give -h for all):
-s CHARSET iconv charset for H3M strings; give -h to see allowed values
-ei ignore maps that couldn't convert, try to convert everything
-ew fail on any warning
-nx do nothing for already converted maps
-w [MS] watch mode: convert again when input map has changed
Valid TARGET and their short aliases:
ECHO;
foreach ($targets as $target => $short) {
printf(' %1s %s%s', $short, $target, PHP_EOL);
}
exit(2);
}
// This script doesn't check writability of directories and files because it
// depends on local set-up and because update.php is mostly meant for local
// development.
//
// In production, you'd want these to be writable:
// * log/ - nginx' access_log/error_log, if not storing in /var/log
// * maps/ - if allowing user map uploads via maps.php
// * tmp/ - PHP's sys_temp_dir, suggested on a zram mount
//
// Additionally, if hosting a HeroWO WebSocket server:
// * core/server/websocket-repl.log
// * replays/ -replays
// * reports/ --report-directory
if (checkPhpExtensions() and
printf(PHP_EOL) and
checkSubmodules() and
printf(PHP_EOL) and
createFolders() and
printf(PHP_EOL) and
checkDiskSpace() and
printf(PHP_EOL) and
writeApiConfig() and
printf(PHP_EOL) and
convertH3Data() and
printf(PHP_EOL) and
removeTemporary() and
$finished = true) {
$url = '';
if (isXAMPP()) {
$root = substr(php_ini_loaded_file(), 0, 2).'\\xampp\\htdocs\\';
if (!strncasecmp(__DIR__, $root, strlen($root))) {
$url = sprintf(PHP_EOL.'| %-57s |',
'http://127.0.0.1/'.strtr(substr(__DIR__, strlen($root)), '\\', '/').'/core/');
}
}
echo <<<ECHO
___________________________________________________________
| |
| HeroWO Workbench Initialized Successfully |
| Open core/index.php in your web browser to start the game |$url
|___________________________________________________________|
ECHO;
}
if (WINDOWS and !config('ignorePause')) {
printf(PHP_EOL);
printf('Press Enter to close this window');
readSTDIN();
}
exit(empty($finished) ? 3 : 0);
function readSTDIN() {
$s = fgets(STDIN);
$s === false and exit(-1); // Ctrl+C
return $s;
}
function folders($flag = null) {
$folders = [
// databank.php outputs here.
'databanks' => ['create' => true],
// maps.php outputs here. api.php reads from here.
'maps' => ['create' => true],
// User places H3bitmap.lod content here.
'BMP' => ['create' => true, 'remove' => true],
// User places H3sprite.lod content here.
'DEF' => ['create' => true, 'remove' => true],
// User places Heroes3.snd content here.
'WAV' => ['create' => true, 'remove' => true],
'WAV-PCM' => ['remove' => true],
// User places content of game's MP3\ folder here
'MP3' => ['create' => true],
// User places HoMM 3 maps for convertion here.
'H3M' => ['create' => true],
// User places DefPreview output here.
'DEF-extracted' => ['create' => true, 'remove' => true],
'BMP-PNG' => [],
'DEF-PNG' => [],
'TXT-en' => [],
'WAV-OGG' => [],
// The following are not currently handled by update.php (see do_bik()).
'BIK-APNG' => [],
'BIK-WAV-OGG' => [],
'CDROM-BIK-WAV-OGG' => [],
];
if (func_num_args()) {
if ($flag) {
$folders = array_filter($folders, function ($folder) use ($flag) {
return !empty($folder[$flag]);
});
}
return array_keys($folders);
} else {
return $folders;
}
}
function folderSize($path) {
static $blksizeOverride;
if ($blksizeOverride === null) {
$blksizeOverride = config('blksize') ?: false;
}
$res = 0;
if (file_exists($path)) {
foreach (scandir($path, SCANDIR_SORT_NONE) as $file) {
if ($file === '.' or $file === '..') {
continue;
}
try {
$stat = stat($full = "$path/$file");
} catch (Throwable $e) {
continue;
}
if ($stat['mode'] & 0x4000) {
$res += folderSize($full);
} elseif ($stat['mode'] & 0x8000) {
// blksize is -1 on Windows so using 4K (default NTFS cluster size).
$blksize = $blksizeOverride === false
? $stat['blksize'] >= 512 ? $stat['blksize'] : 4096
: $blksizeOverride;
$res += ceil($stat['size'] / $blksize) * $blksize;
}
}
}
return $res;
}
function config($key = null, $value = null) {
static $config;
if ($config === null) {
try {
is_file('config.php') and $config = include('config.php');
} catch (Throwable $e) {}
is_array($config) or $config = [];
}
if ($key === null) {
return $config;
} elseif (func_num_args() < 2) {
return $config[$key] ?? null;
} else {
$config[$key] = $value;
writeFile('config.php', "<?php\nreturn ".var_export($config, true).';');
return $value;
}
}
function writeFile($path, $data) {
try {
file_put_contents($path, $data, LOCK_EX);
} catch (Throwable $e) {
printf(PHP_EOL);
printf('=> Looks like %s%s is not writable. The error message was:%s',
getcwd().DIRECTORY_SEPARATOR, $path, PHP_EOL);
printf(' %s%s', trim($e->getMessage()), PHP_EOL);
exit(1);
}
}
function currentDatabank() {
require_once 'core/api.php';
return keyValue('databank');
}
function isXAMPP() {
return stripos(php_ini_loaded_file(), '\\xampp\\php\\php.ini') !== false;
}
function checkPhpExtensions() {
$extensions = [
'gd' => 'convert HoMM 3 images',
'hash' => false,
'iconv' => 'convert HoMM 3 maps (.h3m)',
'json' => false,
'mbstring' => 'generate databanks (databank.php)',
'pdo' => 'store web configuration (index.php, api.php, maps.php, etc.)',
'pdo_sqlite' => 'provide default database engine for web configuration',
'zip' => 'upload and download maps (maps.php)',
'zlib' => 'convert HoMM 3 maps (.h3m), talk to remote server (api.php)',
];
$missing = [];
foreach ($extensions as $extension => $optional) {
checkPhpExtension($extension, $optional) or $missing[] = $extension;
}
$config = config('ignoreExtensions') ?: [];
$ignored = array_intersect($missing, $config);
$newMissing = array_values(array_diff($missing, $config));
if ($ignored) {
printf(PHP_EOL);
printf('Skipping previously ignored extensions: %s%s',
join(', ', $ignored), PHP_EOL);
}
if ($newMissing) {
printf(PHP_EOL);
printf('=> Some PHP extensions are missing:%s', PHP_EOL);
foreach ($newMissing as $i => $extension) {
printf(' % 2d. %s%s', $i + 1, $extension, PHP_EOL);
}
printf(PHP_EOL);
printf('You should enable missing extensions in PHP. Press Enter to exit.%s', PHP_EOL);
if ($ini = isXAMPP()) {
printf(PHP_EOL);
printf('Type "x" to try enabling them in XAMPP automatically.', PHP_EOL);
}
printf(PHP_EOL);
printf('Or type "yes" and press Enter if you wish to proceed anyway (may cause future errors).%s', PHP_EOL);
$s = trim(readSTDIN());
if ($ini and !strcasecmp($s, 'x')) {
$ini = file_get_contents(php_ini_loaded_file());
array_unshift($newMissing, "\r\n# Enabled by HeroWO/update.php:");
$ini .= join("\r\nextension=", $newMissing);
writeFile(php_ini_loaded_file(), $ini);
run([true, __FILE__]);
}
if (stripos($s, 'yes') === false) {
return;
}
config('ignoreExtensions', array_merge($config, $newMissing));
}
return true;
}
function checkPhpExtension($extension, $optional = false) {
printf('PHP extension %s required to %s ... ',
$extension, $optional ?: 'operate');
if (extension_loaded($extension)) {
return printf('found%s', PHP_EOL);
} else {
printf('MISSING%s', PHP_EOL);
}
}
function checkSubmodules() {
$submodules = [
'core' => 'index.php',
'core/client/nodash' => 'nodash.min.js',
'core/client/PathAnimator' => 'pathAnimator.js',
'core/client/r.js' => 'require.js',
'core/client/sqimitive' => 'sqimitive.min.js',
'core/databank/h3m2json' => 'h3m2json.php',
'core/Phiws' => 'Phiws/BaseTunnel.php',
'core/noXXXep' => 'noXXXep.php',
'core/source-map' => 'source-map.js',
];
$missing = false;
foreach ($submodules as $path => $file) {
$missing |= $thisMissing = !is_file("$path/$file");
printf('Submodule %s ... %s%s', strtr($path, '/', DIRECTORY_SEPARATOR),
$thisMissing ? 'MISSING' : 'found', PHP_EOL);
}
if ($missing) {
printf(PHP_EOL);
printf('=> Some parts of this repository are missing. Clone it again with --recurse-submodules enabled and try again.');
}
return !$missing;
}
function createFolders() {
$failed = false;
foreach (folders('create') as $path) {
if (!is_dir($path)) {
$status = 'CREATING';
} elseif ($failed |= !is_writable($path)) {
$status = 'NOT WRITABLE';
} else {
$status = 'found';
}
printf('Folder %s ... %s%s', $path, $status, PHP_EOL);
try {
is_dir($path) or mkdir($path, 0755, true);
} catch (Throwable $e) {
$failed |= 2;
printf(PHP_EOL);
printf('=> Could not create %s%s. The error message was:%s',
getcwd().DIRECTORY_SEPARATOR, $path.DIRECTORY_SEPARATOR, PHP_EOL);
printf(' %s%s', trim($e->getMessage()), PHP_EOL);
continue;
}
}
if ($failed > 1) {
printf(PHP_EOL);
printf('=> Some folders are not writable.%s', PHP_EOL);
}
return !$failed;
}
function checkDiskSpace() {
printf('Checking available disk space ... ');
if (config('ignoreDiskSpace')) {
printf('DISABLED%s', PHP_EOL);
} elseif (config('diskSpaceCheck') > time()) {
printf('DID RECENTLY%s', PHP_EOL);
} else {
// DEF-extracted takes up ~6.5 GiB. Files needed for game client ~1 GiB.
// Also converted official H3M maps 11+ GiB.
$min = 20 * 2 ** 30;
$diskFree = disk_free_space('.');
$used = $diskFree < $min
? array_sum(array_map('folderSize', folders(null))) : null;
$free = $diskFree + $used;
printf('%s MiB free %s(%s)%s', number_format($diskFree / 2 ** 20),
isset($used) ? sprintf('+ %s MiB in Workbench ', number_format($used / 2 ** 20)) : '',
$free < $min ? 'NOT ENOUGH' : 'good', PHP_EOL);
if ($free < $min) {
printf(PHP_EOL);
printf('=> Not enough disk space for initial convertion (need %.1f GiB). Press Enter to exit, then free up at least %.1f GiB and try again.%s',
$min / 2 ** 30, ($min - $used) / 2 ** 30, PHP_EOL);
printf(PHP_EOL);
printf('Or type "yes" and press Enter if you wish to proceed anyway (may cause future errors).%s', PHP_EOL);
printf(PHP_EOL);
printf('Note: most of that (11+ GiB) is taken by converted maps. Enabling file system compression on the below folder will save you 90% of needed disk space. Continue if you\'ve done that.%s', PHP_EOL);
printf(PHP_EOL);
printf('%s%s', __DIR__.DIRECTORY_SEPARATOR.'maps', PHP_EOL);
if (WINDOWS) {
printf(PHP_EOL);
printf('Open Windows Explorer, Properties of the above folder, click Advanced (General tab), tick "Compress contents to save disk space", click OK, OK again, select "Apply changes to the folder, subfolders and files" and finally OK.%s', PHP_EOL);
}
$s = readSTDIN();
if (stripos($s, 'yes') === false) {
return;
}
config('ignoreDiskSpace', true);
}
// Calculating size of a large directory takes a few seconds so do it once
// in a while.
isset($used) and config('diskSpaceCheck', time() + 180);
}
return true;
}
function writeApiConfig() {
$found = is_file($file = 'core/api-db.php');
printf('API config file (%s) ... %s%s', $file, $found ? 'found' : 'CREATING', PHP_EOL);
if (!$found) {
writeFile($file, "<?php return new PDO('sqlite:'.__DIR__.'/../api.sqlite');");
}
printf(PHP_EOL);
require_once 'core/api.php';
printf('API config values ... %s%s', pdo()->getAttribute(PDO::ATTR_DRIVER_NAME), PHP_EOL);
$defaults = [
'maps' => ['maps', '../maps'],
'mapsURL' => ['maps/', '../maps/'],
'databanks' => ['databanks', '../databanks'],
'databanksURL' => ['databanks/', '../databanks/'],
];
$update = pdo()->prepare('UPDATE keyValues SET value = ? WHERE `key` = ? AND value = ?');
foreach ($defaults as $key => [$default, $value]) {
$old = keyValue($key);
$update->bindValue(1, $value);
$update->bindValue(2, $key);
$update->bindValue(3, $default);
$update->execute();
$current = keyValue($key);
if ($old !== $current) {
printf(' %s = %s (changed from the default %s)%s',
$key, $current, $default, PHP_EOL);
} elseif ($old === $value) {
printf(' %s = %s (good)%s', $key, $old, PHP_EOL);
} else {
printf(' %s = %s (should be %s, DIFFERENT)%s', $key, $old, $value, PHP_EOL);
}
}
return true;
}
function removeTemporary() {
$found = false;
foreach (folders('remove') as $path) {
$size = folderSize($path);
$found |= $thisFound = is_dir($path);
printf('Temporary folder %s ... %s%s', $path,
$thisFound ? sprintf('FOUND (%s)',
$size ? number_format($size / 2 ** 20).' MiB' : 'empty') : 'not found',
PHP_EOL);
}
if ($found and !config('ignoreTemporary')) {
printf(PHP_EOL);
printf('=> Initial convertion is finished. You can delete the folders listed above to reclaim disk space. However, if you plan to change game data later then you should keep them to avoid going all over the process again.%s', PHP_EOL);
printf(PHP_EOL);
printf(' Press Enter to continue');
readSTDIN();
config('ignoreTemporary', true);
}
return true;
}
function minify($urlPrefix = null) {
$minify = stripos(exec('minify --version', $output, $code), 'minify v') !== false && !$code;
$node = preg_match('/^v\\d+\\./', exec('node -v', $output, $code)) && !$code;
//$uglify = stripos(exec('uglifyjs -v', $output, $code), 'uglify-js') !== false && !$code;
printf('minify ... %s%s', $minify ? 'found' : 'MISSING', PHP_EOL);
printf('node ... %s%s', $node ? 'found' : 'MISSING', PHP_EOL);
//printf('uglifyjs ... %s%s', $uglify ? 'found' : 'MISSING', PHP_EOL);
if (!$minify) {
printf(PHP_EOL);
printf('=> minify is required: %s%s', 'https://github.com/tdewolff/minify/releases', PHP_EOL);
printf(PHP_EOL);
printf(WINDOWS ? " Download the latest release and put minify.exe into Workbench' tools.%s" : ' Install minify using your package manager.%s', PHP_EOL);
}
if (!$node) {
printf(PHP_EOL);
printf('=> Node.js is required.');
if (WINDOWS) {
printf(" Either install it from https://nodejs.org or download this to Workbench' tools:%s", PHP_EOL);
printf(' %s%s', 'https://nodejs.org/dist/latest/win-x86/node.exe', PHP_EOL);
} else {
printf(' Install nodejs using your package manager.%s', PHP_EOL);
}
}
//if (!$uglify) {
// printf(PHP_EOL);
// printf('=> uglifyjs is required. Install uglify-js using npm or install uglifyjs using your package manager.%s', PHP_EOL);
//}
if (!$minify or !$node /*or !$uglify*/) {
return;
}
printf(PHP_EOL);
$ok = true;
$databank = 'databanks/'.currentDatabank();
// Used by core/exception.php.
run(['git', '-C', 'core', 'rev-parse', '--verify', 'HEAD'],
['>'.escapeshellarg("$databank/revision.txt")]);
$ok &= run(['node', 'core/client/r.js/dist/r.js', '-o', 'build.js',
"out=$databank/herowo.min.js"]);
$minify = ['minify', '--css-precision', 3, '-o'];
// There was a change in behaviour in some recent version: previously, -o
// produced a concatenated file, now it creates a folder given multiple files.
exec('minify 2>&1 -b', $output, $code);
$code === 1 and array_splice($minify, 3, 0, '-b');
$cmd = $minify;
$cmd[] = $output = "$databank/herowo.min.css";
$cmd[] = "$databank/menu.css";
$cmd[] = 'core/herowo.css';
// This must match minified CSS too.
$re = '~@import "([/\\w-]+\\.css)";~u';
preg_match_all($re, file_get_contents('core/herowo.css'), $import);
foreach ($import[1] as $file) {
$cmd[] = "core/$file";
}
$ok &= run($cmd);
// XXX=R At this moment core styles assume the parent directory is the
// Workbench and use references like url(../BMP-PNG/...). Replacing them.
//
// XXX=R Also replacing references to core/custom-graphics as if
// custom-graphics was part of the Workbench (i.e. the server with statics).
// For now, on a development system a symlink or web server rewrite rule has
// to be set up for this folder (unless you just copy it of course).
$folders = join('|', array_map(function ($s) {
return preg_quote($s, '~');
}, folders(null)));
$re2 = '~
(
\\b url \\(
[\'"]?
)
(?:
\\.\\./ ('.$folders.')
| (custom-graphics)
)
/
~xu';
writeFile($output, preg_replace([$re, $re2], ['', '$1../../$2$3/'],
file_get_contents($output)));
foreach (glob('databanks/*/combined.css', GLOB_NOSORT | GLOB_ERR) as $file) {
$cmd = $minify;
$cmd[] = $file;
$cmd[] = $file;
$ok &= run($cmd);
}
if (isset($urlPrefix)) {
// XXX combined.json includes audio.json that uses -au but not processing
// this file here because databankURL() doesn't recognized absolute URLs.
$mask = 'databanks/*/{combined.css,herowo.min.css}';
foreach (glob($mask, GLOB_NOSORT | GLOB_BRACE | GLOB_ERR) as $file) {
writeFile($file, str_replace('../../', $urlPrefix, file_get_contents($file)));
}
}
// Could run minify on combined.json but it's already minimal.
if ($ok) {
printf(PHP_EOL);
printf('Finished. %s%s', isset($urlPrefix) ? "URLs were rewritten to $urlPrefix." : 'Give ?d to index.php to start client in production mode.', PHP_EOL);
printf('Use optimize-png.sh to make images smaller in production.%s', PHP_EOL);
}
return $ok;
}
// You can perform the following by hand to achieve the effect of this script
// (stars mark optional steps whose results are already part of the Core or
// Workbench repository):
//
// 1. Run MMArchive, extract H3bitmap.lod to BMP
// 2. Run MMArchive, extract H3sprite.lod to DEF
// 3. Run MMArchive, extract Heroes3.snd to WAV
// 4. If converting data of a non-English HoMM 3:
// run MMArchive, extract *.txt from H3bitmap.lod to TXT-en
// 5. Copy content of MP3 folder from the game's folder to MP3 in Workbench
// 6. Copy content of Maps folder from the game's folder to H3M in Workbench
// * 7. Generate custom DEFs:
// a. cd custom-graphics\DEF ; php gen.php (correct paths in the template)
// b. Run H3DefTool, open each HDL, press Make Def
// c. Copy produced DEFs to DEF
// 8. Run DefPreview, call these commands on each DEF in DEF\ in order
// (output to DEF-extracted; can automate using the provided AHK script):
// a. Extract All for DefTool
// b. Extract Picture(s)
// c. Export Defmaker DefList
// * 9. Use Photoshop or another tool to convert each frame (bitmap) in
// CRADVNTR.DEF, CRCOMBAT.DEF and CRDEFLT.DEF to .cur; output to
// core\custom-graphics\DEF-CUR (\CRADVNTR\CursrA00.cur, etc.)
// *10. cur-hotspot.php DEF-CUR\CRADVNTR
// cur-hotspot.php DEF-CUR\CRCOMBAT
// cur-hotspot.php DEF-CUR\CRDEFLT
// *11. CMNUMWIN2png.php BMP\CMNUMWIN.BMP core\custom-graphics\CMNUMWIN
// 12. bmp2png.php BMP BMP-PNG
// *13. Run potrace to generate .geojson from BMPs as described in bmp2shape.php
// *14. bmp2shape.php -b BMP -g BMP-geojson -o core\databank\shapes.json
// 15. def2png.php DEF-extracted DEF-PNG -p BMP\PLAYERS.PAL -b BMP-PNG
// 16. Run adpcm2pcm on each WAV (output to WAV-PCM)
// 17. Run oggenc or oggenc2 on each WAV-PCM (output to WAV-OGG)
// 18. Generate databank:
// php -d memory_limit=1G
// databank.php -p -t BMP -g core/databank/shapes.json
// -d DEF-PNG -du ../../DEF-PNG/
// -a MP3 -a WAV-OGG -au ../../
// -b BMP-PNG/bitmap.css -bu ../../BMP-PNG/
// -v sod databanks
// If converting data of a non-English HoMM 3, add:
// -s CHARSET -ti TXT-en
// 19. Generate maps (add -s LANG to both if needed):
// php h3m2herowo.php -d databanks/sod -M -ih H3M/Tutorial.tut maps
// php -d memory_limit=3G h3m2herowo.php -d databanks/sod -M -ew H3M maps
//
// The above doesn't include APNG/OGG generation from BIK/SMK in Heroes3.vid or
// CD-ROM. Refer to Formats.txt on how to do that, and see do_bik().
//
// XXX Replace MMArchive with the console LodTool, feeding it a script like:
// load|...\H3bitmap.lod
// +|*
// export|...\BMP
function convertH3Data() {
// Stuff required by game client.
return !pending('bmp2png') and !pending('def2png') and !pending('mp3') and
!pending('wav2ogg') and !pending('databank') and !pending('maps') and
!pending('bik');
}
function checkFiles($base, array $expected) {
$missing = [];
foreach ($expected as $file) {
WINDOWS or $file = strtr($file, '\\', DIRECTORY_SEPARATOR);
is_file($base.$file) or $missing[] = $file;
}
$missing and printf('%s(...) ', trim(substr(join(' ', $missing), 0, 30), '(). '));
return !$missing;
}
function checkFileCopies($src, $srcExt, $dest, $destExt) {
if (is_dir($src)) {
$len = strlen($srcExt);
$missing = array_filter(
scandir($src, SCANDIR_SORT_NONE),
function ($file) use ($len, $src, $srcExt, $dest, $destExt) {
return !strcasecmp(substr($file, -$len), $srcExt) and
!is_file($dest.substr($file, 0, -$len).$destExt);
}
);
$missing and printf('%s(...) ', trim(substr(join(' ', $missing), 0, 30), '(). '));
}
return empty($missing);
}
function run(array $args, array $rawArgs = []) {
if ($silent = $args[0] === false) {
array_shift($args);
}
if ($php = $args[0] === true) {
$args[0] = PHP_BINARY;
}
$cmd = [];
foreach ($args as $arg) {
// Since we show constructed command line to the user, make it more pretty
// by removing redundant quotes around known-safe arguments.
$cmd[] = ltrim($arg, 'a..zA..Z.-') === '' ? $arg : escapeshellarg($arg);
}
$line = join(' ', array_merge($cmd, $rawArgs));
$sep = str_repeat('-', min(78, strlen($line))).PHP_EOL;
$silent or printf('Executing %s%s', $line, PHP_EOL);
$silent or printf($sep);
system($line, $code);
$silent or printf($sep);
if ($code) {
$silent and printf('Executed %s%s', $line, PHP_EOL);
printf(PHP_EOL);
// Skip php -d ...
for (; !strncmp(ltrim($cmd[$php] ?? '', '\'"'), '-', 1); $php += 1) ;
printf('=> %s exited with code %d. Check the above output and try again.%s',
$cmd[$php] ?? 'Command', $code, PHP_EOL);
}
return !$code;
}
function convertFolder($src, $srcExt, $dest, $destExt, array $cmd) {
foreach ($cmd as $i => $value) {
is_float($value) and is_nan($value) /*NAN*/ and $in = $i;
$value === INF and $out = $i;
}
is_dir($src) or mkdir($src);
$len = strlen($srcExt);
$first = true;
foreach (scandir($src, SCANDIR_SORT_NONE) as $file) {
if (!strcasecmp(substr($file, -$len), $srcExt)) {
$run = $cmd;
$run[$in] = "$src/$file";
$run[$out] = "$dest/".substr($file, 0, -$len).$destExt;
$first or array_unshift($run, false);
if (!run($run)) { return; }
$first = false;
}
}
//$input = null;
//$length = 0;
//
//foreach (scandir($dest, SCANDIR_SORT_NONE) as $file) {
// if (!strcasecmp(substr($file, -$len), $srcExt)) {
// $input or $input = $cmd;
// $length += 3 /*quotes/space*/ + strlen($input[] = "$dest/$file");
//
// // Windows' cmd.exe seems to impose a command line limit of about 8K.
// if ($length > 5000) {
// if (!run($input)) { return; }
// $input = null;
// $length = 0;
// }
// }
//}
//
//if (!run($input)) { return; }
return true;
}
function h3m2herowo($input, array $arguments = []) {
$cmd = array_merge(
[
true,
'-d memory_limit=3G',
'core/databank/h3m2herowo.php',
'-M',
$input,
'maps',
'-d', 'databanks/'.currentDatabank(),
'-s', config('charset'),
],
$arguments,
// -ew -s RU ...
config('h3m2herowo') ?? []
);
return run($cmd);
}
function pending($step) {
static $level = 0;
global $SKIP_PENDING;
if (empty($SKIP_PENDING)) {
printf('%sChecking for [%s] ... ', str_repeat(' ', $level++), $step);
try {
$done = call_user_func("done_$step");
printf('%s%s', $done ? 'found' : 'MISSING', PHP_EOL);
if (!$done) {
// 0 = task succeeded, 1 = failed.
return (int) !call_user_func("do_$step");
}
} finally {
$level--;
}
}
}
function done_bmp() {
// Several random files of each extension in H3bitmap.lod, in upper-case.
// PCX files are converted to BMP when extracted hence PCX is not included.
return checkFiles('BMP/', [
'BOTGA2H.BMP',
'HPS071DK.BMP',
'PUZFOR12.BMP',
'CRGEN1.TXT',
'BIGFONT.FNT',
'SECRET.H3C',
'PLAYERS.PAL',
'DEFAULT.XMI',
'H3SHAD.IFR',
]);
}
function do_bmp() {
$ds = DIRECTORY_SEPARATOR;
$bmp = __DIR__.DIRECTORY_SEPARATOR.'BMP';
echo <<<ECHO
=> 1. Run tools{$ds}MMArchive{$ds}MMArchive.exe
2. Call File > Open
3. Navigate to the folder with installed HoMM 3
4. Navigate to Data subfolder
5. Select H3bitmap.lod, then click Open
6. Click on any file name in the large list on the right (e.g. BIGFONT.FNT)
7. Press Ctrl+A to select everything
8. Call Edit > Extract To...
9. Navigate into BMP subfolder in Workbench (below), then click Save:
$bmp
10. Wait until MMArchive stops hanging
11. Run update.php again
ECHO;
}
// Non-TXTs in BMP/ are considered intermediate; if user supplies all
// non-intermediate files (e.g. BMP-PNG) then no need to ask for extracting
// H3bitmap.lod as long as text files are present.
function done_bmpTXT($dir = 'BMP') {
return checkFiles("$dir/", [
'GENRLTXT.TXT',
'CRBANKS.TXT',
'BLDGNEUT.TXT',
'HEROBIOS.TXT',
'SKILLLEV.TXT',
]);
}
function do_bmpTXT() {
return do_bmp();
}
function done_txtEn() {
return done_bmpTXT('TXT-en');
}
function do_txtEn() {
$ds = DIRECTORY_SEPARATOR;
$txt = __DIR__.DIRECTORY_SEPARATOR.'TXT-en';
is_dir($txt) or mkdir($txt);
echo <<<ECHO
Need original English text files to pair data of a localized HoMM 3 version.
=> 1. Run tools{$ds}MMArchive{$ds}MMArchive.exe
2. Call File > Open
3. Navigate to the folder with installed English (!) HoMM 3
4. Navigate to Data subfolder
5. Select H3bitmap.lod, then click Open
6. Optional: click on the extension filter under the menu and select ".txt"
7. Click on any file name in the large list on the right (e.g. ADVEVENT.TXT)
8. Press Ctrl+A to select everything
9. Call Edit > Extract To...
10. Navigate into TXT-en subfolder in Workbench (below), then click Save:
$txt
11. Run update.php again
ECHO;
}
function done_bmp2png() {
return checkFiles('BMP-PNG/', [
'bitmap.css',
'TRESBAR-blue.png',
'CRSTKPU-tan.png',
]) and checkFileCopies('BMP', '.bmp', 'BMP-PNG/', '.png');
}
function do_bmp2png() {
if (!pending('bmp')) {
return run([true, 'core/databank/bmp2png.php', 'BMP', 'BMP-PNG']);
}
}
function done_def() {
return checkFiles('DEF/', [
'CDEVIL.DEF',
'AH12_.MSK',
'MUBHOT.DEF',
'AVLR4SN0.MSK',
]);
}
function do_def() {
$ds = DIRECTORY_SEPARATOR;
$def = __DIR__.DIRECTORY_SEPARATOR.'DEF';
echo <<<ECHO
=> 1. Run tools{$ds}MMArchive{$ds}MMArchive.exe
2. Call File > Open
3. Navigate to the folder with installed HoMM 3
4. Navigate to Data subfolder
5. Select H3sprite.lod, then click Open
6. Click on any file name in the large list on the right (e.g. AB01_.DEF)
7. Press Ctrl+A to select everything
8. Call Edit > Extract To...
9. Navigate into DEF subfolder in Workbench (below), then click Save:
$def
10. Wait until MMArchive stops hanging
11. Run update.php again
ECHO;
}
function done_defCustom() {
return checkFileCopies('core/custom-graphics/DEF', '.def', 'DEF/', '.def');
}
function do_defCustom() {
foreach (scandir($path = 'core/custom-graphics/DEF') as $file) {
if (!strcasecmp(substr($file, -4), '.def')) {
copy("$path/$file", "DEF/$file");
}
}
return true;
}
function done_defExtracted() {
$res = checkDefExtracted();
if (!$res['missing'] and !$res['missing_t'] and !$res['missing_e'] and
!$res['missing_x']) {
array_map('unlink', $res['touched']);
return checkFiles('DEF-extracted/', [
'CPHX\CPHX.h3l',
'CPHX\CPHX.hdl',
'CPHX\cphx04.bmp',
'CPHX\Shadow\cphx66.bmp',