| 1 | package net.minecraft.client;
|
| 2 |
|
| 3 | import com.google.common.collect.ImmutableList;
|
| 4 | import com.mojang.authlib.GameProfile;
|
| 5 | import com.mojang.authlib.exceptions.AuthenticationException;
|
| 6 | import com.mojang.authlib.minecraft.BanDetails;
|
| 7 | import com.mojang.authlib.minecraft.UserApiService;
|
| 8 | import com.mojang.authlib.minecraft.UserApiService.UserFlag;
|
| 9 | import com.mojang.authlib.minecraft.UserApiService.UserProperties;
|
| 10 | import com.mojang.authlib.services.FriendsService;
|
| 11 | import com.mojang.authlib.services.MinecraftServicesDiscoveryService;
|
| 12 | import com.mojang.authlib.services.ProfileActionType;
|
| 13 | import com.mojang.authlib.services.ProfileResult;
|
| 14 | import com.mojang.blaze3d.TracyFrameCapture;
|
| 15 | import com.mojang.blaze3d.pipeline.RenderTarget;
|
| 16 | import com.mojang.blaze3d.platform.ClientShutdownWatchdog;
|
| 17 | import com.mojang.blaze3d.platform.DisplayData;
|
| 18 | import com.mojang.blaze3d.platform.FramerateLimitTracker;
|
| 19 | import com.mojang.blaze3d.platform.IconSet;
|
| 20 | import com.mojang.blaze3d.platform.InputConstants;
|
| 21 | import com.mojang.blaze3d.platform.MacosUtil;
|
| 22 | import com.mojang.blaze3d.platform.MessageBox;
|
| 23 | import com.mojang.blaze3d.platform.MonitorManager;
|
| 24 | import com.mojang.blaze3d.platform.SDLEventHandler;
|
| 25 | import com.mojang.blaze3d.platform.TextInputManager;
|
| 26 | import com.mojang.blaze3d.platform.Window;
|
| 27 | import com.mojang.blaze3d.platform.WindowEventHandler;
|
| 28 | import com.mojang.blaze3d.systems.RenderSystem;
|
| 29 | import com.mojang.blaze3d.systems.TimerQuery;
|
| 30 | import com.mojang.datafixers.DataFixer;
|
| 31 | import com.mojang.jtracy.DiscontinuousFrame;
|
| 32 | import com.mojang.jtracy.Section;
|
| 33 | import com.mojang.jtracy.SectionCategory;
|
| 34 | import com.mojang.jtracy.TracyClient;
|
| 35 | import com.mojang.logging.LogUtils;
|
| 36 | import com.mojang.realmsclient.RealmsMainScreen;
|
| 37 | import com.mojang.realmsclient.client.RealmsClient;
|
| 38 | import com.mojang.realmsclient.gui.RealmsDataFetcher;
|
| 39 | import com.mojang.renderpearl.api.GpuFormat;
|
| 40 | import com.mojang.renderpearl.api.device.BackendCreationException;
|
| 41 | import com.mojang.renderpearl.api.device.DeviceInfo;
|
| 42 | import com.mojang.renderpearl.api.device.GpuBackend;
|
| 43 | import com.mojang.renderpearl.api.device.GpuDebugOptions;
|
| 44 | import com.mojang.renderpearl.api.device.GpuDevice;
|
| 45 | import com.mojang.renderpearl.api.device.GpuSurface;
|
| 46 | import com.mojang.renderpearl.api.device.SurfaceException;
|
| 47 | import com.mojang.renderpearl.api.textures.GpuTextureView;
|
| 48 | import com.mojang.renderpearl.backend.vulkan.VulkanBackend;
|
| 49 | import java.io.File;
|
| 50 | import java.io.IOException;
|
| 51 | import java.io.UncheckedIOException;
|
| 52 | import java.lang.management.ManagementFactory;
|
| 53 | import java.net.Proxy;
|
| 54 | import java.net.SocketAddress;
|
| 55 | import java.nio.file.Path;
|
| 56 | import java.nio.file.Paths;
|
| 57 | import java.time.Duration;
|
| 58 | import java.time.Instant;
|
| 59 | import java.util.ArrayList;
|
| 60 | import java.util.Collection;
|
| 61 | import java.util.Collections;
|
| 62 | import java.util.List;
|
| 63 | import java.util.Locale;
|
| 64 | import java.util.MissingResourceException;
|
| 65 | import java.util.Optional;
|
| 66 | import java.util.UUID;
|
| 67 | import java.util.concurrent.CompletableFuture;
|
| 68 | import java.util.concurrent.CompletionStage;
|
| 69 | import java.util.concurrent.TimeUnit;
|
| 70 | import java.util.function.Consumer;
|
| 71 | import net.fabricmc.api.EnvType;
|
| 72 | import net.fabricmc.api.Environment;
|
| 73 | import net.minecraft.ChatFormatting;
|
| 74 | import net.minecraft.CrashReport;
|
| 75 | import net.minecraft.CrashReportCategory;
|
| 76 | import net.minecraft.Optionull;
|
| 77 | import net.minecraft.ReportType;
|
| 78 | import net.minecraft.ReportedException;
|
| 79 | import net.minecraft.SharedConstants;
|
| 80 | import net.minecraft.SystemReport;
|
| 81 | import net.minecraft.client.color.block.BlockColors;
|
| 82 | import net.minecraft.client.entity.ClientMannequin;
|
| 83 | import net.minecraft.client.gui.Font;
|
| 84 | import net.minecraft.client.gui.Gui;
|
| 85 | import net.minecraft.client.gui.Hud;
|
| 86 | import net.minecraft.client.gui.components.DebugScreenOverlay;
|
| 87 | import net.minecraft.client.gui.components.debug.DebugEntrySystemSpecs;
|
| 88 | import net.minecraft.client.gui.components.debug.DebugScreenEntries;
|
| 89 | import net.minecraft.client.gui.components.debug.DebugScreenEntryList;
|
| 90 | import net.minecraft.client.gui.components.debugchart.ProfilerPieChart;
|
| 91 | import net.minecraft.client.gui.components.events.GuiEventListener;
|
| 92 | import net.minecraft.client.gui.components.toasts.SystemToast;
|
| 93 | import net.minecraft.client.gui.components.toasts.ToastManager;
|
| 94 | import net.minecraft.client.gui.font.FontManager;
|
| 95 | import net.minecraft.client.gui.font.providers.FreeTypeUtil;
|
| 96 | import net.minecraft.client.gui.screens.GenericMessageScreen;
|
| 97 | import net.minecraft.client.gui.screens.LevelLoadingScreen;
|
| 98 | import net.minecraft.client.gui.screens.LoadingOverlay;
|
| 99 | import net.minecraft.client.gui.screens.MenuScreens;
|
| 100 | import net.minecraft.client.gui.screens.OutOfMemoryScreen;
|
| 101 | import net.minecraft.client.gui.screens.PauseScreen;
|
| 102 | import net.minecraft.client.gui.screens.ProgressScreen;
|
| 103 | import net.minecraft.client.gui.screens.Screen;
|
| 104 | import net.minecraft.client.gui.screens.TitleScreen;
|
| 105 | import net.minecraft.client.gui.screens.friends.FriendsOverlayScreen;
|
| 106 | import net.minecraft.client.gui.screens.inventory.CreativeModeInventoryScreen;
|
| 107 | import net.minecraft.client.gui.screens.inventory.InventoryScreen;
|
| 108 | import net.minecraft.client.gui.screens.multiplayer.JoinMultiplayerScreen;
|
| 109 | import net.minecraft.client.gui.screens.options.OnlineOptionsScreen;
|
| 110 | import net.minecraft.client.gui.screens.options.VideoSettingsScreen;
|
| 111 | import net.minecraft.client.gui.screens.social.PlayerSocialManager;
|
| 112 | import net.minecraft.client.gui.screens.social.RemoteFriendListUpdateHandler;
|
| 113 | import net.minecraft.client.gui.screens.worldselection.WorldOpenFlows;
|
| 114 | import net.minecraft.client.input.InputQuirks;
|
| 115 | import net.minecraft.client.main.GameConfig;
|
| 116 | import net.minecraft.client.model.geom.EntityModelSet;
|
| 117 | import net.minecraft.client.multiplayer.ClientHandshakePacketListenerImpl;
|
| 118 | import net.minecraft.client.multiplayer.ClientLevel;
|
| 119 | import net.minecraft.client.multiplayer.ClientPacketListener;
|
| 120 | import net.minecraft.client.multiplayer.LevelLoadTracker;
|
| 121 | import net.minecraft.client.multiplayer.MultiPlayerGameMode;
|
| 122 | import net.minecraft.client.multiplayer.ProfileKeyPairManager;
|
| 123 | import net.minecraft.client.multiplayer.ServerData;
|
| 124 | import net.minecraft.client.multiplayer.chat.ChatAbilities;
|
| 125 | import net.minecraft.client.multiplayer.chat.ChatRestriction;
|
| 126 | import net.minecraft.client.multiplayer.chat.report.ReportEnvironment;
|
| 127 | import net.minecraft.client.multiplayer.chat.report.ReportingContext;
|
| 128 | import net.minecraft.client.particle.ParticleEngine;
|
| 129 | import net.minecraft.client.particle.ParticleResources;
|
| 130 | import net.minecraft.client.player.LocalPlayer;
|
| 131 | import net.minecraft.client.player.LocalPlayerResolver;
|
| 132 | import net.minecraft.client.profiling.ClientMetricsSamplersProvider;
|
| 133 | import net.minecraft.client.quickplay.QuickPlayLog;
|
| 134 | import net.minecraft.client.renderer.FirstPersonHandsAndItemsRenderer;
|
| 135 | import net.minecraft.client.renderer.GameRenderer;
|
| 136 | import net.minecraft.client.renderer.GpuWarnlistManager;
|
| 137 | import net.minecraft.client.renderer.LevelRenderer;
|
| 138 | import net.minecraft.client.renderer.MapRenderer;
|
| 139 | import net.minecraft.client.renderer.PlayerSkinRenderCache;
|
| 140 | import net.minecraft.client.renderer.ShaderManager;
|
| 141 | import net.minecraft.client.renderer.block.BlockModelResolver;
|
| 142 | import net.minecraft.client.renderer.block.BlockStateModelSet;
|
| 143 | import net.minecraft.client.renderer.block.dispatch.BlockStateModel;
|
| 144 | import net.minecraft.client.renderer.blockentity.BlockEntityRenderDispatcher;
|
| 145 | import net.minecraft.client.renderer.entity.EntityRenderDispatcher;
|
| 146 | import net.minecraft.client.renderer.entity.EntityRenderers;
|
| 147 | import net.minecraft.client.renderer.extract.LevelExtractor;
|
| 148 | import net.minecraft.client.renderer.item.ItemModelResolver;
|
| 149 | import net.minecraft.client.renderer.state.WindowRenderState;
|
| 150 | import net.minecraft.client.renderer.texture.SkinTextureDownloader;
|
| 151 | import net.minecraft.client.renderer.texture.TextureAtlasSprite;
|
| 152 | import net.minecraft.client.renderer.texture.TextureManager;
|
| 153 | import net.minecraft.client.resources.ClientPackSource;
|
| 154 | import net.minecraft.client.resources.DryFoliageColorReloadListener;
|
| 155 | import net.minecraft.client.resources.FoliageColorReloadListener;
|
| 156 | import net.minecraft.client.resources.GrassColorReloadListener;
|
| 157 | import net.minecraft.client.resources.MapTextureManager;
|
| 158 | import net.minecraft.client.resources.SkinManager;
|
| 159 | import net.minecraft.client.resources.language.I18n;
|
| 160 | import net.minecraft.client.resources.language.LanguageManager;
|
| 161 | import net.minecraft.client.resources.model.EquipmentAssetManager;
|
| 162 | import net.minecraft.client.resources.model.ModelManager;
|
| 163 | import net.minecraft.client.resources.model.sprite.AtlasManager;
|
| 164 | import net.minecraft.client.resources.palette.PalettedTextureManager;
|
| 165 | import net.minecraft.client.resources.server.DownloadedPackSource;
|
| 166 | import net.minecraft.client.server.IntegratedServer;
|
| 167 | import net.minecraft.client.sounds.MusicManager;
|
| 168 | import net.minecraft.client.sounds.SoundManager;
|
| 169 | import net.minecraft.client.sounds.SoundBufferLibrary.DebugOutput.Counter;
|
| 170 | import net.minecraft.client.telemetry.ClientTelemetryManager;
|
| 171 | import net.minecraft.client.telemetry.TelemetryEventType;
|
| 172 | import net.minecraft.client.telemetry.TelemetryProperty;
|
| 173 | import net.minecraft.client.telemetry.events.GameLoadTimesEvent;
|
| 174 | import net.minecraft.client.tutorial.Tutorial;
|
| 175 | import net.minecraft.core.BlockPos;
|
| 176 | import net.minecraft.core.Direction;
|
| 177 | import net.minecraft.core.Holder;
|
| 178 | import net.minecraft.core.Registry;
|
| 179 | import net.minecraft.core.component.DataComponents;
|
| 180 | import net.minecraft.core.registries.BuiltInRegistries;
|
| 181 | import net.minecraft.core.registries.Registries;
|
| 182 | import net.minecraft.gizmos.Gizmos;
|
| 183 | import net.minecraft.gizmos.SimpleGizmoCollector;
|
| 184 | import net.minecraft.gizmos.Gizmos.TemporaryCollection;
|
| 185 | import net.minecraft.gizmos.SimpleGizmoCollector.GizmoInstance;
|
| 186 | import net.minecraft.network.Connection;
|
| 187 | import net.minecraft.network.PacketProcessor;
|
| 188 | import net.minecraft.network.chat.Component;
|
| 189 | import net.minecraft.network.chat.ClickEvent.OpenFile;
|
| 190 | import net.minecraft.network.chat.contents.KeybindResolver;
|
| 191 | import net.minecraft.network.protocol.game.ServerboundClientTickEndPacket;
|
| 192 | import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
|
| 193 | import net.minecraft.network.protocol.game.ServerboundPunchPacket;
|
| 194 | import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket.Action;
|
| 195 | import net.minecraft.network.protocol.login.ServerboundHelloPacket;
|
| 196 | import net.minecraft.resources.Identifier;
|
| 197 | import net.minecraft.server.Bootstrap;
|
| 198 | import net.minecraft.server.MinecraftServer;
|
| 199 | import net.minecraft.server.Services;
|
| 200 | import net.minecraft.server.WorldStem;
|
| 201 | import net.minecraft.server.dialog.Dialog;
|
| 202 | import net.minecraft.server.dialog.Dialogs;
|
| 203 | import net.minecraft.server.level.ChunkLevel;
|
| 204 | import net.minecraft.server.level.progress.LevelLoadListener;
|
| 205 | import net.minecraft.server.level.progress.LoggingLevelLoadListener;
|
| 206 | import net.minecraft.server.packs.PackResources;
|
| 207 | import net.minecraft.server.packs.PackType;
|
| 208 | import net.minecraft.server.packs.VanillaPackResources;
|
| 209 | import net.minecraft.server.packs.repository.FolderRepositorySource;
|
| 210 | import net.minecraft.server.packs.repository.PackRepository;
|
| 211 | import net.minecraft.server.packs.repository.PackSource;
|
| 212 | import net.minecraft.server.packs.repository.RepositorySource;
|
| 213 | import net.minecraft.server.packs.resources.ReloadInstance;
|
| 214 | import net.minecraft.server.packs.resources.ReloadableResourceManager;
|
| 215 | import net.minecraft.server.packs.resources.ResourceManager;
|
| 216 | import net.minecraft.server.players.ProfileResolver;
|
| 217 | import net.minecraft.sounds.Music;
|
| 218 | import net.minecraft.sounds.Musics;
|
| 219 | import net.minecraft.sounds.SoundSource;
|
| 220 | import net.minecraft.tags.DialogTags;
|
| 221 | import net.minecraft.util.FileUtil;
|
| 222 | import net.minecraft.util.FileZipper;
|
| 223 | import net.minecraft.util.MemoryReserve;
|
| 224 | import net.minecraft.util.ModCheck;
|
| 225 | import net.minecraft.util.NativeModuleLister;
|
| 226 | import net.minecraft.util.TimeUtil;
|
| 227 | import net.minecraft.util.Unit;
|
| 228 | import net.minecraft.util.Util;
|
| 229 | import net.minecraft.util.datafix.DataFixers;
|
| 230 | import net.minecraft.util.profiling.ContinuousProfiler;
|
| 231 | import net.minecraft.util.profiling.EmptyProfileResults;
|
| 232 | import net.minecraft.util.profiling.InactiveProfiler;
|
| 233 | import net.minecraft.util.profiling.ProfileResults;
|
| 234 | import net.minecraft.util.profiling.Profiler;
|
| 235 | import net.minecraft.util.profiling.ProfilerFiller;
|
| 236 | import net.minecraft.util.profiling.SingleTickProfiler;
|
| 237 | import net.minecraft.util.profiling.Zone;
|
| 238 | import net.minecraft.util.profiling.Profiler.Scope;
|
| 239 | import net.minecraft.util.profiling.metrics.profiling.ActiveMetricsRecorder;
|
| 240 | import net.minecraft.util.profiling.metrics.profiling.InactiveMetricsRecorder;
|
| 241 | import net.minecraft.util.profiling.metrics.profiling.MetricsRecorder;
|
| 242 | import net.minecraft.util.profiling.metrics.storage.MetricsPersister;
|
| 243 | import net.minecraft.util.thread.ReentrantBlockableEventLoop;
|
| 244 | import net.minecraft.world.InteractionHand;
|
| 245 | import net.minecraft.world.InteractionResult;
|
| 246 | import net.minecraft.world.TickRateManager;
|
| 247 | import net.minecraft.world.InteractionResult.Fail;
|
| 248 | import net.minecraft.world.InteractionResult.Success;
|
| 249 | import net.minecraft.world.InteractionResult.SwingSource;
|
| 250 | import net.minecraft.world.attribute.BackgroundMusic;
|
| 251 | import net.minecraft.world.attribute.EnvironmentAttributes;
|
| 252 | import net.minecraft.world.entity.Entity;
|
| 253 | import net.minecraft.world.entity.EntityTypes;
|
| 254 | import net.minecraft.world.entity.player.ChatVisiblity;
|
| 255 | import net.minecraft.world.item.ItemStack;
|
| 256 | import net.minecraft.world.item.component.AttackRange;
|
| 257 | import net.minecraft.world.item.component.PiercingWeapon;
|
| 258 | import net.minecraft.world.item.component.SwingAnimation;
|
| 259 | import net.minecraft.world.level.Level;
|
| 260 | import net.minecraft.world.level.block.Block;
|
| 261 | import net.minecraft.world.level.block.RenderShape;
|
| 262 | import net.minecraft.world.level.block.state.BlockState;
|
| 263 | import net.minecraft.world.level.gamerules.GameRules;
|
| 264 | import net.minecraft.world.level.storage.LevelStorageSource;
|
| 265 | import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess;
|
| 266 | import net.minecraft.world.level.validation.DirectoryValidator;
|
| 267 | import net.minecraft.world.phys.BlockHitResult;
|
| 268 | import net.minecraft.world.phys.EntityHitResult;
|
| 269 | import net.minecraft.world.phys.HitResult;
|
| 270 | import net.minecraft.world.phys.HitResult.Type;
|
| 271 | import org.apache.commons.io.FileUtils;
|
| 272 | import org.jspecify.annotations.Nullable;
|
| 273 | import org.lwjgl.sdl.SDLInit;
|
| 274 | import org.slf4j.Logger;
|
| 275 |
|
| 276 | /**
|
| 277 | * Access widened by fabric-transitive-access-wideners-v1 to accessible
|
| 278 | */
|
| 279 | @Environment(EnvType.CLIENT)
|
| 280 | public class Minecraft extends ReentrantBlockableEventLoop<Runnable> implements WindowEventHandler {
|
| 281 | private static Minecraft instance;
|
| 282 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 283 | private static final SectionCategory TRACY_CURRENT_LEVEL = TracyClient.createSectionCategory("Level");
|
| 284 | private static final int MAX_TICKS_PER_UPDATE = 10;
|
| 285 | public static final Identifier DEFAULT_FONT = Identifier.withDefaultNamespace("default");
|
| 286 | private static final Identifier REGIONAL_COMPLIANCIES = Identifier.withDefaultNamespace("regional_compliancies.json");
|
| 287 | private static final CompletableFuture<Unit> RESOURCE_RELOAD_INITIAL_TASK = CompletableFuture.completedFuture(Unit.INSTANCE);
|
| 288 | public static final String UPDATE_DRIVERS_ADVICE = "Please make sure you have up-to-date drivers (see aka.ms/mcdriver for instructions).";
|
| 289 | private final long canary = Double.doubleToLongBits(Math.PI);
|
| 290 | private final Path resourcePackDirectory;
|
| 291 | private final CompletableFuture<@Nullable ProfileResult> profileFuture;
|
| 292 | private final TextureManager textureManager;
|
| 293 | private final ShaderManager shaderManager;
|
| 294 | private final DataFixer fixerUpper;
|
| 295 | private final MonitorManager monitorManager;
|
| 296 | private final Window window;
|
| 297 | private final GpuSurface windowSurface;
|
| 298 | private final SDLEventHandler sdlEventHandler;
|
| 299 | private final TextInputManager textInputManager;
|
| 300 | private final DeltaTracker.Timer deltaTracker = new DeltaTracker.Timer(20.0F, 0L, this::getTickTargetMillis);
|
| 301 | public final LevelExtractor levelExtractor;
|
| 302 | public final LevelRenderer levelRenderer;
|
| 303 | private final EntityRenderDispatcher entityRenderDispatcher;
|
| 304 | private final ItemModelResolver itemModelResolver;
|
| 305 | private final MapRenderer mapRenderer;
|
| 306 | public final ParticleEngine particleEngine;
|
| 307 | private final User user;
|
| 308 | public final Font font;
|
| 309 | public final Font fontFilterFishy;
|
| 310 | public final GameRenderer gameRenderer;
|
| 311 | public final Gui gui;
|
| 312 | public final Options options;
|
| 313 | public final DebugScreenEntryList debugEntries;
|
| 314 | private final HotbarManager hotbarManager;
|
| 315 | public final MouseHandler mouseHandler;
|
| 316 | public final KeyboardHandler keyboardHandler;
|
| 317 | private InputType lastInputType = InputType.NONE;
|
| 318 | public final File gameDirectory;
|
| 319 | private final String launchedVersion;
|
| 320 | private final Proxy proxy;
|
| 321 | private final boolean offlineDeveloperMode;
|
| 322 | private final LevelStorageSource levelSource;
|
| 323 | private final boolean demo;
|
| 324 | private final boolean allowsMultiplayer;
|
| 325 | private final boolean allowsChat;
|
| 326 | private final ReloadableResourceManager resourceManager;
|
| 327 | private final VanillaPackResources vanillaPackResources;
|
| 328 | private final DownloadedPackSource downloadedPackSource;
|
| 329 | private final PackRepository resourcePackRepository;
|
| 330 | private final LanguageManager languageManager;
|
| 331 | private final BlockColors blockColors;
|
| 332 | private final @Nullable TracyFrameCapture tracyFrameCapture;
|
| 333 | private final SoundManager soundManager;
|
| 334 | private final MusicManager musicManager;
|
| 335 | private final FontManager fontManager;
|
| 336 | private final GpuWarnlistManager gpuWarnlistManager;
|
| 337 | private final PeriodicNotificationManager regionalCompliancies = new PeriodicNotificationManager(REGIONAL_COMPLIANCIES, Minecraft::countryEqualsISO3);
|
| 338 | private final UserApiService userApiService;
|
| 339 | private final CompletableFuture<UserProperties> userPropertiesFuture;
|
| 340 | private final SkinManager skinManager;
|
| 341 | private final AtlasManager atlasManager;
|
| 342 | private final ModelManager modelManager;
|
| 343 | private final PalettedTextureManager palettedTextureManager;
|
| 344 | private final MapTextureManager mapTextureManager;
|
| 345 | private final Tutorial tutorial;
|
| 346 | private final PlayerSocialManager playerSocialManager;
|
| 347 | private final RemoteFriendListUpdateHandler remoteFriendListUpdateHandler;
|
| 348 | private final BlockEntityRenderDispatcher blockEntityRenderDispatcher;
|
| 349 | private final ClientTelemetryManager telemetryManager;
|
| 350 | private final ProfileKeyPairManager profileKeyPairManager;
|
| 351 | private final RealmsDataFetcher realmsDataFetcher;
|
| 352 | private final QuickPlayLog quickPlayLog;
|
| 353 | private final Services services;
|
| 354 | private final PlayerSkinRenderCache playerSkinRenderCache;
|
| 355 | private final TimerQuery timerQuery;
|
| 356 | public @Nullable MultiPlayerGameMode gameMode;
|
| 357 | public @Nullable ClientLevel level;
|
| 358 | public @Nullable LocalPlayer player;
|
| 359 | private @Nullable IntegratedServer singleplayerServer;
|
| 360 | private @Nullable Connection pendingConnection;
|
| 361 | private boolean isLocalServer;
|
| 362 | private @Nullable Section tracyLevelSection;
|
| 363 | public @Nullable Entity crosshairPickEntity;
|
| 364 | public @Nullable HitResult hitResult;
|
| 365 | private int rightClickDelay;
|
| 366 | /**
|
| 367 | * Access widened by fabric-transitive-access-wideners-v1 to accessible
|
| 368 | */
|
| 369 | public int missTime;
|
| 370 | private volatile boolean pause;
|
| 371 | private long lastNanoTime = Util.getNanos();
|
| 372 | private long lastTime;
|
| 373 | private int frames;
|
| 374 | private Thread gameThread;
|
| 375 | private volatile boolean running;
|
| 376 | private static int fps;
|
| 377 | private long frameTimeNs;
|
| 378 | private final FramerateLimitTracker framerateLimitTracker;
|
| 379 | public boolean multiDrawIndirect = true;
|
| 380 | public boolean wireframe;
|
| 381 | public boolean smartCull = true;
|
| 382 | private long lastActiveTime = Util.getMillis();
|
| 383 | private @Nullable CompletableFuture<Void> pendingReload;
|
| 384 | private int fpsPieRenderTicks;
|
| 385 | private final ContinuousProfiler fpsPieProfiler;
|
| 386 | private MetricsRecorder metricsRecorder = InactiveMetricsRecorder.INSTANCE;
|
| 387 | private final ResourceLoadStateTracker reloadStateTracker = new ResourceLoadStateTracker();
|
| 388 | private long savedCpuDuration;
|
| 389 | private double gpuUtilization;
|
| 390 | private final GameNarrator narrator;
|
| 391 | private ReportingContext reportingContext;
|
| 392 | private final DirectoryValidator directoryValidator;
|
| 393 | private boolean gameLoadFinished;
|
| 394 | private final long clientStartTimeMs;
|
| 395 | private long clientTickCount;
|
| 396 | private final PacketProcessor packetProcessor;
|
| 397 | private final SimpleGizmoCollector perTickGizmos = new SimpleGizmoCollector();
|
| 398 | private List<GizmoInstance> drainedLatestTickGizmos = new ArrayList<>();
|
| 399 | private boolean windowSurfaceNeedsReconfiguring = true;
|
| 400 | private boolean surfaceIsInvalid = true;
|
| 401 | private @Nullable BackendCreationException backendCreationException;
|
| 402 |
|
| 403 | public Minecraft(final GameConfig gameConfig) {
|
| 404 | super("Client", true);
|
| 405 | instance = this;
|
| 406 | this.clientStartTimeMs = System.currentTimeMillis();
|
| 407 | this.gameDirectory = gameConfig.location.gameDirectory;
|
| 408 | File assetsDirectory = gameConfig.location.assetDirectory;
|
| 409 | this.resourcePackDirectory = gameConfig.location.resourcePackDirectory.toPath();
|
| 410 | this.launchedVersion = gameConfig.game.launchVersion;
|
| 411 | Path gameDirPath = this.gameDirectory.toPath();
|
| 412 | this.directoryValidator = LevelStorageSource.parseValidator(gameDirPath.resolve("allowed_symlinks.txt"));
|
| 413 | ClientPackSource clientPackSource = new ClientPackSource(gameConfig.location.getExternalAssetSource(), this.directoryValidator);
|
| 414 | this.downloadedPackSource = new DownloadedPackSource(this, gameDirPath.resolve("downloads"), gameConfig.user);
|
| 415 | RepositorySource directoryPacks = new FolderRepositorySource(
|
| 416 | this.resourcePackDirectory, PackType.CLIENT_RESOURCES, PackSource.DEFAULT, this.directoryValidator
|
| 417 | );
|
| 418 | this.resourcePackRepository = new PackRepository(clientPackSource, this.downloadedPackSource.createRepositorySource(), directoryPacks);
|
| 419 | this.vanillaPackResources = clientPackSource.getVanillaPack();
|
| 420 | this.proxy = gameConfig.user.proxy;
|
| 421 | this.offlineDeveloperMode = gameConfig.game.offlineDeveloperMode;
|
| 422 | MinecraftServicesDiscoveryService discoveryService = MinecraftServicesDiscoveryService.create(this.proxy, !this.offlineDeveloperMode);
|
| 423 | this.services = Services.create(discoveryService, this.gameDirectory);
|
| 424 | this.user = gameConfig.user.user;
|
| 425 | this.profileFuture = this.offlineDeveloperMode
|
| 426 | ? CompletableFuture.completedFuture(null)
|
| 427 | : CompletableFuture.supplyAsync(() -> this.services.sessionService().fetchProfile(this.user.getProfileId(), true), Util.nonCriticalIoPool());
|
| 428 | this.userApiService = createUserApiService(discoveryService, gameConfig);
|
| 429 | this.userPropertiesFuture = CompletableFuture.supplyAsync(() -> {
|
| 430 | try {
|
| 431 | return this.userApiService.fetchProperties();
|
| 432 | } catch (AuthenticationException e) {
|
| 433 | LOGGER.error("Failed to fetch user properties", e);
|
| 434 | return UserApiService.OFFLINE_PROPERTIES;
|
| 435 | }
|
| 436 | }, Util.nonCriticalIoPool());
|
| 437 | LOGGER.info("Setting user: {}", this.user.getName());
|
| 438 | LOGGER.debug("(Session ID is {})", this.user.getSessionId());
|
| 439 | this.demo = gameConfig.game.demo;
|
| 440 | this.allowsMultiplayer = !gameConfig.game.disableMultiplayer;
|
| 441 | this.allowsChat = !gameConfig.game.disableChat;
|
| 442 | this.singleplayerServer = null;
|
| 443 | KeybindResolver.setKeyResolver(KeyMapping::createNameSupplier);
|
| 444 | this.fixerUpper = DataFixers.getDataFixer();
|
| 445 | this.gameThread = Thread.currentThread();
|
| 446 | this.options = new Options(this, this.gameDirectory);
|
| 447 | this.debugEntries = new DebugScreenEntryList(this.gameDirectory, this.fixerUpper);
|
| 448 | boolean lastStartWasClean = this.options.startedCleanly;
|
| 449 | this.options.startedCleanly = false;
|
| 450 | this.options.save();
|
| 451 | this.running = true;
|
| 452 | this.tutorial = new Tutorial(this, this.options);
|
| 453 | this.hotbarManager = new HotbarManager(gameDirPath, this.fixerUpper);
|
| 454 | LOGGER.info("Backend library: {}", RenderSystem.getBackendDescription());
|
| 455 | DisplayData displayData = gameConfig.display;
|
| 456 | if (this.options.overrideHeight > 0 && this.options.overrideWidth > 0) {
|
| 457 | displayData = gameConfig.display.withSize(this.options.overrideWidth, this.options.overrideHeight);
|
| 458 | }
|
| 459 |
|
| 460 | if (this.options.fullscreen().get()) {
|
| 461 | displayData = displayData.withFullscreen(true);
|
| 462 | }
|
| 463 |
|
| 464 | if (!lastStartWasClean) {
|
| 465 | displayData = displayData.withFullscreen(false);
|
| 466 | this.options.fullscreen().set(false);
|
| 467 | this.options.fullscreenVideoModeString = null;
|
| 468 | LOGGER.warn("Detected unexpected shutdown during last game startup: resetting fullscreen mode");
|
| 469 | }
|
| 470 |
|
| 471 | Util.setTimeSource(RenderSystem.initBackendSystem());
|
| 472 | this.monitorManager = new MonitorManager();
|
| 473 | StringBuilder errorMsgBuilder = new StringBuilder("No supported graphics backend was found.");
|
| 474 | GpuBackend backend = null;
|
| 475 | GpuDevice device = null;
|
| 476 | PreferredGraphicsApi forcedGraphicsApi = gameConfig.game.forcedGraphicsApi;
|
| 477 | if (forcedGraphicsApi != null) {
|
| 478 | LOGGER.warn("Graphics backend forced to {} by launch argument, in-game preferred graphics backend setting is ignored", forcedGraphicsApi.getSerializedName());
|
| 479 | } else if (!lastStartWasClean) {
|
| 480 | if (this.options.preferredGraphicsBackend().get() == PreferredGraphicsApi.VULKAN) {
|
| 481 | LOGGER.warn("Detected unexpected shutdown during last game startup: resetting preferred graphics API to Default");
|
| 482 | this.options.preferredGraphicsBackend().set(PreferredGraphicsApi.DEFAULT);
|
| 483 | this.options.save();
|
| 484 | } else if (this.options.preferredGraphicsBackend().get() == PreferredGraphicsApi.DEFAULT) {
|
| 485 | LOGGER.warn("Detected unexpected shutdown during last game startup: forcing preferred graphics API to OpenGL");
|
| 486 | this.options.preferredGraphicsBackend().set(PreferredGraphicsApi.OPENGL);
|
| 487 | }
|
| 488 | }
|
| 489 |
|
| 490 | PreferredGraphicsApi preferredGraphicsBackend = forcedGraphicsApi == null ? this.options.preferredGraphicsBackend().get() : forcedGraphicsApi;
|
| 491 | GpuBackend[] backendsToTry = preferredGraphicsBackend.getBackendsToTry();
|
| 492 | if (preferredGraphicsBackend == PreferredGraphicsApi.DEFAULT) {
|
| 493 | this.backendCreationException = VulkanBackend.checkBackendAvailable();
|
| 494 | }
|
| 495 |
|
| 496 | String initialWindowTitle = this.createTitle();
|
| 497 |
|
| 498 | for (GpuBackend backendToTry : backendsToTry) {
|
| 499 | boolean libraryLoaded = false;
|
| 500 |
|
| 501 | try {
|
| 502 | backendToTry.loadLibrary();
|
| 503 | libraryLoaded = true;
|
| 504 | device = backendToTry.createDevice(
|
| 505 | new GpuDebugOptions(
|
| 506 | this.options.glDebugVerbosity, SharedConstants.DEBUG_SYNCHRONOUS_GL_LOGS, gameConfig.game.renderDebugLabels, gameConfig.game.vulkanValidation
|
| 507 | )
|
| 508 | );
|
| 509 | backend = backendToTry;
|
| 510 | break;
|
| 511 | } catch (BackendCreationException exception) {
|
| 512 | LOGGER.error("Failed to create backend {}", backendToTry.getName(), exception);
|
| 513 | errorMsgBuilder.append("\n\n- Tried ").append(backendToTry.getName()).append(": \n ").append(exception.getMessage());
|
| 514 | if (this.backendCreationException == null || exception.getReason() != BackendCreationException.Reason.OPENGL_MISSING) {
|
| 515 | this.backendCreationException = exception;
|
| 516 | }
|
| 517 |
|
| 518 | if (libraryLoaded) {
|
| 519 | backendToTry.unloadLibrary();
|
| 520 | }
|
| 521 | }
|
| 522 | }
|
| 523 |
|
| 524 | if (device == null) {
|
| 525 | errorMsgBuilder.append("\n\n").append("Please make sure you have up-to-date drivers (see aka.ms/mcdriver for instructions).");
|
| 526 | String errorMsg = errorMsgBuilder.toString();
|
| 527 | MessageBox.error(errorMsg);
|
| 528 | throw new Window.WindowInitFailed(errorMsg);
|
| 529 | }
|
| 530 |
|
| 531 | RenderSystem.initRenderer(device);
|
| 532 | RenderSystem.trackBackendLibraryForShutdown(backend);
|
| 533 | DeviceInfo deviceInfo = device.getDeviceInfo();
|
| 534 | LOGGER.info("Using graphics backend {}, using drivers: {}", deviceInfo.backendName(), deviceInfo.driverInfo());
|
| 535 | LOGGER.info("Using graphics device: {} ({})", deviceInfo.name(), deviceInfo.vendorName());
|
| 536 | LOGGER.info("Using graphics device extensions: {}", String.join(", ", deviceInfo.underlyingExtensions()));
|
| 537 | int maxSize = deviceInfo.limits().maxTextureSizeForFormat(GpuFormat.RGBA8_UNORM);
|
| 538 | this.window = new Window(
|
| 539 | this,
|
| 540 | displayData,
|
| 541 | this.options.fullscreenVideoModeString,
|
| 542 | this.options.exclusiveFullscreen().get(),
|
| 543 | initialWindowTitle,
|
| 544 | this.monitorManager,
|
| 545 | backend,
|
| 546 | maxSize
|
| 547 | );
|
| 548 |
|
| 549 | try {
|
| 550 | this.window.setIcon(this.vanillaPackResources.fullResources(), SharedConstants.getCurrentVersion().stable() ? IconSet.RELEASE : IconSet.SNAPSHOT);
|
| 551 | } catch (IOException e) {
|
| 552 | LOGGER.error("Couldn't set icon", e);
|
| 553 | }
|
| 554 |
|
| 555 | this.windowSurface = device.createSurface(this.window.handle(), this.window::isIconified);
|
| 556 | this.sdlEventHandler = new SDLEventHandler(this, this.window);
|
| 557 | this.textInputManager = new TextInputManager(this.window);
|
| 558 | this.sdlEventHandler.flushInputEvents();
|
| 559 | this.window.setWindowCloseCallback(new Runnable() {
|
| 560 | private boolean threadStarted;
|
| 561 |
|
| 562 | @Override
|
| 563 | public void run() {
|
| 564 | if (!this.threadStarted) {
|
| 565 | this.threadStarted = true;
|
| 566 | ClientShutdownWatchdog.startShutdownWatchdog("window close callback", false, Minecraft.this, gameConfig, Minecraft.this.gameThread.threadId());
|
| 567 | }
|
| 568 | }
|
| 569 | });
|
| 570 | GameLoadTimesEvent.INSTANCE.endStep(TelemetryProperty.LOAD_TIME_PRE_WINDOW_MS);
|
| 571 | this.mouseHandler = new MouseHandler(this);
|
| 572 | this.keyboardHandler = new KeyboardHandler(this);
|
| 573 | this.options.applyGraphicsPreset(this.options.graphicsPreset().get());
|
| 574 | this.resourceManager = new ReloadableResourceManager(PackType.CLIENT_RESOURCES);
|
| 575 | this.resourcePackRepository.reload();
|
| 576 | this.options.loadSelectedResourcePacks(this.resourcePackRepository);
|
| 577 | this.languageManager = new LanguageManager(this, this.options.languageCode, var1 -> {
|
| 578 | if (this.player != null) {
|
| 579 | this.player.connection.updateSearchTrees();
|
| 580 | }
|
| 581 | });
|
| 582 | this.resourceManager.registerReloadListener(this.languageManager);
|
| 583 | this.textureManager = new TextureManager(this.resourceManager);
|
| 584 | this.resourceManager.registerReloadListener(this.textureManager);
|
| 585 | this.shaderManager = new ShaderManager(this.textureManager, this::triggerResourcePackRecovery);
|
| 586 | this.resourceManager.registerReloadListener(this.shaderManager);
|
| 587 | SkinTextureDownloader skinTextureDownloader = new SkinTextureDownloader(this.proxy, this.textureManager, this);
|
| 588 | this.skinManager = new SkinManager(assetsDirectory.toPath().resolve("skins"), this.services, skinTextureDownloader, this);
|
| 589 | this.levelSource = new LevelStorageSource(gameDirPath.resolve("saves"), gameDirPath.resolve("backups"), this.directoryValidator, this.fixerUpper);
|
| 590 | this.musicManager = new MusicManager(this);
|
| 591 | this.soundManager = new SoundManager(this.options);
|
| 592 | this.resourceManager.registerReloadListener(this.soundManager);
|
| 593 | this.atlasManager = new AtlasManager(this.textureManager, this.options.mipmapLevels().get());
|
| 594 | this.resourceManager.registerReloadListener(this.atlasManager);
|
| 595 | ProfileResolver localProfileResolver = new LocalPlayerResolver(this, this.services.profileResolver());
|
| 596 | this.playerSkinRenderCache = new PlayerSkinRenderCache(this.textureManager, this.skinManager, localProfileResolver);
|
| 597 | ClientMannequin.registerOverrides(this.playerSkinRenderCache);
|
| 598 | this.fontManager = new FontManager(this.textureManager, this.atlasManager, this.playerSkinRenderCache);
|
| 599 | this.font = this.fontManager.createFont();
|
| 600 | this.fontFilterFishy = this.fontManager.createFontFilterFishy();
|
| 601 | this.resourceManager.registerReloadListener(this.fontManager);
|
| 602 | this.updateFontOptions();
|
| 603 | this.resourceManager.registerReloadListener(new GrassColorReloadListener());
|
| 604 | this.resourceManager.registerReloadListener(new FoliageColorReloadListener());
|
| 605 | this.resourceManager.registerReloadListener(new DryFoliageColorReloadListener());
|
| 606 | RenderSystem.setupDefaultState();
|
| 607 | this.blockColors = BlockColors.createDefault();
|
| 608 | this.modelManager = new ModelManager(this.blockColors, this.atlasManager, this.playerSkinRenderCache);
|
| 609 | this.resourceManager.registerReloadListener(this.modelManager);
|
| 610 | EquipmentAssetManager equipmentAssets = new EquipmentAssetManager();
|
| 611 | this.resourceManager.registerReloadListener(equipmentAssets);
|
| 612 | BlockModelResolver blockModelResolver = new BlockModelResolver(this.modelManager);
|
| 613 | this.itemModelResolver = new ItemModelResolver(this.modelManager);
|
| 614 | this.palettedTextureManager = new PalettedTextureManager(this.resourceManager, this.textureManager);
|
| 615 | this.resourceManager.registerReloadListener(this.palettedTextureManager);
|
| 616 | this.mapTextureManager = new MapTextureManager(this.textureManager);
|
| 617 | this.mapRenderer = new MapRenderer(this.atlasManager, this.mapTextureManager);
|
| 618 | FriendsService friendsService = discoveryService.createFriendsService(this.user.getAccessToken());
|
| 619 | this.remoteFriendListUpdateHandler = new RemoteFriendListUpdateHandler(friendsService, this);
|
| 620 | this.playerSocialManager = new PlayerSocialManager(this, this.userApiService, friendsService, this.remoteFriendListUpdateHandler);
|
| 621 | if (this.playerSocialManager.isFriendListEnabled()) {
|
| 622 | this.remoteFriendListUpdateHandler.start();
|
| 623 | }
|
| 624 |
|
| 625 | this.entityRenderDispatcher = new EntityRenderDispatcher(
|
| 626 | this.textureManager,
|
| 627 | blockModelResolver,
|
| 628 | this.itemModelResolver,
|
| 629 | this.mapRenderer,
|
| 630 | this.atlasManager,
|
| 631 | this.font,
|
| 632 | this.options,
|
| 633 | this.modelManager.entityModels(),
|
| 634 | equipmentAssets,
|
| 635 | this.playerSkinRenderCache,
|
| 636 | this.palettedTextureManager
|
| 637 | );
|
| 638 | this.resourceManager.registerReloadListener(this.entityRenderDispatcher);
|
| 639 | this.blockEntityRenderDispatcher = new BlockEntityRenderDispatcher(
|
| 640 | this.font,
|
| 641 | this.modelManager.entityModels(),
|
| 642 | blockModelResolver,
|
| 643 | this.itemModelResolver,
|
| 644 | this.entityRenderDispatcher,
|
| 645 | this.atlasManager,
|
| 646 | this.playerSkinRenderCache
|
| 647 | );
|
| 648 | this.resourceManager.registerReloadListener(this.blockEntityRenderDispatcher);
|
| 649 | ParticleResources particleResources = new ParticleResources();
|
| 650 | this.resourceManager.registerReloadListener(particleResources);
|
| 651 | this.particleEngine = new ParticleEngine(this.level, particleResources);
|
| 652 | particleResources.onReload(this.particleEngine::clearParticles);
|
| 653 | this.gameRenderer = new GameRenderer(this, new FirstPersonHandsAndItemsRenderer(this), this.modelManager, this.itemModelResolver);
|
| 654 | this.resourceManager.registerReloadListener(this.gameRenderer);
|
| 655 | WindowRenderState windowRenderState = this.gameRenderer.gameRenderState().windowRenderState;
|
| 656 | windowRenderState.width = this.window.getWidth();
|
| 657 | windowRenderState.height = this.window.getHeight();
|
| 658 | this.levelRenderer = new LevelRenderer(
|
| 659 | this.entityRenderDispatcher,
|
| 660 | this.blockEntityRenderDispatcher,
|
| 661 | this.modelManager,
|
| 662 | this.textureManager,
|
| 663 | this.atlasManager,
|
| 664 | this.shaderManager,
|
| 665 | this.gameRenderer,
|
| 666 | this.window.getWidth(),
|
| 667 | this.window.getHeight()
|
| 668 | );
|
| 669 | this.levelExtractor = new LevelExtractor(this, this.gameRenderer.gameRenderState().levelRenderState, this.levelRenderer);
|
| 670 | this.resourceManager.registerReloadListener(this.levelExtractor);
|
| 671 | this.resourceManager.registerReloadListener(this.levelRenderer.cloudRenderer());
|
| 672 | this.gpuWarnlistManager = new GpuWarnlistManager();
|
| 673 | this.resourceManager.registerReloadListener(this.gpuWarnlistManager);
|
| 674 | this.resourceManager.registerReloadListener(this.regionalCompliancies);
|
| 675 | this.gui = new Gui(this, new Hud(this), this.gameRenderer.gameRenderState().guiRenderState);
|
| 676 | this.gui.registerReloadListeners(this.resourceManager);
|
| 677 | RealmsClient realmsClient = RealmsClient.getOrCreate(this);
|
| 678 | this.realmsDataFetcher = new RealmsDataFetcher(realmsClient);
|
| 679 | RenderTarget mainRenderTarget = this.gameRenderer.mainRenderTarget();
|
| 680 | if (mainRenderTarget.width != this.window.getWidth() || mainRenderTarget.height != this.window.getHeight()) {
|
| 681 | StringBuilder message = new StringBuilder(
|
| 682 | "Recovering from unsupported resolution ("
|
| 683 | + this.window.getWidth()
|
| 684 | + "x"
|
| 685 | + this.window.getHeight()
|
| 686 | + ").\nPlease make sure you have up-to-date drivers (see aka.ms/mcdriver for instructions)."
|
| 687 | );
|
| 688 |
|
| 689 | try {
|
| 690 | List<String> messages = device.getLastDebugMessages();
|
| 691 | if (!messages.isEmpty()) {
|
| 692 | message.append("\n\nReported GL debug messages:\n").append(String.join("\n", messages));
|
| 693 | }
|
| 694 | } catch (Throwable var30) {
|
| 695 | }
|
| 696 |
|
| 697 | this.window.setWindowed(mainRenderTarget.width, mainRenderTarget.height);
|
| 698 | MessageBox.error(message.toString());
|
| 699 | }
|
| 700 |
|
| 701 | this.window.setAllowCursorChanges(this.options.allowCursorChanges().get());
|
| 702 | this.window.setQuitShortcuts(this.options.quitShortcuts().get());
|
| 703 | if (InputQuirks.EMULATE_RIGHT_CLICK_WITH_CTRL_KEY) {
|
| 704 | MacosUtil.setCtrlClickEmulatesRightClick(this.options.ctrlClickEmulatesRightClick().get());
|
| 705 | }
|
| 706 |
|
| 707 | MacosUtil.setFullscreenMenuVisibility(this.options.macFullscreenMenuVisibility().get());
|
| 708 | this.resizeGui();
|
| 709 | this.loadCriticalShaders();
|
| 710 | this.telemetryManager = new ClientTelemetryManager(this, this.userApiService, this.user);
|
| 711 | this.profileKeyPairManager = this.offlineDeveloperMode
|
| 712 | ? ProfileKeyPairManager.EMPTY_KEY_MANAGER
|
| 713 | : ProfileKeyPairManager.create(this.userApiService, this.user, gameDirPath);
|
| 714 | this.narrator = new GameNarrator(this);
|
| 715 | this.narrator.checkStatus(this.options.narrator().get() != NarratorStatus.OFF);
|
| 716 | this.reportingContext = ReportingContext.create(ReportEnvironment.local(), this.userApiService);
|
| 717 | TitleScreen.registerTextures(this.textureManager);
|
| 718 | LoadingOverlay.registerTextures(this.textureManager);
|
| 719 | this.gameRenderer.registerPanoramaTextures(this.textureManager);
|
| 720 | this.timerQuery = new TimerQuery();
|
| 721 | this.gui.setScreen(new GenericMessageScreen(Component.translatable("gui.loadingMinecraft")));
|
| 722 | List<PackResources> packs = this.resourcePackRepository.openAllSelected();
|
| 723 | this.reloadStateTracker.startReload(ResourceLoadStateTracker.ReloadReason.INITIAL, packs);
|
| 724 | ReloadInstance reloadInstance = this.resourceManager
|
| 725 | .createReload(Util.backgroundExecutor().forName("resourceLoad"), this, RESOURCE_RELOAD_INITIAL_TASK, packs);
|
| 726 | GameLoadTimesEvent.INSTANCE.beginStep(TelemetryProperty.LOAD_TIME_LOADING_OVERLAY_MS);
|
| 727 | GameLoadCookie loadCookie = new GameLoadCookie(realmsClient, gameConfig.quickPlay);
|
| 728 | this.gui.setOverlay(new LoadingOverlay(this, reloadInstance, maybeT -> Util.ifElse(maybeT, t -> this.rollbackResourcePacks(t, loadCookie), () -> {
|
| 729 | if (SharedConstants.IS_RUNNING_IN_IDE) {
|
| 730 | this.selfTest();
|
| 731 | }
|
| 732 |
|
| 733 | this.reloadStateTracker.finishReload();
|
| 734 | this.onResourceLoadFinished(loadCookie);
|
| 735 | }), false));
|
| 736 | this.quickPlayLog = QuickPlayLog.of(gameConfig.quickPlay.logPath());
|
| 737 | this.framerateLimitTracker = new FramerateLimitTracker(this.options, this);
|
| 738 | this.fpsPieProfiler = new ContinuousProfiler(Util.timeSource(), () -> this.fpsPieRenderTicks, this.framerateLimitTracker::isHeavilyThrottled);
|
| 739 | if (TracyClient.isAvailable() && gameConfig.game.captureTracyImages) {
|
| 740 | this.tracyFrameCapture = new TracyFrameCapture();
|
| 741 | } else {
|
| 742 | this.tracyFrameCapture = null;
|
| 743 | }
|
| 744 |
|
| 745 | this.packetProcessor = new PacketProcessor(this.gameThread);
|
| 746 | this.sdlEventHandler.pumpEvents();
|
| 747 | this.framebufferSizeChanged();
|
| 748 | this.renderFrame(false);
|
| 749 | this.telemetryManager.getOutsideSessionSender().send(TelemetryEventType.GRAPHICS_CAPABILITIES, properties -> {
|
| 750 | properties.putIfNotNull(TelemetryProperty.BACKEND_NAME, RenderSystem.getDevice().getDeviceInfo().backendName());
|
| 751 | if (this.backendCreationException != null) {
|
| 752 | properties.put(TelemetryProperty.BACKEND_FAILURE_MESSAGE, this.backendCreationException.getMessage());
|
| 753 | properties.put(TelemetryProperty.BACKEND_FAILURE_REASON, this.backendCreationException.getReason().displayName());
|
| 754 | properties.put(TelemetryProperty.BACKEND_FAILURE_MISSING_CAPABILITIES, String.join(",", this.backendCreationException.getMissingCapabilities()));
|
| 755 | } else {
|
| 756 | properties.put(TelemetryProperty.BACKEND_FAILURE_MESSAGE, "");
|
| 757 | properties.put(TelemetryProperty.BACKEND_FAILURE_REASON, "");
|
| 758 | properties.put(TelemetryProperty.BACKEND_FAILURE_MISSING_CAPABILITIES, "");
|
| 759 | }
|
| 760 | });
|
| 761 | }
|
| 762 |
|
| 763 | public boolean hasShiftDown() {
|
| 764 | return InputConstants.isKeyDown(225) || InputConstants.isKeyDown(229);
|
| 765 | }
|
| 766 |
|
| 767 | public boolean hasControlDown() {
|
| 768 | return InputConstants.isKeyDown(224) || InputConstants.isKeyDown(228);
|
| 769 | }
|
| 770 |
|
| 771 | public boolean hasAltDown() {
|
| 772 | return InputConstants.isKeyDown(226) || InputConstants.isKeyDown(230);
|
| 773 | }
|
| 774 |
|
| 775 | private void onResourceLoadFinished(final @Nullable GameLoadCookie loadCookie) {
|
| 776 | if (!this.gameLoadFinished) {
|
| 777 | this.gameLoadFinished = true;
|
| 778 | this.onGameLoadFinished(loadCookie);
|
| 779 | }
|
| 780 | }
|
| 781 |
|
| 782 | private void onGameLoadFinished(final @Nullable GameLoadCookie cookie) {
|
| 783 | Runnable showScreen = this.gui.buildInitialScreens(cookie);
|
| 784 | GameLoadTimesEvent.INSTANCE.endStep(TelemetryProperty.LOAD_TIME_LOADING_OVERLAY_MS);
|
| 785 | GameLoadTimesEvent.INSTANCE.endStep(TelemetryProperty.LOAD_TIME_TOTAL_TIME_MS);
|
| 786 | GameLoadTimesEvent.INSTANCE.send(this.telemetryManager.getOutsideSessionSender());
|
| 787 | showScreen.run();
|
| 788 | this.options.startedCleanly = true;
|
| 789 | this.options.save();
|
| 790 | }
|
| 791 |
|
| 792 | public boolean isGameLoadFinished() {
|
| 793 | return this.gameLoadFinished;
|
| 794 | }
|
| 795 |
|
| 796 | private static boolean countryEqualsISO3(final Object iso3Locale) {
|
| 797 | try {
|
| 798 | return Locale.getDefault().getISO3Country().equals(iso3Locale);
|
| 799 | } catch (MissingResourceException e) {
|
| 800 | return false;
|
| 801 | }
|
| 802 | }
|
| 803 |
|
| 804 | public void updateTitle() {
|
| 805 | this.window.setTitle(this.createTitle());
|
| 806 | }
|
| 807 |
|
| 808 | private String createTitle() {
|
| 809 | StringBuilder builder = new StringBuilder("Minecraft");
|
| 810 | if (checkModStatus().shouldReportAsModified()) {
|
| 811 | builder.append("*");
|
| 812 | }
|
| 813 |
|
| 814 | builder.append(" ");
|
| 815 | builder.append(SharedConstants.getCurrentVersion().name());
|
| 816 | ClientPacketListener connection = this.getConnection();
|
| 817 | if (connection != null && connection.getConnection().isConnected()) {
|
| 818 | builder.append(" - ");
|
| 819 | ServerData server = this.getCurrentServer();
|
| 820 | if (this.singleplayerServer != null && !this.singleplayerServer.isPublished()) {
|
| 821 | builder.append(I18n.get("title.singleplayer"));
|
| 822 | } else if (server != null && server.isRealm()) {
|
| 823 | builder.append(I18n.get("title.multiplayer.realms"));
|
| 824 | } else if (this.singleplayerServer == null && (server == null || !server.isLan())) {
|
| 825 | builder.append(I18n.get("title.multiplayer.other"));
|
| 826 | } else {
|
| 827 | builder.append(I18n.get("title.multiplayer.lan"));
|
| 828 | }
|
| 829 | }
|
| 830 |
|
| 831 | return builder.toString();
|
| 832 | }
|
| 833 |
|
| 834 | private static UserApiService createUserApiService(final MinecraftServicesDiscoveryService discoveryService, final GameConfig config) {
|
| 835 | return config.game.offlineDeveloperMode ? UserApiService.OFFLINE : discoveryService.createUserApiService(config.user.user.getAccessToken());
|
| 836 | }
|
| 837 |
|
| 838 | public boolean isOfflineDeveloperMode() {
|
| 839 | return this.offlineDeveloperMode;
|
| 840 | }
|
| 841 |
|
| 842 | public static ModCheck checkModStatus() {
|
| 843 | return ModCheck.identify("vanilla", ClientBrandRetriever::getClientModName, "Client", Minecraft.class);
|
| 844 | }
|
| 845 |
|
| 846 | private void loadCriticalShaders() {
|
| 847 | GameRenderer.preloadUiShader(this.vanillaPackResources.asResourceManager());
|
| 848 | }
|
| 849 |
|
| 850 | private void rollbackResourcePacks(final Throwable t, final @Nullable GameLoadCookie loadCookie) {
|
| 851 | if (this.resourcePackRepository.getSelectedIds().size() > 1) {
|
| 852 | this.clearResourcePacksOnError(t, null, loadCookie);
|
| 853 | } else {
|
| 854 | Util.throwAsRuntime(t);
|
| 855 | }
|
| 856 | }
|
| 857 |
|
| 858 | public void clearResourcePacksOnError(final Throwable t, final @Nullable Component message, final @Nullable GameLoadCookie loadCookie) {
|
| 859 | LOGGER.info("Caught error loading resourcepacks, removing all selected resourcepacks", t);
|
| 860 | this.reloadStateTracker.startRecovery(t);
|
| 861 | this.downloadedPackSource.onRecovery();
|
| 862 | this.resourcePackRepository.setSelected(Collections.emptyList());
|
| 863 | this.options.resourcePacks.clear();
|
| 864 | this.options.incompatibleResourcePacks.clear();
|
| 865 | this.options.save();
|
| 866 | this.reloadResourcePacks(true, loadCookie).thenRunAsync(() -> this.addResourcePackLoadFailToast(message), this);
|
| 867 | }
|
| 868 |
|
| 869 | private void abortResourcePackRecovery() {
|
| 870 | this.gui.setOverlay(null);
|
| 871 | if (this.level != null) {
|
| 872 | this.level.disconnect(ClientLevel.DEFAULT_QUIT_MESSAGE);
|
| 873 | this.disconnectWithProgressScreen();
|
| 874 | }
|
| 875 |
|
| 876 | this.gui.setScreen(new TitleScreen());
|
| 877 | this.addResourcePackLoadFailToast(null);
|
| 878 | }
|
| 879 |
|
| 880 | private void addResourcePackLoadFailToast(final @Nullable Component message) {
|
| 881 | ToastManager toastManager = this.gui.toastManager();
|
| 882 | SystemToast.addOrUpdate(toastManager, SystemToast.SystemToastId.PACK_LOAD_FAILURE, Component.translatable("resourcePack.load_fail"), message);
|
| 883 | }
|
| 884 |
|
| 885 | public void triggerResourcePackRecovery(final Exception exception) {
|
| 886 | if (!this.resourcePackRepository.isAbleToClearAnyPack()) {
|
| 887 | if (this.resourcePackRepository.getSelectedIds().size() <= 1) {
|
| 888 | LOGGER.error(LogUtils.FATAL_MARKER, "Failed to recover from resource pack error", exception);
|
| 889 | this.emergencySaveAndCrash(new CrashReport(exception.getMessage(), exception));
|
| 890 | } else {
|
| 891 | this.schedule(this::abortResourcePackRecovery);
|
| 892 | }
|
| 893 | } else {
|
| 894 | this.clearResourcePacksOnError(exception, Component.translatable("resourcePack.runtime_failure"), null);
|
| 895 | }
|
| 896 | }
|
| 897 |
|
| 898 | public void run() {
|
| 899 | this.gameThread = Thread.currentThread();
|
| 900 | if (Runtime.getRuntime().availableProcessors() > 4) {
|
| 901 | this.gameThread.setPriority(10);
|
| 902 | }
|
| 903 |
|
| 904 | DiscontinuousFrame tickFrame = TracyClient.createDiscontinuousFrame("Client Tick");
|
| 905 |
|
| 906 | try {
|
| 907 | boolean oomRecovery = false;
|
| 908 |
|
| 909 | while (this.running) {
|
| 910 | try {
|
| 911 | SingleTickProfiler tickProfiler = SingleTickProfiler.createTickProfiler("Renderer");
|
| 912 | boolean shouldCollectFrameProfile = this.getDebugOverlay().showProfilerChart();
|
| 913 |
|
| 914 | try (Scope ignored = Profiler.use(this.constructProfiler(shouldCollectFrameProfile, tickProfiler))) {
|
| 915 | this.metricsRecorder.startTick();
|
| 916 | tickFrame.start();
|
| 917 | RenderSystem.pollEvents(this.sdlEventHandler);
|
| 918 | this.runTick(!oomRecovery);
|
| 919 | tickFrame.end();
|
| 920 | this.metricsRecorder.endTick();
|
| 921 | }
|
| 922 |
|
| 923 | this.finishProfilers(shouldCollectFrameProfile, tickProfiler);
|
| 924 | } catch (OutOfMemoryError e) {
|
| 925 | if (oomRecovery) {
|
| 926 | throw e;
|
| 927 | }
|
| 928 |
|
| 929 | this.emergencySave();
|
| 930 | this.gui.setScreen(new OutOfMemoryScreen());
|
| 931 | System.gc();
|
| 932 | LOGGER.error(LogUtils.FATAL_MARKER, "Out of memory", e);
|
| 933 | oomRecovery = true;
|
| 934 | }
|
| 935 | }
|
| 936 | } catch (ReportedException e) {
|
| 937 | LOGGER.error(LogUtils.FATAL_MARKER, "Reported exception thrown!", e);
|
| 938 | this.emergencySaveAndCrash(e.getReport());
|
| 939 | } catch (Throwable t) {
|
| 940 | LOGGER.error(LogUtils.FATAL_MARKER, "Unreported exception thrown!", t);
|
| 941 | this.emergencySaveAndCrash(new CrashReport("Unexpected error", t));
|
| 942 | }
|
| 943 | }
|
| 944 |
|
| 945 | void updateFontOptions() {
|
| 946 | this.fontManager.updateOptions(this.options);
|
| 947 | }
|
| 948 |
|
| 949 | public String getLaunchedVersion() {
|
| 950 | return this.launchedVersion;
|
| 951 | }
|
| 952 |
|
| 953 | @Override
|
| 954 | public void delayCrash(final CrashReport crash) {
|
| 955 | super.delayCrash(this.fillReport(crash));
|
| 956 | }
|
| 957 |
|
| 958 | public void emergencySaveAndCrash(final CrashReport partialReport) {
|
| 959 | MemoryReserve.release();
|
| 960 | CrashReport finalReport = this.fillReport(partialReport);
|
| 961 | int exitCode = saveReportAndShutdownSoundManager(this, this.gameDirectory, finalReport, -1);
|
| 962 | this.emergencySave();
|
| 963 | System.exit(exitCode);
|
| 964 | }
|
| 965 |
|
| 966 | public static void saveReport(final File gameDirectory, final CrashReport crash) {
|
| 967 | saveReport(gameDirectory, crash, -1);
|
| 968 | }
|
| 969 |
|
| 970 | public static int saveReport(final File gameDirectory, final CrashReport crash, final int reportExitCode) {
|
| 971 | Path crashDir = gameDirectory.toPath().resolve("crash-reports");
|
| 972 | Path crashFile = crashDir.resolve("crash-" + Util.getFilenameFormattedDateTime() + "-client.txt");
|
| 973 |
|
| 974 | try {
|
| 975 | Bootstrap.realStdoutPrintln(crash.getFriendlyReport(ReportType.CRASH));
|
| 976 | } catch (Throwable t) {
|
| 977 | LOGGER.error("Failed to print exception", t);
|
| 978 | }
|
| 979 |
|
| 980 | LOGGER.debug("Disabling console - remaining logs will be available only in log file");
|
| 981 |
|
| 982 | try {
|
| 983 | if (crash.getSaveFile() != null) {
|
| 984 | Bootstrap.realStdoutPrintln("#@!@# Game crashed! Crash report saved to: #@!@# " + crash.getSaveFile().toAbsolutePath());
|
| 985 | return reportExitCode;
|
| 986 | } else if (crash.saveToFile(crashFile, ReportType.CRASH)) {
|
| 987 | Bootstrap.realStdoutPrintln("#@!@# Game crashed! Crash report saved to: #@!@# " + crashFile.toAbsolutePath());
|
| 988 | return reportExitCode;
|
| 989 | } else {
|
| 990 | Bootstrap.realStdoutPrintln("#@?@# Game crashed! Crash report could not be saved. #@?@#");
|
| 991 | return -2;
|
| 992 | }
|
| 993 | } finally {
|
| 994 | Bootstrap.shutdownStdout();
|
| 995 | }
|
| 996 | }
|
| 997 |
|
| 998 | public static void crash(final @Nullable Minecraft minecraft, final File gameDirectory, final CrashReport crash, final int exitCode) {
|
| 999 | int actualExitCode = saveReportAndShutdownSoundManager(minecraft, gameDirectory, crash, exitCode);
|
| 1000 | System.exit(actualExitCode);
|
| 1001 | }
|
| 1002 |
|
| 1003 | public static int saveReportAndShutdownSoundManager(final @Nullable Minecraft minecraft, final File gameDirectory, final CrashReport crash, final int exitCode) {
|
| 1004 | int actualExitCode = saveReport(gameDirectory, crash, exitCode);
|
| 1005 | if (minecraft != null) {
|
| 1006 | minecraft.soundManager.emergencyShutdown();
|
| 1007 | }
|
| 1008 |
|
| 1009 | return actualExitCode;
|
| 1010 | }
|
| 1011 |
|
| 1012 | public boolean isEnforceUnicode() {
|
| 1013 | return this.options.forceUnicodeFont().get();
|
| 1014 | }
|
| 1015 |
|
| 1016 | public CompletableFuture<Void> reloadResourcePacks() {
|
| 1017 | return this.reloadResourcePacks(false, null);
|
| 1018 | }
|
| 1019 |
|
| 1020 | private CompletableFuture<Void> reloadResourcePacks(final boolean isRecovery, final @Nullable GameLoadCookie loadCookie) {
|
| 1021 | if (this.pendingReload != null) {
|
| 1022 | return this.pendingReload;
|
| 1023 | }
|
| 1024 |
|
| 1025 | CompletableFuture<Void> result = new CompletableFuture<>();
|
| 1026 | if (!isRecovery && this.gui.overlay() instanceof LoadingOverlay) {
|
| 1027 | this.pendingReload = result;
|
| 1028 | return result;
|
| 1029 | }
|
| 1030 |
|
| 1031 | this.resourcePackRepository.reload();
|
| 1032 | List<PackResources> packs = this.resourcePackRepository.openAllSelected();
|
| 1033 | if (!isRecovery) {
|
| 1034 | this.reloadStateTracker.startReload(ResourceLoadStateTracker.ReloadReason.MANUAL, packs);
|
| 1035 | }
|
| 1036 |
|
| 1037 | this.gui
|
| 1038 | .setOverlay(
|
| 1039 | new LoadingOverlay(
|
| 1040 | this,
|
| 1041 | this.resourceManager.createReload(Util.backgroundExecutor().forName("resourceLoad"), this, RESOURCE_RELOAD_INITIAL_TASK, packs),
|
| 1042 | maybeT -> Util.ifElse(maybeT, t -> {
|
| 1043 | if (isRecovery) {
|
| 1044 | this.downloadedPackSource.onRecoveryFailure();
|
| 1045 | this.abortResourcePackRecovery();
|
| 1046 | } else {
|
| 1047 | this.rollbackResourcePacks(t, loadCookie);
|
| 1048 | }
|
| 1049 | }, () -> {
|
| 1050 | this.levelExtractor.allChanged();
|
| 1051 | this.reloadStateTracker.finishReload();
|
| 1052 | this.downloadedPackSource.onReloadSuccess();
|
| 1053 | result.complete(null);
|
| 1054 | this.onResourceLoadFinished(loadCookie);
|
| 1055 | }),
|
| 1056 | !isRecovery
|
| 1057 | )
|
| 1058 | );
|
| 1059 | return result;
|
| 1060 | }
|
| 1061 |
|
| 1062 | private void selfTest() {
|
| 1063 | boolean error = false;
|
| 1064 | BlockStateModelSet blockModelSet = this.getModelManager().getBlockStateModelSet();
|
| 1065 | BlockStateModel missingModel = blockModelSet.missingModel();
|
| 1066 |
|
| 1067 | for (Block block : BuiltInRegistries.BLOCK) {
|
| 1068 | for (BlockState state : block.getStateDefinition().getPossibleStates()) {
|
| 1069 | if (state.getRenderShape() == RenderShape.MODEL) {
|
| 1070 | BlockStateModel model = blockModelSet.get(state);
|
| 1071 | if (model == missingModel) {
|
| 1072 | LOGGER.debug("Missing model for: {}", state);
|
| 1073 | error = true;
|
| 1074 | }
|
| 1075 | }
|
| 1076 | }
|
| 1077 | }
|
| 1078 |
|
| 1079 | TextureAtlasSprite missingIcon = missingModel.particleMaterial().sprite();
|
| 1080 |
|
| 1081 | for (Block block : BuiltInRegistries.BLOCK) {
|
| 1082 | for (BlockState state : block.getStateDefinition().getPossibleStates()) {
|
| 1083 | TextureAtlasSprite particleIcon = blockModelSet.getParticleMaterial(state).sprite();
|
| 1084 | if (!state.isAir() && particleIcon == missingIcon) {
|
| 1085 | LOGGER.debug("Missing particle icon for: {}", state);
|
| 1086 | }
|
| 1087 | }
|
| 1088 | }
|
| 1089 |
|
| 1090 | error |= TelemetryEventType.selfTest();
|
| 1091 | error |= MenuScreens.selfTest();
|
| 1092 | error |= EntityRenderers.validateRegistrations();
|
| 1093 | if (error) {
|
| 1094 | throw new IllegalStateException("Your game data is foobar, fix the errors above!");
|
| 1095 | }
|
| 1096 | }
|
| 1097 |
|
| 1098 | public LevelStorageSource getLevelSource() {
|
| 1099 | return this.levelSource;
|
| 1100 | }
|
| 1101 |
|
| 1102 | public void exitWorldAndClose() {
|
| 1103 | try {
|
| 1104 | LOGGER.info("Stopping!");
|
| 1105 | if (this.level != null) {
|
| 1106 | this.level.disconnect(ClientLevel.DEFAULT_QUIT_MESSAGE);
|
| 1107 | }
|
| 1108 |
|
| 1109 | this.disconnectWithProgressScreen();
|
| 1110 | if (this.gui.screen() != null) {
|
| 1111 | this.gui.screen().removed();
|
| 1112 | }
|
| 1113 | } finally {
|
| 1114 | this.close();
|
| 1115 | }
|
| 1116 | }
|
| 1117 |
|
| 1118 | @Override
|
| 1119 | public void close() {
|
| 1120 | Util.shutdownTimeSource();
|
| 1121 |
|
| 1122 | try {
|
| 1123 | this.playerSocialManager.getPresenceHandler().sendOfflinePresence();
|
| 1124 | this.remoteFriendListUpdateHandler.close();
|
| 1125 | this.timerQuery.close();
|
| 1126 | this.telemetryManager.close();
|
| 1127 | this.regionalCompliancies.close();
|
| 1128 | this.atlasManager.close();
|
| 1129 | this.fontManager.close();
|
| 1130 | this.gameRenderer.close();
|
| 1131 | this.shaderManager.close();
|
| 1132 | this.levelRenderer.close();
|
| 1133 | this.soundManager.destroy();
|
| 1134 | this.palettedTextureManager.close();
|
| 1135 | this.mapTextureManager.close();
|
| 1136 | this.textureManager.close();
|
| 1137 | this.resourceManager.close();
|
| 1138 | if (this.tracyFrameCapture != null) {
|
| 1139 | this.tracyFrameCapture.close();
|
| 1140 | }
|
| 1141 |
|
| 1142 | this.narrator.destroy();
|
| 1143 | FreeTypeUtil.destroy();
|
| 1144 | this.windowSurface.close();
|
| 1145 | RenderSystem.shutdownRenderer();
|
| 1146 | } catch (Throwable t) {
|
| 1147 | LOGGER.error("Shutdown failure!", t);
|
| 1148 | throw t;
|
| 1149 | } finally {
|
| 1150 | this.window.close();
|
| 1151 | RenderSystem.unloadTrackedBackendLibrary();
|
| 1152 | SDLInit.SDL_Quit();
|
| 1153 | Util.shutdownExecutors();
|
| 1154 | }
|
| 1155 | }
|
| 1156 |
|
| 1157 | private void runTick(final boolean advanceGameTime) {
|
| 1158 | this.window.setErrorSection("Pre render");
|
| 1159 | if (this.window.shouldClose()) {
|
| 1160 | this.stop();
|
| 1161 | }
|
| 1162 |
|
| 1163 | if (this.pendingReload != null && !(this.gui.overlay() instanceof LoadingOverlay)) {
|
| 1164 | CompletableFuture<Void> future = this.pendingReload;
|
| 1165 | this.pendingReload = null;
|
| 1166 | this.reloadResourcePacks().thenRun(() -> future.complete(null));
|
| 1167 | }
|
| 1168 |
|
| 1169 | this.playerSocialManager.getPresenceHandler().tick();
|
| 1170 | int ticksToDo = advanceGameTime ? this.deltaTracker.advanceGameTime(Util.getMillis()) : 0;
|
| 1171 | ProfilerFiller profiler = Profiler.get();
|
| 1172 | if (advanceGameTime) {
|
| 1173 | try (TemporaryCollection ignored = this.collectPerTickGizmos()) {
|
| 1174 | profiler.push("scheduledPacketProcessing");
|
| 1175 | this.packetProcessor.processQueuedPackets();
|
| 1176 | profiler.popPush("scheduledExecutables");
|
| 1177 | this.runAllTasks();
|
| 1178 | profiler.pop();
|
| 1179 | }
|
| 1180 |
|
| 1181 | profiler.push("tick");
|
| 1182 | if (ticksToDo > 0 && this.isLevelRunningNormally()) {
|
| 1183 | profiler.push("textures");
|
| 1184 | this.textureManager.tick();
|
| 1185 | profiler.pop();
|
| 1186 | }
|
| 1187 |
|
| 1188 | for (int i = 0; i < Math.min(10, ticksToDo); i++) {
|
| 1189 | profiler.incrementCounter("clientTick");
|
| 1190 |
|
| 1191 | try (TemporaryCollection ignored = this.collectPerTickGizmos()) {
|
| 1192 | this.tick();
|
| 1193 | }
|
| 1194 | }
|
| 1195 |
|
| 1196 | if (ticksToDo > 0 && (this.level == null || this.level.tickRateManager().runsNormally())) {
|
| 1197 | this.drainedLatestTickGizmos = this.perTickGizmos.drainGizmos();
|
| 1198 | }
|
| 1199 |
|
| 1200 | profiler.pop();
|
| 1201 | }
|
| 1202 |
|
| 1203 | this.window.setErrorSection("Render");
|
| 1204 |
|
| 1205 | try (TemporaryCollection ignored = this.levelExtractor.collectPerFrameMainThreadGizmos()) {
|
| 1206 | profiler.push("sound");
|
| 1207 | this.soundManager.updateSource(this.gameRenderer.mainCamera());
|
| 1208 | profiler.popPush("mouse");
|
| 1209 | this.mouseHandler.handleAccumulatedMovement();
|
| 1210 | }
|
| 1211 |
|
| 1212 | try {
|
| 1213 | profiler.popPush("frame");
|
| 1214 | this.renderFrame(advanceGameTime);
|
| 1215 | } catch (Exception e) {
|
| 1216 | CrashReport report = CrashReport.forThrowable(e, "Render Frame");
|
| 1217 | CrashReportCategory manualCrashDetails = report.addCategory("Render Frame Details");
|
| 1218 | NativeModuleLister.addCrashSection(manualCrashDetails);
|
| 1219 | manualCrashDetails.setDetail("Post effects", this.gameRenderer.getRequestedPostEffects());
|
| 1220 | throw new ReportedException(report);
|
| 1221 | } finally {
|
| 1222 | profiler.pop();
|
| 1223 | }
|
| 1224 |
|
| 1225 | this.window.setErrorSection("Post render");
|
| 1226 | boolean var28 = this.pause;
|
| 1227 | this.pause = this.hasSingleplayerServer() && this.gui.isPausing() && !this.singleplayerServer.isPublished();
|
| 1228 | if (!var28 && this.pause) {
|
| 1229 | this.soundManager.pauseAllExcept(SoundSource.MUSIC, SoundSource.UI);
|
| 1230 | }
|
| 1231 |
|
| 1232 | this.deltaTracker.updatePauseState(this.pause);
|
| 1233 | this.deltaTracker.updateFrozenState(!this.isLevelRunningNormally());
|
| 1234 | }
|
| 1235 |
|
| 1236 | public void renderFrame(final boolean advanceGameTime) {
|
| 1237 | if (!this.windowSurface.isAcquired()) {
|
| 1238 | ProfilerFiller profiler = Profiler.get();
|
| 1239 |
|
| 1240 | long renderStartTimer;
|
| 1241 | boolean recordGpuUtilization;
|
| 1242 | try (TemporaryCollection ignored = this.levelExtractor.collectPerFrameMainThreadGizmos()) {
|
| 1243 | profiler.push("update window");
|
| 1244 | this.window.updateFullscreenIfChanged();
|
| 1245 | if ((this.windowSurfaceNeedsReconfiguring || this.windowSurface.isSuboptimal() && !this.surfaceIsInvalid) && !this.window.isIconified()) {
|
| 1246 | Window.FramebufferSize framebufferSize = this.window.queryFramebufferSize();
|
| 1247 | GpuSurface.PresentMode presentMode = GpuSurface.PresentMode.getSupportedVsyncMode(
|
| 1248 | this.windowSurface.supportedPresentModes(), this.options.enableVsync().get()
|
| 1249 | );
|
| 1250 | GpuSurface.Configuration config = new GpuSurface.Configuration(framebufferSize.width(), framebufferSize.height(), presentMode);
|
| 1251 |
|
| 1252 | try {
|
| 1253 | this.windowSurface.configure(config);
|
| 1254 | this.surfaceIsInvalid = false;
|
| 1255 | this.windowSurfaceNeedsReconfiguring = false;
|
| 1256 | } catch (SurfaceException exception) {
|
| 1257 | LOGGER.warn("Couldn't configure surface to {}", config, exception);
|
| 1258 | this.surfaceIsInvalid = true;
|
| 1259 | }
|
| 1260 | }
|
| 1261 |
|
| 1262 | if (!this.surfaceIsInvalid) {
|
| 1263 | try {
|
| 1264 | this.windowSurface.acquireNextTexture();
|
| 1265 | } catch (SurfaceException ex) {
|
| 1266 | LOGGER.warn("Couldn't acquire next surface texture with config {}", this.windowSurface.currentConfiguration(), ex);
|
| 1267 | this.surfaceIsInvalid = true;
|
| 1268 | this.windowSurfaceNeedsReconfiguring = true;
|
| 1269 | }
|
| 1270 | }
|
| 1271 |
|
| 1272 | profiler.popPush("update");
|
| 1273 | this.deltaTracker.advanceRealTime(Util.getMillis());
|
| 1274 | if (!this.debugEntries.isCurrentlyEnabled(DebugScreenEntries.GPU_UTILIZATION) && !this.metricsRecorder.isRecording()) {
|
| 1275 | recordGpuUtilization = false;
|
| 1276 | this.gpuUtilization = 0.0;
|
| 1277 | } else {
|
| 1278 | recordGpuUtilization = this.timerQuery.getStatus() == TimerQuery.Status.NOT_RECORDING;
|
| 1279 | if (recordGpuUtilization) {
|
| 1280 | this.timerQuery.beginProfile();
|
| 1281 | }
|
| 1282 | }
|
| 1283 |
|
| 1284 | renderStartTimer = Util.getNanos();
|
| 1285 | this.pauseIfInactive();
|
| 1286 | this.gui.update();
|
| 1287 | if (this.isGameLoadFinished() && advanceGameTime && this.level != null) {
|
| 1288 | this.level.update();
|
| 1289 | }
|
| 1290 |
|
| 1291 | this.gameRenderer.update(this.deltaTracker);
|
| 1292 | float worldPartialTicks = this.deltaTracker.getGameTimeDeltaPartialTick(false);
|
| 1293 | this.pick(worldPartialTicks);
|
| 1294 | profiler.popPush("extract");
|
| 1295 | this.gameRenderer.gameRenderState().framerateLimit = this.framerateLimitTracker.getFramerateLimit();
|
| 1296 | this.gameRenderer.extract(this.deltaTracker, advanceGameTime);
|
| 1297 | }
|
| 1298 |
|
| 1299 | try (TemporaryCollection ignored = this.levelRenderer.collectPerFrameRenderThreadGizmos()) {
|
| 1300 | profiler.popPush("gpuAsync");
|
| 1301 | RenderSystem.executePendingTasks();
|
| 1302 | profiler.pop();
|
| 1303 | this.gameRenderer.render();
|
| 1304 | }
|
| 1305 |
|
| 1306 | profiler.push("swapchainBlit");
|
| 1307 | if (this.windowSurface.isAcquired()) {
|
| 1308 | GpuTextureView colorTexture = this.gameRenderer.mainRenderTarget().getColorTextureView();
|
| 1309 | if (colorTexture == null) {
|
| 1310 | throw new IllegalStateException("Can't blit to screen, color texture doesn't exist yet");
|
| 1311 | }
|
| 1312 |
|
| 1313 | this.windowSurface.blitFromTexture(RenderSystem.getDevice().createCommandEncoder(), colorTexture);
|
| 1314 | }
|
| 1315 |
|
| 1316 | this.frameTimeNs = Util.getNanos() - renderStartTimer;
|
| 1317 | if (recordGpuUtilization) {
|
| 1318 | this.timerQuery.endProfile();
|
| 1319 | }
|
| 1320 |
|
| 1321 | if (this.tracyFrameCapture != null) {
|
| 1322 | profiler.popPush("tracyCapture");
|
| 1323 | this.tracyFrameCapture.upload();
|
| 1324 | this.tracyFrameCapture.capture(this.gameRenderer.mainRenderTarget());
|
| 1325 | }
|
| 1326 |
|
| 1327 | profiler.popPush("submit");
|
| 1328 | RenderSystem.getDevice().createCommandEncoder().submit();
|
| 1329 | profiler.popPush("present");
|
| 1330 | if (this.windowSurface.isAcquired()) {
|
| 1331 | this.windowSurface.present();
|
| 1332 | }
|
| 1333 |
|
| 1334 | profiler.popPush("endFrame");
|
| 1335 | if (this.tracyFrameCapture != null) {
|
| 1336 | this.tracyFrameCapture.endFrame();
|
| 1337 | }
|
| 1338 |
|
| 1339 | RenderSystem.getDynamicUniforms().reset();
|
| 1340 | this.levelRenderer.endFrame();
|
| 1341 | profiler.popPush("frameLimiter");
|
| 1342 | int framerateLimit = this.gameRenderer.gameRenderState().framerateLimit;
|
| 1343 | if (framerateLimit < 260) {
|
| 1344 | FramerateLimiter.limitDisplayFPS(framerateLimit);
|
| 1345 | }
|
| 1346 |
|
| 1347 | profiler.popPush("fpsUpdate");
|
| 1348 | this.frames++;
|
| 1349 | long currentTime = Util.getNanos();
|
| 1350 | long frameDuration = currentTime - this.lastNanoTime;
|
| 1351 | if (recordGpuUtilization) {
|
| 1352 | this.savedCpuDuration = frameDuration;
|
| 1353 | }
|
| 1354 |
|
| 1355 | this.getDebugOverlay().logFrameDuration(frameDuration);
|
| 1356 | this.lastNanoTime = currentTime;
|
| 1357 |
|
| 1358 | for (this.gpuUtilization = this.timerQuery.get() * 100.0 / this.savedCpuDuration; Util.getMillis() >= this.lastTime + 1000L; this.frames = 0) {
|
| 1359 | fps = this.frames;
|
| 1360 | this.lastTime += 1000L;
|
| 1361 | }
|
| 1362 |
|
| 1363 | profiler.pop();
|
| 1364 | }
|
| 1365 | }
|
| 1366 |
|
| 1367 | private void pauseIfInactive() {
|
| 1368 | if (!this.window.isFocused() && this.options.pauseOnLostFocus) {
|
| 1369 | if (Util.getMillis() - this.lastActiveTime > 500L) {
|
| 1370 | this.pauseGame(false);
|
| 1371 | }
|
| 1372 | } else {
|
| 1373 | this.lastActiveTime = Util.getMillis();
|
| 1374 | }
|
| 1375 | }
|
| 1376 |
|
| 1377 | private ProfilerFiller constructProfiler(final boolean shouldCollectFrameProfile, final @Nullable SingleTickProfiler tickProfiler) {
|
| 1378 | if (!shouldCollectFrameProfile) {
|
| 1379 | this.fpsPieProfiler.disable();
|
| 1380 | if (!this.metricsRecorder.isRecording() && tickProfiler == null) {
|
| 1381 | return InactiveProfiler.INSTANCE;
|
| 1382 | }
|
| 1383 | }
|
| 1384 |
|
| 1385 | ProfilerFiller result;
|
| 1386 | if (shouldCollectFrameProfile) {
|
| 1387 | if (!this.fpsPieProfiler.isEnabled()) {
|
| 1388 | this.fpsPieRenderTicks = 0;
|
| 1389 | this.fpsPieProfiler.enable();
|
| 1390 | }
|
| 1391 |
|
| 1392 | this.fpsPieRenderTicks++;
|
| 1393 | result = this.fpsPieProfiler.getFiller();
|
| 1394 | } else {
|
| 1395 | result = InactiveProfiler.INSTANCE;
|
| 1396 | }
|
| 1397 |
|
| 1398 | if (this.metricsRecorder.isRecording()) {
|
| 1399 | result = ProfilerFiller.combine(result, this.metricsRecorder.getProfiler());
|
| 1400 | }
|
| 1401 |
|
| 1402 | return SingleTickProfiler.decorateFiller(result, tickProfiler);
|
| 1403 | }
|
| 1404 |
|
| 1405 | private void finishProfilers(final boolean shouldCollectFrameProfile, final @Nullable SingleTickProfiler tickProfiler) {
|
| 1406 | if (tickProfiler != null) {
|
| 1407 | tickProfiler.endTick();
|
| 1408 | }
|
| 1409 |
|
| 1410 | ProfilerPieChart profilerPieChart = this.getDebugOverlay().getProfilerPieChart();
|
| 1411 | if (shouldCollectFrameProfile) {
|
| 1412 | profilerPieChart.setPieChartResults(this.fpsPieProfiler.getResults());
|
| 1413 | } else {
|
| 1414 | profilerPieChart.setPieChartResults(null);
|
| 1415 | }
|
| 1416 | }
|
| 1417 |
|
| 1418 | @Override
|
| 1419 | public void framebufferSizeChanged() {
|
| 1420 | this.invalidateSurfaceConfiguration();
|
| 1421 | this.resizeGui();
|
| 1422 | }
|
| 1423 |
|
| 1424 | @Override
|
| 1425 | public void resizeGui() {
|
| 1426 | int guiScale = this.window.calculateScale(this.options.guiScale().get(), this.isEnforceUnicode());
|
| 1427 | this.window.setGuiScale(guiScale);
|
| 1428 | if (this.gui.screen() != null) {
|
| 1429 | this.gui.screen().resize(this.window.getGuiScaledWidth(), this.window.getGuiScaledHeight());
|
| 1430 | }
|
| 1431 |
|
| 1432 | this.mouseHandler.resyncMousePosition();
|
| 1433 | this.mouseHandler.setIgnoreFirstMove();
|
| 1434 | }
|
| 1435 |
|
| 1436 | @Override
|
| 1437 | public void cursorEntered() {
|
| 1438 | this.mouseHandler.cursorEntered();
|
| 1439 | }
|
| 1440 |
|
| 1441 | @Override
|
| 1442 | public void fullscreenStateChanged(final boolean fullscreen) {
|
| 1443 | if (this.options.fullscreen().get() != fullscreen) {
|
| 1444 | this.options.fullscreen().set(fullscreen);
|
| 1445 | this.options.save();
|
| 1446 | if (this.gui != null && this.gui.screen() instanceof VideoSettingsScreen videoSettingsScreen) {
|
| 1447 | videoSettingsScreen.updateFullscreenButton(fullscreen);
|
| 1448 | }
|
| 1449 | }
|
| 1450 | }
|
| 1451 |
|
| 1452 | public int getFps() {
|
| 1453 | return fps;
|
| 1454 | }
|
| 1455 |
|
| 1456 | public long getFrameTimeNs() {
|
| 1457 | return this.frameTimeNs;
|
| 1458 | }
|
| 1459 |
|
| 1460 | public void sendLowDiskSpaceWarning() {
|
| 1461 | this.execute(() -> SystemToast.onLowDiskSpace(this));
|
| 1462 | }
|
| 1463 |
|
| 1464 | private void emergencySave() {
|
| 1465 | MemoryReserve.release();
|
| 1466 |
|
| 1467 | try {
|
| 1468 | if (this.isLocalServer && this.singleplayerServer != null) {
|
| 1469 | this.singleplayerServer.halt(true);
|
| 1470 | }
|
| 1471 |
|
| 1472 | this.disconnectWithSavingScreen();
|
| 1473 | } catch (Throwable var2) {
|
| 1474 | }
|
| 1475 |
|
| 1476 | System.gc();
|
| 1477 | }
|
| 1478 |
|
| 1479 | public boolean debugClientMetricsStart(final Consumer<Component> debugFeedback) {
|
| 1480 | if (this.metricsRecorder.isRecording()) {
|
| 1481 | this.debugClientMetricsStop();
|
| 1482 | return false;
|
| 1483 | }
|
| 1484 |
|
| 1485 | Consumer<ProfileResults> onStopped = results -> {
|
| 1486 | if (results != EmptyProfileResults.EMPTY) {
|
| 1487 | int ticks = results.getTickDuration();
|
| 1488 | double durationInSeconds = (double)results.getNanoDuration() / TimeUtil.NANOSECONDS_PER_SECOND;
|
| 1489 | this.execute(
|
| 1490 | () -> debugFeedback.accept(
|
| 1491 | Component.translatable(
|
| 1492 | "commands.debug.stopped", String.format(Locale.ROOT, "%.2f", durationInSeconds), ticks, String.format(Locale.ROOT, "%.2f", ticks / durationInSeconds)
|
| 1493 | )
|
| 1494 | )
|
| 1495 | );
|
| 1496 | }
|
| 1497 | };
|
| 1498 | Consumer<Path> onFinished = profilePath -> {
|
| 1499 | Component profilePathComponent = Component.literal(profilePath.toString())
|
| 1500 | .withStyle(ChatFormatting.UNDERLINE)
|
| 1501 | .withStyle(s -> s.withClickEvent(new OpenFile(profilePath.getParent())));
|
| 1502 | this.execute(() -> debugFeedback.accept(Component.translatable("debug.profiling.stop", profilePathComponent)));
|
| 1503 | };
|
| 1504 | SystemReport systemReport = fillSystemReport(new SystemReport(), this, this.languageManager, this.launchedVersion, this.options);
|
| 1505 | Consumer<List<Path>> profileReports = logs -> {
|
| 1506 | Path profilePath = this.archiveProfilingReport(systemReport, logs);
|
| 1507 | onFinished.accept(profilePath);
|
| 1508 | };
|
| 1509 | Consumer<Path> whenClientMetricsRecordingFinished;
|
| 1510 | if (this.singleplayerServer == null) {
|
| 1511 | whenClientMetricsRecordingFinished = path -> profileReports.accept(ImmutableList.of(path));
|
| 1512 | } else {
|
| 1513 | this.singleplayerServer.fillSystemReport(systemReport);
|
| 1514 | CompletableFuture<Path> clientMetricRecordingResult = new CompletableFuture<>();
|
| 1515 | CompletableFuture<Path> serverMetricRecordingResult = new CompletableFuture<>();
|
| 1516 | CompletableFuture.allOf(clientMetricRecordingResult, serverMetricRecordingResult)
|
| 1517 | .thenRunAsync(() -> profileReports.accept(ImmutableList.of(clientMetricRecordingResult.join(), serverMetricRecordingResult.join())), Util.ioPool());
|
| 1518 | this.singleplayerServer.startRecordingMetrics(ignored -> {}, serverMetricRecordingResult::complete);
|
| 1519 | whenClientMetricsRecordingFinished = clientMetricRecordingResult::complete;
|
| 1520 | }
|
| 1521 |
|
| 1522 | this.metricsRecorder = ActiveMetricsRecorder.createStarted(
|
| 1523 | new ClientMetricsSamplersProvider(Util.timeSource(), this.levelRenderer, this.levelExtractor),
|
| 1524 | Util.timeSource(),
|
| 1525 | Util.ioPool(),
|
| 1526 | new MetricsPersister("client"),
|
| 1527 | results -> {
|
| 1528 | this.metricsRecorder = InactiveMetricsRecorder.INSTANCE;
|
| 1529 | onStopped.accept(results);
|
| 1530 | },
|
| 1531 | whenClientMetricsRecordingFinished
|
| 1532 | );
|
| 1533 | return true;
|
| 1534 | }
|
| 1535 |
|
| 1536 | private void debugClientMetricsStop() {
|
| 1537 | this.metricsRecorder.end();
|
| 1538 | if (this.singleplayerServer != null) {
|
| 1539 | this.singleplayerServer.finishRecordingMetrics();
|
| 1540 | }
|
| 1541 | }
|
| 1542 |
|
| 1543 | private void debugClientMetricsCancel() {
|
| 1544 | this.metricsRecorder.cancel();
|
| 1545 | if (this.singleplayerServer != null) {
|
| 1546 | this.singleplayerServer.cancelRecordingMetrics();
|
| 1547 | }
|
| 1548 | }
|
| 1549 |
|
| 1550 | private Path archiveProfilingReport(final SystemReport systemReport, final List<Path> profilingResultPaths) {
|
| 1551 | String levelName;
|
| 1552 | if (this.isLocalServer()) {
|
| 1553 | levelName = this.getSingleplayerServer().getWorldData().getLevelName();
|
| 1554 | } else {
|
| 1555 | ServerData server = this.getCurrentServer();
|
| 1556 | levelName = server != null ? server.name : "unknown";
|
| 1557 | }
|
| 1558 |
|
| 1559 | Path archivePath;
|
| 1560 | try {
|
| 1561 | String profilingName = String.format(Locale.ROOT, "%s-%s-%s", Util.getFilenameFormattedDateTime(), levelName, SharedConstants.getCurrentVersion().id());
|
| 1562 | String zipFileName = FileUtil.findAvailableName(MetricsPersister.PROFILING_RESULTS_DIR, profilingName, ".zip");
|
| 1563 | archivePath = MetricsPersister.PROFILING_RESULTS_DIR.resolve(zipFileName);
|
| 1564 | } catch (IOException e) {
|
| 1565 | throw new UncheckedIOException(e);
|
| 1566 | }
|
| 1567 |
|
| 1568 | try (FileZipper fileZipper = new FileZipper(archivePath)) {
|
| 1569 | fileZipper.add(Paths.get("system.txt"), systemReport.toLineSeparatedString());
|
| 1570 | fileZipper.add(Paths.get("client").resolve(this.options.getFile().getName()), this.options.dumpOptionsForReport());
|
| 1571 | profilingResultPaths.forEach(fileZipper::add);
|
| 1572 | } finally {
|
| 1573 | for (Path path : profilingResultPaths) {
|
| 1574 | try {
|
| 1575 | FileUtils.forceDelete(path.toFile());
|
| 1576 | } catch (IOException e) {
|
| 1577 | LOGGER.warn("Failed to delete temporary profiling result {}", path, e);
|
| 1578 | }
|
| 1579 | }
|
| 1580 | }
|
| 1581 |
|
| 1582 | return archivePath;
|
| 1583 | }
|
| 1584 |
|
| 1585 | public void stop() {
|
| 1586 | this.running = false;
|
| 1587 | }
|
| 1588 |
|
| 1589 | public boolean isRunning() {
|
| 1590 | return this.running;
|
| 1591 | }
|
| 1592 |
|
| 1593 | public void pauseGame(final boolean suppressPauseMenuIfWeReallyArePausing) {
|
| 1594 | boolean canGameReallyBePaused = this.hasSingleplayerServer() && !this.singleplayerServer.isPublished();
|
| 1595 | this.gui.setPauseScreen(suppressPauseMenuIfWeReallyArePausing, canGameReallyBePaused);
|
| 1596 | if (this.gameMode != null) {
|
| 1597 | this.gameMode.stopDestroyBlock();
|
| 1598 | }
|
| 1599 | }
|
| 1600 |
|
| 1601 | private void continueAttack(final boolean down) {
|
| 1602 | if (!down) {
|
| 1603 | this.missTime = 0;
|
| 1604 | }
|
| 1605 |
|
| 1606 | if (this.missTime <= 0 && !this.player.isUsingItem()) {
|
| 1607 | ItemStack heldItem = this.player.getItemInHand(InteractionHand.MAIN_HAND);
|
| 1608 | if (!heldItem.has(DataComponents.PIERCING_WEAPON)) {
|
| 1609 | SwingAnimation swingAnimation = heldItem.getAttackAnimation();
|
| 1610 | if (down && this.hitResult != null && this.hitResult.getType() == Type.BLOCK) {
|
| 1611 | BlockHitResult blockHit = (BlockHitResult)this.hitResult;
|
| 1612 | BlockPos pos = blockHit.getBlockPos();
|
| 1613 | if (!this.level.getBlockState(pos).isAir()) {
|
| 1614 | Direction direction = blockHit.getDirection();
|
| 1615 | if (this.gameMode.continueDestroyBlock(pos, direction)) {
|
| 1616 | this.player.swing(InteractionHand.MAIN_HAND, swingAnimation, false);
|
| 1617 | this.player.connection.send(ServerboundPunchPacket.INSTANCE);
|
| 1618 | }
|
| 1619 | }
|
| 1620 | } else {
|
| 1621 | this.gameMode.stopDestroyBlock();
|
| 1622 | }
|
| 1623 | }
|
| 1624 | }
|
| 1625 | }
|
| 1626 |
|
| 1627 | private boolean startAttack() {
|
| 1628 | if (this.missTime > 0) {
|
| 1629 | return false;
|
| 1630 | }
|
| 1631 |
|
| 1632 | if (this.hitResult == null) {
|
| 1633 | LOGGER.error("Null returned as 'hitResult', this shouldn't happen!");
|
| 1634 | if (this.gameMode.hasMissTime()) {
|
| 1635 | this.missTime = 10;
|
| 1636 | }
|
| 1637 |
|
| 1638 | return false;
|
| 1639 | } else {
|
| 1640 | if (this.player.isHandsBusy()) {
|
| 1641 | return false;
|
| 1642 | }
|
| 1643 |
|
| 1644 | if (this.gameMode.isSpectator()) {
|
| 1645 | if (this.hitResult instanceof EntityHitResult entityHitResult) {
|
| 1646 | this.gameMode.spectate(entityHitResult.getEntity());
|
| 1647 | } else {
|
| 1648 | this.gameMode.spectatorNoAction();
|
| 1649 | }
|
| 1650 |
|
| 1651 | return true;
|
| 1652 | } else {
|
| 1653 | ItemStack heldItem = this.player.getItemInHand(InteractionHand.MAIN_HAND);
|
| 1654 | if (!heldItem.isItemEnabled(this.level.enabledFeatures())) {
|
| 1655 | return false;
|
| 1656 | }
|
| 1657 |
|
| 1658 | if (this.player.cannotAttackWithItem(heldItem, 0)) {
|
| 1659 | return false;
|
| 1660 | }
|
| 1661 |
|
| 1662 | SwingAnimation attackAnimation = heldItem.getAttackAnimation();
|
| 1663 | boolean endAttack = false;
|
| 1664 | PiercingWeapon piercingWeapon = heldItem.get(DataComponents.PIERCING_WEAPON);
|
| 1665 | if (piercingWeapon != null) {
|
| 1666 | this.gameMode.piercingAttack(attackAnimation, piercingWeapon);
|
| 1667 | return true;
|
| 1668 | }
|
| 1669 |
|
| 1670 | switch (this.hitResult.getType()) {
|
| 1671 | case ENTITY:
|
| 1672 | AttackRange customItemRange = heldItem.get(DataComponents.ATTACK_RANGE);
|
| 1673 | if (customItemRange == null || customItemRange.isInRange(this.player, this.hitResult.getLocation())) {
|
| 1674 | this.gameMode.attack(this.player, ((EntityHitResult)this.hitResult).getEntity());
|
| 1675 | }
|
| 1676 | break;
|
| 1677 | case BLOCK:
|
| 1678 | BlockHitResult blockHit = (BlockHitResult)this.hitResult;
|
| 1679 | BlockPos pos = blockHit.getBlockPos();
|
| 1680 | if (!this.level.getBlockState(pos).isAir()) {
|
| 1681 | this.gameMode.startDestroyBlock(pos, blockHit.getDirection());
|
| 1682 | if (this.level.getBlockState(pos).isAir()) {
|
| 1683 | endAttack = true;
|
| 1684 | }
|
| 1685 | break;
|
| 1686 | }
|
| 1687 | case MISS:
|
| 1688 | if (this.gameMode.hasMissTime()) {
|
| 1689 | this.missTime = 10;
|
| 1690 | }
|
| 1691 |
|
| 1692 | this.player.resetAttackStrengthTicker();
|
| 1693 | }
|
| 1694 |
|
| 1695 | this.player.swing(InteractionHand.MAIN_HAND, attackAnimation, false);
|
| 1696 | this.player.connection.send(ServerboundPunchPacket.INSTANCE);
|
| 1697 | return endAttack;
|
| 1698 | }
|
| 1699 | }
|
| 1700 | }
|
| 1701 |
|
| 1702 | private void startUseItem() {
|
| 1703 | if (!this.gameMode.isDestroying()) {
|
| 1704 | this.rightClickDelay = 4;
|
| 1705 | if (!this.player.isHandsBusy()) {
|
| 1706 | if (this.hitResult == null) {
|
| 1707 | LOGGER.warn("Null returned as 'hitResult', this shouldn't happen!");
|
| 1708 | }
|
| 1709 |
|
| 1710 | for (InteractionHand hand : InteractionHand.values()) {
|
| 1711 | ItemStack heldItem = this.player.getItemInHand(hand);
|
| 1712 | if (!heldItem.isItemEnabled(this.level.enabledFeatures())) {
|
| 1713 | return;
|
| 1714 | }
|
| 1715 |
|
| 1716 | SwingAnimation swingAnimation = heldItem.getInteractAnimation();
|
| 1717 | if (this.hitResult != null) {
|
| 1718 | switch (this.hitResult.getType()) {
|
| 1719 | case ENTITY:
|
| 1720 | EntityHitResult entityHit = (EntityHitResult)this.hitResult;
|
| 1721 | Entity entity = entityHit.getEntity();
|
| 1722 | if (!this.level.getWorldBorder().isWithinBounds(entity.blockPosition())) {
|
| 1723 | return;
|
| 1724 | }
|
| 1725 |
|
| 1726 | if (this.player.isWithinEntityInteractionRange(entity, 0.0) && this.gameMode.interact(this.player, entity, entityHit, hand) instanceof Success success) {
|
| 1727 | if (success.swingSource() == SwingSource.PREDICTED) {
|
| 1728 | this.player.swing(hand, swingAnimation, false);
|
| 1729 | }
|
| 1730 |
|
| 1731 | return;
|
| 1732 | }
|
| 1733 | break;
|
| 1734 | case BLOCK:
|
| 1735 | BlockHitResult blockHit = (BlockHitResult)this.hitResult;
|
| 1736 | int oldCount = heldItem.getCount();
|
| 1737 | InteractionResult useResult = this.gameMode.useItemOn(this.player, hand, blockHit);
|
| 1738 | if (useResult instanceof Success success) {
|
| 1739 | if (success.swingSource() == SwingSource.PREDICTED) {
|
| 1740 | this.player.swing(hand, swingAnimation, false);
|
| 1741 | if (!heldItem.isEmpty() && (heldItem.getCount() != oldCount || this.player.hasInfiniteMaterials())) {
|
| 1742 | this.player.itemUsed(hand);
|
| 1743 | }
|
| 1744 | }
|
| 1745 |
|
| 1746 | return;
|
| 1747 | }
|
| 1748 |
|
| 1749 | if (useResult instanceof Fail) {
|
| 1750 | return;
|
| 1751 | }
|
| 1752 | }
|
| 1753 | }
|
| 1754 |
|
| 1755 | if (!heldItem.isEmpty() && this.gameMode.useItem(this.player, hand) instanceof Success success) {
|
| 1756 | if (success.swingSource() == SwingSource.PREDICTED) {
|
| 1757 | this.player.swing(hand, swingAnimation, false);
|
| 1758 | }
|
| 1759 |
|
| 1760 | this.player.itemUsed(hand);
|
| 1761 | return;
|
| 1762 | }
|
| 1763 | }
|
| 1764 | }
|
| 1765 | }
|
| 1766 | }
|
| 1767 |
|
| 1768 | public MusicManager getMusicManager() {
|
| 1769 | return this.musicManager;
|
| 1770 | }
|
| 1771 |
|
| 1772 | public void tick() {
|
| 1773 | this.clientTickCount++;
|
| 1774 | if (this.level != null && !this.pause) {
|
| 1775 | this.level.tickRateManager().tick();
|
| 1776 | }
|
| 1777 |
|
| 1778 | if (this.rightClickDelay > 0) {
|
| 1779 | this.rightClickDelay--;
|
| 1780 | }
|
| 1781 |
|
| 1782 | ProfilerFiller profiler = Profiler.get();
|
| 1783 | profiler.push("gameMode");
|
| 1784 | if (!this.pause && this.level != null) {
|
| 1785 | this.gameMode.tick();
|
| 1786 | }
|
| 1787 |
|
| 1788 | profiler.pop();
|
| 1789 | this.pick(1.0F);
|
| 1790 | this.tutorial.onLookAt(this.level, this.hitResult);
|
| 1791 | profiler.push("gui");
|
| 1792 | this.gui.tick();
|
| 1793 | if (this.gui.screen() != null) {
|
| 1794 | this.missTime = 10000;
|
| 1795 | }
|
| 1796 |
|
| 1797 | if (this.gui.overlay() == null && this.gui.screen() == null) {
|
| 1798 | profiler.popPush("Keybindings");
|
| 1799 | this.handleKeybinds();
|
| 1800 | if (this.missTime > 0) {
|
| 1801 | this.missTime--;
|
| 1802 | }
|
| 1803 | }
|
| 1804 |
|
| 1805 | if (this.level != null) {
|
| 1806 | if (!this.pause) {
|
| 1807 | profiler.popPush("gameRenderer");
|
| 1808 | this.gameRenderer.tick();
|
| 1809 | profiler.popPush("entities");
|
| 1810 | this.level.tickEntities();
|
| 1811 | profiler.popPush("blockEntities");
|
| 1812 | this.level.tickBlockEntities();
|
| 1813 | if (this.player != null && !this.player.isRemoved()) {
|
| 1814 | profiler.popPush("playerSync");
|
| 1815 | this.player.sendChanges();
|
| 1816 | }
|
| 1817 | }
|
| 1818 | } else if (this.gameRenderer.spectatedEntityPostEffect() != null) {
|
| 1819 | this.gameRenderer.clearSpectatedEntityPostEffect();
|
| 1820 | }
|
| 1821 |
|
| 1822 | this.musicManager.tick();
|
| 1823 | this.soundManager.tick(this.pause);
|
| 1824 | if (this.level != null) {
|
| 1825 | if (!this.pause) {
|
| 1826 | profiler.popPush("level");
|
| 1827 | if (!this.options.joinedFirstServer && this.isMultiplayerServer()) {
|
| 1828 | this.gui.addSocialInteractionsToast();
|
| 1829 | this.options.joinedFirstServer = true;
|
| 1830 | this.options.save();
|
| 1831 | }
|
| 1832 |
|
| 1833 | this.tutorial.tick();
|
| 1834 |
|
| 1835 | try {
|
| 1836 | this.level.tick(() -> true);
|
| 1837 | } catch (Throwable t) {
|
| 1838 | CrashReport report = CrashReport.forThrowable(t, "Exception in world tick");
|
| 1839 | if (this.level == null) {
|
| 1840 | CrashReportCategory levelCategory = report.addCategory("Affected level");
|
| 1841 | levelCategory.setDetail("Problem", "Level is null!");
|
| 1842 | } else {
|
| 1843 | this.level.fillReportDetails(report);
|
| 1844 | }
|
| 1845 |
|
| 1846 | throw new ReportedException(report);
|
| 1847 | }
|
| 1848 | }
|
| 1849 |
|
| 1850 | profiler.popPush("animateTick");
|
| 1851 | if (!this.pause && this.isLevelRunningNormally()) {
|
| 1852 | this.level.animateTick(this.player.getBlockX(), this.player.getBlockY(), this.player.getBlockZ());
|
| 1853 | }
|
| 1854 |
|
| 1855 | profiler.popPush("particles");
|
| 1856 | if (!this.pause && this.isLevelRunningNormally()) {
|
| 1857 | this.particleEngine.tick();
|
| 1858 | }
|
| 1859 |
|
| 1860 | ClientPacketListener connection = this.getConnection();
|
| 1861 | if (connection != null && !this.pause) {
|
| 1862 | connection.send(ServerboundClientTickEndPacket.INSTANCE);
|
| 1863 | }
|
| 1864 | } else if (this.pendingConnection != null) {
|
| 1865 | profiler.popPush("pendingConnection");
|
| 1866 | this.pendingConnection.tick();
|
| 1867 | }
|
| 1868 |
|
| 1869 | profiler.popPush("keyboard");
|
| 1870 | this.keyboardHandler.tick();
|
| 1871 | profiler.pop();
|
| 1872 | }
|
| 1873 |
|
| 1874 | private boolean isLevelRunningNormally() {
|
| 1875 | return this.level == null || this.level.tickRateManager().runsNormally();
|
| 1876 | }
|
| 1877 |
|
| 1878 | public boolean isMultiplayerServer() {
|
| 1879 | return !this.isLocalServer || this.singleplayerServer != null && this.singleplayerServer.isPublished();
|
| 1880 | }
|
| 1881 |
|
| 1882 | private void handleKeybinds() {
|
| 1883 | while (this.options.keyTogglePerspective.consumeClick()) {
|
| 1884 | CameraType previous = this.options.getCameraType();
|
| 1885 | this.options.setCameraType(this.options.getCameraType().cycle());
|
| 1886 | if (previous.isFirstPerson() != this.options.getCameraType().isFirstPerson()) {
|
| 1887 | this.gameRenderer.checkEntityPostEffect(this.options.getCameraType().isFirstPerson() ? this.getCameraEntity() : null);
|
| 1888 | }
|
| 1889 | }
|
| 1890 |
|
| 1891 | while (this.options.keySmoothCamera.consumeClick()) {
|
| 1892 | this.options.smoothCamera = !this.options.smoothCamera;
|
| 1893 | }
|
| 1894 |
|
| 1895 | this.gui.handleKeybinds();
|
| 1896 |
|
| 1897 | while (this.options.keyToggleSpectatorShaderEffects.consumeClick()) {
|
| 1898 | this.gameRenderer.toggleSpectatorPostEffect();
|
| 1899 | }
|
| 1900 |
|
| 1901 | for (int i = 0; i < 9; i++) {
|
| 1902 | boolean savePressed = this.options.keySaveHotbarActivator.isDown();
|
| 1903 | boolean loadPressed = this.options.keyLoadHotbarActivator.isDown();
|
| 1904 | if (this.options.keyHotbarSlots[i].consumeClick()) {
|
| 1905 | if (this.player.isSpectator()) {
|
| 1906 | this.gui.hud.getSpectatorGui().onHotbarSelected(i);
|
| 1907 | } else if (!this.player.hasInfiniteMaterials() || this.gui.screen() != null || !loadPressed && !savePressed) {
|
| 1908 | this.player.getInventory().setSelectedSlot(i);
|
| 1909 | } else {
|
| 1910 | CreativeModeInventoryScreen.handleHotbarLoadOrSave(this, i, loadPressed, savePressed);
|
| 1911 | }
|
| 1912 | }
|
| 1913 | }
|
| 1914 |
|
| 1915 | while (this.options.keyInventory.consumeClick()) {
|
| 1916 | if (this.gameMode.isServerControlledInventory()) {
|
| 1917 | this.player.sendOpenInventory();
|
| 1918 | } else {
|
| 1919 | this.tutorial.onOpenInventory();
|
| 1920 | this.gui.setScreen(new InventoryScreen(this.player));
|
| 1921 | }
|
| 1922 | }
|
| 1923 |
|
| 1924 | while (this.options.keyQuickActions.consumeClick()) {
|
| 1925 | this.getQuickActionsDialog().ifPresent(dialog -> this.player.connection.showDialog((Holder<Dialog>)dialog, this.gui.screen()));
|
| 1926 | }
|
| 1927 |
|
| 1928 | while (this.options.keySwapOffhand.consumeClick()) {
|
| 1929 | if (!this.player.isSpectator()) {
|
| 1930 | this.getConnection().send(new ServerboundPlayerActionPacket(Action.SWAP_ITEM_WITH_OFFHAND, BlockPos.ZERO, Direction.DOWN));
|
| 1931 | }
|
| 1932 | }
|
| 1933 |
|
| 1934 | while (this.options.keyDrop.consumeClick()) {
|
| 1935 | if (!this.player.isSpectator()) {
|
| 1936 | this.gameMode.dropItem(this.player, this.hasControlDown());
|
| 1937 | }
|
| 1938 | }
|
| 1939 |
|
| 1940 | boolean instantAttack = false;
|
| 1941 | if (this.player.isUsingItem()) {
|
| 1942 | if (!this.options.keyUse.isDown()) {
|
| 1943 | this.gameMode.releaseUsingItem(this.player);
|
| 1944 | }
|
| 1945 |
|
| 1946 | while (this.options.keyAttack.consumeClick()) {
|
| 1947 | }
|
| 1948 |
|
| 1949 | while (this.options.keyUse.consumeClick()) {
|
| 1950 | }
|
| 1951 |
|
| 1952 | while (this.options.keyPickItem.consumeClick()) {
|
| 1953 | }
|
| 1954 | } else {
|
| 1955 | while (this.options.keyAttack.consumeClick()) {
|
| 1956 | instantAttack |= this.startAttack();
|
| 1957 | }
|
| 1958 |
|
| 1959 | while (this.options.keyUse.consumeClick()) {
|
| 1960 | this.startUseItem();
|
| 1961 | }
|
| 1962 |
|
| 1963 | while (this.options.keyPickItem.consumeClick()) {
|
| 1964 | this.pickBlockOrEntity();
|
| 1965 | }
|
| 1966 |
|
| 1967 | if (this.player.isSpectator()) {
|
| 1968 | while (this.options.keySpectatorHotbar.consumeClick()) {
|
| 1969 | this.gui.hud.getSpectatorGui().onHotbarActionKeyPressed();
|
| 1970 | }
|
| 1971 | }
|
| 1972 | }
|
| 1973 |
|
| 1974 | if (this.options.keyUse.isDown() && this.rightClickDelay == 0 && !this.player.isUsingItem()) {
|
| 1975 | this.startUseItem();
|
| 1976 | }
|
| 1977 |
|
| 1978 | this.continueAttack(this.gui.screen() == null && !instantAttack && this.options.keyAttack.isDown() && this.mouseHandler.isMouseGrabbed());
|
| 1979 | }
|
| 1980 |
|
| 1981 | private Optional<Holder<Dialog>> getQuickActionsDialog() {
|
| 1982 | Registry<Dialog> dialogRegistry = this.player.connection.registryAccess().lookupOrThrow(Registries.DIALOG);
|
| 1983 | return dialogRegistry.get(DialogTags.QUICK_ACTIONS).flatMap(quickActions -> {
|
| 1984 | if (quickActions.size() == 0) {
|
| 1985 | return Optional.empty();
|
| 1986 | } else {
|
| 1987 | return quickActions.size() == 1 ? Optional.of(quickActions.get(0)) : dialogRegistry.get(Dialogs.QUICK_ACTIONS);
|
| 1988 | }
|
| 1989 | });
|
| 1990 | }
|
| 1991 |
|
| 1992 | public ClientTelemetryManager getTelemetryManager() {
|
| 1993 | return this.telemetryManager;
|
| 1994 | }
|
| 1995 |
|
| 1996 | public MetricsRecorder getMetricsRecorder() {
|
| 1997 | return this.metricsRecorder;
|
| 1998 | }
|
| 1999 |
|
| 2000 | public double getGpuUtilization() {
|
| 2001 | return this.gpuUtilization;
|
| 2002 | }
|
| 2003 |
|
| 2004 | public ProfileKeyPairManager getProfileKeyPairManager() {
|
| 2005 | return this.profileKeyPairManager;
|
| 2006 | }
|
| 2007 |
|
| 2008 | public WorldOpenFlows createWorldOpenFlows() {
|
| 2009 | return new WorldOpenFlows(this, this.levelSource);
|
| 2010 | }
|
| 2011 |
|
| 2012 | public void doWorldLoad(
|
| 2013 | final LevelStorageAccess levelSourceAccess,
|
| 2014 | final PackRepository packRepository,
|
| 2015 | final WorldStem worldStem,
|
| 2016 | final Optional<GameRules> gameRules,
|
| 2017 | final boolean newWorld
|
| 2018 | ) {
|
| 2019 | this.disconnectWithProgressScreen();
|
| 2020 | Instant worldLoadStart = Instant.now();
|
| 2021 | LevelLoadTracker loadTracker = new LevelLoadTracker(newWorld ? 500L : 0L);
|
| 2022 | LevelLoadingScreen screen = new LevelLoadingScreen(loadTracker, LevelLoadingScreen.Reason.OTHER);
|
| 2023 | this.gui.setScreen(screen);
|
| 2024 | int chunkStatusViewRadius = Math.max(5, 3) + ChunkLevel.RADIUS_AROUND_FULL_CHUNK + 1;
|
| 2025 |
|
| 2026 | try {
|
| 2027 | levelSourceAccess.saveDataTag(worldStem.worldDataAndGenSettings().data());
|
| 2028 | LevelLoadListener loadListener = LevelLoadListener.compose(loadTracker, LoggingLevelLoadListener.forSingleplayer());
|
| 2029 | this.singleplayerServer = MinecraftServer.spin(
|
| 2030 | thread -> new IntegratedServer(thread, this, levelSourceAccess, packRepository, worldStem, gameRules, this.services, loadListener)
|
| 2031 | );
|
| 2032 | loadTracker.setServerChunkStatusView(this.singleplayerServer.createChunkLoadStatusView(chunkStatusViewRadius));
|
| 2033 | this.isLocalServer = true;
|
| 2034 | this.updateReportEnvironment(ReportEnvironment.local());
|
| 2035 | this.quickPlayLog.setWorldData(QuickPlayLog.Type.SINGLEPLAYER, levelSourceAccess.getLevelId(), worldStem.worldDataAndGenSettings().data().getLevelName());
|
| 2036 | } catch (Throwable t) {
|
| 2037 | CrashReport report = CrashReport.forThrowable(t, "Starting integrated server");
|
| 2038 | CrashReportCategory category = report.addCategory("Starting integrated server");
|
| 2039 | category.setDetail("Level ID", levelSourceAccess.getLevelId());
|
| 2040 | category.setDetail("Level Name", () -> worldStem.worldDataAndGenSettings().data().getLevelName());
|
| 2041 | throw new ReportedException(report);
|
| 2042 | }
|
| 2043 |
|
| 2044 | ProfilerFiller profiler = Profiler.get();
|
| 2045 | profiler.push("waitForServer");
|
| 2046 | long tickLengthNs = TimeUnit.SECONDS.toNanos(1L) / 60L;
|
| 2047 |
|
| 2048 | while (!this.singleplayerServer.isReady() || this.gui.overlay() != null) {
|
| 2049 | long finishTime = Util.getNanos() + tickLengthNs;
|
| 2050 | RenderSystem.pumpEvents(this.sdlEventHandler);
|
| 2051 | screen.tick();
|
| 2052 | if (this.gui.overlay() != null) {
|
| 2053 | this.gui.overlay().tick();
|
| 2054 | }
|
| 2055 |
|
| 2056 | this.renderFrame(false);
|
| 2057 | this.runAllTasks();
|
| 2058 | this.managedBlock(() -> Util.getNanos() > finishTime);
|
| 2059 | }
|
| 2060 |
|
| 2061 | profiler.pop();
|
| 2062 | Duration worldLoadDuration = Duration.between(worldLoadStart, Instant.now());
|
| 2063 | SocketAddress socketAddress = this.singleplayerServer.getConnection().startMemoryChannel();
|
| 2064 | Connection connection = Connection.connectToLocalServer(socketAddress);
|
| 2065 | connection.initiateServerboundPlayConnection(
|
| 2066 | socketAddress.toString(), 0, new ClientHandshakePacketListenerImpl(connection, this, null, null, newWorld, worldLoadDuration, var0 -> {}, loadTracker, null)
|
| 2067 | );
|
| 2068 | connection.send(new ServerboundHelloPacket(this.getUser().getName(), this.getUser().getProfileId()));
|
| 2069 | this.pendingConnection = connection;
|
| 2070 | this.getPlayerSocialManager().getPresenceHandler().tryUpdatePresence();
|
| 2071 | }
|
| 2072 |
|
| 2073 | public void setLevel(final ClientLevel level) {
|
| 2074 | this.level = level;
|
| 2075 | this.updateLevelInEngines(level);
|
| 2076 | }
|
| 2077 |
|
| 2078 | public void disconnectFromWorld(final Component message) {
|
| 2079 | boolean localServer = this.isLocalServer();
|
| 2080 | ServerData currentServer = this.getCurrentServer();
|
| 2081 | if (this.level != null) {
|
| 2082 | this.level.disconnect(message);
|
| 2083 | }
|
| 2084 |
|
| 2085 | if (localServer) {
|
| 2086 | this.disconnectWithSavingScreen();
|
| 2087 | } else {
|
| 2088 | this.disconnectWithProgressScreen();
|
| 2089 | }
|
| 2090 |
|
| 2091 | TitleScreen titleScreen = new TitleScreen();
|
| 2092 | if (localServer) {
|
| 2093 | this.gui.setScreen(titleScreen);
|
| 2094 | } else if (currentServer != null && currentServer.isRealm()) {
|
| 2095 | this.gui.setScreen(new RealmsMainScreen(titleScreen));
|
| 2096 | } else {
|
| 2097 | this.gui.setScreen(new JoinMultiplayerScreen(titleScreen));
|
| 2098 | }
|
| 2099 | }
|
| 2100 |
|
| 2101 | public void disconnectWithSavingScreen() {
|
| 2102 | this.disconnect(new GenericMessageScreen(Gui.SAVING_LEVEL), false);
|
| 2103 | }
|
| 2104 |
|
| 2105 | public void disconnectWithProgressScreen() {
|
| 2106 | this.disconnectWithProgressScreen(true);
|
| 2107 | }
|
| 2108 |
|
| 2109 | public void disconnectWithProgressScreen(final boolean stopSound) {
|
| 2110 | this.disconnect(new ProgressScreen(true), false, stopSound);
|
| 2111 | }
|
| 2112 |
|
| 2113 | public void disconnect(final Screen screen, final boolean keepResourcePacks) {
|
| 2114 | this.disconnect(screen, keepResourcePacks, true);
|
| 2115 | }
|
| 2116 |
|
| 2117 | public void disconnect(final Screen screen, final boolean keepResourcePacks, final boolean stopSound) {
|
| 2118 | ClientPacketListener connection = this.getConnection();
|
| 2119 | if (connection != null) {
|
| 2120 | this.dropAllTasks();
|
| 2121 | connection.close();
|
| 2122 | if (!keepResourcePacks) {
|
| 2123 | this.clearDownloadedResourcePacks();
|
| 2124 | }
|
| 2125 | }
|
| 2126 |
|
| 2127 | this.playerSocialManager.stopOnlineMode();
|
| 2128 | if (this.metricsRecorder.isRecording()) {
|
| 2129 | this.debugClientMetricsCancel();
|
| 2130 | }
|
| 2131 |
|
| 2132 | IntegratedServer server = this.singleplayerServer;
|
| 2133 | this.singleplayerServer = null;
|
| 2134 | this.gameRenderer.resetData();
|
| 2135 | this.gameMode = null;
|
| 2136 | this.narrator.clear();
|
| 2137 | this.gui.setClientLevelTeardownInProgress(true);
|
| 2138 |
|
| 2139 | try {
|
| 2140 | if (this.level != null) {
|
| 2141 | this.gui.hud.onDisconnected();
|
| 2142 | }
|
| 2143 |
|
| 2144 | this.level = null;
|
| 2145 | if (server != null) {
|
| 2146 | server.halt(false);
|
| 2147 | this.gui.setScreen(new GenericMessageScreen(Gui.SAVING_LEVEL));
|
| 2148 | ProfilerFiller profiler = Profiler.get();
|
| 2149 | profiler.push("waitForServer");
|
| 2150 |
|
| 2151 | while (!server.isShutdown()) {
|
| 2152 | RenderSystem.pumpEvents(this.sdlEventHandler);
|
| 2153 | this.renderFrame(false);
|
| 2154 | }
|
| 2155 |
|
| 2156 | profiler.pop();
|
| 2157 | }
|
| 2158 |
|
| 2159 | this.setScreenAndShow(screen);
|
| 2160 | this.isLocalServer = false;
|
| 2161 | this.updateLevelInEngines(null, stopSound);
|
| 2162 | this.player = null;
|
| 2163 | } finally {
|
| 2164 | this.gui.setClientLevelTeardownInProgress(false);
|
| 2165 | }
|
| 2166 | }
|
| 2167 |
|
| 2168 | public void clearDownloadedResourcePacks() {
|
| 2169 | this.downloadedPackSource.cleanupAfterDisconnect();
|
| 2170 | this.runAllTasks();
|
| 2171 | }
|
| 2172 |
|
| 2173 | public void clearClientLevel(final Screen screen) {
|
| 2174 | ClientPacketListener connection = this.getConnection();
|
| 2175 | if (connection != null) {
|
| 2176 | connection.clearLevel();
|
| 2177 | }
|
| 2178 |
|
| 2179 | if (this.metricsRecorder.isRecording()) {
|
| 2180 | this.debugClientMetricsCancel();
|
| 2181 | }
|
| 2182 |
|
| 2183 | this.gameRenderer.resetData();
|
| 2184 | this.gameMode = null;
|
| 2185 | this.narrator.clear();
|
| 2186 | this.gui.setClientLevelTeardownInProgress(true);
|
| 2187 |
|
| 2188 | try {
|
| 2189 | this.setScreenAndShow(screen);
|
| 2190 | this.gui.hud.onDisconnected();
|
| 2191 | this.level = null;
|
| 2192 | this.updateLevelInEngines(null);
|
| 2193 | this.player = null;
|
| 2194 | } finally {
|
| 2195 | this.gui.setClientLevelTeardownInProgress(false);
|
| 2196 | }
|
| 2197 | }
|
| 2198 |
|
| 2199 | public void setScreenAndShow(final Screen screen) {
|
| 2200 | try (Zone ignored = Profiler.get().zone("forcedTick")) {
|
| 2201 | this.gui.setScreen(screen);
|
| 2202 | this.renderFrame(false);
|
| 2203 | }
|
| 2204 | }
|
| 2205 |
|
| 2206 | private void updateLevelInEngines(final @Nullable ClientLevel level) {
|
| 2207 | this.updateLevelInEngines(level, true);
|
| 2208 | }
|
| 2209 |
|
| 2210 | private void updateLevelInEngines(final @Nullable ClientLevel level, final boolean stopSound) {
|
| 2211 | if (stopSound) {
|
| 2212 | this.soundManager.stop();
|
| 2213 | }
|
| 2214 |
|
| 2215 | this.setCameraEntity(null);
|
| 2216 | this.pendingConnection = null;
|
| 2217 | this.levelExtractor.setLevel(level);
|
| 2218 | this.particleEngine.setLevel(level);
|
| 2219 | this.gameRenderer.setLevel(level);
|
| 2220 | this.updateTitle();
|
| 2221 | if (this.tracyLevelSection != null) {
|
| 2222 | this.tracyLevelSection.close();
|
| 2223 | this.tracyLevelSection = null;
|
| 2224 | }
|
| 2225 |
|
| 2226 | if (level != null) {
|
| 2227 | String name;
|
| 2228 | if (this.isLocalServer()) {
|
| 2229 | if (this.isMultiplayerServer()) {
|
| 2230 | name = "Multiplayer (host)";
|
| 2231 | } else {
|
| 2232 | name = "Singleplayer";
|
| 2233 | }
|
| 2234 | } else {
|
| 2235 | name = "Multiplayer (client)";
|
| 2236 | }
|
| 2237 |
|
| 2238 | this.tracyLevelSection = TRACY_CURRENT_LEVEL.enterSection(name);
|
| 2239 | }
|
| 2240 | }
|
| 2241 |
|
| 2242 | private UserProperties userProperties() {
|
| 2243 | return this.userPropertiesFuture.join();
|
| 2244 | }
|
| 2245 |
|
| 2246 | public boolean telemetryOptInExtra() {
|
| 2247 | return this.extraTelemetryAvailable() && this.options.telemetryOptInExtra().get();
|
| 2248 | }
|
| 2249 |
|
| 2250 | public boolean extraTelemetryAvailable() {
|
| 2251 | return this.allowsTelemetry() && this.userProperties().flag(UserFlag.OPTIONAL_TELEMETRY_AVAILABLE);
|
| 2252 | }
|
| 2253 |
|
| 2254 | public boolean allowsTelemetry() {
|
| 2255 | return SharedConstants.IS_RUNNING_IN_IDE && !SharedConstants.DEBUG_FORCE_TELEMETRY ? false : this.userProperties().flag(UserFlag.TELEMETRY_ENABLED);
|
| 2256 | }
|
| 2257 |
|
| 2258 | public boolean allowsMultiplayer() {
|
| 2259 | return this.allowsMultiplayer && this.userProperties().flag(UserFlag.SERVERS_ALLOWED) && this.multiplayerBan() == null && !this.isNameBanned();
|
| 2260 | }
|
| 2261 |
|
| 2262 | public boolean allowsRealms() {
|
| 2263 | return this.userProperties().flag(UserFlag.REALMS_ALLOWED) && this.multiplayerBan() == null;
|
| 2264 | }
|
| 2265 |
|
| 2266 | public boolean friendsEnabled() {
|
| 2267 | return this.userProperties().flag(UserFlag.FRIENDS_ENABLED) && !this.offlineDeveloperMode;
|
| 2268 | }
|
| 2269 |
|
| 2270 | public boolean handleGlobalKeyPress(final InputConstants.Key key, final boolean controlDown) {
|
| 2271 | if (this.options.keyDebugModifier.isDown()) {
|
| 2272 | return false;
|
| 2273 | } else if (this.options.keyFullscreen.matches(key)) {
|
| 2274 | this.toggleFullscreen();
|
| 2275 | return true;
|
| 2276 | } else if (this.options.keyScreenshot.matches(key)) {
|
| 2277 | Screenshot.grab(this, controlDown);
|
| 2278 | return true;
|
| 2279 | } else {
|
| 2280 | Screen current = this.gui.screen();
|
| 2281 | if (current != null && current.isInputCaptured()) {
|
| 2282 | return false;
|
| 2283 | } else {
|
| 2284 | return this.options.keyFriends.matches(key) ? this.toggleFriendsScreen() : false;
|
| 2285 | }
|
| 2286 | }
|
| 2287 | }
|
| 2288 |
|
| 2289 | private void toggleFullscreen() {
|
| 2290 | boolean fullscreen = !this.options.fullscreen().get();
|
| 2291 | this.options.fullscreen().set(fullscreen);
|
| 2292 | this.options.save();
|
| 2293 | if (this.gui != null && this.gui.screen() instanceof VideoSettingsScreen videoSettingsScreen) {
|
| 2294 | videoSettingsScreen.updateFullscreenButton(fullscreen);
|
| 2295 | }
|
| 2296 | }
|
| 2297 |
|
| 2298 | private boolean toggleFriendsScreen() {
|
| 2299 | if (!this.isDemo() && !this.isOfflineDeveloperMode()) {
|
| 2300 | Screen current = this.gui.screen();
|
| 2301 | if (current instanceof FriendsOverlayScreen friends) {
|
| 2302 | friends.onClose();
|
| 2303 | return true;
|
| 2304 | } else {
|
| 2305 | if (current != null && !(current instanceof TitleScreen) && !(current instanceof PauseScreen)) {
|
| 2306 | return false;
|
| 2307 | }
|
| 2308 |
|
| 2309 | OnlineOptionsScreen.confirmFriendsListEnabled(this, () -> this.gui.setScreen(new FriendsOverlayScreen(current)), current);
|
| 2310 | return true;
|
| 2311 | }
|
| 2312 | } else {
|
| 2313 | return false;
|
| 2314 | }
|
| 2315 | }
|
| 2316 |
|
| 2317 | public boolean allowFriendRequests() {
|
| 2318 | return this.userProperties().flag(UserFlag.ACCEPT_FRIEND_INVITES);
|
| 2319 | }
|
| 2320 |
|
| 2321 | public boolean allowChatOnlyWithFriend() {
|
| 2322 | return SharedConstants.DEBUG_CHAT_FRIENDS_ONLY || this.userProperties().flag(UserFlag.CHAT_FRIENDS_ONLY);
|
| 2323 | }
|
| 2324 |
|
| 2325 | public @Nullable BanDetails multiplayerBan() {
|
| 2326 | return this.userProperties().bannedScopes().get("MULTIPLAYER");
|
| 2327 | }
|
| 2328 |
|
| 2329 | public boolean isNameBanned() {
|
| 2330 | ProfileResult result = this.profileFuture.getNow(null);
|
| 2331 | return result != null && result.actions().contains(ProfileActionType.FORCED_NAME_CHANGE);
|
| 2332 | }
|
| 2333 |
|
| 2334 | public boolean isBlocked(final UUID uuid) {
|
| 2335 | return !this.isLocalOrUnknownPlayer(uuid) && this.playerSocialManager.shouldHideMessageFrom(uuid);
|
| 2336 | }
|
| 2337 |
|
| 2338 | public boolean isFriendOnlyRestricted(final UUID uuid) {
|
| 2339 | if (!this.allowChatOnlyWithFriend()) {
|
| 2340 | return false;
|
| 2341 | }
|
| 2342 |
|
| 2343 | ClientPacketListener conn = this.getConnection();
|
| 2344 | return conn != null && conn.getLocalGameProfile().id().equals(uuid)
|
| 2345 | ? false
|
| 2346 | : !this.getPlayerSocialManager().isFriendListEnabled() || !this.getPlayerSocialManager().isFriend(uuid);
|
| 2347 | }
|
| 2348 |
|
| 2349 | private boolean isLocalOrUnknownPlayer(final UUID uuid) {
|
| 2350 | return uuid.equals(Util.NIL_UUID) ? true : this.player != null && uuid.equals(this.player.getUUID());
|
| 2351 | }
|
| 2352 |
|
| 2353 | public ChatAbilities computeChatAbilities() {
|
| 2354 | ChatAbilities.Builder builder = new ChatAbilities.Builder();
|
| 2355 | ChatVisiblity visiblityOption = this.options.chatVisibility().get();
|
| 2356 | if (visiblityOption == ChatVisiblity.HIDDEN) {
|
| 2357 | builder.addRestriction(ChatRestriction.CHAT_AND_COMMANDS_DISABLED_BY_OPTIONS);
|
| 2358 | } else if (visiblityOption == ChatVisiblity.SYSTEM) {
|
| 2359 | builder.addRestriction(ChatRestriction.CHAT_DISABLED_BY_OPTIONS);
|
| 2360 | }
|
| 2361 |
|
| 2362 | if (this.isMultiplayerServer()) {
|
| 2363 | if (!this.allowsChat) {
|
| 2364 | builder.addRestriction(ChatRestriction.DISABLED_BY_LAUNCHER);
|
| 2365 | }
|
| 2366 |
|
| 2367 | if (SharedConstants.DEBUG_CHAT_DISABLED || !this.userProperties().flag(UserFlag.CHAT_ALLOWED)) {
|
| 2368 | builder.addRestriction(ChatRestriction.DISABLED_BY_PROFILE);
|
| 2369 | }
|
| 2370 | }
|
| 2371 |
|
| 2372 | return builder.build();
|
| 2373 | }
|
| 2374 |
|
| 2375 | public final boolean isDemo() {
|
| 2376 | return this.demo;
|
| 2377 | }
|
| 2378 |
|
| 2379 | public final boolean canSwitchGameMode() {
|
| 2380 | return this.player != null && this.gameMode != null;
|
| 2381 | }
|
| 2382 |
|
| 2383 | public @Nullable ClientPacketListener getConnection() {
|
| 2384 | return this.player == null ? null : this.player.connection;
|
| 2385 | }
|
| 2386 |
|
| 2387 | private void pickBlockOrEntity() {
|
| 2388 | if (this.hitResult != null && this.hitResult.getType() != Type.MISS) {
|
| 2389 | boolean includeData = this.hasControlDown();
|
| 2390 | switch (this.hitResult) {
|
| 2391 | case BlockHitResult blockHitResult:
|
| 2392 | this.gameMode.handlePickItemFromBlock(blockHitResult.getBlockPos(), includeData);
|
| 2393 | break;
|
| 2394 | case EntityHitResult entityHitResult:
|
| 2395 | this.gameMode.handlePickItemFromEntity(entityHitResult.getEntity(), includeData);
|
| 2396 | break;
|
| 2397 | default:
|
| 2398 | }
|
| 2399 | }
|
| 2400 | }
|
| 2401 |
|
| 2402 | public CrashReport fillReport(final CrashReport report) {
|
| 2403 | SystemReport systemReport = report.getSystemReport();
|
| 2404 |
|
| 2405 | try {
|
| 2406 | fillSystemReport(systemReport, this, this.languageManager, this.launchedVersion, this.options);
|
| 2407 | this.fillUptime(report.addCategory("Uptime"));
|
| 2408 | report.addCategory("Window").setDetail("Error section", this.window::getErrorSection);
|
| 2409 | if (this.level != null) {
|
| 2410 | this.level.fillReportDetails(report);
|
| 2411 | }
|
| 2412 |
|
| 2413 | if (this.singleplayerServer != null) {
|
| 2414 | this.singleplayerServer.fillSystemReport(systemReport);
|
| 2415 | }
|
| 2416 |
|
| 2417 | this.reloadStateTracker.fillCrashReport(report);
|
| 2418 | } catch (Throwable t) {
|
| 2419 | LOGGER.error("Failed to collect details", t);
|
| 2420 | }
|
| 2421 |
|
| 2422 | return report;
|
| 2423 | }
|
| 2424 |
|
| 2425 | public static void fillReport(
|
| 2426 | final @Nullable Minecraft minecraft,
|
| 2427 | final @Nullable LanguageManager languageManager,
|
| 2428 | final @Nullable String launchedVersion,
|
| 2429 | final @Nullable Options options,
|
| 2430 | final CrashReport report
|
| 2431 | ) {
|
| 2432 | SystemReport system = report.getSystemReport();
|
| 2433 | fillSystemReport(system, minecraft, languageManager, launchedVersion, options);
|
| 2434 | }
|
| 2435 |
|
| 2436 | private static String formatSeconds(final double timeInSeconds) {
|
| 2437 | return String.format(Locale.ROOT, "%.3fs", timeInSeconds);
|
| 2438 | }
|
| 2439 |
|
| 2440 | private void fillUptime(final CrashReportCategory category) {
|
| 2441 | category.setDetail("JVM uptime", () -> formatSeconds(ManagementFactory.getRuntimeMXBean().getUptime() / 1000.0));
|
| 2442 | category.setDetail("Wall uptime", () -> formatSeconds((System.currentTimeMillis() - this.clientStartTimeMs) / 1000.0));
|
| 2443 | category.setDetail("High-res time", () -> formatSeconds(Util.getMillis() / 1000.0));
|
| 2444 | category.setDetail("Client ticks", () -> String.format(Locale.ROOT, "%d ticks / %.3fs", this.clientTickCount, this.clientTickCount / 20.0));
|
| 2445 | }
|
| 2446 |
|
| 2447 | private static SystemReport fillSystemReport(
|
| 2448 | final SystemReport systemReport,
|
| 2449 | final @Nullable Minecraft minecraft,
|
| 2450 | final @Nullable LanguageManager languageManager,
|
| 2451 | final @Nullable String launchedVersion,
|
| 2452 | final @Nullable Options options
|
| 2453 | ) {
|
| 2454 | systemReport.setDetail("Launched Version", () -> launchedVersion);
|
| 2455 | String launcherBrand = getLauncherBrand();
|
| 2456 | if (launcherBrand != null) {
|
| 2457 | systemReport.setDetail("Launcher name", launcherBrand);
|
| 2458 | }
|
| 2459 |
|
| 2460 | systemReport.setDetail("Backend library", RenderSystem::getBackendDescription);
|
| 2461 | systemReport.setDetail("Window size", () -> minecraft != null ? minecraft.window.getWidth() + "x" + minecraft.window.getHeight() : "<not initialized>");
|
| 2462 | systemReport.setDetail("Surface Info", () -> {
|
| 2463 | if (minecraft != null && minecraft.windowSurface != null) {
|
| 2464 | StringBuilder builder = new StringBuilder();
|
| 2465 | if (minecraft.windowSurface.isAcquired()) {
|
| 2466 | builder.append("acquired, ");
|
| 2467 | }
|
| 2468 |
|
| 2469 | if (minecraft.windowSurface.isSuboptimal()) {
|
| 2470 | builder.append("suboptimal, ");
|
| 2471 | }
|
| 2472 |
|
| 2473 | if (minecraft.windowSurface.currentConfiguration().isEmpty()) {
|
| 2474 | builder.append("unconfigured");
|
| 2475 | } else {
|
| 2476 | GpuSurface.Configuration config = minecraft.windowSurface.currentConfiguration().get();
|
| 2477 | builder.append(config.presentMode()).append(", ");
|
| 2478 | builder.append(config.width()).append(" x ").append(config.height());
|
| 2479 | }
|
| 2480 |
|
| 2481 | return builder.toString();
|
| 2482 | } else {
|
| 2483 | return "<no surface>";
|
| 2484 | }
|
| 2485 | });
|
| 2486 | systemReport.setDetail("SDL Platform", Window::getPlatform);
|
| 2487 | GpuDevice device = RenderSystem.tryGetDevice();
|
| 2488 | DeviceInfo deviceInfo = device == null ? null : device.getDeviceInfo();
|
| 2489 | if (deviceInfo != null) {
|
| 2490 | systemReport.setDetail("Graphics Device", deviceInfo.name());
|
| 2491 | systemReport.setDetail("Graphics Backend", deviceInfo.backendName());
|
| 2492 | systemReport.setDetail("Graphics Vendor", deviceInfo.vendorName());
|
| 2493 | systemReport.setDetail("Graphics Drivers", deviceInfo.driverInfo());
|
| 2494 | systemReport.setDetail("Graphics Device Extensions", String.join(", ", deviceInfo.underlyingExtensions()));
|
| 2495 | systemReport.setDetail("Graphics Device Type", deviceInfo.type().toString());
|
| 2496 | systemReport.setDetail("Graphics Device Features", deviceInfo.features().toString());
|
| 2497 | } else {
|
| 2498 | systemReport.setDetail("Graphics Device", "<none>");
|
| 2499 | }
|
| 2500 |
|
| 2501 | if (minecraft != null && minecraft.backendCreationException != null) {
|
| 2502 | BackendCreationException exception = minecraft.backendCreationException;
|
| 2503 | systemReport.setDetail("Backend failure message", exception.getMessage());
|
| 2504 | systemReport.setDetail("Backend failure reason", exception.getReason().displayName());
|
| 2505 | systemReport.setDetail("Backend failure missing capabilities", String.join(", ", exception.getMissingCapabilities()));
|
| 2506 | }
|
| 2507 |
|
| 2508 | systemReport.setDetail("GL debug messages", () -> {
|
| 2509 | if (device == null) {
|
| 2510 | return "<no renderer available>";
|
| 2511 | } else {
|
| 2512 | return device.isDebuggingEnabled() ? String.join("\n", device.getLastDebugMessages()) : "<debugging unavailable>";
|
| 2513 | }
|
| 2514 | });
|
| 2515 | systemReport.setDetail("Is Modded", () -> checkModStatus().fullDescription());
|
| 2516 | systemReport.setDetail("Universe", () -> minecraft != null ? Long.toHexString(minecraft.canary) : "404");
|
| 2517 | systemReport.setDetail("Type", "Client");
|
| 2518 | if (options != null) {
|
| 2519 | if (minecraft != null) {
|
| 2520 | String gpuWarnings = minecraft.getGpuWarnlistManager().getAllWarnings();
|
| 2521 | if (gpuWarnings != null) {
|
| 2522 | systemReport.setDetail("GPU Warnings", gpuWarnings);
|
| 2523 | }
|
| 2524 | }
|
| 2525 |
|
| 2526 | systemReport.setDetail("Transparency", options.improvedTransparency().get() ? "shader" : "regular");
|
| 2527 | systemReport.setDetail("Render Distance", options.getEffectiveRenderDistance() + "/" + options.renderDistance().get() + " chunks");
|
| 2528 | systemReport.setDetail("Narrator config", options.narrator().get().toString());
|
| 2529 | }
|
| 2530 |
|
| 2531 | if (minecraft != null) {
|
| 2532 | systemReport.setDetail("Narrator status", () -> minecraft.narrator.isActive());
|
| 2533 | systemReport.setDetail("Resource Packs", () -> PackRepository.displayPackList(minecraft.getResourcePackRepository().getSelectedPacks()));
|
| 2534 | systemReport.setDetail("Sound Cache", () -> {
|
| 2535 | Counter counter = new Counter();
|
| 2536 | minecraft.getSoundManager().getSoundCacheDebugStats(counter);
|
| 2537 | return String.format(Locale.ROOT, "%d bytes in %d buffers", counter.totalSize(), counter.totalCount());
|
| 2538 | });
|
| 2539 | }
|
| 2540 |
|
| 2541 | if (languageManager != null) {
|
| 2542 | systemReport.setDetail("Current Language", () -> languageManager.getSelected());
|
| 2543 | }
|
| 2544 |
|
| 2545 | systemReport.setDetail("Locale", String.valueOf(Locale.getDefault()));
|
| 2546 | systemReport.setDetail("System encoding", () -> System.getProperty("sun.jnu.encoding", "<not set>"));
|
| 2547 | systemReport.setDetail("File encoding", () -> System.getProperty("file.encoding", "<not set>"));
|
| 2548 | systemReport.setDetail("CPU", DebugEntrySystemSpecs::getCpuInfo);
|
| 2549 | return systemReport;
|
| 2550 | }
|
| 2551 |
|
| 2552 | public static Minecraft getInstance() {
|
| 2553 | return instance;
|
| 2554 | }
|
| 2555 |
|
| 2556 | public CompletableFuture<Void> delayTextureReload() {
|
| 2557 | return this.<CompletableFuture<Void>>submit(this::reloadResourcePacks).thenCompose(result -> (CompletionStage<Void>)result);
|
| 2558 | }
|
| 2559 |
|
| 2560 | public void updateReportEnvironment(final ReportEnvironment environment) {
|
| 2561 | if (!this.reportingContext.matches(environment)) {
|
| 2562 | this.reportingContext = ReportingContext.create(environment, this.userApiService);
|
| 2563 | }
|
| 2564 | }
|
| 2565 |
|
| 2566 | public @Nullable ServerData getCurrentServer() {
|
| 2567 | return Optionull.map(this.getConnection(), ClientPacketListener::getServerData);
|
| 2568 | }
|
| 2569 |
|
| 2570 | public boolean isLocalServer() {
|
| 2571 | return this.isLocalServer;
|
| 2572 | }
|
| 2573 |
|
| 2574 | public boolean hasSingleplayerServer() {
|
| 2575 | return this.isLocalServer && this.singleplayerServer != null;
|
| 2576 | }
|
| 2577 |
|
| 2578 | public @Nullable IntegratedServer getSingleplayerServer() {
|
| 2579 | return this.singleplayerServer;
|
| 2580 | }
|
| 2581 |
|
| 2582 | public boolean isLocalPlayer(final UUID profileId) {
|
| 2583 | return profileId.equals(this.getUser().getProfileId());
|
| 2584 | }
|
| 2585 |
|
| 2586 | public User getUser() {
|
| 2587 | return this.user;
|
| 2588 | }
|
| 2589 |
|
| 2590 | public @Nullable ProfileResult getProfileResult() {
|
| 2591 | return this.profileFuture.join();
|
| 2592 | }
|
| 2593 |
|
| 2594 | public GameProfile getGameProfile() {
|
| 2595 | ProfileResult profileResult = this.profileFuture.join();
|
| 2596 | return profileResult != null ? profileResult.profile() : new GameProfile(this.user.getProfileId(), this.user.getName());
|
| 2597 | }
|
| 2598 |
|
| 2599 | public Proxy getProxy() {
|
| 2600 | return this.proxy;
|
| 2601 | }
|
| 2602 |
|
| 2603 | public TextureManager getTextureManager() {
|
| 2604 | return this.textureManager;
|
| 2605 | }
|
| 2606 |
|
| 2607 | public ShaderManager getShaderManager() {
|
| 2608 | return this.shaderManager;
|
| 2609 | }
|
| 2610 |
|
| 2611 | public ResourceManager getResourceManager() {
|
| 2612 | return this.resourceManager;
|
| 2613 | }
|
| 2614 |
|
| 2615 | public PackRepository getResourcePackRepository() {
|
| 2616 | return this.resourcePackRepository;
|
| 2617 | }
|
| 2618 |
|
| 2619 | public VanillaPackResources getVanillaPackResources() {
|
| 2620 | return this.vanillaPackResources;
|
| 2621 | }
|
| 2622 |
|
| 2623 | public DownloadedPackSource getDownloadedPackSource() {
|
| 2624 | return this.downloadedPackSource;
|
| 2625 | }
|
| 2626 |
|
| 2627 | public Path getResourcePackDirectory() {
|
| 2628 | return this.resourcePackDirectory;
|
| 2629 | }
|
| 2630 |
|
| 2631 | public LanguageManager getLanguageManager() {
|
| 2632 | return this.languageManager;
|
| 2633 | }
|
| 2634 |
|
| 2635 | public boolean isPaused() {
|
| 2636 | return this.pause;
|
| 2637 | }
|
| 2638 |
|
| 2639 | public GpuWarnlistManager getGpuWarnlistManager() {
|
| 2640 | return this.gpuWarnlistManager;
|
| 2641 | }
|
| 2642 |
|
| 2643 | public SoundManager getSoundManager() {
|
| 2644 | return this.soundManager;
|
| 2645 | }
|
| 2646 |
|
| 2647 | public @Nullable Music getSituationalMusic() {
|
| 2648 | Music screenMusic = Optionull.map(this.gui.screen(), Screen::getBackgroundMusic);
|
| 2649 | if (screenMusic != null) {
|
| 2650 | return screenMusic;
|
| 2651 | }
|
| 2652 |
|
| 2653 | Camera camera = this.gameRenderer.mainCamera();
|
| 2654 | if (this.player != null) {
|
| 2655 | Level playerLevel = this.player.level();
|
| 2656 | if (playerLevel.dimension() == Level.END && this.gui.hud.getBossOverlay().shouldPlayMusic()) {
|
| 2657 | return Musics.END_BOSS;
|
| 2658 | }
|
| 2659 |
|
| 2660 | BackgroundMusic backgroundMusic = camera.attributeProbe().getValue(EnvironmentAttributes.BACKGROUND_MUSIC, 1.0F);
|
| 2661 | boolean isCreative = this.player.getAbilities().instabuild && this.player.getAbilities().mayfly;
|
| 2662 | boolean isUnderwater = this.player.isUnderWater();
|
| 2663 | return backgroundMusic.select(isCreative, isUnderwater).orElse(null);
|
| 2664 | } else {
|
| 2665 | return Musics.MENU;
|
| 2666 | }
|
| 2667 | }
|
| 2668 |
|
| 2669 | public float getMusicVolume() {
|
| 2670 | return this.gui.screen() != null && this.gui.screen().getBackgroundMusic() != null
|
| 2671 | ? 1.0F
|
| 2672 | : this.gameRenderer.mainCamera().attributeProbe().getValue(EnvironmentAttributes.MUSIC_VOLUME, 1.0F);
|
| 2673 | }
|
| 2674 |
|
| 2675 | public Services services() {
|
| 2676 | return this.services;
|
| 2677 | }
|
| 2678 |
|
| 2679 | public SkinManager getSkinManager() {
|
| 2680 | return this.skinManager;
|
| 2681 | }
|
| 2682 |
|
| 2683 | public @Nullable Entity getCameraEntity() {
|
| 2684 | return this.gameRenderer.mainCamera().entity();
|
| 2685 | }
|
| 2686 |
|
| 2687 | public void setCameraEntity(final @Nullable Entity cameraEntity) {
|
| 2688 | this.gameRenderer.mainCamera().setEntity(cameraEntity);
|
| 2689 | this.gameRenderer.checkEntityPostEffect(cameraEntity);
|
| 2690 | }
|
| 2691 |
|
| 2692 | public boolean shouldEntityAppearGlowing(final Entity entity) {
|
| 2693 | return entity.isCurrentlyGlowing()
|
| 2694 | || this.player != null && this.player.isSpectator() && this.options.keySpectatorOutlines.isDown() && entity.is(EntityTypes.PLAYER);
|
| 2695 | }
|
| 2696 |
|
| 2697 | @Override
|
| 2698 | public Thread getRunningThread() {
|
| 2699 | return this.gameThread;
|
| 2700 | }
|
| 2701 |
|
| 2702 | @Override
|
| 2703 | public Runnable wrapRunnable(final Runnable runnable) {
|
| 2704 | return runnable;
|
| 2705 | }
|
| 2706 |
|
| 2707 | @Override
|
| 2708 | protected boolean shouldRun(final Runnable task) {
|
| 2709 | return true;
|
| 2710 | }
|
| 2711 |
|
| 2712 | public EntityRenderDispatcher getEntityRenderDispatcher() {
|
| 2713 | return this.entityRenderDispatcher;
|
| 2714 | }
|
| 2715 |
|
| 2716 | public BlockEntityRenderDispatcher getBlockEntityRenderDispatcher() {
|
| 2717 | return this.blockEntityRenderDispatcher;
|
| 2718 | }
|
| 2719 |
|
| 2720 | public MapRenderer getMapRenderer() {
|
| 2721 | return this.mapRenderer;
|
| 2722 | }
|
| 2723 |
|
| 2724 | public DataFixer getFixerUpper() {
|
| 2725 | return this.fixerUpper;
|
| 2726 | }
|
| 2727 |
|
| 2728 | public DeltaTracker getDeltaTracker() {
|
| 2729 | return this.deltaTracker;
|
| 2730 | }
|
| 2731 |
|
| 2732 | public BlockColors getBlockColors() {
|
| 2733 | return this.blockColors;
|
| 2734 | }
|
| 2735 |
|
| 2736 | public boolean showOnlyReducedInfo() {
|
| 2737 | return this.player != null && this.player.isReducedDebugInfo() || this.options.reducedDebugInfo().get();
|
| 2738 | }
|
| 2739 |
|
| 2740 | public Tutorial getTutorial() {
|
| 2741 | return this.tutorial;
|
| 2742 | }
|
| 2743 |
|
| 2744 | public boolean isWindowActive() {
|
| 2745 | return this.window.isFocused();
|
| 2746 | }
|
| 2747 |
|
| 2748 | public HotbarManager getHotbarManager() {
|
| 2749 | return this.hotbarManager;
|
| 2750 | }
|
| 2751 |
|
| 2752 | public ModelManager getModelManager() {
|
| 2753 | return this.modelManager;
|
| 2754 | }
|
| 2755 |
|
| 2756 | public AtlasManager getAtlasManager() {
|
| 2757 | return this.atlasManager;
|
| 2758 | }
|
| 2759 |
|
| 2760 | public PalettedTextureManager getPalettedTextureManager() {
|
| 2761 | return this.palettedTextureManager;
|
| 2762 | }
|
| 2763 |
|
| 2764 | public MapTextureManager getMapTextureManager() {
|
| 2765 | return this.mapTextureManager;
|
| 2766 | }
|
| 2767 |
|
| 2768 | public Component grabPanoramixScreenshot(final File folder) {
|
| 2769 | int downscaleFactor = 4;
|
| 2770 | int width = 4096;
|
| 2771 | int height = 4096;
|
| 2772 | int ow = this.window.getWidth();
|
| 2773 | int oh = this.window.getHeight();
|
| 2774 | RenderTarget target = this.gameRenderer.mainRenderTarget();
|
| 2775 | float xRot = this.player.getXRot();
|
| 2776 | float yRot = this.player.getYRot();
|
| 2777 | float xRotO = this.player.xRotO;
|
| 2778 | float yRotO = this.player.yRotO;
|
| 2779 | this.gameRenderer.setRenderBlockOutline(false);
|
| 2780 | Camera camera = this.gameRenderer.mainCamera();
|
| 2781 |
|
| 2782 | try {
|
| 2783 | camera.enablePanoramicMode();
|
| 2784 | this.window.setWidth(4096);
|
| 2785 | this.window.setHeight(4096);
|
| 2786 | target.resize(4096, 4096);
|
| 2787 |
|
| 2788 | for (int i = 0; i < 6; i++) {
|
| 2789 | switch (i) {
|
| 2790 | case 0:
|
| 2791 | this.player.setYRot(yRot);
|
| 2792 | this.player.setXRot(0.0F);
|
| 2793 | break;
|
| 2794 | case 1:
|
| 2795 | this.player.setYRot((yRot + 90.0F) % 360.0F);
|
| 2796 | this.player.setXRot(0.0F);
|
| 2797 | break;
|
| 2798 | case 2:
|
| 2799 | this.player.setYRot((yRot + 180.0F) % 360.0F);
|
| 2800 | this.player.setXRot(0.0F);
|
| 2801 | break;
|
| 2802 | case 3:
|
| 2803 | this.player.setYRot((yRot - 90.0F) % 360.0F);
|
| 2804 | this.player.setXRot(0.0F);
|
| 2805 | break;
|
| 2806 | case 4:
|
| 2807 | this.player.setYRot(yRot);
|
| 2808 | this.player.setXRot(-90.0F);
|
| 2809 | break;
|
| 2810 | case 5:
|
| 2811 | default:
|
| 2812 | this.player.setYRot(yRot);
|
| 2813 | this.player.setXRot(90.0F);
|
| 2814 | }
|
| 2815 |
|
| 2816 | this.player.yRotO = this.player.getYRot();
|
| 2817 | this.player.xRotO = this.player.getXRot();
|
| 2818 | this.gameRenderer.update(DeltaTracker.ONE);
|
| 2819 | this.gameRenderer.extract(DeltaTracker.ONE, true);
|
| 2820 | this.gameRenderer.renderLevel();
|
| 2821 |
|
| 2822 | try {
|
| 2823 | Thread.sleep(10L);
|
| 2824 | } catch (InterruptedException var19) {
|
| 2825 | }
|
| 2826 |
|
| 2827 | Screenshot.grab(folder, "panorama_" + i + ".png", target, 4, var0 -> {});
|
| 2828 | }
|
| 2829 |
|
| 2830 | Component name = Component.literal(folder.getName())
|
| 2831 | .withStyle(ChatFormatting.UNDERLINE)
|
| 2832 | .withStyle(s -> s.withClickEvent(new OpenFile(folder.getAbsoluteFile())));
|
| 2833 | return Component.translatable("screenshot.success", name);
|
| 2834 | } catch (Exception e) {
|
| 2835 | LOGGER.error("Couldn't save image", e);
|
| 2836 | return Component.translatable("screenshot.failure", e.getMessage());
|
| 2837 | } finally {
|
| 2838 | this.player.setXRot(xRot);
|
| 2839 | this.player.setYRot(yRot);
|
| 2840 | this.player.xRotO = xRotO;
|
| 2841 | this.player.yRotO = yRotO;
|
| 2842 | this.gameRenderer.setRenderBlockOutline(true);
|
| 2843 | this.window.setWidth(ow);
|
| 2844 | this.window.setHeight(oh);
|
| 2845 | target.resize(ow, oh);
|
| 2846 | camera.disablePanoramicMode();
|
| 2847 | }
|
| 2848 | }
|
| 2849 |
|
| 2850 | public PlayerSocialManager getPlayerSocialManager() {
|
| 2851 | return this.playerSocialManager;
|
| 2852 | }
|
| 2853 |
|
| 2854 | public Window getWindow() {
|
| 2855 | return this.window;
|
| 2856 | }
|
| 2857 |
|
| 2858 | public TextInputManager textInputManager() {
|
| 2859 | return this.textInputManager;
|
| 2860 | }
|
| 2861 |
|
| 2862 | public void onTextInputFocusChange(final GuiEventListener element, final boolean isFocused) {
|
| 2863 | this.textInputManager.onTextInputFocusChange(element, isFocused);
|
| 2864 | if (this.gui.screen() != null) {
|
| 2865 | if (isFocused) {
|
| 2866 | this.keyboardHandler.resubmitLastPreeditEvent(element);
|
| 2867 | } else {
|
| 2868 | KeyboardHandler.submitPreeditEvent(element, null);
|
| 2869 | }
|
| 2870 | }
|
| 2871 | }
|
| 2872 |
|
| 2873 | public GpuSurface windowSurface() {
|
| 2874 | return this.windowSurface;
|
| 2875 | }
|
| 2876 |
|
| 2877 | public FramerateLimitTracker getFramerateLimitTracker() {
|
| 2878 | return this.framerateLimitTracker;
|
| 2879 | }
|
| 2880 |
|
| 2881 | public DebugScreenOverlay getDebugOverlay() {
|
| 2882 | return this.gui.hud.getDebugOverlay();
|
| 2883 | }
|
| 2884 |
|
| 2885 | public void updateMaxMipLevel(final int mipmapLevels) {
|
| 2886 | this.atlasManager.updateMaxMipLevel(mipmapLevels);
|
| 2887 | }
|
| 2888 |
|
| 2889 | public EntityModelSet getEntityModels() {
|
| 2890 | return this.modelManager.entityModels().get();
|
| 2891 | }
|
| 2892 |
|
| 2893 | public boolean isTextFilteringEnabled() {
|
| 2894 | return this.userProperties().flag(UserFlag.PROFANITY_FILTER_ENABLED);
|
| 2895 | }
|
| 2896 |
|
| 2897 | public void prepareForMultiplayer() {
|
| 2898 | this.playerSocialManager.startOnlineMode();
|
| 2899 | this.getProfileKeyPairManager().prepareKeyPair();
|
| 2900 | }
|
| 2901 |
|
| 2902 | public InputType getLastInputType() {
|
| 2903 | return this.lastInputType;
|
| 2904 | }
|
| 2905 |
|
| 2906 | public void setLastInputType(final InputType lastInputType) {
|
| 2907 | this.lastInputType = lastInputType;
|
| 2908 | }
|
| 2909 |
|
| 2910 | public GameNarrator getNarrator() {
|
| 2911 | return this.narrator;
|
| 2912 | }
|
| 2913 |
|
| 2914 | public ReportingContext getReportingContext() {
|
| 2915 | return this.reportingContext;
|
| 2916 | }
|
| 2917 |
|
| 2918 | public RealmsDataFetcher realmsDataFetcher() {
|
| 2919 | return this.realmsDataFetcher;
|
| 2920 | }
|
| 2921 |
|
| 2922 | public QuickPlayLog quickPlayLog() {
|
| 2923 | return this.quickPlayLog;
|
| 2924 | }
|
| 2925 |
|
| 2926 | public DirectoryValidator directoryValidator() {
|
| 2927 | return this.directoryValidator;
|
| 2928 | }
|
| 2929 |
|
| 2930 | public PlayerSkinRenderCache playerSkinRenderCache() {
|
| 2931 | return this.playerSkinRenderCache;
|
| 2932 | }
|
| 2933 |
|
| 2934 | private float getTickTargetMillis(final float defaultTickTargetMillis) {
|
| 2935 | if (this.level != null) {
|
| 2936 | TickRateManager manager = this.level.tickRateManager();
|
| 2937 | if (manager.runsNormally()) {
|
| 2938 | return Math.max(defaultTickTargetMillis, manager.millisecondsPerTick());
|
| 2939 | }
|
| 2940 | }
|
| 2941 |
|
| 2942 | return defaultTickTargetMillis;
|
| 2943 | }
|
| 2944 |
|
| 2945 | public ItemModelResolver getItemModelResolver() {
|
| 2946 | return this.itemModelResolver;
|
| 2947 | }
|
| 2948 |
|
| 2949 | public boolean canInterruptScreen() {
|
| 2950 | return this.gui.canInterruptScreen();
|
| 2951 | }
|
| 2952 |
|
| 2953 | public void invalidateSurfaceConfiguration() {
|
| 2954 | this.windowSurfaceNeedsReconfiguring = true;
|
| 2955 | }
|
| 2956 |
|
| 2957 | public static @Nullable String getLauncherBrand() {
|
| 2958 | return System.getProperty("minecraft.launcher.brand");
|
| 2959 | }
|
| 2960 |
|
| 2961 | public PacketProcessor packetProcessor() {
|
| 2962 | return this.packetProcessor;
|
| 2963 | }
|
| 2964 |
|
| 2965 | public TemporaryCollection collectPerTickGizmos() {
|
| 2966 | return Gizmos.withCollector(this.perTickGizmos);
|
| 2967 | }
|
| 2968 |
|
| 2969 | public Collection<GizmoInstance> getPerTickGizmos() {
|
| 2970 | return this.drainedLatestTickGizmos;
|
| 2971 | }
|
| 2972 |
|
| 2973 | private void pick(final float partialTicks) {
|
| 2974 | Entity cameraEntity = this.getCameraEntity();
|
| 2975 | if (cameraEntity != null) {
|
| 2976 | if (this.level != null && this.player != null) {
|
| 2977 | Profiler.get().push("pick");
|
| 2978 | this.hitResult = this.player.raycastHitResult(partialTicks, cameraEntity);
|
| 2979 | this.crosshairPickEntity = this.hitResult instanceof EntityHitResult entityHitResult ? entityHitResult.getEntity() : null;
|
| 2980 | Profiler.get().pop();
|
| 2981 | }
|
| 2982 | }
|
| 2983 | }
|
| 2984 |
|
| 2985 | public void showDebugChat(final Component message) {
|
| 2986 | this.gui.hud.getChat().addClientSystemMessage(message);
|
| 2987 | this.getNarrator().saySystemQueued(message);
|
| 2988 | }
|
| 2989 | }
|
| 2990 |
|