Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support resource pack filters, overlays and features from pack.mcmeta files in mods. #3312

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion fabric-resource-loader-v0/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,6 @@ loom {
testDependencies(project, [
':fabric-lifecycle-events-v1',
':fabric-api-base',
':fabric-resource-loader-v0'
':fabric-resource-loader-v0',
':fabric-networking-api-v1'
])
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,41 @@
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import com.google.common.base.Charsets;
import com.mojang.serialization.Codec;
import com.mojang.serialization.JsonOps;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import org.apache.commons.io.IOUtils;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.minecraft.SharedConstants;
import net.minecraft.resource.AbstractFileResourcePack;
import net.minecraft.resource.InputSupplier;
import net.minecraft.resource.ResourcePack;
import net.minecraft.resource.ResourceType;
import net.minecraft.resource.metadata.BlockEntry;
import net.minecraft.resource.metadata.PackResourceMetadata;
import net.minecraft.resource.metadata.ResourceFilter;
import net.minecraft.resource.metadata.ResourceMetadataReader;
import net.minecraft.text.Text;
import net.minecraft.util.Util;

import net.fabricmc.fabric.api.resource.ModResourcePack;
import net.fabricmc.fabric.mixin.resource.loader.ResourceFilterAccessor;
import net.fabricmc.loader.api.FabricLoader;

/**
* The Fabric mods resource pack, holds all the mod resource packs as one pack.
*/
public class FabricModResourcePack extends GroupResourcePack {
private static final Logger LOGGER = LoggerFactory.getLogger(FabricModResourcePack.class);

public FabricModResourcePack(ResourceType type, List<ModResourcePack> packs) {
super(type, packs);
}
Expand All @@ -47,10 +63,7 @@ public InputSupplier<InputStream> openRoot(String... pathSegments) {
String fileName = String.join("/", pathSegments);

if ("pack.mcmeta".equals(fileName)) {
String description = "pack.description.modResources";
String fallback = "Mod resources.";
String pack = String.format("{\"pack\":{\"pack_format\":" + SharedConstants.getGameVersion().getResourceVersion(type) + ",\"description\":{\"translate\":\"%s\",\"fallback\":\"%s.\"}}}", description, fallback);
return () -> IOUtils.toInputStream(pack, Charsets.UTF_8);
return () -> IOUtils.toInputStream(generateMetadataJson(), Charsets.UTF_8);
} else if ("pack.png".equals(fileName)) {
return FabricLoader.getInstance().getModContainer("fabric-resource-loader-v0")
.flatMap(container -> container.getMetadata().getIconPath(512).flatMap(container::findPath))
Expand All @@ -61,6 +74,48 @@ public InputSupplier<InputStream> openRoot(String... pathSegments) {
return null;
}

private String generateMetadataJson() {
record PackMetadata(PackResourceMetadata pack, Optional<ResourceFilter> filter) {
static final Codec<PackMetadata> CODEC = RecordCodecBuilder.create(instance ->
instance.group(
PackResourceMetadata.CODEC.fieldOf("pack").forGetter(PackMetadata::pack),
ResourceFilterAccessor.getCodec().optionalFieldOf("filter").forGetter(PackMetadata::filter)
).apply(instance, PackMetadata::new));
}

final var resourceMetadata = new PackResourceMetadata(
Text.translatableWithFallback("pack.description.modResources", "Mod resources."),
SharedConstants.getGameVersion().getResourceVersion(type),
Optional.empty()
);
modmuss50 marked this conversation as resolved.
Show resolved Hide resolved

final List<BlockEntry> blockEntries = collectBlockEntries();
final Optional<ResourceFilter> filter = blockEntries.isEmpty() ? Optional.empty() : Optional.of(new ResourceFilter(blockEntries));
final var metadata = new PackMetadata(resourceMetadata, filter);
return Util.getResult(PackMetadata.CODEC.encodeStart(JsonOps.INSTANCE, metadata), IllegalArgumentException::new).toString();
}

// Reads all the resource filters from the sub packs
private List<BlockEntry> collectBlockEntries() {
var filterBlocks = new ArrayList<BlockEntry>();

for (ResourcePack pack : packs) {
try {
ResourceFilter resourceFilter = pack.parseMetadata(ResourceFilter.SERIALIZER);

if (resourceFilter == null) {
continue;
}

filterBlocks.addAll(((ResourceFilterAccessor) resourceFilter).getBlocks());
} catch (IOException e) {
LOGGER.error("Failed to get filter section from pack {}", pack.getName());
}
}

return filterBlocks;
}

@Override
public <T> @Nullable T parseMetadata(ResourceMetadataReader<T> metaReader) throws IOException {
InputSupplier<InputStream> inputSupplier = this.openRoot("pack.mcmeta");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.fabricmc.fabric.mixin.resource.loader;

import java.util.List;

import com.mojang.serialization.Codec;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;

import net.minecraft.resource.metadata.BlockEntry;
import net.minecraft.resource.metadata.ResourceFilter;

@Mixin(ResourceFilter.class)
public interface ResourceFilterAccessor {
@Accessor
List<BlockEntry> getBlocks();

@Accessor("CODEC")
static Codec<ResourceFilter> getCodec() {
throw new IllegalStateException();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
"MinecraftServerMixin",
"NamespaceResourceManagerMixin",
"ReloadableResourceManagerImplMixin",
"ResourceFilterAccessor",
"ResourceMixin",
"ResourcePackManagerMixin",
"ResourcePackProfileMixin",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
* Copyright (c) 2016, 2017, 2018, 2019 FabricMC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package net.fabricmc.fabric.test.resource.loader;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

import org.intellij.lang.annotations.Language;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import net.minecraft.SharedConstants;
import net.minecraft.resource.ResourceType;
import net.minecraft.resource.metadata.PackResourceMetadata;
import net.minecraft.resource.metadata.ResourceFilter;

import net.fabricmc.fabric.api.resource.ModResourcePack;
import net.fabricmc.fabric.api.resource.ResourcePackActivationType;
import net.fabricmc.fabric.impl.resource.loader.FabricModResourcePack;
import net.fabricmc.fabric.impl.resource.loader.ModNioResourcePack;
import net.fabricmc.loader.api.ModContainer;
import net.fabricmc.loader.api.metadata.ModMetadata;

public class FabricModResourcePackTest {
@BeforeAll
static void beforeAll() {
SharedConstants.createGameVersion();
}

@Test
void resourcePackMetadata(@TempDir Path rootPath) throws IOException {
writeDummyResources("test1", rootPath);

try (var resourcePack = new FabricModResourcePack(ResourceType.CLIENT_RESOURCES, List.of(
createModResourcePack("test1", rootPath)
))) {
final PackResourceMetadata resourceMetadata = resourcePack.parseMetadata(PackResourceMetadata.SERIALIZER);
assertNotNull(resourceMetadata);
assertEquals(resourceMetadata.description().getString(), "Mod resources.");

final ResourceFilter resourceFilter = resourcePack.parseMetadata(ResourceFilter.SERIALIZER);
assertNull(resourceFilter);
}
}

@Test
void resourcePackFiters(@TempDir Path rootPath) throws IOException {
@Language("json")
String mcmeta = """
{
"pack": {
"pack_format": 18,
"description": "My epic test mod"
},
"filter": {
"block": [
{
"namespace": "minecraft",
"path": "recipes/.*"
}
]
}
}""";

writeDummyResources("test1", rootPath);
Files.writeString(rootPath.resolve("pack.mcmeta"), mcmeta);

try (var resourcePack = new FabricModResourcePack(ResourceType.CLIENT_RESOURCES, List.of(
createModResourcePack("test1", rootPath)
))) {
final ResourceFilter resourceFilter = resourcePack.parseMetadata(ResourceFilter.SERIALIZER);
assertNotNull(resourceFilter);

assertTrue(resourceFilter.isNamespaceBlocked("minecraft"));
assertFalse(resourceFilter.isNamespaceBlocked("fabric"));

assertTrue(resourceFilter.isPathBlocked("recipes/example.json"));
assertFalse(resourceFilter.isPathBlocked("blocks/example.json"));
}
}

private static ModResourcePack createModResourcePack(String modId, Path rootDir) {
final ModMetadata modMetadata = mock(ModMetadata.class);
when(modMetadata.getId()).thenReturn(modId);

final ModContainer modContainer = mock(ModContainer.class);
when(modContainer.getRootPaths()).thenReturn(List.of(rootDir));
when(modContainer.getMetadata()).thenReturn(modMetadata);

ModNioResourcePack modNioResourcePack = ModNioResourcePack.create(modId, modContainer, null, ResourceType.CLIENT_RESOURCES, ResourcePackActivationType.ALWAYS_ENABLED);
assertNotNull(modNioResourcePack);
return modNioResourcePack;
}

// A resource pack will only be loaded when it has either an assets or data directory.
private static void writeDummyResources(String modId, Path rootPath) throws IOException {
Files.createDirectories(rootPath.resolve("assets/%s/".formatted(modId)));
Files.createDirectories(rootPath.resolve("data/%s/".formatted(modId)));
}
}
Loading