Add optional adaptive distant terrain budget and resource telemetry
This commit is contained in:
@@ -14,6 +14,7 @@ Use native **Java 25 ARM64**, maximum heap **6144 MiB**, minimum **512 MiB** on
|
||||
| --- | ---: | ---: | ---: |
|
||||
| baseline | 12 | none | 6144 MiB |
|
||||
| m2-balanced | 12 | 128 | 6144 MiB |
|
||||
| adaptive (experiment) | 12 | 128 | 6144 MiB |
|
||||
| low-memory | 8 | none | 3072 MiB |
|
||||
| far-distance | 12 | 256 | 8192 MiB, with sufficient physical RAM |
|
||||
| cinematic | 12 | 128 | 6144 MiB |
|
||||
@@ -25,6 +26,11 @@ Distant LOD is simplified terrain. Nearby blocks retain full detail. Initial gen
|
||||
|
||||
## Measure on your hardware
|
||||
|
||||
The optional [adaptive terrain experiment](docs/adaptive-terrain.md) throttles distant
|
||||
terrain background work when frames slow down or heap pressure rises, keeping the
|
||||
balanced profile's view distances and simulation settings. It remains opt-in until
|
||||
real hardware demonstrates a benefit.
|
||||
|
||||
Press **F8** during gameplay to start a 120-second recording, or again to stop early. Rebind in Controls if needed. This also works with restricted chat accounts. Alternatively: `/horizon bench <label> 120`, `/horizon stop`, `/horizon status`.
|
||||
|
||||
Use separate identical world copies and the same camera route, resolution, render/simulation distance, heap, VSync and FPS limit. Warm up, then alternate at least three baseline/optimized runs. Test fresh chunk exploration separately. For everyday play cap FPS or enable VSync to reduce power usage.
|
||||
@@ -46,7 +52,7 @@ python3 tools/build_mod.py
|
||||
python3 tools/build_release.py
|
||||
```
|
||||
|
||||
Gitignored `dist/` contains six packs, our original instrumentation JAR, client/server starter ZIPs and SHA256SUMS. [mods.lock.json](packs/mods.lock.json) pins mod versions, exact dependency closure, SHA-1/SHA-512 and source/license; [fabric.lock.json](packs/fabric.lock.json) pins loader/library SHA-256. Packs use the [Modrinth format](https://support.modrinth.com/en/articles/8802351-modrinth-modpack-format-mrpack). They embed only original project code; third-party mods, game and assets download from their publishers.
|
||||
Gitignored `dist/` contains seven packs, our original instrumentation JAR, client/server starter ZIPs and SHA256SUMS. [mods.lock.json](packs/mods.lock.json) pins mod versions, exact dependency closure, SHA-1/SHA-512 and source/license; [fabric.lock.json](packs/fabric.lock.json) pins loader/library SHA-256. Packs use the [Modrinth format](https://support.modrinth.com/en/articles/8802351-modrinth-modpack-format-mrpack). They embed only original project code; third-party mods, game and assets download from their publishers.
|
||||
|
||||
The server starter uses Lithium/FerriteCore and `/horizonserver bench <label> <seconds>`. [Server instructions](docs/server-quickstart.txt) cover setup and a baseline. Files are prepared before you accept Minecraft's EULA locally. A 50-active-player workload remains to be measured.
|
||||
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# Adaptive distant-terrain budget
|
||||
|
||||
The optional `adaptive` profile keeps the balanced profile's full-detail distance,
|
||||
distant radius, worker count and simulation settings. Its original controller changes
|
||||
only Distant Horizons' background worker duty cycle. Existing stable downloads remain
|
||||
available while this experiment is validated.
|
||||
|
||||
Import adaptive into a separate Prism instance with the same Java, heap, world copy
|
||||
and graphics settings as balanced. `/horizon adaptive on` and `/horizon adaptive off`
|
||||
change the policy for the current session. Changes are refused during recording;
|
||||
`/horizon status` shows the current budget.
|
||||
|
||||
The opt-in configuration is `config/horizon-adaptive.properties`:
|
||||
|
||||
```properties
|
||||
enabled=true
|
||||
targetFps=60
|
||||
```
|
||||
|
||||
The target is clamped to 10–240 FPS and respects a lower configured frame cap.
|
||||
Every two seconds of focused gameplay, the policy considers mean frame duration,
|
||||
the fraction of frames exceeding twice the target duration, and current used heap.
|
||||
Slow frames or heap usage above 85% cut the duty cycle to 65% of its previous
|
||||
value, with a 0.05 floor or the user's lower ceiling. Three consecutive healthy
|
||||
windows permit a 0.025 increase. The user-configured DH ratio remains the ceiling.
|
||||
Menus, pauses and loss of focus release the temporary override and discard the partial
|
||||
window. Another mod's existing or changed override makes the controller yield.
|
||||
The controller does not write DH settings to disk.
|
||||
|
||||
Frame intervals include presentation and frame pacing. A GPU bottleneck can also
|
||||
trigger this heuristic even when background CPU work was not responsible. Terrain
|
||||
generation may take longer. Reducing duty cycle does not free cached terrain or
|
||||
guarantee lower peak memory. No resolution, visual-quality, worker-count,
|
||||
simulation-distance or tick-rate change is made.
|
||||
|
||||
The pinned DH public `threadRuntimeRatio()` API wraps its live configuration entry.
|
||||
Inspection confirmed that its executor reads the effective entry after each task
|
||||
and sleeps according to that ratio. Changes affect subsequent pacing without
|
||||
restarting the pool; individual long-running tasks cannot be preempted. API code
|
||||
stays in the upstream dependency. Only original `dev.horizonlab` classes are packaged.
|
||||
|
||||
Compare **balanced against adaptive**, first with matched cold terrain exploration
|
||||
and then matched warm terrain. Record three alternating runs per condition. Check
|
||||
average FPS, slowest-1% FPS, p99 frame duration, integrated-server tick times,
|
||||
sampled peak heap and process mean CPU cores. Also judge terrain completion time:
|
||||
improved pacing at the expense of excessive generation delay is a tradeoff to measure.
|
||||
The local software renderer validates integration only; the M2 Pro must provide
|
||||
the actual performance result.
|
||||
|
||||
JVM heap/nonheap samples are taken once per second during recorded gameplay, plus
|
||||
start/end samples. Short spikes can be missed. Process CPU time covers the whole
|
||||
recording, including menus, all Java threads and the integrated server; one mean CPU
|
||||
core means one CPU-second per elapsed second. JVM memory excludes some native
|
||||
allocations and GPU memory and is not process RSS.
|
||||
@@ -0,0 +1,38 @@
|
||||
package dev.horizonlab.budget;
|
||||
|
||||
/** Foreground-first background duty cycle. Inputs are two-second observation windows. */
|
||||
public final class TerrainBudget {
|
||||
private double ratio;
|
||||
private int healthyWindows;
|
||||
|
||||
public TerrainBudget(double ceiling) { ratio = ceiling; }
|
||||
|
||||
public double update(double ceiling, double meanFrameMs, double targetFrameMs,
|
||||
double lateFraction, double heapFraction) {
|
||||
if (!Double.isFinite(ceiling) || ceiling < 0.01 || ceiling > 1.0
|
||||
|| !Double.isFinite(meanFrameMs) || meanFrameMs < 0
|
||||
|| !Double.isFinite(targetFrameMs) || targetFrameMs <= 0
|
||||
|| !Double.isFinite(lateFraction) || lateFraction < 0 || lateFraction > 1
|
||||
|| !Double.isFinite(heapFraction) || heapFraction < 0 || heapFraction > 1) {
|
||||
throw new IllegalArgumentException("Invalid budget observations");
|
||||
}
|
||||
double floor = Math.min(ceiling, 0.05);
|
||||
ratio = Math.min(ratio, ceiling);
|
||||
boolean pressure = meanFrameMs > targetFrameMs * 1.35 || lateFraction > 0.20 || heapFraction > 0.85;
|
||||
boolean healthy = meanFrameMs < targetFrameMs * 1.10 && lateFraction < 0.05 && heapFraction < 0.75;
|
||||
if (pressure) {
|
||||
healthyWindows = 0;
|
||||
ratio = Math.max(floor, ratio * 0.65);
|
||||
} else if (healthy) {
|
||||
if (++healthyWindows >= 3) {
|
||||
ratio = Math.min(ceiling, ratio + 0.025);
|
||||
healthyWindows = 0;
|
||||
}
|
||||
} else {
|
||||
healthyWindows = 0;
|
||||
}
|
||||
return ratio;
|
||||
}
|
||||
|
||||
public double ratio() { return ratio; }
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package dev.horizonlab.client;
|
||||
|
||||
import com.seibel.distanthorizons.api.DhApi;
|
||||
import com.seibel.distanthorizons.api.interfaces.config.IDhApiConfigValue;
|
||||
import dev.horizonlab.HorizonLab;
|
||||
import dev.horizonlab.budget.TerrainBudget;
|
||||
|
||||
/** Loaded only when DH is installed. Overrides are temporary, never written to its TOML. */
|
||||
final class DistantTerrainBudget {
|
||||
private IDhApiConfigValue<Double> setting;
|
||||
private TerrainBudget policy;
|
||||
private Double owned;
|
||||
private boolean yielded;
|
||||
private long windowStart;
|
||||
private long totalNs;
|
||||
private int count;
|
||||
private int late;
|
||||
private int changes;
|
||||
|
||||
void observe(long now, long frameNs, double targetMs) {
|
||||
if (yielded || DhApi.Delayed.configs == null) return;
|
||||
if (setting == null) {
|
||||
setting = DhApi.Delayed.configs.multiThreading().threadRuntimeRatio();
|
||||
if (!setting.getCanBeOverrodeByApi() || setting.getApiValue() != null) {
|
||||
yielded = true;
|
||||
HorizonLab.LOGGER.info("Adaptive terrain budget yielded to an existing DH override");
|
||||
return;
|
||||
}
|
||||
policy = new TerrainBudget(setting.getTrueValue());
|
||||
}
|
||||
if (!java.util.Objects.equals(setting.getApiValue(), owned)) {
|
||||
yielded = true;
|
||||
owned = null;
|
||||
HorizonLab.LOGGER.info("Adaptive terrain budget yielded after another DH override changed");
|
||||
return;
|
||||
}
|
||||
if (windowStart == 0) windowStart = now;
|
||||
if (frameNs > 0) {
|
||||
totalNs += frameNs;
|
||||
count++;
|
||||
if (frameNs / 1e6 > targetMs * 2) late++;
|
||||
}
|
||||
if (now - windowStart < 2_000_000_000L || count == 0) return;
|
||||
Runtime runtime = Runtime.getRuntime();
|
||||
double heap = (runtime.totalMemory() - runtime.freeMemory()) / (double) runtime.maxMemory();
|
||||
double next = policy.update(setting.getTrueValue(), totalNs / 1e6 / count, targetMs,
|
||||
late / (double) count, heap);
|
||||
if (owned == null || Math.abs(next - owned) > 0.0001) {
|
||||
if (setting.setValue(next, "Horizon Lab adaptive budget")) {
|
||||
owned = next;
|
||||
changes++;
|
||||
HorizonLab.LOGGER.info("Adaptive terrain background runtime ratio: {}", next);
|
||||
}
|
||||
}
|
||||
resetWindow();
|
||||
}
|
||||
|
||||
void suspend() {
|
||||
if (setting != null && owned != null && java.util.Objects.equals(setting.getApiValue(), owned)) {
|
||||
setting.clearValue();
|
||||
}
|
||||
owned = null;
|
||||
policy = setting == null ? null : new TerrainBudget(setting.getTrueValue());
|
||||
resetWindow();
|
||||
}
|
||||
|
||||
private void resetWindow() { windowStart = 0; totalNs = 0; count = 0; late = 0; }
|
||||
|
||||
String status() {
|
||||
return yielded ? "yielded to another mod" : owned == null ? "waiting for active gameplay"
|
||||
: "DH runtime ratio " + owned + "; adjustments " + changes;
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,9 @@ public final class HorizonClient implements ClientModInitializer {
|
||||
private static Recording frames;
|
||||
private static long previousStart;
|
||||
private static String profile = "custom";
|
||||
private static DistantTerrainBudget terrainBudget;
|
||||
private static long previousBudgetFrame;
|
||||
private static int targetFps = 60;
|
||||
|
||||
@Override public void onInitializeClient() {
|
||||
KeyMapping benchmarkKey = KeyMappingHelper.registerKeyMapping(new KeyMapping(
|
||||
@@ -41,6 +44,15 @@ public final class HorizonClient implements ClientModInitializer {
|
||||
try {
|
||||
if (Files.exists(profileFile)) profile = Files.readString(profileFile).strip();
|
||||
} catch (Exception error) { HorizonLab.LOGGER.warn("Profile label could not be read", error); }
|
||||
Path budgetFile = FabricLoader.getInstance().getConfigDir().resolve("horizon-adaptive.properties");
|
||||
try {
|
||||
if (Files.exists(budgetFile)) {
|
||||
var properties = new java.util.Properties();
|
||||
try (var reader = Files.newBufferedReader(budgetFile)) { properties.load(reader); }
|
||||
targetFps = Math.clamp(Integer.parseInt(properties.getProperty("targetFps", "60")), 10, 240);
|
||||
if (Boolean.parseBoolean(properties.getProperty("enabled", "false"))) enableBudget();
|
||||
}
|
||||
} catch (Exception error) { HorizonLab.LOGGER.warn("Adaptive budget disabled: invalid configuration", error); }
|
||||
ClientCommandRegistrationCallback.EVENT.register((dispatcher, context) -> dispatcher.register(
|
||||
literal("horizon")
|
||||
.then(literal("bench")
|
||||
@@ -51,8 +63,22 @@ public final class HorizonClient implements ClientModInitializer {
|
||||
.executes(command -> start(StringArgumentType.getString(command, "label"),
|
||||
IntegerArgumentType.getInteger(command, "seconds"))))))
|
||||
.then(literal("stop").executes(command -> { finish(); return 1; }))
|
||||
.then(literal("adaptive")
|
||||
.then(literal("on").executes(command -> {
|
||||
if (frames != null) { message("Finish the recording before changing the budget"); return 0; }
|
||||
message(enableBudget() ? "Adaptive terrain budget enabled" : "Distant Horizons is required");
|
||||
return 1;
|
||||
}))
|
||||
.then(literal("off").executes(command -> {
|
||||
if (frames != null) { message("Finish the recording before changing the budget"); return 0; }
|
||||
if (terrainBudget != null) terrainBudget.suspend();
|
||||
terrainBudget = null;
|
||||
previousBudgetFrame = 0;
|
||||
message("Adaptive terrain budget disabled"); return 1;
|
||||
})))
|
||||
.then(literal("status").executes(command -> {
|
||||
message("Profile: " + profile + "; recording: " + (frames != null)); return 1;
|
||||
message("Profile: " + profile + "; recording: " + (frames != null)
|
||||
+ "; adaptive: " + (terrainBudget == null ? "off" : terrainBudget.status())); return 1;
|
||||
}))));
|
||||
HorizonLab.LOGGER.info("Horizon client profile: {}. F8 or /horizon bench <label> [seconds]", profile);
|
||||
}
|
||||
@@ -64,6 +90,8 @@ public final class HorizonClient implements ClientModInitializer {
|
||||
Map<String, Object> context = new LinkedHashMap<>();
|
||||
context.put("minecraft", "26.3");
|
||||
context.put("profile", profile);
|
||||
context.put("adaptive_budget_enabled", terrainBudget != null);
|
||||
context.put("adaptive_target_fps", targetFps);
|
||||
context.put("render_distance", client.options.renderDistance().get());
|
||||
context.put("simulation_distance", client.options.simulationDistance().get());
|
||||
context.put("vsync", client.options.enableVsync().get());
|
||||
@@ -95,17 +123,33 @@ public final class HorizonClient implements ClientModInitializer {
|
||||
|
||||
public static void frameStart() {
|
||||
Recording recording = frames;
|
||||
if (recording == null) return;
|
||||
if (recording == null && terrainBudget == null) return;
|
||||
long now = System.nanoTime();
|
||||
if (now >= recording.deadlineNs) { finish(); return; }
|
||||
if (recording != null && now >= recording.deadlineNs) { finish(); recording = null; }
|
||||
Minecraft client = Minecraft.getInstance();
|
||||
if (client.level == null || client.isPaused() || !client.isWindowActive() || client.gui.screen() != null) {
|
||||
recording.exclude();
|
||||
if (recording != null) recording.exclude();
|
||||
if (terrainBudget != null && previousBudgetFrame != 0) terrainBudget.suspend();
|
||||
previousBudgetFrame = 0;
|
||||
previousStart = 0;
|
||||
return;
|
||||
}
|
||||
if (previousStart != 0) recording.add(now - previousStart);
|
||||
previousStart = now;
|
||||
if (terrainBudget != null) {
|
||||
int cap = client.options.framerateLimit().get();
|
||||
double targetMs = 1000.0 / Math.min(targetFps, Math.max(1, cap));
|
||||
terrainBudget.observe(now, previousBudgetFrame == 0 ? 0 : now - previousBudgetFrame, targetMs);
|
||||
previousBudgetFrame = now;
|
||||
}
|
||||
if (recording != null) {
|
||||
if (previousStart != 0) recording.add(now - previousStart);
|
||||
previousStart = now;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean enableBudget() {
|
||||
if (!FabricLoader.getInstance().isModLoaded("distanthorizons")) return false;
|
||||
if (terrainBudget == null) terrainBudget = new DistantTerrainBudget();
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void finish() {
|
||||
|
||||
@@ -22,6 +22,14 @@ public final class Recording {
|
||||
private int peakPlayers;
|
||||
private final long initialGcCount;
|
||||
private final long initialGcMs;
|
||||
private final java.lang.management.MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
|
||||
private final com.sun.management.OperatingSystemMXBean operatingSystem =
|
||||
ManagementFactory.getOperatingSystemMXBean() instanceof com.sun.management.OperatingSystemMXBean bean ? bean : null;
|
||||
private final long initialCpuNs;
|
||||
private long nextResourceSampleNs;
|
||||
private long peakHeap;
|
||||
private long peakNonHeap;
|
||||
private int resourceSamples;
|
||||
|
||||
public Recording(String label, String kind, Path output, int seconds, Map<String, Object> context) {
|
||||
if (seconds < 1 || seconds > 600) throw new IllegalArgumentException("Duration must be 1..600 seconds");
|
||||
@@ -34,10 +42,14 @@ public final class Recording {
|
||||
this.deadlineNs = startedNs + seconds * 1_000_000_000L;
|
||||
this.initialGcCount = gcCount();
|
||||
this.initialGcMs = gcMs();
|
||||
this.initialCpuNs = operatingSystem == null ? -1 : operatingSystem.getProcessCpuTime();
|
||||
sampleResources(startedNs);
|
||||
}
|
||||
|
||||
public synchronized void add(long ns) {
|
||||
if (ns <= 0) return;
|
||||
long now = System.nanoTime();
|
||||
if (now >= nextResourceSampleNs) sampleResources(now);
|
||||
if (count == samples.length) { dropped++; return; }
|
||||
samples[count++] = ns;
|
||||
}
|
||||
@@ -46,6 +58,7 @@ public final class Recording {
|
||||
public synchronized void players(int players) { peakPlayers = Math.max(players, peakPlayers); }
|
||||
|
||||
public synchronized Snapshot finish() {
|
||||
sampleResources(System.nanoTime());
|
||||
Map<String, Object> metadata = new LinkedHashMap<>(context);
|
||||
metadata.put("label", label);
|
||||
metadata.put("kind", kind);
|
||||
@@ -61,14 +74,33 @@ public final class Recording {
|
||||
metadata.put("os_version", System.getProperty("os.version"));
|
||||
metadata.put("architecture", System.getProperty("os.arch"));
|
||||
metadata.put("logical_processors", Runtime.getRuntime().availableProcessors());
|
||||
metadata.put("heap_used_end_bytes", ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed());
|
||||
metadata.put("heap_committed_end_bytes", ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getCommitted());
|
||||
var endHeap = memory.getHeapMemoryUsage();
|
||||
peakHeap = Math.max(peakHeap, endHeap.getUsed());
|
||||
metadata.put("heap_used_end_bytes", endHeap.getUsed());
|
||||
metadata.put("heap_committed_end_bytes", endHeap.getCommitted());
|
||||
metadata.put("heap_max_bytes", Runtime.getRuntime().maxMemory());
|
||||
metadata.put("heap_used_peak_sampled_bytes", peakHeap);
|
||||
metadata.put("nonheap_used_peak_sampled_bytes", peakNonHeap);
|
||||
metadata.put("resource_samples", resourceSamples);
|
||||
metadata.put("resource_sample_interval_ms", 1000);
|
||||
long endCpuNs = operatingSystem == null ? -1 : operatingSystem.getProcessCpuTime();
|
||||
if (initialCpuNs >= 0 && endCpuNs >= initialCpuNs) {
|
||||
double cpuSeconds = (endCpuNs - initialCpuNs) / 1e9;
|
||||
metadata.put("process_cpu_seconds", cpuSeconds);
|
||||
metadata.put("process_cpu_mean_cores", cpuSeconds / elapsed);
|
||||
}
|
||||
metadata.put("gc_collections", gcCount() - initialGcCount);
|
||||
metadata.put("gc_time_ms", gcMs() - initialGcMs);
|
||||
return new Snapshot(label, kind, output, Arrays.copyOf(samples, count), metadata);
|
||||
}
|
||||
|
||||
private void sampleResources(long now) {
|
||||
peakHeap = Math.max(peakHeap, memory.getHeapMemoryUsage().getUsed());
|
||||
peakNonHeap = Math.max(peakNonHeap, memory.getNonHeapMemoryUsage().getUsed());
|
||||
resourceSamples++;
|
||||
nextResourceSampleNs = now + 1_000_000_000L;
|
||||
}
|
||||
|
||||
private static long gcCount() {
|
||||
return ManagementFactory.getGarbageCollectorMXBeans().stream()
|
||||
.mapToLong(gc -> Math.max(0, gc.getCollectionCount())).sum();
|
||||
|
||||
@@ -1,17 +1,25 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"id": "horizonlab",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.0",
|
||||
"name": "Horizon Lab",
|
||||
"description": "Client frame pacing and server tick measurements for reproducible optimization experiments.",
|
||||
"authors": ["Ludovic"],
|
||||
"authors": [
|
||||
"Ludovic"
|
||||
],
|
||||
"license": "MIT",
|
||||
"environment": "*",
|
||||
"entrypoints": {
|
||||
"main": ["dev.horizonlab.HorizonLab"],
|
||||
"client": ["dev.horizonlab.client.HorizonClient"]
|
||||
"main": [
|
||||
"dev.horizonlab.HorizonLab"
|
||||
],
|
||||
"client": [
|
||||
"dev.horizonlab.client.HorizonClient"
|
||||
]
|
||||
},
|
||||
"mixins": ["horizonlab.mixins.json"],
|
||||
"mixins": [
|
||||
"horizonlab.mixins.json"
|
||||
],
|
||||
"depends": {
|
||||
"fabricloader": ">=0.19.5",
|
||||
"fabric-api": "*",
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
package dev.horizonlab.budget;
|
||||
|
||||
public final class TerrainBudgetTest {
|
||||
private static void check(boolean value, String reason) { if (!value) throw new AssertionError(reason); }
|
||||
public static void main(String[] args) {
|
||||
TerrainBudget budget = new TerrainBudget(0.5);
|
||||
for (int i = 0; i < 100; i++) budget.update(0.5, 40, 16.667, 0.5, 0.3);
|
||||
check(budget.ratio() == 0.05, "Sustained pressure reaches a nonzero floor");
|
||||
for (int i = 0; i < 2; i++) budget.update(0.5, 10, 16.667, 0, 0.3);
|
||||
check(budget.ratio() == 0.05, "Recovery requires three healthy windows");
|
||||
budget.update(0.5, 10, 16.667, 0, 0.3);
|
||||
check(Math.abs(budget.ratio() - 0.075) < 1e-9, "Recovery is gradual");
|
||||
for (int i = 0; i < 1000; i++) budget.update(0.5, 10, 16.667, 0, 0.3);
|
||||
check(budget.ratio() == 0.5, "Recovery never exceeds the user's ceiling");
|
||||
check(budget.update(0.02, 40, 16.667, 0.5, 0.3) == 0.02, "Respect a user ceiling below our floor");
|
||||
budget = new TerrainBudget(0.5);
|
||||
check(budget.update(0.5, 10, 16.667, 0, 0.9) < 0.5, "Heap pressure reduces work");
|
||||
budget = new TerrainBudget(0.5);
|
||||
check(budget.update(0.5, 33.3, 1000.0 / 30, 0, 0.3) == 0.5, "Respect a 30 FPS cap");
|
||||
budget = new TerrainBudget(0.5);
|
||||
for (int i = 0; i < 100; i++) {
|
||||
budget.update(0.5, 40, 16.667, 0.5, 0.3);
|
||||
budget.update(0.5, 10, 16.667, 0, 0.3);
|
||||
}
|
||||
check(budget.ratio() == 0.05, "Alternating pressure cannot trigger rapid recovery");
|
||||
try { budget.update(0.5, Double.NaN, 16, 0, 0); throw new AssertionError("NaN accepted"); }
|
||||
catch (IllegalArgumentException expected) { }
|
||||
System.out.println("Terrain budget tests passed");
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,12 @@ public final class MetricsTest {
|
||||
check(snapshot.metadata().get("dropped_samples").equals(2), "overflow reported");
|
||||
check(snapshot.metadata().get("excluded_frames").equals(1), "excluded frames reported");
|
||||
check(snapshot.metadata().get("peak_players").equals(50), "workload size reported");
|
||||
check((long) snapshot.metadata().get("heap_used_peak_sampled_bytes") >=
|
||||
(long) snapshot.metadata().get("heap_used_end_bytes"), "heap peak includes the final sample");
|
||||
check((int) snapshot.metadata().get("resource_samples") >= 2, "start/end resource snapshots");
|
||||
if (snapshot.metadata().containsKey("process_cpu_seconds")) {
|
||||
check((double) snapshot.metadata().get("process_cpu_seconds") >= 0, "CPU time is nonnegative");
|
||||
}
|
||||
check(!snapshot.label().contains("/"), "safe report filename");
|
||||
System.out.println("Metrics tests passed.");
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
PACK="$PWD/horizon-m2-balanced-0.2.0.mrpack"
|
||||
PACK="$PWD/horizon-m2-balanced-@PACK_VERSION@.mrpack"
|
||||
if [[ ! -f "$PACK" ]]; then
|
||||
printf 'Keep this script beside the .mrpack files from the extracted starter ZIP.\n'
|
||||
exit 1
|
||||
|
||||
+12
-3
@@ -1,11 +1,11 @@
|
||||
HORIZON LAB 0.2.0 — first playable optimization release
|
||||
HORIZON LAB @PACK_VERSION@ — playable optimization experiments
|
||||
|
||||
YOUR MAC
|
||||
1. Extract this ZIP. Double-click Mac-Start.command. If macOS asks, use Open
|
||||
from the file's context menu. It installs the official Prism Launcher in
|
||||
~/Applications if needed and opens the M2 balanced pack import.
|
||||
Alternatively install Prism yourself: https://prismlauncher.org/download/macOS/
|
||||
then Add Instance > Import > horizon-m2-balanced-0.2.0.mrpack.
|
||||
then Add Instance > Import > horizon-m2-balanced-@PACK_VERSION@.mrpack.
|
||||
2. Sign into your Microsoft account in Prism yourself. No credentials are
|
||||
shared with this project. You need an owned Minecraft Java license.
|
||||
3. Enable Prism automatic Java downloads, using Java 25 ARM64 on Apple Silicon.
|
||||
@@ -27,6 +27,13 @@ PROFILES
|
||||
- baseline: original game renderer and simulation with Fabric API and the same
|
||||
Horizon timing instrument. 12 full-detail chunks, no performance mods or LOD.
|
||||
Use the SAME 6144 MiB maximum heap as m2-balanced for a fair comparison.
|
||||
- adaptive: same render distances, worker count and mods as m2-balanced, with
|
||||
experimental foreground-first terrain work scheduling. /horizon adaptive off
|
||||
disables it; /horizon adaptive on enables it. /horizon status shows its budget.
|
||||
It reduces DH background duty cycle when frames fall below a 60 FPS target or
|
||||
heap usage exceeds 85%, then recovers gradually. Distant terrain can take longer
|
||||
to appear. It does not reduce your view distance or change normal simulation.
|
||||
This is a heuristic, not proof that background work caused a slow frame.
|
||||
- low-memory: 8 full-detail chunks, no LOD. Set maximum memory 3072 MiB.
|
||||
For a matched comparison set both instances to the same render distance.
|
||||
- far-distance: 12 full-detail plus 256 LOD chunks. Start with 8192 MiB ONLY on
|
||||
@@ -57,7 +64,9 @@ MEASURE ON YOUR M2 PRO
|
||||
/horizon status shows the profile. F8 also works when chat is restricted.
|
||||
4. Open Prism's instance Minecraft folder > horizon-benchmarks. Each run writes
|
||||
frames JSON/CSV and integrated-server ticks JSON/CSV. They include average FPS,
|
||||
slowest-1%-average FPS, p95/p99 frame durations, stalls and JVM heap/GC data.
|
||||
slowest-1%-average FPS, p95/p99 frame durations, stalls, sampled peak JVM heap,
|
||||
process CPU time and GC data. Heap is sampled once per second during gameplay;
|
||||
shorter peaks can be missed. CPU measurement spans the whole recording.
|
||||
Menus, pauses and unfocused frames are excluded. Tick execution time is not
|
||||
the observed TPS. JVM heap is not whole-process memory or unified GPU memory.
|
||||
5. Repeat at least three times, alternating baseline/optimized. For daily play
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"minecraft": "26.3",
|
||||
"java_major": 25,
|
||||
"fabric_loader": "0.19.5",
|
||||
"pack_version": "0.2.0",
|
||||
"pack_version": "0.3.0",
|
||||
"projects": {
|
||||
"sodium": {
|
||||
"slug": "sodium",
|
||||
|
||||
+2
-1
@@ -39,7 +39,8 @@ class PackTests(unittest.TestCase):
|
||||
pack = build_pack.build("m2-balanced", original)
|
||||
with zipfile.ZipFile(pack) as archive:
|
||||
names = archive.namelist()
|
||||
self.assertEqual([n for n in names if n.endswith(".jar")], ["overrides/mods/horizon-lab-0.2.0.jar"])
|
||||
self.assertEqual([n for n in names if n.endswith(".jar")],
|
||||
[f"overrides/mods/horizon-lab-{build_pack.read_lock()['pack_version']}.jar"])
|
||||
index = json.loads(archive.read("modrinth.index.json"))
|
||||
self.assertEqual(index["dependencies"]["minecraft"], "26.3")
|
||||
for entry in index["files"]:
|
||||
|
||||
@@ -28,11 +28,18 @@ def test_metrics():
|
||||
sources.append(SOURCE / "test/java/dev/horizonlab/metrics/MetricsTest.java")
|
||||
subprocess.run(["javac", "--release", "25", "-d", str(destination), *map(str, sources)], check=True)
|
||||
subprocess.run(["java", "-cp", str(destination), "dev.horizonlab.metrics.MetricsTest"], check=True)
|
||||
budget_sources = [SOURCE / "main/java/dev/horizonlab/budget/TerrainBudget.java",
|
||||
SOURCE / "test/java/dev/horizonlab/budget/TerrainBudgetTest.java"]
|
||||
subprocess.run(["javac", "--release", "25", "-d", str(destination), *map(str, budget_sources)], check=True)
|
||||
subprocess.run(["java", "-cp", str(destination), "dev.horizonlab.budget.TerrainBudgetTest"], check=True)
|
||||
|
||||
|
||||
def build():
|
||||
lock = json.loads((ROOT / "packs/mods.lock.json").read_text())
|
||||
_, jars, _ = runtime.prepare_client(assets=False)
|
||||
dh = lock["projects"]["distanthorizons"]
|
||||
jars.append(runtime.fetch(dh["url"], ROOT / ".local/pack-cache" / dh["filename"],
|
||||
dh["hashes"]["sha512"], "sha512"))
|
||||
api = lock["projects"]["fabric-api"]
|
||||
api_jar = runtime.fetch(api["url"], ROOT / ".local/pack-cache" / api["filename"],
|
||||
api["hashes"]["sha512"], "sha512")
|
||||
|
||||
+6
-3
@@ -18,6 +18,7 @@ CORE = ["fabric-api", "sodium", "lithium", "ferrite-core", "immediatelyfast", "e
|
||||
PROFILES = {
|
||||
"baseline": {"title": "Vanilla baseline", "mods": ["fabric-api"], "render": 12, "lod": 0, "heap": 6144},
|
||||
"m2-balanced": {"title": "M2 Pro balanced", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144},
|
||||
"adaptive": {"title": "Adaptive terrain experiment", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 128, "heap": 6144, "adaptive": True},
|
||||
"low-memory": {"title": "Low memory", "mods": CORE, "render": 8, "lod": 0, "heap": 3072},
|
||||
"far-distance": {"title": "Far distance", "mods": CORE + ["distanthorizons"], "render": 12, "lod": 256, "heap": 8192},
|
||||
"cinematic": {"title": "Cinematic (optional)", "mods": CORE + ["distanthorizons", "iris", "complementary-reimagined"], "render": 12, "lod": 128, "heap": 6144},
|
||||
@@ -67,10 +68,12 @@ def options(profile):
|
||||
|
||||
def overrides(profile_name, mod_bytes):
|
||||
profile = PROFILES[profile_name]
|
||||
files = {"mods/horizon-lab-0.2.0.jar": mod_bytes,
|
||||
files = {f"mods/horizon-lab-{read_lock()['pack_version']}.jar": mod_bytes,
|
||||
"config/horizon-profile.txt": (profile_name + "\n").encode(),
|
||||
"options.txt": options(profile).encode()}
|
||||
config = ROOT / "packs/config" / f"{profile_name}.toml"
|
||||
config = ROOT / "packs/config" / f"{'m2-balanced' if profile_name == 'adaptive' else profile_name}.toml"
|
||||
files["config/horizon-adaptive.properties"] = (
|
||||
f"enabled={str(profile.get('adaptive', False)).lower()}\ntargetFps=60\n").encode()
|
||||
if profile["lod"]:
|
||||
if not config.exists():
|
||||
raise FileNotFoundError(f"Missing verified DH profile config: {config}")
|
||||
@@ -136,7 +139,7 @@ def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--profile", choices=PROFILES)
|
||||
parser.add_argument("--instance", type=Path, help="Local demo smoke-test directory (no normal account launch)")
|
||||
parser.add_argument("--mod", type=Path, default=ROOT / "dist/horizon-lab-0.2.0.jar")
|
||||
parser.add_argument("--mod", type=Path, default=ROOT / "dist" / f"horizon-lab-{read_lock()['pack_version']}.jar")
|
||||
args = parser.parse_args()
|
||||
if not args.mod.exists():
|
||||
parser.error("Build the original mod first: python3 tools/build_mod.py")
|
||||
|
||||
@@ -20,8 +20,8 @@ def main():
|
||||
raise FileNotFoundError("Run tools/build_mod.py first")
|
||||
packs = [build_pack.build(profile, mod) for profile in build_pack.PROFILES]
|
||||
client = {pack.name: pack.read_bytes() for pack in packs}
|
||||
client["START-HERE.txt"] = (ROOT / "packs/START-HERE.txt").read_bytes()
|
||||
client["Mac-Start.command"] = (ROOT / "packs/Mac-Start.command").read_bytes()
|
||||
client["START-HERE.txt"] = (ROOT / "packs/START-HERE.txt").read_text().replace("@PACK_VERSION@", version).encode()
|
||||
client["Mac-Start.command"] = (ROOT / "packs/Mac-Start.command").read_text().replace("@PACK_VERSION@", version).encode()
|
||||
client["LICENSE"] = (ROOT / "LICENSE").read_bytes()
|
||||
build_pack.write_zip(ROOT / "dist" / f"horizon-mac-starter-{version}.zip", client)
|
||||
server = {"LICENSE": client["LICENSE"], "dist/" + mod.name: mod.read_bytes(),
|
||||
@@ -32,7 +32,7 @@ def main():
|
||||
for name in ["mods.lock.json", "fabric.lock.json"]:
|
||||
server["packs/" + name] = (ROOT / "packs" / name).read_bytes()
|
||||
build_pack.write_zip(ROOT / "dist" / f"horizon-server-starter-{version}.zip", server)
|
||||
artifacts = sorted((ROOT / "dist").glob("*"))
|
||||
artifacts = sorted(path for path in (ROOT / "dist").glob("*") if version in path.name)
|
||||
checksums = []
|
||||
for path in artifacts:
|
||||
if path.suffix in [".jar", ".mrpack", ".zip"]:
|
||||
|
||||
@@ -36,7 +36,8 @@ def compare(baseline, candidate):
|
||||
before, after = baseline["stats"][key], candidate["stats"][key]
|
||||
rows.append({"metric": key, "baseline": before, "candidate": after,
|
||||
"change_percent": 100 * (after / before - 1) if before else None})
|
||||
for key in ["heap_used_end_bytes", "gc_time_ms", "observed_ticks_per_second"]:
|
||||
for key in ["heap_used_end_bytes", "heap_used_peak_sampled_bytes", "nonheap_used_peak_sampled_bytes",
|
||||
"process_cpu_mean_cores", "gc_time_ms", "observed_ticks_per_second"]:
|
||||
if key in baseline and key in candidate:
|
||||
before, after = baseline[key], candidate[key]
|
||||
rows.append({"metric": key, "baseline": before, "candidate": after,
|
||||
|
||||
+3
-2
@@ -27,7 +27,8 @@ def prepare(instance, baseline=False):
|
||||
launcher = runtime.fetch(artifact["url"], directory / "jars/server.jar", artifact["sha1"])
|
||||
server, libraries = lab.unpack_server(launcher, directory, game["version"])
|
||||
libraries = [server, *libraries, *runtime.fabric_libraries()]
|
||||
mods = json.loads((ROOT / "packs/mods.lock.json").read_text())["projects"]
|
||||
pack_lock = json.loads((ROOT / "packs/mods.lock.json").read_text())
|
||||
mods = pack_lock["projects"]
|
||||
selection = ["fabric-api"] if baseline else ["fabric-api", "lithium", "ferrite-core"]
|
||||
mod_dir = instance / "mods"
|
||||
mod_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -36,7 +37,7 @@ def prepare(instance, baseline=False):
|
||||
source = runtime.fetch(entry["url"], ROOT / ".local/pack-cache" / entry["filename"],
|
||||
entry["hashes"]["sha512"], "sha512")
|
||||
shutil.copyfile(source, mod_dir / entry["filename"])
|
||||
original = ROOT / "dist/horizon-lab-0.2.0.jar"
|
||||
original = ROOT / "dist" / f"horizon-lab-{pack_lock['pack_version']}.jar"
|
||||
if not original.exists():
|
||||
raise FileNotFoundError("Build the original mod first with tools/build_mod.py, or use the server starter ZIP")
|
||||
shutil.copyfile(original, mod_dir / original.name)
|
||||
|
||||
Reference in New Issue
Block a user