| 1 | package net.minecraft.client.resources.model;
|
| 2 |
|
| 3 | import com.google.common.collect.Sets;
|
| 4 | import com.mojang.datafixers.util.Pair;
|
| 5 | import com.mojang.logging.LogUtils;
|
| 6 | import it.unimi.dsi.fastutil.objects.Object2IntMap;
|
| 7 | import it.unimi.dsi.fastutil.objects.Object2IntMaps;
|
| 8 | import java.io.Reader;
|
| 9 | import java.util.ArrayList;
|
| 10 | import java.util.IdentityHashMap;
|
| 11 | import java.util.List;
|
| 12 | import java.util.Map;
|
| 13 | import java.util.Objects;
|
| 14 | import java.util.Set;
|
| 15 | import java.util.Map.Entry;
|
| 16 | import java.util.concurrent.CompletableFuture;
|
| 17 | import java.util.concurrent.Executor;
|
| 18 | import java.util.function.Supplier;
|
| 19 | import java.util.stream.Collectors;
|
| 20 | import net.fabricmc.api.EnvType;
|
| 21 | import net.fabricmc.api.Environment;
|
| 22 | import net.fabricmc.fabric.api.client.model.loading.v1.FabricModelManager;
|
| 23 | import net.minecraft.client.color.block.BlockColors;
|
| 24 | import net.minecraft.client.model.geom.EntityModelSet;
|
| 25 | import net.minecraft.client.renderer.PlayerSkinRenderCache;
|
| 26 | import net.minecraft.client.renderer.block.BlockModelSet;
|
| 27 | import net.minecraft.client.renderer.block.BlockStateModelSet;
|
| 28 | import net.minecraft.client.renderer.block.BuiltInBlockModels;
|
| 29 | import net.minecraft.client.renderer.block.FluidModel;
|
| 30 | import net.minecraft.client.renderer.block.FluidStateModelSet;
|
| 31 | import net.minecraft.client.renderer.block.LoadedBlockModels;
|
| 32 | import net.minecraft.client.renderer.block.dispatch.BlockStateModel;
|
| 33 | import net.minecraft.client.renderer.block.model.BlockModel;
|
| 34 | import net.minecraft.client.renderer.item.ClientItem;
|
| 35 | import net.minecraft.client.renderer.item.ItemModel;
|
| 36 | import net.minecraft.client.renderer.texture.SpriteLoader;
|
| 37 | import net.minecraft.client.resources.model.cuboid.CuboidModel;
|
| 38 | import net.minecraft.client.resources.model.cuboid.ItemModelGenerator;
|
| 39 | import net.minecraft.client.resources.model.cuboid.MissingCuboidModel;
|
| 40 | import net.minecraft.client.resources.model.sprite.AtlasManager;
|
| 41 | import net.minecraft.client.resources.model.sprite.MaterialBaker;
|
| 42 | import net.minecraft.core.registries.BuiltInRegistries;
|
| 43 | import net.minecraft.data.AtlasIds;
|
| 44 | import net.minecraft.resources.FileToIdConverter;
|
| 45 | import net.minecraft.resources.Identifier;
|
| 46 | import net.minecraft.server.packs.resources.PreparableReloadListener;
|
| 47 | import net.minecraft.server.packs.resources.Resource;
|
| 48 | import net.minecraft.server.packs.resources.ResourceManager;
|
| 49 | import net.minecraft.server.packs.resources.PreparableReloadListener.PreparationBarrier;
|
| 50 | import net.minecraft.server.packs.resources.PreparableReloadListener.SharedState;
|
| 51 | import net.minecraft.util.Util;
|
| 52 | import net.minecraft.util.profiling.Profiler;
|
| 53 | import net.minecraft.util.profiling.Zone;
|
| 54 | import net.minecraft.world.level.block.Block;
|
| 55 | import net.minecraft.world.level.block.state.BlockState;
|
| 56 | import net.minecraft.world.level.material.Fluid;
|
| 57 | import net.minecraft.world.level.material.FluidState;
|
| 58 | import org.jspecify.annotations.Nullable;
|
| 59 | import org.slf4j.Logger;
|
| 60 |
|
| 61 | @Environment(EnvType.CLIENT)
|
| 62 | public class ModelManager implements PreparableReloadListener, FabricModelManager {
|
| 63 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 64 | private static final FileToIdConverter MODEL_LISTER = FileToIdConverter.json("models");
|
| 65 | private Map<Identifier, ItemModel> bakedItemStackModels = Map.of();
|
| 66 | private Map<Identifier, ClientItem.Properties> itemProperties = Map.of();
|
| 67 | private final AtlasManager atlasManager;
|
| 68 | private final PlayerSkinRenderCache playerSkinRenderCache;
|
| 69 | private final BlockColors blockColors;
|
| 70 | private EntityModelSet entityModelSet = EntityModelSet.EMPTY;
|
| 71 | private ModelBakery.MissingModels missingModels;
|
| 72 | private @Nullable BlockStateModelSet blockStateModelSet;
|
| 73 | private @Nullable BlockModelSet blockModelSet;
|
| 74 | private @Nullable FluidStateModelSet fluidStateModelSet;
|
| 75 | private Object2IntMap<BlockState> modelGroups = Object2IntMaps.emptyMap();
|
| 76 |
|
| 77 | public ModelManager(final BlockColors blockColors, final AtlasManager atlasManager, final PlayerSkinRenderCache playerSkinRenderCache) {
|
| 78 | this.blockColors = blockColors;
|
| 79 | this.atlasManager = atlasManager;
|
| 80 | this.playerSkinRenderCache = playerSkinRenderCache;
|
| 81 | }
|
| 82 |
|
| 83 | public ItemModel getItemModel(final Identifier id) {
|
| 84 | return this.bakedItemStackModels.getOrDefault(id, this.missingModels.item());
|
| 85 | }
|
| 86 |
|
| 87 | public ClientItem.Properties getItemProperties(final Identifier id) {
|
| 88 | return this.itemProperties.getOrDefault(id, ClientItem.Properties.DEFAULT);
|
| 89 | }
|
| 90 |
|
| 91 | public BlockStateModelSet getBlockStateModelSet() {
|
| 92 | return Objects.requireNonNull(this.blockStateModelSet, "Block models not yet initialized");
|
| 93 | }
|
| 94 |
|
| 95 | public BlockModelSet getBlockModelSet() {
|
| 96 | return Objects.requireNonNull(this.blockModelSet, "Block models not yet initialized");
|
| 97 | }
|
| 98 |
|
| 99 | public FluidStateModelSet getFluidStateModelSet() {
|
| 100 | return Objects.requireNonNull(this.fluidStateModelSet, "Fluid models not yet initialized");
|
| 101 | }
|
| 102 |
|
| 103 | @Override
|
| 104 | public final CompletableFuture<Void> reload(
|
| 105 | final SharedState currentReload, final Executor taskExecutor, final PreparationBarrier preparationBarrier, final Executor reloadExecutor
|
| 106 | ) {
|
| 107 | ResourceManager manager = currentReload.resourceManager();
|
| 108 | CompletableFuture<EntityModelSet> entityModelSet = CompletableFuture.supplyAsync(EntityModelSet::vanilla, taskExecutor);
|
| 109 | CompletableFuture<Map<Identifier, UnbakedModel>> modelCache = loadBlockModels(manager, taskExecutor);
|
| 110 | CompletableFuture<BlockStateModelLoader.LoadedModels> blockStateModels = BlockStateModelLoader.loadBlockStates(manager, taskExecutor);
|
| 111 | CompletableFuture<Map<BlockState, BlockModel.Unbaked>> blockModelContents = CompletableFuture.supplyAsync(
|
| 112 | () -> BuiltInBlockModels.createBlockModels(this.blockColors), taskExecutor
|
| 113 | );
|
| 114 | CompletableFuture<ClientItemInfoLoader.LoadedClientInfos> itemStackModels = ClientItemInfoLoader.scheduleLoad(manager, taskExecutor);
|
| 115 | CompletableFuture<ModelManager.ResolvedModels> modelDiscovery = CompletableFuture.allOf(modelCache, blockStateModels, itemStackModels)
|
| 116 | .thenApplyAsync(var3 -> discoverModelDependencies(modelCache.join(), blockStateModels.join(), itemStackModels.join()), taskExecutor);
|
| 117 | CompletableFuture<Object2IntMap<BlockState>> modelGroups = blockStateModels.thenApplyAsync(models -> buildModelGroups(this.blockColors, models), taskExecutor);
|
| 118 | AtlasManager.PendingStitchResults pendingStitches = currentReload.get(AtlasManager.PENDING_STITCH);
|
| 119 | CompletableFuture<SpriteLoader.Preparations> pendingBlockAtlasSprites = pendingStitches.get(AtlasIds.BLOCKS);
|
| 120 | CompletableFuture<SpriteLoader.Preparations> pendingItemAtlasSprites = pendingStitches.get(AtlasIds.ITEMS);
|
| 121 | CompletableFuture<LoadedBlockModels> blockModels = CompletableFuture.allOf(blockModelContents, entityModelSet)
|
| 122 | .thenApply(var3 -> new LoadedBlockModels(blockModelContents.join(), entityModelSet.join(), this.atlasManager, this.playerSkinRenderCache));
|
| 123 | return CompletableFuture.allOf(
|
| 124 | pendingBlockAtlasSprites, pendingItemAtlasSprites, modelDiscovery, modelGroups, blockStateModels, itemStackModels, entityModelSet, blockModels, modelCache
|
| 125 | )
|
| 126 | .thenComposeAsync(
|
| 127 | var11x -> {
|
| 128 | SpriteLoader.Preparations blockAtlasSprites = pendingBlockAtlasSprites.join();
|
| 129 | SpriteLoader.Preparations itemAtlasSprites = pendingItemAtlasSprites.join();
|
| 130 | ModelManager.ResolvedModels resolvedModels = modelDiscovery.join();
|
| 131 | Object2IntMap<BlockState> groups = modelGroups.join();
|
| 132 | Set<Identifier> unreferencedModels = Sets.difference(modelCache.join().keySet(), resolvedModels.models.keySet());
|
| 133 | if (!unreferencedModels.isEmpty()) {
|
| 134 | LOGGER.debug("Unreferenced models: \n{}", unreferencedModels.stream().sorted().map(modelId -> "\t" + modelId + "\n").collect(Collectors.joining()));
|
| 135 | }
|
| 136 |
|
| 137 | ModelBakery bakery = new ModelBakery(
|
| 138 | entityModelSet.join(),
|
| 139 | this.atlasManager,
|
| 140 | this.playerSkinRenderCache,
|
| 141 | blockStateModels.join().models(),
|
| 142 | itemStackModels.join().contents(),
|
| 143 | resolvedModels.models(),
|
| 144 | resolvedModels.missing()
|
| 145 | );
|
| 146 | return loadModels(blockAtlasSprites, itemAtlasSprites, bakery, blockModels.join(), groups, entityModelSet.join(), taskExecutor);
|
| 147 | },
|
| 148 | taskExecutor
|
| 149 | )
|
| 150 | .thenCompose(preparationBarrier::wait)
|
| 151 | .thenAcceptAsync(this::apply, reloadExecutor);
|
| 152 | }
|
| 153 |
|
| 154 | private static CompletableFuture<Map<Identifier, UnbakedModel>> loadBlockModels(final ResourceManager manager, final Executor executor) {
|
| 155 | return CompletableFuture.<Map<Identifier, Resource>>supplyAsync(() -> MODEL_LISTER.listMatchingResources(manager), executor)
|
| 156 | .thenCompose(
|
| 157 | resources -> {
|
| 158 | List<CompletableFuture<Pair<Identifier, CuboidModel>>> result = new ArrayList<>(resources.size());
|
| 159 |
|
| 160 | for (Entry<Identifier, Resource> resource : resources.entrySet()) {
|
| 161 | result.add(CompletableFuture.supplyAsync(() -> {
|
| 162 | Identifier modelId = MODEL_LISTER.fileToId(resource.getKey());
|
| 163 |
|
| 164 | try (Reader reader = resource.getValue().openAsReader()) {
|
| 165 | return Pair.of(modelId, CuboidModel.fromStream(reader));
|
| 166 | } catch (Exception e) {
|
| 167 | LOGGER.error("Failed to load model {}", resource.getKey(), e);
|
| 168 | return null;
|
| 169 | }
|
| 170 | }, executor));
|
| 171 | }
|
| 172 |
|
| 173 | return Util.sequence(result)
|
| 174 | .thenApply(pairs -> pairs.stream().filter(Objects::nonNull).collect(Collectors.toUnmodifiableMap(Pair::getFirst, Pair::getSecond)));
|
| 175 | }
|
| 176 | );
|
| 177 | }
|
| 178 |
|
| 179 | private static ModelManager.ResolvedModels discoverModelDependencies(
|
| 180 | final Map<Identifier, UnbakedModel> allModels,
|
| 181 | final BlockStateModelLoader.LoadedModels blockStateModels,
|
| 182 | final ClientItemInfoLoader.LoadedClientInfos itemInfos
|
| 183 | ) {
|
| 184 | try (Zone ignored = Profiler.get().zone("dependencies")) {
|
| 185 | ModelDiscovery result = new ModelDiscovery(allModels, MissingCuboidModel.missingModel());
|
| 186 | result.addSpecialModel(ItemModelGenerator.GENERATED_ITEM_MODEL_ID, new ItemModelGenerator());
|
| 187 | blockStateModels.models().values().forEach(result::addRoot);
|
| 188 | itemInfos.contents().values().forEach(info -> result.addRoot(info.model()));
|
| 189 | return new ModelManager.ResolvedModels(result.missingModel(), result.resolve());
|
| 190 | }
|
| 191 | }
|
| 192 |
|
| 193 | private static CompletableFuture<ModelManager.ReloadState> loadModels(
|
| 194 | final SpriteLoader.Preparations blockAtlas,
|
| 195 | final SpriteLoader.Preparations itemAtlas,
|
| 196 | final ModelBakery bakery,
|
| 197 | final LoadedBlockModels blockModels,
|
| 198 | final Object2IntMap<BlockState> modelGroups,
|
| 199 | final EntityModelSet entityModelSet,
|
| 200 | final Executor taskExecutor
|
| 201 | ) {
|
| 202 | MaterialBaker materialBaker = new MaterialBaker(blockAtlas, itemAtlas);
|
| 203 | CompletableFuture<ModelBakery.BakingResult> bakedStateResults = bakery.bakeModels(materialBaker, taskExecutor);
|
| 204 | CompletableFuture<Map<BlockState, BlockModel>> bakedModelsFuture = bakedStateResults.thenCompose(
|
| 205 | bakingResult -> blockModels.bake(bakingResult::getBlockStateModel, bakingResult.missingModels().block(), taskExecutor)
|
| 206 | );
|
| 207 | return bakedStateResults.thenCombine(bakedModelsFuture, (bakingResult, bakedModels) -> {
|
| 208 | Map<Fluid, FluidModel> fluidModels = FluidStateModelSet.bake(materialBaker);
|
| 209 | materialBaker.logMissingTextures();
|
| 210 | Map<BlockState, BlockStateModel> modelByStateCache = createBlockStateToModelDispatch(bakingResult.blockStateModels(), bakingResult.missingModels().block());
|
| 211 | return new ModelManager.ReloadState(bakingResult, modelGroups, modelByStateCache, (Map<BlockState, BlockModel>)bakedModels, fluidModels, entityModelSet);
|
| 212 | });
|
| 213 | }
|
| 214 |
|
| 215 | private static Map<BlockState, BlockStateModel> createBlockStateToModelDispatch(
|
| 216 | final Map<BlockState, BlockStateModel> bakedModels, final BlockStateModel missingModel
|
| 217 | ) {
|
| 218 | try (Zone ignored = Profiler.get().zone("block state dispatch")) {
|
| 219 | Map<BlockState, BlockStateModel> modelByStateCache = new IdentityHashMap<>(bakedModels);
|
| 220 |
|
| 221 | for (Block block : BuiltInRegistries.BLOCK) {
|
| 222 | block.getStateDefinition().getPossibleStates().forEach(state -> {
|
| 223 | if (bakedModels.putIfAbsent(state, missingModel) == null) {
|
| 224 | LOGGER.warn("Missing model for variant: '{}'", state);
|
| 225 | }
|
| 226 | });
|
| 227 | }
|
| 228 |
|
| 229 | return modelByStateCache;
|
| 230 | }
|
| 231 | }
|
| 232 |
|
| 233 | private static Object2IntMap<BlockState> buildModelGroups(final BlockColors blockColors, final BlockStateModelLoader.LoadedModels blockStateModels) {
|
| 234 | try (Zone ignored = Profiler.get().zone("block groups")) {
|
| 235 | return ModelGroupCollector.build(blockColors, blockStateModels);
|
| 236 | }
|
| 237 | }
|
| 238 |
|
| 239 | private void apply(final ModelManager.ReloadState preparations) {
|
| 240 | ModelBakery.BakingResult bakedModels = preparations.bakedModels;
|
| 241 | this.bakedItemStackModels = bakedModels.itemStackModels();
|
| 242 | this.itemProperties = bakedModels.itemProperties();
|
| 243 | this.modelGroups = preparations.modelGroups;
|
| 244 | this.missingModels = bakedModels.missingModels();
|
| 245 | this.blockStateModelSet = new BlockStateModelSet(preparations.blockStateModels, this.missingModels.block());
|
| 246 | this.blockModelSet = new BlockModelSet(this.blockStateModelSet, preparations.blockModels, this.blockColors);
|
| 247 | this.fluidStateModelSet = new FluidStateModelSet(preparations.fluidModels, this.missingModels.fluid());
|
| 248 | this.entityModelSet = preparations.entityModelSet;
|
| 249 | }
|
| 250 |
|
| 251 | public boolean requiresRender(final BlockState oldState, final BlockState newState) {
|
| 252 | if (oldState == newState) {
|
| 253 | return false;
|
| 254 | }
|
| 255 |
|
| 256 | int oldModelGroup = this.modelGroups.getInt(oldState);
|
| 257 | if (oldModelGroup != -1) {
|
| 258 | int newModelGroup = this.modelGroups.getInt(newState);
|
| 259 | if (oldModelGroup == newModelGroup) {
|
| 260 | FluidState oldFluidState = oldState.getFluidState();
|
| 261 | FluidState newFluidState = newState.getFluidState();
|
| 262 | return oldFluidState != newFluidState;
|
| 263 | }
|
| 264 | }
|
| 265 |
|
| 266 | return true;
|
| 267 | }
|
| 268 |
|
| 269 | public Supplier<EntityModelSet> entityModels() {
|
| 270 | return () -> this.entityModelSet;
|
| 271 | }
|
| 272 |
|
| 273 | @Environment(EnvType.CLIENT)
|
| 274 | private record ReloadState(
|
| 275 | ModelBakery.BakingResult bakedModels,
|
| 276 | Object2IntMap<BlockState> modelGroups,
|
| 277 | Map<BlockState, BlockStateModel> blockStateModels,
|
| 278 | Map<BlockState, BlockModel> blockModels,
|
| 279 | Map<Fluid, FluidModel> fluidModels,
|
| 280 | EntityModelSet entityModelSet
|
| 281 | ) {
|
| 282 | }
|
| 283 |
|
| 284 | @Environment(EnvType.CLIENT)
|
| 285 | private record ResolvedModels(ResolvedModel missing, Map<Identifier, ResolvedModel> models) {
|
| 286 | }
|
| 287 | }
|
| 288 |
|