yash gautam

OPRO FPS v2 — AI Build Script

> Paste this whole file into any coding AI (or follow it by hand) to produce the same mod. > Target: Fabric, Minecraft 1.21.11, Java 21, client-side only. > Goal: raise 1% lows and frame-time stability on weak PCs by actually changing costly settings at runtime, safely and reversibly.

---

0. Instructions to the AI executing this script

  1. Do the steps in order. Do not skip Step 3 (symbol verification) or Step 7 (tests).
  2. Never guess a Minecraft/Yarn symbol. If something does not compile, run ./gradlew genSources, grep the decompiled sources, and fix the name. Record every rename you make in NOTES.md.
  3. Do not add features that are not in this script. Do not claim FPS numbers. Only measured results go in the README.
  4. If you cannot run Gradle, say so clearly and deliver the source as "unbuilt".
  5. Output: a complete project folder + NOTES.md listing what was verified and what was not.

---

1. Why v2 exists (problems found in v1 uploads)

| # | v1 problem | Consequence | v2 fix | |---|-----------|-------------|--------| | 1 | RenderBudgetGovernor, LatencyGovernor, AdaptivePerformanceEngine, AutoTune compute values that nothing applies | The mod changes zero FPS; it only displays numbers | One controller whose output is applied to real GameOptions (Step 5) | | 2 | PerformanceMonitor.recalculateLows() copies and sorts the sample array every frame and is synchronized | Allocation + O(n log n) per frame on the render thread; contradicts "low allocation" | Preallocated scratch array, recompute every 15 frames, no locks | | 3 | Heap "pressure" = totalMemory - freeMemory | Includes uncollected garbage, so G1 looks permanently "pressured" | Use post-GC occupancy from MemoryPoolMXBean.getCollectionUsage() | | 4 | OproCommands registers on CommandDispatcher<ClientCommandSource> | Does not compile with Fabric's literal() (needs FabricClientCommandSource) | Correct types | | 5 | Two overlapping controllers (AdaptivePerformanceController + AdaptivePerformanceEngine) with different thresholds | Contradictory decisions | One LoadController, pure Java, unit-tested | | 6 | Mixin config defaultRequire: 1 | If the target method changes, the game crashes | defaultRequire: 0 + watchdog that disables the mod safely | | 7 | No restore of changed settings | Degraded values could be saved into options.txt | Baseline capture, restore on disconnect/exit, crash-recovery file |

---

2. Design: "AIMD Quality Ladder" (the new tech)

Borrowed from TCP congestion control and AAA dynamic-quality systems, adapted to what a Fabric client mod can safely do:

  • Signals (all cheap): EWMA frame time, 1% low frame time, post-GC heap ratio.
  • Controller: AIMD — Additive-Increase / Multiplicative-Decrease.

- Bad for ≥ 2 s → degrade 1 level. Severely bad (frame time > 2× target) for ≥ 1 s → degrade 2 levels. - Good for ≥ 20 s → recover 1 level. - A dead band between "good" and "bad" prevents oscillation (hysteresis).

  • Ladder (each level only lowers the user's own baseline, never raises it):

| Level | Applied change (relative to user's baseline) | Cost to apply | |------|-----------------------------------------------|---------------| | 0 | none | — | | 1 | Particles → DECREASED | free | | 2 | Clouds OFF, entity distance ×0.80 | free | | 3 | Particles → MINIMAL, entity distance ×0.65 | free | | 4 | View distance −2 (≥ floor) | chunk reload | | 5 | View distance −4 (≥ floor), entity distance ×0.50 | chunk reload | | 6 | View distance = floor | chunk reload |

  • PvP mode caps the ladder at level 3 (never shrinks view distance, so visibility/reaction is unchanged).
  • Safety rails: only active in a world, window focused, 10 s after joining (chunk-load spike is ignored); detects if the user changes a setting and re-baselines; restores everything on disconnect, game exit, and after a crash.
  • Never touches reach, hitboxes, packets, attack timing, or anything server-side.

Explicitly out of scope (do not implement)

  • Frame generation / DLSS-style upscaling: no motion vectors or depth data exposed; adds latency.
  • Re-implementing Sodium/Lithium/etc. They are detected (optional) but never bundled.
  • Simulation-distance changes (affects server-side load).

---

3. Symbols to VERIFY after first compile (Yarn 1.21.11)

I could not compile in the authoring environment. These are the names most likely to differ; confirm each with genSources:

  • MinecraftClient#render(boolean) (mixin target) and MinecraftClient#isWindowFocused()
  • GameOptions#getViewDistance(), getEntityDistanceScaling(), getParticles(), getCloudRenderMode()
  • Enum ParticlesMode order = ALL, DECREASED, MINIMAL (ordinal logic depends on it)
  • Enum CloudRenderMode has OFF
  • ClientWorld, FabricClientCommandSource#sendFeedback(Text)
  • Fabric events: ClientTickEvents.END_CLIENT_TICK, ClientLifecycleEvents.CLIENT_STARTED/CLIENT_STOPPING, ClientPlayConnectionEvents.DISCONNECT
  • Gradle: latest Loom + Fabric API versions for 1.21.11 from https://fabricmc.net/develop

If CloudRenderMode changed shape, drop the clouds lever (keep the rest) and note it in NOTES.md.

---

4. Project layout

groovy
plugins {
    id 'fabric-loom' version '1.11-SNAPSHOT'   // VERIFY: use current Loom for 1.21.11
    id 'maven-publish'
}

group = project.maven_group
version = project.mod_version
base { archivesName = project.archives_base_name }

repositories { maven { url = 'https://maven.fabricmc.net/' } }

dependencies {
    minecraft "com.mojang:minecraft:${project.minecraft_version}"
    mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2"
    modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
    modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"

    testImplementation platform('org.junit:junit-bom:5.10.2')
    testImplementation 'org.junit.jupiter:junit-jupiter'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

test { useJUnitPlatform() }

processResources {
    inputs.property 'version', project.version
    filesMatching('fabric.mod.json') { expand 'version': project.version }
}

tasks.withType(JavaCompile).configureEach {
    it.options.release = 21
    it.options.encoding = 'UTF-8'
}

java { withSourcesJar() }

---

5. Files (copy exactly, then fix only what the compiler/tests force)

build.gradle

properties
org.gradle.jvmargs=-Xmx2G
org.gradle.parallel=true
minecraft_version=1.21.11
yarn_mappings=1.21.11+build.1
loader_version=0.17.2
fabric_version=0.135.0+1.21.11
mod_version=2.0.0
maven_group=com.oproyash
archives_base_name=opro-fps

gradle.properties

groovy
pluginManagement {
    repositories {
        maven { url = uri("https://maven.fabricmc.net/") }
        gradlePluginPortal()
        mavenCentral()
    }
}
rootProject.name = "opro-fps"

settings.gradle

json
{
  "schemaVersion": 1,
  "id": "opro-fps",
  "version": "${version}",
  "name": "OPRO FPS",
  "description": "Adaptive quality ladder that stabilizes frame times on low-end PCs. Client-side only.",
  "authors": ["oproyash"],
  "license": "MIT",
  "environment": "client",
  "entrypoints": { "client": ["com.oproyash.oprofps.OproFpsClient"] },
  "mixins": ["opro-fps.mixins.json"],
  "depends": {
    "fabricloader": ">=0.17.0",
    "minecraft": "~1.21.11",
    "fabric-api": "*",
    "java": ">=21"
  },
  "recommends": {
    "sodium": "*", "lithium": "*", "ferritecore": "*",
    "immediatelyfast": "*", "modernfix": "*", "entityculling": "*",
    "dynamic_fps": "*"
  }
}

src/main/resources/fabric.mod.json

json
{
  "required": true,
  "package": "com.oproyash.oprofps.mixin",
  "compatibilityLevel": "JAVA_21",
  "client": ["MinecraftClientMixin"],
  "injectors": { "defaultRequire": 0 }
}

src/main/resources/opro-fps.mixins.json

java
package com.oproyash.oprofps.mixin;

import com.oproyash.oprofps.core.OproEngine;
import net.minecraft.client.MinecraftClient;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

/** One call per frame. HEAD-to-HEAD interval = true frame period (includes vsync wait). */
@Mixin(MinecraftClient.class)
public abstract class MinecraftClientMixin {
    @Inject(method = "render", at = @At("HEAD"))
    private void opro$frame(boolean tick, CallbackInfo ci) {
        OproEngine.INSTANCE.monitor().onFrame();
    }
}

mixin/MinecraftClientMixin.java

java
package com.oproyash.oprofps.telemetry;

import java.util.Arrays;

/** Frame telemetry. Render-thread only. No allocation after construction. */
public final class PerformanceMonitor {
    private static final int CAP = 600;
    private final float[] ring = new float[CAP];
    private final float[] scratch = new float[CAP];
    private int idx, count;
    private long lastNanos;
    private long frames;
    private double lastMs;
    private double ewmaMs = 16.7;
    private double p1LowMs, p01LowMs;

    public void start() {
        lastNanos = System.nanoTime();
        idx = 0; count = 0; frames = 0;
    }

    /** Called once per rendered frame by the mixin. */
    public void onFrame() {
        long now = System.nanoTime();
        double ms = (now - lastNanos) / 1_000_000.0;
        lastNanos = now;
        recordMs(ms);
    }

    /** Public for tests. Ignores non-positive and >1s gaps (loading/pauses). */
    public void recordMs(double ms) {
        if (ms <= 0.0 || ms > 1000.0) return;
        lastMs = ms;
        ewmaMs += 0.1 * (ms - ewmaMs);
        ring[idx] = (float) ms;
        idx = (idx + 1) % CAP;
        if (count < CAP) count++;
        frames++;
        if ((frames % 15) == 0) refreshLows();
    }

    public void refreshLows() {
        if (count < 30) return;
        System.arraycopy(ring, 0, scratch, 0, count);
        Arrays.sort(scratch, 0, count);
        p1LowMs = avgWorst(Math.max(1, (count + 99) / 100));
        p01LowMs = avgWorst(Math.max(1, (count + 999) / 1000));
    }

    private double avgWorst(int n) {
        double sum = 0;
        for (int i = count - n; i < count; i++) sum += scratch[i];
        return sum / n;
    }

    public double frameMs() { return lastMs; }
    public double ewmaMs() { return ewmaMs; }
    public double fps() { return ewmaMs > 0 ? 1000.0 / ewmaMs : 0; }
    public double p1LowMs() { return p1LowMs; }
    public double p1LowFps() { return p1LowMs > 0 ? 1000.0 / p1LowMs : 0; }
    public double p01LowFps() { return p01LowMs > 0 ? 1000.0 / p01LowMs : 0; }
    public long frames() { return frames; }
}

telemetry/PerformanceMonitor.java (pure Java, no MC imports)

java
package com.oproyash.oprofps.telemetry;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryType;
import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.List;

/** Heap occupancy measured right after the last GC (ignores uncollected garbage). */
public final class HeapPressure {
    private final List<MemoryPoolMXBean> pools = new ArrayList<>();
    private long lastRefreshMs;
    private double ratio;

    public HeapPressure() {
        for (MemoryPoolMXBean p : ManagementFactory.getMemoryPoolMXBeans()) {
            if (p.getType() == MemoryType.HEAP && p.isCollectionUsageThresholdSupported()) pools.add(p);
        }
    }

    /** Refreshes at most once per second. */
    public double postGcRatio(long nowMs) {
        if (nowMs - lastRefreshMs < 1000) return ratio;
        lastRefreshMs = nowMs;
        long used = 0;
        for (MemoryPoolMXBean p : pools) {
            MemoryUsage u = p.getCollectionUsage();
            if (u != null) used += Math.max(0, u.getUsed());
        }
        long max = Runtime.getRuntime().maxMemory();
        ratio = max > 0 ? Math.min(1.0, used / (double) max) : 0;
        return ratio;
    }
}

telemetry/HeapPressure.java (pure Java)

java
package com.oproyash.oprofps.core;

/** AIMD quality-level controller. Deterministic: time is passed in, so it is unit-testable. */
public final class LoadController {
    private final double targetMs;
    private final long degradeHoldMs;
    private final long upgradeHoldMs;
    private int maxLevel;
    private int level;
    private long badSince = -1, goodSince = -1;
    private long lastChangeMs = -1_000_000_000L;

    public LoadController(double targetMs, long degradeHoldMs, long upgradeHoldMs, int maxLevel) {
        this.targetMs = targetMs;
        this.degradeHoldMs = degradeHoldMs;
        this.upgradeHoldMs = upgradeHoldMs;
        this.maxLevel = maxLevel;
    }

    public int update(long nowMs, double ewmaMs, double p1Ms, double heapPostGc, boolean active) {
        if (!active) { badSince = -1; goodSince = -1; return level; }

        boolean severe = ewmaMs > targetMs * 2.0;
        boolean bad = severe
                || ewmaMs > targetMs * 1.10
                || (p1Ms > targetMs * 2.5 && ewmaMs > targetMs * 0.95)
                || heapPostGc > 0.88;
        boolean good = ewmaMs < targetMs * 0.85 && p1Ms < targetMs * 1.8 && heapPostGc < 0.75;

        if (bad) {
            goodSince = -1;
            if (badSince < 0) badSince = nowMs;
            long hold = severe ? degradeHoldMs / 2 : degradeHoldMs;
            if (nowMs - badSince >= hold && nowMs - lastChangeMs >= hold && level < maxLevel) {
                level = Math.min(maxLevel, level + (severe ? 2 : 1));
                lastChangeMs = nowMs;
                badSince = nowMs;
            }
        } else if (good) {
            badSince = -1;
            if (goodSince < 0) goodSince = nowMs;
            if (nowMs - goodSince >= upgradeHoldMs && nowMs - lastChangeMs >= upgradeHoldMs && level > 0) {
                level--;
                lastChangeMs = nowMs;
                goodSince = nowMs;
            }
        } else { // dead band: do nothing, restart timers
            badSince = -1; goodSince = -1;
        }
        return level;
    }

    public void reset() { level = 0; badSince = -1; goodSince = -1; }
    public int level() { return level; }
    public int maxLevel() { return maxLevel; }
    public void setMaxLevel(int m) { maxLevel = Math.max(0, m); level = Math.min(level, maxLevel); }
    public double targetMs() { return targetMs; }
}

core/LoadController.java (pure Java — the brain)

java
package com.oproyash.oprofps.config;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;

public final class OproConfig {
    public boolean enabled = true;
    public boolean pvpMode = false;
    public int targetFps = 0;        // 0 = auto from hardware
    public int minViewDistance = 0;  // 0 = auto from hardware
    private Path path;

    public void load(Path configDir) {
        path = configDir.resolve("opro-fps.properties");
        Properties p = new Properties();
        if (Files.isRegularFile(path)) {
            try (var in = Files.newInputStream(path)) { p.load(in); } catch (IOException ignored) {}
        }
        enabled = Boolean.parseBoolean(p.getProperty("enabled", "true"));
        pvpMode = Boolean.parseBoolean(p.getProperty("pvp_mode", "false"));
        targetFps = parseInt(p.getProperty("target_fps"), 0);
        minViewDistance = parseInt(p.getProperty("min_view_distance"), 0);
        applyHardwareDefaults();
        save();
    }

    private void applyHardwareDefaults() {
        int cores = Runtime.getRuntime().availableProcessors();
        long heapGb = Runtime.getRuntime().maxMemory() / (1024L * 1024L * 1024L);
        int autoTarget, autoMinView;
        if (cores <= 2 || heapGb <= 2) { autoTarget = 40; autoMinView = 2; }
        else if (cores <= 4 || heapGb <= 3) { autoTarget = 50; autoMinView = 4; }
        else if (cores <= 8) { autoTarget = 60; autoMinView = 6; }
        else { autoTarget = 60; autoMinView = 8; }
        if (targetFps <= 0) targetFps = autoTarget;
        if (minViewDistance <= 0) minViewDistance = autoMinView;
        targetFps = Math.max(20, Math.min(240, targetFps));
        minViewDistance = Math.max(2, Math.min(32, minViewDistance));
    }

    public void save() {
        if (path == null) return;
        Properties p = new Properties();
        p.setProperty("enabled", Boolean.toString(enabled));
        p.setProperty("pvp_mode", Boolean.toString(pvpMode));
        p.setProperty("target_fps", Integer.toString(targetFps));
        p.setProperty("min_view_distance", Integer.toString(minViewDistance));
        try {
            Files.createDirectories(path.getParent());
            try (var out = Files.newOutputStream(path)) { p.store(out, "OPRO FPS configuration"); }
        } catch (IOException ignored) {}
    }

    private static int parseInt(String s, int fallback) {
        try { return s == null ? fallback : Integer.parseInt(s.trim()); } catch (NumberFormatException e) { return fallback; }
    }
}

config/OproConfig.java

code
opro-fps/
├─ build.gradle
├─ gradle.properties
├─ settings.gradle
├─ NOTES.md                      (you write: verified / not verified / renames)
├─ README.md                     (you write: honest, no invented numbers)
└─ src/
   ├─ main/resources/
   │   ├─ fabric.mod.json
   │   └─ opro-fps.mixins.json
   ├─ main/java/com/oproyash/oprofps/
   │   ├─ OproFpsClient.java
   │   ├─ core/OproEngine.java
   │   ├─ core/LoadController.java        (pure Java)
   │   ├─ telemetry/PerformanceMonitor.java (pure Java)
   │   ├─ telemetry/HeapPressure.java     (pure Java)
   │   ├─ apply/OptionApplier.java
   │   ├─ config/OproConfig.java
   │   ├─ command/OproCommands.java
   │   └─ mixin/MinecraftClientMixin.java
   └─ test/java/com/oproyash/oprofps/
       ├─ LoadControllerTest.java
       └─ PerformanceMonitorTest.java

apply/OptionApplier.java (the part that actually changes FPS)

```java package com.oproyash.oprofps.apply;

import net.minecraft.client.MinecraftClient; import net.minecraft.client.option.CloudRenderMode; import net.minecraft.client.option.GameOptions; import net.minecraft.client.option.ParticlesMode;

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Properties;

/** * Applies a quality level to GameOptions relative to the USER'S baseline. * Never raises a setting above the baseline. Never calls options.write(). */ public final class OptionApplier { private record Snap(int view, double entity, ParticlesMode particles, CloudRenderMode clouds) {}

private static final double[] ENTITY_FACTOR = {1.0, 1.0, 0.80, 0.65, 0.65, 0.50, 0.50}; private static final int[] VIEW_DROP = {0, 0, 0, 0, 2, 4, 99};

private Snap base, applied; private Path recoveryFile;

public void setRecoveryFile(Path p) { this.recoveryFile = p; }

/** @return true if the user changed a setting by hand and we re-baselined (caller must reset level to 0). */ public boolean apply(MinecraftClient mc, int level, int minView) { GameOptions o = mc.options; Snap cur = read(o); if (base == null) { base = cur; applied = cur; } else if (!cur.equals(applied)) { base = cur; applied = cur; return true; }

int lv = Math.max(0, Math.min(level, 6)); Snap want = target(base, lv, minView); if (!want.equals(base) && recoveryFile != null && !Files.exists(recoveryFile)) writeRecovery(base);

if (o.getParticles().getValue() != want.particles()) o.getParticles().setValue(want.particles()); if (o.getCloudRenderMode().getValue() != want.clouds()) o.getCloudRenderMode().setValue(want.clouds()); if (Math.abs(o.getEntityDistanceScaling().getValue() - want.entity()) > 1e-6) o

Kodari AI
KodariOct 10 at 2:38 pm 3
AdaptiveQualityLadder
Client-side Minecraft Fabric mod that stabilizes frame times on low-end PCs through an AIMD (Additive-Increase/Multiplicative-Decrease) quality ladder system. Monitors EWMA frame time, 1% lows, and post-GC heap pressure to automatically adjust particle effects, cloud rendering, entity distance scaling, and view distance relative to user baseline settings. Features hysteresis dead band to prevent oscillation, PvP mode capping ladder at level 3, baseline capture with crash recovery, and restoration of settings on disconnect or exit. Pure Java controller with unit tests, low-allocation telemetry, and safe mixin integration.
  1. Create the Fabric 1.21.11 client mod structure and build metadata.

  2. Implement the telemetry, AIMD controller, config, reversible option applier, lifecycle, and commands.

  3. Add crash recovery, mixin watchdog behavior, unit tests, and honest project notes.

Created the OPRO FPS v2 Fabric 1.21.11 client project with the adaptive quality ladder, option-baseline restoration and crash recovery, lifecycle hooks, watchdog, and /opro commands.

Added unit tests for the controller and frame monitor, plus README and verification notes. The project is unbuilt here; the tests have not been run.

yash gautam

File

Kodari AI
KodariOct 10 at 3:07 pm 1

Which file would you like me to create or edit, and what should it contain?

Kodari can make mistakes. Review important code before using.
Files
src
build.gradle
gradle.properties
IMPORTANT.txt
NOTES.md
README.md
settings.gradle
Code
19 811
src/client/java/com/oproyash/oprofps/OproFpsClient.java
package com.oproyash.oprofps;

import net.fabricmc.api.ClientModInitializer;

public final class OproFpsClient implements ClientModInitializer {
    @Override
    public void onInitializeClient() {
        OproEngine.INSTANCE.initialize();
    }
}