1.21.11 Mounts of Mayhem Release

Lots of rendering related changes, specifically for BackedQuad and IQuadTransformers.
Removed our deprecated model generators, modders should have been using vanilla's for a while.
This commit is contained in:
LexManos committed 2025-12-09 18:28:42 -08:00
1 parent 17e1002e86
commit 01bfc33b28
698 files changed
+4892 -10126

No files matched your search

@@ -129,7 +129,7 @@ public class ClientCommandHandler {
},
player.position(),
player.getRotationVector(),
player.getPermissionLevel(),
player.permissions(),
player.getName().getString(),
player.getDisplayName(),
player
@@ -12,9 +12,10 @@ import net.minecraft.commands.CommandSourceStack;
import net.minecraft.core.RegistryAccess;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.permissions.PermissionSet;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.Vec2;
@@ -30,7 +31,7 @@ import java.util.stream.Collectors;
* overrides for {@link CommandSourceStack} so that the methods will run successfully client side
*/
public class ClientCommandSourceStack extends CommandSourceStack {
public ClientCommandSourceStack(CommandSource source, Vec3 position, Vec2 rotation, int permission, String plainTextName, Component displayName, Entity executing) {
public ClientCommandSourceStack(CommandSource source, Vec3 position, Vec2 rotation, PermissionSet permission, String plainTextName, Component displayName, Entity executing) {
super(source, position, rotation, null, permission, plainTextName, displayName, null, executing);
}
@@ -89,7 +90,7 @@ public class ClientCommandSourceStack extends CommandSourceStack {
* {@return the advancement from the id from the client side where the advancement needs to be visible to the player}
*/
@Override
public AdvancementHolder getAdvancement(ResourceLocation id) {
public AdvancementHolder getAdvancement(Identifier id) {
return Minecraft.getInstance().getConnection().getAdvancements().get(id);
}
@@ -7,7 +7,7 @@ package net.minecraftforge.client;
import net.minecraft.client.renderer.chunk.ChunkSectionLayer;
import net.minecraft.client.resources.model.UnbakedGeometry;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.client.event.ModelEvent;
import net.minecraftforge.client.event.RegisterClientReloadListenersEvent;
@@ -38,7 +38,7 @@ public class ClientForgeMod {
event.register(forgeRL("item_unlit"), ChunkSectionLayer.TRANSLUCENT, ForgeRenderTypes.ITEM_UNSORTED_UNLIT_TRANSLUCENT.get());
}
private static ResourceLocation forgeRL(String path) {
return ResourceLocation.fromNamespaceAndPath("forge", path);
private static Identifier forgeRL(String path) {
return Identifier.fromNamespaceAndPath("forge", path);
}
}
@@ -1,56 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client;
import net.minecraft.client.renderer.DimensionSpecialEffects;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
import net.minecraftforge.client.event.RegisterDimensionSpecialEffectsEvent;
import org.jetbrains.annotations.ApiStatus;
import java.util.HashMap;
import java.util.Map;
/**
* Manager for {@link DimensionSpecialEffects} instances.
* <p>
* Provides a lookup by dimension type.
*/
public final class DimensionSpecialEffectsManager {
private DimensionSpecialEffectsManager() {}
private static Map<ResourceLocation, DimensionSpecialEffects> EFFECTS;
private static DimensionSpecialEffects DEFAULT_EFFECTS;
/**
* Finds the {@link DimensionSpecialEffects} for a given dimension type, or the default if none is registered.
*/
public static DimensionSpecialEffects getForType(ResourceLocation type) {
return EFFECTS.getOrDefault(type, DEFAULT_EFFECTS);
}
@ApiStatus.Internal
public static void init() {
var effects = new HashMap<ResourceLocation, DimensionSpecialEffects>();
DEFAULT_EFFECTS = preRegisterVanillaEffects(effects);
var event = new RegisterDimensionSpecialEffectsEvent(effects);
RegisterDimensionSpecialEffectsEvent.BUS.post(event);
EFFECTS = Map.copyOf(effects);
}
/**
* Pre-registers vanilla dimension effects and returns the default fallback effects instance.
* <p>
* Borrowed from {@link DimensionSpecialEffects#EFFECTS}.
*/
private static DimensionSpecialEffects preRegisterVanillaEffects(Map<ResourceLocation, DimensionSpecialEffects> effects) {
var overworldEffects = new DimensionSpecialEffects.OverworldEffects();
effects.put(BuiltinDimensionTypes.OVERWORLD_EFFECTS, overworldEffects);
effects.put(BuiltinDimensionTypes.NETHER_EFFECTS, new DimensionSpecialEffects.NetherEffects());
effects.put(BuiltinDimensionTypes.END_EFFECTS, new DimensionSpecialEffects.EndEffects());
return overworldEffects;
}
}
@@ -5,7 +5,7 @@
package net.minecraftforge.client;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.world.entity.EntityType;
import net.minecraftforge.client.event.RegisterEntitySpectatorShadersEvent;
import org.jetbrains.annotations.ApiStatus;
@@ -24,19 +24,19 @@ import java.util.Map;
public final class EntitySpectatorShaderManager {
private EntitySpectatorShaderManager() {}
private static @Nullable Map<EntityType<?>, ResourceLocation> SHADERS;
private static @Nullable Map<EntityType<?>, Identifier> SHADERS;
/**
* Finds the path to the spectator mode shader used for the specified entity type, or null if none is registered.
*/
public static @Nullable ResourceLocation get(EntityType<?> entityType) {
public static @Nullable Identifier get(EntityType<?> entityType) {
assert SHADERS != null;
return SHADERS.get(entityType);
}
@ApiStatus.Internal
public static void init() {
var shaders = new HashMap<EntityType<?>, ResourceLocation>();
var shaders = new HashMap<EntityType<?>, Identifier>();
RegisterEntitySpectatorShadersEvent.BUS.post(new RegisterEntitySpectatorShadersEvent(shaders));
SHADERS = Map.copyOf(shaders);
}
@@ -16,7 +16,7 @@ import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.datafixers.util.Either;
import com.mojang.math.Transformation;
import net.minecraft.FileUtil;
import net.minecraft.util.FileUtil;
import net.minecraft.client.Camera;
import net.minecraft.client.DeltaTracker;
import net.minecraft.client.Minecraft;
@@ -51,6 +51,7 @@ import net.minecraft.client.renderer.LevelRenderer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderPipelines;
import net.minecraft.client.renderer.SubmitNodeCollector;
import net.minecraft.client.renderer.block.model.BlockModelPart;
import net.minecraft.client.renderer.chunk.ChunkSectionLayer;
import net.minecraft.client.renderer.entity.state.HumanoidRenderState;
import net.minecraft.client.renderer.fog.FogData;
@@ -77,7 +78,7 @@ import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.FormattedText;
import net.minecraft.network.chat.PlayerChatMessage;
import net.minecraft.network.protocol.status.ServerStatus;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.server.packs.metadata.MetadataSectionType;
import net.minecraft.server.packs.resources.ReloadableResourceManager;
import net.minecraft.server.packs.resources.Resource;
@@ -183,7 +184,7 @@ public class ForgeHooksClient {
private static final Logger LOGGER = LogManager.getLogger();
private static final Marker CLIENTHOOKS = MarkerManager.getMarker("CLIENTHOOKS");
//private static final ResourceLocation ITEM_GLINT = new ResourceLocation("textures/misc/enchanted_item_glint.png");
//private static final Identifier ITEM_GLINT = new Identifier("textures/misc/enchanted_item_glint.png");
/**
* Contains the *extra* GUI layers.
@@ -192,7 +193,7 @@ public class ForgeHooksClient {
private static final Stack<Screen> guiLayers = new Stack<>();
public static void resizeGuiLayers(Minecraft minecraft, int width, int height) {
guiLayers.forEach(screen -> screen.resize(minecraft, width, height));
guiLayers.forEach(screen -> screen.resize(width, height));
}
public static void clearGuiLayers(Minecraft minecraft) {
@@ -210,7 +211,7 @@ public class ForgeHooksClient {
if (minecraft.screen != null)
guiLayers.push(minecraft.screen);
minecraft.screen = Objects.requireNonNull(screen);
screen.init(minecraft, minecraft.getWindow().getGuiScaledWidth(), minecraft.getWindow().getGuiScaledHeight());
screen.init(minecraft.getWindow().getGuiScaledWidth(), minecraft.getWindow().getGuiScaledHeight());
minecraft.getNarrator().saySystemNow(screen.getNarrationMessage());
}
@@ -241,7 +242,7 @@ public class ForgeHooksClient {
}
/*
public static ResourceLocation getArmorTexture(Entity entity, ItemStack armor, EquipmentSlot slot, ArmorMaterial.Layer layer, boolean inner) {
public static Identifier getArmorTexture(Entity entity, ItemStack armor, EquipmentSlot slot, ArmorMaterial.Layer layer, boolean inner) {
var result = armor.getItem().getArmorTexture(armor, entity, slot, layer, inner);
return result != null ? result : layer.texture(inner);
}
@@ -337,9 +338,9 @@ public class ForgeHooksClient {
public static Vector3f getFogColor(Camera camera, float partialTick, ClientLevel level, int renderDistance, float darkenWorldAmount, float fogRed, float fogGreen, float fogBlue) {
// Modify fog color depending on the fluid
FluidState state = level.getFluidState(camera.getBlockPosition());
FluidState state = level.getFluidState(camera.blockPosition());
Vector3f fluidFogColor = new Vector3f(fogRed, fogGreen, fogBlue);
if (camera.getPosition().y < (double)((float)camera.getBlockPosition().getY() + state.getHeight(level, camera.getBlockPosition())))
if (camera.position().y < (double)((float)camera.blockPosition().getY() + state.getHeight(level, camera.blockPosition())))
fluidFogColor = IClientFluidTypeExtensions.of(state).modifyFogColor(camera, partialTick, level, renderDistance, darkenWorldAmount, fluidFogColor);
var event = ViewportEvent.ComputeFogColor.BUS.fire(new ViewportEvent.ComputeFogColor(camera, partialTick, fluidFogColor.x(), fluidFogColor.y(), fluidFogColor.z()));
@@ -350,8 +351,8 @@ public class ForgeHooksClient {
public static Vector4f setupFog(FogType type, Camera camera, DeltaTracker delta, FogData data, Vector4f color) {
// Modify fog rendering depending on the fluid
FluidState state = camera.getEntity().level().getFluidState(camera.getBlockPosition());
if (camera.getPosition().y < (double)((float)camera.getBlockPosition().getY() + state.getHeight(camera.getEntity().level(), camera.getBlockPosition())))
FluidState state = camera.entity().level().getFluidState(camera.blockPosition());
if (camera.position().y < (double)((float)camera.blockPosition().getY() + state.getHeight(camera.entity().level(), camera.blockPosition())))
IClientFluidTypeExtensions.of(state).modifyFogRender(camera, type, delta.getRealtimeDeltaTicks(), data, color);
ViewportEvent.RenderFog.BUS.post(new ViewportEvent.RenderFog(type, camera, delta.getRealtimeDeltaTicks(), data, color));
@@ -368,7 +369,7 @@ public class ForgeHooksClient {
public static TextureAtlasSprite[] getFluidSprites(BlockAndTintGetter level, BlockPos pos, FluidState fluidStateIn) {
IClientFluidTypeExtensions props = IClientFluidTypeExtensions.of(fluidStateIn);
ResourceLocation overlayTexture = props.getOverlayTexture(fluidStateIn, level, pos);
Identifier overlayTexture = props.getOverlayTexture(fluidStateIn, level, pos);
var atlas = Minecraft.getInstance().getAtlasManager().getAtlasOrThrow(AtlasIds.BLOCKS);
return new TextureAtlasSprite[] {
atlas.getSprite(props.getStillTexture(fluidStateIn, level, pos)),
@@ -400,14 +401,14 @@ public class ForgeHooksClient {
return CustomizeGuiOverlayEvent.BossEventProgress.BUS.post(evt) ? null : evt;
}
public static void onCustomizeChatEvent(GuiGraphics guiGraphics, ChatComponent chat, Window window, int mouseX, int mouseY, int tickCount) {
public static void onCustomizeChatEvent(GuiGraphics guiGraphics, ChatComponent chat, Window window, int mouseX, int mouseY, int tickCount, Font font) {
var minecraft = Minecraft.getInstance();
var evt = new CustomizeGuiOverlayEvent.Chat(window, guiGraphics, minecraft.getDeltaTracker().getRealtimeDeltaTicks(), 0, chat.getHeight() - 40);
CustomizeGuiOverlayEvent.Chat.BUS.post(evt);
guiGraphics.pose().pushMatrix();
// We give the absolute Y position of the chat component in the event and account for the chat component's own offsetting here.
guiGraphics.pose().translate(evt.getPosX(), (float) ((evt.getPosY() - chat.getHeight() + 40) / chat.getScale()));
chat.render(guiGraphics, tickCount, mouseX, mouseY, false);
chat.render(guiGraphics, font, tickCount, mouseX, mouseY, false, false);
guiGraphics.pose().popMatrix();
}
@@ -463,7 +464,7 @@ public class ForgeHooksClient {
return IClientMobEffectExtensions.of(effectInstance).isVisibleInInventory(effectInstance);
}
public static Set<MetadataSectionType<?>> getAtlastMetadataSections(ResourceLocation atlasId, Set<MetadataSectionType<?>> vanilla) {
public static Set<MetadataSectionType<?>> getAtlastMetadataSections(Identifier atlasId, Set<MetadataSectionType<?>> vanilla) {
var ret = new HashSet<>(vanilla);
ret.add(ForgeTextureMetadata.TYPE);
@@ -473,7 +474,7 @@ public class ForgeHooksClient {
}
@Nullable
public static SpriteContents loadSpriteContents(ResourceLocation name, Resource resource, FrameSize frameSize, NativeImage image, List<MetadataSectionType.WithValue<?>> metadata) {
public static SpriteContents loadSpriteContents(Identifier name, Resource resource, FrameSize frameSize, NativeImage image, List<MetadataSectionType.WithValue<?>> metadata) {
for (var meta : metadata) {
var forgeMeta = meta.unwrapToType(ForgeTextureMetadata.TYPE).orElse(null);
if (forgeMeta != null && forgeMeta.loader() != null)
@@ -483,12 +484,12 @@ public class ForgeHooksClient {
}
@Nullable
public static TextureAtlasSprite loadTextureAtlasSprite(ResourceLocation atlasName, SpriteContents contents, int atlasWidth, int atlasHeight, int spriteX, int spriteY, int mipmapLevel) {
public static TextureAtlasSprite loadTextureAtlasSprite(Identifier atlasName, SpriteContents contents, int atlasWidth, int atlasHeight, int spriteX, int spriteY, int padding, int mipmapLevel) {
var forgeMeta = contents.getAdditionalMetadata(ForgeTextureMetadata.TYPE).orElse(null);
if (forgeMeta == null || forgeMeta.loader() == null)
return null;
return forgeMeta.loader().makeSprite(atlasName, contents, atlasWidth, atlasHeight, spriteX, spriteY, mipmapLevel);
return forgeMeta.loader().makeSprite(atlasName, contents, atlasWidth, atlasHeight, spriteX, spriteY, padding, mipmapLevel);
}
private static final Map<ModelLayerLocation, Supplier<LayerDefinition>> layerDefinitions = new HashMap<>();
@@ -506,7 +507,7 @@ public class ForgeHooksClient {
public static void processForgeListPingData(ServerStatus packet, ServerData target) {
packet.forgeData().ifPresentOrElse(forgeData -> {
final Map<String, String> mods = forgeData.getRemoteModData();
final Map<ResourceLocation, ServerStatusPing.ChannelData> remoteChannels = forgeData.getRemoteChannels();
final Map<Identifier, ServerStatusPing.ChannelData> remoteChannels = forgeData.getRemoteChannels();
final int fmlver = forgeData.getFMLNetworkVersion();
int wantedVer = NetworkInitialization.getVersion();
@@ -556,7 +557,7 @@ public class ForgeHooksClient {
}, () -> target.forgeData = new ExtendedServerListData("VANILLA", NetworkRegistry.canConnectToVanillaServer(),0, null));
}
private static final ResourceLocation ICON_SHEET = ResourceLocation.fromNamespaceAndPath(ForgeVersion.MOD_ID, "textures/gui/icons.png");
private static final Identifier ICON_SHEET = Identifier.fromNamespaceAndPath(ForgeVersion.MOD_ID, "textures/gui/icons.png");
public static void drawForgePingInfo(JoinMultiplayerScreen gui, ServerData target, GuiGraphics guiGraphics, int x, int y, int width, int relativeMouseX, int relativeMouseY) {
int idx;
String tooltip;
@@ -658,7 +659,7 @@ public class ForgeHooksClient {
return stackFont == null ? fallbackFont : stackFont;
}
public static @Nullable RenderTooltipEvent.Pre onRenderTooltipPre(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, int screenWidth, int screenHeight, @NotNull List<ClientTooltipComponent> components, @NotNull Font fallbackFont, @NotNull ClientTooltipPositioner positioner, @Nullable ResourceLocation background) {
public static @Nullable RenderTooltipEvent.Pre onRenderTooltipPre(@NotNull ItemStack stack, GuiGraphics graphics, int x, int y, int screenWidth, int screenHeight, @NotNull List<ClientTooltipComponent> components, @NotNull Font fallbackFont, @NotNull ClientTooltipPositioner positioner, @Nullable Identifier background) {
var preEvent = new RenderTooltipEvent.Pre(stack, graphics, x, y, screenWidth, screenHeight, getTooltipFont(stack, fallbackFont), components, positioner, background);
return RenderTooltipEvent.Pre.BUS.post(preEvent) ? null : preEvent;
}
@@ -769,8 +770,8 @@ public class ForgeHooksClient {
);
}
public static ResourceLocation getShaderImportLocation(String basePath, boolean isRelative, String importPath) {
final var loc = ResourceLocation.parse(importPath);
public static Identifier getShaderImportLocation(String basePath, boolean isRelative, String importPath) {
final var loc = Identifier.parse(importPath);
final var normalised = FileUtil.normalizeResourcePath(
(isRelative ? basePath : "shaders/include/") + loc.getPath());
return loc.withPath(normalised);
@@ -793,7 +794,7 @@ public class ForgeHooksClient {
EntitySpectatorShaderManager.init();
ForgeHooksClient.onRegisterKeyMappings(mc.options);
//GuiOverlayManager.init();
DimensionSpecialEffectsManager.init();
//DimensionSpecialEffectsManager.init();
NamedRenderTypeManager.init();
ColorResolverManager.init();
ItemDecoratorHandler.init();
@@ -819,7 +820,7 @@ public class ForgeHooksClient {
if (name == null)
return null;
var loader = GeometryLoaderManager.get(ResourceLocation.parse(name));
var loader = GeometryLoaderManager.get(Identifier.parse(name));
if (loader == null)
throw new JsonParseException(String.format(Locale.ENGLISH, "Model loader '%s' not found. Registered loaders: %s", name, GeometryLoaderManager.getLoaderList()));
@@ -829,19 +830,19 @@ public class ForgeHooksClient {
@Nullable
public static ForgeBlockModelData deserializeBlockModel(JsonObject json, JsonDeserializationContext context) {
Optional<ResourceLocation> renderType = Optional.empty();
Optional<ResourceLocation> renderTypeFast = Optional.empty();
Optional<Identifier> renderType = Optional.empty();
Optional<Identifier> renderTypeFast = Optional.empty();
Optional<Map<String, Boolean>> visibility = Optional.empty();
var transform = Optional.ofNullable(GsonHelper.getAsObject(json, "transform", null, context, Transformation.class));
var renderTypeName = GsonHelper.getAsString(json, "render_type", null);
if (renderTypeName != null)
renderType = Optional.of(ResourceLocation.parse(renderTypeName));
renderType = Optional.of(Identifier.parse(renderTypeName));
var renderTypeFastName = GsonHelper.getAsString(json, "render_type_fast", null);
if (renderTypeFastName != null)
renderTypeFast = Optional.of(ResourceLocation.parse(renderTypeFastName));
renderTypeFast = Optional.of(Identifier.parse(renderTypeFastName));
var visibilityJson = GsonHelper.getAsJsonObject(json, "visibility", null);
if (visibilityJson != null) {
@@ -878,7 +879,7 @@ public class ForgeHooksClient {
return group;
}
@Override public ResolvedModel getModel(ResourceLocation p_397309_) {
@Override public ResolvedModel getModel(Identifier p_397309_) {
return parent.getModel(p_397309_);
}
@@ -891,9 +892,19 @@ public class ForgeHooksClient {
public <T> T compute(SharedOperationKey<T> p_395456_) {
return parent.compute(p_395456_);
}
@Override
public BlockModelPart missingBlockModelPart() {
return parent.missingBlockModelPart();
}
@Override
public PartCache parts() {
return parent.parts();
}
}
public static void addFramePass(ResourceLocation rl, FramePassManager.PassDefinition definition) {
public static void addFramePass(Identifier rl, FramePassManager.PassDefinition definition) {
FramePassManager.addPass(rl, definition);
}
}
@@ -5,34 +5,29 @@
package net.minecraftforge.client;
import com.mojang.blaze3d.opengl.GlConst;
import com.mojang.blaze3d.pipeline.BlendFunction;
import com.mojang.blaze3d.pipeline.RenderPipeline;
import com.mojang.blaze3d.platform.DepthTestFunction;
import com.mojang.blaze3d.platform.DestFactor;
import com.mojang.blaze3d.platform.SourceFactor;
import com.mojang.blaze3d.systems.GpuDevice;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.textures.GpuTexture;
import com.mojang.blaze3d.textures.GpuTextureView;
import com.mojang.blaze3d.textures.AddressMode;
import com.mojang.blaze3d.textures.FilterMode;
import com.mojang.blaze3d.textures.GpuSampler;
import com.mojang.blaze3d.textures.TextureFormat;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.util.Util;
import net.minecraft.client.renderer.RenderPipelines;
import net.minecraft.client.renderer.RenderStateShard.TextureStateShard;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.rendertype.RenderSetup;
import net.minecraft.client.renderer.rendertype.RenderType;
import net.minecraft.client.renderer.texture.TextureAtlas;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.common.util.NonNullLazy;
import net.minecraftforge.common.util.NonNullSupplier;
import net.minecraftforge.fml.earlydisplay.DisplayWindow;
import java.util.function.Function;
import org.jetbrains.annotations.ApiStatus;
import org.lwjgl.opengl.GL30C;
public enum ForgeRenderTypes {
ITEM_LAYERED_SOLID(()-> getItemLayeredSolid(blockAtlas())),
@@ -56,42 +51,42 @@ public enum ForgeRenderTypes {
public static boolean enableTextTextureLinearFiltering = false;
@SuppressWarnings("deprecation")
private static ResourceLocation blockAtlas() {
private static Identifier blockAtlas() {
return TextureAtlas.LOCATION_BLOCKS;
}
/**
* @return A RenderType fit for multi-layer solid item rendering.
*/
public static RenderType getItemLayeredSolid(ResourceLocation textureLocation) {
public static RenderType getItemLayeredSolid(Identifier textureLocation) {
return Internal.LAYERED_ITEM_SOLID.apply(textureLocation);
}
/**
* @return A RenderType fit for multi-layer cutout item item rendering.
*/
public static RenderType getItemLayeredCutout(ResourceLocation textureLocation) {
public static RenderType getItemLayeredCutout(Identifier textureLocation) {
return Internal.LAYERED_ITEM_CUTOUT.apply(textureLocation);
}
/**
* @return A RenderType fit for multi-layer cutout-mipped item rendering.
*/
public static RenderType getItemLayeredCutoutMipped(ResourceLocation textureLocation) {
public static RenderType getItemLayeredCutoutMipped(Identifier textureLocation) {
return Internal.LAYERED_ITEM_CUTOUT_MIPPED.apply(textureLocation);
}
/**
* @return A RenderType fit for multi-layer translucent item rendering.
*/
public static RenderType getItemLayeredTranslucent(ResourceLocation textureLocation) {
public static RenderType getItemLayeredTranslucent(Identifier textureLocation) {
return Internal.LAYERED_ITEM_TRANSLUCENT.apply(textureLocation);
}
/**
* @return A RenderType fit for translucent item/entity rendering, but with depth sorting disabled.
*/
public static RenderType getUnsortedTranslucent(ResourceLocation textureLocation) {
public static RenderType getUnsortedTranslucent(Identifier textureLocation) {
return Internal.UNSORTED_TRANSLUCENT.apply(textureLocation);
}
@@ -99,7 +94,7 @@ public enum ForgeRenderTypes {
* @return A RenderType fit for translucent item/entity rendering, but with diffuse lighting disabled
* so that fullbright quads look correct.
*/
public static RenderType getUnlitTranslucent(ResourceLocation textureLocation) {
public static RenderType getUnlitTranslucent(Identifier textureLocation) {
return Internal.UNLIT_TRANSLUCENT_SORTED.apply(textureLocation);
}
@@ -108,68 +103,68 @@ public enum ForgeRenderTypes {
* so that fullbright quads look correct.
* @param sortingEnabled If false, depth sorting will not be performed.
*/
public static RenderType getUnlitTranslucent(ResourceLocation textureLocation, boolean sortingEnabled) {
public static RenderType getUnlitTranslucent(Identifier textureLocation, boolean sortingEnabled) {
return (sortingEnabled ? Internal.UNLIT_TRANSLUCENT_SORTED : Internal.UNLIT_TRANSLUCENT_UNSORTED).apply(textureLocation);
}
/**
* @return Same as {@link RenderType#entityCutout(ResourceLocation)}, but with mipmapping enabled.
* @return Same as {@link RenderType#entityCutout(Identifier)}, but with mipmapping enabled.
*/
public static RenderType getEntityCutoutMipped(ResourceLocation textureLocation) {
public static RenderType getEntityCutoutMipped(Identifier textureLocation) {
return Internal.LAYERED_ITEM_CUTOUT_MIPPED.apply(textureLocation);
}
/**
* @see #enableTextTextureLinearFiltering
*
* @return Replacement of {@link RenderType#text(ResourceLocation)}, but with optional linear texture filtering.
* @return Replacement of {@link RenderType#text(Identifier)}, but with optional linear texture filtering.
*/
public static RenderType getText(ResourceLocation locationIn) {
public static RenderType getText(Identifier locationIn) {
return Internal.TEXT.apply(locationIn);
}
/**
* @see #enableTextTextureLinearFiltering
*
* @return Replacement of {@link RenderType#textIntensity(ResourceLocation)}, but with optional linear texture filtering.
* @return Replacement of {@link RenderType#textIntensity(Identifier)}, but with optional linear texture filtering.
*/
public static RenderType getTextIntensity(ResourceLocation locationIn) {
public static RenderType getTextIntensity(Identifier locationIn) {
return Internal.TEXT_INTENSITY.apply(locationIn);
}
/**
* @see #enableTextTextureLinearFiltering
*
* @return Replacement of {@link RenderType#textPolygonOffset(ResourceLocation)}, but with optional linear texture filtering.
* @return Replacement of {@link RenderType#textPolygonOffset(Identifier)}, but with optional linear texture filtering.
*/
public static RenderType getTextPolygonOffset(ResourceLocation locationIn) {
public static RenderType getTextPolygonOffset(Identifier locationIn) {
return Internal.TEXT_POLYGON_OFFSET.apply(locationIn);
}
/**
* @see #enableTextTextureLinearFiltering
*
* @return Replacement of {@link RenderType#textIntensityPolygonOffset(ResourceLocation)}, but with optional linear texture filtering.
* @return Replacement of {@link RenderType#textIntensityPolygonOffset(Identifier)}, but with optional linear texture filtering.
*/
public static RenderType getTextIntensityPolygonOffset(ResourceLocation locationIn) {
public static RenderType getTextIntensityPolygonOffset(Identifier locationIn) {
return Internal.TEXT_INTENSITY_POLYGON_OFFSET.apply(locationIn);
}
/**
* @see #enableTextTextureLinearFiltering
*
* @return Replacement of {@link RenderType#textSeeThrough(ResourceLocation)}, but with optional linear texture filtering.
* @return Replacement of {@link RenderType#textSeeThrough(Identifier)}, but with optional linear texture filtering.
*/
public static RenderType getTextSeeThrough(ResourceLocation locationIn) {
return Internal.TEXT_SEETHROUGH.apply(locationIn);
public static RenderType getTextSeeThrough(Identifier locationIn) {
return Internal.TEXT_SEE_THROUGH.apply(locationIn);
}
/**
* @see #enableTextTextureLinearFiltering
*
* @return Replacement of {@link RenderType#textIntensitySeeThrough(ResourceLocation)}, but with optional linear texture filtering.
* @return Replacement of {@link RenderType#textIntensitySeeThrough(Identifier)}, but with optional linear texture filtering.
*/
public static RenderType getTextIntensitySeeThrough(ResourceLocation locationIn) {
public static RenderType getTextIntensitySeeThrough(Identifier locationIn) {
return Internal.TEXT_INTENSITY_SEE_THROUGH.apply(locationIn);
}
@@ -202,217 +197,175 @@ public enum ForgeRenderTypes {
// This was done for the sake of consistency, but it may be wrong. Need validation.
// Additionally, I am unsure if I have set all the flags correctly. Most of these don't have full docs on
// what they are meant to be used for, so I had to guess how to remap them to the new system.
private static abstract class Internal extends RenderType {
// TODO: [VEN] This is really just here because argument names are stripped I guess? Just as a weird doc thing?
private Internal(String name, int bufferSize, boolean affectsCrumbling, boolean sortOnUpload, Runnable setupState, Runnable clearState) {
super(name, bufferSize, affectsCrumbling, sortOnUpload, setupState, clearState);
throw new IllegalStateException("This class must not be instantiated");
}
public static Function<ResourceLocation, RenderType> UNSORTED_TRANSLUCENT = Util.memoize(Internal::unsortedTranslucent);
private static RenderType unsortedTranslucent(ResourceLocation textureLocation) {
return create("forge_unsorted_translucent",
TRANSIENT_BUFFER_SIZE,
true,
false,
RenderPipelines.ENTITY_TRANSLUCENT,
CompositeState.builder()
.setTextureState(new TextureStateShard(textureLocation, false))
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true));
}
public static Function<ResourceLocation, RenderType> UNLIT_TRANSLUCENT_SORTED = Util.memoize(Internal::unlitTranslucentSorted);
private static RenderType unlitTranslucentSorted(ResourceLocation textureLocation) {
return create("forge_unlit_translucent_sorted",
TRANSIENT_BUFFER_SIZE,
true,
true,
RenderPipelines.ENTITY_TRANSLUCENT,
CompositeState.builder()
.setTextureState(new TextureStateShard(textureLocation, false))
.setLightmapState(NO_LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true));
}
public static Function<ResourceLocation, RenderType> UNLIT_TRANSLUCENT_UNSORTED = Util.memoize(Internal::unlitTranslucentUnsorted);
private static RenderType unlitTranslucentUnsorted(ResourceLocation textureLocation) {
return create("forge_unlit_translucent_sorted",
TRANSIENT_BUFFER_SIZE,
true,
false,
RenderPipelines.ENTITY_TRANSLUCENT,
CompositeState.builder()
.setTextureState(new TextureStateShard(textureLocation, false))
.setLightmapState(NO_LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true));
}
public static Function<ResourceLocation, RenderType> LAYERED_ITEM_SOLID = Util.memoize(Internal::layeredItemSolid);
private static RenderType layeredItemSolid(ResourceLocation locationIn) {
return create(
"forge_layered_item_soild",
TRANSIENT_BUFFER_SIZE,
true,
false,
RenderPipelines.ENTITY_SOLID,
CompositeState.builder()
.setTextureState(new TextureStateShard(locationIn, false))
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true)
private static abstract class Internal {
public static Function<Identifier, RenderType> UNSORTED_TRANSLUCENT = Util.memoize(Internal::unsortedTranslucent);
private static RenderType unsortedTranslucent(Identifier texture) {
return RenderType.create("forge_unsorted_translucent",
RenderSetup.builder(RenderPipelines.ENTITY_TRANSLUCENT)
.bufferSize(RenderType.TRANSIENT_BUFFER_SIZE)
.withTexture("Sampler0", texture)
.bufferSize(RenderType.TRANSIENT_BUFFER_SIZE)
.affectsCrumbling()
.useLightmap()
.useOverlay()
.setOutline(RenderSetup.OutlineProperty.AFFECTS_OUTLINE)
.createRenderSetup()
);
}
public static Function<ResourceLocation, RenderType> LAYERED_ITEM_CUTOUT = Util.memoize(Internal::layeredItemCutout);
private static RenderType layeredItemCutout(ResourceLocation locationIn) {
return create(
"forge_layered_item_cutout",
TRANSIENT_BUFFER_SIZE,
true,
false,
RenderPipelines.ENTITY_CUTOUT,
CompositeState.builder()
.setTextureState(new TextureStateShard(locationIn, false))
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true)
public static Function<Identifier, RenderType> UNLIT_TRANSLUCENT_SORTED = Util.memoize(Internal::unlitTranslucentSorted);
private static RenderType unlitTranslucentSorted(Identifier texture) {
return RenderType.create("forge_unlit_translucent_sorted",
RenderSetup.builder(RenderPipelines.ENTITY_TRANSLUCENT)
.bufferSize(RenderType.TRANSIENT_BUFFER_SIZE)
.affectsCrumbling()
.sortOnUpload()
.withTexture("Sampler0", texture)
.useOverlay()
.setOutline(RenderSetup.OutlineProperty.AFFECTS_OUTLINE)
.createRenderSetup()
);
}
public static Function<ResourceLocation, RenderType> LAYERED_ITEM_CUTOUT_MIPPED = Util.memoize(Internal::layeredItemCutoutMipped);
private static RenderType layeredItemCutoutMipped(ResourceLocation locationIn) {
return create(
"forge_layered_item_cutout_mipped",
TRANSIENT_BUFFER_SIZE,
true,
false,
RenderPipelines.ENTITY_SMOOTH_CUTOUT,
CompositeState.builder()
.setTextureState(new TextureStateShard(locationIn, true))
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true)
public static Function<Identifier, RenderType> UNLIT_TRANSLUCENT_UNSORTED = Util.memoize(Internal::unlitTranslucentUnsorted);
private static RenderType unlitTranslucentUnsorted(Identifier texture) {
return RenderType.create("forge_unlit_translucent_sorted",
RenderSetup.builder(RenderPipelines.ENTITY_TRANSLUCENT)
.bufferSize(RenderType.TRANSIENT_BUFFER_SIZE)
.affectsCrumbling()
.withTexture("Sampler0", texture)
.useOverlay()
.setOutline(RenderSetup.OutlineProperty.AFFECTS_OUTLINE)
.createRenderSetup()
);
}
public static Function<ResourceLocation, RenderType> LAYERED_ITEM_TRANSLUCENT = Util.memoize(Internal::layeredItemTranslucent);
private static RenderType layeredItemTranslucent(ResourceLocation locationIn) {
return create(
"forge_layered_item_translucent",
TRANSIENT_BUFFER_SIZE,
true,
true,
RenderPipelines.ITEM_ENTITY_TRANSLUCENT_CULL,
CompositeState.builder()
.setTextureState(new TextureStateShard(locationIn, false))
.setLightmapState(LIGHTMAP)
.setOverlayState(OVERLAY)
.createCompositeState(true)
public static Function<Identifier, RenderType> LAYERED_ITEM_SOLID = Util.memoize(Internal::layeredItemSolid);
private static RenderType layeredItemSolid(Identifier texture) {
return RenderType.create("forge_layered_item_soild",
RenderSetup.builder(RenderPipelines.ENTITY_SOLID)
.bufferSize(RenderType.TRANSIENT_BUFFER_SIZE)
.affectsCrumbling()
.withTexture("Sampler0", texture)
.useLightmap()
.useOverlay()
.setOutline(RenderSetup.OutlineProperty.AFFECTS_OUTLINE)
.createRenderSetup()
);
}
public static Function<ResourceLocation, RenderType> TEXT = Util.memoize(Internal::getText);
private static RenderType getText(ResourceLocation locationIn) {
return create(
"forge_text",
SMALL_BUFFER_SIZE,
false,
true,
RenderPipelines.TEXT,
CompositeState.builder()
.setTextureState(new CustomizableTextureState(locationIn, false))
.setLightmapState(LIGHTMAP)
.createCompositeState(false)
public static Function<Identifier, RenderType> LAYERED_ITEM_CUTOUT = Util.memoize(Internal::layeredItemCutout);
private static RenderType layeredItemCutout(Identifier texture) {
return RenderType.create("forge_layered_item_cutout",
RenderSetup.builder(RenderPipelines.ENTITY_CUTOUT)
.bufferSize(RenderType.TRANSIENT_BUFFER_SIZE)
.affectsCrumbling()
.withTexture("Sampler0", texture)
.useLightmap()
.useOverlay()
.setOutline(RenderSetup.OutlineProperty.AFFECTS_OUTLINE)
.createRenderSetup()
);
}
public static Function<ResourceLocation, RenderType> TEXT_INTENSITY = Util.memoize(Internal::getTextIntensity);
private static RenderType getTextIntensity(ResourceLocation locationIn) {
return create(
"forge_text_intensity",
SMALL_BUFFER_SIZE,
false,
false,
RenderPipelines.TEXT_INTENSITY,
CompositeState.builder()
.setTextureState(new CustomizableTextureState(locationIn, false))
.setLightmapState(LIGHTMAP)
.createCompositeState(false)
public static Function<Identifier, RenderType> LAYERED_ITEM_CUTOUT_MIPPED = Util.memoize(Internal::layeredItemCutoutMipped);
private static RenderType layeredItemCutoutMipped(Identifier texture) {
return RenderType.create("forge_layered_item_cutout_mipped",
RenderSetup.builder(RenderPipelines.ENTITY_SMOOTH_CUTOUT)
.bufferSize(RenderType.TRANSIENT_BUFFER_SIZE)
.affectsCrumbling()
.withTexture("Sampler0", texture) // Used to have mipmap = true
.useLightmap()
.useOverlay()
.setOutline(RenderSetup.OutlineProperty.AFFECTS_OUTLINE)
.createRenderSetup()
);
}
public static Function<ResourceLocation, RenderType> TEXT_POLYGON_OFFSET = Util.memoize(Internal::getTextPolygonOffset);
private static RenderType getTextPolygonOffset(ResourceLocation locationIn) {
return create(
"forge_text_polygon_offset",
TRANSIENT_BUFFER_SIZE,
false,
true,
RenderPipelines.TEXT_POLYGON_OFFSET,
CompositeState.builder()
.setTextureState(new CustomizableTextureState(locationIn, false))
.setLightmapState(LIGHTMAP)
.createCompositeState(false)
public static Function<Identifier, RenderType> LAYERED_ITEM_TRANSLUCENT = Util.memoize(Internal::layeredItemTranslucent);
private static RenderType layeredItemTranslucent(Identifier texture) {
return RenderType.create("forge_layered_item_translucent",
RenderSetup.builder(RenderPipelines.ITEM_ENTITY_TRANSLUCENT_CULL)
.bufferSize(RenderType.TRANSIENT_BUFFER_SIZE)
.affectsCrumbling()
.sortOnUpload()
.withTexture("Sampler0", texture)
.useLightmap()
.useOverlay()
.setOutline(RenderSetup.OutlineProperty.AFFECTS_OUTLINE)
.createRenderSetup()
);
}
public static Function<ResourceLocation, RenderType> TEXT_INTENSITY_POLYGON_OFFSET = Util.memoize(Internal::getTextIntensityPolygonOffset);
private static RenderType getTextIntensityPolygonOffset(ResourceLocation locationIn) {
return create(
"forge_text_intensity_polygon_offset",
TRANSIENT_BUFFER_SIZE,
false,
true,
RenderPipelines.TEXT_INTENSITY,
CompositeState.builder()
.setTextureState(new CustomizableTextureState(locationIn, false))
.setLightmapState(LIGHTMAP)
.createCompositeState(false)
public static Function<Identifier, RenderType> TEXT = Util.memoize(Internal::getText);
private static RenderType getText(Identifier texture) {
return RenderType.create(
"forge_text",
RenderSetup.builder(RenderPipelines.TEXT)
.withTexture("Sampler0", texture)
.useLightmap()
.bufferSize(RenderType.SMALL_BUFFER_SIZE)
.sortOnUpload() // This is what is different from RenderTypes.TEXT
.createRenderSetup()
);
}
public static Function<ResourceLocation, RenderType> TEXT_SEE_THROUGH = Util.memoize(Internal::getTextSeeThrough);
/**
* Use {@link #TEXT_SEE_THROUGH} instead.
*/
@Deprecated
public static Function<ResourceLocation, RenderType> TEXT_SEETHROUGH = TEXT_SEE_THROUGH;
private static RenderType getTextSeeThrough(ResourceLocation locationIn) {
return create(
"forge_text_see_through",
TRANSIENT_BUFFER_SIZE,
false,
false,
RenderPipelines.TEXT_SEE_THROUGH,
CompositeState.builder()
.setTextureState(new CustomizableTextureState(locationIn, false))
.setLightmapState(LIGHTMAP)
.createCompositeState(false)
public static Function<Identifier, RenderType> TEXT_INTENSITY = Util.memoize(Internal::getTextIntensity);
private static RenderType getTextIntensity(Identifier texture) {
return RenderType.create("forge_text_intensity",
RenderSetup.builder(RenderPipelines.TEXT_INTENSITY)
.bufferSize(RenderType.SMALL_BUFFER_SIZE)
.withTexture("Sampler0", texture)
.useLightmap()
.useOverlay()
.createRenderSetup()
);
}
public static Function<ResourceLocation, RenderType> TEXT_INTENSITY_SEE_THROUGH = Util.memoize(Internal::getTextIntensitySeeThrough);
/**
* Use {@link #TEXT_INTENSITY_SEE_THROUGH} instead.
*/
@SuppressWarnings("unused")
@Deprecated(forRemoval = true, since = "1.21.5")
public static Function<ResourceLocation, RenderType> TEXT_INTENSITY_SEETHROUGH = TEXT_INTENSITY_SEE_THROUGH;
private static RenderType getTextIntensitySeeThrough(ResourceLocation locationIn) {
return create(
"forge_text_intensity_see_through",
TRANSIENT_BUFFER_SIZE,
false,
true,
RenderPipelines.TEXT_INTENSITY_SEE_THROUGH,
CompositeState.builder()
.setTextureState(new CustomizableTextureState(locationIn, false))
.setLightmapState(LIGHTMAP)
.createCompositeState(false)
public static Function<Identifier, RenderType> TEXT_POLYGON_OFFSET = Util.memoize(Internal::getTextPolygonOffset);
private static RenderType getTextPolygonOffset(Identifier texture) {
return RenderType.create("forge_text_polygon_offset",
RenderSetup.builder(RenderPipelines.TEXT_POLYGON_OFFSET)
.bufferSize(RenderType.TRANSIENT_BUFFER_SIZE)
.sortOnUpload()
.withTexture("Sampler0", texture)
.useLightmap()
.createRenderSetup()
);
}
public static Function<Identifier, RenderType> TEXT_INTENSITY_POLYGON_OFFSET = Util.memoize(Internal::getTextIntensityPolygonOffset);
private static RenderType getTextIntensityPolygonOffset(Identifier texture) {
return RenderType.create("forge_text_intensity_polygon_offset",
RenderSetup.builder(RenderPipelines.TEXT_INTENSITY)
.bufferSize(RenderType.TRANSIENT_BUFFER_SIZE)
.sortOnUpload()
.withTexture("Sampler0", texture)
.useLightmap()
.createRenderSetup()
);
}
public static Function<Identifier, RenderType> TEXT_SEE_THROUGH = Util.memoize(Internal::getTextSeeThrough);
private static RenderType getTextSeeThrough(Identifier texture) {
return RenderType.create("forge_text_see_through",
RenderSetup.builder(RenderPipelines.TEXT_SEE_THROUGH)
.bufferSize(RenderType.TRANSIENT_BUFFER_SIZE)
.withTexture("Sampler0", texture)
.useLightmap()
.createRenderSetup()
);
}
public static Function<Identifier, RenderType> TEXT_INTENSITY_SEE_THROUGH = Util.memoize(Internal::getTextIntensitySeeThrough);
private static RenderType getTextIntensitySeeThrough(Identifier texture) {
return RenderType.create("forge_text_intensity_see_through",
RenderSetup.builder(RenderPipelines.TEXT_INTENSITY_SEE_THROUGH)
.bufferSize(RenderType.TRANSIENT_BUFFER_SIZE)
.sortOnUpload()
.withTexture("Sampler0", texture)
.useLightmap()
.createRenderSetup()
);
}
@@ -423,51 +376,22 @@ public enum ForgeRenderTypes {
.withDepthWrite(false)
.build();
private static final GpuSampler LOADING_SAMPLER = RenderSystem.getSamplerCache().getSampler(AddressMode.REPEAT, AddressMode.REPEAT, FilterMode.NEAREST, FilterMode.NEAREST, false);
private static final Identifier LOADING_TEXTURE = Identifier.fromNamespaceAndPath("forge", "loading_overlay");
public static RenderType getLoadingOverlay(DisplayWindow window) {
return create(
"forge_loading_overlay",
TRANSIENT_BUFFER_SIZE,
false,
false,
LOADING_PIPELINE,
CompositeState.builder()
.setTextureState(new LoadingOverlayTextureState(window))
.createCompositeState(false)
var gpu = RenderSystem.getDevice();
var texture = gpu.createTexture(LOADING_TEXTURE.toString(), 5, TextureFormat.RGBA8,
window.context().width(), window.context().height(),
1, window.getFramebufferTextureId());
var textureView = gpu.createTextureView(texture);
return RenderType.create("forge_loading_overlay",
RenderSetup.builder(LOADING_PIPELINE)
.bufferSize(RenderType.TRANSIENT_BUFFER_SIZE)
.withTexture("Sampler0", textureView, LOADING_SAMPLER)
.createRenderSetup()
);
}
}
private static class CustomizableTextureState extends TextureStateShard {
private CustomizableTextureState(ResourceLocation resLoc, boolean mipmap) {
super(resLoc, mipmap);
this.setupState = () -> {
TextureManager manager = Minecraft.getInstance().getTextureManager();
var texture = manager.getTexture(resLoc);
texture.setFilter(enableTextTextureLinearFiltering, this.mipmap);
RenderSystem.setShaderTexture(0, texture.getTextureView());
};
}
}
private static class LoadingOverlayTextureState extends TextureStateShard {
private static final ResourceLocation LOADING_TEXTURE = ResourceLocation.fromNamespaceAndPath("forge", "loading_overlay");
private final GpuTexture texture;
private final GpuTextureView textureView;
private LoadingOverlayTextureState(DisplayWindow window) {
super(LOADING_TEXTURE, false);
GpuDevice gpu = RenderSystem.getDevice();
this.texture = gpu.createTexture(LOADING_TEXTURE.toString(), 5, TextureFormat.RGBA8,
window.context().width(), window.context().height(),
1, window.getFramebufferTextureId());
this.textureView = gpu.createTextureView(this.texture);
this.setupState = () -> {
GL30C.glTexParameterIi(GlConst.GL_TEXTURE_2D, GlConst.GL_TEXTURE_MIN_FILTER, GlConst.GL_NEAREST);
GL30C.glTexParameterIi(GlConst.GL_TEXTURE_2D, GlConst.GL_TEXTURE_MAG_FILTER, GlConst.GL_NEAREST);
RenderSystem.setShaderTexture(0, this.textureView);
};
}
}
}
@@ -10,7 +10,7 @@ import com.mojang.blaze3d.framegraph.FramePass;
import com.mojang.blaze3d.resource.ResourceHandle;
import net.minecraft.client.renderer.LevelTargetBundle;
import net.minecraft.client.renderer.state.LevelRenderState;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.Nullable;
@@ -20,7 +20,7 @@ import java.util.List;
public class FramePassManager {
private static final List<PassInfo> addedPasses = new ArrayList<>();
protected static void addPass(ResourceLocation name, PassDefinition pass) {
protected static void addPass(Identifier name, PassDefinition pass) {
if (addedPasses.stream().noneMatch(info -> info.name.equals(name.toString()))) {
addedPasses.add(new PassInfo(name.toString(), pass));
} else {
@@ -5,9 +5,8 @@
package net.minecraftforge.client;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.chunk.ChunkSectionLayer;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.client.event.RegisterNamedRenderTypesEvent;
import org.jetbrains.annotations.ApiStatus;
@@ -20,18 +19,18 @@ import java.util.Map;
* Provides a lookup.
*/
public final class NamedRenderTypeManager {
private static Map<ResourceLocation, RenderTypeGroup> RENDER_TYPES;
private static Map<Identifier, RenderTypeGroup> RENDER_TYPES;
/**
* Finds the {@link RenderTypeGroup} for a given name, or the {@link RenderTypeGroup#EMPTY empty group} if not found.
*/
public static RenderTypeGroup get(ResourceLocation name) {
public static RenderTypeGroup get(Identifier name) {
return RENDER_TYPES.getOrDefault(name, RenderTypeGroup.EMPTY);
}
@ApiStatus.Internal
public static void init() {
var renderTypes = new HashMap<ResourceLocation, RenderTypeGroup>();
var renderTypes = new HashMap<Identifier, RenderTypeGroup>();
preRegisterVanillaRenderTypes(renderTypes);
RegisterNamedRenderTypesEvent.BUS.post(new RegisterNamedRenderTypesEvent(renderTypes));
RENDER_TYPES = Map.copyOf(renderTypes);
@@ -40,18 +39,15 @@ public final class NamedRenderTypeManager {
/**
* Pre-registers vanilla render types.
*/
private static void preRegisterVanillaRenderTypes(Map<ResourceLocation, RenderTypeGroup> blockRenderTypes) {
private static void preRegisterVanillaRenderTypes(Map<Identifier, RenderTypeGroup> blockRenderTypes) {
blockRenderTypes.put(rl("solid"), new RenderTypeGroup(ChunkSectionLayer.SOLID, ForgeRenderTypes.ITEM_LAYERED_SOLID.get()));
blockRenderTypes.put(rl("cutout"), new RenderTypeGroup(ChunkSectionLayer.CUTOUT, ForgeRenderTypes.ITEM_LAYERED_CUTOUT.get()));
// Generally entity/item rendering shouldn't use mipmaps, so cutout_mipped has them off by default. To enforce them, use cutout_mipped_all.
blockRenderTypes.put(rl("cutout_mipped"), new RenderTypeGroup(ChunkSectionLayer.CUTOUT_MIPPED, ForgeRenderTypes.ITEM_LAYERED_CUTOUT.get()));
blockRenderTypes.put(rl("cutout_mipped_all"), new RenderTypeGroup(ChunkSectionLayer.CUTOUT_MIPPED, ForgeRenderTypes.ITEM_LAYERED_CUTOUT_MIPPED.get()));
blockRenderTypes.put(rl("translucent_moving_block"), new RenderTypeGroup(ChunkSectionLayer.TRANSLUCENT, ForgeRenderTypes.ITEM_LAYERED_TRANSLUCENT.get()));
blockRenderTypes.put(rl("tripwire"), new RenderTypeGroup(ChunkSectionLayer.TRIPWIRE, ForgeRenderTypes.ITEM_LAYERED_TRANSLUCENT.get()));
}
private static ResourceLocation rl(String path) {
return ResourceLocation.withDefaultNamespace(path);
private static Identifier rl(String path) {
return Identifier.withDefaultNamespace(path);
}
private NamedRenderTypeManager() {}
@@ -5,8 +5,8 @@
package net.minecraftforge.client;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.chunk.ChunkSectionLayer;
import net.minecraft.client.renderer.rendertype.RenderType;
/**
* A set of functionally equivalent shaders. One using {@link com.mojang.blaze3d.vertex.DefaultVertexFormat#BLOCK},
@@ -7,10 +7,11 @@ package net.minecraftforge.client;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import net.minecraft.client.renderer.ItemBlockRenderTypes;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.Sheets;
import net.minecraft.client.renderer.block.model.BlockStateModel;
import net.minecraft.client.renderer.chunk.ChunkSectionLayer;
import net.minecraft.client.renderer.rendertype.RenderType;
import net.minecraft.client.renderer.rendertype.RenderTypes;
import net.minecraft.util.RandomSource;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.ItemStack;
@@ -42,14 +43,13 @@ public final class RenderTypeHelper {
@NotNull
public static RenderType getMovingBlockRenderType(ChunkSectionLayer layer) {
if (layer == null)
return RenderType.solid();
return RenderTypes.solidMovingBlock();
return switch (layer) {
case SOLID -> RenderType.solid();
case CUTOUT_MIPPED -> RenderType.cutoutMipped();
case CUTOUT -> RenderType.cutout();
case TRANSLUCENT -> RenderType.translucentMovingBlock();
case TRIPWIRE -> RenderType.tripwire();
case SOLID -> RenderTypes.solidMovingBlock();
case CUTOUT -> RenderTypes.cutoutMovingBlock();
case TRANSLUCENT -> RenderTypes.translucentMovingBlock();
case TRIPWIRE -> RenderTypes.tripwireMovingBlock();
};
}
@@ -5,7 +5,7 @@
package net.minecraftforge.client.event;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.client.ForgeHooksClient;
import net.minecraftforge.client.FramePassManager;
import net.minecraftforge.eventbus.api.bus.EventBus;
@@ -29,7 +29,7 @@ public record AddFramePassEvent() implements RecordEvent {
* @param definition see usages of {@linkplain com.mojang.blaze3d.framegraph.FramePass} in {@linkplain net.minecraft.client.renderer.LevelRenderer}
* @throws IllegalArgumentException If the name is a duplicate.
*/
public void addPass(ResourceLocation rl, FramePassManager.PassDefinition definition) {
public void addPass(Identifier rl, FramePassManager.PassDefinition definition) {
ForgeHooksClient.addFramePass(rl, definition);
}
}
@@ -5,7 +5,7 @@
package net.minecraftforge.client.event;
import net.minecraft.Util;
import net.minecraft.util.Util;
import net.minecraft.network.chat.ChatType;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.PlayerChatMessage;
@@ -8,12 +8,11 @@ package net.minecraftforge.client.event;
import com.google.common.collect.ImmutableMap;
import net.minecraft.client.entity.ClientMannequin;
import net.minecraft.client.model.SkullModel;
import net.minecraft.client.model.SkullModelBase;
import net.minecraft.client.model.geom.EntityModelSet;
import net.minecraft.client.model.geom.ModelLayerLocation;
import net.minecraft.client.model.geom.ModelLayers;
import net.minecraft.client.model.geom.builders.LayerDefinition;
import net.minecraft.client.model.object.skull.SkullModelBase;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider;
import net.minecraft.client.renderer.blockentity.BlockEntityRenderers;
@@ -5,16 +5,13 @@
package net.minecraftforge.client.event;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import net.minecraftforge.client.gui.overlay.ForgeLayeredDraw;
import net.minecraftforge.common.util.Result;
import net.minecraftforge.event.TickEvent;
import net.minecraftforge.fml.ModLoader;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.google.common.collect.ImmutableMap;
@@ -27,19 +24,17 @@ import net.minecraft.client.KeyMapping;
import net.minecraft.client.MouseHandler;
import net.minecraft.client.entity.ClientAvatarEntity;
import net.minecraft.client.entity.ClientMannequin;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.toasts.Toast;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent;
import net.minecraft.client.input.CharacterEvent;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.client.input.MouseButtonInfo;
import net.minecraft.client.model.EntityModel;
import net.minecraft.client.model.SkullModelBase;
import net.minecraft.client.model.geom.EntityModelSet;
import net.minecraft.client.model.object.skull.SkullModelBase;
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.player.LocalPlayer;
@@ -60,7 +55,6 @@ import net.minecraft.client.resources.sounds.SoundInstance;
import net.minecraft.client.sounds.SoundEngine;
import net.minecraft.network.Connection;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.Avatar;
import net.minecraft.world.entity.EntityType;
@@ -68,7 +62,6 @@ import net.minecraft.world.entity.HumanoidArm;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.player.PlayerModelType;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.SkullBlock.Type;
import net.minecraftforge.client.event.sound.PlaySoundSourceEvent;
@@ -201,7 +194,7 @@ public final class ForgeEventFactoryClient {
}
public static ViewportEvent.ComputeCameraAngles fireComputeCameraAngles(GameRenderer renderer, Camera camera, float partial) {
return ViewportEvent.ComputeCameraAngles.BUS.fire(new ViewportEvent.ComputeCameraAngles(renderer, camera, partial, camera.getYRot(), camera.getXRot(), 0));
return ViewportEvent.ComputeCameraAngles.BUS.fire(new ViewportEvent.ComputeCameraAngles(renderer, camera, partial, camera.yRot(), camera.xRot(), 0));
}
public static <T extends LivingEntity, S extends LivingEntityRenderState, M extends EntityModel<? super S>> boolean onRenderLivingPre(S state, LivingEntityRenderer<T, S, M> renderer, PoseStack poseStack, SubmitNodeCollector nodeCollector, CameraRenderState cameraState) {
@@ -8,7 +8,7 @@ package net.minecraftforge.client.event;
import com.google.common.base.Preconditions;
import net.minecraft.client.resources.model.ModelBakery;
import net.minecraft.client.resources.model.ModelManager;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
@@ -102,8 +102,8 @@ public sealed interface ModelEvent {
return BUS;
}
private final Map<ResourceLocation, StateDefinition<Block, BlockState>> states = new HashMap<>();
private final Map<ResourceLocation, StateDefinition<Block, BlockState>> view = Collections.unmodifiableMap(states);
private final Map<Identifier, StateDefinition<Block, BlockState>> states = new HashMap<>();
private final Map<Identifier, StateDefinition<Block, BlockState>> view = Collections.unmodifiableMap(states);
@ApiStatus.Internal
public RegisterModelStateDefinitions() {}
@@ -111,14 +111,14 @@ public sealed interface ModelEvent {
/**
* Returns a read only view of the extra registered models
*/
public Map<ResourceLocation, StateDefinition<Block, BlockState>> getStates() {
public Map<Identifier, StateDefinition<Block, BlockState>> getStates() {
return this.view;
}
/**
* Registers a StateDefinition for a synthetic block.
*/
public void register(ResourceLocation key, StateDefinition<Block, BlockState> value) {
public void register(Identifier key, StateDefinition<Block, BlockState> value) {
states.put(key, value);
}
}
@@ -138,20 +138,20 @@ public sealed interface ModelEvent {
return BUS;
}
private final Map<ResourceLocation, IGeometryLoader> loaders;
private final Map<Identifier, IGeometryLoader> loaders;
@ApiStatus.Internal
public RegisterGeometryLoaders(Map<ResourceLocation, IGeometryLoader> loaders) {
public RegisterGeometryLoaders(Map<Identifier, IGeometryLoader> loaders) {
this.loaders = loaders;
}
/**
* Registers a new geometry loader.
* @param resourceLocation The namespace should match your mod's namespace, such as your mod ID
* @param Identifier The namespace should match your mod's namespace, such as your mod ID
*/
public void register(ResourceLocation resourceLocation, IGeometryLoader loader) {
Preconditions.checkArgument(!loaders.containsKey(resourceLocation), "Geometry loader already registered: " + resourceLocation);
loaders.put(resourceLocation, loader);
public void register(Identifier Identifier, IGeometryLoader loader) {
Preconditions.checkArgument(!loaders.containsKey(Identifier), "Geometry loader already registered: " + Identifier);
loaders.put(Identifier, loader);
}
}
}
@@ -10,7 +10,7 @@ import com.mojang.brigadier.context.CommandContext;
import net.minecraft.commands.CommandBuildContext;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.ObjectiveArgument;
import net.minecraft.commands.arguments.ResourceLocationArgument;
import net.minecraft.commands.arguments.IdentifierArgument;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.RecordEvent;
import net.minecraftforge.fml.LogicalSide;
@@ -22,7 +22,7 @@ import org.jspecify.annotations.NullMarked;
*
* <p>Some command arguments behave differently for the client commands dispatcher:</p>
* <ul>
* <li>{@link ResourceLocationArgument#getId(CommandContext, String)} only returns advancements that are shown on
* <li>{@link IdentifierArgument#getId(CommandContext, String)} only returns advancements that are shown on
* the advancements screen.
* <li>{@link ObjectiveArgument#getObjective(com.mojang.brigadier.context.CommandContext, String)} only returns
* objectives that are displayed to the player.
@@ -1,49 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.event;
import net.minecraft.client.renderer.DimensionSpecialEffects;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import org.jetbrains.annotations.ApiStatus;
import org.jspecify.annotations.NullMarked;
import java.util.Map;
/**
* Allows users to register custom {@link DimensionSpecialEffects} for their dimensions.
*
* <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
*/
@NullMarked
public final class RegisterDimensionSpecialEffectsEvent extends MutableEvent implements SelfDestructing {
public static final EventBus<RegisterDimensionSpecialEffectsEvent> BUS = EventBus.create(RegisterDimensionSpecialEffectsEvent.class);
/** @deprecated {@link RegisterDimensionSpecialEffectsEvent} is no longer an {@link IModBusEvent}, so use {@link #BUS} directly. */
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterDimensionSpecialEffectsEvent> getBus(BusGroup modBusGroup) {
return BUS;
}
private final Map<ResourceLocation, DimensionSpecialEffects> effects;
@ApiStatus.Internal
public RegisterDimensionSpecialEffectsEvent(Map<ResourceLocation, DimensionSpecialEffects> effects) {
this.effects = effects;
}
/**
* Registers the effects for a given dimension type.
*/
public void register(ResourceLocation dimensionType, DimensionSpecialEffects effects) {
this.effects.put(dimensionType, effects);
}
}
@@ -5,7 +5,7 @@
package net.minecraftforge.client.event;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.world.entity.EntityType;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
@@ -34,17 +34,17 @@ public final class RegisterEntitySpectatorShadersEvent extends MutableEvent impl
return BUS;
}
private final Map<EntityType<?>, ResourceLocation> shaders;
private final Map<EntityType<?>, Identifier> shaders;
@ApiStatus.Internal
public RegisterEntitySpectatorShadersEvent(Map<EntityType<?>, ResourceLocation> shaders) {
public RegisterEntitySpectatorShadersEvent(Map<EntityType<?>, Identifier> shaders) {
this.shaders = shaders;
}
/**
* Registers a spectator shader for a given entity type.
*/
public void register(EntityType<?> entityType, ResourceLocation shader) {
public void register(EntityType<?> entityType, Identifier shader) {
shaders.put(entityType, shader);
}
}
@@ -7,7 +7,7 @@
package net.minecraftforge.client.event;
import com.google.common.base.Preconditions;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.client.gui.overlay.IGuiOverlay;
import net.minecraftforge.client.gui.overlay.VanillaGuiOverlay;
import net.minecraftforge.eventbus.api.Cancelable;
@@ -33,11 +33,11 @@ import java.util.Map;
* /
public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent
{
private final Map<ResourceLocation, IGuiOverlay> overlays;
private final List<ResourceLocation> orderedOverlays;
private final Map<Identifier, IGuiOverlay> overlays;
private final List<Identifier> orderedOverlays;
@ApiStatus.Internal
public RegisterGuiOverlaysEvent(Map<ResourceLocation, IGuiOverlay> overlays, List<ResourceLocation> orderedOverlays)
public RegisterGuiOverlaysEvent(Map<Identifier, IGuiOverlay> overlays, List<Identifier> orderedOverlays)
{
this.overlays = overlays;
this.orderedOverlays = orderedOverlays;
@@ -62,7 +62,7 @@ public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent
* @param id A unique resource id for this overlay
* @param overlay The overlay
* /
public void registerBelow(@NotNull ResourceLocation other, @NotNull String id, @NotNull IGuiOverlay overlay)
public void registerBelow(@NotNull Identifier other, @NotNull String id, @NotNull IGuiOverlay overlay)
{
register(Ordering.BEFORE, other, id, overlay);
}
@@ -75,7 +75,7 @@ public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent
* @param id A unique resource id for this overlay
* @param overlay The overlay
* /
public void registerAbove(@NotNull ResourceLocation other, @NotNull String id, @NotNull IGuiOverlay overlay)
public void registerAbove(@NotNull Identifier other, @NotNull String id, @NotNull IGuiOverlay overlay)
{
register(Ordering.AFTER, other, id, overlay);
}
@@ -91,9 +91,9 @@ public class RegisterGuiOverlaysEvent extends Event implements IModBusEvent
register(Ordering.AFTER, null, id, overlay);
}
private void register(@NotNull Ordering ordering, @Nullable ResourceLocation other, @NotNull String id, @NotNull IGuiOverlay overlay)
private void register(@NotNull Ordering ordering, @Nullable Identifier other, @NotNull String id, @NotNull IGuiOverlay overlay)
{
var key = new ResourceLocation(ModLoadingContext.get().getActiveNamespace(), id);
var key = new Identifier(ModLoadingContext.get().getActiveNamespace(), id);
Preconditions.checkArgument(!overlays.containsKey(key), "Overlay already registered: " + key);
int insertPosition;
@@ -7,16 +7,14 @@ package net.minecraftforge.client.event;
import com.google.common.base.Preconditions;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.chunk.ChunkSectionLayer;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.client.renderer.rendertype.RenderType;
import net.minecraft.resources.Identifier;
import net.minecraftforge.client.RenderTypeGroup;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
import net.minecraftforge.eventbus.api.event.MutableEvent;
import net.minecraftforge.eventbus.api.event.characteristic.SelfDestructing;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.fml.event.IModBusEvent;
import org.jetbrains.annotations.ApiStatus;
import java.util.Map;
@@ -29,28 +27,22 @@ import java.util.Map;
public final class RegisterNamedRenderTypesEvent extends MutableEvent implements SelfDestructing {
public static final EventBus<RegisterNamedRenderTypesEvent> BUS = EventBus.create(RegisterNamedRenderTypesEvent.class);
/** @deprecated {@link RegisterNamedRenderTypesEvent} is no longer an {@link IModBusEvent}, so use {@link #BUS} directly. */
@Deprecated(forRemoval = true, since = "1.21.9")
public static EventBus<RegisterNamedRenderTypesEvent> getBus(BusGroup modBusGroup) {
return BUS;
}
private final Map<ResourceLocation, RenderTypeGroup> renderTypes;
private final Map<Identifier, RenderTypeGroup> renderTypes;
@ApiStatus.Internal
public RegisterNamedRenderTypesEvent(Map<ResourceLocation, RenderTypeGroup> renderTypes) {
public RegisterNamedRenderTypesEvent(Map<Identifier, RenderTypeGroup> renderTypes) {
this.renderTypes = renderTypes;
}
/**
* Registers a named {@link RenderTypeGroup}.
*
* @param resourceLocation The namespace should match your mod's namespace, such as your mod ID
* @param Identifier The namespace should match your mod's namespace, such as your mod ID
* @param blockRenderType What ChunkSectionLayer to render in
* @param entityRenderType A {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY}
*/
public void register(ResourceLocation resourceLocation, ChunkSectionLayer blockRenderType, RenderType entityRenderType) {
register(resourceLocation, blockRenderType, entityRenderType, entityRenderType);
public void register(Identifier Identifier, ChunkSectionLayer blockRenderType, RenderType entityRenderType) {
register(Identifier, blockRenderType, entityRenderType, entityRenderType);
}
/**
@@ -62,7 +54,7 @@ public final class RegisterNamedRenderTypesEvent extends MutableEvent implements
* @param fabulousEntityRenderType A {@link RenderType} using {@link DefaultVertexFormat#NEW_ENTITY} for use when
* "fabulous" rendering is enabled
*/
public void register(ResourceLocation key, ChunkSectionLayer blockRenderType, RenderType entityRenderType, RenderType fabulousEntityRenderType) {
public void register(Identifier key, ChunkSectionLayer blockRenderType, RenderType entityRenderType, RenderType fabulousEntityRenderType) {
Preconditions.checkArgument(!renderTypes.containsKey(key), "Render type already registered: " + key);
Preconditions.checkArgument(entityRenderType.format() == DefaultVertexFormat.NEW_ENTITY, "The entity render type must use the NEW_ENTITY vertex format.");
Preconditions.checkArgument(fabulousEntityRenderType.format() == DefaultVertexFormat.NEW_ENTITY, "The fabulous entity render type must use the NEW_ENTITY vertex format.");
@@ -48,7 +48,7 @@ public final class RegisterPresetEditorsEvent implements SelfDestructing, IModBu
public void register(ResourceKey<WorldPreset> key, PresetEditor editor) {
PresetEditor old = this.editors.put(key, editor);
if (old != null) {
LOGGER.debug("PresetEditor {} overridden by mod {}", key.location(), ModLoadingContext.get().getActiveNamespace());
LOGGER.debug("PresetEditor {} overridden by mod {}", key.identifier(), ModLoadingContext.get().getActiveNamespace());
}
}
}
@@ -8,7 +8,7 @@ package net.minecraftforge.client.event;
import com.google.common.base.Preconditions;
import com.google.common.collect.BiMap;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.client.textures.ITextureAtlasSpriteLoader;
import net.minecraftforge.eventbus.api.bus.BusGroup;
import net.minecraftforge.eventbus.api.bus.EventBus;
@@ -32,20 +32,20 @@ public final class RegisterTextureAtlasSpriteLoadersEvent extends MutableEvent i
return BUS;
}
private final BiMap<ResourceLocation, ITextureAtlasSpriteLoader> loaders;
private final BiMap<Identifier, ITextureAtlasSpriteLoader> loaders;
@ApiStatus.Internal
public RegisterTextureAtlasSpriteLoadersEvent(BiMap<ResourceLocation, ITextureAtlasSpriteLoader> loaders) {
public RegisterTextureAtlasSpriteLoadersEvent(BiMap<Identifier, ITextureAtlasSpriteLoader> loaders) {
this.loaders = loaders;
}
/**
* Registers a custom {@link ITextureAtlasSpriteLoader sprite loader}.
* @param resourceLocation The namespace should match your mod's namespace, such as your mod ID
* @param Identifier The namespace should match your mod's namespace, such as your mod ID
*/
public void register(ResourceLocation resourceLocation, ITextureAtlasSpriteLoader loader) {
Preconditions.checkArgument(!loaders.containsKey(resourceLocation), "Sprite loader already registered: " + resourceLocation);
public void register(Identifier Identifier, ITextureAtlasSpriteLoader loader) {
Preconditions.checkArgument(!loaders.containsKey(Identifier), "Sprite loader already registered: " + Identifier);
Preconditions.checkArgument(!loaders.containsValue(loader), "Sprite loader already registered as " + loaders.inverse().get(loader));
loaders.put(resourceLocation, loader);
loaders.put(Identifier, loader);
}
}
@@ -11,7 +11,7 @@ import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent;
import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipPositioner;
import net.minecraft.network.chat.FormattedText;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.world.inventory.tooltip.TooltipComponent;
import net.minecraft.world.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
@@ -209,12 +209,12 @@ public abstract sealed class RenderTooltipEvent extends MutableEvent implements
private final int screenHeight;
private final ClientTooltipPositioner positioner;
@Nullable
private ResourceLocation background;
private Identifier background;
@Nullable
private ResourceLocation originalBackground;
private Identifier originalBackground;
@ApiStatus.Internal
public Pre(ItemStack stack, GuiGraphics graphics, int x, int y, int screenWidth, int screenHeight, Font font, List<ClientTooltipComponent> components, ClientTooltipPositioner positioner, @Nullable ResourceLocation background) {
public Pre(ItemStack stack, GuiGraphics graphics, int x, int y, int screenWidth, int screenHeight, Font font, List<ClientTooltipComponent> components, ClientTooltipPositioner positioner, @Nullable Identifier background) {
super(stack, graphics, x, y, font, components);
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
@@ -274,21 +274,21 @@ public abstract sealed class RenderTooltipEvent extends MutableEvent implements
/**
* Sets the new prefix for the background texture
*/
public void setBackground(@Nullable ResourceLocation background) {
public void setBackground(@Nullable Identifier background) {
this.background = background;
}
/**
* @return the potentially modified background's prefix, can be null for default
*/
public @Nullable ResourceLocation getBackground() {
public @Nullable Identifier getBackground() {
return this.background;
}
/**
* @return the original tooltip background's prefix, can be null for default
*/
public @Nullable ResourceLocation getOriginalBackground() {
public @Nullable Identifier getOriginalBackground() {
return originalBackground;
}
}
@@ -35,10 +35,10 @@ public sealed interface TextureStitchEvent {
// * <p>This event is fired only on the {@linkplain LogicalSide#CLIENT logical client}.</p>
// */
// public static class Pre extends TextureStitchEvent {
// private final Set<ResourceLocation> sprites;
// private final Set<Identifier> sprites;
//
// @ApiStatus.Internal
// public Pre(TextureAtlas map, Set<ResourceLocation> sprites) {
// public Pre(TextureAtlas map, Set<Identifier> sprites) {
// super(map);
// this.sprites = sprites;
// }
@@ -51,7 +51,7 @@ public sealed interface TextureStitchEvent {
// *
// * @param sprite the location of the sprite
// */
// public boolean addSprite(ResourceLocation sprite) {
// public boolean addSprite(Identifier sprite) {
// return this.sprites.add(sprite);
// }
// }
@@ -6,12 +6,7 @@
/**
* Events fired only on the client-side, chiefly related to rendering and user interfaces (screens and input).
*/
@FieldsAreNonnullByDefault
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
@NullMarked
package net.minecraftforge.client.event;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
import org.jspecify.annotations.NullMarked;
@@ -36,7 +36,7 @@ public final class PlaySoundEvent extends MutableEvent implements SoundEvent {
public PlaySoundEvent(SoundEngine manager, SoundInstance sound) {
this.manager = manager;
this.originalSound = sound;
this.name = sound.getLocation().getPath();
this.name = sound.getIdentifier().getPath();
this.setSound(sound);
}
@@ -30,7 +30,7 @@ public record PlaySoundSourceEvent(SoundEngine getEngine, SoundInstance getSound
@ApiStatus.Internal
public PlaySoundSourceEvent(SoundEngine engine, SoundInstance sound, Channel channel) {
this(engine, sound, channel, sound.getLocation().getPath());
this(engine, sound, channel, sound.getIdentifier().getPath());
}
@ApiStatus.Internal
@@ -30,7 +30,7 @@ public record PlayStreamingSourceEvent(SoundEngine getEngine, SoundInstance getS
@ApiStatus.Internal
public PlayStreamingSourceEvent(SoundEngine engine, SoundInstance sound, Channel channel) {
this(engine, sound, channel, sound.getLocation().getPath());
this(engine, sound, channel, sound.getIdentifier().getPath());
}
@ApiStatus.Internal
@@ -6,7 +6,7 @@
package net.minecraftforge.client.extensions;
import net.minecraft.client.renderer.ItemBlockRenderTypes;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.rendertype.RenderType;
import net.minecraft.client.renderer.block.model.BlockModelPart;
import net.minecraft.client.renderer.block.model.BlockStateModel;
import net.minecraft.client.renderer.chunk.ChunkSectionLayer;
@@ -7,7 +7,7 @@ package net.minecraftforge.client.extensions;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.renderer.RenderPipelines;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
/**
* Extension interface for {@link GuiGraphics}.
@@ -35,7 +35,7 @@ public interface IForgeGuiGraphics {
* Draws a textured box of any size (smallest size is borderSize * 2 square)
* based on a fixed size textured box with continuous borders and filler.
*
* @param texture the ResourceLocation object that contains the desired image
* @param texture the Identifier object that contains the desired image
* @param x x-axis offset
* @param y y-axis offset
* @param u bound resource location image x offset
@@ -46,7 +46,7 @@ public interface IForgeGuiGraphics {
* @param textureHeight the height of the box texture in the resource location image
* @param borderSize the size of the box's borders
*/
default void blitWithBorder(ResourceLocation texture, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight, int borderSize) {
default void blitWithBorder(Identifier texture, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight, int borderSize) {
this.blitWithBorder(texture, x, y, u, v, width, height, textureWidth, textureHeight, borderSize, borderSize, borderSize, borderSize);
}
@@ -54,7 +54,7 @@ public interface IForgeGuiGraphics {
* Draws a textured box of any size (smallest size is borderSize * 2 square)
* based on a fixed size textured box with continuous borders and filler.
*
* @param texture the ResourceLocation object that contains the desired image
* @param texture the Identifier object that contains the desired image
* @param x x-axis offset
* @param y y-axis offset
* @param u bound resource location image x offset
@@ -68,7 +68,7 @@ public interface IForgeGuiGraphics {
* @param leftBorder the size of the box's left border
* @param rightBorder the size of the box's right border
*/
default void blitWithBorder(ResourceLocation texture, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight, int topBorder, int bottomBorder, int leftBorder, int rightBorder) {
default void blitWithBorder(Identifier texture, int x, int y, int u, int v, int width, int height, int textureWidth, int textureHeight, int topBorder, int bottomBorder, int leftBorder, int rightBorder) {
int fillerWidth = textureWidth - leftBorder - rightBorder;
int fillerHeight = textureHeight - topBorder - bottomBorder;
int canvasWidth = width - leftBorder - rightBorder;
@@ -108,11 +108,11 @@ public interface IForgeGuiGraphics {
}
}
default void blitInscribed(ResourceLocation texture, int x, int y, int boundsWidth, int boundsHeight, int rectWidth, int rectHeight) {
default void blitInscribed(Identifier texture, int x, int y, int boundsWidth, int boundsHeight, int rectWidth, int rectHeight) {
this.blitInscribed(texture, x, y, boundsWidth, boundsHeight, rectWidth, rectHeight, true, true);
}
default void blitInscribed(ResourceLocation texture, int x, int y, int boundsWidth, int boundsHeight, int rectWidth, int rectHeight, boolean centerX, boolean centerY) {
default void blitInscribed(Identifier texture, int x, int y, int boundsWidth, int boundsHeight, int rectWidth, int rectHeight, boolean centerX, boolean centerY) {
if (rectWidth * boundsHeight > rectHeight * boundsWidth) {
int h = boundsHeight;
boundsHeight = (int) (boundsWidth * ((double) rectHeight / rectWidth));
@@ -7,7 +7,6 @@ package net.minecraftforge.client.extensions;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.math.Transformation;
import org.joml.Vector3f;
/**
* Extension interface for {@link com.mojang.blaze3d.vertex.PoseStack}.
@@ -27,12 +26,12 @@ public interface IForgePoseStack {
final PoseStack self = self();
self.pushPose();
Vector3f trans = transformation.getTranslation();
var trans = transformation.getTranslation();
self.translate(trans.x(), trans.y(), trans.z());
self.mulPose(transformation.getLeftRotation());
Vector3f scale = transformation.getScale();
var scale = transformation.getScale();
self.scale(scale.x(), scale.y(), scale.z());
self.mulPose(transformation.getRightRotation());
@@ -7,13 +7,7 @@ package net.minecraftforge.client.extensions;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.blaze3d.vertex.VertexFormatElement;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraftforge.client.model.IQuadTransformer;
import org.joml.Matrix3f;
import org.joml.Vector3f;
import java.nio.ByteBuffer;
/**
* Extension interface for {@link VertexConsumer}.
@@ -23,40 +17,10 @@ public interface IForgeVertexConsumer {
return (VertexConsumer)this;
}
/**
* Consumes an unknown {@link VertexFormatElement} as a raw int data array.
* <p>
* If the consumer needs to store the data for later use, it must copy it. There are no guarantees on immutability.
*/
default VertexConsumer misc(VertexFormatElement element, int... rawData) {
return self();
}
/**
* Variant with no per-vertex shading.
*/
default void putBulkData(PoseStack.Pose pose, BakedQuad bakedQuad, float red, float green, float blue, float alpha, int packedLight, int packedOverlay, boolean readExistingColor) {
self().putBulkData(pose, bakedQuad, new float[] { 1.0F, 1.0F, 1.0F, 1.0F }, red, green, blue, alpha, new int[] { packedLight, packedLight, packedLight, packedLight }, packedOverlay, readExistingColor);
}
default int applyBakedLighting(int packedLight, ByteBuffer data) {
int bl = packedLight & 0xFFFF;
int sl = (packedLight >> 16) & 0xFFFF;
int offset = IQuadTransformer.UV2 * 4; // int offset for vertex 0 * 4 bytes per int
int blBaked = Short.toUnsignedInt(data.getShort(offset));
int slBaked = Short.toUnsignedInt(data.getShort(offset + 2));
bl = Math.max(bl, blBaked);
sl = Math.max(sl, slBaked);
return bl | (sl << 16);
}
default void applyBakedNormals(Vector3f generated, ByteBuffer data, Matrix3f normalTransform) {
byte nx = data.get(28);
byte ny = data.get(29);
byte nz = data.get(30);
if (nx != 0 || ny != 0 || nz != 0) {
generated.set(nx / 127f, ny / 127f, nz / 127f);
generated.mul(normalTransform);
}
default void putBulkData(PoseStack.Pose pose, BakedQuad bakedQuad, float red, float green, float blue, float alpha, int packedLight, int packedOverlay) {
self().putBulkData(pose, bakedQuad, new float[] { 1.0F, 1.0F, 1.0F, 1.0F }, red, green, blue, alpha, new int[] { packedLight, packedLight, packedLight, packedLight }, packedOverlay);
}
}
@@ -14,7 +14,7 @@ import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.ScreenEffectRenderer;
import net.minecraft.client.renderer.fog.FogData;
import net.minecraft.core.BlockPos;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.world.level.BlockAndTintGetter;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.FluidState;
@@ -74,7 +74,7 @@ public interface IClientFluidTypeExtensions {
*
* @return the reference of the texture to apply to a source fluid
*/
default ResourceLocation getStillTexture() {
default Identifier getStillTexture() {
return null;
}
@@ -90,7 +90,7 @@ public interface IClientFluidTypeExtensions {
*
* @return the reference of the texture to apply to a flowing fluid
*/
default ResourceLocation getFlowingTexture() {
default Identifier getFlowingTexture() {
return null;
}
@@ -108,7 +108,7 @@ public interface IClientFluidTypeExtensions {
* a non-opaque block
*/
@Nullable
default ResourceLocation getOverlayTexture() {
default Identifier getOverlayTexture() {
return null;
}
@@ -125,7 +125,7 @@ public interface IClientFluidTypeExtensions {
* within the fluid
*/
@Nullable
default ResourceLocation getRenderOverlayTexture(Minecraft mc) {
default Identifier getRenderOverlayTexture(Minecraft mc) {
return null;
}
@@ -137,7 +137,7 @@ public interface IClientFluidTypeExtensions {
* @param poseStack the transformations representing the current rendering position
*/
default void renderOverlay(Minecraft mc, PoseStack poseStack, MultiBufferSource buffer) {
ResourceLocation texture = this.getRenderOverlayTexture(mc);
Identifier texture = this.getRenderOverlayTexture(mc);
if (texture != null)
ScreenEffectRenderer.renderFluid(mc, poseStack, buffer, texture);
}
@@ -185,7 +185,7 @@ public interface IClientFluidTypeExtensions {
* @param pos the position of the fluid
* @return the reference of the texture to apply to a source fluid
*/
default ResourceLocation getStillTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos) {
default Identifier getStillTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos) {
return this.getStillTexture();
}
@@ -204,7 +204,7 @@ public interface IClientFluidTypeExtensions {
* @param pos the position of the fluid
* @return the reference of the texture to apply to a flowing fluid
*/
default ResourceLocation getFlowingTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos) {
default Identifier getFlowingTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos) {
return this.getFlowingTexture();
}
@@ -224,7 +224,7 @@ public interface IClientFluidTypeExtensions {
* @return the reference of the texture to apply to a fluid directly touching
* a non-opaque block
*/
default ResourceLocation getOverlayTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos) {
default Identifier getOverlayTexture(FluidState state, BlockAndTintGetter getter, BlockPos pos) {
return this.getOverlayTexture();
}
@@ -271,7 +271,7 @@ public interface IClientFluidTypeExtensions {
* @param stack the stack the fluid is in
* @return the reference of the texture to apply to a source fluid
*/
default ResourceLocation getStillTexture(FluidStack stack) {
default Identifier getStillTexture(FluidStack stack) {
return this.getStillTexture();
}
@@ -288,7 +288,7 @@ public interface IClientFluidTypeExtensions {
* @param stack the stack the fluid is in
* @return the reference of the texture to apply to a flowing fluid
*/
default ResourceLocation getFlowingTexture(FluidStack stack) {
default Identifier getFlowingTexture(FluidStack stack) {
return this.getFlowingTexture();
}
@@ -306,7 +306,7 @@ public interface IClientFluidTypeExtensions {
* @return the reference of the texture to apply to a fluid directly touching
* a non-opaque block
*/
default ResourceLocation getOverlayTexture(FluidStack stack) {
default Identifier getOverlayTexture(FluidStack stack) {
return this.getOverlayTexture();
}
}
@@ -49,8 +49,7 @@ public interface IClientMobEffectExtensions {
}
/**
* Renders the icon of the specified effect in the player's inventory.
* This can be used to render icons from your own texture sheet.
* Renders the text and icon of the specified effect in the player's inventory.
*
* @param instance The effect instance
* @param effects The effect-rendering screen
@@ -60,22 +59,7 @@ public interface IClientMobEffectExtensions {
* @param blitOffset The blit offset
* @return true to prevent default rendering, false otherwise
*/
default boolean renderInventoryIcon(MobEffectInstance instance, EffectsInInventory effects, GuiGraphics guiGraphics, int x, int y, int blitOffset) {
return false;
}
/**
* Renders the text of the specified effect in the player's inventory.
*
* @param instance The effect instance
* @param effects The effect-rendering screen
* @param guiGraphics The gui graphics
* @param x The x coordinate
* @param y The y coordinate
* @param blitOffset The blit offset
* @return true to prevent default rendering, false otherwise
*/
default boolean renderInventoryText(MobEffectInstance instance, EffectsInInventory effects, GuiGraphics guiGraphics, int x, int y, int blitOffset) {
default boolean renderInventory(MobEffectInstance instance, EffectsInInventory effects, GuiGraphics guiGraphics, int x, int y, int blitOffset) {
return false;
}
@@ -15,12 +15,7 @@
* methods are usually {@code default} with an implementation in the interface itself, but methods may be implemented
* in the target class instead if it requires access to (patched-in or original) fields in the instance.</p>
*/
@FieldsAreNonnullByDefault
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
@NullMarked
package net.minecraftforge.client.extensions;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
import org.jspecify.annotations.NullMarked;
@@ -12,7 +12,7 @@ import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.ErrorScreen;
import net.minecraft.client.gui.components.ObjectSelectionList;
import net.minecraft.util.FormattedCharSequence;
import net.minecraft.Util;
import net.minecraft.util.Util;
import net.minecraft.network.chat.Component;
import net.minecraft.ChatFormatting;
import net.minecraftforge.common.ForgeI18n;
@@ -25,10 +25,10 @@ import net.minecraftforge.fml.loading.moddiscovery.ModFileInfo;
import org.apache.maven.artifact.versioning.ComparableVersion;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.ActiveTextCollector;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.ObjectSelectionList;
@@ -37,10 +37,9 @@ import net.minecraft.client.gui.components.StringWidget;
import net.minecraft.client.renderer.texture.DynamicTexture;
import com.mojang.blaze3d.platform.NativeImage;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ARGB;
import net.minecraft.util.FormattedCharSequence;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.Util;
import net.minecraft.resources.Identifier;
import net.minecraft.util.Util;
import net.minecraftforge.common.ForgeHooks;
import net.minecraftforge.common.util.Size2i;
import net.minecraftforge.common.ForgeI18n;
@@ -52,14 +51,11 @@ import net.minecraftforge.fml.loading.FMLPaths;
import net.minecraftforge.fml.loading.StringUtils;
import net.minecraftforge.forgespi.language.IModInfo;
import net.minecraft.locale.Language;
import net.minecraft.network.chat.ClickEvent;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style;
import org.slf4j.Logger;
public class ModListScreen extends Screen {
private static final ResourceLocation LOGO = ResourceLocation.fromNamespaceAndPath("forge", "mod_logo");
private static final Identifier LOGO = Identifier.fromNamespaceAndPath("forge", "mod_logo");
private static String stripControlCodes(String value) { return net.minecraft.util.StringUtil.stripColor(value); }
private static final Logger LOGGER = LogUtils.getLogger();
private enum SortType implements Comparator<IModInfo> {
@@ -112,7 +108,7 @@ public class ModListScreen extends Screen {
}
class InfoPanel extends ScrollPanel {
private ResourceLocation logoPath;
private Identifier logoPath;
private Size2i logoDims = new Size2i(0, 0);
private List<FormattedCharSequence> lines = Collections.emptyList();
@@ -120,7 +116,7 @@ public class ModListScreen extends Screen {
super(mcIn, widthIn, heightIn, topIn, modList.getRight() + PADDING);
}
void setInfo(List<String> lines, ResourceLocation logoPath, Size2i logoDims) {
void setInfo(List<String> lines, Identifier logoPath, Size2i logoDims) {
this.logoPath = logoPath;
this.logoDims = logoDims;
this.lines = resizeContent(lines);
@@ -143,7 +139,7 @@ public class ModListScreen extends Screen {
Component chat = ForgeHooks.newChatWithLinks(line, false);
int maxTextLength = this.width - 12;
if (maxTextLength >= 0)
ret.addAll(Language.getInstance().getVisualOrder(font.getSplitter().splitLines(chat, maxTextLength, Style.EMPTY)));
ret.addAll(font.split(chat, maxTextLength));
}
return ret;
}
@@ -172,45 +168,36 @@ public class ModListScreen extends Screen {
relativeY += headerHeight + PADDING;
}
for (FormattedCharSequence line : lines) {
if (line != null)
guiGraphics.drawString(ModListScreen.this.font, line, left + PADDING, relativeY, ARGB.white(1));
relativeY += font.lineHeight;
}
final Style component = findTextLine(mouseX, mouseY);
if (component!=null)
guiGraphics.renderComponentHoverEffect(ModListScreen.this.font, component, mouseX, mouseY);
visitText(guiGraphics.textRenderer(GuiGraphics.HoveredTextEffects.TOOLTIP_AND_CURSOR), relativeY);
}
private Style findTextLine(final int mouseX, final int mouseY) {
if (!isMouseOver(mouseX, mouseY))
return null;
private void visitText(ActiveTextCollector collector, int header) {
int x = left + PADDING;
int y = header;
double offset = (mouseY - top - PADDING - border) + scrollDistance;
if (logoPath != null)
offset -= 50;
if (offset <= 0)
return null;
int lineIdx = (int) (offset / font.lineHeight);
if (lineIdx >= lines.size() || lineIdx < 0)
return null;
FormattedCharSequence line = lines.get(lineIdx);
if (line != null)
return font.getSplitter().componentStyleAtWidth(line, mouseX - left - border);
return null;
for (int i = 0; i < this.lines.size(); i++) {
var line = this.lines.get(i);
if (line != null)
collector.accept(x, y, line);
y += font.lineHeight;
}
}
@Override
public boolean mouseClicked(MouseButtonEvent info, boolean recent) {
final Style component = findTextLine((int)info.x(), (int)info.y());
if (component != null) {
ModListScreen.this.handleComponentClicked(component);
return true;
}
return super.mouseClicked(info, recent);
protected boolean clickPanel(double mouseX, double mouseY, int button) {
var finder = new ActiveTextCollector.ClickableStyleFinder(font, (int)mouseX + left, (int)mouseY);
visitText(finder, logoPath == null ? 0 : 50 + PADDING);
var style = finder.result();
if (style == null || style.getClickEvent() == null)
return false;
var event = style.getClickEvent();
if (this.client.player == null)
defaultHandleClickEvent(event, this.client, ModListScreen.this);
else
defaultHandleGameClickEvent(event, this.client, ModListScreen.this);
return true;
}
@Override
@@ -382,7 +369,7 @@ public class ModListScreen extends Screen {
updateCache();
}
record Logo(ResourceLocation texture, Size2i size) {}
record Logo(Identifier texture, Size2i size) {}
private static final Logo NONE = new Logo(null, new Size2i(0, 0));
private void updateCache() {
@@ -480,11 +467,11 @@ public class ModListScreen extends Screen {
}
@Override
public void resize(Minecraft mc, int width, int height) {
public void resize(int width, int height) {
String s = this.search.getValue();
SortType sort = this.sortType;
ModListWidget.ModEntry selected = this.selected;
this.init(mc, width, height);
this.init(width, height);
this.search.setValue(s);
this.selected = selected;
@@ -501,12 +488,4 @@ public class ModListScreen extends Screen {
public void onClose() {
this.minecraft.setScreen(this.parentScreen);
}
@Override
protected void handleClickEvent(Minecraft mc, ClickEvent event) {
if (mc.player == null)
defaultHandleClickEvent(event, mc, this);
else
defaultHandleGameClickEvent(event, mc, this);
}
}
@@ -12,16 +12,16 @@ import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import net.minecraftforge.client.gui.widget.ScrollPanel;
import org.apache.commons.lang3.tuple.Pair;
import net.minecraft.ChatFormatting;
import net.minecraft.Util;
import net.minecraft.util.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.TextAlignment;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.MultiLineLabel;
import net.minecraft.client.gui.narration.NarrationElementOutput;
@@ -32,8 +32,7 @@ import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.HoverEvent;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.network.chat.Style;
import net.minecraft.network.chat.TextColor;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.util.FormattedCharSequence;
import net.minecraftforge.common.ForgeI18n;
import net.minecraftforge.fml.ModList;
@@ -41,7 +40,8 @@ import net.minecraftforge.fml.loading.FMLPaths;
import net.minecraftforge.network.NetworkContext.NetworkMismatchData;
import net.minecraftforge.network.packets.ModVersions;
//TODO: Oh god... Whoever wrote this was on something very very strong.
//TODO: [Forge][Rendering] Rewrite entire ModMismatch screen
//Oh god... Whoever wrote this was on something very very strong.
public class ModMismatchDisconnectedScreen extends Screen {
private final Component reason;
private MultiLineLabel message = MultiLineLabel.EMPTY;
@@ -102,7 +102,8 @@ public class ModMismatchDisconnectedScreen extends Screen {
this.renderBackground(guiGraphics, mouseX, mouseY, partialTicks);
int textYOffset = hasMismatches ? 18 : 0;
guiGraphics.drawCenteredString(this.font, this.title, this.width / 2, (this.height - this.listHeight - this.textHeight) / 2 - textYOffset - 9 * 2, 0xAAAAAA);
this.message.render(guiGraphics, MultiLineLabel.Align.CENTER, this.width / 2, (this.height - this.listHeight - this.textHeight) / 2 - textYOffset, 9, true, -1);
var lineCollector = guiGraphics.textRenderer(GuiGraphics.HoveredTextEffects.notClickable(false));
this.message.visitLines(TextAlignment.CENTER, this.width / 2, (this.height - this.listHeight - this.textHeight) / 2 - textYOffset, 9, lineCollector);
super.render(guiGraphics, mouseX, mouseY, partialTicks);
}
@@ -134,7 +135,7 @@ public class ModMismatchDisconnectedScreen extends Screen {
)
));
int i = 0;
for (ResourceLocation mod : data.missing()) {
for (Identifier mod : data.missing()) {
rawTable.add(Pair.of(
toModNameComponent(mod, data.mods().get(mod.getNamespace()).name(), i),
Pair.of(
@@ -223,7 +224,7 @@ public class ModMismatchDisconnectedScreen extends Screen {
* @param color Defines the color of the returned style information. An odd number will result in a yellow, an even one in a gold color. This color variation makes it easier for users to distinguish different mod entries.
* @return A component with the mod name as the main text component, and an assigned style which will be used for the whole content row.
*/
private MutableComponent toModNameComponent(ResourceLocation id, String modName, int color) {
private MutableComponent toModNameComponent(Identifier id, String modName, int color) {
String modId = id.getNamespace();
String tooltipId = id.getPath().isEmpty() ? id.getNamespace() : id.toString();
return Component.literal(modName).withStyle(color % 2 == 0 ? ChatFormatting.GOLD : ChatFormatting.YELLOW)
@@ -257,7 +258,7 @@ public class ModMismatchDisconnectedScreen extends Screen {
FormattedCharSequence name = line.getLeft();
Pair<FormattedCharSequence, FormattedCharSequence> versions = line.getRight();
//Since font#draw does not respect the color of the given component, we have to read it out here and then use it as the last parameter
int color = Optional.ofNullable(font.getSplitter().componentStyleAtWidth(name, 0)).map(Style::getColor).map(TextColor::getValue).orElse(0xFFFFFF);
int color = 0xFFFFFF; //Optional.ofNullable(font.substrByWidth(name, 0)).map(Style::getColor).map(TextColor::getValue).orElse(0xFFFFFF);
//Only indent the given name if a version string is present. This makes it easier to distinguish table section headers and mod entries
int nameLeft = left + border + (versions == null ? 0 : nameIndent);
guiGraphics.drawString(font, name, nameLeft, relativeY + i * 12, color, false);
@@ -285,8 +286,8 @@ public class ModMismatchDisconnectedScreen extends Screen {
if (slotIndex < contentSize) {
//The relative x needs to take the potentially missing indent of the row into account. It does that by checking if the line has a version associated to it
double relativeX = x - left - border - (lineTable.get(slotIndex).getRight() == null ? 0 : nameIndent);
if (relativeX >= 0)
return font.getSplitter().componentStyleAtWidth(lineTable.get(slotIndex).getLeft(), (int)relativeX);
//if (relativeX >= 0)
// return font.getSplitter().componentStyleAtWidth(lineTable.get(slotIndex).getLeft(), (int)relativeX);
}
}
@@ -297,7 +298,7 @@ public class ModMismatchDisconnectedScreen extends Screen {
public boolean mouseClicked(MouseButtonEvent info, boolean recent) {
Style style = getComponentStyleAt(info.x(), info.y());
if (style != null) {
handleComponentClicked(style);
//handleComponentClicked(style);
return true;
}
return super.mouseClicked(info, recent);
@@ -11,7 +11,7 @@ import net.minecraft.client.gui.screens.TitleScreen;
import net.minecraft.client.renderer.RenderPipelines;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.fml.loading.FMLConfig;
import net.minecraftforge.versions.forge.ForgeVersion;
import net.minecraftforge.fml.VersionChecker;
@@ -19,7 +19,7 @@ import net.minecraftforge.client.loading.ClientModLoader;
public class TitleScreenModUpdateIndicator extends Screen {
private static final ResourceLocation VERSION_CHECK_ICONS = ResourceLocation.fromNamespaceAndPath(ForgeVersion.MOD_ID, "textures/gui/version_check_icons.png");
private static final Identifier VERSION_CHECK_ICONS = Identifier.fromNamespaceAndPath(ForgeVersion.MOD_ID, "textures/gui/version_check_icons.png");
private final Button modButton;
private VersionChecker.Status showNotification = null;
@@ -18,7 +18,7 @@ import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.resources.language.I18n;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.util.Mth;
import net.minecraft.util.StringUtil;
import net.minecraft.world.effect.MobEffects;
@@ -274,9 +274,9 @@ public class ForgeGui extends Gui {
FoodData stats = minecraft.player.getFoodData();
int level = stats.getFoodLevel();
ResourceLocation empty = FOOD_EMPTY_SPRITE;
ResourceLocation half = FOOD_HALF_SPRITE;
ResourceLocation full = FOOD_FULL_SPRITE;
Identifier empty = FOOD_EMPTY_SPRITE;
Identifier half = FOOD_HALF_SPRITE;
Identifier full = FOOD_FULL_SPRITE;
if (player.hasEffect(MobEffects.HUNGER)) {
empty = FOOD_EMPTY_HUNGER_SPRITE;
@@ -6,19 +6,17 @@
package net.minecraftforge.client.gui.overlay;
import com.mojang.logging.LogUtils;
import net.minecraft.FieldsAreNonnullByDefault;
import net.minecraft.MethodsReturnNonnullByDefault;
import net.minecraft.client.DeltaTracker;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.client.event.ForgeEventFactoryClient;
import net.minecraftforge.client.event.AddGuiOverlayLayersEvent;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
import org.jspecify.annotations.NullMarked;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.*;
import java.util.function.BooleanSupplier;
@@ -29,47 +27,45 @@ import java.util.function.BooleanSupplier;
* Layers must be uniquely named per ForgeLayeredDraw, but may be duplicated across different instances.
* Any change which would result in a duplicate will not be applied.
* All methods which return a {@linkplain ForgeLayeredDraw} will return its caller's instance.
* To select a specific instance, use {@linkplain ForgeLayeredDraw#locateStack(ResourceLocation)} before adding
* To select a specific instance, use {@linkplain ForgeLayeredDraw#locateStack(Identifier)} before adding
* or use the methods that include a stack identifier.
*/
@FieldsAreNonnullByDefault
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
@NullMarked
public final class ForgeLayeredDraw implements ForgeLayer {
private final Map<ResourceLocation, ForgeLayer> namedLayers = new HashMap<>();
private final Map<ResourceLocation, Map.Entry<ForgeLayeredDraw, BooleanSupplier>> subLayerStacks = new HashMap<>();
private final List<ResourceLocation> order = new LinkedList<>();
private final Map<Identifier, ForgeLayer> namedLayers = new HashMap<>();
private final Map<Identifier, Map.Entry<ForgeLayeredDraw, BooleanSupplier>> subLayerStacks = new HashMap<>();
private final List<Identifier> order = new LinkedList<>();
private final List<ForgeLayer> bakedLayers = new ArrayList<>();
private final ResourceLocation name;
private final Identifier name;
public static final ResourceLocation PRE_SLEEP_STACK = ResourceLocation.withDefaultNamespace("pre_sleep_phase");
public static final ResourceLocation CAMERA_OVERLAY = ResourceLocation.withDefaultNamespace("camera_overlay");
public static final ResourceLocation CROSSHAIR = ResourceLocation.withDefaultNamespace("crosshair");
public static final ResourceLocation CHANGE_STRATUM = ResourceLocation.withDefaultNamespace("stratum_change");
public static final ResourceLocation HOTBAR_AND_DECOS = ResourceLocation.withDefaultNamespace("hotbar");
public static final ResourceLocation POTION_EFFECTS = ResourceLocation.withDefaultNamespace("potion_effects");
public static final ResourceLocation BOSS_OVERLAY = ResourceLocation.withDefaultNamespace("boss_overlay");
public static final Identifier PRE_SLEEP_STACK = Identifier.withDefaultNamespace("pre_sleep_phase");
public static final Identifier CAMERA_OVERLAY = Identifier.withDefaultNamespace("camera_overlay");
public static final Identifier CROSSHAIR = Identifier.withDefaultNamespace("crosshair");
public static final Identifier CHANGE_STRATUM = Identifier.withDefaultNamespace("stratum_change");
public static final Identifier HOTBAR_AND_DECOS = Identifier.withDefaultNamespace("hotbar");
public static final Identifier POTION_EFFECTS = Identifier.withDefaultNamespace("potion_effects");
public static final Identifier BOSS_OVERLAY = Identifier.withDefaultNamespace("boss_overlay");
public static final ResourceLocation POST_SLEEP_STACK = ResourceLocation.withDefaultNamespace("post_sleep_phase");
public static final ResourceLocation DEMO_OVERLAY = ResourceLocation.withDefaultNamespace("demo");
public static final ResourceLocation DEBUG_OVERLAY = ResourceLocation.withDefaultNamespace("debug");
public static final ResourceLocation SCOREBOARD = ResourceLocation.withDefaultNamespace("scoreboard");
public static final ResourceLocation HOTBAR_MESSAGE = ResourceLocation.withDefaultNamespace("hotbar_message");
public static final ResourceLocation TITLE_OVERLAY = ResourceLocation.withDefaultNamespace("title");
public static final ResourceLocation CHAT_OVERLAY = ResourceLocation.withDefaultNamespace("chat_overlay");
public static final ResourceLocation TAB_LIST = ResourceLocation.withDefaultNamespace("tab_list");
public static final ResourceLocation SUBTITLE_OVERLAY = ResourceLocation.withDefaultNamespace("subtitle");
public static final Identifier POST_SLEEP_STACK = Identifier.withDefaultNamespace("post_sleep_phase");
public static final Identifier DEMO_OVERLAY = Identifier.withDefaultNamespace("demo");
public static final Identifier DEBUG_OVERLAY = Identifier.withDefaultNamespace("debug");
public static final Identifier SCOREBOARD = Identifier.withDefaultNamespace("scoreboard");
public static final Identifier HOTBAR_MESSAGE = Identifier.withDefaultNamespace("hotbar_message");
public static final Identifier TITLE_OVERLAY = Identifier.withDefaultNamespace("title");
public static final Identifier CHAT_OVERLAY = Identifier.withDefaultNamespace("chat_overlay");
public static final Identifier TAB_LIST = Identifier.withDefaultNamespace("tab_list");
public static final Identifier SUBTITLE_OVERLAY = Identifier.withDefaultNamespace("subtitle");
public static final ResourceLocation VANILLA_ROOT = ResourceLocation.withDefaultNamespace("vanilla_root");
public static final ResourceLocation SLEEP_OVERLAY = ResourceLocation.withDefaultNamespace("sleep_overlay");
public static final Identifier VANILLA_ROOT = Identifier.withDefaultNamespace("vanilla_root");
public static final Identifier SLEEP_OVERLAY = Identifier.withDefaultNamespace("sleep_overlay");
private static final ForgeLayeredDraw instance = new ForgeLayeredDraw(VANILLA_ROOT);
/**
* Creates an empty draw list. Add entries with {@linkplain ForgeLayeredDraw#add(ResourceLocation, ForgeLayer)}
* Creates an empty draw list. Add entries with {@linkplain ForgeLayeredDraw#add(Identifier, ForgeLayer)}
* @param name marker for which phase this is.
*/
public ForgeLayeredDraw(ResourceLocation name) {
public ForgeLayeredDraw(Identifier name) {
this.name = name;
}
@@ -81,7 +77,7 @@ public final class ForgeLayeredDraw implements ForgeLayer {
* @param supplier condition for this stack to render
* @return this
*/
public ForgeLayeredDraw add(ResourceLocation name, ForgeLayeredDraw layeredDraw, BooleanSupplier supplier) {
public ForgeLayeredDraw add(Identifier name, ForgeLayeredDraw layeredDraw, BooleanSupplier supplier) {
if (isNameAvailable(name)) {
subLayerStacks.put(name, Map.entry(layeredDraw, supplier));
order.add(name);
@@ -98,7 +94,7 @@ public final class ForgeLayeredDraw implements ForgeLayer {
* @param layer layer render code, see {@linkplain ForgeLayer} and example usages in {@linkplain Gui}
* @return this
*/
public ForgeLayeredDraw add(ResourceLocation targetStack, ResourceLocation name, ForgeLayer layer) {
public ForgeLayeredDraw add(Identifier targetStack, Identifier name, ForgeLayer layer) {
locateStack(targetStack).ifPresentOrElse((stack) -> stack.add(name, layer), () -> stackNotPresentWarning(targetStack));
return this;
}
@@ -106,12 +102,12 @@ public final class ForgeLayeredDraw implements ForgeLayer {
/**
* Helper method, assumes the intended draw stack instance is the caller.
* Use any of the non-deprecated add methods if you want a specific instance,
* or call {@linkplain ForgeLayeredDraw#locateStack(ResourceLocation)} to get a reference to an instance.
* or call {@linkplain ForgeLayeredDraw#locateStack(Identifier)} to get a reference to an instance.
* @param name RL of layer to add
* @param layer layer render code, see {@linkplain ForgeLayer} and example usages in {@linkplain Gui}
* @return this
*/
public ForgeLayeredDraw add(ResourceLocation name, ForgeLayer layer) {
public ForgeLayeredDraw add(Identifier name, ForgeLayer layer) {
if (isNameAvailable(name)) {
namedLayers.put(name, layer);
order.add(name);
@@ -124,12 +120,12 @@ public final class ForgeLayeredDraw implements ForgeLayer {
/**
* Use to specify where your custom draw stack should go. Can also be used to re-order layers.
* Both target and destination must be in the same draw stack.
* @param expectedStack Which ForgeLayeredDraw the target is expected to be in. If you already have a reference to it, you can use {@linkplain ForgeLayeredDraw#move(ResourceLocation, ResourceLocation, LayerOffset)}
* @param expectedStack Which ForgeLayeredDraw the target is expected to be in. If you already have a reference to it, you can use {@linkplain ForgeLayeredDraw#move(Identifier, Identifier, LayerOffset)}
* @param target layer name to move
* @param destination layer name to order against
* @return this
*/
public ForgeLayeredDraw putAbove(ResourceLocation expectedStack, ResourceLocation target, ResourceLocation destination) {
public ForgeLayeredDraw putAbove(Identifier expectedStack, Identifier target, Identifier destination) {
locateStack(expectedStack).ifPresentOrElse((stack) -> stack.move(target, destination, LayerOffset.ABOVE), () -> stackNotPresentWarning(expectedStack));
return this;
}
@@ -137,12 +133,12 @@ public final class ForgeLayeredDraw implements ForgeLayer {
/**
* Use to specify where your custom draw stack should go. Can also be used to re-order layers.
* Both target and destination must be in the same draw stack.
* @param expectedStack Which ForgeLayeredDraw the target is expected to be in. If you already have a reference to it, you can use {@linkplain ForgeLayeredDraw#move(ResourceLocation, ResourceLocation, LayerOffset)}
* @param expectedStack Which ForgeLayeredDraw the target is expected to be in. If you already have a reference to it, you can use {@linkplain ForgeLayeredDraw#move(Identifier, Identifier, LayerOffset)}
* @param target layer name to move
* @param destination layer name to order against
* @return this
*/
public ForgeLayeredDraw putBelow(ResourceLocation expectedStack, ResourceLocation target, ResourceLocation destination) {
public ForgeLayeredDraw putBelow(Identifier expectedStack, Identifier target, Identifier destination) {
locateStack(expectedStack).ifPresentOrElse((stack) -> stack.move(target, destination, LayerOffset.BELOW), () -> stackNotPresentWarning(expectedStack));
return this;
}
@@ -155,7 +151,7 @@ public final class ForgeLayeredDraw implements ForgeLayer {
* @param offset Self-explanatory
* @return this
*/
public ForgeLayeredDraw move(ResourceLocation target, ResourceLocation destination, LayerOffset offset) {
public ForgeLayeredDraw move(Identifier target, Identifier destination, LayerOffset offset) {
if (!order.contains(target)) {
layerNotPresentWarning(target);
return this;
@@ -179,7 +175,7 @@ public final class ForgeLayeredDraw implements ForgeLayer {
* @param layer layer render code, see {@linkplain ForgeLayer} and example usages in {@linkplain Gui}
* @return this
*/
public ForgeLayeredDraw addAbove(ResourceLocation expectedStack, ResourceLocation newLayer, ResourceLocation otherLayer, ForgeLayer layer) {
public ForgeLayeredDraw addAbove(Identifier expectedStack, Identifier newLayer, Identifier otherLayer, ForgeLayer layer) {
locateStack(expectedStack).ifPresentOrElse((stack) -> {
if (!stack.isNameAvailable(otherLayer)) {
stack.add(newLayer, layer).move(newLayer, otherLayer, LayerOffset.ABOVE);
@@ -193,7 +189,7 @@ public final class ForgeLayeredDraw implements ForgeLayer {
/**
* Helper method, assumes intended draw stack is the caller
*/
public ForgeLayeredDraw addAbove(ResourceLocation newLayer, ResourceLocation otherLayer, ForgeLayer layer) {
public ForgeLayeredDraw addAbove(Identifier newLayer, Identifier otherLayer, ForgeLayer layer) {
return addAbove(name, newLayer, otherLayer, layer);
}
@@ -206,7 +202,7 @@ public final class ForgeLayeredDraw implements ForgeLayer {
* @param layer layer render code, see {@linkplain ForgeLayer} and example usages in {@linkplain Gui}
* @return this
*/
public ForgeLayeredDraw addBelow(ResourceLocation expectedStack, ResourceLocation newLayer, ResourceLocation otherLayer, ForgeLayer layer) {
public ForgeLayeredDraw addBelow(Identifier expectedStack, Identifier newLayer, Identifier otherLayer, ForgeLayer layer) {
locateStack(expectedStack).ifPresentOrElse((stack) -> {
if (!stack.isNameAvailable(otherLayer)) {
stack.add(newLayer, layer).move(newLayer, otherLayer, LayerOffset.BELOW);
@@ -220,7 +216,7 @@ public final class ForgeLayeredDraw implements ForgeLayer {
/**
* Helper method, assumes intended draw stack is the caller
*/
public ForgeLayeredDraw addBelow(ResourceLocation newLayer, ResourceLocation otherLayer, ForgeLayer layer) {
public ForgeLayeredDraw addBelow(Identifier newLayer, Identifier otherLayer, ForgeLayer layer) {
return addBelow(name, newLayer, otherLayer, layer);
}
@@ -232,7 +228,7 @@ public final class ForgeLayeredDraw implements ForgeLayer {
* @param condition supplier for the condition
* @return this
*/
public ForgeLayeredDraw addWithCondition(ResourceLocation targetStack, ResourceLocation name, ForgeLayer layer, BooleanSupplier condition) {
public ForgeLayeredDraw addWithCondition(Identifier targetStack, Identifier name, ForgeLayer layer, BooleanSupplier condition) {
locateStack(targetStack).ifPresentOrElse((stack) -> stack.addWithCondition(name, layer, condition), () -> stackNotPresentWarning(targetStack));
return this;
}
@@ -244,7 +240,7 @@ public final class ForgeLayeredDraw implements ForgeLayer {
* @param condition supplier for the condition
* @return this
*/
public ForgeLayeredDraw addWithCondition(ResourceLocation name, ForgeLayer layer, BooleanSupplier condition) {
public ForgeLayeredDraw addWithCondition(Identifier name, ForgeLayer layer, BooleanSupplier condition) {
add(name, layer).addConditionTo(name, condition);
return this;
}
@@ -257,20 +253,20 @@ public final class ForgeLayeredDraw implements ForgeLayer {
* @param condition supplier for the condition
* @return this
*/
public ForgeLayeredDraw addConditionTo(ResourceLocation targetStack, ResourceLocation targetLayer, BooleanSupplier condition) {
public ForgeLayeredDraw addConditionTo(Identifier targetStack, Identifier targetLayer, BooleanSupplier condition) {
locateStack(targetStack).ifPresentOrElse((stack) -> stack.addConditionTo(targetLayer, condition), () -> stackNotPresentWarning(targetStack));
return this;
}
/**
* Assumes the correct stack is the caller of this method.
* Use {@linkplain ForgeLayeredDraw#addConditionTo(ResourceLocation, ResourceLocation, BooleanSupplier)}
* Use {@linkplain ForgeLayeredDraw#addConditionTo(Identifier, Identifier, BooleanSupplier)}
* if you do not have a reference to the draw stack you want.
* @param targetLayer name of layer to add condition to
* @param condition supplier for the condition
* @return this
*/
public ForgeLayeredDraw addConditionTo(ResourceLocation targetLayer, BooleanSupplier condition) {
public ForgeLayeredDraw addConditionTo(Identifier targetLayer, BooleanSupplier condition) {
var result = namedLayers.computeIfPresent(targetLayer,
(name, layer) -> (guiGraphics, deltaTracker) -> {
if (condition.getAsBoolean()) {
@@ -303,7 +299,7 @@ public final class ForgeLayeredDraw implements ForgeLayer {
* Parent layer stack {@linkplain ForgeLayeredDraw#VANILLA_ROOT} holds the results.
*/
private void resolveNested() {
for (ResourceLocation layerName : order) {
for (Identifier layerName : order) {
if (subLayerStacks.containsKey(layerName)) {
var entry = subLayerStacks.get(layerName);
entry.getKey().resolveNested();
@@ -322,7 +318,7 @@ public final class ForgeLayeredDraw implements ForgeLayer {
* @param targetStack Name of ForgeLayeredDraw to find
* @return Filled Optional if target exists, empty otherwise.
*/
public Optional<ForgeLayeredDraw> locateStack(ResourceLocation targetStack) {
public Optional<ForgeLayeredDraw> locateStack(Identifier targetStack) {
if (!name.equals(targetStack)) {
for (Map.Entry<ForgeLayeredDraw, BooleanSupplier> value : subLayerStacks.values()) {
if (value.getKey() instanceof ForgeLayeredDraw searchable) {
@@ -337,32 +333,32 @@ public final class ForgeLayeredDraw implements ForgeLayer {
}
@Nullable
public ForgeLayeredDraw getChild(ResourceLocation childName) {
public ForgeLayeredDraw getChild(Identifier childName) {
return locateStack(childName).orElse(null);
}
@Nullable
public ForgeLayer getLayer(ResourceLocation layerName) {
public ForgeLayer getLayer(Identifier layerName) {
return namedLayers.get(layerName);
}
public ResourceLocation getName() {
public Identifier getName() {
return name;
}
private void stackNotPresentWarning(ResourceLocation stackName) {
LogUtils.getLogger().warn("Target stack {} was not present anywhere. Is your ResourceLocation correct?", stackName);
private void stackNotPresentWarning(Identifier stackName) {
LogUtils.getLogger().warn("Target stack {} was not present anywhere. Is your Identifier correct?", stackName);
}
private void layerNotPresentWarning(ResourceLocation layer) {
private void layerNotPresentWarning(Identifier layer) {
LogUtils.getLogger().warn("Expected layer {} was not found in stack {}, no layer modifications have been made.", layer, name);
}
private void nameTakenWarning(ResourceLocation layer) {
private void nameTakenWarning(Identifier layer) {
LogUtils.getLogger().warn("Name {} was already present in {} and cannot be re-used.", layer, name);
}
private boolean isNameAvailable(ResourceLocation name) {
private boolean isNameAvailable(Identifier name) {
return !namedLayers.containsKey(name) && !subLayerStacks.containsKey(name);
}
@@ -8,7 +8,7 @@ package net.minecraftforge.client.gui.overlay;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.client.event.RegisterGuiOverlaysEvent;
import net.minecraftforge.fml.ModLoader;
import org.jetbrains.annotations.ApiStatus;
@@ -26,7 +26,7 @@ import java.util.function.Function;
public final class GuiOverlayManager
{
private static ImmutableList<NamedGuiOverlay> OVERLAYS;
private static ImmutableMap<ResourceLocation, NamedGuiOverlay> OVERLAYS_BY_NAME;
private static ImmutableMap<Identifier, NamedGuiOverlay> OVERLAYS_BY_NAME;
/**
* Retrieves an ordered list of all registered overlays.
@@ -41,7 +41,7 @@ public final class GuiOverlayManager
* Do not call this before {@link RegisterGuiOverlaysEvent} has finished firing.
* /
@Nullable
public static NamedGuiOverlay findOverlay(ResourceLocation id)
public static NamedGuiOverlay findOverlay(Identifier id)
{
return OVERLAYS_BY_NAME.get(id);
}
@@ -49,8 +49,8 @@ public final class GuiOverlayManager
@ApiStatus.Internal
public static void init()
{
var overlays = new HashMap<ResourceLocation, IGuiOverlay>();
var orderedOverlays = new ArrayList<ResourceLocation>();
var overlays = new HashMap<Identifier, IGuiOverlay>();
var orderedOverlays = new ArrayList<Identifier>();
preRegisterVanillaOverlays(overlays, orderedOverlays);
var event = new RegisterGuiOverlaysEvent(overlays, orderedOverlays);
ModLoader.get().postEventWrapContainerInModOrder(event);
@@ -65,7 +65,7 @@ public final class GuiOverlayManager
/**
* Pre-registers vanilla overlays so they are available for ordering.
* /
private static void preRegisterVanillaOverlays(HashMap<ResourceLocation, IGuiOverlay> overlays, ArrayList<ResourceLocation> orderedOverlays)
private static void preRegisterVanillaOverlays(HashMap<Identifier, IGuiOverlay> overlays, ArrayList<Identifier> orderedOverlays)
{
for (var entry : VanillaGuiOverlay.values())
{
@@ -6,7 +6,7 @@
/** Forge 1.20.5 - Removed, Mojang created a layered rendering system that should make this all obsolete finally.. - Lex 042724
package net.minecraftforge.client.gui.overlay;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import org.jetbrains.annotations.ApiStatus;
/**
@@ -16,7 +16,7 @@ import org.jetbrains.annotations.ApiStatus;
* <p>
* Users should not be instantiating this themselves. Retrieve from {@link GuiOverlayManager}.
* /
public record NamedGuiOverlay(ResourceLocation id, IGuiOverlay overlay)
public record NamedGuiOverlay(Identifier id, IGuiOverlay overlay)
{
@ApiStatus.Internal
public NamedGuiOverlay
@@ -8,7 +8,7 @@ package net.minecraftforge.client.gui.overlay;
import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.Minecraft;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.util.Mth;
import net.minecraft.world.effect.MobEffects;
import net.minecraft.world.entity.Entity;
@@ -216,17 +216,17 @@ public enum VanillaGuiOverlay {
gui.renderPlayerList(screenWidth, screenHeight, guiGraphics);
});
private final ResourceLocation id;
private final Identifier id;
final IGuiOverlay overlay;
NamedGuiOverlay type;
VanillaGuiOverlay(String id, IGuiOverlay overlay) {
this.id = new ResourceLocation("minecraft", id);
this.id = new Identifier("minecraft", id);
this.overlay = overlay;
}
@NotNull
public ResourceLocation id() {
public Identifier id() {
return id;
}
@@ -38,7 +38,7 @@ public class ExtendedButton extends Button {
* Draws this button to the screen.
*/
@Override
public void renderWidget(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
public void renderContents(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
Minecraft mc = Minecraft.getInstance();
guiGraphics.blitSprite(RenderPipelines.GUI_TEXTURED, SPRITES.get(this.active, this.isHoveredOrFocused()), this.getX(), this.getY(), this.getWidth(), this.getHeight());
@@ -198,10 +198,9 @@ public class ForgeSlider extends AbstractSliderButton {
@Override
public void renderWidget(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
final Minecraft mc = Minecraft.getInstance();
guiGraphics.blitSprite(RenderPipelines.GUI_TEXTURED, this.getSprite(), this.getX(), this.getY(), this.getWidth(), this.getHeight());
guiGraphics.blitSprite(RenderPipelines.GUI_TEXTURED, this.getHandleSprite(), this.getX() + (int)(this.value * (double)(this.width - 8)), this.getY(), 8, this.getHeight());
renderScrollingString(guiGraphics, mc.font, 2, getFGColor() | Mth.ceil(this.alpha * 255.0F) << 24);
renderScrollingStringOverContents(guiGraphics.textRendererForWidget(this, GuiGraphics.HoveredTextEffects.NONE), this.getMessage(), 2);
}
}
@@ -10,7 +10,7 @@ import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.ObjectSelectionList;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.client.renderer.RenderPipelines;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.FormattedText;
import net.minecraft.locale.Language;
@@ -22,7 +22,7 @@ import net.minecraftforge.forgespi.language.IModInfo;
public class ModListWidget extends ObjectSelectionList<ModListWidget.ModEntry> {
private static String stripControlCodes(String value) { return net.minecraft.util.StringUtil.stripColor(value); }
private static final ResourceLocation VERSION_CHECK_ICONS = ResourceLocation.fromNamespaceAndPath(ForgeVersion.MOD_ID, "textures/gui/version_check_icons.png");
private static final Identifier VERSION_CHECK_ICONS = Identifier.fromNamespaceAndPath(ForgeVersion.MOD_ID, "textures/gui/version_check_icons.png");
private final int listWidth;
private final ModListScreen parent;
@@ -19,7 +19,7 @@ import java.util.List;
* Abstract scroll panel class.
*/
public abstract class ScrollPanel extends AbstractContainerEventHandler implements Renderable, NarratableEntry {
private final Minecraft client;
protected final Minecraft client;
protected final int width;
protected final int height;
protected final int top;
@@ -10,7 +10,7 @@ import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.screens.LoadingOverlay;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.rendertype.RenderType;
import net.minecraft.server.packs.resources.ReloadInstance;
import net.minecraft.util.ARGB;
import net.minecraft.util.Mth;
@@ -33,6 +33,7 @@ import java.util.function.Supplier;
*
* It is somewhat a copy of the superclass render method.
*/
@SuppressWarnings("unused")
public class ForgeLoadingOverlay extends LoadingOverlay {
private static final boolean ENABLE = false; //Boolean.parseBoolean("forge.enableForgeLoadingOverlay");
private final Minecraft minecraft;
@@ -18,7 +18,7 @@ import net.minecraft.client.resources.model.ModelDebugName;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.QuadCollection;
import net.minecraft.client.resources.model.UnbakedGeometry;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.util.GsonHelper;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.world.level.material.Fluids;
@@ -65,7 +65,7 @@ public class DynamicFluidContainerModel implements UnbakedGeometry {
}
@SuppressWarnings("deprecation")
private static Material getMaterial(ResourceLocation texture) {
private static Material getMaterial(Identifier texture) {
return new Material(TextureAtlas.LOCATION_BLOCKS, texture);
}
@@ -116,7 +116,7 @@ public class DynamicFluidContainerModel implements UnbakedGeometry {
if (baseSprite != null) {
// Base texture
var unbaked = UnbakedGeometryHelper.createUnbakedItemElements(0, baseSprite.contents());
UnbakedGeometryHelper.bakeElements(unbaked, $ -> baseSprite, state, buf);
UnbakedGeometryHelper.bakeElements(baker.parts(), unbaked, $ -> baseSprite, state, buf);
}
if (fluidMaskLocation != null && fluidSprite != null) {
@@ -126,10 +126,11 @@ public class DynamicFluidContainerModel implements UnbakedGeometry {
var transformedState = new SimpleModelState(transformation.compose(FLUID_TRANSFORM));
var unbaked = UnbakedGeometryHelper.createUnbakedItemMaskElements(1, templateSprite.contents()); // Use template as mask
var emissive = applyFluidLuminosity && fluid.getFluidType().getLightLevel() > 0;
var transformer = emissive ? QuadTransformers.settingMaxEmissivity() : QuadTransformers.empty();
//var emissive = applyFluidLuminosity && fluid.getFluidType().getLightLevel() > 0;
//var transformer = emissive ? QuadTransformers.settingMaxEmissivity() : QuadTransformers.empty();
// TODO: [Forge][Rendering] Emissive fluid models
UnbakedGeometryHelper.bakeElements(unbaked, $ -> fluidSprite, transformedState, transformer, buf); // Bake with fluid texture
UnbakedGeometryHelper.bakeElements(baker.parts(), unbaked, $ -> fluidSprite, transformedState, buf); // Bake with fluid texture
}
}
@@ -139,7 +140,7 @@ public class DynamicFluidContainerModel implements UnbakedGeometry {
// Cover/overlay
var transformedState = new SimpleModelState(transformation.compose(COVER_TRANSFORM));
var unbaked = UnbakedGeometryHelper.createUnbakedItemMaskElements(2, coverSprite.contents()); // Use cover as mask
UnbakedGeometryHelper.bakeElements(unbaked, $ -> sprite, transformedState, buf); // Bake with selected texture
UnbakedGeometryHelper.bakeElements(baker.parts(), unbaked, $ -> sprite, transformedState, buf); // Bake with selected texture
}
}
@@ -154,7 +155,7 @@ public class DynamicFluidContainerModel implements UnbakedGeometry {
@Override
public UnbakedGeometry read(JsonObject jsonObject, JsonDeserializationContext deserializationContext) {
var fluidName = ResourceLocation.parse(GsonHelper.getAsString(jsonObject, "fluid"));
var fluidName = Identifier.parse(GsonHelper.getAsString(jsonObject, "fluid"));
Fluid fluid = ForgeRegistries.FLUIDS.getValue(fluidName);
@@ -10,12 +10,12 @@ import java.util.Optional;
import com.mojang.math.Transformation;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
public record ForgeBlockModelData(
Optional<Transformation> transform,
Optional<ResourceLocation> renderType,
Optional<ResourceLocation> renderTypeFast,
Optional<Identifier> renderType,
Optional<Identifier> renderTypeFast,
Optional<Map<String, Boolean>> visibility
) {
public ForgeBlockModelData() {
@@ -5,13 +5,10 @@
package net.minecraftforge.client.model;
import java.util.function.Function;
import javax.annotation.Nullable;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.mojang.datafixers.util.Either;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import com.mojang.serialization.codecs.RecordCodecBuilder;
@@ -23,27 +20,17 @@ import net.minecraft.client.renderer.block.model.BlockElementFace;
* Holds extra data that may be injected into a face.<p>
* Used by {@link ItemLayerGeometry}, {@link BlockElement} and {@link BlockElementFace}
*
* @param color Color in ARGB format
* @param blockLight Block Light for this face from 0-15 (inclusive)
* @param skyLight Sky Light for this face from 0-15 (inclusive)
* @param ambientOcclusion If this face has AO
* @param calculateNormals If we should manually calculate the normals for this block or inherit facing normals like vanilla
*/
public record ForgeFaceData(int color, int blockLight, int skyLight, boolean ambientOcclusion, boolean calculateNormals) {
public ForgeFaceData(int color, int blockLight, int skyLight, boolean ambientOcclusion) {
this(color, blockLight, skyLight, ambientOcclusion, false);
public record ForgeFaceData(boolean ambientOcclusion, boolean calculateNormals) {
public ForgeFaceData(boolean ambientOcclusion) {
this(ambientOcclusion, false);
}
public static final ForgeFaceData DEFAULT = new ForgeFaceData(0xFFFFFFFF, 0, 0, true, false);
public static final Codec<Integer> COLOR = Codec.either(Codec.INT, Codec.STRING).xmap(
either -> either.map(Function.identity(), str -> (int) Long.parseLong(str, 16)),
color -> Either.right(Integer.toHexString(color)));
public static final ForgeFaceData DEFAULT = new ForgeFaceData(true, false);
public static final Codec<ForgeFaceData> CODEC = RecordCodecBuilder.create(builder -> builder.group(
COLOR.optionalFieldOf("color", 0xFFFFFFFF).forGetter(ForgeFaceData::color),
Codec.intRange(0, 15).optionalFieldOf("block_light", 0).forGetter(ForgeFaceData::blockLight),
Codec.intRange(0, 15).optionalFieldOf("sky_light", 0).forGetter(ForgeFaceData::skyLight),
Codec.BOOL.optionalFieldOf("ambient_occlusion", true).forGetter(ForgeFaceData::ambientOcclusion),
Codec.BOOL.optionalFieldOf("calculate_normals", false).forGetter(ForgeFaceData::calculateNormals))
.apply(builder, ForgeFaceData::new));
@@ -1,160 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.ItemTransforms;
import net.minecraft.client.renderer.block.model.SimpleModelWrapper;
import net.minecraft.client.renderer.item.EmptyModel;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.renderer.block.model.BlockModelPart;
import net.minecraft.client.resources.model.QuadCollection;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.RenderTypeGroup;
import java.util.List;
/**
* Base interface for any object that collects culled and unculled faces and bakes them into a model.
* <p>
* Provides a generic base implementation via {@link #of(boolean, boolean, boolean, ItemTransforms, TextureAtlasSprite, RenderTypeGroup, RenderTypeGroup)}
* and a quad-collecting alternative via {@link #collecting(List)}.
*
* @deprecated Use {@link net.minecraft.client.resources.model.QuadCollection} instead.
*/
@Deprecated(forRemoval = true, since = "1.21.5")
public interface IModelBuilder<T extends IModelBuilder<T>> {
/**
* Creates a new model builder that uses the provided attributes in the final baked model.
*/
static IModelBuilder<?> of(
boolean hasAmbientOcclusion,
boolean usesBlockLight,
boolean isGui3d,
ItemTransforms transforms,
TextureAtlasSprite particle
){
return of(hasAmbientOcclusion, usesBlockLight, isGui3d, transforms, particle, RenderTypeGroup.EMPTY);
}
static IModelBuilder<?> of(
boolean hasAmbientOcclusion,
boolean usesBlockLight,
boolean isGui3d,
ItemTransforms transforms,
TextureAtlasSprite particle,
RenderTypeGroup renderTypes
){
return new Simple(hasAmbientOcclusion, usesBlockLight, isGui3d, transforms, particle, renderTypes);
}
static IModelBuilder<?> of(
boolean hasAmbientOcclusion,
boolean usesBlockLight,
boolean isGui3d,
ItemTransforms transforms,
TextureAtlasSprite particle,
RenderTypeGroup renderTypes,
RenderTypeGroup renderTypesFast
){
return new Simple(hasAmbientOcclusion, usesBlockLight, isGui3d, transforms, particle, renderTypes, renderTypesFast);
}
/**
* Creates a new model builder that collects quads to the provided list, returning
* {@linkplain EmptyModel#BAKED an empty model} if you call {@link #build()}.
*/
static IModelBuilder<?> collecting(List<BakedQuad> quads) {
return new Collecting(quads);
}
T addCulledFace(Direction facing, BakedQuad quad);
T addUnculledFace(BakedQuad quad);
BlockModelPart build();
class Simple implements IModelBuilder<Simple> {
private final QuadCollection.Builder builder;
private final boolean hasAmbientOcclusion;
// TODO: [VEN] These are UNUSED, and this is GOING TO BREAK.
private final boolean usesBlockLight;
private final boolean isGui3d;
private final ItemTransforms transforms;
private final TextureAtlasSprite particle;
private final RenderTypeGroup renderTypes;
private final RenderTypeGroup renderTypesFast;
private Simple(
boolean hasAmbientOcclusion, boolean usesBlockLight, boolean isGui3d,
ItemTransforms transforms, TextureAtlasSprite particle, RenderTypeGroup renderTypes
) {
this(hasAmbientOcclusion, usesBlockLight, isGui3d, transforms, particle, renderTypes, RenderTypeGroup.EMPTY);
}
private Simple(
boolean hasAmbientOcclusion, boolean usesBlockLight, boolean isGui3d,
ItemTransforms transforms, TextureAtlasSprite particle, RenderTypeGroup renderTypes, RenderTypeGroup renderTypesFast
) {
this.builder = new QuadCollection.Builder();
this.hasAmbientOcclusion = hasAmbientOcclusion;
this.usesBlockLight = usesBlockLight;
this.isGui3d = isGui3d;
this.transforms = transforms;
this.particle = particle;
this.renderTypes = renderTypes;
this.renderTypesFast = renderTypesFast;
}
@Override
public Simple addCulledFace(Direction facing, BakedQuad quad) {
builder.addCulledFace(facing, quad);
return this;
}
@Override
public Simple addUnculledFace(BakedQuad quad) {
builder.addUnculledFace(quad);
return this;
}
@Override
public BlockModelPart build() {
var quads = builder.build();
// TODO: [VEN] Models will NOT be complete here!!!!
return new SimpleModelWrapper(quads, hasAmbientOcclusion, particle);
}
}
class Collecting implements IModelBuilder<Collecting> {
private static final BlockModelPart EMPTY = new SimpleModelWrapper(QuadCollection.EMPTY, false, new TextureAtlasSprite(ResourceLocation.fromNamespaceAndPath("forge", "empty"), null, 0, 0, 0, 0) {});
private final List<BakedQuad> quads;
private Collecting(List<BakedQuad> quads) {
this.quads = quads;
}
@Override
public Collecting addCulledFace(Direction facing, BakedQuad quad) {
quads.add(quad);
return this;
}
@Override
public Collecting addUnculledFace(BakedQuad quad) {
quads.add(quad);
return this;
}
@Override
public BlockModelPart build() {
return EMPTY;
}
}
}
@@ -5,8 +5,6 @@
package net.minecraftforge.client.model;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.VertexFormatElement;
import net.minecraft.client.renderer.block.model.BakedQuad;
import java.util.List;
@@ -17,14 +15,6 @@ import java.util.List;
*/
@FunctionalInterface
public interface IQuadTransformer {
int STRIDE = DefaultVertexFormat.BLOCK.getVertexSize() / 4;
int POSITION = findOffset(VertexFormatElement.POSITION);
int COLOR = findOffset(VertexFormatElement.COLOR);
int UV0 = findOffset(VertexFormatElement.UV0);
int UV1 = findOffset(VertexFormatElement.UV1);
int UV2 = findOffset(VertexFormatElement.UV2);
int NORMAL = findOffset(VertexFormatElement.NORMAL);
BakedQuad process(BakedQuad quad);
default List<BakedQuad> process(List<BakedQuad> inputs) {
@@ -34,10 +24,4 @@ public interface IQuadTransformer {
default IQuadTransformer andThen(IQuadTransformer other) {
return quad -> other.process(process(quad));
}
private static int findOffset(VertexFormatElement element) {
// Divide by 4 because we want the int offset
var index = DefaultVertexFormat.BLOCK.getOffset(element);
return index < 0 ? -1 : index / 4;
}
}
@@ -12,7 +12,7 @@ import com.google.gson.JsonParseException;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectMaps;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.rendertype.RenderType;
import net.minecraft.client.renderer.block.model.ItemModelGenerator;
import net.minecraft.client.renderer.block.model.SimpleUnbakedGeometry;
import net.minecraft.client.renderer.block.model.TextureSlots;
@@ -24,7 +24,7 @@ import net.minecraft.client.resources.model.ModelDebugName;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.QuadCollection;
import net.minecraft.client.resources.model.UnbakedGeometry;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.client.ForgeRenderTypes;
import net.minecraftforge.client.RenderTypeGroup;
import net.minecraftforge.client.model.geometry.IGeometryBakingContext;
@@ -47,10 +47,10 @@ import org.jetbrains.annotations.Nullable;
public class ItemLayerGeometry implements UnbakedGeometry {
private static final ItemLayerGeometry INSTANCE = new ItemLayerGeometry(Int2ObjectMaps.emptyMap(), Int2ObjectMaps.emptyMap());
private final Int2ObjectMap<ResourceLocation> renderTypeNames;
private final Int2ObjectMap<ResourceLocation> renderTypeFastNames;
private final Int2ObjectMap<Identifier> renderTypeNames;
private final Int2ObjectMap<Identifier> renderTypeFastNames;
private ItemLayerGeometry(Int2ObjectMap<ResourceLocation> renderTypeNames, Int2ObjectMap<ResourceLocation> renderTypeFastNames) {
private ItemLayerGeometry(Int2ObjectMap<Identifier> renderTypeNames, Int2ObjectMap<Identifier> renderTypeFastNames) {
this.renderTypeNames = renderTypeNames;
this.renderTypeFastNames = renderTypeFastNames;
}
@@ -69,7 +69,7 @@ public class ItemLayerGeometry implements UnbakedGeometry {
elements.addAll(ItemModelGenerator.processFrames(i, layer, contents));
}
return SimpleUnbakedGeometry.bake(elements, textures, baker.sprites(), state, name);
return SimpleUnbakedGeometry.bake(elements, textures, baker, state, name);
/*
Material particleMaterial = spriteGetter.getMaterial("particle");
var particle = baker.sprites().get(particleMaterial == null ? textures.get(0) : particleMaterial, name);
@@ -107,12 +107,12 @@ public class ItemLayerGeometry implements UnbakedGeometry {
*/
}
private static Int2ObjectMap<ResourceLocation> readRenderTypeNames(JsonObject jsonObject, String key) {
var renderTypeNames = new Int2ObjectOpenHashMap<ResourceLocation>();
private static Int2ObjectMap<Identifier> readRenderTypeNames(JsonObject jsonObject, String key) {
var renderTypeNames = new Int2ObjectOpenHashMap<Identifier>();
if (jsonObject.has(key)) {
var renderTypes = jsonObject.getAsJsonObject(key);
for (var entry : renderTypes.entrySet()) {
var renderType = ResourceLocation.parse(entry.getKey());
var renderType = Identifier.parse(entry.getKey());
for (var layer : entry.getValue().getAsJsonArray())
if (renderTypeNames.put(layer.getAsInt(), renderType) != null)
throw new JsonParseException("Registered duplicate " + key + " for layer " + layer);
@@ -5,16 +5,12 @@
package net.minecraftforge.client.model;
import com.google.common.base.Preconditions;
import com.mojang.math.Transformation;
import net.minecraft.Util;
import net.minecraft.client.renderer.LightTexture;
import net.minecraft.client.renderer.block.model.BakedQuad;
import org.joml.Vector3f;
import org.joml.Vector3fc;
import org.joml.Vector4f;
import java.util.Arrays;
/**
* A collection of {@link IQuadTransformer} implementations.
*
@@ -22,9 +18,6 @@ import java.util.Arrays;
*/
public final class QuadTransformers {
private static final IQuadTransformer EMPTY = quad -> quad;
private static final IQuadTransformer[] EMISSIVE_TRANSFORMERS = Util.make(new IQuadTransformer[16], array -> {
Arrays.setAll(array, i -> applyingLightmap(LightTexture.pack(i, i)));
});
/**
* {@return a {@link BakedQuad} transformer that does nothing}
@@ -41,116 +34,19 @@ public final class QuadTransformers {
return empty();
return quad -> {
var vertices = Arrays.copyOf(quad.vertices(), quad.vertices().length);
var positions = new Vector3fc[4];
for (int i = 0; i < 4; i++) {
int offset = i * IQuadTransformer.STRIDE + IQuadTransformer.POSITION;
float x = Float.intBitsToFloat(vertices[offset]);
float y = Float.intBitsToFloat(vertices[offset + 1]);
float z = Float.intBitsToFloat(vertices[offset + 2]);
Vector4f pos = new Vector4f(x, y, z, 1);
var pos = new Vector4f(quad.position(i), 1);
transform.transformPosition(pos);
pos.div(pos.w);
vertices[offset] = Float.floatToRawIntBits(pos.x());
vertices[offset + 1] = Float.floatToRawIntBits(pos.y());
vertices[offset + 2] = Float.floatToRawIntBits(pos.z());
positions[i] = new Vector3f(pos.x(), pos.y(), pos.z());
}
for (int i = 0; i < 4; i++) {
int offset = i * IQuadTransformer.STRIDE + IQuadTransformer.NORMAL;
int normalIn = vertices[offset];
if ((normalIn & 0x00FFFFFF) != 0) { // The ignored byte is padding and may be filled with user data
float x = ((byte) (normalIn & 0xFF)) / 127.0f;
float y = ((byte) ((normalIn >> 8) & 0xFF)) / 127.0f;
float z = ((byte) ((normalIn >> 16) & 0xFF)) / 127.0f;
Vector3f pos = new Vector3f(x, y, z);
transform.transformNormal(pos);
vertices[offset] = (((byte) (pos.x() * 127.0f)) & 0xFF) |
((((byte) (pos.y() * 127.0f)) & 0xFF) << 8) |
((((byte) (pos.z() * 127.0f)) & 0xFF) << 16) |
(normalIn & 0xFF000000); // Restore padding, just in case
}
}
return new BakedQuad(vertices, quad.tintIndex(), quad.direction(), quad.sprite(), quad.shade(), quad.lightEmission(), quad.ambientOcclusion());
return new BakedQuad(positions[0], positions[1], positions[2], positions[3],
quad.packedUV0(), quad.packedUV1(), quad.packedUV2(), quad.packedUV3(),
quad.tintIndex(), quad.direction(), quad.sprite(), quad.shade(), quad.lightEmission(), quad.ambientOcclusion());
};
}
/**
* @return A new {@link BakedQuad} transformer that applies the specified packed light value.
*/
public static IQuadTransformer applyingLightmap(int packedLight) {
return quad -> {
var vertices = Arrays.copyOf(quad.vertices(), quad.vertices().length);
for (int i = 0; i < 4; i++)
vertices[i * IQuadTransformer.STRIDE + IQuadTransformer.UV2] = packedLight;
return new BakedQuad(vertices, quad.tintIndex(), quad.direction(), quad.sprite(), quad.shade(), quad.lightEmission(), quad.ambientOcclusion());
};
}
/**
* @return A new {@link BakedQuad} transformer that applies the specified block and sky light values.
*/
public static IQuadTransformer applyingLightmap(int blockLight, int skyLight) {
return applyingLightmap(LightTexture.pack(blockLight, skyLight));
}
/**
* @return A {@link BakedQuad} transformer that sets the lightmap to the given emissivity (0-15)
*/
public static IQuadTransformer settingEmissivity(int emissivity) {
Preconditions.checkArgument(emissivity >= 0 && emissivity < 16, "Emissivity must be between 0 and 15.");
return EMISSIVE_TRANSFORMERS[emissivity];
}
/**
* @return A {@link BakedQuad} transformer that sets the lightmap to its max value
*/
public static IQuadTransformer settingMaxEmissivity() {
return EMISSIVE_TRANSFORMERS[15];
}
/**
* @param color The color in ARGB format.
* @return A {@link BakedQuad} transformer that sets the color to the specified value.
*/
public static IQuadTransformer applyingColor(int color) {
final int fixedColor = toABGR(color);
return quad -> {
var vertices = Arrays.copyOf(quad.vertices(), quad.vertices().length);
for (int i = 0; i < 4; i++)
vertices[i * IQuadTransformer.STRIDE + IQuadTransformer.COLOR] = fixedColor;
return new BakedQuad(vertices, quad.tintIndex(), quad.direction(), quad.sprite(), quad.shade(), quad.lightEmission(), quad.ambientOcclusion());
};
}
/**
* This method supplies a default alpha value of 255 (no transparency)
* @param red The red value (0-255)
* @param green The green value (0-255)
* @param blue The blue value (0-255)
* @return A {@link BakedQuad} transformer that sets the color to the specified value.
*/
public static IQuadTransformer applyingColor(int red, int green, int blue) {
return applyingColor(255, red, green, blue);
}
/**
* @param alpha The alpha value (0-255)
* @param red The red value (0-255)
* @param green The green value (0-255)
* @param blue The blue value (0-255)
* @return A {@link BakedQuad} transformer that sets the color to the specified value.
*/
public static IQuadTransformer applyingColor(int alpha, int red, int green, int blue) {
return applyingColor(alpha << 24 | red << 16 | green << 8 | blue);
}
/**
* Converts an ARGB color to an ABGR color, as the commonly used color format is not the format colors end up packed into.
* This function doubles as its own inverse.
@@ -1,37 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators;
import com.google.gson.JsonObject;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.data.ExistingFileHelper;
/**
* Builder for block models, does not currently provide any additional
* functionality over {@link ModelBuilder}, purely a stub class with a concrete
* generic.
*
* @see ModelProvider
* @see ModelBuilder
*
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
@Deprecated(since = "1.21.4", forRemoval = true)
public class BlockModelBuilder extends ModelBuilder<BlockModelBuilder>
{
public BlockModelBuilder(ResourceLocation outputLocation, ExistingFileHelper existingFileHelper)
{
super(outputLocation, existingFileHelper);
}
@Override
public JsonObject toJson()
{
return super.toJson();
}
}
@@ -1,32 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators;
import net.minecraft.data.PackOutput;
import net.minecraftforge.common.data.ExistingFileHelper;
import org.jetbrains.annotations.NotNull;
/**
* Stub class to extend for block model data providers, eliminates some
* boilerplate constructor parameters.
*
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
@Deprecated(since = "1.21.4", forRemoval = true)
public abstract class BlockModelProvider extends ModelProvider<BlockModelBuilder> {
public BlockModelProvider(PackOutput output, String modid, ExistingFileHelper existingFileHelper) {
super(output, modid, BLOCK_FOLDER, BlockModelBuilder::new, existingFileHelper);
}
@NotNull
@Override
public String getName() {
return "Block Models: " + modid;
}
}
File diff suppressed because it is too large. Load diff
@@ -1,323 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.IntStream;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ObjectArrays;
import com.google.gson.JsonObject;
import com.mojang.math.Quadrant;
import net.minecraft.client.resources.model.BlockModelRotation;
import net.minecraft.util.Mth;
import net.minecraftforge.client.model.generators.MultiPartBlockStateBuilder.PartBuilder;
import net.minecraftforge.client.model.generators.VariantBlockStateBuilder.PartialBlockstate;
import org.jetbrains.annotations.Nullable;
/**
* Represents a model with blockstate configurations, e.g. rotation, uvlock, and
* random weight.
* <p>
* Can be manually constructed, created by static factory such as
* {@link #allYRotations(ModelFile, int, boolean)}, or created by builder via
* {@link #builder()}.
*
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
@Deprecated(since = "1.21.4", forRemoval = true)
public final class ConfiguredModel {
/**
* The default random weight of configured models, used by convenience
* overloads.
*/
public static final int DEFAULT_WEIGHT = 1;
public final ModelFile model;
public final int rotationX;
public final int rotationY;
public final boolean uvLock;
public final int weight;
private static IntStream validRotations() {
return IntStream.range(0, 4).map(i -> i * 90);
}
public static ConfiguredModel[] allYRotations(ModelFile model, int x, boolean uvlock) {
return allYRotations(model, x, uvlock, DEFAULT_WEIGHT);
}
public static ConfiguredModel[] allYRotations(ModelFile model, int x, boolean uvlock, int weight) {
return validRotations()
.mapToObj(y -> new ConfiguredModel(model, x, y, uvlock, weight))
.toArray(ConfiguredModel[]::new);
}
public static ConfiguredModel[] allRotations(ModelFile model, boolean uvlock) {
return allRotations(model, uvlock, DEFAULT_WEIGHT);
}
public static ConfiguredModel[] allRotations(ModelFile model, boolean uvlock, int weight) {
return validRotations()
.mapToObj(x -> allYRotations(model, x, uvlock, weight))
.flatMap(Arrays::stream)
.toArray(ConfiguredModel[]::new);
}
/**
* Construct a new {@link ConfiguredModel}.
*
* @param model the underlying model
* @param rotationX x-rotation to apply to the model
* @param rotationY y-rotation to apply to the model
* @param uvLock if uvlock should be enabled
* @param weight the random weight of the model
*
* @throws NullPointerException if {@code model} is {@code null}
* @throws IllegalArgumentException if x and/or y rotation are not valid (see
* {@link BlockModelRotation})
* @throws IllegalArgumentException if weight is less than or equal to zero
*/
public ConfiguredModel(ModelFile model, int rotationX, int rotationY, boolean uvLock, int weight) {
Preconditions.checkNotNull(model);
this.model = model;
checkRotation(rotationX, rotationY);
this.rotationX = rotationX;
this.rotationY = rotationY;
this.uvLock = uvLock;
checkWeight(weight);
this.weight = weight;
}
/**
* Construct a new {@link ConfiguredModel} with the {@link #DEFAULT_WEIGHT
* default random weight}.
*
* @param model the underlying model
* @param rotationX x-rotation to apply to the model
* @param rotationY y-rotation to apply to the model
* @param uvLock if uvlock should be enabled
*
* @throws NullPointerException if {@code model} is {@code null}
* @throws IllegalArgumentException if x and/or y rotation are not valid (see
* {@link BlockModelRotation})
*/
public ConfiguredModel(ModelFile model, int rotationX, int rotationY, boolean uvLock) {
this(model, rotationX, rotationY, uvLock, DEFAULT_WEIGHT);
}
/**
* Construct a new {@link ConfiguredModel} with the default rotation (0, 0),
* uvlock (false), and {@link #DEFAULT_WEIGHT default random weight}.
*
* @throws NullPointerException if {@code model} is {@code null}
*/
public ConfiguredModel(ModelFile model) {
this(model, 0, 0, false);
}
static void checkRotation(int rotationX, int rotationY) {
Preconditions.checkArgument(quadrantFromDeg(rotationX) == null || quadrantFromDeg(rotationY) == null, "Invalid model rotation x=%d, y=%d", rotationX, rotationY);
}
static @Nullable Quadrant quadrantFromDeg(int degrees) {
return switch (Mth.positiveModulo(degrees, 360)) {
case 0 -> Quadrant.R0;
case 90 -> Quadrant.R90;
case 180 -> Quadrant.R180;
case 270 -> Quadrant.R270;
default -> null;
};
}
static void checkWeight(int weight) {
Preconditions.checkArgument(weight >= 1, "Model weight must be greater than or equal to 1. Found: %d", weight);
}
JsonObject toJSON(boolean includeWeight) {
JsonObject modelJson = new JsonObject();
modelJson.addProperty("model", model.getLocation().toString());
if (rotationX != 0)
modelJson.addProperty("x", rotationX);
if (rotationY != 0)
modelJson.addProperty("y", rotationY);
if (uvLock)
modelJson.addProperty("uvlock", uvLock);
if (includeWeight && weight != DEFAULT_WEIGHT)
modelJson.addProperty("weight", weight);
return modelJson;
}
/**
* Create a new unowned {@link Builder}.
*
* @return the builder
* @see Builder
*/
public static Builder<?> builder() {
return new Builder<>();
}
static Builder<VariantBlockStateBuilder> builder(VariantBlockStateBuilder outer, PartialBlockstate state) {
return new Builder<>(models -> outer.setModels(state, models), ImmutableList.of());
}
static Builder<PartBuilder> builder(MultiPartBlockStateBuilder outer) {
return new Builder<PartBuilder>(models -> {
PartBuilder ret = outer.new PartBuilder(new BlockStateProvider.ConfiguredModelList(models));
outer.addPart(ret);
return ret;
}, ImmutableList.of());
}
/**
* A builder for {@link ConfiguredModel}s, which can contain a callback for
* processing the finished result. If no callback is available (e.g. in the case
* of {@link ConfiguredModel#builder()}), some methods will not be available.
* <p>
* Multiple models can be configured at once through the use of
* {@link #nextModel()}.
*
* @param <T> the type of the owning builder, which supplied the callback, and
* will be returned upon completion.
*/
public static class Builder<T> {
private ModelFile model;
@Nullable
private final Function<ConfiguredModel[], T> callback;
private final List<ConfiguredModel> otherModels;
private int rotationX;
private int rotationY;
private boolean uvLock;
private int weight = DEFAULT_WEIGHT;
Builder() {
this(null, ImmutableList.of());
}
Builder(@Nullable Function<ConfiguredModel[], T> callback, List<ConfiguredModel> otherModels) {
this.callback = callback;
this.otherModels = otherModels;
}
/**
* Set the underlying model object for this configured model.
*
* @param model the model
* @return this builder
* @throws NullPointerException if {@code model} is {@code null}
*/
public Builder<T> modelFile(ModelFile model) {
Preconditions.checkNotNull(model, "Model must not be null");
this.model = model;
return this;
}
/**
* Set the x-rotation for this model.
*
* @param value the x-rotation value
* @return this builder
* @throws IllegalArgumentException if {@code value} is not a valid x-rotation
* (see {@link BlockModelRotation})
*/
public Builder<T> rotationX(int value) {
checkRotation(value, rotationY);
rotationX = value;
return this;
}
/**
* Set the y-rotation for this model.
*
* @param value the y-rotation value
* @return this builder
* @throws IllegalArgumentException if {@code value} is not a valid y-rotation
* (see {@link BlockModelRotation})
*/
public Builder<T> rotationY(int value) {
checkRotation(rotationX, value);
rotationY = value;
return this;
}
public Builder<T> uvLock(boolean value) {
uvLock = value;
return this;
}
/**
* Set the random weight for this model.
*
* @param value the weight value
* @return this builder
* @throws IllegalArgumentException if {@code value} is less than or equal to
* zero
*/
public Builder<T> weight(int value) {
checkWeight(value);
weight = value;
return this;
}
/**
* Build the most recent model, as if {@link #nextModel()} was never called.
* Useful for single-model builders.
*
* @return the most recently configured model
*/
public ConfiguredModel buildLast() {
return new ConfiguredModel(model, rotationX, rotationY, uvLock, weight);
}
/**
* Build all configured models and return them as an array.
*
* @return the array of built models.
*/
public ConfiguredModel[] build() {
return ObjectArrays.concat(otherModels.toArray(new ConfiguredModel[0]), buildLast());
}
/**
* Apply the contained callback and return the owning builder object. What the
* callback does is not defined by this class, but most likely it adds the built
* models to the current variant being configured.
* <p>
* Known callbacks include:
* <ul>
* <li>{@link PartialBlockstate#modelForState()}</li>
* <li>{@link MultiPartBlockStateBuilder#part()}</li>
* </ul>
*
* @return the owning builder object
* @throws NullPointerException if there is no owning builder (and thus no callback)
*/
public T addModel() {
Preconditions.checkNotNull(callback, "Cannot use addModel() without an owning builder present");
return callback.apply(build());
}
/**
* Complete the current model and return a new builder instance with the same
* callback, and storing all previously built models.
*
* @return a new builder for configuring the next model
*/
public Builder<T> nextModel() {
return new Builder<>(callback, Arrays.asList(build()));
}
}
}
@@ -1,70 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators;
import com.google.common.base.Preconditions;
import com.google.gson.JsonObject;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.data.ExistingFileHelper;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
*
* This is the only class that doesn't seem to have a vanilla alternative however, it should be a simple helper
* function to replace this functionality for your custom models
*
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
@Deprecated(since = "1.21.4", forRemoval = true)
public abstract class CustomLoaderBuilder<T extends ModelBuilder<T>>
{
protected final ResourceLocation loaderId;
protected final T parent;
protected final ExistingFileHelper existingFileHelper;
protected final Map<String, Boolean> visibility = new LinkedHashMap<>();
protected CustomLoaderBuilder(ResourceLocation loaderId, T parent, ExistingFileHelper existingFileHelper)
{
this.loaderId = loaderId;
this.parent = parent;
this.existingFileHelper = existingFileHelper;
}
public CustomLoaderBuilder<T> visibility(String partName, boolean show)
{
Preconditions.checkNotNull(partName, "partName must not be null");
this.visibility.put(partName, show);
return this;
}
public T end()
{
return parent;
}
public JsonObject toJson(JsonObject json)
{
json.addProperty("loader", loaderId.toString());
if (!visibility.isEmpty())
{
JsonObject visibilityObj = new JsonObject();
for(Map.Entry<String, Boolean> entry : visibility.entrySet())
{
visibilityObj.addProperty(entry.getKey(), entry.getValue());
}
json.add("visibility", visibilityObj);
}
return json;
}
}
@@ -1,21 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators;
import com.google.gson.JsonObject;
import org.jetbrains.annotations.VisibleForTesting;
/**
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
@Deprecated(since = "1.21.4", forRemoval = true)
@VisibleForTesting
public interface IGeneratedBlockState
{
JsonObject toJson();
}
@@ -1,94 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.google.common.base.Preconditions;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.data.ExistingFileHelper;
/**
* Builder for item models, adds the ability to build overrides via
* {@link #override()}.
*
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
@Deprecated(since = "1.21.4", forRemoval = true)
public class ItemModelBuilder extends ModelBuilder<ItemModelBuilder> {
protected List<OverrideBuilder> overrides = new ArrayList<>();
public ItemModelBuilder(ResourceLocation outputLocation, ExistingFileHelper existingFileHelper) {
super(outputLocation, existingFileHelper);
}
public OverrideBuilder override() {
OverrideBuilder ret = new OverrideBuilder();
overrides.add(ret);
return ret;
}
/**
* Get an existing override builder
*
* @param index the index of the existing override builder
* @return the override builder
* @throws IndexOutOfBoundsException if {@code} index is out of bounds
*/
public OverrideBuilder override(int index) {
Preconditions.checkElementIndex(index, overrides.size(), "override");
return overrides.get(index);
}
@Override
public JsonObject toJson() {
JsonObject root = super.toJson();
if (!overrides.isEmpty()) {
JsonArray overridesJson = new JsonArray();
overrides.stream().map(OverrideBuilder::toJson).forEach(overridesJson::add);
root.add("overrides", overridesJson);
}
return root;
}
public class OverrideBuilder {
private ModelFile model;
private final Map<ResourceLocation, Float> predicates = new LinkedHashMap<>();
public OverrideBuilder model(ModelFile model) {
this.model = model;
model.assertExistence();
return this;
}
public OverrideBuilder predicate(ResourceLocation key, float value) {
this.predicates.put(key, value);
return this;
}
public ItemModelBuilder end() { return ItemModelBuilder.this; }
JsonObject toJson() {
JsonObject ret = new JsonObject();
JsonObject predicatesJson = new JsonObject();
predicates.forEach((key, val) -> predicatesJson.addProperty(key.toString(), val));
ret.add("predicate", predicatesJson);
ret.addProperty("model", model.getLocation().toString());
return ret;
}
}
}
@@ -1,49 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators;
import net.minecraft.data.PackOutput;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraftforge.common.data.ExistingFileHelper;
import net.minecraftforge.registries.ForgeRegistries;
import org.jetbrains.annotations.NotNull;
import java.util.Objects;
/**
* Stub class to extend for item model data providers, eliminates some
* boilerplate constructor parameters.
*
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
@Deprecated(since = "1.21.4", forRemoval = true)
public abstract class ItemModelProvider extends ModelProvider<ItemModelBuilder> {
public ItemModelProvider(PackOutput output, String modid, ExistingFileHelper existingFileHelper) {
super(output, modid, ITEM_FOLDER, ItemModelBuilder::new, existingFileHelper);
}
public ItemModelBuilder basicItem(Item item)
{
return basicItem(Objects.requireNonNull(ForgeRegistries.ITEMS.getKey(item)));
}
public ItemModelBuilder basicItem(ResourceLocation item)
{
return getBuilder(item.toString())
.parent(new ModelFile.UncheckedModelFile("item/generated"))
.texture("layer0", item.withPrefix("item/"));
}
@NotNull
@Override
public String getName() {
return "Item Models: " + modid;
}
}
File diff suppressed because it is too large. Load diff
@@ -1,77 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators;
import com.google.common.base.Preconditions;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.common.data.ExistingFileHelper;
/**
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
@Deprecated(since = "1.21.4", forRemoval = true)
public abstract class ModelFile {
protected ResourceLocation location;
protected ModelFile(ResourceLocation location) {
this.location = location;
}
protected abstract boolean exists();
public ResourceLocation getLocation() {
assertExistence();
return location;
}
/**
* Assert that this model exists.
* @throws IllegalStateException if this model does not exist
*/
public void assertExistence() {
Preconditions.checkState(exists(), "Model at %s does not exist", location);
}
public ResourceLocation getUncheckedLocation() {
return location;
}
public static class UncheckedModelFile extends ModelFile {
public UncheckedModelFile(String location) {
this(ResourceLocation.parse(location));
}
public UncheckedModelFile(ResourceLocation location) {
super(location);
}
@Override
protected boolean exists() {
return true;
}
}
public static class ExistingModelFile extends ModelFile {
private final ExistingFileHelper existingHelper;
public ExistingModelFile(ResourceLocation location, ExistingFileHelper existingHelper) {
super(location);
this.existingHelper = existingHelper;
}
@Override
protected boolean exists() {
if (getUncheckedLocation().getPath().contains("."))
return existingHelper.exists(getUncheckedLocation(), ModelProvider.MODEL_WITH_EXTENSION);
else
return existingHelper.exists(getUncheckedLocation(), ModelProvider.MODEL);
}
}
}
@@ -1,419 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators;
import com.google.common.base.Preconditions;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.function.BiFunction;
import java.util.function.Function;
import net.minecraft.data.CachedOutput;
import net.minecraft.data.DataProvider;
import net.minecraft.data.PackOutput;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.packs.PackType;
import net.minecraftforge.common.data.ExistingFileHelper;
import net.minecraftforge.common.data.ExistingFileHelper.ResourceType;
import org.jetbrains.annotations.VisibleForTesting;
/**
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
@Deprecated(since = "1.21.4", forRemoval = true)
public abstract class ModelProvider<T extends ModelBuilder<T>> implements DataProvider {
public static final String BLOCK_FOLDER = "block";
public static final String ITEM_FOLDER = "item";
protected static final ResourceType TEXTURE = new ResourceType(PackType.CLIENT_RESOURCES, ".png", "textures");
protected static final ResourceType MODEL = new ResourceType(PackType.CLIENT_RESOURCES, ".json", "models");
protected static final ResourceType MODEL_WITH_EXTENSION = new ResourceType(PackType.CLIENT_RESOURCES, "", "models");
protected final PackOutput output;
protected final String modid;
protected final String folder;
protected final Function<ResourceLocation, T> factory;
@VisibleForTesting
public final Map<ResourceLocation, T> generatedModels = new HashMap<>();
@VisibleForTesting
public final ExistingFileHelper existingFileHelper;
protected abstract void registerModels();
public ModelProvider(PackOutput output, String modid, String folder, Function<ResourceLocation, T> factory, ExistingFileHelper existingFileHelper) {
Preconditions.checkNotNull(output);
this.output = output;
Preconditions.checkNotNull(modid);
this.modid = modid;
Preconditions.checkNotNull(folder);
this.folder = folder;
Preconditions.checkNotNull(factory);
this.factory = factory;
Preconditions.checkNotNull(existingFileHelper);
this.existingFileHelper = existingFileHelper;
}
public ModelProvider(PackOutput output, String modid, String folder, BiFunction<ResourceLocation, ExistingFileHelper, T> builderFromModId, ExistingFileHelper existingFileHelper) {
this(output, modid, folder, loc->builderFromModId.apply(loc, existingFileHelper), existingFileHelper);
}
public T getBuilder(String path) {
Preconditions.checkNotNull(path, "Path must not be null");
ResourceLocation outputLoc = extendWithFolder(path.contains(":") ? ResourceLocation.parse(path) : ResourceLocation.fromNamespaceAndPath(modid, path));
this.existingFileHelper.trackGenerated(outputLoc, MODEL);
return generatedModels.computeIfAbsent(outputLoc, factory);
}
private ResourceLocation extendWithFolder(ResourceLocation rl) {
if (rl.getPath().contains("/")) {
return rl;
}
return rl.withPrefix(folder + '/');
}
public ResourceLocation modLoc(String name) {
return ResourceLocation.fromNamespaceAndPath(modid, name);
}
public ResourceLocation mcLoc(String name) {
return ResourceLocation.parse(name);
}
public T withExistingParent(String name, String parent) {
return withExistingParent(name, mcLoc(parent));
}
public T withExistingParent(String name, ResourceLocation parent) {
return getBuilder(name).parent(getExistingFile(parent));
}
public T cube(String name, ResourceLocation down, ResourceLocation up, ResourceLocation north, ResourceLocation south, ResourceLocation east, ResourceLocation west) {
return withExistingParent(name, "cube")
.texture("down", down)
.texture("up", up)
.texture("north", north)
.texture("south", south)
.texture("east", east)
.texture("west", west);
}
private T singleTexture(String name, String parent, ResourceLocation texture) {
return singleTexture(name, mcLoc(parent), texture);
}
public T singleTexture(String name, ResourceLocation parent, ResourceLocation texture) {
return singleTexture(name, parent, "texture", texture);
}
private T singleTexture(String name, String parent, String textureKey, ResourceLocation texture) {
return singleTexture(name, mcLoc(parent), textureKey, texture);
}
public T singleTexture(String name, ResourceLocation parent, String textureKey, ResourceLocation texture) {
return withExistingParent(name, parent)
.texture(textureKey, texture);
}
public T cubeAll(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/cube_all", "all", texture);
}
public T cubeTop(String name, ResourceLocation side, ResourceLocation top) {
return withExistingParent(name, BLOCK_FOLDER + "/cube_top")
.texture("side", side)
.texture("top", top);
}
private T sideBottomTop(String name, String parent, ResourceLocation side, ResourceLocation bottom, ResourceLocation top) {
return withExistingParent(name, parent)
.texture("side", side)
.texture("bottom", bottom)
.texture("top", top);
}
public T cubeBottomTop(String name, ResourceLocation side, ResourceLocation bottom, ResourceLocation top) {
return sideBottomTop(name, BLOCK_FOLDER + "/cube_bottom_top", side, bottom, top);
}
public T cubeColumn(String name, ResourceLocation side, ResourceLocation end) {
return withExistingParent(name, BLOCK_FOLDER + "/cube_column")
.texture("side", side)
.texture("end", end);
}
public T cubeColumnHorizontal(String name, ResourceLocation side, ResourceLocation end) {
return withExistingParent(name, BLOCK_FOLDER + "/cube_column_horizontal")
.texture("side", side)
.texture("end", end);
}
public T orientableVertical(String name, ResourceLocation side, ResourceLocation front) {
return withExistingParent(name, BLOCK_FOLDER + "/orientable_vertical")
.texture("side", side)
.texture("front", front);
}
public T orientableWithBottom(String name, ResourceLocation side, ResourceLocation front, ResourceLocation bottom, ResourceLocation top) {
return withExistingParent(name, BLOCK_FOLDER + "/orientable_with_bottom")
.texture("side", side)
.texture("front", front)
.texture("bottom", bottom)
.texture("top", top);
}
public T orientable(String name, ResourceLocation side, ResourceLocation front, ResourceLocation top) {
return withExistingParent(name, BLOCK_FOLDER + "/orientable")
.texture("side", side)
.texture("front", front)
.texture("top", top);
}
public T crop(String name, ResourceLocation crop) {
return singleTexture(name, BLOCK_FOLDER + "/crop", "crop", crop);
}
public T cross(String name, ResourceLocation cross) {
return singleTexture(name, BLOCK_FOLDER + "/cross", "cross", cross);
}
public T stairs(String name, ResourceLocation side, ResourceLocation bottom, ResourceLocation top) {
return sideBottomTop(name, BLOCK_FOLDER + "/stairs", side, bottom, top);
}
public T stairsOuter(String name, ResourceLocation side, ResourceLocation bottom, ResourceLocation top) {
return sideBottomTop(name, BLOCK_FOLDER + "/outer_stairs", side, bottom, top);
}
public T stairsInner(String name, ResourceLocation side, ResourceLocation bottom, ResourceLocation top) {
return sideBottomTop(name, BLOCK_FOLDER + "/inner_stairs", side, bottom, top);
}
public T slab(String name, ResourceLocation side, ResourceLocation bottom, ResourceLocation top) {
return sideBottomTop(name, BLOCK_FOLDER + "/slab", side, bottom, top);
}
public T slabTop(String name, ResourceLocation side, ResourceLocation bottom, ResourceLocation top) {
return sideBottomTop(name, BLOCK_FOLDER + "/slab_top", side, bottom, top);
}
public T button(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/button", texture);
}
public T buttonPressed(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/button_pressed", texture);
}
public T buttonInventory(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/button_inventory", texture);
}
public T pressurePlate(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/pressure_plate_up", texture);
}
public T pressurePlateDown(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/pressure_plate_down", texture);
}
public T sign(String name, ResourceLocation texture) {
return getBuilder(name).texture("particle", texture);
}
public T fencePost(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/fence_post", texture);
}
public T fenceSide(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/fence_side", texture);
}
public T fenceInventory(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/fence_inventory", texture);
}
public T fenceGate(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/template_fence_gate", texture);
}
public T fenceGateOpen(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/template_fence_gate_open", texture);
}
public T fenceGateWall(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/template_fence_gate_wall", texture);
}
public T fenceGateWallOpen(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/template_fence_gate_wall_open", texture);
}
public T wallPost(String name, ResourceLocation wall) {
return singleTexture(name, BLOCK_FOLDER + "/template_wall_post", "wall", wall);
}
public T wallSide(String name, ResourceLocation wall) {
return singleTexture(name, BLOCK_FOLDER + "/template_wall_side", "wall", wall);
}
public T wallSideTall(String name, ResourceLocation wall) {
return singleTexture(name, BLOCK_FOLDER + "/template_wall_side_tall", "wall", wall);
}
public T wallInventory(String name, ResourceLocation wall) {
return singleTexture(name, BLOCK_FOLDER + "/wall_inventory", "wall", wall);
}
private T pane(String name, String parent, ResourceLocation pane, ResourceLocation edge) {
return withExistingParent(name, BLOCK_FOLDER + "/" + parent)
.texture("pane", pane)
.texture("edge", edge);
}
public T panePost(String name, ResourceLocation pane, ResourceLocation edge) {
return pane(name, "template_glass_pane_post", pane, edge);
}
public T paneSide(String name, ResourceLocation pane, ResourceLocation edge) {
return pane(name, "template_glass_pane_side", pane, edge);
}
public T paneSideAlt(String name, ResourceLocation pane, ResourceLocation edge) {
return pane(name, "template_glass_pane_side_alt", pane, edge);
}
public T paneNoSide(String name, ResourceLocation pane) {
return singleTexture(name, BLOCK_FOLDER + "/template_glass_pane_noside", "pane", pane);
}
public T paneNoSideAlt(String name, ResourceLocation pane) {
return singleTexture(name, BLOCK_FOLDER + "/template_glass_pane_noside_alt", "pane", pane);
}
private T door(String name, String model, ResourceLocation bottom, ResourceLocation top) {
return withExistingParent(name, BLOCK_FOLDER + "/" + model)
.texture("bottom", bottom)
.texture("top", top);
}
public T doorBottomLeft(String name, ResourceLocation bottom, ResourceLocation top) {
return door(name, "door_bottom_left", bottom, top);
}
public T doorBottomLeftOpen(String name, ResourceLocation bottom, ResourceLocation top) {
return door(name, "door_bottom_left_open", bottom, top);
}
public T doorBottomRight(String name, ResourceLocation bottom, ResourceLocation top) {
return door(name, "door_bottom_right", bottom, top);
}
public T doorBottomRightOpen(String name, ResourceLocation bottom, ResourceLocation top) {
return door(name, "door_bottom_right_open", bottom, top);
}
public T doorTopLeft(String name, ResourceLocation bottom, ResourceLocation top) {
return door(name, "door_top_left", bottom, top);
}
public T doorTopLeftOpen(String name, ResourceLocation bottom, ResourceLocation top) {
return door(name, "door_top_left_open", bottom, top);
}
public T doorTopRight(String name, ResourceLocation bottom, ResourceLocation top) {
return door(name, "door_top_right", bottom, top);
}
public T doorTopRightOpen(String name, ResourceLocation bottom, ResourceLocation top) {
return door(name, "door_top_right_open", bottom, top);
}
public T trapdoorBottom(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/template_trapdoor_bottom", texture);
}
public T trapdoorTop(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/template_trapdoor_top", texture);
}
public T trapdoorOpen(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/template_trapdoor_open", texture);
}
public T trapdoorOrientableBottom(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/template_orientable_trapdoor_bottom", texture);
}
public T trapdoorOrientableTop(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/template_orientable_trapdoor_top", texture);
}
public T trapdoorOrientableOpen(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/template_orientable_trapdoor_open", texture);
}
public T torch(String name, ResourceLocation torch) {
return singleTexture(name, BLOCK_FOLDER + "/template_torch", "torch", torch);
}
public T torchWall(String name, ResourceLocation torch) {
return singleTexture(name, BLOCK_FOLDER + "/template_torch_wall", "torch", torch);
}
public T carpet(String name, ResourceLocation wool) {
return singleTexture(name, BLOCK_FOLDER + "/carpet", "wool", wool);
}
public T leaves(String name, ResourceLocation texture) {
return singleTexture(name, BLOCK_FOLDER + "/leaves", "all", texture)
.renderType("cutout_mipped", "solid");
}
/**
* {@return a model builder that's not directly saved to disk. Meant for use in custom model loaders.}
*/
public T nested() {
return factory.apply(ResourceLocation.fromNamespaceAndPath("dummy", "dummy"));
}
public ModelFile.ExistingModelFile getExistingFile(ResourceLocation path) {
ModelFile.ExistingModelFile ret = new ModelFile.ExistingModelFile(extendWithFolder(path), existingFileHelper);
ret.assertExistence();
return ret;
}
protected void clear() {
generatedModels.clear();
}
@Override
public CompletableFuture<?> run(CachedOutput cache) {
clear();
registerModels();
return generateAll(cache);
}
protected CompletableFuture<?> generateAll(CachedOutput cache) {
CompletableFuture<?>[] futures = new CompletableFuture<?>[this.generatedModels.size()];
int i = 0;
for (T model : this.generatedModels.values()) {
Path target = getPath(model);
futures[i++] = DataProvider.saveStable(cache, model.toJson(), target);
}
return CompletableFuture.allOf(futures);
}
protected Path getPath(T model) {
ResourceLocation loc = model.getLocation();
return this.output.getOutputFolder(PackOutput.Target.RESOURCE_PACK).resolve(loc.getNamespace()).resolve("models").resolve(loc.getPath() + ".json");
}
}
@@ -1,264 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import com.google.common.base.Preconditions;
import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.properties.Property;
/**
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
@Deprecated(since = "1.21.4", forRemoval = true)
public final class MultiPartBlockStateBuilder implements IGeneratedBlockState {
private final List<PartBuilder> parts = new ArrayList<>();
private final Block owner;
public MultiPartBlockStateBuilder(Block owner) {
this.owner = owner;
}
/**
* Creates a builder for models to assign to a {@link PartBuilder}, which when
* completed via {@link ConfiguredModel.Builder#addModel()} will assign the
* resultant set of models to the part and return it for further processing.
*
* @return the model builder
* @see ConfiguredModel.Builder
*/
public ConfiguredModel.Builder<PartBuilder> part() {
return ConfiguredModel.builder(this);
}
MultiPartBlockStateBuilder addPart(PartBuilder part) {
this.parts.add(part);
return this;
}
@Override
public JsonObject toJson() {
JsonArray variants = new JsonArray();
for (PartBuilder part : parts) {
variants.add(part.toJson());
}
JsonObject main = new JsonObject();
main.add("multipart", variants);
return main;
}
public class PartBuilder {
public BlockStateProvider.ConfiguredModelList models;
public boolean useOr;
public final Multimap<Property<?>, Comparable<?>> conditions = MultimapBuilder.linkedHashKeys().arrayListValues().build();
public final List<ConditionGroup> nestedConditionGroups = new ArrayList<>();
PartBuilder(BlockStateProvider.ConfiguredModelList models) {
this.models = models;
}
/**
* Makes this part get applied if any of the conditions/condition groups are true, instead of all of them needing to be true.
*/
public PartBuilder useOr() {
this.useOr = true;
return this;
}
/**
* Set a condition for this part, which consists of a property and a set of
* valid values. Can be called multiple times for multiple different properties.
*
* @param <T> the type of the property value
* @param prop the property
* @param values a set of valid values
* @return this builder
* @throws NullPointerException if {@code prop} is {@code null}
* @throws NullPointerException if {@code values} is {@code null}
* @throws IllegalArgumentException if {@code values} is empty
* @throws IllegalArgumentException if {@code prop} has already been configured
* @throws IllegalArgumentException if {@code prop} is not applicable to the
* current block's state
* @throws IllegalStateException if {@code !nestedConditionGroups.isEmpty()}
*/
@SafeVarargs
public final <T extends Comparable<T>> PartBuilder condition(Property<T> prop, T... values) {
Preconditions.checkNotNull(prop, "Property must not be null");
Preconditions.checkNotNull(values, "Value list must not be null");
Preconditions.checkArgument(values.length > 0, "Value list must not be empty");
Preconditions.checkArgument(!conditions.containsKey(prop), "Cannot set condition for property \"%s\" more than once", prop.getName());
Preconditions.checkArgument(canApplyTo(owner), "IProperty %s is not valid for the block %s", prop, owner);
Preconditions.checkState(nestedConditionGroups.isEmpty(), "Can't have normal conditions if there are already nested condition groups");
this.conditions.putAll(prop, Arrays.asList(values));
return this;
}
/**
* Allows having nested groups of conditions if there are not any normal conditions.
* @throws IllegalStateException if {@code !conditions.isEmpty()}
*/
public final ConditionGroup nestedGroup() {
Preconditions.checkState(conditions.isEmpty(), "Can't have nested condition groups if there are already normal conditions");
ConditionGroup group = new ConditionGroup();
this.nestedConditionGroups.add(group);
return group;
}
public MultiPartBlockStateBuilder end() { return MultiPartBlockStateBuilder.this; }
JsonObject toJson() {
JsonObject out = new JsonObject();
if (!conditions.isEmpty()) {
out.add("when", MultiPartBlockStateBuilder.toJson(this.conditions, this.useOr));
} else if (!nestedConditionGroups.isEmpty()) {
out.add("when", MultiPartBlockStateBuilder.toJson(this.nestedConditionGroups, this.useOr));
}
out.add("apply", models.toJSON());
return out;
}
public boolean canApplyTo(Block b) {
return b.getStateDefinition().getProperties().containsAll(conditions.keySet());
}
public class ConditionGroup {
public final Multimap<Property<?>, Comparable<?>> conditions = MultimapBuilder.linkedHashKeys().arrayListValues().build();
public final List<ConditionGroup> nestedConditionGroups = new ArrayList<>();
private ConditionGroup parent = null;
public boolean useOr;
/**
* Set a condition for this part, which consists of a property and a set of
* valid values. Can be called multiple times for multiple different properties.
*
* @param <T> the type of the property value
* @param prop the property
* @param values a set of valid values
* @return this builder
* @throws NullPointerException if {@code prop} is {@code null}
* @throws NullPointerException if {@code values} is {@code null}
* @throws IllegalArgumentException if {@code values} is empty
* @throws IllegalArgumentException if {@code prop} has already been configured
* @throws IllegalArgumentException if {@code prop} is not applicable to the
* current block's state
* @throws IllegalStateException if {@code !nestedConditionGroups.isEmpty()}
*/
@SafeVarargs
public final <T extends Comparable<T>> ConditionGroup condition(Property<T> prop, T... values) {
Preconditions.checkNotNull(prop, "Property must not be null");
Preconditions.checkNotNull(values, "Value list must not be null");
Preconditions.checkArgument(values.length > 0, "Value list must not be empty");
Preconditions.checkArgument(!conditions.containsKey(prop), "Cannot set condition for property \"%s\" more than once", prop.getName());
Preconditions.checkArgument(canApplyTo(owner), "IProperty %s is not valid for the block %s", prop, owner);
Preconditions.checkState(nestedConditionGroups.isEmpty(), "Can't have normal conditions if there are already nested condition groups");
this.conditions.putAll(prop, Arrays.asList(values));
return this;
}
/**
* Allows having nested groups of conditions if there are not any normal conditions.
* @throws IllegalStateException if {@code !conditions.isEmpty()}
*/
public ConditionGroup nestedGroup() {
Preconditions.checkState(conditions.isEmpty(), "Can't have nested condition groups if there are already normal conditions");
ConditionGroup group = new ConditionGroup();
group.parent = this;
this.nestedConditionGroups.add(group);
return group;
}
/**
* Ends this nested condition group and returns the parent condition group
*
* @throws IllegalStateException If this is not a nested condition group
*/
public ConditionGroup endNestedGroup() {
if (parent == null)
throw new IllegalStateException("This condition group is not nested, use end() instead");
return parent;
}
/**
* Ends this condition group and returns the part builder
*
* @throws IllegalStateException If this is a nested condition group
*/
public MultiPartBlockStateBuilder.PartBuilder end() {
if (this.parent != null)
throw new IllegalStateException("This is a nested condition group, use endNestedGroup() instead");
return MultiPartBlockStateBuilder.PartBuilder.this;
}
/**
* Makes this part get applied if any of the conditions/condition groups are true, instead of all of them needing to be true.
*/
public ConditionGroup useOr() {
this.useOr = true;
return this;
}
JsonObject toJson() {
if (!this.conditions.isEmpty())
return MultiPartBlockStateBuilder.toJson(this.conditions, this.useOr);
else if (!this.nestedConditionGroups.isEmpty())
return MultiPartBlockStateBuilder.toJson(this.nestedConditionGroups, this.useOr);
return new JsonObject();
}
}
}
private static JsonObject toJson(List<PartBuilder.ConditionGroup> conditions, boolean useOr) {
JsonObject groupJson = new JsonObject();
JsonArray innerGroupJson = new JsonArray();
groupJson.add(useOr ? "OR" : "AND", innerGroupJson);
for (PartBuilder.ConditionGroup group : conditions)
innerGroupJson.add(group.toJson());
return groupJson;
}
private static JsonObject toJson(Multimap<Property<?>, Comparable<?>> conditions, boolean useOr) {
JsonObject groupJson = new JsonObject();
for (Entry<Property<?>, Collection<Comparable<?>>> e : conditions.asMap().entrySet()) {
StringBuilder activeString = new StringBuilder();
for (Comparable<?> val : e.getValue()) {
if (!activeString.isEmpty())
activeString.append("|");
activeString.append(getName(e.getKey(), val));
}
groupJson.addProperty(e.getKey().getName(), activeString.toString());
}
if (useOr) {
JsonArray innerWhen = new JsonArray();
for (Entry<String, JsonElement> entry : groupJson.entrySet()) {
JsonObject obj = new JsonObject();
obj.add(entry.getKey(), entry.getValue());
innerWhen.add(obj);
}
groupJson = new JsonObject();
groupJson.add("OR", innerWhen);
}
return groupJson;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T> String getName(Property<?> key, Comparable<?> value) {
return ((Property)key).getName((Comparable)value);
}
}
@@ -1,332 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.function.Function;
import java.util.function.Predicate;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.JsonObject;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.Property;
import net.minecraftforge.client.model.generators.BlockStateProvider.ConfiguredModelList;
import org.jetbrains.annotations.Nullable;
/**
* Builder for variant-type blockstates, i.e. non-multipart blockstates. Should
* not be manually instantiated, instead use
* {@link BlockStateProvider#getVariantBuilder(Block)}.
* <p>
* Variants can either be set via
* {@link #setModels(PartialBlockstate, ConfiguredModel...)} or
* {@link #addModels(PartialBlockstate, ConfiguredModel...)}, where model(s) can
* be assigned directly to {@link PartialBlockstate partial states}, or builder
* style via {@link #partialState()} and its subsequent methods.
* <p>
* This class also provides the convenience methods
* {@link #forAllStates(Function)} and
* {@link #forAllStatesExcept(Function, Property...)} for cases where the model
* for each variant can be decided dynamically based on the state's property
* values.
*
* @see BlockStateProvider
*
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
@Deprecated(since = "1.21.4", forRemoval = true)
public class VariantBlockStateBuilder implements IGeneratedBlockState
{
private final Block owner;
private final Map<PartialBlockstate, ConfiguredModelList> models = new LinkedHashMap<>();
private final Set<BlockState> coveredStates = new HashSet<>();
VariantBlockStateBuilder(Block owner) {
this.owner = owner;
}
public Map<PartialBlockstate, ConfiguredModelList> getModels() {
return models;
}
public Block getOwner() {
return owner;
}
@Override
public JsonObject toJson() {
List<BlockState> missingStates = Lists.newArrayList(owner.getStateDefinition().getPossibleStates());
missingStates.removeAll(coveredStates);
Preconditions.checkState(missingStates.isEmpty(), "Blockstate for block %s does not cover all states. Missing: %s", owner, missingStates);
JsonObject variants = new JsonObject();
getModels().entrySet().stream()
.sorted(Entry.comparingByKey(PartialBlockstate.comparingByProperties()))
.forEach(entry -> variants.add(entry.getKey().toString(), entry.getValue().toJSON()));
JsonObject main = new JsonObject();
main.add("variants", variants);
return main;
}
/**
* Assign some models to a given {@link PartialBlockstate partial state}.
*
* @param state The {@link PartialBlockstate partial state} for which to add
* the models
* @param models A set of models to add to this state
* @return this builder
* @throws NullPointerException if {@code state} is {@code null}
* @throws IllegalArgumentException if {@code models} is empty
* @throws IllegalArgumentException if {@code state}'s owning block differs from
* the builder's
* @throws IllegalArgumentException if {@code state} partially matches another
* state which has already been configured
*/
public VariantBlockStateBuilder addModels(PartialBlockstate state, ConfiguredModel... models) {
Preconditions.checkNotNull(state, "state must not be null");
Preconditions.checkArgument(models.length > 0, "Cannot set models to empty array");
Preconditions.checkArgument(state.getOwner() == owner, "Cannot set models for a different block. Found: %s, Current: %s", state.getOwner(), owner);
if (!this.models.containsKey(state)) {
Preconditions.checkArgument(disjointToAll(state), "Cannot set models for a state for which a partial match has already been configured");
this.models.put(state, new ConfiguredModelList(models));
for (BlockState fullState : owner.getStateDefinition().getPossibleStates()) {
if (state.test(fullState)) {
coveredStates.add(fullState);
}
}
} else {
this.models.compute(state, ($, cml) -> cml.append(models));
}
return this;
}
/**
* Assign some models to a given {@link PartialBlockstate partial state},
* throwing an exception if the state has already been configured. Otherwise,
* simply calls {@link #addModels(PartialBlockstate, ConfiguredModel...)}.
*
* @param state The {@link PartialBlockstate partial state} for which to set
* the models
* @param model A set of models to assign to this state
* @return this builder
* @throws IllegalArgumentException if {@code state} has already been configured
* @see #addModels(PartialBlockstate, ConfiguredModel...)
*/
public VariantBlockStateBuilder setModels(PartialBlockstate state, ConfiguredModel... model) {
Preconditions.checkArgument(!models.containsKey(state), "Cannot set models for a state that has already been configured: %s", state);
addModels(state, model);
return this;
}
private boolean disjointToAll(PartialBlockstate newState) {
return coveredStates.stream().noneMatch(newState);
}
public PartialBlockstate partialState() {
return new PartialBlockstate(owner, this);
}
public VariantBlockStateBuilder forAllStates(Function<BlockState, ConfiguredModel[]> mapper) {
return forAllStatesExcept(mapper);
}
public VariantBlockStateBuilder forAllStatesExcept(Function<BlockState, ConfiguredModel[]> mapper, Property<?>... ignored) {
Set<PartialBlockstate> seen = new HashSet<>();
for (BlockState fullState : owner.getStateDefinition().getPossibleStates()) {
Map<Property<?>, Comparable<?>> propertyValues = Maps.newLinkedHashMap(fullState.getValues());
for (Property<?> p : ignored) {
propertyValues.remove(p);
}
PartialBlockstate partialState = new PartialBlockstate(owner, propertyValues, this);
if (seen.add(partialState)) {
setModels(partialState, mapper.apply(fullState));
}
}
return this;
}
public static class PartialBlockstate implements Predicate<BlockState> {
private final Block owner;
private final SortedMap<Property<?>, Comparable<?>> setStates;
@Nullable
private final VariantBlockStateBuilder outerBuilder;
PartialBlockstate(Block owner, @Nullable VariantBlockStateBuilder outerBuilder) {
this(owner, ImmutableMap.of(), outerBuilder);
}
PartialBlockstate(Block owner, Map<Property<?>, Comparable<?>> setStates, @Nullable VariantBlockStateBuilder outerBuilder) {
this.owner = owner;
this.outerBuilder = outerBuilder;
for (Map.Entry<Property<?>, Comparable<?>> entry : setStates.entrySet()) {
Property<?> prop = entry.getKey();
Comparable<?> value = entry.getValue();
Preconditions.checkArgument(owner.getStateDefinition().getProperties().contains(prop), "Property %s not found on block %s", entry, this.owner);
Preconditions.checkArgument(prop.getPossibleValues().contains(value), "%s is not a valid value for %s", value, prop);
}
this.setStates = Maps.newTreeMap(Comparator.comparing(Property::getName));
this.setStates.putAll(setStates);
}
public <T extends Comparable<T>> PartialBlockstate with(Property<T> prop, T value) {
Preconditions.checkArgument(!setStates.containsKey(prop), "Property %s has already been set", prop);
Map<Property<?>, Comparable<?>> newState = new HashMap<>(setStates);
newState.put(prop, value);
return new PartialBlockstate(owner, newState, outerBuilder);
}
private void checkValidOwner() {
Preconditions.checkNotNull(outerBuilder, "Partial blockstate must have a valid owner to perform this action");
}
/**
* Creates a builder for models to assign to this state, which when completed
* via {@link ConfiguredModel.Builder#addModel()} will assign the resultant set
* of models to this state.
*
* @return the model builder
* @see ConfiguredModel.Builder
*/
public ConfiguredModel.Builder<VariantBlockStateBuilder> modelForState() {
checkValidOwner();
return ConfiguredModel.builder(outerBuilder, this);
}
/**
* Add models to the current state's variant. For use when it is more convenient
* to add multiple sets of models, as a replacement for
* {@link #setModels(ConfiguredModel...)}.
*
* @param models The models to add.
* @return {@code this}
* @throws NullPointerException If the parent builder is {@code null}
*/
public PartialBlockstate addModels(ConfiguredModel... models) {
checkValidOwner();
outerBuilder.addModels(this, models);
return this;
}
/**
* Set this variant's models, and return the parent builder.
*
* @param models The models to set
* @return The parent builder instance
* @throws NullPointerException If the parent builder is {@code null}
*/
public VariantBlockStateBuilder setModels(ConfiguredModel... models) {
checkValidOwner();
return outerBuilder.setModels(this, models);
}
/**
* Complete this state without adding any new models, and return a new partial
* state via the parent builder. For use after calling
* {@link #addModels(ConfiguredModel...)}.
*
* @return A fresh partial state as specified by
* {@link VariantBlockStateBuilder#partialState()}.
* @throws NullPointerException If the parent builder is {@code null}
*/
public PartialBlockstate partialState() {
checkValidOwner();
return outerBuilder.partialState();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PartialBlockstate that = (PartialBlockstate) o;
return owner.equals(that.owner) &&
setStates.equals(that.setStates);
}
@Override
public int hashCode() {
return Objects.hash(owner, setStates);
}
public Block getOwner() {
return owner;
}
public SortedMap<Property<?>, Comparable<?>> getSetStates() {
return setStates;
}
@Override
public boolean test(BlockState blockState) {
if (blockState.getBlock() != getOwner()) {
return false;
}
for (Map.Entry<Property<?>, Comparable<?>> entry : setStates.entrySet()) {
if (blockState.getValue(entry.getKey()) != entry.getValue()) {
return false;
}
}
return true;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public String toString() {
StringBuilder ret = new StringBuilder();
for (Map.Entry<Property<?>, Comparable<?>> entry : setStates.entrySet()) {
if (!ret.isEmpty()) {
ret.append(',');
}
ret.append(entry.getKey().getName())
.append('=')
.append(((Property) entry.getKey()).getName(entry.getValue()));
}
return ret.toString();
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Comparator<PartialBlockstate> comparingByProperties() {
// Sort variants inversely by property values, to approximate vanilla style
return (s1, s2) -> {
SortedSet<Property<?>> propUniverse = new TreeSet<>(s1.getSetStates().comparator().reversed());
propUniverse.addAll(s1.getSetStates().keySet());
propUniverse.addAll(s2.getSetStates().keySet());
for (Property<?> prop : propUniverse) {
Comparable val1 = s1.getSetStates().get(prop);
Comparable val2 = s2.getSetStates().get(prop);
if (val1 == null && val2 != null) {
return -1;
} else if (val2 == null && val1 != null) {
return 1;
} else if (val1 != null && val2 != null){
int cmp = val1.compareTo(val2);
if (cmp != 0) {
return cmp;
}
}
}
return 0;
};
}
}
}
@@ -1,81 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators.loaders;
import com.google.common.base.Preconditions;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.model.generators.CustomLoaderBuilder;
import net.minecraftforge.client.model.generators.ModelBuilder;
import net.minecraftforge.common.data.ExistingFileHelper;
import java.util.*;
/**
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
public class CompositeModelBuilder<T extends ModelBuilder<T>> extends CustomLoaderBuilder<T>
{
private static final ResourceLocation NAME = ResourceLocation.fromNamespaceAndPath("forge", "composite");
public static <T extends ModelBuilder<T>> CompositeModelBuilder<T> begin(T parent, ExistingFileHelper existingFileHelper)
{
return new CompositeModelBuilder<>(parent, existingFileHelper);
}
private final Map<String, T> childModels = new LinkedHashMap<>();
private final List<String> itemRenderOrder = new ArrayList<>();
protected CompositeModelBuilder(T parent, ExistingFileHelper existingFileHelper)
{
super(NAME, parent, existingFileHelper);
}
public CompositeModelBuilder<T> child(String name, T modelBuilder)
{
Preconditions.checkNotNull(name, "name must not be null");
Preconditions.checkNotNull(modelBuilder, "modelBuilder must not be null");
childModels.put(name, modelBuilder);
itemRenderOrder.add(name);
return this;
}
public CompositeModelBuilder<T> itemRenderOrder(String... names)
{
Preconditions.checkNotNull(names, "names must not be null");
Preconditions.checkArgument(names.length > 0, "names must contain at least one element");
for (String name : names)
if (!childModels.containsKey(name))
throw new IllegalArgumentException("names contains \"" + name + "\", which is not a child of this model");
itemRenderOrder.clear();
itemRenderOrder.addAll(Arrays.asList(names));
return this;
}
@Override
public JsonObject toJson(JsonObject json)
{
json = super.toJson(json);
JsonObject children = new JsonObject();
for(Map.Entry<String, T> entry : childModels.entrySet())
{
children.add(entry.getKey(), entry.getValue().toJson());
}
json.add("children", children);
JsonArray itemRenderOrder = new JsonArray();
for (String name : this.itemRenderOrder) {
itemRenderOrder.add(name);
}
json.add("item_render_order", itemRenderOrder);
return json;
}
}
@@ -1,95 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators.loaders;
import com.google.common.base.Preconditions;
import com.google.gson.JsonObject;
import net.minecraft.world.level.material.Fluid;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.model.generators.CustomLoaderBuilder;
import net.minecraftforge.client.model.generators.ModelBuilder;
import net.minecraftforge.common.data.ExistingFileHelper;
import net.minecraftforge.registries.ForgeRegistries;
/**
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
public class DynamicFluidContainerModelBuilder<T extends ModelBuilder<T>> extends CustomLoaderBuilder<T>
{
private static final ResourceLocation NAME = ResourceLocation.fromNamespaceAndPath("forge", "fluid_container");
public static <T extends ModelBuilder<T>> DynamicFluidContainerModelBuilder<T> begin(T parent, ExistingFileHelper existingFileHelper)
{
return new DynamicFluidContainerModelBuilder<>(parent, existingFileHelper);
}
private ResourceLocation fluid;
private Boolean flipGas;
private Boolean applyTint;
private Boolean coverIsMask;
private Boolean applyFluidLuminosity;
protected DynamicFluidContainerModelBuilder(T parent, ExistingFileHelper existingFileHelper)
{
super(NAME, parent, existingFileHelper);
}
public DynamicFluidContainerModelBuilder<T> fluid(Fluid fluid)
{
Preconditions.checkNotNull(fluid, "fluid must not be null");
this.fluid = ForgeRegistries.FLUIDS.getKey(fluid);
return this;
}
public DynamicFluidContainerModelBuilder<T> flipGas(boolean flip)
{
this.flipGas = flip;
return this;
}
public DynamicFluidContainerModelBuilder<T> applyTint(boolean tint)
{
this.applyTint = tint;
return this;
}
public DynamicFluidContainerModelBuilder<T> coverIsMask(boolean coverIsMask)
{
this.coverIsMask = coverIsMask;
return this;
}
public DynamicFluidContainerModelBuilder<T> applyFluidLuminosity(boolean applyFluidLuminosity)
{
this.applyFluidLuminosity = applyFluidLuminosity;
return this;
}
@Override
public JsonObject toJson(JsonObject json)
{
json = super.toJson(json);
Preconditions.checkNotNull(fluid, "fluid must not be null");
json.addProperty("fluid", fluid.toString());
if (flipGas != null)
json.addProperty("flip_gas", flipGas);
if (applyTint != null)
json.addProperty("apply_tint", applyTint);
if (coverIsMask != null)
json.addProperty("cover_is_mask", coverIsMask);
if (applyFluidLuminosity != null)
json.addProperty("apply_fluid_luminosity", applyFluidLuminosity);
return json;
}
}
@@ -1,226 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators.loaders;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import com.google.common.base.Preconditions;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.mojang.serialization.JsonOps;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntOpenHashSet;
import it.unimi.dsi.fastutil.ints.IntSet;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.model.ForgeFaceData;
import net.minecraftforge.client.model.generators.CustomLoaderBuilder;
import net.minecraftforge.client.model.generators.ModelBuilder;
import net.minecraftforge.common.data.ExistingFileHelper;
/**
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
public class ItemLayerModelBuilder<T extends ModelBuilder<T>> extends CustomLoaderBuilder<T>
{
private static final ResourceLocation NAME = ResourceLocation.fromNamespaceAndPath("forge", "item_layers");
public static <T extends ModelBuilder<T>> ItemLayerModelBuilder<T> begin(T parent, ExistingFileHelper existingFileHelper)
{
return new ItemLayerModelBuilder<>(parent, existingFileHelper);
}
private final Int2ObjectMap<ForgeFaceData> faceData = new Int2ObjectOpenHashMap<>();
private final Map<ResourceLocation, IntSet> renderTypes = new LinkedHashMap<>();
private final Map<ResourceLocation, IntSet> renderTypesFast = new LinkedHashMap<>();
private final IntSet layersWithRenderTypes = new IntOpenHashSet();
protected ItemLayerModelBuilder(T parent, ExistingFileHelper existingFileHelper)
{
super(NAME, parent, existingFileHelper);
}
/**
* Marks a set of layers to be rendered emissively.
*
* @param blockLight The block light (0-15)
* @param skyLight The sky light (0-15)
* @param layers the layers that will render unlit
* @return this builder
* @throws NullPointerException if {@code layers} is {@code null}
* @throws IllegalArgumentException if {@code layers} is empty
* @throws IllegalArgumentException if any entry in {@code layers} is smaller than 0
*/
public ItemLayerModelBuilder<T> emissive(int blockLight, int skyLight, int... layers)
{
Preconditions.checkNotNull(layers, "Layers must not be null");
Preconditions.checkArgument(layers.length > 0, "At least one layer must be specified");
Preconditions.checkArgument(Arrays.stream(layers).allMatch(i -> i >= 0), "All layers must be >= 0");
for(int i : layers)
{
faceData.compute(i, (key, value) -> {
ForgeFaceData fallback = value == null ? ForgeFaceData.DEFAULT : value;
return new ForgeFaceData(fallback.color(), blockLight, skyLight, fallback.ambientOcclusion(), fallback.calculateNormals());
});
}
return this;
}
/**
* Marks a set of layers to be rendered with a specific color.
*
* @param color The color, in ARGB.
* @param layers the layers that will render with color
* @return this builder
* @throws NullPointerException if {@code layers} is {@code null}
* @throws IllegalArgumentException if {@code layers} is empty
* @throws IllegalArgumentException if any entry in {@code layers} is smaller than 0
*/
public ItemLayerModelBuilder<T> color(int color, int... layers)
{
Preconditions.checkNotNull(layers, "Layers must not be null");
Preconditions.checkArgument(layers.length > 0, "At least one layer must be specified");
Preconditions.checkArgument(Arrays.stream(layers).allMatch(i -> i >= 0), "All layers must be >= 0");
for(int i : layers)
{
faceData.compute(i, (key, value) -> {
ForgeFaceData fallback = value == null ? ForgeFaceData.DEFAULT : value;
return new ForgeFaceData(color, fallback.blockLight(), fallback.skyLight(), fallback.ambientOcclusion(), fallback.calculateNormals());
});
}
return this;
}
/**
* Set the render type for a set of layers.
*
* @param renderType the render type. Must be registered via
* {@link net.minecraftforge.client.event.RegisterNamedRenderTypesEvent}
* @param layers the layers that will use this render type
* @return this builder
* @throws NullPointerException if {@code renderType} is {@code null}
* @throws NullPointerException if {@code layers} is {@code null}
* @throws IllegalArgumentException if {@code layers} is empty
* @throws IllegalArgumentException if any entry in {@code layers} is smaller than 0
* @throws IllegalArgumentException if any entry in {@code layers} already has a render type
*/
public ItemLayerModelBuilder<T> renderType(String renderType, int... layers)
{
Preconditions.checkNotNull(renderType, "Render type must not be null");
ResourceLocation asLoc;
if (renderType.contains(":"))
asLoc = ResourceLocation.parse(renderType);
else
asLoc = parent.getLocation().withPath(renderType);
return renderType(asLoc, layers);
}
public ItemLayerModelBuilder<T> renderType(String renderType, String renderTypeFast, int... layers)
{
Preconditions.checkNotNull(renderType, "Render type must not be null");
Preconditions.checkNotNull(renderTypeFast, "Fast graphics render type must not be null");
ResourceLocation asLoc;
if (renderType.contains(":"))
asLoc = ResourceLocation.parse(renderType);
else
asLoc = parent.getLocation().withPath(renderType);
ResourceLocation asLocFast;
if (renderTypeFast.contains(":"))
asLocFast = ResourceLocation.parse(renderTypeFast);
else
asLocFast = parent.getLocation().withPath(renderTypeFast);
return renderType(asLoc, asLocFast, layers);
}
/**
* Set the render type for a set of layers.
*
* @param renderType the render type. Must be registered via
* {@link net.minecraftforge.client.event.RegisterNamedRenderTypesEvent}
* @param layers the layers that will use this render type
* @return this builder
* @throws NullPointerException if {@code renderType} is {@code null}
* @throws NullPointerException if {@code layers} is {@code null}
* @throws IllegalArgumentException if {@code layers} is empty
* @throws IllegalArgumentException if any entry in {@code layers} is smaller than 0
* @throws IllegalArgumentException if any entry in {@code layers} already has a render type
*/
public ItemLayerModelBuilder<T> renderType(ResourceLocation renderType, int... layers)
{
Preconditions.checkNotNull(renderType, "Render type must not be null");
Preconditions.checkNotNull(layers, "Layers must not be null");
Preconditions.checkArgument(layers.length > 0, "At least one layer must be specified");
Preconditions.checkArgument(Arrays.stream(layers).allMatch(i -> i >= 0), "All layers must be >= 0");
var alreadyAssigned = Arrays.stream(layers).filter(layersWithRenderTypes::contains).toArray();
Preconditions.checkArgument(alreadyAssigned.length == 0, "Attempted to re-assign layer render types: " + Arrays.toString(alreadyAssigned));
var renderTypeLayers = renderTypes.computeIfAbsent(renderType, $ -> new IntOpenHashSet());
Arrays.stream(layers).forEach(layer -> {
renderTypeLayers.add(layer);
layersWithRenderTypes.add(layer);
});
return this;
}
public ItemLayerModelBuilder<T> renderType(ResourceLocation renderType, ResourceLocation renderTypeFast, int... layers)
{
Preconditions.checkNotNull(renderType, "Render type must not be null");
Preconditions.checkNotNull(renderTypeFast, "Fast graphics render type must not be null");
Preconditions.checkNotNull(layers, "Layers must not be null");
Preconditions.checkArgument(layers.length > 0, "At least one layer must be specified");
Preconditions.checkArgument(Arrays.stream(layers).allMatch(i -> i >= 0), "All layers must be >= 0");
var alreadyAssigned = Arrays.stream(layers).filter(layersWithRenderTypes::contains).toArray();
Preconditions.checkArgument(alreadyAssigned.length == 0, "Attempted to re-assign layer render types: " + Arrays.toString(alreadyAssigned));
var renderTypeLayers = renderTypes.computeIfAbsent(renderType, $ -> new IntOpenHashSet());
var renderTypeFastLayers = renderTypesFast.computeIfAbsent(renderType, $ -> new IntOpenHashSet());
Arrays.stream(layers).forEach(layer -> {
renderTypeLayers.add(layer);
renderTypeFastLayers.add(layer);
layersWithRenderTypes.add(layer);
});
return this;
}
@Override
public JsonObject toJson(JsonObject json)
{
json = super.toJson(json);
JsonObject forgeData = new JsonObject();
JsonObject layerObj = new JsonObject();
for(Int2ObjectMap.Entry<ForgeFaceData> entry : this.faceData.int2ObjectEntrySet())
{
layerObj.add(String.valueOf(entry.getIntKey()), ForgeFaceData.CODEC.encodeStart(JsonOps.INSTANCE, entry.getValue()).getOrThrow(s -> {
return new RuntimeException(); // Perhaps not the best way to deal with this? - MangoRage
}));
}
forgeData.add("layers", layerObj);
json.add("forge_data", forgeData);
JsonObject renderTypes = new JsonObject();
this.renderTypes.forEach((renderType, layers) -> {
JsonArray array = new JsonArray();
layers.intStream().sorted().forEach(array::add);
renderTypes.add(renderType.toString(), array);
});
json.add("render_types", renderTypes);
JsonObject renderTypesFast = new JsonObject();
this.renderTypesFast.forEach((renderTypeFast, layers) -> {
JsonArray array = new JsonArray();
layers.intStream().sorted().forEach(array::add);
renderTypesFast.add(renderTypeFast.toString(), array);
});
json.add("render_types_fast", renderTypesFast);
return json;
}
}
@@ -1,109 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators.loaders;
import com.google.common.base.Preconditions;
import com.google.gson.JsonObject;
import net.minecraft.server.packs.PackType;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.model.generators.CustomLoaderBuilder;
import net.minecraftforge.client.model.generators.ModelBuilder;
import net.minecraftforge.common.data.ExistingFileHelper;
/**
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
public class ObjModelBuilder<T extends ModelBuilder<T>> extends CustomLoaderBuilder<T>
{
private static final ResourceLocation NAME = ResourceLocation.fromNamespaceAndPath("forge", "obj");
public static <T extends ModelBuilder<T>> ObjModelBuilder<T> begin(T parent, ExistingFileHelper existingFileHelper)
{
return new ObjModelBuilder<>(parent, existingFileHelper);
}
private ResourceLocation modelLocation;
private Boolean automaticCulling;
private Boolean shadeQuads;
private Boolean flipV;
private Boolean emissiveAmbient;
private ResourceLocation mtlOverride;
protected ObjModelBuilder(T parent, ExistingFileHelper existingFileHelper)
{
super(NAME, parent, existingFileHelper);
}
public ObjModelBuilder<T> modelLocation(ResourceLocation modelLocation)
{
Preconditions.checkNotNull(modelLocation, "modelLocation must not be null");
Preconditions.checkArgument(existingFileHelper.exists(modelLocation, PackType.CLIENT_RESOURCES),
"OBJ Model %s does not exist in any known resource pack", modelLocation);
this.modelLocation = modelLocation;
return this;
}
public ObjModelBuilder<T> automaticCulling(boolean automaticCulling)
{
this.automaticCulling = automaticCulling;
return this;
}
public ObjModelBuilder<T> shadeQuads(boolean shadeQuads)
{
this.shadeQuads = shadeQuads;
return this;
}
public ObjModelBuilder<T> flipV(boolean flipV)
{
this.flipV = flipV;
return this;
}
public ObjModelBuilder<T> emissiveAmbient(boolean ambientEmissive)
{
this.emissiveAmbient = ambientEmissive;
return this;
}
public ObjModelBuilder<T> overrideMaterialLibrary(ResourceLocation mtlOverride)
{
Preconditions.checkNotNull(mtlOverride, "mtlOverride must not be null");
Preconditions.checkArgument(existingFileHelper.exists(mtlOverride, PackType.CLIENT_RESOURCES),
"OBJ Model %s does not exist in any known resource pack", mtlOverride);
this.mtlOverride = mtlOverride;
return this;
}
@Override
public JsonObject toJson(JsonObject json)
{
json = super.toJson(json);
Preconditions.checkNotNull(modelLocation, "modelLocation must not be null");
json.addProperty("model", modelLocation.toString());
if (automaticCulling != null)
json.addProperty("automatic_culling", automaticCulling);
if (shadeQuads != null)
json.addProperty("shade_quads", shadeQuads);
if (flipV != null)
json.addProperty("flip_v", flipV);
if (emissiveAmbient != null)
json.addProperty("emissive_ambient", emissiveAmbient);
if (mtlOverride != null)
json.addProperty("mtl_override", mtlOverride.toString());
return json;
}
}
@@ -1,75 +0,0 @@
/*
* Copyright (c) Forge Development LLC and contributors
* SPDX-License-Identifier: LGPL-2.1-only
*/
package net.minecraftforge.client.model.generators.loaders;
import com.google.common.base.Preconditions;
import com.google.gson.JsonObject;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraftforge.client.model.generators.CustomLoaderBuilder;
import net.minecraftforge.client.model.generators.ModelBuilder;
import net.minecraftforge.common.data.ExistingFileHelper;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* In 1.21.4 Mojang exposed their data generators for their models. So it should be feasible to just use theirs.
* If you find something lacking feel free to open a PR so that we can extend it.
* @deprecated Use Vanilla's providers {@link net.minecraft.client.data.models.ModelProvider}
*/
public class SeparateTransformsModelBuilder<T extends ModelBuilder<T>> extends CustomLoaderBuilder<T>
{
private static final ResourceLocation NAME = ResourceLocation.fromNamespaceAndPath("forge", "separate_transforms");
public static <T extends ModelBuilder<T>> SeparateTransformsModelBuilder<T> begin(T parent, ExistingFileHelper existingFileHelper)
{
return new SeparateTransformsModelBuilder<>(parent, existingFileHelper);
}
private T base;
private final Map<String, T> childModels = new LinkedHashMap<>();
protected SeparateTransformsModelBuilder(T parent, ExistingFileHelper existingFileHelper)
{
super(NAME, parent, existingFileHelper);
}
public SeparateTransformsModelBuilder<T> base(T modelBuilder)
{
Preconditions.checkNotNull(modelBuilder, "modelBuilder must not be null");
base = modelBuilder;
return this;
}
public SeparateTransformsModelBuilder<T> perspective(ItemDisplayContext perspective, T modelBuilder)
{
Preconditions.checkNotNull(perspective, "layer must not be null");
Preconditions.checkNotNull(modelBuilder, "modelBuilder must not be null");
childModels.put(perspective.getSerializedName(), modelBuilder);
return this;
}
@Override
public JsonObject toJson(JsonObject json)
{
json = super.toJson(json);
if (base != null)
{
json.add("base", base.toJson());
}
JsonObject parts = new JsonObject();
for(Map.Entry<String, T> entry : childModels.entrySet())
{
parts.add(entry.getKey(), entry.getValue().toJson());
}
json.add("perspectives", parts);
return json;
}
}
@@ -5,7 +5,7 @@
package net.minecraftforge.client.model.geometry;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.client.event.ModelEvent;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
@@ -20,14 +20,14 @@ import java.util.stream.Collectors;
* Provides a lookup.
*/
public final class GeometryLoaderManager {
private static Map<ResourceLocation, IGeometryLoader> LOADERS;
private static Map<Identifier, IGeometryLoader> LOADERS;
private static String LOADER_LIST;
/**
* Finds the {@link IGeometryLoader} for a given name, or null if not found.
*/
@Nullable
public static IGeometryLoader get(ResourceLocation name) {
public static IGeometryLoader get(Identifier name) {
return LOADERS.get(name);
}
@@ -40,10 +40,10 @@ public final class GeometryLoaderManager {
@ApiStatus.Internal
public static void init() {
var loaders = new HashMap<ResourceLocation, IGeometryLoader>();
var loaders = new HashMap<Identifier, IGeometryLoader>();
ModelEvent.RegisterGeometryLoaders.BUS.post(new ModelEvent.RegisterGeometryLoaders(loaders));
LOADERS = Map.copyOf(loaders);
LOADER_LIST = loaders.keySet().stream().map(ResourceLocation::toString).collect(Collectors.joining(", "));
LOADER_LIST = loaders.keySet().stream().map(Identifier::toString).collect(Collectors.joining(", "));
}
private GeometryLoaderManager() {}
@@ -8,7 +8,7 @@ package net.minecraftforge.client.model.geometry;
import com.mojang.math.Transformation;
import net.minecraft.client.renderer.block.model.ItemTransforms;
import net.minecraft.client.resources.model.Material;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.client.NamedRenderTypeManager;
import net.minecraftforge.client.RenderTypeGroup;
import org.jetbrains.annotations.Nullable;
@@ -50,14 +50,14 @@ public interface IGeometryBakingContext {
* {@return a hint of the render type this model should use. Custom loaders may ignore this.}
*/
@Nullable
ResourceLocation getRenderTypeHint();
Identifier getRenderTypeHint();
/**
* @return a hint of the {@linkplain net.minecraft.client.GraphicsStatus#FAST fast graphics} render type this model
* should use. Custom loaders may ignore this.
*/
@Nullable
default ResourceLocation getRenderTypeFastHint() { return null; }
default Identifier getRenderTypeFastHint() { return null; }
/**
* Queries the visibility of a component of this model.
@@ -71,7 +71,7 @@ public interface IGeometryBakingContext {
/**
* {@return a {@link RenderTypeGroup} with the given name, or the empty group if not found.}
*/
default RenderTypeGroup getRenderType(ResourceLocation name) {
default RenderTypeGroup getRenderType(Identifier name) {
return NamedRenderTypeManager.get(name);
}
@@ -14,7 +14,7 @@ import net.minecraft.client.renderer.block.model.BlockModel;
import net.minecraft.client.renderer.block.model.ItemTransforms;
import net.minecraft.client.resources.model.ModelDiscovery.ModelWrapper;
import net.minecraft.client.resources.model.ResolvedModel;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.client.model.ForgeBlockModelData;
@ApiStatus.Internal
@@ -76,7 +76,7 @@ public record ModelContext(
}
@Override
public @Nullable ResourceLocation getRenderTypeHint() {
public @Nullable Identifier getRenderTypeHint() {
return data == null ? null : data.renderType().orElse(null);
}
@@ -8,7 +8,7 @@ package net.minecraftforge.client.model.geometry;
import com.mojang.math.Transformation;
import it.unimi.dsi.fastutil.objects.Object2BooleanMap;
import net.minecraft.client.renderer.block.model.ItemTransforms;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import org.jetbrains.annotations.Nullable;
import java.util.function.BiPredicate;
@@ -17,7 +17,7 @@ import java.util.function.BiPredicate;
* A {@linkplain IGeometryBakingContext geometry baking context} that is not bound to block/item model loading.
*/
public class StandaloneGeometryBakingContext implements IGeometryBakingContext {
public static final ResourceLocation LOCATION = ResourceLocation.fromNamespaceAndPath("forge", "standalone");
public static final Identifier LOCATION = Identifier.fromNamespaceAndPath("forge", "standalone");
public static final StandaloneGeometryBakingContext INSTANCE = builder().build();
@@ -27,16 +27,16 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext {
private final ItemTransforms transforms;
private final Transformation rootTransform;
@Nullable
private final ResourceLocation renderTypeHint;
private final Identifier renderTypeHint;
@Nullable
private final ResourceLocation renderTypeFastHint;
private final Identifier renderTypeFastHint;
private final BiPredicate<String, Boolean> visibilityTest;
private StandaloneGeometryBakingContext(
boolean isGui3d,
boolean useBlockLight, boolean useAmbientOcclusion,
ItemTransforms transforms, Transformation rootTransform,
@Nullable ResourceLocation renderTypeHint,
@Nullable Identifier renderTypeHint,
BiPredicate<String, Boolean> visibilityTest
) {
this(isGui3d, useBlockLight, useAmbientOcclusion, transforms, rootTransform, renderTypeHint, null, visibilityTest);
@@ -46,8 +46,8 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext {
boolean isGui3d,
boolean useBlockLight, boolean useAmbientOcclusion,
ItemTransforms transforms, Transformation rootTransform,
@Nullable ResourceLocation renderTypeHint,
@Nullable ResourceLocation renderTypeFastHint,
@Nullable Identifier renderTypeHint,
@Nullable Identifier renderTypeFastHint,
BiPredicate<String, Boolean> visibilityTest
) {
this.isGui3d = isGui3d;
@@ -87,13 +87,13 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext {
@Nullable
@Override
public ResourceLocation getRenderTypeHint() {
public Identifier getRenderTypeHint() {
return renderTypeHint;
}
@Nullable
@Override
public ResourceLocation getRenderTypeFastHint() {
public Identifier getRenderTypeFastHint() {
return renderTypeFastHint;
}
@@ -117,9 +117,9 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext {
private ItemTransforms transforms = ItemTransforms.NO_TRANSFORMS;
private Transformation rootTransform = Transformation.identity();
@Nullable
private ResourceLocation renderTypeHint;
private Identifier renderTypeHint;
@Nullable
private ResourceLocation renderTypeFastHint;
private Identifier renderTypeFastHint;
private BiPredicate<String, Boolean> visibilityTest = (c, def) -> def;
private Builder() { }
@@ -160,12 +160,12 @@ public class StandaloneGeometryBakingContext implements IGeometryBakingContext {
return this;
}
public Builder withRenderTypeHint(ResourceLocation renderTypeHint) {
public Builder withRenderTypeHint(Identifier renderTypeHint) {
this.renderTypeHint = renderTypeHint;
return this;
}
public Builder withRenderTypeHint(ResourceLocation renderTypeHint, ResourceLocation renderTypeFastHint) {
public Builder withRenderTypeHint(Identifier renderTypeHint, Identifier renderTypeFastHint) {
this.renderTypeHint = renderTypeHint;
this.renderTypeFastHint = renderTypeFastHint;
return this;
@@ -7,7 +7,7 @@ package net.minecraftforge.client.model.geometry;
import com.mojang.math.Quadrant;
import com.mojang.math.Transformation;
import net.minecraft.Util;
import net.minecraft.util.Util;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.block.model.BlockElement;
import net.minecraft.client.renderer.block.model.BlockElementFace;
@@ -19,12 +19,11 @@ import net.minecraft.client.renderer.texture.SpriteContents;
import net.minecraft.client.renderer.texture.TextureAtlas;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.model.Material;
import net.minecraft.client.resources.model.ModelBaker;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.QuadCollection;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.client.model.IQuadTransformer;
import net.minecraftforge.client.model.QuadTransformers;
import net.minecraft.resources.Identifier;
import net.minecraftforge.client.model.SimpleModelState;
import org.jetbrains.annotations.ApiStatus;
@@ -44,7 +43,7 @@ import java.util.regex.Pattern;
public class UnbakedGeometryHelper {
/**
* Explanation:
* This takes anything that looks like a valid resourcepack texture location, and tries to extract a resourcelocation out of it.
* This takes anything that looks like a valid resourcepack texture location, and tries to extract a Identifier out of it.
* 1. it will ignore anything up to and including an /assets/ folder,
* 2. it will take the next path component as a namespace,
* 3. it will match but skip the /textures/ part of the path,
@@ -62,7 +61,7 @@ public class UnbakedGeometryHelper {
private static final Material MISSING_MATERIAL = getMaterial(MissingTextureAtlasSprite.getLocation().toString());
/**
* Resolves a material that may have been defined with a filesystem path instead of a proper {@link ResourceLocation}.
* Resolves a material that may have been defined with a filesystem path instead of a proper {@link Identifier}.
* <p>
* The target atlas will always be {@link TextureAtlas#LOCATION_BLOCKS}.
*/
@@ -73,7 +72,7 @@ public class UnbakedGeometryHelper {
if (tex.startsWith("#"))
return textures.getMaterial(tex);
// Attempt to convert a common (windows/linux/mac) filesystem path to a ResourceLocation.
// Attempt to convert a common (windows/linux/mac) filesystem path to a Identifier.
// This makes no promises, if it doesn't work, too bad, fix your mtl file.
Matcher match = FILESYSTEM_PATH_TO_RESLOC.matcher(tex);
if (match.matches()) {
@@ -159,34 +158,20 @@ public class UnbakedGeometryHelper {
/**
* Bakes a list of {@linkplain BlockElement block elements} and returns a {@link QuadCollection}.
*/
public static QuadCollection bakeElements(List<BlockElement> elements, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState) {
return bakeElements(elements, spriteGetter, modelState, QuadTransformers.empty());
}
/**
* Bakes a list of {@linkplain BlockElement block elements} and returns a {@link QuadCollection}.
*/
public static QuadCollection bakeElements(List<BlockElement> elements, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, IQuadTransformer transformer) {
public static QuadCollection bakeElements(ModelBaker.PartCache cache, List<BlockElement> elements, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState) {
var builder = new QuadCollection.Builder();
bakeElements(elements, spriteGetter, modelState, builder);
bakeElements(cache, elements, spriteGetter, modelState, builder);
return builder.build();
}
/**
* Adds a list of {@linkplain BlockElement block elements} int a {@link QuadCollection.Builder}.
*/
public static void bakeElements(List<BlockElement> elements, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, QuadCollection.Builder builder) {
bakeElements(elements, spriteGetter, modelState, QuadTransformers.empty(), builder);
}
/**
* Adds a list of {@linkplain BlockElement block elements} int a {@link QuadCollection.Builder}.
*/
public static void bakeElements(List<BlockElement> elements, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, IQuadTransformer transformer, QuadCollection.Builder builder) {
public static void bakeElements(ModelBaker.PartCache cache, List<BlockElement> elements, Function<Material, TextureAtlasSprite> spriteGetter, ModelState modelState, QuadCollection.Builder builder) {
for (var element : elements) {
element.faces().forEach((side, face) -> {
var sprite = spriteGetter.apply(getMaterial(face.texture()));
var quad = bakeElementFace(element, face, sprite, side, modelState, element.lightEmission());
var quad = bakeElementFace(cache, element, face, sprite, side, modelState, element.lightEmission());
if (face.cullForDirection() == null)
builder.addUnculledFace(quad);
else
@@ -197,14 +182,14 @@ public class UnbakedGeometryHelper {
@SuppressWarnings("deprecation")
private static Material getMaterial(String texture) {
return new Material(TextureAtlas.LOCATION_BLOCKS, ResourceLocation.parse(texture));
return new Material(TextureAtlas.LOCATION_BLOCKS, Identifier.parse(texture));
}
/**
* Turns a single {@link BlockElementFace} into a {@link BakedQuad}.
*/
public static BakedQuad bakeElementFace(BlockElement element, BlockElementFace face, TextureAtlasSprite sprite, Direction direction, ModelState state, int lightEmission) {
return FaceBakery.bakeQuad(element.from(), element.to(), face, sprite, direction, state, element.rotation(), element.shade(), lightEmission);
public static BakedQuad bakeElementFace(ModelBaker.PartCache cache, BlockElement element, BlockElementFace face, TextureAtlasSprite sprite, Direction direction, ModelState state, int lightEmission) {
return FaceBakery.bakeQuad(cache, element.from(), element.to(), face, sprite, direction, state, element.rotation(), element.shade(), lightEmission);
}
/**
@@ -215,6 +200,7 @@ public class UnbakedGeometryHelper {
* @return an {@code IQuadTransformer} that applies the root transform to a baked quad that already has the
* transformation of the given {@code ModelState} applied to it
*/
/*
public static IQuadTransformer applyRootTransform(ModelState modelState, Transformation rootTransform) {
// Move the origin of the ModelState transform and its inverse from the negative corner to the block center
// to replicate the way the ModelState transform is applied in the FaceBakery by moving the vertices such that
@@ -222,6 +208,7 @@ public class UnbakedGeometryHelper {
Transformation transform = modelState.transformation().applyOrigin(new Vector3f(.5F, .5F, .5F));
return QuadTransformers.applying(transform.compose(rootTransform).compose(transform.inverse()));
}
*/
/**
* {@return a {@link ModelState} that combines the existing model state and the {@linkplain Transformation root transform}}
@@ -15,7 +15,7 @@ import net.minecraft.client.resources.model.ModelDebugName;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.QuadCollection;
import net.minecraft.client.resources.model.UnbakedGeometry;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.server.packs.resources.Resource;
import net.minecraft.server.packs.resources.ResourceManager;
import net.minecraft.server.packs.resources.ResourceManagerReloadListener;
@@ -36,7 +36,7 @@ public class ObjLoader implements IGeometryLoader, ResourceManagerReloadListener
public static ObjLoader INSTANCE = new ObjLoader();
private final Map<ObjModel.ModelSettings, ObjModel> modelCache = Maps.newConcurrentMap();
private final Map<ResourceLocation, ObjMaterialLibrary> materialCache = Maps.newConcurrentMap();
private final Map<Identifier, ObjMaterialLibrary> materialCache = Maps.newConcurrentMap();
private ResourceManager manager = Minecraft.getInstance().getResourceManager();
@@ -49,7 +49,7 @@ public class ObjLoader implements IGeometryLoader, ResourceManagerReloadListener
@Override
public UnbakedGeometry read(JsonObject json, JsonDeserializationContext deserializationContext) {
var location = ResourceLocation.parse(GsonHelper.getAsString(json, "model"));
var location = Identifier.parse(GsonHelper.getAsString(json, "model"));
boolean automaticCulling = GsonHelper.getAsBoolean(json, "automatic_culling", true);
boolean shadeQuads = GsonHelper.getAsBoolean(json, "shade_quads", true);
@@ -74,7 +74,7 @@ public class ObjLoader implements IGeometryLoader, ResourceManagerReloadListener
});
}
public ObjMaterialLibrary loadMaterialLibrary(ResourceLocation materialLocation) {
public ObjMaterialLibrary loadMaterialLibrary(Identifier materialLocation) {
return materialCache.computeIfAbsent(materialLocation, (location) -> {
Resource resource = manager.getResource(location).orElseThrow();
try (ObjTokenizer rdr = new ObjTokenizer(resource.open())) {
@@ -19,13 +19,12 @@ import net.minecraft.client.resources.model.ModelDebugName;
import net.minecraft.client.resources.model.ModelState;
import net.minecraft.client.resources.model.QuadCollection;
import net.minecraft.core.Direction;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.util.Mth;
import net.minecraft.world.phys.Vec2;
import net.minecraftforge.client.model.IModelBuilder;
import net.minecraftforge.client.model.geometry.IGeometryBakingContext;
import net.minecraftforge.client.model.geometry.UnbakedGeometryHelper;
import net.minecraftforge.client.model.pipeline.QuadBakingVertexConsumer;
import net.minecraftforge.client.model.pipeline.BakedQuadBuilder;
import net.minecraftforge.client.model.renderable.CompositeRenderable;
import net.minecraftforge.client.textures.UnitTextureAtlasSprite;
import org.apache.commons.lang3.tuple.Pair;
@@ -50,7 +49,7 @@ import java.util.stream.Collectors;
* A model loaded from an OBJ file.
* <p>
* Supports positions, texture coordinates, normals and colors. The {@link ObjMaterialLibrary material library}
* has support for numerous features, including support for {@link ResourceLocation} textures (non-standard).
* has support for numerous features, including support for {@link Identifier} textures (non-standard).
*/
public class ObjModel {
private static final Vector4f COLOR_WHITE = new Vector4f(1, 1, 1, 1);
@@ -78,7 +77,7 @@ public class ObjModel {
@Nullable
public final String mtlOverride;
public final ResourceLocation modelLocation;
public final Identifier modelLocation;
private ObjModel(ModelSettings settings) {
this.modelLocation = settings.modelLocation;
@@ -119,9 +118,9 @@ public class ObjModel {
if (materialLibraryOverrideLocation != null) {
String lib = materialLibraryOverrideLocation;
if (lib.contains(":"))
mtllib = ObjLoader.INSTANCE.loadMaterialLibrary(ResourceLocation.parse(lib));
mtllib = ObjLoader.INSTANCE.loadMaterialLibrary(Identifier.parse(lib));
else
mtllib = ObjLoader.INSTANCE.loadMaterialLibrary(ResourceLocation.fromNamespaceAndPath(modelDomain, modelPath + lib));
mtllib = ObjLoader.INSTANCE.loadMaterialLibrary(Identifier.fromNamespaceAndPath(modelDomain, modelPath + lib));
}
String[] line;
@@ -133,9 +132,9 @@ public class ObjModel {
String lib = line[1];
if (lib.contains(":"))
mtllib = ObjLoader.INSTANCE.loadMaterialLibrary(ResourceLocation.parse(lib));
mtllib = ObjLoader.INSTANCE.loadMaterialLibrary(Identifier.parse(lib));
else
mtllib = ObjLoader.INSTANCE.loadMaterialLibrary(ResourceLocation.fromNamespaceAndPath(modelDomain, modelPath + lib));
mtllib = ObjLoader.INSTANCE.loadMaterialLibrary(Identifier.fromNamespaceAndPath(modelDomain, modelPath + lib));
break;
}
case "usemtl": { // Sets the current material (starts new mesh)
@@ -307,7 +306,7 @@ public class ObjModel {
faceNormal = abs;
}
var quadBaker = new QuadBakingVertexConsumer.Buffered();
var quadBaker = new BakedQuadBuilder.Single();
quadBaker.setSprite(texture);
quadBaker.setTintIndex(tintIndex);
@@ -555,14 +554,14 @@ public class ObjModel {
quads.add(pair.getLeft());
}
ResourceLocation textureLocation = UnbakedGeometryHelper.resolveDirtyMaterial(mat.diffuseColorMap, textures).texture();
ResourceLocation texturePath = textureLocation.withPath(p -> "textures/" + p + ".png");
Identifier textureLocation = UnbakedGeometryHelper.resolveDirtyMaterial(mat.diffuseColorMap, textures).texture();
Identifier texturePath = textureLocation.withPath(p -> "textures/" + p + ".png");
builder.addMesh(texturePath, quads);
}
}
public record ModelSettings(@NotNull ResourceLocation modelLocation,
public record ModelSettings(@NotNull Identifier modelLocation,
boolean automaticCulling, boolean shadeQuads, boolean flipV,
boolean emissiveAmbient, @Nullable String mtlOverride)
{ }
@@ -3,10 +3,7 @@
* SPDX-License-Identifier: LGPL-2.1-only
*/
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@NullMarked
package net.minecraftforge.client.model.obj;
import net.minecraft.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
import org.jspecify.annotations.NullMarked;
@@ -3,10 +3,7 @@
* SPDX-License-Identifier: LGPL-2.1-only
*/
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@NullMarked
package net.minecraftforge.client.model;
import net.minecraft.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
import org.jspecify.annotations.NullMarked;
@@ -6,39 +6,30 @@
package net.minecraftforge.client.model.pipeline;
import com.google.common.base.Preconditions;
import com.mojang.blaze3d.vertex.DefaultVertexFormat;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.blaze3d.vertex.VertexFormatElement;
import net.minecraft.Util;
import net.minecraft.client.model.geom.builders.UVPair;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.core.Direction;
import net.minecraftforge.client.model.IQuadTransformer;
import net.minecraftforge.client.textures.UnitTextureAtlasSprite;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.function.Consumer;
import org.joml.Vector3f;
/**
* Vertex consumer that outputs {@linkplain BakedQuad baked quads}.
* <p>
* This consumer accepts data in {@link com.mojang.blaze3d.vertex.DefaultVertexFormat#BLOCK} and is not picky about
* ordering or missing elements, but will not automatically populate missing data (color will be black, for example).
*/
public class QuadBakingVertexConsumer implements VertexConsumer {
private final Map<VertexFormatElement, Integer> ELEMENT_OFFSETS = Util.make(new IdentityHashMap<>(), map -> {
int i = 0;
for (var element : DefaultVertexFormat.BLOCK.getElements())
map.put(element, DefaultVertexFormat.BLOCK.getOffset(i++) / 4); // Int offset
});
public class BakedQuadBuilder implements VertexConsumer {
private static final int MAX_VERTICES = 4;
private static final int QUAD_DATA_SIZE = IQuadTransformer.STRIDE * MAX_VERTICES;
private final Consumer<BakedQuad> quadConsumer;
int vertexIndex = -1;
private int[] quadData = new int[QUAD_DATA_SIZE];
private Vector3f[] positions;
private long[] uvs;
private int tintIndex;
private Direction direction = Direction.DOWN;
@@ -47,8 +38,9 @@ public class QuadBakingVertexConsumer implements VertexConsumer {
private boolean hasAmbientOcclusion;
private int lightEmission;
public QuadBakingVertexConsumer(Consumer<BakedQuad> quadConsumer) {
public BakedQuadBuilder(Consumer<BakedQuad> quadConsumer) {
this.quadConsumer = quadConsumer;
setup();
}
@Override
@@ -56,72 +48,76 @@ public class QuadBakingVertexConsumer implements VertexConsumer {
if (vertexIndex++ == MAX_VERTICES)
build();
int offset = vertexIndex * IQuadTransformer.STRIDE + IQuadTransformer.POSITION;
quadData[offset] = Float.floatToRawIntBits((float) x);
quadData[offset + 1] = Float.floatToRawIntBits((float) y);
quadData[offset + 2] = Float.floatToRawIntBits((float) z);
return this;
}
@Override
public VertexConsumer setNormal(float x, float y, float z) {
int offset = vertexIndex * IQuadTransformer.STRIDE + IQuadTransformer.NORMAL;
quadData[offset] = ((int) (x * 127.0f) & 0xFF) |
(((int) (y * 127.0f) & 0xFF) << 8) |
(((int) (z * 127.0f) & 0xFF) << 16);
return this;
}
@Override
public VertexConsumer setColor(int r, int g, int b, int a) {
int offset = vertexIndex * IQuadTransformer.STRIDE + IQuadTransformer.COLOR;
quadData[offset] = ((a & 0xFF) << 24) |
((b & 0xFF) << 16) |
((g & 0xFF) << 8) |
(r & 0xFF);
var pos = this.positions[vertexIndex];
pos.x = x;
pos.y = y;
pos.z = z;
return this;
}
@Override
public VertexConsumer setUv(float u, float v) {
int offset = vertexIndex * IQuadTransformer.STRIDE + IQuadTransformer.UV0;
quadData[offset] = Float.floatToRawIntBits(u);
quadData[offset + 1] = Float.floatToRawIntBits(v);
this.uvs[vertexIndex] = UVPair.pack(u, v);
return this;
}
/** Will not actually do anything, vanilla implementations ignore if passed invalid data so we do as well */
@Override
public VertexConsumer setNormal(float x, float y, float z) {
//throw new IllegalStateException("Normal is not supported in BakedQuads anymore, vanilla never used this");
return this;
}
/** Will not actually do anything, vanilla implementations ignore if passed invalid data so we do as well */
@Override
public VertexConsumer setColor(int r, int g, int b, int a) {
//throw new IllegalStateException("Per-vertex color is not supported in BakedQuads anymore, vanilla removed the feature");
return this;
}
/** Will not actually do anything, vanilla implementations ignore if passed invalid data so we do as well */
@Override
public VertexConsumer setColor(int packed) {
//throw new IllegalStateException("Per-vertex color is not supported in BakedQuads anymore, vanilla removed the feature");
return this;
}
/** Will not actually do anything, vanilla implementations ignore if passed invalid data so we do as well */
@Override
public VertexConsumer setLineWidth(float packed) {
//throw new IllegalStateException("Normal is not supported in BakedQuads anymore, vanilla never used this");
return this;
}
/** Will not actually do anything, vanilla implementations ignore if passed invalid data so we do as well */
@Override
public VertexConsumer setUv1(int u, int v) {
if (IQuadTransformer.UV1 >= 0) { // Vanilla doesn't support this, but it may be added by a 3rd party
int offset = vertexIndex * IQuadTransformer.STRIDE + IQuadTransformer.UV1;
quadData[offset] = (u & 0xFFFF) | ((v & 0xFFFF) << 16);
}
//throw new IllegalStateException("UV1 is not supported in BakedQuads anymore, vanilla never used this");
return this;
}
/** Will not actually do anything, vanilla implementations ignore if passed invalid data so we do as well */
@Override
public VertexConsumer setUv2(int u, int v) {
int offset = vertexIndex * IQuadTransformer.STRIDE + IQuadTransformer.UV2;
quadData[offset] = (u & 0xFFFF) | ((v & 0xFFFF) << 16);
//throw new IllegalStateException("UV2 is not supported in BakedQuads anymore, you can't bake lighting per vertex anymore");
return this;
}
@Override
public VertexConsumer misc(VertexFormatElement element, int... rawData) {
Integer baseOffset = ELEMENT_OFFSETS.get(element);
if (baseOffset != null) {
int offset = vertexIndex * IQuadTransformer.STRIDE + baseOffset;
System.arraycopy(rawData, 0, quadData, offset, rawData.length);
}
return this;
private void setup() {
this.positions = new Vector3f[]{ new Vector3f(), new Vector3f(), new Vector3f(), new Vector3f() };
this.uvs = new long[4];
this.vertexIndex = 0;
}
public BakedQuad build() {
BakedQuad quad = new BakedQuad(quadData, tintIndex, direction, sprite, shade, lightEmission, hasAmbientOcclusion);
BakedQuad quad = new BakedQuad(
this.positions[0], this.positions[1], this.positions[2], this.positions[3],
this.uvs[0], this.uvs[1], this.uvs[2], this.uvs[3],
tintIndex, direction, sprite, shade, lightEmission, hasAmbientOcclusion
);
setup();
// We have a full quad, pass it to the consumer and reset
quadConsumer.accept(quad);
vertexIndex = 0;
quadData = new int[QUAD_DATA_SIZE];
return quad;
}
@@ -149,14 +145,14 @@ public class QuadBakingVertexConsumer implements VertexConsumer {
this.lightEmission = value;
}
public static class Buffered extends QuadBakingVertexConsumer {
public static class Single extends BakedQuadBuilder {
private final BakedQuad[] output;
public Buffered() {
public Single() {
this(new BakedQuad[1]);
}
private Buffered(BakedQuad[] output) {
private Single(BakedQuad[] output) {
super(q -> output[0] = q);
this.output = output;
}
@@ -6,68 +6,64 @@
package net.minecraftforge.client.model.pipeline;
import com.mojang.blaze3d.vertex.VertexConsumer;
import com.mojang.blaze3d.vertex.VertexFormatElement;
/**
* Wrapper for {@link VertexConsumer} which delegates all operations to its parent.
* <p>
* Useful for defining custom pipeline elements that only process certain data.
*/
public abstract class VertexConsumerWrapper implements VertexConsumer
{
public class VertexConsumerWrapper implements VertexConsumer {
protected final VertexConsumer parent;
public VertexConsumerWrapper(VertexConsumer parent)
{
public VertexConsumerWrapper(VertexConsumer parent) {
this.parent = parent;
}
@Override
public VertexConsumer addVertex(float x, float y, float z)
{
public VertexConsumer addVertex(float x, float y, float z) {
parent.addVertex(x, y, z);
return this;
}
@Override
public VertexConsumer setColor(int r, int g, int b, int a)
{
public VertexConsumer setColor(int color) {
parent.setColor(color);
return this;
}
@Override
public VertexConsumer setColor(int r, int g, int b, int a) {
parent.setColor(r, g, b, a);
return this;
}
@Override
public VertexConsumer setUv(float u, float v)
{
public VertexConsumer setUv(float u, float v) {
parent.setUv(u, v);
return this;
}
@Override
public VertexConsumer setUv1(int u, int v)
{
public VertexConsumer setUv1(int u, int v) {
parent.setUv1(u, v);
return this;
}
@Override
public VertexConsumer setUv2(int u, int v)
{
public VertexConsumer setUv2(int u, int v) {
parent.setUv2(u, v);
return this;
}
@Override
public VertexConsumer setNormal(float x, float y, float z)
{
public VertexConsumer setNormal(float x, float y, float z) {
parent.setNormal(x, y, z);
return this;
}
@Override
public VertexConsumer misc(VertexFormatElement element, int... values)
{
parent.misc(element, values);
public VertexConsumer setLineWidth(float width) {
parent.setLineWidth(width);
return this;
}
}
@@ -3,10 +3,7 @@
* SPDX-License-Identifier: LGPL-2.1-only
*/
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
@NullMarked
package net.minecraftforge.client.model.pipeline;
import net.minecraft.MethodsReturnNonnullByDefault;
import javax.annotation.ParametersAreNonnullByDefault;
import org.jspecify.annotations.NullMarked;
@@ -67,7 +67,7 @@ public class BakedModelRenderable implements IRenderable<BakedModelRenderable.Co
for (var part : parts) {
for (var direction : Direction.valuesView()) {
for (var quad : part.getQuads(direction)) {
buffer.putBulkData(poseStack.last(), quad, tint.x(), tint.y(), tint.z(), tint.w(), lightmap, overlay, true);
buffer.putBulkData(poseStack.last(), quad, tint.x(), tint.y(), tint.z(), tint.w(), lightmap, overlay);
}
}
}
@@ -9,7 +9,7 @@ import com.google.common.collect.ImmutableMap;
import com.mojang.blaze3d.vertex.PoseStack;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.block.model.BakedQuad;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import org.jetbrains.annotations.Nullable;
import org.joml.Matrix4f;
@@ -66,17 +66,17 @@ public class CompositeRenderable implements IRenderable<CompositeRenderable.Tran
}
private static class Mesh {
private final ResourceLocation texture;
private final Identifier texture;
private final List<BakedQuad> quads = new ArrayList<>();
public Mesh(ResourceLocation texture) {
public Mesh(Identifier texture) {
this.texture = texture;
}
public void render(PoseStack poseStack, MultiBufferSource bufferSource, ITextureRenderTypeLookup textureRenderTypeLookup, int lightmap, int overlay) {
var consumer = bufferSource.getBuffer(textureRenderTypeLookup.get(texture));
for (var quad : quads)
consumer.putBulkData(poseStack.last(), quad, 1, 1, 1, 1, lightmap, overlay, true);
consumer.putBulkData(poseStack.last(), quad, 1, 1, 1, 1, lightmap, overlay);
}
}
@@ -111,7 +111,7 @@ public class CompositeRenderable implements IRenderable<CompositeRenderable.Tran
return new PartBuilder<>(this, child);
}
public PartBuilder<T> addMesh(ResourceLocation texture, List<BakedQuad> quads) {
public PartBuilder<T> addMesh(Identifier texture, List<BakedQuad> quads) {
var mesh = new Mesh(texture);
mesh.quads.addAll(quads);
component.meshes.add(mesh);
@@ -5,14 +5,13 @@
package net.minecraftforge.client.model.renderable;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.client.renderer.rendertype.RenderType;
import net.minecraft.resources.Identifier;
/**
* A generic lookup for {@link RenderType} implementations that use the specified texture.
*/
@FunctionalInterface
public interface ITextureRenderTypeLookup
{
RenderType get(ResourceLocation name);
public interface ITextureRenderTypeLookup {
RenderType get(Identifier name);
}
@@ -21,7 +21,9 @@ public enum KeyModifier {
CONTROL {
@Override
public boolean matches(InputConstants.Key key) {
return key.getValue() == InputQuirks.EDIT_SHORTCUT_KEY_LEFT || key.getValue() == InputQuirks.EDIT_SHORTCUT_KEY_RIGHT;
if (InputQuirks.REPLACE_CTRL_KEY_WITH_CMD_KEY)
return key.getValue() == 343 || key.getValue() == 347;
return key.getValue() == 341 || key.getValue() == 345;
}
@Override
@@ -5,7 +5,7 @@
package net.minecraftforge.client.textures;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.server.packs.metadata.MetadataSectionType;
import net.minecraft.server.packs.resources.Resource;
import com.mojang.serialization.Codec;
@@ -29,7 +29,7 @@ public record ForgeTextureMetadata(@Nullable ITextureAtlasSpriteLoader loader) {
var ret = TextureAtlasSpriteLoaderManager.getKey(loader);
return ret == null ? null : ret.toString();
},
name -> TextureAtlasSpriteLoaderManager.get(ResourceLocation.parse(name))
name -> TextureAtlasSpriteLoaderManager.get(Identifier.parse(name))
);
private static final Codec<ForgeTextureMetadata> CODEC = RecordCodecBuilder.create(i ->
@@ -9,7 +9,7 @@ import com.mojang.blaze3d.platform.NativeImage;
import net.minecraft.client.renderer.texture.SpriteContents;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.metadata.animation.FrameSize;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.server.packs.metadata.MetadataSectionType;
import net.minecraft.server.packs.resources.Resource;
import net.minecraftforge.client.event.RegisterTextureAtlasSpriteLoadersEvent;
@@ -33,11 +33,11 @@ import org.jetbrains.annotations.NotNull;
* @see RegisterTextureAtlasSpriteLoadersEvent
*/
public interface ITextureAtlasSpriteLoader {
SpriteContents loadContents(ResourceLocation name, Resource resource, FrameSize frameSize, NativeImage image, List<MetadataSectionType.WithValue<?>> metadata);
SpriteContents loadContents(Identifier name, Resource resource, FrameSize frameSize, NativeImage image, List<MetadataSectionType.WithValue<?>> metadata);
/**
* Creates a {@link TextureAtlasSprite} from the given {@link SpriteContents}.
*/
@NotNull
TextureAtlasSprite makeSprite(ResourceLocation atlasName, SpriteContents contents, int atlasWidth, int atlasHeight, int spriteX, int spriteY, int mipmapLevel);
TextureAtlasSprite makeSprite(Identifier atlasName, SpriteContents contents, int atlasWidth, int atlasHeight, int spriteX, int spriteY, int padding, int mipmapLevel);
}
@@ -8,7 +8,7 @@ package net.minecraftforge.client.textures;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.ImmutableBiMap;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.client.event.RegisterTextureAtlasSpriteLoadersEvent;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Nullable;
@@ -20,24 +20,24 @@ import org.jetbrains.annotations.Nullable;
* TODO: Convert this into a proper registry
*/
public final class TextureAtlasSpriteLoaderManager {
private static BiMap<ResourceLocation, ITextureAtlasSpriteLoader> LOADERS;
private static BiMap<Identifier, ITextureAtlasSpriteLoader> LOADERS;
/**
* Finds the loader with the given name, or null if none is registered.
*/
@Nullable
public static ITextureAtlasSpriteLoader get(ResourceLocation name) {
public static ITextureAtlasSpriteLoader get(Identifier name) {
return LOADERS.get(name);
}
@Nullable
public static ResourceLocation getKey(ITextureAtlasSpriteLoader value) {
public static Identifier getKey(ITextureAtlasSpriteLoader value) {
return LOADERS.inverse().get(value);
}
@ApiStatus.Internal
public static void init() {
var loaders = HashBiMap.<ResourceLocation, ITextureAtlasSpriteLoader>create();
var loaders = HashBiMap.<Identifier, ITextureAtlasSpriteLoader>create();
RegisterTextureAtlasSpriteLoadersEvent.BUS.post(new RegisterTextureAtlasSpriteLoadersEvent(loaders));
LOADERS = ImmutableBiMap.copyOf(loaders);
}
@@ -9,7 +9,7 @@ import com.mojang.blaze3d.platform.NativeImage;
import net.minecraft.client.renderer.texture.SpriteContents;
import net.minecraft.client.renderer.texture.TextureAtlasSprite;
import net.minecraft.client.resources.metadata.animation.FrameSize;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
/**
* A helper sprite with UVs spanning the entire texture.
@@ -17,11 +17,11 @@ import net.minecraft.resources.ResourceLocation;
* Useful for baking quads that won't be used with an atlas.
*/
public class UnitTextureAtlasSprite extends TextureAtlasSprite {
public static final ResourceLocation LOCATION = ResourceLocation.fromNamespaceAndPath("forge", "unit");
public static final Identifier LOCATION = Identifier.fromNamespaceAndPath("forge", "unit");
public static final UnitTextureAtlasSprite INSTANCE = new UnitTextureAtlasSprite();
private UnitTextureAtlasSprite() {
super(LOCATION, new SpriteContents(LOCATION, new FrameSize(1, 1), new NativeImage(1, 1, false)), 1, 1, 0, 0);
super(LOCATION, new SpriteContents(LOCATION, new FrameSize(1, 1), new NativeImage(1, 1, false)), 1, 1, 0, 0, 0);
}
@Override
@@ -13,20 +13,16 @@ import java.util.List;
import com.google.common.collect.ImmutableList;
import net.minecraft.util.random.WeightedRandom;
import net.minecraft.world.entity.ai.behavior.ShufflingList;
import net.minecraft.world.level.biome.Biomes;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.level.biome.Biome;
public class BiomeManager
{
public class BiomeManager {
private static final TrackedList<BiomeEntry>[] biomes = setupBiomes();
private static final List<ResourceKey<Biome>> additionalOverworldBiomes = new ArrayList<>();
private static final List<ResourceKey<Biome>> additionalOverworldBiomesView = Collections.unmodifiableList(additionalOverworldBiomes);
private static TrackedList<BiomeEntry>[] setupBiomes()
{
private static TrackedList<BiomeEntry>[] setupBiomes() {
@SuppressWarnings("unchecked")
TrackedList<BiomeEntry>[] currentBiomes = new TrackedList[BiomeType.values().length];
@@ -68,28 +64,22 @@ public class BiomeManager
/**
* Add biomes that you add to the overworld without using {@link BiomeManager#addBiome(BiomeType, BiomeEntry)}
*/
public static void addAdditionalOverworldBiomes(ResourceKey<Biome> biome)
{
if (!"minecraft".equals(biome.location().getNamespace()) && additionalOverworldBiomes.stream().noneMatch(entry -> entry.location().equals(biome.location())))
{
public static void addAdditionalOverworldBiomes(ResourceKey<Biome> biome) {
if (!"minecraft".equals(biome.identifier().getNamespace()) && additionalOverworldBiomes.stream().noneMatch(entry -> entry.identifier().equals(biome.identifier())))
additionalOverworldBiomes.add(biome);
}
}
public static boolean addBiome(BiomeType type, BiomeEntry entry)
{
public static boolean addBiome(BiomeType type, BiomeEntry entry) {
int idx = type.ordinal();
List<BiomeEntry> list = idx > biomes.length ? null : biomes[idx];
if (list != null)
{
if (list != null) {
additionalOverworldBiomes.add(entry.key);
return list.add(entry);
}
return false;
}
public static boolean removeBiome(BiomeType type, BiomeEntry entry)
{
public static boolean removeBiome(BiomeType type, BiomeEntry entry) {
int idx = type.ordinal();
List<BiomeEntry> list = idx > biomes.length ? null : biomes[idx];
return list == null ? false : list.remove(entry);
@@ -98,128 +88,108 @@ public class BiomeManager
/**
* @return list of biomes that might be generated in the overworld in addition to the vanilla biomes
*/
public static List<ResourceKey<Biome>> getAdditionalOverworldBiomes()
{
public static List<ResourceKey<Biome>> getAdditionalOverworldBiomes() {
return additionalOverworldBiomesView;
}
public static ImmutableList<BiomeEntry> getBiomes(BiomeType type)
{
public static ImmutableList<BiomeEntry> getBiomes(BiomeType type) {
int idx = type.ordinal();
List<BiomeEntry> list = idx >= biomes.length ? null : biomes[idx];
return list != null ? ImmutableList.copyOf(list) : ImmutableList.of();
}
public static boolean isTypeListModded(BiomeType type)
{
public static boolean isTypeListModded(BiomeType type) {
int idx = type.ordinal();
TrackedList<BiomeEntry> list = idx > biomes.length ? null : biomes[idx];
return list == null ? false : list.isModded();
}
public static enum BiomeType
{
public static enum BiomeType {
DESERT, DESERT_LEGACY, WARM, COOL, ICY;
}
public static class BiomeEntry
{
public static class BiomeEntry {
private final ResourceKey<Biome> key;
public BiomeEntry(ResourceKey<Biome> key, int weight)
{
public BiomeEntry(ResourceKey<Biome> key, int weight) {
this.key = key;
}
public ResourceKey<Biome> getKey()
{
public ResourceKey<Biome> getKey() {
return this.key;
}
}
private static class TrackedList<E> extends ArrayList<E>
{
private static class TrackedList<E> extends ArrayList<E> {
private static final long serialVersionUID = 1L;
private boolean isModded = false;
@SafeVarargs
private <T extends E> TrackedList(T... c)
{
private <T extends E> TrackedList(T... c) {
super(Arrays.asList(c));
}
@Override
public E set(int index, E element)
{
public E set(int index, E element) {
isModded = true;
return super.set(index, element);
}
@Override
public boolean add(E e)
{
public boolean add(E e) {
isModded = true;
return super.add(e);
}
@Override
public void add(int index, E element)
{
public void add(int index, E element) {
isModded = true;
super.add(index, element);
}
@Override
public E remove(int index)
{
public E remove(int index) {
isModded = true;
return super.remove(index);
}
@Override
public boolean remove(Object o)
{
public boolean remove(Object o) {
isModded = true;
return super.remove(o);
}
@Override
public void clear()
{
public void clear() {
isModded = true;
super.clear();
}
@Override
public boolean addAll(Collection<? extends E> c)
{
public boolean addAll(Collection<? extends E> c) {
isModded = true;
return super.addAll(c);
}
@Override
public boolean addAll(int index, Collection<? extends E> c)
{
public boolean addAll(int index, Collection<? extends E> c) {
isModded = true;
return super.addAll(index, c);
}
@Override
public boolean removeAll(Collection<?> c)
{
public boolean removeAll(Collection<?> c) {
isModded = true;
return super.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c)
{
public boolean retainAll(Collection<?> c) {
isModded = true;
return super.retainAll(c);
}
public boolean isModded()
{
public boolean isModded() {
return isModded;
}
}
@@ -21,7 +21,7 @@ import java.util.Comparator;
import net.minecraft.core.Holder;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.packs.resources.PreparableReloadListener;
import net.minecraft.server.packs.resources.Resource;
@@ -49,7 +49,7 @@ import java.util.stream.Collectors;
public final class CreativeModeTabRegistry {
private static final Logger LOGGER = LogUtils.getLogger();
private static final ResourceLocation CREATIVE_MODE_TAB_ORDERING_JSON = ResourceLocation.fromNamespaceAndPath("forge", "creative_mode_tab_ordering.json");
private static final Identifier CREATIVE_MODE_TAB_ORDERING_JSON = Identifier.fromNamespaceAndPath("forge", "creative_mode_tab_ordering.json");
private static final List<CreativeModeTab> SORTED_TABS = new ArrayList<>();
private static final List<CreativeModeTab> SORTED_TABS_VIEW = Collections.unmodifiableList(SORTED_TABS);
private static final List<CreativeModeTab> DEFAULT_TABS = new ArrayList<>();
@@ -71,7 +71,7 @@ public final class CreativeModeTabRegistry {
* @param name the name to look up
*/
@Nullable
public static CreativeModeTab getTab(ResourceLocation name) {
public static CreativeModeTab getTab(Identifier name) {
return BuiltInRegistries.CREATIVE_MODE_TAB.getValue(name);
}
@@ -81,11 +81,11 @@ public final class CreativeModeTabRegistry {
* @param tab the tab to look up
*/
@Nullable
public static ResourceLocation getName(CreativeModeTab tab) {
public static Identifier getName(CreativeModeTab tab) {
return BuiltInRegistries.CREATIVE_MODE_TAB.getKey(tab);
}
private static final Multimap<ResourceLocation, ResourceLocation> edges = HashMultimap.create();
private static final Multimap<Identifier, Identifier> edges = HashMultimap.create();
static PreparableReloadListener getReloadListener() {
return new SimplePreparableReloadListener<JsonObject>() {
@@ -113,7 +113,7 @@ public final class CreativeModeTabRegistry {
JsonArray order = GsonHelper.getAsJsonArray(data, "order");
List<CreativeModeTab> customOrder = new ArrayList<>();
for (JsonElement entry : order) {
ResourceLocation id = ResourceLocation.parse(entry.getAsString());
Identifier id = Identifier.parse(entry.getAsString());
CreativeModeTab CreativeModeTab = getTab(id);
if (CreativeModeTab == null)
throw new IllegalStateException("CreativeModeTab not found with name " + id);
@@ -192,24 +192,24 @@ public final class CreativeModeTabRegistry {
for (int i = 0; i < vanillaTabs; i++) { // Vanilla ordering
final Holder<CreativeModeTab> value = indexed.get(i);
final CreativeModeTab tab = value.get();
final ResourceLocation name = value.unwrapKey().orElseThrow().location();
final Identifier name = value.unwrapKey().orElseThrow().identifier();
if (!tab.tabsBefore.isEmpty() || !tab.tabsAfter.isEmpty())
addTabOrder(tab, name);
else {
// If there is no order specified ensure vanilla ordering by specifying the previous and next indexed tab as edges
if (i != 0)
edges.put(indexed.get(i - 1).unwrapKey().orElseThrow().location(), name);
edges.put(indexed.get(i - 1).unwrapKey().orElseThrow().identifier(), name);
if (i + 1 < indexed.size())
edges.put(name, indexed.get(i + 1).unwrapKey().orElseThrow().location());
edges.put(name, indexed.get(i + 1).unwrapKey().orElseThrow().identifier());
}
}
ResourceLocation lastVanilla = indexed.get(vanillaTabs - 1).unwrapKey().orElseThrow().location();
Identifier lastVanilla = indexed.get(vanillaTabs - 1).unwrapKey().orElseThrow().identifier();
for (int i = vanillaTabs; i < indexed.size(); i++) {
final Holder<CreativeModeTab> value = indexed.get(i);
final CreativeModeTab tab = value.get();
final ResourceLocation name = value.unwrapKey().orElseThrow().location();
final Identifier name = value.unwrapKey().orElseThrow().identifier();
if (!tab.tabsBefore.isEmpty() || !tab.tabsAfter.isEmpty())
addTabOrder(tab, name);
@@ -220,7 +220,7 @@ public final class CreativeModeTabRegistry {
recalculateItemCreativeModeTabs();
}
private static void addTabOrder(CreativeModeTab tab, ResourceLocation name) {
private static void addTabOrder(CreativeModeTab tab, Identifier name) {
for (var after : tab.tabsAfter) {
edges.put(name, after);
}
@@ -63,6 +63,7 @@ import net.minecraft.network.chat.TextColor;
import net.minecraft.network.chat.contents.PlainTextContents.LiteralContents;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.tags.BlockTags;
import net.minecraft.tags.TagKey;
import net.minecraft.util.CrudeIncrementalIntIdentityHashBiMap;
import net.minecraft.util.GsonHelper;
@@ -98,6 +99,7 @@ import net.minecraft.world.item.enchantment.EnchantmentHelper;
import net.minecraft.world.entity.item.ItemEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.server.permissions.Permissions;
import net.minecraft.world.inventory.AnvilMenu;
import net.minecraft.world.Container;
import net.minecraft.world.item.context.UseOnContext;
@@ -181,7 +183,7 @@ import org.apache.logging.log4j.MarkerManager;
import net.minecraft.ChatFormatting;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.world.damagesource.DamageSource;
import net.minecraft.world.level.GameType;
import net.minecraft.world.level.Level;
@@ -282,6 +284,8 @@ public final class ForgeHooks {
public static Optional<BlockPos> isLivingOnLadder(@NotNull BlockState state, @NotNull Level level, @NotNull BlockPos pos, @NotNull LivingEntity entity) {
boolean isSpectator = (entity instanceof Player && entity.isSpectator());
if (isSpectator) return Optional.empty();
if (entity.isFallFlying() && state.is(BlockTags.CAN_GLIDE_THROUGH))
return Optional.empty();
if (!ForgeConfig.SERVER.fullBoundingBoxLadders.get())
return state.isLadder(level, pos, entity) ? Optional.of(pos) : Optional.empty();
else {
@@ -678,7 +682,7 @@ public final class ForgeHooks {
@Nullable
public static String getDefaultCreatorModId(@NotNull ItemStack itemStack) {
Item item = itemStack.getItem();
ResourceLocation registryName = ForgeRegistries.ITEMS.getKey(item);
Identifier registryName = ForgeRegistries.ITEMS.getKey(item);
String modId = registryName == null ? null : registryName.getNamespace();
if ("minecraft".equals(modId)) {
if (itemStack.is(Items.ENCHANTED_BOOK)) {
@@ -687,18 +691,18 @@ public final class ForgeHooks {
var enchant = enchants.keySet().iterator().next();
var name = enchant.unwrapKey();
if (name.isPresent())
return name.get().location().getNamespace();
return name.get().identifier().getNamespace();
}
} else if (itemStack.has(DataComponents.POTION_CONTENTS)) {
var potion = itemStack.get(DataComponents.POTION_CONTENTS).potion().orElse(null);
if (potion != null && potion.unwrapKey().isPresent())
return potion.unwrapKey().get().location().getNamespace();
return potion.unwrapKey().get().identifier().getNamespace();
} else if (item instanceof SpawnEggItem) {
var data = item.components().get(DataComponents.ENTITY_DATA);
if (data != null && data.type() != null) {
var resourceLocation = EntityType.getKey(data.type());
if (resourceLocation != null)
return resourceLocation.getNamespace();
var Identifier = EntityType.getKey(data.type());
if (Identifier != null)
return Identifier.getNamespace();
}
}
}
@@ -817,7 +821,7 @@ public final class ForgeHooks {
fmlData.put("Registries", registries);
LOGGER.debug(WORLDPERSISTENCE, "Gathering id map for writing to world save {}", worldData.getLevelName());
for (Map.Entry<ResourceLocation, ForgeRegistry.Snapshot> e : RegistryManager.ACTIVE.takeSnapshot(true).entrySet())
for (Map.Entry<Identifier, ForgeRegistry.Snapshot> e : RegistryManager.ACTIVE.takeSnapshot(true).entrySet())
registries.put(e.getKey().toString(), e.getValue().write());
LOGGER.debug(WORLDPERSISTENCE, "ID Map collection complete {}", worldData.getLevelName());
levelTag.put("fml", fmlData);
@@ -907,13 +911,13 @@ public final class ForgeHooks {
}
}
Multimap<ResourceLocation, ResourceLocation> failedElements = null;
Multimap<Identifier, Identifier> failedElements = null;
if (tag.contains("Registries")) {
Map<ResourceLocation, ForgeRegistry.Snapshot> snapshot = new HashMap<>();
Map<Identifier, ForgeRegistry.Snapshot> snapshot = new HashMap<>();
CompoundTag regs = tag.getCompoundOrEmpty("Registries");
for (String key : regs.keySet())
snapshot.put(ResourceLocation.parse(key), ForgeRegistry.Snapshot.read(regs.getCompoundOrEmpty(key)));
snapshot.put(Identifier.parse(key), ForgeRegistry.Snapshot.read(regs.getCompoundOrEmpty(key)));
failedElements = GameData.injectSnapshot(snapshot, true, true);
}
@@ -980,12 +984,12 @@ public final class ForgeHooks {
* @hidden For internal use only.
*/
public static boolean checkStructureNamespace(String biome) {
@Nullable ResourceLocation biomeLocation = ResourceLocation.tryParse(biome);
return biomeLocation != null && !biomeLocation.getNamespace().equals(ResourceLocation.DEFAULT_NAMESPACE);
@Nullable Identifier biomeLocation = Identifier.tryParse(biome);
return biomeLocation != null && !biomeLocation.getNamespace().equals(Identifier.DEFAULT_NAMESPACE);
}
public static boolean canUseEntitySelectors(SharedSuggestionProvider provider) {
if (EntitySelectorParser.allowSelectors(provider))
if (provider.permissions().hasPermission(Permissions.COMMANDS_ENTITY_SELECTORS))
return true;
else if (provider instanceof CommandSourceStack source && source.source instanceof ServerPlayer player)
return PermissionAPI.getPermission(player, ForgeMod.USE_SELECTORS_PERMISSION);
@@ -1073,7 +1077,7 @@ public final class ForgeHooks {
}
@ApiStatus.Internal
public static <B extends FriendlyByteBuf> StreamCodec<B, ? extends CustomPacketPayload> getCustomPayloadCodec(ResourceLocation id, int max) {
public static <B extends FriendlyByteBuf> StreamCodec<B, ? extends CustomPacketPayload> getCustomPayloadCodec(Identifier id, int max) {
var channel = NetworkRegistry.findTarget(id);
if (channel == null)
return DiscardedPayload.codec(id, max);
@@ -1111,13 +1115,6 @@ public final class ForgeHooks {
@ApiStatus.Internal
public static boolean onCustomPayload(CustomPayloadEvent event) {
var connection = event.getSource().getConnection();
var expectedSide = connection.getReceiving() == PacketFlow.CLIENTBOUND ? LogicalSide.CLIENT : LogicalSide.SERVER;
if (expectedSide != EffectiveSide.get()) {
connection.disconnect(Component.literal("Illegal packet received, terminating connection"));
return false;
}
var channel = NetworkRegistry.findTarget(event.getChannel());
if (channel != null && channel.dispatch(event))
return true;
@@ -1216,7 +1213,7 @@ public final class ForgeHooks {
throw new IllegalArgumentException("Tried to write unregistered Ingredient to network: " + value);
buf.writeVarInt(-1); // Our Marker
buf.writeResourceLocation(key);
buf.writeIdentifier(key);
}
serializer.write(buf, value);
},
@@ -1227,7 +1224,7 @@ public final class ForgeHooks {
if (size != -1) {
buf.resetReaderIndex();
} else {
var key = buf.readResourceLocation();
var key = buf.readIdentifier();
serializer = ForgeRegistries.INGREDIENT_SERIALIZERS.get().getValue(key);
if (serializer == null)
throw new DecoderException("Could not read ingredient of type: " + key);
@@ -1257,7 +1254,7 @@ public final class ForgeHooks {
}
@SuppressWarnings("unchecked")
public static <T> T onJsonDataParsed(Codec<T> codec, ResourceLocation key, T value) {
public static <T> T onJsonDataParsed(Codec<T> codec, Identifier key, T value) {
if (codec == LootDataType.TABLE.codec()) {
var table = (LootTable)value;
table.setLootTableId(key);
@@ -1274,7 +1271,7 @@ public final class ForgeHooks {
*
* This is useful for game tests that need a structure, but want to create the contents in code.
*/
public static Optional<StructureTemplate> createEmptyStructure(ResourceLocation name) {
public static Optional<StructureTemplate> createEmptyStructure(Identifier name) {
if (name== null || !"forge".equals(name.getNamespace()))
return Optional.empty();
@@ -6,7 +6,6 @@
package net.minecraftforge.common;
import net.minecraft.DetectedVersion;
import net.minecraft.SharedConstants;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BiomeColors;
import net.minecraft.commands.synchronization.ArgumentTypeInfo;
@@ -22,6 +21,7 @@ import net.minecraft.network.chat.Component;
import net.minecraft.server.packs.PackType;
import net.minecraft.server.packs.metadata.pack.PackMetadataSection;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.world.attribute.EnvironmentAttributes;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.Mob;
import net.minecraft.commands.Commands;
@@ -95,7 +95,7 @@ import org.apache.logging.log4j.Logger;
import net.minecraft.data.DataGenerator;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraftforge.common.crafting.ConditionalRecipe;
import net.minecraftforge.common.crafting.conditions.AndCondition;
import net.minecraftforge.common.crafting.conditions.FalseCondition;
@@ -232,29 +232,29 @@ public class ForgeMod {
@Override
public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) {
consumer.accept(new IClientFluidTypeExtensions() {
private static final ResourceLocation UNDERWATER_LOCATION = ResourceLocation.withDefaultNamespace("textures/misc/underwater.png");
private static final ResourceLocation WATER_STILL = ResourceLocation.withDefaultNamespace("block/water_still");
private static final ResourceLocation WATER_FLOW = ResourceLocation.withDefaultNamespace("block/water_flow");
private static final ResourceLocation WATER_OVERLAY = ResourceLocation.withDefaultNamespace("block/water_overlay");
private static final Identifier UNDERWATER_LOCATION = Identifier.withDefaultNamespace("textures/misc/underwater.png");
private static final Identifier WATER_STILL = Identifier.withDefaultNamespace("block/water_still");
private static final Identifier WATER_FLOW = Identifier.withDefaultNamespace("block/water_flow");
private static final Identifier WATER_OVERLAY = Identifier.withDefaultNamespace("block/water_overlay");
@Override
public ResourceLocation getStillTexture() {
public Identifier getStillTexture() {
return WATER_STILL;
}
@Override
public ResourceLocation getFlowingTexture() {
public Identifier getFlowingTexture() {
return WATER_FLOW;
}
@Nullable
@Override
public ResourceLocation getOverlayTexture() {
public Identifier getOverlayTexture() {
return WATER_OVERLAY;
}
@Override
public ResourceLocation getRenderOverlayTexture(Minecraft mc) {
public Identifier getRenderOverlayTexture(Minecraft mc) {
return UNDERWATER_LOCATION;
}
@@ -287,7 +287,7 @@ public class ForgeMod {
{
@Override
public double motionScale(Entity entity) {
return entity.level().dimensionType().ultraWarm() ? 0.007D : 0.0023333333333333335D;
return entity.level().environmentAttributes().getDimensionValue(EnvironmentAttributes.WATER_EVAPORATES) ? 0.007D : 0.0023333333333333335D;
}
@Override
@@ -299,16 +299,16 @@ public class ForgeMod {
@Override
public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) {
consumer.accept(new IClientFluidTypeExtensions() {
private static final ResourceLocation LAVA_STILL = ResourceLocation.withDefaultNamespace("block/lava_still");
private static final ResourceLocation LAVA_FLOW = ResourceLocation.withDefaultNamespace("block/lava_flow");
private static final Identifier LAVA_STILL = Identifier.withDefaultNamespace("block/lava_still");
private static final Identifier LAVA_FLOW = Identifier.withDefaultNamespace("block/lava_flow");
@Override
public ResourceLocation getStillTexture() {
public Identifier getStillTexture() {
return LAVA_STILL;
}
@Override
public ResourceLocation getFlowingTexture() {
public Identifier getFlowingTexture() {
return LAVA_FLOW;
}
});
@@ -349,11 +349,11 @@ public class ForgeMod {
private static boolean enableMilkFluid = false;
public static final RegistryObject<SoundEvent> BUCKET_EMPTY_MILK = RegistryObject.create(ResourceLocation.withDefaultNamespace("item.bucket.empty_milk"), ForgeRegistries.SOUND_EVENTS);
public static final RegistryObject<SoundEvent> BUCKET_FILL_MILK = RegistryObject.create(ResourceLocation.withDefaultNamespace("item.bucket.fill_milk"), ForgeRegistries.SOUND_EVENTS);
public static final RegistryObject<FluidType> MILK_TYPE = RegistryObject.createOptional(ResourceLocation.withDefaultNamespace("milk"), ForgeRegistries.Keys.FLUID_TYPES.location(), "minecraft");
public static final RegistryObject<Fluid> MILK = RegistryObject.create(ResourceLocation.withDefaultNamespace("milk"), ForgeRegistries.FLUIDS);
public static final RegistryObject<Fluid> FLOWING_MILK = RegistryObject.create(ResourceLocation.withDefaultNamespace("flowing_milk"), ForgeRegistries.FLUIDS);
public static final RegistryObject<SoundEvent> BUCKET_EMPTY_MILK = RegistryObject.create(Identifier.withDefaultNamespace("item.bucket.empty_milk"), ForgeRegistries.SOUND_EVENTS);
public static final RegistryObject<SoundEvent> BUCKET_FILL_MILK = RegistryObject.create(Identifier.withDefaultNamespace("item.bucket.fill_milk"), ForgeRegistries.SOUND_EVENTS);
public static final RegistryObject<FluidType> MILK_TYPE = RegistryObject.createOptional(Identifier.withDefaultNamespace("milk"), ForgeRegistries.Keys.FLUID_TYPES.identifier(), "minecraft");
public static final RegistryObject<Fluid> MILK = RegistryObject.create(Identifier.withDefaultNamespace("milk"), ForgeRegistries.FLUIDS);
public static final RegistryObject<Fluid> FLOWING_MILK = RegistryObject.create(Identifier.withDefaultNamespace("flowing_milk"), ForgeRegistries.FLUIDS);
private static ForgeMod INSTANCE;
public static ForgeMod getInstance() {
@@ -419,8 +419,8 @@ public class ForgeMod {
ForgeRegistries.ITEMS.tags().addOptionalTagDefaults(Tags.Items.ENCHANTING_FUELS, Set.of(ForgeRegistries.ITEMS.getDelegateOrThrow(Items.LAPIS_LAZULI)));
// TODO: Remove when addAlias becomes proper API, as this should be done in the DR's above.
addAlias(ForgeRegistries.ATTRIBUTES, ResourceLocation.fromNamespaceAndPath("forge", "reach_distance"), ResourceLocation.fromNamespaceAndPath("forge", "block_reach"));
addAlias(ForgeRegistries.ATTRIBUTES, ResourceLocation.fromNamespaceAndPath("forge", "attack_range"), ResourceLocation.fromNamespaceAndPath("forge", "entity_reach"));
addAlias(ForgeRegistries.ATTRIBUTES, Identifier.fromNamespaceAndPath("forge", "reach_distance"), Identifier.fromNamespaceAndPath("forge", "block_reach"));
addAlias(ForgeRegistries.ATTRIBUTES, Identifier.fromNamespaceAndPath("forge", "attack_range"), Identifier.fromNamespaceAndPath("forge", "entity_reach"));
}
private static void preInit(FMLCommonSetupEvent evt) {
@@ -480,16 +480,16 @@ public class ForgeMod {
@Override
public void initializeClient(Consumer<IClientFluidTypeExtensions> consumer) {
consumer.accept(new IClientFluidTypeExtensions() {
private static final ResourceLocation MILK_STILL = ResourceLocation.fromNamespaceAndPath("forge", "block/milk_still");
private static final ResourceLocation MILK_FLOW = ResourceLocation.fromNamespaceAndPath("forge", "block/milk_flowing");
private static final Identifier MILK_STILL = Identifier.fromNamespaceAndPath("forge", "block/milk_still");
private static final Identifier MILK_FLOW = Identifier.fromNamespaceAndPath("forge", "block/milk_flowing");
@Override
public ResourceLocation getStillTexture() {
public Identifier getStillTexture() {
return MILK_STILL;
}
@Override
public ResourceLocation getFlowingTexture() {
public Identifier getFlowingTexture() {
return MILK_FLOW;
}
});
@@ -515,18 +515,18 @@ public class ForgeMod {
Arrays.stream(ItemDisplayContext.values())
.filter(Predicate.not(ItemDisplayContext::isModded))
.forEach(ctx -> forgeRegistry.register(ctx.getId(), ResourceLocation.fromNamespaceAndPath("minecraft", ctx.getSerializedName()), ctx));
.forEach(ctx -> forgeRegistry.register(ctx.getId(), Identifier.fromNamespaceAndPath("minecraft", ctx.getSerializedName()), ctx));
}
}
public static final PermissionNode<Boolean> USE_SELECTORS_PERMISSION = new PermissionNode<>("forge", "use_entity_selectors",
PermissionTypes.BOOLEAN, (player, uuid, contexts) -> player != null && player.hasPermissions(Commands.LEVEL_GAMEMASTERS));
PermissionTypes.BOOLEAN, (player, uuid, contexts) -> player != null && Commands.LEVEL_GAMEMASTERS.check(player.permissions()));
/**
* TODO: Remove when {@link ForgeRegistry#addAlias(ResourceLocation, ResourceLocation)} is elevated to {@link IForgeRegistry}.
* TODO: Remove when {@link ForgeRegistry#addAlias(Identifier, Identifier)} is elevated to {@link IForgeRegistry}.
*/
//@Deprecated(forRemoval = true, since = "1.20")
private static <T> void addAlias(IForgeRegistry<T> registry, ResourceLocation from, ResourceLocation to) {
private static <T> void addAlias(IForgeRegistry<T> registry, Identifier from, Identifier to) {
ForgeRegistry<T> fReg = (ForgeRegistry<T>) registry;
fReg.addAlias(from, to);
}
@@ -8,7 +8,7 @@ package net.minecraftforge.common;
import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceKey;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.resources.Identifier;
import net.minecraft.tags.TagKey;
import java.util.List;
@@ -365,22 +365,22 @@ public final class TagConventionMappings {
* Example: {@code legacyToCommon(Registries.BLOCK, forgeRl("cobblestone"), Tags.Blocks.COBBLESTONES)} for {@code forge:cobblestone} -> {@code c:cobblestones}
* </p>
* @param registryKey Example: {@link net.minecraft.core.registries.Registries.BLOCK}
* @param legacyTagResourceLocation Example: {@code forgeRl("cobblestone")}
* @param legacyTagIdentifier Example: {@code forgeRl("cobblestone")}
* @param replacementTag Example: {@link Tags.Blocks#COBBLESTONES}
* @return A map entry with the legacy tag's TagKey and the suggested replacement tag ID.
*/
private static <T, R> Map.Entry<TagKey<T>, String> legacyToCommon(ResourceKey<Registry<T>> registryKey,
ResourceLocation legacyTagResourceLocation,
Identifier legacyTagIdentifier,
TagKey<R> replacementTag) {
return Map.entry(TagKey.create(registryKey, legacyTagResourceLocation), replacementTag.toString());
return Map.entry(TagKey.create(registryKey, legacyTagIdentifier), replacementTag.toString());
}
/**
* Same as {@link #legacyToCommon(ResourceKey, ResourceLocation, TagKey)} but for multiple replacement tags.
* Same as {@link #legacyToCommon(ResourceKey, Identifier, TagKey)} but for multiple replacement tags.
* This is useful when a single legacy tag is intended to be replaced by combining multiple common convention tags.
*/
private static <T> Map.Entry<TagKey<T>, String> legacyToCommon(ResourceKey<Registry<T>> registryKey,
ResourceLocation legacyTagRessourceLocation,
Identifier legacyTagRessourceLocation,
List<TagKey<?>> replacementTags) {
return Map.entry(
TagKey.create(registryKey, legacyTagRessourceLocation),
@@ -388,7 +388,7 @@ public final class TagConventionMappings {
);
}
private static ResourceLocation forgeRl(String path) {
return ResourceLocation.fromNamespaceAndPath("forge", path);
private static Identifier forgeRl(String path) {
return Identifier.fromNamespaceAndPath("forge", path);
}
}
Loaded 100 of 698 files, more files were not shown because too many files have changed in this diff. Show more