bdf0ae866a
Проект начинается с двух вещей: клиент, который мы действительно собрали, и загрузчик, который является его частью, а не чем-то рядом. Форк - prepare-game.ps1 пересобирает клиент целиком: ванильный jar, SRG и MCP, SpecialSource, FernFlower, патчи, автофиксеры, javac. Идемпотентен. - Свой код игры лежит в src-overlay, потому что src пересоздаётся при каждой сборке и всё написанное вручную там погибает. - 116 патчей в patches/decompiler-fixes.txt. Каждый сверялся с оригинальным байткодом через javap: компиляция не ловит ошибки декомпиляции. - struct_diff.py сравнивает исходный байткод с нашей сборкой по классам, интерфейсам, суперклассам, методам и полям, и отдельно проверяет, что пропавшие классы действительно никому не нужны. Загрузчик - Собирается и тестируется без игры: build.ps1 не использует classpath вообще, поэтому SelfTest из 128 проверок проходит без запущенного форка. - Клиентский API не содержит ни одного игрового типа, реализацию даёт игра. - Политика: мод меняет то, что клиент показывает, но никогда то, что истинно в мире. Мир, предметы, игроки и сеть принадлежат серверу. - Capability приведены в соответствие с этой политикой: осталось шесть, и за каждым стоит реальная проверка. Прежние WORLD, PLAYER, NETWORK, TEXT, INPUT и COMMAND выдавались, но ничего не проверяли. - Команды модов имеют область CLIENT, SERVER или BOTH. Серверные не выполняются на клиенте никогда. - Свой jar загрузчика лежит в classpath игры и сборки форка. Инструменты - add_patch.py, чтобы каждое исправление переживало передекомпиляцию - find_self_comparisons.py, find_remove_index_bugs.py, find_callers.py - stage_run.py и fetch_missing.py для запуска клиента
199 lines
6.7 KiB
Java
199 lines
6.7 KiB
Java
package net.rustnotmc.client;
|
|
|
|
import java.io.File;
|
|
import java.util.List;
|
|
|
|
import net.minecraft.client.Minecraft;
|
|
import net.minecraft.client.gui.ScaledResolution;
|
|
import net.minecraft.client.renderer.GlStateManager;
|
|
import net.rustnotmc.api.client.ClientHost;
|
|
import net.rustnotmc.api.hud.HudLayout;
|
|
import net.rustnotmc.loader.Log;
|
|
import net.rustnotmc.loader.ModContainer;
|
|
import net.rustnotmc.loader.ModLoader;
|
|
|
|
/**
|
|
* Where the client and the mod loader meet.
|
|
*
|
|
* The loader is a library, not an agent. The game calls in at two points: once
|
|
* during startup, and once per frame. Everything a mod does hangs off those two
|
|
* calls, so the loader never has to know how a game loop is shaped.
|
|
*
|
|
* Every entry point is wrapped. A mod that throws must not be able to take the
|
|
* client down with it, and a loader that cannot start must not stop the game
|
|
* from being a game.
|
|
*
|
|
* This file lives in game-fork/src-overlay because src is regenerated from the
|
|
* vanilla jar on every build and anything written there is lost.
|
|
*/
|
|
public final class RsxBootstrap {
|
|
|
|
private static ModLoader loader;
|
|
private static RsxHudSurface surface;
|
|
private static RsxClientServices client;
|
|
private static boolean broken;
|
|
private static boolean frameFailed;
|
|
|
|
private RsxBootstrap() {
|
|
}
|
|
|
|
/** True once mods have been discovered and enabled. */
|
|
public static boolean ready() {
|
|
return loader != null && !broken;
|
|
}
|
|
|
|
public static ModLoader loader() {
|
|
return loader;
|
|
}
|
|
|
|
public static int loadedMods() {
|
|
return loader == null ? 0 : loader.count();
|
|
}
|
|
|
|
/**
|
|
* Discovers and enables mods. Called once, after the client has a display,
|
|
* a font and a resource manager, so a mod may touch any of them.
|
|
*/
|
|
public static synchronized void start(Minecraft minecraft) {
|
|
if (loader != null || broken) {
|
|
return;
|
|
}
|
|
try {
|
|
// the client API goes up before any mod runs, so onConstruct can use
|
|
// it: a mod registers commands and reads the screen there
|
|
client = new RsxClientServices(minecraft);
|
|
ClientHost.install(client);
|
|
|
|
File directory = new File(minecraft.gameDir, "mods");
|
|
loader = new ModLoader(directory);
|
|
|
|
int found = loader.discover();
|
|
Log.info("RustNotMC: scanning " + directory + ", " + found + " mod jar(s)");
|
|
|
|
if (!loader.resolve()) {
|
|
reportProblems();
|
|
broken = true;
|
|
loader = null;
|
|
return;
|
|
}
|
|
|
|
loader.loadAll();
|
|
surface = new RsxHudSurface(minecraft);
|
|
reportProblems();
|
|
|
|
if (loader.count() == 0) {
|
|
Log.info("RustNotMC: no mods loaded");
|
|
return;
|
|
}
|
|
|
|
StringBuilder line = new StringBuilder("RustNotMC: loaded ");
|
|
List<ModContainer> mods = loader.mods();
|
|
for (int i = 0; i < mods.size(); i++) {
|
|
if (i > 0) {
|
|
line.append(", ");
|
|
}
|
|
ModContainer mod = mods.get(i);
|
|
line.append(mod.id()).append(' ').append(mod.version());
|
|
}
|
|
Log.info(line.toString());
|
|
} catch (Throwable throwable) {
|
|
broken = true;
|
|
loader = null;
|
|
Log.error("RustNotMC: mod loader failed to start", throwable);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Offers a typed chat line to the mod commands.
|
|
*
|
|
* Called from the point where a line leaves the client. Returns true when a
|
|
* CLIENT scoped command carried it out and the line must not be sent on.
|
|
* SERVER and BOTH commands return false on purpose: the server is the one
|
|
* that has to see them and decide.
|
|
*/
|
|
public static boolean handleChatCommand(String line) {
|
|
if (client == null || !ClientHost.present()) {
|
|
return false;
|
|
}
|
|
return client.dispatchCommand(line, localName());
|
|
}
|
|
|
|
private static String localName() {
|
|
Minecraft mc = Minecraft.getMinecraft();
|
|
if (mc != null && mc.getSession() != null) {
|
|
return mc.getSession().getUsername();
|
|
}
|
|
return "local";
|
|
}
|
|
|
|
private static void reportProblems() {
|
|
List<String> problems = loader.problems();
|
|
for (int i = 0; i < problems.size(); i++) {
|
|
Log.error("RustNotMC: " + problems.get(i));
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Runs scheduled mod work and draws registered overlays.
|
|
*
|
|
* Called once per frame with the main framebuffer bound and the game's own
|
|
* matrices already unwound, so the overlay sets up its own projection and
|
|
* leaves the state it did not set alone.
|
|
*/
|
|
public static void renderFrame(Minecraft minecraft) {
|
|
if (loader == null || surface == null || !surface.available()) {
|
|
return;
|
|
}
|
|
if (frameFailed) {
|
|
return;
|
|
}
|
|
if (client != null) {
|
|
client.advanceFrame();
|
|
}
|
|
try {
|
|
loader.tick();
|
|
if (client != null) {
|
|
client.advanceTick();
|
|
}
|
|
|
|
ScaledResolution scaled = new ScaledResolution(minecraft);
|
|
int width = scaled.getScaledWidth();
|
|
int height = scaled.getScaledHeight();
|
|
if (width <= 0 || height <= 0) {
|
|
return;
|
|
}
|
|
|
|
// the overlay draws in flat screen space, so depth would fight it
|
|
// and the blend state has to be ours for the duration
|
|
GlStateManager.disableDepth();
|
|
|
|
GlStateManager.pushMatrix();
|
|
GlStateManager.matrixMode(5889);
|
|
GlStateManager.loadIdentity();
|
|
GlStateManager.ortho(0.0D, width, height, 0.0D, 1000.0D, 3000.0D);
|
|
GlStateManager.matrixMode(5888);
|
|
GlStateManager.loadIdentity();
|
|
GlStateManager.translate(0.0F, 0.0F, -2000.0F);
|
|
|
|
GlStateManager.enableBlend();
|
|
GlStateManager.tryBlendFuncSeparate(
|
|
GlStateManager.SourceFactor.SRC_ALPHA,
|
|
GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA,
|
|
GlStateManager.SourceFactor.ONE,
|
|
GlStateManager.DestFactor.ZERO);
|
|
|
|
try {
|
|
HudLayout.render(surface);
|
|
} finally {
|
|
GlStateManager.disableBlend();
|
|
GlStateManager.enableDepth();
|
|
GlStateManager.popMatrix();
|
|
}
|
|
} catch (Throwable throwable) {
|
|
// one bad frame is a bug worth seeing, but it must not become a
|
|
// per-frame stack trace or a dead client
|
|
frameFailed = true;
|
|
Log.error("RustNotMC: overlay rendering failed, disabling overlays", throwable);
|
|
}
|
|
}
|
|
} |