diff --git a/build.gradle b/build.gradle index a40aa23b..10f02268 100644 --- a/build.gradle +++ b/build.gradle @@ -74,10 +74,13 @@ dependencies { // mojang's official mappings, or feel free // to add your own mappings here (how about // mojmap layered with parchment, for example?) + mappings loom.officialMojangMappings() + /* mappings loom.layered() { officialMojangMappings() parchment("org.parchmentmc.data:parchment-${minecraft_version}:${parchment_version}@zip") } + */ // uncomment this if you want to use yarn mappings // mappings "net.fabricmc:yarn:${project.yarn_mappings}:v2" @@ -90,12 +93,11 @@ dependencies { // compile against the JEI API but do not include it at runtime modCompileOnly("mezz.jei:jei-${minecraft_version}-forge:${jei_version}") - modCompileOnly("curse.maven:jeresources-240630:3951643") modCompileOnly "me.shedaniel:RoughlyEnoughItems-forge:${rei_version}" modCompileOnly("dev.latvian.mods:kubejs-forge:${kubejs_version}") - modRuntimeOnly("curse.maven:ferritecore-429235:4117906") + modRuntimeOnly("curse.maven:ferritecore-429235:4441949") modCompileOnly("team.chisel.ctm:CTM:${ctm_version}") - modCompileOnly("curse.maven:supermartijncore-454372:4455391") + modCompileOnly("curse.maven:supermartijncore-454372:4484241") } tasks.withType(JavaCompile) { diff --git a/gradle.properties b/gradle.properties index fd60c215..d0012562 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,11 +8,11 @@ org.gradle.jvmargs=-Xmx1G loom.platform=forge mod_id=modernfix -minecraft_version=1.19.2 -forge_version=1.19.2-43.2.0 -parchment_version=2022.11.27 +minecraft_version=1.19.4 +forge_version=1.19.4-45.0.43 +parchment_version=2023.03.12 refined_storage_version=4392788 -jei_version=11.6.0.1011 -rei_version=9.1.591 +jei_version=13.1.0.2 +rei_version=11.0.597 ctm_version=1.19.2-1.1.7+11 kubejs_version=1902.6.0-build.142 diff --git a/src/main/java/org/embeddedt/modernfix/duck/IDynamicModelBakery.java b/src/main/java/org/embeddedt/modernfix/duck/IDynamicModelBakery.java new file mode 100644 index 00000000..53420430 --- /dev/null +++ b/src/main/java/org/embeddedt/modernfix/duck/IDynamicModelBakery.java @@ -0,0 +1,8 @@ +package org.embeddedt.modernfix.duck; + +import net.minecraft.client.resources.model.BakedModel; +import net.minecraft.resources.ResourceLocation; + +public interface IDynamicModelBakery { + BakedModel bakeDefault(ResourceLocation modelLocation); +} diff --git a/src/main/java/org/embeddedt/modernfix/duck/IExtendedModelBakery.java b/src/main/java/org/embeddedt/modernfix/duck/IExtendedModelBakery.java deleted file mode 100644 index 34ce3862..00000000 --- a/src/main/java/org/embeddedt/modernfix/duck/IExtendedModelBakery.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.embeddedt.modernfix.duck; - - -import net.minecraft.client.renderer.texture.AtlasSet; - -public interface IExtendedModelBakery { - AtlasSet getUnfinishedAtlasSet(); -} diff --git a/src/main/java/org/embeddedt/modernfix/dynamicresources/DynamicBakedModelProvider.java b/src/main/java/org/embeddedt/modernfix/dynamicresources/DynamicBakedModelProvider.java index 74fca3d5..9647a984 100644 --- a/src/main/java/org/embeddedt/modernfix/dynamicresources/DynamicBakedModelProvider.java +++ b/src/main/java/org/embeddedt/modernfix/dynamicresources/DynamicBakedModelProvider.java @@ -8,6 +8,7 @@ import net.minecraft.client.resources.model.BlockModelRotation; import net.minecraft.client.resources.model.ModelBakery; import net.minecraft.resources.ResourceLocation; import org.apache.commons.lang3.tuple.Triple; +import org.embeddedt.modernfix.duck.IDynamicModelBakery; import org.jetbrains.annotations.NotNull; import javax.annotation.Nullable; @@ -20,10 +21,10 @@ import java.util.stream.Collectors; public class DynamicBakedModelProvider implements Map { private final ModelBakery bakery; - private final Map, BakedModel> bakedCache; + private final Map bakedCache; private final Map permanentOverrides; - public DynamicBakedModelProvider(ModelBakery bakery, Map, BakedModel> cache) { + public DynamicBakedModelProvider(ModelBakery bakery, Map cache) { this.bakery = bakery; this.bakedCache = cache; this.permanentOverrides = new Object2ObjectOpenHashMap<>(); @@ -54,7 +55,7 @@ public class DynamicBakedModelProvider implements Map keySet() { - return bakedCache.keySet().stream().map(Triple::getLeft).collect(Collectors.toSet()); + return bakedCache.keySet().stream().map(ModelBakery.BakedCacheKey::id).collect(Collectors.toSet()); } @NotNull @@ -100,7 +101,7 @@ public class DynamicBakedModelProvider implements Map> entrySet() { - return bakedCache.entrySet().stream().map(entry -> new AbstractMap.SimpleImmutableEntry<>(entry.getKey().getLeft(), entry.getValue())).collect(Collectors.toSet()); + return bakedCache.entrySet().stream().map(entry -> new AbstractMap.SimpleImmutableEntry<>(entry.getKey().id(), entry.getValue())).collect(Collectors.toSet()); } @Override @@ -110,10 +111,10 @@ public class DynamicBakedModelProvider implements Map { - if(loc.getMiddle() != rotation || loc.getRight() != uvLock || overridenLocations.contains(loc.getLeft())) + if(loc.transformation() != rotation || loc.isUvLocked() != uvLock || overridenLocations.contains(loc.id())) return oldModel; else - return function.apply(loc.getLeft(), oldModel); + return function.apply(loc.id(), oldModel); }); } } diff --git a/src/main/java/org/embeddedt/modernfix/dynamicresources/DynamicModelBakeEvent.java b/src/main/java/org/embeddedt/modernfix/dynamicresources/DynamicModelBakeEvent.java index 96f67954..f1488ac3 100644 --- a/src/main/java/org/embeddedt/modernfix/dynamicresources/DynamicModelBakeEvent.java +++ b/src/main/java/org/embeddedt/modernfix/dynamicresources/DynamicModelBakeEvent.java @@ -1,9 +1,6 @@ package org.embeddedt.modernfix.dynamicresources; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.client.resources.model.ModelBakery; -import net.minecraft.client.resources.model.ModelManager; -import net.minecraft.client.resources.model.UnbakedModel; +import net.minecraft.client.resources.model.*; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.eventbus.api.Event; import net.minecraftforge.fml.event.IModBusEvent; @@ -19,8 +16,8 @@ public class DynamicModelBakeEvent extends Event { private final ResourceLocation location; private BakedModel model; private final UnbakedModel unbakedModel; - private final ModelBakery modelLoader; - public DynamicModelBakeEvent(ResourceLocation location, UnbakedModel unbakedModel, BakedModel model, ModelBakery loader) { + private final ModelBaker modelLoader; + public DynamicModelBakeEvent(ResourceLocation location, UnbakedModel unbakedModel, BakedModel model, ModelBaker loader) { this.location = location; this.model = model; this.unbakedModel = unbakedModel; @@ -39,7 +36,7 @@ public class DynamicModelBakeEvent extends Event { return this.unbakedModel; } - public ModelBakery getModelLoader() { + public ModelBaker getModelLoader() { return this.modelLoader; } diff --git a/src/main/java/org/embeddedt/modernfix/mixin/bugfix/chunk_deadlock/ServerChunkCacheMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/bugfix/chunk_deadlock/ServerChunkCacheMixin.java index 93806ffc..f695b369 100644 --- a/src/main/java/org/embeddedt/modernfix/mixin/bugfix/chunk_deadlock/ServerChunkCacheMixin.java +++ b/src/main/java/org/embeddedt/modernfix/mixin/bugfix/chunk_deadlock/ServerChunkCacheMixin.java @@ -2,7 +2,7 @@ package org.embeddedt.modernfix.mixin.bugfix.chunk_deadlock; import com.mojang.datafixers.util.Either; import net.minecraft.core.Holder; -import net.minecraft.core.Registry; +import net.minecraft.core.registries.Registries; import net.minecraft.server.level.ChunkHolder; import net.minecraft.server.level.ServerChunkCache; import net.minecraft.server.level.ServerLevel; @@ -38,7 +38,7 @@ public abstract class ServerChunkCacheMixin { if(debugDeadServerAccess) { new Exception().printStackTrace(); } - Holder plains = this.level.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY).getHolderOrThrow(Biomes.PLAINS); + Holder plains = this.level.registryAccess().registryOrThrow(Registries.BIOME).getHolderOrThrow(Biomes.PLAINS); cir.setReturnValue(new EmptyLevelChunk(this.level, new ChunkPos(chunkX, chunkZ), plains)); } else if(Thread.currentThread() != this.mainThread) { CompletableFuture> future = CompletableFuture.supplyAsync(() -> this.getChunkFutureMainThread(chunkX, chunkZ, requiredStatus, false), this.mainThreadProcessor).join(); diff --git a/src/main/java/org/embeddedt/modernfix/mixin/core/MinecraftMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/core/MinecraftMixin.java index b5ef2b0e..25781a44 100644 --- a/src/main/java/org/embeddedt/modernfix/mixin/core/MinecraftMixin.java +++ b/src/main/java/org/embeddedt/modernfix/mixin/core/MinecraftMixin.java @@ -15,8 +15,8 @@ import java.util.function.Function; @Mixin(Minecraft.class) public class MinecraftMixin { - @Inject(method = "m_231380_", at = @At("HEAD"), remap = false) - private void setLatch(String string, LevelStorageSource.LevelStorageAccess arg, PackRepository arg2, WorldStem arg3, CallbackInfo ci) { + @Inject(method = "doWorldLoad", at = @At("HEAD"), remap = false) + private void setLatch(String string, LevelStorageSource.LevelStorageAccess arg, PackRepository arg2, WorldStem arg3, boolean bl, CallbackInfo ci) { ModernFix.worldLoadSemaphore = new CountDownLatch(1); } } diff --git a/src/main/java/org/embeddedt/modernfix/mixin/feature/measure_time/MinecraftMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/feature/measure_time/MinecraftMixin.java index 2776d7fb..420f6c16 100644 --- a/src/main/java/org/embeddedt/modernfix/mixin/feature/measure_time/MinecraftMixin.java +++ b/src/main/java/org/embeddedt/modernfix/mixin/feature/measure_time/MinecraftMixin.java @@ -34,7 +34,7 @@ public class MinecraftMixin { ModernFix.LOGGER.warn("Datapack reload took " + timeSpentReloading + " seconds."); } */ - @Inject(method = "m_231380_", at = @At("HEAD"), remap = false) + @Inject(method = "doWorldLoad", at = @At("HEAD"), remap = false) private void recordWorldLoadStart(CallbackInfo ci) { ModernFixClient.worldLoadStartTime = System.nanoTime(); } diff --git a/src/main/java/org/embeddedt/modernfix/mixin/feature/reduce_loading_screen_freezes/ModelBakeryMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/feature/reduce_loading_screen_freezes/ModelBakeryMixin.java deleted file mode 100644 index 8e73592c..00000000 --- a/src/main/java/org/embeddedt/modernfix/mixin/feature/reduce_loading_screen_freezes/ModelBakeryMixin.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.embeddedt.modernfix.mixin.feature.reduce_loading_screen_freezes; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.resources.model.ModelBakery; -import net.minecraft.Util; -import net.minecraftforge.fml.loading.progress.StartupMessageManager; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.function.Consumer; - -@Mixin(ModelBakery.class) -public class ModelBakeryMixin { - @Redirect(method = "uploadTextures", at = @At(value = "INVOKE", target = "Ljava/util/Set;forEach(Ljava/util/function/Consumer;)V", ordinal = 0)) - private void bakeAndTickGUI(Set instance, Consumer consumer) { - StartupMessageManager.mcLoaderConsumer().ifPresent(c -> c.accept("Baking models")); - CompletableFuture modelBakingFuture = CompletableFuture.runAsync(() -> { - instance.forEach(consumer); - }, Util.backgroundExecutor()); - /* allow the GUI to continue running */ - Minecraft.getInstance().managedBlock(modelBakingFuture::isDone); - } -} diff --git a/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_model_materials/VanillaModelMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_model_materials/VanillaModelMixin.java deleted file mode 100644 index 6d9a9a55..00000000 --- a/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_model_materials/VanillaModelMixin.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.embeddedt.modernfix.mixin.perf.cache_model_materials; - -import com.mojang.datafixers.util.Pair; -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.client.resources.model.Material; -import net.minecraft.client.renderer.block.model.MultiVariant; -import net.minecraft.client.renderer.block.model.multipart.MultiPart; -import net.minecraft.resources.ResourceLocation; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.Collection; -import java.util.Collections; -import java.util.Set; -import java.util.function.Function; - -@Mixin(value = {MultiVariant.class, MultiPart.class, BlockModel.class}) -public class VanillaModelMixin { - private Collection materialsCache = null; - - @Inject(method = "getMaterials", at = @At("HEAD"), cancellable = true) - private void useCachedMaterials(Function pModelGetter, Set> pMissingTextureErrors, CallbackInfoReturnable> cir) { - if(materialsCache != null) { - cir.setReturnValue(materialsCache); - } - } - - @Inject(method = "getMaterials", at = @At("RETURN")) - private void storeCachedMaterials(Function pModelGetter, Set> pMissingTextureErrors, CallbackInfoReturnable> cir) { - if(materialsCache == null) - materialsCache = Collections.unmodifiableCollection(cir.getReturnValue()); - } -} diff --git a/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_strongholds/ChunkGeneratorMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_strongholds/ChunkGeneratorMixin.java index d8f9ab86..923e3fe5 100644 --- a/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_strongholds/ChunkGeneratorMixin.java +++ b/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_strongholds/ChunkGeneratorMixin.java @@ -6,6 +6,7 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.chunk.ChunkGeneratorStructureState; import net.minecraft.world.level.levelgen.RandomState; import net.minecraft.world.level.levelgen.structure.StructureSet; import net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement; @@ -23,7 +24,7 @@ import java.lang.ref.WeakReference; import java.util.List; import java.util.concurrent.CompletableFuture; -@Mixin(ChunkGenerator.class) +@Mixin(ChunkGeneratorStructureState.class) public class ChunkGeneratorMixin implements IChunkGenerator { private WeakReference mfix$serverLevel; @@ -33,7 +34,7 @@ public class ChunkGeneratorMixin implements IChunkGenerator { } @Inject(method = "generateRingPositions", at = @At("HEAD"), cancellable = true) - private void useCachedDataIfAvailable(Holder structureSet, RandomState random, ConcentricRingsStructurePlacement placement, CallbackInfoReturnable>> cir) { + private void useCachedDataIfAvailable(Holder structureSet, ConcentricRingsStructurePlacement placement, CallbackInfoReturnable>> cir) { if(placement.count() == 0) return; ServerLevel level = searchLevel(); @@ -55,7 +56,7 @@ public class ChunkGeneratorMixin implements IChunkGenerator { } @Inject(method = "generateRingPositions", at = @At("RETURN"), cancellable = true) - private void saveCachedData(Holder structureSet, RandomState random, ConcentricRingsStructurePlacement placement, CallbackInfoReturnable>> cir) { + private void saveCachedData(Holder structureSet, ConcentricRingsStructurePlacement placement, CallbackInfoReturnable>> cir) { cir.setReturnValue(cir.getReturnValue().thenApplyAsync(list -> { if(list.size() == 0) return list; diff --git a/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_strongholds/ServerLevelMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_strongholds/ServerLevelMixin.java index 3611cb62..3e5baee3 100644 --- a/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_strongholds/ServerLevelMixin.java +++ b/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_strongholds/ServerLevelMixin.java @@ -1,6 +1,7 @@ package org.embeddedt.modernfix.mixin.perf.cache_strongholds; import net.minecraft.core.Holder; +import net.minecraft.core.RegistryAccess; import net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerChunkCache; @@ -10,6 +11,7 @@ import net.minecraft.util.profiling.ProfilerFiller; import net.minecraft.world.level.CustomSpawner; import net.minecraft.world.level.Level; import net.minecraft.world.level.chunk.ChunkGenerator; +import net.minecraft.world.level.chunk.ChunkGeneratorStructureState; import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.dimension.LevelStem; import net.minecraft.world.level.levelgen.RandomState; @@ -34,8 +36,8 @@ import java.util.function.Supplier; @Mixin(ServerLevel.class) public abstract class ServerLevelMixin extends Level implements IServerLevel { - protected ServerLevelMixin(WritableLevelData arg, ResourceKey arg2, Holder arg3, Supplier supplier, boolean bl, boolean bl2, long l, int i) { - super(arg, arg2, arg3, supplier, bl, bl2, l, i); + protected ServerLevelMixin(WritableLevelData arg, ResourceKey arg2, RegistryAccess arg3, Holder arg4, Supplier supplier, boolean bl, boolean bl2, long l, int i) { + super(arg, arg2, arg3, arg4, supplier, bl, bl2, l, i); } @Shadow public abstract DimensionDataStorage getDataStorage(); @@ -46,8 +48,8 @@ public abstract class ServerLevelMixin extends Level implements IServerLevel { /** * Initialize the stronghold cache but don't force any structure generation yet. */ - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/chunk/ChunkGenerator;ensureStructuresGenerated(Lnet/minecraft/world/level/levelgen/RandomState;)V")) - private void hookStrongholdCache(ChunkGenerator generator, RandomState state) { + @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/chunk/ChunkGeneratorStructureState;ensureStructuresGenerated()V")) + private void hookStrongholdCache(ChunkGeneratorStructureState generator) { ((IChunkGenerator)generator).mfix$setAssociatedServerLevel((ServerLevel)(Object)this); } @@ -59,7 +61,7 @@ public abstract class ServerLevelMixin extends Level implements IServerLevel { mfix$strongholdCache = this.getDataStorage().computeIfAbsent(StrongholdLocationCache::load, StrongholdLocationCache::new, StrongholdLocationCache.getFileId(this.dimensionTypeRegistration())); - this.chunkSource.getGenerator().ensureStructuresGenerated(this.chunkSource.randomState()); + this.chunkSource.getGeneratorState().ensureStructuresGenerated(); } @Override diff --git a/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_upgraded_structures/StructureManagerMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_upgraded_structures/StructureManagerMixin.java index 73a2268e..5ff16762 100644 --- a/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_upgraded_structures/StructureManagerMixin.java +++ b/src/main/java/org/embeddedt/modernfix/mixin/perf/cache_upgraded_structures/StructureManagerMixin.java @@ -1,8 +1,10 @@ package org.embeddedt.modernfix.mixin.perf.cache_upgraded_structures; import com.mojang.datafixers.DataFixer; +import net.minecraft.core.HolderGetter; import net.minecraft.resources.ResourceLocation; import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; import org.embeddedt.modernfix.ModernFix; @@ -23,6 +25,8 @@ public class StructureManagerMixin { @Shadow private ResourceManager resourceManager; + @Shadow @Final private HolderGetter blockLookup; + /** * @author embeddedt * @reason use our own manager to avoid needless DFU updates @@ -31,7 +35,7 @@ public class StructureManagerMixin { private Optional loadFromResource(ResourceLocation id) { ResourceLocation arg = new ResourceLocation(id.getNamespace(), "structures/" + id.getPath() + ".nbt"); try { - return Optional.of(CachingStructureManager.readStructure(id, this.fixerUpper, this.resourceManager.open(arg))); + return Optional.of(CachingStructureManager.readStructure(id, this.fixerUpper, this.resourceManager.open(arg), this.blockLookup)); } catch(FileNotFoundException e) { return Optional.empty(); } catch(IOException e) { diff --git a/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/BlockModelShaperMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/BlockModelShaperMixin.java index 91d45970..e72bf739 100644 --- a/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/BlockModelShaperMixin.java +++ b/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/BlockModelShaperMixin.java @@ -30,14 +30,6 @@ import java.util.concurrent.ConcurrentHashMap; public class BlockModelShaperMixin { @Shadow @Final private ModelManager modelManager; - /** - * @author embeddedt - * @reason no need to rebuild model cache, and location cache is done elsewhere - */ - @Overwrite - public void rebuildCache() { - } - @Overwrite public BakedModel getBlockModel(BlockState state) { BakedModel model = modelManager.getModel(ModelLocationCache.get(state)); diff --git a/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/ModelBakeryMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/ModelBakeryMixin.java index 7af54884..fefd9717 100644 --- a/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/ModelBakeryMixin.java +++ b/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/ModelBakeryMixin.java @@ -15,7 +15,6 @@ import net.minecraft.Util; import net.minecraft.client.color.block.BlockColors; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.client.renderer.block.model.ItemModelGenerator; -import net.minecraft.client.renderer.texture.AtlasSet; import net.minecraft.client.renderer.texture.TextureAtlas; import net.minecraft.client.renderer.texture.TextureAtlasSprite; import net.minecraft.client.renderer.texture.TextureManager; @@ -37,10 +36,12 @@ import net.minecraftforge.fml.ModLoader; import net.minecraftforge.registries.ForgeRegistries; import org.apache.commons.lang3.tuple.Triple; import org.embeddedt.modernfix.ModernFix; +import org.embeddedt.modernfix.duck.IDynamicModelBakery; import org.embeddedt.modernfix.dynamicresources.DynamicBakedModelProvider; import org.embeddedt.modernfix.dynamicresources.DynamicModelBakeEvent; import org.embeddedt.modernfix.dynamicresources.ModelLocationCache; import org.embeddedt.modernfix.dynamicresources.ResourcePackHandler; +import org.embeddedt.modernfix.mixin.perf.dynamic_resources.supermartijncore.ModelBakerImplMixin; import org.slf4j.Logger; import org.spongepowered.asm.mixin.*; import org.spongepowered.asm.mixin.injection.At; @@ -58,13 +59,14 @@ import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; +import java.util.function.BiFunction; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; /* high priority so that our injectors are added before other mods' */ @Mixin(value = ModelBakery.class, priority = 600) -public abstract class ModelBakeryMixin { +public abstract class ModelBakeryMixin implements IDynamicModelBakery { private static final boolean debugDynamicModelLoading = Boolean.getBoolean("modernfix.debugDynamicModelLoading"); @@ -75,7 +77,6 @@ public abstract class ModelBakeryMixin { @Shadow protected abstract BlockModel loadBlockModel(ResourceLocation location) throws IOException; @Shadow @Final protected static Set UNREFERENCED_TEXTURES; - @Shadow private Map> atlasPreparations; @Shadow @Final protected ResourceManager resourceManager; @Shadow @Nullable private AtlasSet atlasSet; @Shadow @Final private Set loadingStack; @@ -93,7 +94,7 @@ public abstract class ModelBakeryMixin { @Shadow @Final @Mutable private Map bakedTopLevelModels; - @Shadow @Final @Mutable private Map, BakedModel> bakedCache; + @Shadow @Final @Mutable private Map bakedCache; @Shadow @Final public static BlockModel GENERATION_MARKER; @@ -103,7 +104,7 @@ public abstract class ModelBakeryMixin { @Shadow public abstract UnbakedModel getModel(ResourceLocation modelLocation); - private Cache, BakedModel> loadedBakedModels; + private Cache loadedBakedModels; private Cache loadedModels; private HashMap smallLoadingCache = new HashMap<>(); @@ -163,170 +164,30 @@ public abstract class ModelBakeryMixin { /** * @author embeddedt - * @reason don't actually load the model. instead, keep track of if we need to load a blockstate or a model, - * and save the info into the two lists + * @reason don't actually load the model. */ @Inject(method = "loadTopLevel", at = @At("HEAD"), cancellable = true) private void addTopLevelFile(ModelResourceLocation location, CallbackInfo ci) { ci.cancel(); - if(Objects.equals(location.getVariant(), "inventory")) { - modelFiles.add(new ResourceLocation(location.getNamespace(), "item/" + location.getPath())); - } else { - blockStateFiles.add(new ResourceLocation(location.getNamespace(), location.getPath())); - } - } - - @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraftforge/client/ForgeHooksClient;gatherFluidTextures(Ljava/util/Set;)V", remap = false), remap = false) - private void gatherModelTextures(Set materialSet) { - ForgeHooksClient.gatherFluidTextures(materialSet); - gatherModelMaterials(materialSet); } @Redirect(method = "", at = @At(value = "INVOKE", target = "Ljava/util/Map;forEach(Ljava/util/function/BiConsumer;)V", ordinal = 0)) private void fetchStaticDefinitions(Map> map, BiConsumer> func) { - map.forEach((loc, def) -> blockStateFiles.add(loc)); + /* no-op */ } @Redirect(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/StateDefinition;getPossibleStates()Lcom/google/common/collect/ImmutableList;", ordinal = 0)) private ImmutableList fetchBlocks(StateDefinition def) { - blockStateFiles.add(ForgeRegistries.BLOCKS.getKey(def.any().getBlock())); + /* no-op */ return ImmutableList.of(); } - /** - * Load all blockstate JSONs and model files, collect textures. - */ - private void gatherModelMaterials(Set materialSet) { - Stopwatch stopwatch = Stopwatch.createStarted(); - List>> blockStateData = new ArrayList<>(); - for(ResourceLocation blockstate : blockStateFiles) { - blockStateData.add(CompletableFuture.supplyAsync(() -> { - ResourceLocation fileLocation = new ResourceLocation(blockstate.getNamespace(), "blockstates/" + blockstate.getPath() + ".json"); - Optional resource = this.resourceManager.getResource(fileLocation); - if(resource.isPresent()) { - try(InputStream stream = resource.get().open()) { - JsonParser parser = new JsonParser(); - return Pair.of(blockstate, parser.parse(new InputStreamReader(stream, StandardCharsets.UTF_8))); - } catch(IOException | JsonParseException e) { - ModernFix.LOGGER.error("Error reading blockstate {}: {}", blockstate, e); - } - } - return Pair.of(blockstate, null); - }, Util.backgroundExecutor())); - } - blockStateFiles = null; - CompletableFuture.allOf(blockStateData.toArray(new CompletableFuture[0])).join(); - for(CompletableFuture> result : blockStateData) { - Pair pair = result.join(); - if(pair.getSecond() != null) { - try { - JsonObject obj = pair.getSecond().getAsJsonObject(); - if(obj.has("variants")) { - JsonObject eachVariant = obj.getAsJsonObject("variants"); - for(Map.Entry entry : eachVariant.entrySet()) { - JsonElement variantData = entry.getValue(); - List variantModels; - if(variantData.isJsonArray()) { - variantModels = new ArrayList<>(); - for(JsonElement model : variantData.getAsJsonArray()) { - variantModels.add(model.getAsJsonObject()); - } - } else - variantModels = Collections.singletonList(variantData.getAsJsonObject()); - for(JsonObject variant : variantModels) { - modelFiles.add(new ResourceLocation(variant.get("model").getAsString())); - } - } + private BiFunction textureGetter; - } else { - JsonArray multipartData = obj.get("multipart").getAsJsonArray(); - for(JsonElement element : multipartData) { - JsonObject self = element.getAsJsonObject(); - JsonElement apply = self.get("apply"); - List applyObjects; - if(apply.isJsonArray()) { - applyObjects = new ArrayList<>(); - for(JsonElement e : apply.getAsJsonArray()) { - applyObjects.add(e.getAsJsonObject()); - } - } else - applyObjects = Collections.singletonList(apply.getAsJsonObject()); - for(JsonObject applyEntry : applyObjects) { - modelFiles.add(new ResourceLocation(applyEntry.get("model").getAsString())); - } - } - - } - } catch(RuntimeException e) { - ModernFix.LOGGER.error("Error with blockstate {}: {}", pair.getFirst(), e); - } - - } - } - blockStateData = null; - Map basicModels = new HashMap<>(); - basicModels.put(MISSING_MODEL_LOCATION, (BlockModel)missingModel); - basicModels.put(new ResourceLocation("builtin/generated"), GENERATION_MARKER); - basicModels.put(new ResourceLocation("builtin/entity"), BLOCK_ENTITY_MARKER); - Set> errorSet = Sets.newLinkedHashSet(); - while(modelFiles.size() > 0) { - List>> modelBytes = new ArrayList<>(); - for(ResourceLocation model : modelFiles) { - if(basicModels.containsKey(model)) - continue; - ResourceLocation fileLocation = new ResourceLocation(model.getNamespace(), "models/" + model.getPath() + ".json"); - modelBytes.add(CompletableFuture.supplyAsync(() -> { - Optional resource = this.resourceManager.getResource(fileLocation); - if(resource.isPresent()) { - try(InputStream stream = resource.get().open()) { - JsonParser parser = new JsonParser(); - return Pair.of(model, parser.parse(new InputStreamReader(stream, StandardCharsets.UTF_8))); - } catch(IOException | JsonParseException e) { - ModernFix.LOGGER.error("Error reading model {}: {}", fileLocation, e); - } - } - return Pair.of(fileLocation, null); - }, Util.backgroundExecutor())); - } - modelFiles.clear(); - CompletableFuture.allOf(modelBytes.toArray(new CompletableFuture[0])).join(); - for(CompletableFuture> future : modelBytes) { - Pair pair = future.join(); - try { - if(pair.getSecond() != null) { - BlockModel model = ExtendedBlockModelDeserializer.INSTANCE.fromJson(pair.getSecond(), BlockModel.class); - model.name = pair.getFirst().toString(); - modelFiles.addAll(model.getDependencies()); - basicModels.put(pair.getFirst(), model); - continue; - } - } catch(Throwable e) { - ModernFix.LOGGER.warn("Unable to parse {}: {}", pair.getFirst(), e); - } - basicModels.put(pair.getFirst(), (BlockModel)missingModel); - } - } - modelFiles = null; - Function modelGetter = loc -> { - UnbakedModel m = basicModels.get(loc); - /* fallback to vanilla loader if missing */ - return m != null ? m : this.getModel(loc); - }; - for(BlockModel model : basicModels.values()) { - materialSet.addAll(model.getMaterials(modelGetter, errorSet)); - } - /* discard whatever garbage was just produced */ - loadedModels.invalidateAll(); - loadedModels.put(MISSING_MODEL_LOCATION, missingModel); - //errorSet.stream().filter(pair -> !pair.getSecond().equals(MISSING_MODEL_LOCATION_STRING)).forEach(pair -> LOGGER.warn("Unable to resolve texture reference: {} in {}", pair.getFirst(), pair.getSecond())); - stopwatch.stop(); - ModernFix.LOGGER.info("Resolving model textures took " + stopwatch); - } - - @Inject(method = "uploadTextures", at = @At(value = "FIELD", target = "Lnet/minecraft/client/resources/model/ModelBakery;topLevelModels:Ljava/util/Map;", ordinal = 0), cancellable = true) - private void skipBake(TextureManager resourceManager, ProfilerFiller profiler, CallbackInfoReturnable cir) { - profiler.pop(); - cir.setReturnValue(atlasSet); + @Inject(method = "bakeModels", at = @At("HEAD"), cancellable = true) + private void skipBake(BiFunction getter, CallbackInfo ci) { + textureGetter = getter; + ci.cancel(); } /** @@ -443,35 +304,10 @@ public abstract class ModelBakeryMixin { return ImmutableList.copyOf(finalList); } - @Inject(method = "bake(Lnet/minecraft/resources/ResourceLocation;Lnet/minecraft/client/resources/model/ModelState;Ljava/util/function/Function;)Lnet/minecraft/client/resources/model/BakedModel;", at = @At("HEAD"), cancellable = true, remap = false) - public void getOrLoadBakedModelDynamic(ResourceLocation arg, ModelState arg2, Function textureGetter, CallbackInfoReturnable cir) { - Triple triple = Triple.of(arg, arg2.getRotation(), arg2.isUvLocked()); - BakedModel existing = this.bakedCache.get(triple); - if (existing != null) { - cir.setReturnValue(existing); - } else if (this.atlasSet == null) { - throw new IllegalStateException("bake called too early"); - } else { - synchronized (this) { - if(debugDynamicModelLoading) - LOGGER.info("Baking {}", arg); - UnbakedModel iunbakedmodel = this.getModel(arg); - iunbakedmodel.getMaterials(this::getModel, new HashSet<>()); - BakedModel ibakedmodel = null; - if (iunbakedmodel instanceof BlockModel) { - BlockModel blockmodel = (BlockModel)iunbakedmodel; - if (blockmodel.getRootModel() == GENERATION_MARKER) { - ibakedmodel = ITEM_MODEL_GENERATOR.generateBlockModel(textureGetter, blockmodel).bake((ModelBakery)(Object)this, blockmodel, this.atlasSet::getSprite, arg2, arg, false); - } - } - if(ibakedmodel == null) { - ibakedmodel = iunbakedmodel.bake((ModelBakery) (Object) this, textureGetter, arg2, arg); - } - DynamicModelBakeEvent event = new DynamicModelBakeEvent(arg, iunbakedmodel, ibakedmodel, (ModelBakery)(Object)this); - MinecraftForge.EVENT_BUS.post(event); - this.bakedCache.put(triple, event.getModel()); - cir.setReturnValue(event.getModel()); - } - } + @Override + public BakedModel bakeDefault(ResourceLocation modelLocation) { + ModelBakery self = (ModelBakery)(Object)this; + ModelBaker theBaker = self.new ModelBakerImpl(textureGetter, modelLocation); + return theBaker.bake(modelLocation, BlockModelRotation.X0_Y0); } } diff --git a/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/ModelManagerMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/ModelManagerMixin.java new file mode 100644 index 00000000..30022fee --- /dev/null +++ b/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/ModelManagerMixin.java @@ -0,0 +1,30 @@ +package org.embeddedt.modernfix.mixin.perf.dynamic_resources; + +import net.minecraft.client.renderer.block.model.BlockModel; +import net.minecraft.client.resources.model.ModelBakery; +import net.minecraft.client.resources.model.ModelManager; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.ResourceManager; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; + +@Mixin(ModelManager.class) +public class ModelManagerMixin { + @Inject(method = "loadBlockModels", at = @At("HEAD"), cancellable = true) + private static void deferBlockModelLoad(ResourceManager manager, Executor executor, CallbackInfoReturnable>> cir) { + cir.setReturnValue(CompletableFuture.completedFuture(new HashMap<>())); + } + + @Inject(method = "loadBlockStates", at = @At("HEAD"), cancellable = true) + private static void deferBlockStateLoad(ResourceManager manager, Executor executor, CallbackInfoReturnable>>> cir) { + cir.setReturnValue(CompletableFuture.completedFuture(new HashMap<>())); + } +} diff --git a/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/ctm/TextureMetadataHandlerMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/ctm/TextureMetadataHandlerMixin.java index f00a5b91..bd6bf7af 100644 --- a/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/ctm/TextureMetadataHandlerMixin.java +++ b/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/ctm/TextureMetadataHandlerMixin.java @@ -2,10 +2,7 @@ package org.embeddedt.modernfix.mixin.perf.dynamic_resources.ctm; import com.mojang.datafixers.util.Pair; import it.unimi.dsi.fastutil.objects.Object2BooleanMap; -import net.minecraft.client.resources.model.BakedModel; -import net.minecraft.client.resources.model.Material; -import net.minecraft.client.resources.model.ModelBakery; -import net.minecraft.client.resources.model.UnbakedModel; +import net.minecraft.client.resources.model.*; import net.minecraft.resources.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.eventbus.api.SubscribeEvent; @@ -29,7 +26,7 @@ import java.util.*; @Mixin(TextureMetadataHandler.class) public abstract class TextureMetadataHandlerMixin { - @Shadow @Nonnull protected abstract BakedModel wrap(ResourceLocation loc, UnbakedModel model, BakedModel object, ModelBakery loader) throws IOException; + @Shadow @Nonnull protected abstract BakedModel wrap(ResourceLocation loc, UnbakedModel model, BakedModel object, ModelBaker loader) throws IOException; @Inject(method = "", at = @At("RETURN")) private void subscribeDynamic(CallbackInfo ci) { @@ -57,7 +54,8 @@ public abstract class TextureMetadataHandlerMixin { continue; } - Collection textures = model.getMaterials(event.getModelLoader()::getModel, errors); + // TODO port + Collection textures = Collections.emptyList(); // model.getMaterials(event.getModelLoader()::getModel, errors); Collection newDependencies = model.getDependencies(); for (Material tex : textures) { IMetadataSectionCTM meta = null; diff --git a/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/supermartijncore/ModelBakerImplMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/supermartijncore/ModelBakerImplMixin.java new file mode 100644 index 00000000..c14a1158 --- /dev/null +++ b/src/main/java/org/embeddedt/modernfix/mixin/perf/dynamic_resources/supermartijncore/ModelBakerImplMixin.java @@ -0,0 +1,58 @@ +package org.embeddedt.modernfix.mixin.perf.dynamic_resources.supermartijncore; + +import com.mojang.math.Transformation; +import net.minecraft.client.renderer.block.model.BlockModel; +import net.minecraft.client.renderer.texture.TextureAtlasSprite; +import net.minecraft.client.resources.model.*; +import net.minecraft.resources.ResourceLocation; +import net.minecraftforge.common.MinecraftForge; +import org.apache.commons.lang3.tuple.Triple; +import org.embeddedt.modernfix.ModernFix; +import org.embeddedt.modernfix.dynamicresources.DynamicModelBakeEvent; +import org.spongepowered.asm.mixin.Final; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Shadow; +import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.Inject; +import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; + +import java.util.function.Function; + +@Mixin(ModelBakery.ModelBakerImpl.class) +public abstract class ModelBakerImplMixin { + private static final boolean debugDynamicModelLoading = Boolean.getBoolean("modernfix.debugDynamicModelLoading"); + @Shadow @Final private ModelBakery field_40571; + + @Shadow public abstract UnbakedModel getModel(ResourceLocation arg); + + @Inject(method = "bake(Lnet/minecraft/resources/ResourceLocation;Lnet/minecraft/client/resources/model/ModelState;Ljava/util/function/Function;)Lnet/minecraft/client/resources/model/BakedModel;", at = @At("HEAD"), cancellable = true, remap = false) + public void getOrLoadBakedModelDynamic(ResourceLocation arg, ModelState arg2, Function textureGetter, CallbackInfoReturnable cir) { + ModelBakery.BakedCacheKey key = new ModelBakery.BakedCacheKey(arg, arg2.getRotation(), arg2.isUvLocked()); + BakedModel existing = this.field_40571.bakedCache.get(key); + if (existing != null) { + cir.setReturnValue(existing); + } else { + synchronized (this) { + if(debugDynamicModelLoading) + ModernFix.LOGGER.info("Baking {}", arg); + UnbakedModel iunbakedmodel = this.getModel(arg); + // TODO: make sure parent resolution doesn't re-run many times + iunbakedmodel.resolveParents(this::getModel); + BakedModel ibakedmodel = null; + if (iunbakedmodel instanceof BlockModel) { + BlockModel blockmodel = (BlockModel)iunbakedmodel; + if (blockmodel.getRootModel() == ModelBakery.GENERATION_MARKER) { + ibakedmodel = ModelBakery.ITEM_MODEL_GENERATOR.generateBlockModel(textureGetter, blockmodel).bake((ModelBaker)this, blockmodel, textureGetter, arg2, arg, false); + } + } + if(ibakedmodel == null) { + ibakedmodel = iunbakedmodel.bake((ModelBaker)this, textureGetter, arg2, arg); + } + DynamicModelBakeEvent event = new DynamicModelBakeEvent(arg, iunbakedmodel, ibakedmodel, (ModelBaker)this); + MinecraftForge.EVENT_BUS.post(event); + this.field_40571.bakedCache.put(key, event.getModel()); + cir.setReturnValue(event.getModel()); + } + } + } +} diff --git a/src/main/java/org/embeddedt/modernfix/mixin/perf/faster_texture_stitching/StitcherMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/perf/faster_texture_stitching/StitcherMixin.java index 820383de..90bc16b0 100644 --- a/src/main/java/org/embeddedt/modernfix/mixin/perf/faster_texture_stitching/StitcherMixin.java +++ b/src/main/java/org/embeddedt/modernfix/mixin/perf/faster_texture_stitching/StitcherMixin.java @@ -20,15 +20,15 @@ import java.util.List; import java.util.Set; @Mixin(Stitcher.class) -public class StitcherMixin { - @Shadow @Final private Set texturesToBeStitched; +public class StitcherMixin { + @Shadow @Final private List> texturesToBeStitched; @Shadow private int storageX; @Shadow private int storageY; - @Shadow @Final private static Comparator HOLDER_COMPARATOR; - private List loadableSpriteInfos; + @Shadow @Final private static Comparator> HOLDER_COMPARATOR; + private List> loadableSpriteInfos; /** * @author embeddedt, SuperCoder79 @@ -41,11 +41,11 @@ public class StitcherMixin { return; } ci.cancel(); - ObjectArrayList holderList = new ObjectArrayList<>(this.texturesToBeStitched); + ObjectArrayList> holderList = new ObjectArrayList<>(this.texturesToBeStitched); holderList.sort(HOLDER_COMPARATOR); - Stitcher.Holder[] aholder = holderList.toArray(new Stitcher.Holder[0]); + Stitcher.Holder[] aholder = holderList.toArray(new Stitcher.Holder[0]); - Pair, List> packingInfo = StbStitcher.packRects(aholder); + Pair, List>> packingInfo = StbStitcher.packRects(aholder); this.storageX = packingInfo.getFirst().getFirst(); this.storageY = packingInfo.getFirst().getSecond(); this.loadableSpriteInfos = packingInfo.getSecond(); @@ -56,12 +56,12 @@ public class StitcherMixin { * @reason We setup the image ourselves in the StbStitcher, so we just feed this information back into the vanilla code */ @Inject(method = "gatherSprites", at = @At("HEAD"), cancellable = true) - private void gatherSpritesFast(Stitcher.SpriteLoader spriteLoader, CallbackInfo ci) { + private void gatherSpritesFast(Stitcher.SpriteLoader spriteLoader, CallbackInfo ci) { if(!ModLoader.isLoadingStateValid()) return; ci.cancel(); - for(StbStitcher.LoadableSpriteInfo info : loadableSpriteInfos) { - spriteLoader.load(info.info, info.width, info.height, info.x, info.y); + for(StbStitcher.LoadableSpriteInfo info : loadableSpriteInfos) { + spriteLoader.load(info.info, info.x, info.y); } } } diff --git a/src/main/java/org/embeddedt/modernfix/mixin/perf/model_optimizations/TransformationMatrixMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/perf/model_optimizations/TransformationMatrixMixin.java index 3ef98818..74593d33 100644 --- a/src/main/java/org/embeddedt/modernfix/mixin/perf/model_optimizations/TransformationMatrixMixin.java +++ b/src/main/java/org/embeddedt/modernfix/mixin/perf/model_optimizations/TransformationMatrixMixin.java @@ -1,7 +1,7 @@ package org.embeddedt.modernfix.mixin.perf.model_optimizations; -import com.mojang.math.Matrix4f; import com.mojang.math.Transformation; +import org.joml.Matrix4f; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Overwrite; diff --git a/src/main/java/org/embeddedt/modernfix/mixin/perf/modern_resourcepacks/PathPackResourcesMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/perf/modern_resourcepacks/PathPackResourcesMixin.java index 35b48835..5ea6b903 100644 --- a/src/main/java/org/embeddedt/modernfix/mixin/perf/modern_resourcepacks/PathPackResourcesMixin.java +++ b/src/main/java/org/embeddedt/modernfix/mixin/perf/modern_resourcepacks/PathPackResourcesMixin.java @@ -121,7 +121,7 @@ public abstract class PathPackResourcesMixin { } } - @Inject(method = "hasResource(Ljava/lang/String;)Z", at = @At(value = "HEAD"), cancellable = true) + //@Inject(method = "hasResource(Ljava/lang/String;)Z", at = @At(value = "HEAD"), cancellable = true) private void useCacheForExistence(String path, CallbackInfoReturnable cir) { this.generateResourceCache(); cir.setReturnValue(this.containedPaths.contains(FileUtil.normalize(path))); @@ -131,7 +131,7 @@ public abstract class PathPackResourcesMixin { * @author embeddedt * @reason Use cached listing of mod resources */ - @Inject(method = "getResources", at = @At("HEAD"), cancellable = true) + @Inject(method = "getResources", at = @At("HEAD"), cancellable = true, remap = false) public void getResources(PackType type, String resourceNamespace, String pathIn, Predicate filter, CallbackInfoReturnable> cir) { this.generateResourceCache(); diff --git a/src/main/java/org/embeddedt/modernfix/mixin/perf/modern_resourcepacks/VanillaPackResourcesMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/perf/modern_resourcepacks/VanillaPackResourcesMixin.java index 8fc0086a..68f0a216 100644 --- a/src/main/java/org/embeddedt/modernfix/mixin/perf/modern_resourcepacks/VanillaPackResourcesMixin.java +++ b/src/main/java/org/embeddedt/modernfix/mixin/perf/modern_resourcepacks/VanillaPackResourcesMixin.java @@ -23,7 +23,7 @@ public class VanillaPackResourcesMixin { * @reason avoid going through the module class loader when we know exactly what path this resource should come * from */ - @Overwrite + //@Overwrite protected InputStream getResourceAsStream(PackType type, ResourceLocation location) { Path rootPath = ROOT_DIR_BY_TYPE.get(type); Path targetPath = rootPath.resolve(location.getNamespace() + "/" + location.getPath()); diff --git a/src/main/java/org/embeddedt/modernfix/mixin/perf/skip_first_datapack_reload/CreateWorldScreenMixin.java b/src/main/java/org/embeddedt/modernfix/mixin/perf/skip_first_datapack_reload/CreateWorldScreenMixin.java index b7ef661c..ef52705d 100644 --- a/src/main/java/org/embeddedt/modernfix/mixin/perf/skip_first_datapack_reload/CreateWorldScreenMixin.java +++ b/src/main/java/org/embeddedt/modernfix/mixin/perf/skip_first_datapack_reload/CreateWorldScreenMixin.java @@ -1,92 +1,14 @@ package org.embeddedt.modernfix.mixin.perf.skip_first_datapack_reload; -import com.google.common.collect.ImmutableList; -import com.mojang.datafixers.util.Pair; -import com.mojang.serialization.Lifecycle; -import it.unimi.dsi.fastutil.booleans.BooleanConsumer; -import net.minecraft.Util; import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.worldselection.CreateWorldScreen; -import net.minecraft.client.gui.screens.worldselection.WorldCreationContext; -import net.minecraft.client.gui.screens.worldselection.WorldGenSettingsComponent; -import net.minecraft.core.RegistryAccess; import net.minecraft.network.chat.Component; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.WorldLoader; -import net.minecraft.server.packs.PackType; -import net.minecraft.server.packs.repository.PackRepository; -import net.minecraft.server.packs.repository.ServerPacksSource; -import net.minecraft.world.level.DataPackConfig; -import net.minecraft.world.level.levelgen.WorldGenSettings; -import net.minecraft.world.level.levelgen.presets.WorldPresets; -import org.embeddedt.modernfix.ModernFix; -import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyArg; -import org.spongepowered.asm.mixin.injection.Redirect; - -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executor; @Mixin(CreateWorldScreen.class) public abstract class CreateWorldScreenMixin extends Screen { - @Shadow protected static WorldLoader.InitConfig createDefaultLoadConfig(PackRepository arg, DataPackConfig arg2) { - throw new AssertionError(); - } - - @Shadow protected DataPackConfig dataPacks; - - @Shadow @Final public WorldGenSettingsComponent worldGenSettingsComponent; - - @Shadow protected abstract void openDataPackSelectionScreen(); - protected CreateWorldScreenMixin(Component arg) { super(arg); } - - @Redirect(method = "openFresh", at = @At(value = "INVOKE", target = "Lnet/minecraft/server/WorldLoader;load(Lnet/minecraft/server/WorldLoader$InitConfig;Lnet/minecraft/server/WorldLoader$WorldDataSupplier;Lnet/minecraft/server/WorldLoader$ResultFactory;Ljava/util/concurrent/Executor;Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletableFuture;")) - private static CompletableFuture doLoad(WorldLoader.InitConfig config, WorldLoader.WorldDataSupplier supplier, WorldLoader.ResultFactory factory, Executor backgroundExecutor, Executor mainExecutor) { - ModernFix.LOGGER.warn("Skipping first datapack reload"); - // Make sure to configure the pack repository as though the load happened - MinecraftServer.configurePackRepository(config.packConfig().packRepository(), config.packConfig().initialDataPacks(), config.packConfig().safeMode()); - Pair creationPair = supplier.get(null, null); - WorldGenSettings settings = creationPair.getFirst(); - // Don't load any datapack resources, since Forge is about to do it themselves - WorldCreationContext context = new WorldCreationContext(settings, Lifecycle.stable(), creationPair.getSecond(), null); - return CompletableFuture.completedFuture(context); - } - - @ModifyArg(method = "*", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/gui/screens/ConfirmScreen;(Lit/unimi/dsi/fastutil/booleans/BooleanConsumer;Lnet/minecraft/network/chat/Component;Lnet/minecraft/network/chat/Component;Lnet/minecraft/network/chat/Component;Lnet/minecraft/network/chat/Component;)V"), index = 0) - private BooleanConsumer replaceConsumer(BooleanConsumer consumer) { - return bl -> { - if(bl) { - // just open the selection screen again - this.openDataPackSelectionScreen(); - } else { - this.dataPacks = new DataPackConfig(ImmutableList.of("vanilla"), ImmutableList.of()); - this.mfix$loadVanillaResources(); - this.minecraft.setScreen(this); - } - }; - } - - private void mfix$loadVanillaResources() { - ModernFix.LOGGER.warn("Loading vanilla resources"); - // We now need to perform the reload that was skipped above - PackRepository packrepository = new PackRepository(PackType.SERVER_DATA, new ServerPacksSource()); - WorldLoader.InitConfig vanillaConfig = createDefaultLoadConfig(packrepository, new DataPackConfig(ImmutableList.of("vanilla"), ImmutableList.of())); - CompletableFuture completablefuture = WorldLoader.load(vanillaConfig, (argx, arg2x) -> { - RegistryAccess.Frozen registryaccess$frozen = RegistryAccess.builtinCopy().freeze(); - WorldGenSettings worldgensettings = WorldPresets.createNormalWorldFromPreset(registryaccess$frozen); - return Pair.of(worldgensettings, registryaccess$frozen); - }, (argx, arg2x, arg3, arg4) -> { - argx.close(); - return new WorldCreationContext(arg4, Lifecycle.stable(), arg3, arg2x); - }, Util.backgroundExecutor(), this.minecraft); - this.minecraft.managedBlock(completablefuture::isDone); - this.worldGenSettingsComponent.updateSettings(completablefuture.join()); - this.rebuildWidgets(); - } + // TODO: incorporate https://github.com/MinecraftForge/MinecraftForge/pull/9454 } diff --git a/src/main/java/org/embeddedt/modernfix/screen/DeferredLevelLoadingScreen.java b/src/main/java/org/embeddedt/modernfix/screen/DeferredLevelLoadingScreen.java index cd49687a..d66bde97 100644 --- a/src/main/java/org/embeddedt/modernfix/screen/DeferredLevelLoadingScreen.java +++ b/src/main/java/org/embeddedt/modernfix/screen/DeferredLevelLoadingScreen.java @@ -3,6 +3,7 @@ package org.embeddedt.modernfix.screen; import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.client.gui.screens.LevelLoadingScreen; import net.minecraft.server.level.progress.StoringChunkProgressListener; +import org.jetbrains.annotations.NotNull; import java.util.function.BooleanSupplier; @@ -21,7 +22,7 @@ public class DeferredLevelLoadingScreen extends LevelLoadingScreen { } @Override - public void renderBackground(PoseStack matrixStack, int vOffset) { - renderDirtBackground(vOffset); + public void renderBackground(@NotNull PoseStack arg) { + renderDirtBackground(arg); } } diff --git a/src/main/java/org/embeddedt/modernfix/structure/CachingStructureManager.java b/src/main/java/org/embeddedt/modernfix/structure/CachingStructureManager.java index 8839a255..61c47320 100644 --- a/src/main/java/org/embeddedt/modernfix/structure/CachingStructureManager.java +++ b/src/main/java/org/embeddedt/modernfix/structure/CachingStructureManager.java @@ -3,11 +3,13 @@ package org.embeddedt.modernfix.structure; import com.mojang.datafixers.DataFixer; import cpw.mods.modlauncher.api.LamdbaExceptionUtils; import net.minecraft.SharedConstants; +import net.minecraft.core.HolderGetter; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtIo; import net.minecraft.nbt.NbtUtils; import net.minecraft.resources.ResourceLocation; import net.minecraft.util.datafix.DataFixTypes; +import net.minecraft.world.level.block.Block; import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import net.minecraftforge.fml.loading.FMLPaths; import org.embeddedt.modernfix.ModernFix; @@ -24,10 +26,10 @@ public class CachingStructureManager { STRUCTURE_CACHE_FOLDER.mkdirs(); } - public static StructureTemplate readStructure(ResourceLocation location, DataFixer datafixer, InputStream stream) throws IOException { + public static StructureTemplate readStructure(ResourceLocation location, DataFixer datafixer, InputStream stream, HolderGetter blockGetter) throws IOException { CompoundTag tag = readStructureTag(location, datafixer, stream); StructureTemplate template = new StructureTemplate(); - template.load(tag); + template.load(blockGetter, tag); return template; } @@ -46,20 +48,20 @@ public class CachingStructureManager { currentTag.putInt("DataVersion", 500); } int currentDataVersion = currentTag.getInt("DataVersion"); - if(currentDataVersion < SharedConstants.getCurrentVersion().getWorldVersion()) { + if(currentDataVersion < SharedConstants.getCurrentVersion().getDataVersion().getVersion()) { /* Needs upgrade, try looking up from cache */ MessageDigest hasher = digestThreadLocal.get(); hasher.reset(); String hash = encodeHex(hasher.digest(structureBytes)); CompoundTag cachedUpgraded = getCachedUpgraded(location, hash); - if(cachedUpgraded != null && cachedUpgraded.getInt("DataVersion") == SharedConstants.getCurrentVersion().getWorldVersion()) { + if(cachedUpgraded != null && cachedUpgraded.getInt("DataVersion") == SharedConstants.getCurrentVersion().getDataVersion().getVersion()) { ModernFix.LOGGER.debug("Using cached upgraded version of {}", location); currentTag = cachedUpgraded; } else { ModernFix.LOGGER.debug("Structure {} is being run through DFU (hash {}), this will cause launch time delays", location, hash); - currentTag = NbtUtils.update(datafixer, DataFixTypes.STRUCTURE, currentTag, currentDataVersion, - SharedConstants.getCurrentVersion().getWorldVersion()); - currentTag.putInt("DataVersion", SharedConstants.getCurrentVersion().getWorldVersion()); + currentTag = DataFixTypes.STRUCTURE.update(datafixer, currentTag, currentDataVersion, + SharedConstants.getCurrentVersion().getDataVersion().getVersion()); + currentTag.putInt("DataVersion", SharedConstants.getCurrentVersion().getDataVersion().getVersion()); saveCachedUpgraded(location, hash, currentTag); } } diff --git a/src/main/java/org/embeddedt/modernfix/textures/StbStitcher.java b/src/main/java/org/embeddedt/modernfix/textures/StbStitcher.java index 42c2fdf8..94ff65e0 100644 --- a/src/main/java/org/embeddedt/modernfix/textures/StbStitcher.java +++ b/src/main/java/org/embeddedt/modernfix/textures/StbStitcher.java @@ -125,10 +125,10 @@ public class StbStitcher { } } - public static Pair, List> packRects(Stitcher.Holder[] holders) { + public static Pair, List>> packRects(Stitcher.Holder[] holders) { int holderSize = holders.length; - List infoList = new ArrayList<>(); + List> infoList = new ArrayList<>(); // Allocate memory for the rectangles and the context try (STBRPRect.Buffer rectBuf = STBRPRect.malloc(holderSize); @@ -139,10 +139,10 @@ public class StbStitcher { int totalArea = 0; int longestWidth = 0, longestHeight = 0; for (int j = 0; j < holderSize; ++j) { - Stitcher.Holder holder = holders[j]; + Stitcher.Holder holder = holders[j]; - int width = holder.width; - int height = holder.height; + int width = holder.width(); + int height = holder.height(); // The ID here is just the array index, for easy lookup later STBRPRect rect = rectBuf.get(j); @@ -184,16 +184,16 @@ public class StbStitcher { STBRectPack.stbrp_pack_rects(ctx, rectBuf); for (STBRPRect rect : rectBuf) { - Stitcher.Holder holder = holders[rect.id()]; + Stitcher.Holder holder = holders[rect.id()]; // Ensure that everything is properly packed! if (!rect.was_packed()) { - throw new StitcherException(holder.spriteInfo, - Stream.of(holders).map(arg -> arg.spriteInfo).collect(ImmutableList.toImmutableList())); + throw new StitcherException(holder.entry(), + Stream.of(holders).map(Stitcher.Holder::entry).collect(ImmutableList.toImmutableList())); } // Initialize the sprite now with the position and size that we've calculated so far - infoList.add(new LoadableSpriteInfo(holder.spriteInfo, longestWidth, longestHeight, getX(rect), getY(rect))); + infoList.add(new LoadableSpriteInfo(holder.entry(), longestWidth, longestHeight, getX(rect), getY(rect))); //holder.spriteInfo.initSprite(size, size, rect.x(), rect.y(), false); } @@ -202,8 +202,8 @@ public class StbStitcher { if(numTries >= 4) { // If we get here, we weren't able to stitch. Throw an error. ModernFix.LOGGER.error("Stitcher ran out of space with target atlas size " + longestWidth + "x" + longestHeight + ":"); - for(Stitcher.Holder h : holders) { - ModernFix.LOGGER.error(" - " + h.spriteInfo.name() + ", " + h.spriteInfo.width() + "x" + h.spriteInfo.height()); + for(Stitcher.Holder h : holders) { + ModernFix.LOGGER.error(" - " + h.entry().name() + ", " + h.width() + "x" + h.height()); } throw e; } else { @@ -218,14 +218,14 @@ public class StbStitcher { } } - public static class LoadableSpriteInfo { - public final TextureAtlasSprite.Info info; + public static class LoadableSpriteInfo { + public final T info; public final int width; public final int height; public final int x; public final int y; - LoadableSpriteInfo(TextureAtlasSprite.Info info, int width, int height, int x, int y) { + LoadableSpriteInfo(T info, int width, int height, int x, int y) { this.info = info; this.width = width; this.height = height; diff --git a/src/main/java/org/embeddedt/modernfix/util/DummyServerConfiguration.java b/src/main/java/org/embeddedt/modernfix/util/DummyServerConfiguration.java index 96e3fbf1..988a57f1 100644 --- a/src/main/java/org/embeddedt/modernfix/util/DummyServerConfiguration.java +++ b/src/main/java/org/embeddedt/modernfix/util/DummyServerConfiguration.java @@ -3,13 +3,11 @@ package org.embeddedt.modernfix.util; import com.google.common.collect.ImmutableSet; import com.mojang.serialization.Lifecycle; import net.minecraft.nbt.CompoundTag; -import net.minecraft.world.level.DataPackConfig; +import net.minecraft.world.level.*; import net.minecraft.core.RegistryAccess; import net.minecraft.world.Difficulty; -import net.minecraft.world.level.GameRules; -import net.minecraft.world.level.GameType; -import net.minecraft.world.level.LevelSettings; import net.minecraft.world.level.levelgen.WorldGenSettings; +import net.minecraft.world.level.levelgen.WorldOptions; import net.minecraft.world.level.storage.WorldData; import net.minecraft.world.level.storage.ServerLevelData; @@ -18,12 +16,12 @@ import java.util.Set; public class DummyServerConfiguration implements WorldData { @Override - public DataPackConfig getDataPackConfig() { - return DataPackConfig.DEFAULT; + public WorldDataConfiguration getDataConfiguration() { + return null; } @Override - public void setDataPackConfig(DataPackConfig codec) { + public void setDataConfiguration(WorldDataConfiguration arg) { } @@ -139,10 +137,20 @@ public class DummyServerConfiguration implements WorldData { } @Override - public WorldGenSettings worldGenSettings() { + public WorldOptions worldGenOptions() { return null; } + @Override + public boolean isFlatWorld() { + return false; + } + + @Override + public boolean isDebugWorld() { + return false; + } + @Override public Lifecycle worldGenSettingsLifecycle() { return Lifecycle.stable(); diff --git a/src/main/resources/META-INF/accesstransformer.cfg b/src/main/resources/META-INF/accesstransformer.cfg index ab5b89aa..7a21c5da 100644 --- a/src/main/resources/META-INF/accesstransformer.cfg +++ b/src/main/resources/META-INF/accesstransformer.cfg @@ -25,3 +25,9 @@ public net.minecraft.world.level.block.state.BlockBehaviour$Properties f_60902_ public net.minecraft.world.level.block.state.BlockBehaviour$Properties f_60889_ # requiresCorrectToolForDrops public net.minecraft.world.level.block.state.BlockBehaviour$Properties f_60888_ # destroyTime public net.minecraft.server.level.ServerChunkCache$MainThreadExecutor +public net.minecraft.client.resources.model.ModelBakery f_119213_ # bakedCache +public net.minecraft.client.resources.model.ModelBakery$BakedCacheKey +public net.minecraft.client.resources.model.ModelBakery$BakedCacheKey (Lnet/minecraft/resources/ResourceLocation;Lcom/mojang/math/Transformation;Z)V # +public net.minecraft.client.resources.model.ModelBakery f_119241_ # ITEM_MODEL_GENERATOR +public net.minecraft.client.resources.model.ModelBakery$ModelBakerImpl +public net.minecraft.client.resources.model.ModelBakery$ModelBakerImpl (Lnet/minecraft/client/resources/model/ModelBakery;Ljava/util/function/BiFunction;Lnet/minecraft/resources/ResourceLocation;)V # \ No newline at end of file diff --git a/src/main/resources/META-INF/mods.toml b/src/main/resources/META-INF/mods.toml index f895414c..7da1b8f8 100644 --- a/src/main/resources/META-INF/mods.toml +++ b/src/main/resources/META-INF/mods.toml @@ -6,7 +6,7 @@ # The name of the mod loader type to load - for regular FML @Mod mods it should be javafml modLoader = "javafml" #mandatory # A version range to match for said mod loader - for regular FML @Mod it will be the forge version -loaderVersion = "[43,)" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions. +loaderVersion = "[45,)" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions. # The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties. # Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here. license = "GNU LGPL 3.0" @@ -43,7 +43,7 @@ modId = "forge" #mandatory # Does this dependency have to exist - if not, ordering below must be specified mandatory = true #mandatory # The version range of the dependency -versionRange = "[43,)" #mandatory +versionRange = "[45,)" #mandatory # An ordering relationship for the dependency - BEFORE or AFTER required if the relationship is not mandatory ordering = "NONE" # Side this dependency is applied on - BOTH, CLIENT or SERVER @@ -53,13 +53,13 @@ side = "BOTH" modId = "minecraft" mandatory = true # This version range declares a minimum of the current minecraft version up to but not including the next major version -versionRange = "[1.19.1, 1.19.2]" +versionRange = "[1.19.4, 1.20)" ordering = "NONE" side = "BOTH" [[dependencies.modernfix]] modId = "jei" mandatory = false # This version range declares a minimum of the current minecraft version up to but not including the next major version -versionRange = "[11,)" +versionRange = "[13,)" ordering = "BEFORE" side = "CLIENT" diff --git a/src/main/resources/modernfix.mixins.json b/src/main/resources/modernfix.mixins.json index 1997abd5..d05ad324 100644 --- a/src/main/resources/modernfix.mixins.json +++ b/src/main/resources/modernfix.mixins.json @@ -7,8 +7,6 @@ "refmap": "modernfix.refmap.json", "mixins": [ "bugfix.edge_chunk_not_saved.ChunkManagerMixin", - "perf.modern_resourcepacks.VanillaPackResourcesMixin", - "perf.modern_resourcepacks.PathPackResourcesMixin", "bugfix.chunk_deadlock.ServerChunkCacheMixin", "perf.remove_biome_temperature_cache.BiomeMixin", "perf.reduce_blockstate_cache_rebuilds.GameDataMixin", @@ -39,7 +37,6 @@ "core.MinecraftMixin", "core.SynchedEntityDataMixin", "feature.measure_time.MinecraftMixin", - "feature.reduce_loading_screen_freezes.ModelBakeryMixin", "bugfix.concurrency.MinecraftMixin", "perf.dynamic_resources.BlockModelShaperMixin", "perf.dynamic_resources.ItemModelShaperMixin", @@ -59,7 +56,6 @@ "perf.flatten_model_predicates.PropertyValueConditionMixin", "perf.blast_search_trees.MinecraftMixin", "perf.blast_search_trees.IngredientFilterInvoker", - "perf.cache_model_materials.VanillaModelMixin", "perf.cache_model_materials.MultipartMixin", "perf.faster_texture_stitching.StitcherMixin", "perf.skip_first_datapack_reload.CreateWorldScreenMixin",