-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild.gradle.kts
More file actions
1841 lines (1669 loc) · 68.1 KB
/
build.gradle.kts
File metadata and controls
1841 lines (1669 loc) · 68.1 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
import groovy.json.JsonSlurper
import org.gradle.api.file.DuplicatesStrategy
import org.gradle.api.tasks.bundling.Zip
import org.gradle.api.tasks.testing.Test
import org.gradle.jvm.tasks.Jar
import org.gradle.jvm.toolchain.JavaToolchainService
import java.net.HttpURLConnection
import java.net.URL
import java.security.MessageDigest
import java.time.Instant
import java.util.Properties
plugins {
java
}
val jvnGroup = (findProperty("jvnGroup") as String?) ?: "com.jvn"
val jvnVersion = (findProperty("jvnVersion") as String?) ?: "0.1-SNAPSHOT"
group = jvnGroup
version = jvnVersion
val configuredJavaVersion = (findProperty("javaVersion") as String?)?.toIntOrNull() ?: 21
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(configuredJavaVersion))
}
}
val jvnToolchains = extensions.getByType<JavaToolchainService>()
val jvnPackagingLauncher = jvnToolchains.launcherFor {
languageVersion.set(JavaLanguageVersion.of(configuredJavaVersion))
}
data class JvnGameTarget(
val id: String,
val taskSuffix: String,
val javafxClassifier: String,
val windows: Boolean
)
data class JvnGameProjectValidation(
val dir: File,
val manifest: Properties,
val type: String,
val entryKey: String?,
val warnings: List<String>
)
data class JvnGamePackageHost(
val osId: String,
val target: JvnGameTarget,
val nativePackageTypes: List<String>,
val defaultNativePackageType: String
)
data class JvnBundledRuntimeSelection(
val target: JvnGameTarget,
val imageType: String,
val downloadUrl: String,
val checksum: String,
val checksumUrl: String?,
val archiveFile: File,
val runtimeDir: File,
val javaExecutableRelativePath: String
)
data class JvnBundledRuntimeAsset(
val imageType: String,
val downloadUrl: String,
val checksum: String,
val checksumUrl: String?
)
data class JvnReleaseProfile(
val name: String,
val file: File?,
val properties: Properties
) {
fun value(key: String): String? {
return listOf(
"profile.$name.$key",
"profile.default.$key",
key
).asSequence()
.mapNotNull { properties.getProperty(it)?.trim() }
.firstOrNull { it.isNotBlank() }
}
fun flag(key: String, default: Boolean = false): Boolean {
val raw = value(key) ?: return default
return raw.lowercase() !in setOf("", "0", "false", "no", "off")
}
fun commands(prefix: String): List<String> {
val roots = listOf("profile.$name.$prefix.", "profile.default.$prefix.")
val values = mutableMapOf<String, String>()
roots.forEach { root ->
properties.stringPropertyNames()
.filter { it.startsWith(root) }
.sortedBy { it.removePrefix(root) }
.forEach { key ->
val suffix = key.removePrefix(root)
val value = properties.getProperty(key)?.trim()
if (!value.isNullOrBlank()) values.putIfAbsent(suffix, value)
}
}
return values.toSortedMap().values.toList()
}
}
val jvnJavaFxVersion = "21.0.3"
val jvnJavaFxModules = listOf(
"javafx-base",
"javafx-graphics",
"javafx-controls",
"javafx-media",
"javafx-swing",
"javafx-fxml"
)
val jvnJavaFxRuntimeModules = listOf(
"javafx.controls",
"javafx.graphics",
"javafx.base",
"javafx.media",
"javafx.swing",
"javafx.fxml"
)
val jvnGameTargets = listOf(
JvnGameTarget("windows-x64", "WindowsX64", "win", true),
JvnGameTarget("linux-x64", "LinuxX64", "linux", false),
JvnGameTarget("macos-x64", "MacosX64", "mac", false),
JvnGameTarget("macos-aarch64", "MacosAarch64", "mac-aarch64", false)
)
val jvnGameRuntimeProjectPaths = listOf(
":core",
":fx",
":audio",
":scripting",
":swing",
":runtime",
":demo-game"
)
val jvnGameJavaFxConfigurations = mutableMapOf<String, org.gradle.api.artifacts.Configuration>()
fun currentGameTarget(): JvnGameTarget {
val osName = System.getProperty("os.name", "").lowercase()
val arch = System.getProperty("os.arch", "").lowercase()
return when {
osName.contains("win") -> jvnGameTargets.first { it.id == "windows-x64" }
osName.contains("linux") && (arch.contains("aarch64") || arch.contains("arm64")) ->
throw GradleException("Linux aarch64 portable builds are not supported by OpenJFX $jvnJavaFxVersion target classifiers.")
osName.contains("linux") -> jvnGameTargets.first { it.id == "linux-x64" }
osName.contains("mac") && (arch.contains("aarch64") || arch.contains("arm64")) ->
jvnGameTargets.first { it.id == "macos-aarch64" }
osName.contains("mac") -> jvnGameTargets.first { it.id == "macos-x64" }
else -> throw GradleException("Unsupported host OS/Arch for current portable target: $osName/$arch")
}
}
fun gameProjectDir(): File {
val raw = findProperty("jvnGameProject") as String?
if (raw.isNullOrBlank()) {
throw GradleException("Missing -PjvnGameProject=/absolute/path/to/jvn-game. Game packaging builds JVN-made projects, not the engine workspace.")
}
val dir = file(raw)
if (!dir.isDirectory) {
throw GradleException("JVN game project does not exist or is not a directory: ${dir.absolutePath}")
}
val manifest = File(dir, "jvn.project")
if (!manifest.isFile) {
throw GradleException("JVN game project is missing jvn.project: ${dir.absolutePath}")
}
return dir
}
fun gameManifest(): Properties {
val props = Properties()
val manifest = File(gameProjectDir(), "jvn.project")
manifest.inputStream().use { props.load(it) }
return props
}
fun gradleFlag(name: String): Boolean {
val raw = findProperty(name) as String?
return raw != null && raw.trim().lowercase() !in setOf("", "0", "false", "no", "off")
}
fun canonicalOrAbsolute(file: File): File {
return try {
file.canonicalFile
} catch (_: Exception) {
file.absoluteFile
}
}
fun normalizeProjectPath(raw: String?): String? {
if (raw == null) return null
var value = raw.trim().replace('\\', '/')
if (value.isBlank()) return null
while (value.startsWith("./")) value = value.substring(2)
while (value.startsWith("/")) value = value.substring(1)
return value.ifBlank { null }
}
fun normalizeScriptKey(raw: String?): String? {
var value = normalizeProjectPath(raw) ?: return null
if (value.startsWith("game/scripts/")) value = value.substring("game/scripts/".length)
if (value.startsWith("scripts/")) value = value.substring("scripts/".length)
return value.ifBlank { null }
}
fun resolveScriptFile(dir: File, raw: String?): File? {
val normalized = normalizeProjectPath(raw) ?: return null
val scriptKey = normalizeScriptKey(normalized) ?: normalized
val candidates = linkedSetOf<File>()
candidates += File(dir, normalized)
candidates += File(dir, scriptKey)
candidates += File(dir, "scripts/$scriptKey")
candidates += File(dir, "game/scripts/$scriptKey")
if (normalized.startsWith("game/") && !normalized.startsWith("game/scripts/")) {
candidates += File(dir, "scripts/${normalized.substring("game/".length)}")
}
return candidates.firstOrNull { it.isFile }
}
fun discoveredScript(dir: File, extension: String): String? {
val ext = extension.removePrefix(".")
val scriptsDir = listOf(File(dir, "scripts"), File(dir, "game/scripts")).firstOrNull { it.isDirectory } ?: return null
return scriptsDir.walkTopDown()
.filter { it.isFile && it.extension.equals(ext, ignoreCase = true) }
.map { scriptsDir.toPath().relativize(it.toPath()).toString().replace('\\', '/') }
.sortedWith(compareBy<String> {
val key = it.lowercase()
when {
key == "story/prologue.$ext" -> 0
key == "prologue.$ext" -> 1
key == "story/main.$ext" -> 2
key == "main.$ext" -> 3
key.contains("prologue") -> 10
key.contains("start") -> 11
key.contains("main") -> 12
else -> 100
}
}.thenBy { it.lowercase() })
.firstOrNull()
}
fun validateGameProject(): JvnGameProjectValidation {
val dir = gameProjectDir()
val manifest = gameManifest()
val warnings = mutableListOf<String>()
val errors = mutableListOf<String>()
val type = manifest.getProperty("type", "vn").trim().lowercase().ifBlank { "vn" }
if (canonicalOrAbsolute(dir) == canonicalOrAbsolute(projectDir) && !gradleFlag("jvnAllowEngineWorkspacePackage")) {
errors += "Selected project is the JVN engine workspace. Game packaging expects a separate JVN-made game project. If this is intentional, pass -PjvnAllowEngineWorkspacePackage=true."
}
if (dir.name != dir.name.trim()) {
warnings += "Project folder name has leading or trailing whitespace. The build preserves it, but it is easy to mistype on the CLI."
}
val entryKey = when (type) {
"vn" -> {
val configured = normalizeScriptKey(manifest.getProperty("entryVns"))
if (configured != null) {
if (resolveScriptFile(dir, configured) == null) {
errors += "Configured entryVns is missing: ${manifest.getProperty("entryVns")}"
}
configured
} else {
val discovered = discoveredScript(dir, "vns")
if (discovered == null) {
errors += "No VN entry script could be resolved. Set entryVns in jvn.project or add a .vns file under scripts/."
} else {
warnings += "entryVns is not set; runtime will start from discovered script: $discovered"
}
discovered
}
}
"jes" -> {
val configured = normalizeProjectPath(manifest.getProperty("entry") ?: "scripts/main.jes")
if (configured == null) {
errors += "JES projects must define entry=<path-to-jes> in jvn.project."
null
} else {
if (resolveScriptFile(dir, configured) == null) {
errors += "Configured JES entry is missing: $configured"
}
configured
}
}
"gradle" -> {
errors += "type=gradle projects describe an engine/workspace run command, not a distributable JVN game. Open a type=vn or type=jes game project for packaging."
null
}
else -> {
errors += "Unsupported jvn.project type for portable game packaging: $type. Supported types: vn, jes."
null
}
}
if (!File(dir, "scripts").isDirectory && !File(dir, "game/scripts").isDirectory) {
warnings += "No scripts/ or game/scripts/ directory was found."
}
if (!File(dir, "assets").isDirectory && !File(dir, "game").isDirectory) {
warnings += "No assets/ or game/ directory was found; package may be script-only."
}
if (errors.isNotEmpty()) {
throw GradleException("Invalid JVN game project:\n - ${errors.joinToString("\n - ")}")
}
return JvnGameProjectValidation(dir, manifest, type, entryKey, warnings)
}
fun currentHostIsWindows(): Boolean = System.getProperty("os.name", "").lowercase().contains("win")
fun packagingJavaHome(): File = jvnPackagingLauncher.get().metadata.installationPath.asFile
fun packagingTool(name: String): File {
val executable = if (currentHostIsWindows()) "$name.exe" else name
val tool = packagingJavaHome().resolve("bin/$executable")
if (!tool.isFile) {
throw GradleException("Required packaging tool was not found in the configured JDK toolchain: ${tool.absolutePath}")
}
return tool
}
fun currentPackageHost(): JvnGamePackageHost {
val target = currentGameTarget()
val osName = System.getProperty("os.name", "").lowercase()
return when {
osName.contains("win") -> JvnGamePackageHost("windows", target, listOf("app-image", "exe", "msi"), "exe")
osName.contains("linux") -> JvnGamePackageHost("linux", target, listOf("app-image", "deb", "rpm"), "deb")
osName.contains("mac") -> JvnGamePackageHost("macos", target, listOf("app-image", "dmg", "pkg"), "dmg")
else -> throw GradleException("Unsupported host OS for native packaging: $osName")
}
}
fun gameReleaseConfigFile(): File? {
val dir = gameProjectDir()
return listOf(
File(dir, "config/release/jvn-release.properties"),
File(dir, "config/release/release.properties"),
File(dir, "release/jvn-release.properties"),
File(dir, "jvn-release.properties")
).firstOrNull { it.isFile }
}
fun gameReleaseConfig(): Properties {
val props = Properties()
val file = gameReleaseConfigFile() ?: return props
file.inputStream().use { props.load(it) }
return props
}
fun gameReleaseProfileNames(): List<String> {
val props = gameReleaseConfig()
val discovered = props.stringPropertyNames()
.mapNotNull { key ->
if (!key.startsWith("profile.")) return@mapNotNull null
val suffix = key.removePrefix("profile.")
val profile = suffix.substringBefore('.', "")
profile.ifBlank { null }
}
.filterNot { it.equals("default", ignoreCase = true) }
.distinct()
.sorted()
return if (discovered.isEmpty()) listOf("default") else listOf("default") + discovered
}
fun selectedReleaseProfileName(): String {
val explicit = (findProperty("jvnReleaseProfile") as String?)?.trim()
if (!explicit.isNullOrBlank()) return explicit
val configured = gameReleaseConfig().getProperty("defaultProfile", "").trim()
return configured.ifBlank { "default" }
}
fun selectedReleaseProfile(): JvnReleaseProfile {
return JvnReleaseProfile(selectedReleaseProfileName(), gameReleaseConfigFile(), gameReleaseConfig())
}
fun nativeGameVersion(): String {
val explicit = (findProperty("jvnNativeVersion") as String?)?.trim()
if (!explicit.isNullOrBlank()) return explicit
val parts = Regex("\\d+").findAll(gameVersion())
.map { it.value.toIntOrNull() ?: 0 }
.toList()
.toMutableList()
while (parts.size < 3) parts += 0
if (parts.isEmpty()) return "1.0.0"
if (parts[0] <= 0) parts[0] = 1
return parts.take(3).joinToString(".")
}
fun targetJavaFxConfiguration(target: JvnGameTarget): org.gradle.api.artifacts.Configuration {
return jvnGameJavaFxConfigurations[target.id]
?: throw GradleException("No JavaFX runtime configuration is registered for ${target.id}.")
}
fun currentJavaFxConfiguration(): org.gradle.api.artifacts.Configuration = targetJavaFxConfiguration(currentGameTarget())
fun targetJavaFxRuntimeJars(target: JvnGameTarget): List<File> {
return targetJavaFxConfiguration(target).resolve()
.filter { it.isFile && it.name.startsWith("javafx-") && it.name.endsWith(".jar") }
.distinctBy { it.name }
.sortedBy { it.name }
}
fun currentJavaFxRuntimeJars(): List<File> = targetJavaFxRuntimeJars(currentGameTarget())
fun gameRuntimeClasspathJars(): List<File> {
return (
jvnGameRuntimeProjectPaths.map { projectPath ->
project(projectPath).tasks.named<Jar>("jar").get().archiveFile.get().asFile
} + externalRuntimeJars()
).filter { it.isFile }
.distinctBy { it.name }
.sortedBy { it.name }
}
fun currentJpackageType(): String {
val host = currentPackageHost()
val explicit = (findProperty("jvnNativePackageType") as String?)?.trim()?.lowercase()
if (!explicit.isNullOrBlank()) {
if (explicit !in host.nativePackageTypes) {
throw GradleException("Unsupported native package type '$explicit' for ${host.osId}. Supported values: ${host.nativePackageTypes.joinToString(", ")}.")
}
return explicit
}
return host.defaultNativePackageType
}
fun bundledRuntimeVendor(): String {
val explicit = (findProperty("jvnBundledRuntimeVendor") as String?)?.trim()
return explicit?.ifBlank { null } ?: "eclipse"
}
fun bundledRuntimeImageTypeCandidates(): List<String> {
val explicit = (findProperty("jvnBundledRuntimeImageType") as String?)?.trim()?.lowercase()
return when {
explicit.isNullOrBlank() -> listOf("jre", "jdk")
explicit in setOf("jre", "jdk") -> listOf(explicit)
else -> throw GradleException("Unsupported jvnBundledRuntimeImageType '$explicit'. Supported values: jre, jdk.")
}
}
fun bundledRuntimeOs(target: JvnGameTarget): String = when {
target.id.startsWith("windows") -> "windows"
target.id.startsWith("linux") -> "linux"
target.id.startsWith("macos") -> "mac"
else -> throw GradleException("Unsupported bundled runtime target OS: ${target.id}")
}
fun bundledRuntimeArch(target: JvnGameTarget): String = when {
target.id.endsWith("aarch64") -> "aarch64"
else -> "x64"
}
fun bundledRuntimeArchiveType(target: JvnGameTarget): String = if (target.windows) "zip" else "tar.gz"
fun bundledRuntimeAssetApiUrl(target: JvnGameTarget, imageType: String): String {
return "https://api.adoptium.net/v3/assets/latest/$configuredJavaVersion/hotspot" +
"?os=${bundledRuntimeOs(target)}" +
"&architecture=${bundledRuntimeArch(target)}" +
"&image_type=$imageType" +
"&jvm_impl=hotspot" +
"&heap_size=normal" +
"&vendor=${bundledRuntimeVendor()}"
}
fun bundledRuntimeArchiveFile(target: JvnGameTarget, imageType: String): File {
val extension = bundledRuntimeArchiveType(target)
return layout.buildDirectory.file(
"downloads/jvnRuntime/${target.id}/temurin-${configuredJavaVersion}-${target.id}-$imageType.$extension"
).get().asFile
}
fun bundledRuntimeExtractDir(target: JvnGameTarget): File {
return layout.buildDirectory.dir("vendor-runtimes/${target.id}").get().asFile
}
fun bundledRuntimeInfoFile(target: JvnGameTarget): File {
return layout.buildDirectory.file("vendor-runtimes/${target.id}.properties").get().asFile
}
fun sha256Hex(file: File): String {
val digest = MessageDigest.getInstance("SHA-256")
file.inputStream().use { input ->
val buffer = ByteArray(1024 * 64)
while (true) {
val read = input.read(buffer)
if (read < 0) break
if (read > 0) digest.update(buffer, 0, read)
}
}
return digest.digest().joinToString("") { "%02x".format(it) }
}
fun gameBundledDistName(target: JvnGameTarget): String {
return "${sanitizeGameName(gameDisplayName())}-${sanitizeGameName(gameVersion())}-${target.id}-runtime"
}
fun gameNativeArtifactStem(packageType: String): String {
val host = currentPackageHost()
return "${sanitizeGameName(gameDisplayName())}-${sanitizeGameName(nativeGameVersion())}-${host.target.id}-$packageType"
}
fun jpackageAppName(): String {
val fromProfile = selectedReleaseProfile().value("appName")
return if (!fromProfile.isNullOrBlank()) fromProfile else gameDisplayName()
}
fun bundledRuntimeMetadata(target: JvnGameTarget, runtime: JvnBundledRuntimeSelection): String {
val profile = selectedReleaseProfile()
return """
|JVN Game Bundled Runtime Build
|builtAt=${Instant.now()}
|target=${target.id}
|distName=${gameBundledDistName(target)}
|gameName=${gameDisplayName()}
|gameVersion=${gameVersion()}
|nativeVersion=${nativeGameVersion()}
|releaseProfile=${profile.name}
|releaseConfig=${profile.file?.absolutePath ?: "(none)"}
|runtimeRequirement=Bundled Java runtime image
|runtimeVendor=${bundledRuntimeVendor()}
|runtimeImageType=${runtime.imageType}
|runtimeArchive=${runtime.archiveFile.name}
|runtimeDownloadUrl=${runtime.downloadUrl}
|runtimeChecksum=${runtime.checksum}
|runtimeChecksumUrl=${runtime.checksumUrl ?: "(none)"}
|runtimeJavaExecutable=${runtime.javaExecutableRelativePath}
|javafxVersion=$jvnJavaFxVersion
|javafxClassifier=${target.javafxClassifier}
|
""".trimMargin()
}
fun nativeBuildMetadata(packageType: String): String {
val profile = selectedReleaseProfile()
return """
|JVN Game Native Package
|builtAt=${Instant.now()}
|target=${currentPackageHost().target.id}
|packageType=$packageType
|gameName=${gameDisplayName()}
|gameVersion=${gameVersion()}
|nativeVersion=${nativeGameVersion()}
|releaseProfile=${profile.name}
|releaseConfig=${profile.file?.absolutePath ?: "(none)"}
|
""".trimMargin()
}
fun gamePackagedMainClass(): String = "com.jvn.runtime.GamePackageLauncher"
fun runtimeImageModules(): List<String> {
val modules = linkedSetOf(
"java.base",
"java.desktop",
"java.logging",
"java.management",
"java.naming",
"java.prefs",
"java.scripting",
"java.sql",
"java.xml",
"jdk.unsupported"
)
modules += jvnJavaFxRuntimeModules
selectedReleaseProfile().value("runtime.modules")
?.split(',', ';', ' ')
?.map { it.trim() }
?.filter { it.isNotBlank() }
?.forEach { modules += it }
return modules.toList()
}
fun resolveProjectRelativeFile(raw: String?): File? {
if (raw.isNullOrBlank()) return null
val candidate = File(raw)
if (candidate.isAbsolute) return candidate
val releaseFile = gameReleaseConfigFile()
val bases = listOfNotNull(releaseFile?.parentFile, gameProjectDir())
return bases.asSequence()
.map { File(it, raw) }
.firstOrNull { it.exists() }
?: File(gameProjectDir(), raw)
}
fun gamePackageVendor(): String {
return selectedReleaseProfile().value("vendor")
?: gameManifest().getProperty("author", "").trim().ifBlank { "JVN" }
}
fun gamePackageDescription(): String {
return selectedReleaseProfile().value("description")
?: gameManifest().getProperty("description", "").trim().ifBlank { "${gameDisplayName()} built with JVN." }
}
fun gamePackageCopyright(): String? = selectedReleaseProfile().value("copyright")
fun gamePackageAboutUrl(): String? = selectedReleaseProfile().value("aboutUrl")
fun gamePackageLicenseFile(): File? {
return resolveProjectRelativeFile(selectedReleaseProfile().value("licenseFile"))?.takeIf { it.isFile }
}
fun gamePackageIconFile(): File? {
val explicit = resolveProjectRelativeFile(selectedReleaseProfile().value("icon"))
if (explicit != null && explicit.isFile) return explicit
val candidates = when (currentPackageHost().osId) {
"macos" -> listOf("icon.icns", "Icon.icns", "assets/icon.icns")
"windows" -> listOf("icon.ico", "Icon.ico", "assets/icon.ico")
else -> listOf("icon.png", "Icon.png", "assets/icon.png")
}
return candidates.asSequence()
.mapNotNull { resolveProjectRelativeFile(it) }
.firstOrNull { it.isFile }
}
fun copyGameProjectFiles(destination: File) {
copy {
from(gameProjectDir())
into(destination)
exclude(
".git/**",
".gradle/**",
".jvn-gradle-user-home/**",
"build/**",
"out/**",
"dist/**",
"save/**",
"saves/**",
"logs/**",
".idea/**",
".vscode/**",
"__MACOSX/**",
"**/*.log",
"**/*.tmp",
"**/Icon\r",
"**/.DS_Store",
"**/Thumbs.db"
)
}
}
fun bundledRuntimeRootDir(target: JvnGameTarget): File {
return layout.buildDirectory.dir("generated/jvnGameBundledRuntime/${target.id}/${gameBundledDistName(target)}").get().asFile
}
fun bundledRuntimeZipDir(): File {
return layout.buildDirectory.dir("distributions/games").get().asFile
}
fun bundledRuntimeDistributionFile(target: JvnGameTarget): File {
return bundledRuntimeZipDir().resolve("${gameBundledDistName(target)}.zip")
}
fun runtimeImageDir(): File {
return layout.buildDirectory.dir("runtime-images/games/${currentPackageHost().target.id}/${sanitizeGameName(gameDisplayName())}-${sanitizeGameName(nativeGameVersion())}").get().asFile
}
fun jpackageInputDir(): File {
return layout.buildDirectory.dir("generated/jvnGameJpackage/${currentPackageHost().target.id}/input").get().asFile
}
fun jpackageContentDir(): File {
return layout.buildDirectory.dir("generated/jvnGameJpackage/${currentPackageHost().target.id}/content").get().asFile
}
fun jpackageRawOutputDir(packageType: String): File {
return layout.buildDirectory.dir("jpackage/games/${currentPackageHost().target.id}/$packageType").get().asFile
}
fun downloadUrlToFile(urlString: String, outputFile: File) {
outputFile.parentFile.mkdirs()
val tempFile = File(outputFile.absolutePath + ".part")
tempFile.delete()
val connection = URL(urlString).openConnection()
connection.connectTimeout = 30_000
connection.readTimeout = 300_000
connection.setRequestProperty("Accept", "application/octet-stream")
if (connection is HttpURLConnection) {
connection.instanceFollowRedirects = true
val response = connection.responseCode
if (response >= 400) {
throw GradleException("HTTP $response while downloading $urlString")
}
}
connection.getInputStream().use { input ->
tempFile.outputStream().use { output ->
input.copyTo(output)
}
}
if (outputFile.exists()) outputFile.delete()
if (!tempFile.renameTo(outputFile)) {
tempFile.copyTo(outputFile, overwrite = true)
tempFile.delete()
}
}
fun fetchBundledRuntimeAsset(target: JvnGameTarget, imageType: String): JvnBundledRuntimeAsset {
val connection = URL(bundledRuntimeAssetApiUrl(target, imageType)).openConnection()
connection.connectTimeout = 30_000
connection.readTimeout = 120_000
connection.setRequestProperty("Accept", "application/json")
connection.setRequestProperty("User-Agent", "JVN Build")
if (connection is HttpURLConnection) {
connection.instanceFollowRedirects = true
val response = connection.responseCode
if (response >= 400) {
throw GradleException("HTTP $response while fetching bundled runtime metadata for ${target.id} ($imageType)")
}
}
val parsed = connection.getInputStream().use { input ->
JsonSlurper().parse(input)
}
val entries = parsed as? List<*> ?: throw GradleException("Unexpected bundled runtime metadata payload for ${target.id} ($imageType)")
val first = entries.firstOrNull() as? Map<*, *> ?: throw GradleException("No bundled runtime metadata returned for ${target.id} ($imageType)")
val binary = first["binary"] as? Map<*, *> ?: throw GradleException("Bundled runtime metadata is missing binary data for ${target.id} ($imageType)")
val pkg = binary["package"] as? Map<*, *> ?: throw GradleException("Bundled runtime metadata is missing package data for ${target.id} ($imageType)")
val link = pkg["link"]?.toString()?.trim().orEmpty()
val checksum = pkg["checksum"]?.toString()?.trim().orEmpty().lowercase()
val checksumUrl = pkg["checksum_link"]?.toString()?.trim()?.ifBlank { null }
if (link.isBlank() || checksum.isBlank()) {
throw GradleException("Bundled runtime metadata for ${target.id} ($imageType) is missing link/checksum information.")
}
return JvnBundledRuntimeAsset(imageType, link, checksum, checksumUrl)
}
fun verifyBundledRuntimeArchive(archiveFile: File, expectedChecksum: String) {
if (!archiveFile.isFile) {
throw GradleException("Bundled runtime archive is missing: ${archiveFile.absolutePath}")
}
val actualChecksum = sha256Hex(archiveFile)
if (!actualChecksum.equals(expectedChecksum, ignoreCase = true)) {
throw GradleException(
"Bundled runtime checksum mismatch for ${archiveFile.name}. Expected $expectedChecksum but found $actualChecksum."
)
}
}
fun extractBundledRuntimeArchive(archiveFile: File, target: JvnGameTarget, destination: File) {
deleteAndMkdir(destination)
copy {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
when (bundledRuntimeArchiveType(target)) {
"zip" -> from(zipTree(archiveFile))
"tar.gz" -> from(tarTree(resources.gzip(archiveFile)))
else -> throw GradleException("Unsupported bundled runtime archive type for ${target.id}: ${bundledRuntimeArchiveType(target)}")
}
into(destination)
}
}
fun detectBundledRuntimeJavaExecutableRelativePath(runtimeDir: File, target: JvnGameTarget): String? {
val expectedName = if (target.windows) "java.exe" else "java"
return runtimeDir.walkTopDown()
.filter { file -> file.isFile && file.name.equals(expectedName, ignoreCase = true) && file.parentFile?.name.equals("bin", ignoreCase = true) == true }
.map { file -> runtimeDir.toPath().relativize(file.toPath()).toString().replace('\\', '/') }
.sortedWith(compareBy<String>({ it.count { ch -> ch == '/' } }, { it.length }))
.firstOrNull()
}
fun ensureBundledRuntimeSelection(target: JvnGameTarget): JvnBundledRuntimeSelection {
val refresh = gradleFlag("jvnRefreshBundledRuntime")
val runtimeDir = bundledRuntimeExtractDir(target)
val infoFile = bundledRuntimeInfoFile(target)
if (!refresh && infoFile.isFile() && runtimeDir.isDirectory) {
val props = Properties()
infoFile.inputStream().use { props.load(it) }
val imageType = props.getProperty("imageType", "").trim()
val downloadUrl = props.getProperty("downloadUrl", "").trim()
val checksum = props.getProperty("checksum", "").trim().lowercase()
val checksumUrl = props.getProperty("checksumUrl", "").trim().ifBlank { null }
val archivePath = props.getProperty("archiveFile", "").trim()
val javaExecutableRelativePath = props.getProperty("javaExecutableRelativePath", "").trim()
if (imageType.isNotBlank() && downloadUrl.isNotBlank() && checksum.isNotBlank() && javaExecutableRelativePath.isNotBlank()) {
val archiveFile = File(archivePath)
if (archiveFile.isFile && runtimeDir.resolve(javaExecutableRelativePath).exists()) {
verifyBundledRuntimeArchive(archiveFile, checksum)
return JvnBundledRuntimeSelection(target, imageType, downloadUrl, checksum, checksumUrl, archiveFile, runtimeDir, javaExecutableRelativePath)
}
}
}
val attempts = mutableListOf<String>()
bundledRuntimeImageTypeCandidates().forEach { imageType ->
val asset = fetchBundledRuntimeAsset(target, imageType)
val archiveFile = bundledRuntimeArchiveFile(target, asset.imageType)
try {
if (refresh || !archiveFile.isFile || archiveFile.length() == 0L) {
logger.lifecycle("Downloading bundled runtime for ${target.id}: ${asset.downloadUrl}")
downloadUrlToFile(asset.downloadUrl, archiveFile)
}
verifyBundledRuntimeArchive(archiveFile, asset.checksum)
extractBundledRuntimeArchive(archiveFile, target, runtimeDir)
val javaExecutableRelativePath = detectBundledRuntimeJavaExecutableRelativePath(runtimeDir, target)
?: throw GradleException("Downloaded runtime for ${target.id} does not contain a detectable java executable under a bin/ directory.")
val props = Properties()
props.setProperty("imageType", asset.imageType)
props.setProperty("downloadUrl", asset.downloadUrl)
props.setProperty("checksum", asset.checksum)
asset.checksumUrl?.let { props.setProperty("checksumUrl", it) }
props.setProperty("archiveFile", archiveFile.absolutePath)
props.setProperty("javaExecutableRelativePath", javaExecutableRelativePath)
infoFile.parentFile.mkdirs()
infoFile.outputStream().use { props.store(it, "JVN bundled runtime cache") }
return JvnBundledRuntimeSelection(target, asset.imageType, asset.downloadUrl, asset.checksum, asset.checksumUrl, archiveFile, runtimeDir, javaExecutableRelativePath)
} catch (ex: Exception) {
runtimeDir.deleteRecursively()
infoFile.delete()
archiveFile.delete()
attempts += "${asset.imageType} from ${asset.downloadUrl} (${ex.message ?: ex.javaClass.simpleName})"
}
}
throw GradleException("Could not prepare a bundled runtime for ${target.id}. Tried:\n - ${attempts.joinToString("\n - ")}")
}
fun gameBundledScriptUnix(javaExecutableRelativePath: String): String {
val dollar = "$"
val javaPath = javaExecutableRelativePath.replace('\\', '/')
return """
|#!/usr/bin/env sh
|set -eu
|APP_HOME=${dollar}(CDPATH= cd -- "${dollar}(dirname -- "${dollar}0")/.." && pwd)
|JAVA_EXE="${dollar}APP_HOME/runtime/$javaPath"
|if [ ! -x "${dollar}JAVA_EXE" ]; then
| echo "JVN launcher error: bundled runtime image is missing ${dollar}JAVA_EXE." >&2
| exit 1
|fi
|exec "${dollar}JAVA_EXE" \
| --module-path "${dollar}APP_HOME/lib/javafx" \
| --add-modules ${jvnJavaFxRuntimeModules.joinToString(",")} \
| -cp "${dollar}APP_HOME/lib/*" \
| com.jvn.runtime.JvnApp \
${gameLauncherArgsUnix(dollar)}
|
""".trimMargin()
}
fun gameBundledScriptWindows(target: JvnGameTarget, javaExecutableRelativePath: String): String {
val javaPath = javaExecutableRelativePath.replace('/', '\\')
return """
|@echo off
|setlocal
|set "APP_HOME=%~dp0.."
|if not exist "%APP_HOME%\game\jvn.project" (
| echo JVN launcher error: bundled game\jvn.project is missing.
| exit /b 1
|)
|set "JAVA_EXE=%APP_HOME%\runtime\$javaPath"
|if not exist "%JAVA_EXE%" (
| echo JVN launcher error: bundled runtime image is missing %JAVA_EXE%.
| exit /b 1
|)
|"%JAVA_EXE%" --module-path "%APP_HOME%\lib\javafx" --add-modules ${jvnJavaFxRuntimeModules.joinToString(",")} -cp "%APP_HOME%\lib\*" com.jvn.runtime.JvnApp --assets "%APP_HOME%\game"${gameLauncherExtraArgsWindows()} %*
|exit /b %ERRORLEVEL%
|
""".trimMargin()
}
fun gameBundledReadme(target: JvnGameTarget, runtime: JvnBundledRuntimeSelection): String {
val launcher = if (target.windows) "bin\\${gameLauncherBaseName()}.bat" else "bin/${gameLauncherBaseName()}"
return """
|${gameBundledDistName(target)}
|
|Self-contained JVN game build for ${target.id}.
|
|Requirements:
| None. This package includes its own Java runtime image.
|
|Launch:
| $launcher
|
|Contents:
| bin/ game launcher
| game/ bundled JVN project files
| lib/ JVN runtime jars and third-party dependencies
| lib/javafx/ JavaFX native jars for ${target.javafxClassifier}
| runtime/ bundled ${bundledRuntimeVendor()} runtime archive (${runtime.imageType})
| BUILD-METADATA.txt package metadata for this build
|
""".trimMargin()
}
fun gameNativeReadme(): String {
val host = currentPackageHost()
return """
|${jpackageAppName()}
|
|Native JVN game package for ${host.target.id}.
|
|Requirements:
| None. This package includes its own Java runtime image.
|
|Contents:
| game/ bundled JVN project files
| BUILD-METADATA.txt package metadata for this build
|
""".trimMargin()
}
fun deleteAndMkdir(dir: File) {
dir.deleteRecursively()
dir.mkdirs()
}
fun copyDirectoryContents(from: File, into: File) {
copy {
from(from)
into(into)
}
}
fun currentNativePackageExtension(packageType: String): String = when (packageType) {
"app-image" -> ".zip"
"dmg" -> ".dmg"
"pkg" -> ".pkg"
"exe" -> ".exe"
"msi" -> ".msi"
"deb" -> ".deb"
"rpm" -> ".rpm"
else -> ".bin"
}
fun currentNativeDistributionFile(packageType: String): File {
return bundledRuntimeZipDir().resolve("${gameNativeArtifactStem(packageType)}${currentNativePackageExtension(packageType)}")
}
fun currentReleaseArtifactFile(mode: String): File {
return when (mode) {
"portable" -> bundledRuntimeZipDir().resolve("${gameDistName(currentPackageHost().target)}.zip")
"bundled" -> bundledRuntimeDistributionFile(currentPackageHost().target)
"native" -> currentNativeDistributionFile(currentJpackageType())
else -> throw GradleException("Unsupported release artifact mode: $mode")
}
}
fun publishCommandVariables(mode: String, artifact: File, targetId: String = currentPackageHost().target.id): Map<String, String> {
return mapOf(
"artifact" to artifact.absolutePath,
"artifactName" to artifact.name,
"artifactDir" to artifact.parentFile.absolutePath,
"artifactType" to mode,
"packageType" to if (mode == "native") currentJpackageType() else mode,
"gameName" to gameDisplayName(),
"gameVersion" to gameVersion(),
"nativeVersion" to nativeGameVersion(),
"target" to targetId,
"releaseProfile" to selectedReleaseProfile().name
)
}
fun expandPublishCommand(template: String, values: Map<String, String>): String {
var result = template
values.forEach { (key, value) ->
result = result.replace("{$key}", value)
}
return result
}
fun validateExistingProfileFile(label: String, raw: String?) {
if (raw.isNullOrBlank()) return
val resolved = resolveProjectRelativeFile(raw)
if (resolved == null || !resolved.isFile) {
throw GradleException("Release profile '${selectedReleaseProfile().name}' references $label='$raw', but that file was not found.")
}
}
fun unresolvedPublishPlaceholders(template: String, allowedKeys: Set<String>): List<String> {
return Regex("\\{([A-Za-z][A-Za-z0-9]*)\\}")
.findAll(template)
.map { it.groupValues[1] }
.filter { it !in allowedKeys }
.distinct()
.toList()
}
fun validateSelectedReleaseProfile() {
val releaseFile = gameReleaseConfigFile()
val selectedName = selectedReleaseProfile().name
val explicit = (findProperty("jvnReleaseProfile") as String?)?.trim()
val configuredDefault = gameReleaseConfig().getProperty("defaultProfile", "").trim()
if (!configuredDefault.isNullOrBlank() &&
!configuredDefault.equals("default", ignoreCase = true) &&
configuredDefault !in gameReleaseProfileNames()) {
throw GradleException(
"Configured defaultProfile '$configuredDefault' was not found in ${releaseFile?.absolutePath ?: "(missing release config)"}." +
" Available profiles: ${gameReleaseProfileNames().joinToString(", ")}"
)
}
if (!explicit.isNullOrBlank() && !explicit.equals("default", ignoreCase = true) && releaseFile == null) {